diff --git "a/2489.jsonl" "b/2489.jsonl" new file mode 100644--- /dev/null +++ "b/2489.jsonl" @@ -0,0 +1,691 @@ +{"seq_id":"556619530","text":"from graphql import GraphQLError\nfrom django.core.exceptions import ObjectDoesNotExist\n\nfrom healthid.utils.messages.business_responses import BUSINESS_ERROR_RESPONSES\n\n\ndef get_user_business(user):\n \"\"\"\n get the logged user's business\n\n Args:\n user(obj): logged in user\n\n Returns:\n business(obj): user's business\n graphql error: if use has no business\n \"\"\"\n business = None\n try:\n business = user.business_user\n if not business:\n raise GraphQLError(\n BUSINESS_ERROR_RESPONSES[\"no_business_error\"])\n else:\n return business\n except ObjectDoesNotExist:\n return business\n","sub_path":"healthid/utils/app_utils/get_user_business.py","file_name":"get_user_business.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"417416725","text":"\n\ndef get_processor_facts(self):\n processor = []\n dmesg_boot = get_file_content(OpenBSDHardware.DMESG_BOOT)\n if (not dmesg_boot):\n (rc, dmesg_boot, err) = self.module.run_command('/sbin/dmesg')\n i = 0\n for line in dmesg_boot.splitlines():\n if (line.split(' ', 1)[0] == ('cpu%i:' % i)):\n processor.append(line.split(' ', 1)[1])\n i = (i + 1)\n processor_count = i\n self.facts['processor'] = processor\n self.facts['processor_count'] = processor_count\n self.facts['processor_cores'] = 'NA'\n","sub_path":"Data Set/bug-fixing-2/c17dad0def2fa86733c07610189e94486e056203--bug.py","file_name":"c17dad0def2fa86733c07610189e94486e056203--bug.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"506438382","text":"#!/usr/bin/env python3.4\n\nimport re\n\nfile = \"rawGrades.xml\"\n\ndef openGrades(file):\n a = \"\"\n with open(file) as f:\n for line in f:\n a += line\n\n return(a)\n\ndef format(data):\n regex = r\".*(?P.*).*\"\n regex2 = r\".*?<(?P[A-Z0-9]{3}?)>(?P.*?):(?P.*?)[A-Z0-9]{3}?)>.*?\"\n\n a = re.match(regex, data, re.S)\n\n b = a.group(\"info\")\n\n d = re.findall(regex2, b, re.S)\n\n c = []\n\n for item in d:\n w, x, y, z = item\n\n if(w == z):\n c.append(item)\n\n master = []\n new_c = []\n\n for item in c:\n the_list = []\n w, x, y, z = item\n temp = y.split()\n new_c.append([w, x])\n\n for item in range(len(temp)):\n if(item != len(temp) - 1):\n the_string = temp[item][:-1]\n the_list.append(the_string)\n else:\n the_list.append(temp[item])\n\n master.append(the_list)\n\n scores = []\n\n for i in range(len(master)):\n dict = {}\n\n for j in range(len(master[i])):\n # HERERE\n temp = master[i][j]\n temp = temp[1:-1]\n values = temp.split(':')\n\n key = values[0]\n value = int(values[1])\n\n dict[key] = value\n\n scores.append(dict)\n\n f = open('finalGrades.xml', 'w')\n\n f.write('\\n')\n f.write('\\n')\n\n total = []\n for item in scores:\n interim = []\n for key, value in item.items():\n interim.append([key, value])\n \n interim.sort()\n total.append(interim)\n\n for i in range(len(new_c)):\n f.write(' \\n'.format(new_c[i][1], new_c[i][0]))\n\n for score in total[i]:\n mark = score[1]\n\n if(mark >= 90):\n mark = \"A\"\n elif(mark >= 80):\n mark = \"B\"\n elif(mark >= 70):\n mark = \"C\"\n elif(mark >= 60):\n mark = \"D\"\n else:\n mark = \"F\"\n\n f.write(' \\n'.format(score[0], score[1], mark))\n\n f.write(' \\n')\n\n f.write('')\n\nif __name__ == \"__main__\":\n data = openGrades(file)\n format(data)\n","sub_path":"Lab09/generateReport.py","file_name":"generateReport.py","file_ext":"py","file_size_in_byte":2017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"565136680","text":"import os\nimport subprocess\nimport datetime\nimport xml.dom.minidom\nimport numpy as np\nimport h5py\nimport tempfile\nimport shutil\nfrom os.path import dirname, abspath, join\nfrom xml.etree import ElementTree as ET\nfrom matplotlib import pyplot as plt\n\n\ndef pretty_xml_string(element):\n # sometimes jLEMS freaks out on unprettified xml. This is meant to\n # work around that.\n ugly_xml = xml.dom.minidom.parseString(ET.tostring(element))\n return ugly_xml.toprettyxml()\n\nclass StimulusLEMSAdapter(object):\n def __init__(self, exc_rates):\n self.lems = ET.Element(\"Lems\")\n for k, rate in enumerate(exc_rates):\n exc_spikegen = ET.SubElement(self.lems, \"spikeGeneratorRefPoisson\")\n exc_spikegen.set(\"id\", \"mossySpiker{}\".format(k))\n exc_spikegen.set(\"averageRate\", \"{} Hz\".format(rate))\n exc_spikegen.set(\"minimumISI\", \"1 ms\")\n\nclass SimulationConfigurationLEMSAdapter(object):\n def __init__(self,\n length,\n n_stims,\n out_filename,\n step=0.05,\n target=\"poissonStimNetwork\",\n save_synaptic_conductances=False):\n self.lems = ET.Element(\"Lems\")\n simulation = ET.SubElement(self.lems, \"Simulation\")\n simulation.set(\"id\", \"generatedSimulation\")\n simulation.set(\"length\", \"{} s\".format(length))\n simulation.set(\"step\", \"{} ms\".format(step))\n simulation.set(\"target\", target)\n output_file = ET.SubElement(simulation, \"OutputFile\")\n output_file.set(\"id\", \"of0\")\n output_file.set(\"fileName\", out_filename)\n voltage_column = ET.SubElement(output_file, \"OutputColumn\")\n voltage_column.set(\"id\", \"v\")\n voltage_column.set(\"quantity\", \"GrCPop[0]/v\")\n spike_column = ET.SubElement(output_file, \"OutputColumn\")\n spike_column.set(\"id\", \"sc\")\n spike_column.set(\"quantity\", \"SpikeRecorderPop[0]/spikeRecorder/spikeCount\")\n if save_synaptic_conductances:\n for stim in range(n_stims):\n for conn_type in ['AMPA', 'NMDA']:\n syn_column = ET.SubElement(output_file, \"OutputColumn\")\n syn_column.set(\"id\", \"{}{}\".format(conn_type, stim))\n syn_column.set(\"quantity\", \"GrCPop[0]/RothmanMFToGrC{}{}/g\".format(conn_type, stim))\n\nclass NetworkLEMSAdapter(object):\n def __init__(self, n_stims):\n self.lems = ET.Element(\"Lems\")\n network = ET.SubElement(self.lems, \"network\")\n network.set(\"id\", \"poissonStimNetwork\")\n grc_pop = ET.SubElement(network, \"population\")\n grc_pop.set(\"id\", \"GrCPop\")\n grc_pop.set(\"component\", \"IaF_GrC_no_tonic_GABA\")\n grc_pop.set(\"size\", \"1\")\n sr_pop = ET.SubElement(network, \"population\")\n sr_pop.set(\"id\", \"SpikeRecorderPop\")\n sr_pop.set(\"component\", \"IaF_GrC_no_tonic_GABA\")\n sr_pop.set(\"size\", \"1\")\n for mf in range(n_stims):\n mf_pop = ET.SubElement(network, \"population\")\n mf_pop.set(\"id\", \"mossySpikerPop{}\".format(mf))\n mf_pop.set(\"component\", \"mossySpiker{}\".format(mf))\n mf_pop.set(\"size\", \"1\")\n for conn_type in ['AMPA', 'NMDA']:\n conn = ET.SubElement(network, \"synapticConnection\")\n conn.set(\"from\", \"mossySpikerPop{}[0]\".format(mf))\n conn.set(\"to\", \"GrCPop[0]\")\n conn.set(\"synapse\", \"RothmanMFToGrC{}{}\".format(conn_type, mf))\n conn.set(\"destination\", \"synapses\")\n sr_conn = ET.SubElement(network, \"synapticConnection\")\n sr_conn.set(\"from\", \"GrCPop[0]\")\n sr_conn.set(\"to\", \"SpikeRecorderPop[0]\")\n sr_conn.set(\"synapse\", \"spikeRecorder\")\n sr_conn.set(\"destination\", \"synapses\")\n\nclass CustomLEMSInclude(object):\n def __init__(self, filename):\n self.lems = ET.Element(\"Lems\")\n include_element = ET.SubElement(self.lems, \"Include\")\n include_element.set(\"file\", filename)\n \ndef set_tonic_GABA(project_dir, conductance_in_nS, reversal_potential=-79.1):\n \"\"\"\n Modify the IaF_GrC_no_tonic_GABA.nml file in the working copy of\n the nC project to change the level of tonic GABA from what is\n originally set in the model.\n\n \"\"\"\n ET.register_namespace('', 'http://www.neuroml.org/schema/neuroml2')\n filename = project_dir + \"/cellMechanisms/IaF_GrC_no_tonic_GABA/IaF_GrC_no_tonic_GABA.nml\"\n tree = ET.parse(filename)\n root = tree.getroot()\n cell = root.find(\"{http://www.neuroml.org/schema/neuroml2}iafRefCell\")\n old_conductance = float(cell.get('leakConductance').rstrip('nS'))\n old_reversal_potential = float(cell.get('leakReversal').rstrip('mV'))\n new_conductance = old_conductance + conductance_in_nS\n new_reversal_potential = (old_conductance * old_reversal_potential + conductance_in_nS * reversal_potential)/new_conductance\n cell.set('leakConductance', '{}nS'.format(new_conductance))\n cell.set('leakReversal', '{}mV'.format(new_reversal_potential))\n tree.write(filename, encoding=\"UTF-8\", xml_declaration=True)\n\ndef scale_synaptic_conductance(project_dir, component_name, scaling_factor, attributes_to_scale, units='nS'):\n ET.register_namespace('', 'http://www.neuroml.org/schema/neuroml2')\n filename = project_dir + \"/cellMechanisms/{0}/{0}.nml\".format(component_name)\n tree = ET.parse(filename)\n root = tree.getroot()\n synapse = root.findall(\".//*[@id='{}']\".format(component_name))[0]\n for attribute in attributes_to_scale:\n old_conductance = float(synapse.get(attribute).rstrip(units))\n new_conductance = old_conductance * scaling_factor\n synapse.set(attribute, '{}{}'.format(new_conductance, units))\n tree.write(filename, encoding=\"UTF-8\", xml_declaration=True)\n\n\ndef scale_excitatory_conductances(project_dir, scaling_factor):\n \"\"\"\n Modify the RothmanMFToGrCAMPA.nml and RothmanMFToGrCNMDA.nml files\n in the working copy of of the nC project to scale the total amount\n of excitatory conductance.\n\n \"\"\"\n # scale AMPA\n scale_synaptic_conductance(project_dir=project_dir,\n component_name='RothmanMFToGrCAMPA',\n scaling_factor=scaling_factor,\n attributes_to_scale=['directAmp1',\n 'directAmp2',\n 'spilloverAmp1',\n 'spilloverAmp2',\n 'spilloverAmp3'])\n # scale NMDA\n scale_synaptic_conductance(project_dir=project_dir,\n component_name='RothmanMFToGrCNMDA',\n scaling_factor=scaling_factor,\n attributes_to_scale=['directAmp1',\n 'directAmp2'])\n\n\ndef simulate_poisson_stimulation(exc_rates, sim_duration_in_s, save_synaptic_conductances=False, inh_scaling_factor=1., exc_scaling_factor=1.):\n n_stims = len(exc_rates)\n # create file where simulation data will be stored\n sim_data_file = tempfile.NamedTemporaryFile(delete=False, dir='./')\n sim_data_file.close()\n\n project_dir = dirname(dirname(abspath(__file__)))\n cell_mechs_dir = join(project_dir, 'cellMechanisms')\n\n # make temporary copy of mech files\n temp_project_dir = tempfile.mkdtemp()\n temp_cell_mechs_dir = join(temp_project_dir, 'cellMechanisms')\n shutil.copytree(cell_mechs_dir, temp_cell_mechs_dir)\n\n # scale conductances\n gGABA_base_in_nS = 0.438\n total_GABA_conductance_in_nS = gGABA_base_in_nS*inh_scaling_factor\n set_tonic_GABA(temp_project_dir, total_GABA_conductance_in_nS)\n scale_excitatory_conductances(temp_project_dir, exc_scaling_factor)\n\n # load base template for xml simulation description\n ET.register_namespace('', 'http://www.neuroml.org/schema/neuroml2')\n template_filename = join(join(project_dir, \"lemsSimulations\"), \"poisson_inputs_simulation_template.xml\")\n lems_tree = ET.parse(template_filename)\n lems_root = lems_tree.getroot()\n\n # define includes for custom component types and components\n custom_lems_defs_dir = join(project_dir, \"lemsDefinitions\")\n include_filenames = [join(custom_lems_defs_dir, 'spikeRecorder.xml'),\n join(custom_lems_defs_dir, 'spikeGeneratorRefPoisson.xml')]\n for component_name in ['RothmanMFToGrCAMPA', 'RothmanMFToGrCNMDA', 'IaF_GrC_no_tonic_GABA']:\n include_filenames.append(join(join(temp_cell_mechs_dir, component_name), component_name+'.nml'))\n lems_includes = [CustomLEMSInclude(filename).lems for filename in include_filenames]\n\n\n\n\n # define replicas of synaptic components\n synaptic_replicas = []\n for stim in range(n_stims):\n for syn_name in ['RothmanMFToGrCAMPA', 'RothmanMFToGrCNMDA']:\n tree = ET.parse(join(join(temp_cell_mechs_dir, syn_name), syn_name+'.nml'))\n root = tree.getroot()\n element = root.findall(\"./*[@id='{}']\".format(syn_name))[0]\n element.set(\"id\", \"{}{}\".format(syn_name, stim))\n synaptic_replicas.append(element)\n\n # define procedurally generated lems elements\n lems_stim = StimulusLEMSAdapter(exc_rates).lems\n lems_net = NetworkLEMSAdapter(n_stims).lems\n lems_sim = SimulationConfigurationLEMSAdapter(length=sim_duration_in_s,\n n_stims=n_stims,\n out_filename=sim_data_file.name,\n save_synaptic_conductances=save_synaptic_conductances).lems\n \n # insert custom includes in simulation description template\n position_includes = 5\n position_syn_replicas = 6\n position_stim = 7\n position_net = 8\n position_sim = 9\n for k, inc in enumerate(lems_includes):\n lems_root.insert(position_includes, inc[0])\n position_syn_replicas += 1\n position_stim += 1\n position_net += 1\n position_sim += 1\n # insert synaptic replicas\n for replica in synaptic_replicas:\n lems_root.insert(position_syn_replicas, replica)\n position_stim += 1\n position_net += 1\n position_sim += 1\n # insert procedurally generated lems\n for stim in range(n_stims):\n lems_root.insert(position_stim, lems_stim[stim])\n position_net += 1\n position_sim += 1\n lems_root.insert(position_net, lems_net[0])\n lems_root.insert(position_sim, lems_sim[0])\n # write simulation description to disk\n sim_description_file = tempfile.NamedTemporaryFile(delete=False, dir='./')\n sim_description_file.write(pretty_xml_string(lems_root))\n sim_description_file.close()\n # run jLEMS\n proc = subprocess.Popen([\"jnml {}\".format(sim_description_file.name)],\n shell=True,\n stdout=subprocess.PIPE)\n proc.communicate()\n # remove simulation description file\n os.remove(sim_description_file.name)\n # remove temp mech dir\n shutil.rmtree(temp_project_dir)\n # read in output firing rate and remove simulation data file\n out_data = np.loadtxt(sim_data_file.name)\n os.remove(sim_data_file.name)\n return out_data\n","sub_path":"neuroConstruct/lemsSimulations/simulation_tools.py","file_name":"simulation_tools.py","file_ext":"py","file_size_in_byte":11326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"56202135","text":"from setuptools import setup, find_packages\n\nmain_module = 'sidetopics'\nproject_name = 'sidetopics'\n__author__ = 'Bryan Feeney'\n__author_email__ = 'bryan.feeney@gmail.com'\n\n\nVERSION = '0.1.0'\n\nsetup(\n name=project_name,\n author=__author__,\n author_email=__author_email__,\n python_requires='>=3.6',\n version=VERSION,\n packages=find_packages(),\n # namespace_packages=namespace_packages,\n entry_points={\n 'console_scripts': [\n f'{project_name} = {main_module}.__main__:main',\n ]\n },\n package_data={\n f'{main_module}': ['versionfile']\n }\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"609823986","text":"from enum import Enum\nimport src.utils.vt100_codes as vt100\nimport src.utils.string_utils as string_utils\n\nclass Connection(object):\n def __init__(self, reader, writer, notify_queue):\n self._reader = reader\n self._writer = writer\n self.notify_queue = notify_queue\n # self._player = None\n self._handler_stack = []\n self._id = self._writer.get_extra_info('peername')[1]\n self.player = None\n\n def __str__(self):\n return '#{1}'.format(self.get_id())\n\n def get_id(self):\n return self._id\n\n def handler(self):\n if not len(self._handler_stack):\n return None\n\n return self._handler_stack[len(self._handler_stack)-1]\n\n def enter_handler(self, new_state):\n self._handler_stack.append(new_state)\n new_state.enter()\n\n def leave_handler(self):\n current_handler = self._handler_stack.pop()\n current_handler.leave()\n self.handler().enter()\n\n def switch_handler(self, new_state):\n self._handler_stack.pop()\n self.enter_handler(new_state)\n\n def hang_up(self):\n current_handler = self.handler()\n self._handler_stack = []\n current_handler.hang_up()\n self.close()\n\n def send(self, msg, indent=False, wrap=False):\n new_msg = self.__translate_colors(msg)\n if wrap:\n new_msg = string_utils.wrap(new_msg, indent=indent)\n\n self._writer.write(new_msg)\n\n def send_line(self, msg, indent=False, wrap=False):\n self.send(msg, indent=indent, wrap=wrap)\n self.send_blank_line()\n\n def send_blank_line(self):\n self._writer.write(vt100.newline)\n\n def echo(self, msg):\n self._writer.echo(self.__translate_colors(msg))\n\n def readline(self):\n return self._reader.readline()\n\n def set_iac(self, cmd, opt):\n return self._writer.iac(cmd, opt)\n\n def set_echo(self, echo):\n from telnetlib3 import WONT, WILL, ECHO\n if echo:\n self.set_iac(WONT, ECHO)\n else:\n self.set_iac(WILL, ECHO)\n\n def close(self):\n self._writer.close()\n\n def __translate_colors(self, msg):\n index = msg.find('<')\n new_msg = msg\n\n while index >= 0:\n end_index = new_msg.find('>')\n if end_index >= 0:\n type_indicator = new_msg[index + 1]\n if type_indicator == '$':\n new_msg = self.__translate_string_color(index, end_index, new_msg)\n elif type_indicator == '#':\n new_msg = self.__translate_number_color(index, end_index, new_msg)\n index = new_msg.find('<', index + 1)\n\n return new_msg\n\n def __translate_string_color(self, start_index, end_index, msg):\n color_tag = msg[start_index:end_index+1]\n vt100_color = None\n\n if color_tag == '<$black>':\n vt100_color = vt100.black\n elif color_tag == '<$red>':\n vt100_color = vt100.red\n elif color_tag == '<$green>':\n vt100_color = vt100.green\n elif color_tag == '<$yellow>':\n vt100_color = vt100.yellow\n elif color_tag == '<$blue>':\n vt100_color = vt100.blue\n elif color_tag == '<$magenta>':\n vt100_color = vt100.magenta\n elif color_tag == '<$cyan>':\n vt100_color = vt100.cyan\n elif color_tag == '<$white>':\n vt100_color = vt100.white\n elif color_tag == '<$bold>':\n vt100_color = vt100.bold\n elif color_tag == '<$dim>':\n vt100_color = vt100.dim\n elif color_tag == '<$reset>':\n vt100_color = vt100.reset\n elif color_tag == '<$nl>':\n vt100_color = vt100.newline\n\n if vt100_color:\n return msg.replace(color_tag, vt100_color)\n\n return msg\n\n def __translate_number_color(self, start_index, end_index, msg):\n return msg #TODO\n","sub_path":"src/connection.py","file_name":"connection.py","file_ext":"py","file_size_in_byte":3512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"258470821","text":"import numpy as np\n\nfrom keras.preprocessing import sequence\n\nfrom utils import get_module_logger\n\nlogger = get_module_logger(__name__)\n\n\nclass TextPrepper(object):\n pass\n\n\nclass LSTMPrepper(TextPrepper):\n def __init__(self, docs, vocab, embeddings, maxlen=300):\n self.docs = docs\n self.vocab = vocab\n self.embeddings = embeddings\n self.maxlen = maxlen\n self.fixZero()\n\n def fixZero(self):\n '''Add zeros in the first row and shift the entire matrix'''\n vocab = {}\n if not all(self.embeddings[0, :] == 0):\n try:\n assert all(self.embeddings[0, :] == 0)\n for k, v in self.vocab.iteritems():\n vocab[k] = self.vocab[k].index\n except AssertionError:\n logger.warning(\"First word was not empty,\\\nshifting the matrix\")\n mat = np.zeros([self.embeddings.shape[0] + 1,\n self.embeddings.shape[1]])\n mat[1:, :] = self.embeddings\n for k, v in self.vocab.iteritems():\n vocab[k] = self.vocab[k].index + 1\n self.embeddings = mat\n self.vocab = vocab\n self.prepCorpus()\n\n def prepCorpus(self):\n self.docs = [[self.vocab[w] if w in self.vocab else 0\n for w in line]\n for line in self.docs]\n self.vocab_size = self.embeddings.shape[0]\n\n self.docs = sequence.pad_sequences(self.docs, self.maxlen)\n self.docs = np.array(self.docs)\n","sub_path":"utils/textPrep.py","file_name":"textPrep.py","file_ext":"py","file_size_in_byte":1562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"569012286","text":"s = '君不見黃河之水天上來,奔流到海不復迴。\\\n君不見高堂明鏡悲白髮,朝如青絲暮成雪。\\\n人生得意須盡歡,莫使金樽空對月。\\\n天生我材必有用,千金散盡還復來。\\\n烹羊宰牛且為樂,會須一飲三百杯。\\\n岑夫子,丹丘生。將進酒,君莫停。\\\n與君歌一曲,請君為我側耳聽。\\\n鐘鼓饌玉不足貴,但願長醉不願醒。\\\n古來聖賢皆寂寞,惟有飲者留其名。\\\n陳王昔時宴平樂,斗酒十千恣讙謔。\\\n主人何為言少錢,徑須沽取對君酌。五花馬,千金裘。\\\n呼兒將出換美酒,與爾同銷萬古愁。' #將進酒 李白\ndic = {w:s.count(w) for w in set(s) if w != ',' and w != '。' and s.count(w) > 2}\nprint(dic)\ndic2 = {k:v for k,v in dic.items() if v ==3}\nprint(dic2)","sub_path":"ch05/5-7-2-字與字的出現次數的字典.py","file_name":"5-7-2-字與字的出現次數的字典.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"117142198","text":"from itertools import permutations, product\n# open file to write the expressions in\nfile = open(\"output.txt\", \"w\")\n\n# define function to evaluate expressions in reverse polish notation\ndef reverse_polish(exp):\n stack = []\n for val in exp.split(' '):\n if val in ['-', '+', '*', '/']:\n op1 = stack.pop()\n op2 = stack.pop()\n if val == '-':\n result = op2 - op1\n if val == '+':\n result = op2 + op1\n if val == '*':\n result = op2 * op1\n if val == '/':\n try:\n result = op2 / op1\n except:\n return 0\n stack.append(result)\n else:\n stack.append(float(val))\n\n return stack.pop()\n\nnums4 = []\nnums3 = []\nnums2 = []\nnums1 = []\nexpression = []\n\n# get all permutations of numbers 1, 4, 8, 9\nperm4 = permutations(['1', '4', '8', '9'], 4)\nfor p in perm4: nums4.append(p)\nperm3 = permutations(['1', '4', '8', '9'], 3)\nfor p in perm3: nums3.append(p)\nperm2 = permutations(['1', '4', '8', '9'], 2)\nfor p in perm2: nums2.append(p)\nperm1 = permutations(['1', '4', '8', '9'], 1)\nfor p in perm1: nums1.append(p)\n\n# Cartesian product to get all operation possibilities\nfor item in nums4:\n OpsPerm4 = product(['+','-','/','*'], repeat=3)\n for p in OpsPerm4:\n expression.append(item+p)\nfor item in nums3:\n OpsPerm3 = product(['+','-','/','*'], repeat=2)\n for p in OpsPerm3:\n expression.append(item+p)\nfor item in nums2:\n OpsPerm2 = product(['+','-','/','*'], repeat=1)\n for p in OpsPerm2:\n expression.append(item+p)\nfor item in nums1:\n OpsPerm1 = product(['+','-','/','*'], repeat=0)\n for p in OpsPerm1:\n expression.append(item+p)\n\n# iterating over our reverse polish notation evaluator and printing results\nfor i in expression:\n exp = \" \".join(i)\n polish_result = reverse_polish(exp)\n if (1 <= polish_result <= 100) and (polish_result.is_integer()):\n print(i, '=', polish_result, file=file)\n\nfile.close()\n","sub_path":"ReversePolishNotation.py","file_name":"ReversePolishNotation.py","file_ext":"py","file_size_in_byte":2068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"177545439","text":"import pandas as pd\nimport numpy as np\nimport keras\nimport tensorflow as tf\nfrom keras.preprocessing.sequence import TimeseriesGenerator\nfrom keras.models import Sequential\nfrom keras.layers import LSTM, Dense\nimport matplotlib.pyplot as plt\nsplit_ratio = 0.8\ndf = pd.read_csv('AAPL.csv')\ndf['Date'] = pd.to_datetime(df['Date'])\ndf.set_axis(df['Date'], inplace=True)\n\nclose_data = df['Close'].values\nclose_data = close_data.reshape((-1,1))\n\nsplit = int(split_ratio*len(close_data))\n\nclose_train = close_data[:split]\nclose_test = close_data[split:]\n\ndate_train = df['Date'][:split]\ndate_test = df['Date'][split:]\n\nprint(len(close_train))\nprint(len(close_test))\n\nlook_back = 10\n\ntrain_generator = TimeseriesGenerator(close_train, close_train, length=look_back, batch_size=20)\ntest_generator = TimeseriesGenerator(close_test, close_test, length=look_back, batch_size=1)\n\nmodel = Sequential()\nmodel.add(\n LSTM(10,\n activation='relu',\n input_shape=(look_back,1))\n)\nmodel.add(Dense(1))\nmodel.compile(optimizer='adam', loss='mse')\n\nnum_epochs = 25\nmodel.fit_generator(train_generator, epochs=num_epochs, verbose=1)\n\nprediction = model.predict_generator(test_generator)\n\nclose_train = close_train.reshape((-1))\nclose_test = close_test.reshape((-1))\nprediction = prediction.reshape((-1))\n\nplt.plot(date_train,close_train,color = 'blue',label = 'тренировочные данные')\nplt.plot(date_test,close_test,color ='g',label ='тестовые')\nplt.plot(date_test[0:(252-look_back)],prediction,color = 'r',label = 'предсказание')\nplt.title('Предсказание стоимости акций Apple за {} недель'.format(look_back))\nplt.legend()\nplt.show()\n","sub_path":"stok.py","file_name":"stok.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"583259299","text":"# Copyright (c) 2014 Hewlett-Packard Development Company, L.P.\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\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport storyboard.db.api.base as db_api_base\nimport storyboard.plugin.event_worker as plugin_base\nimport storyboard.tests.base as base\n\n\nclass TestWorkerTaskBase(base.FunctionalTest):\n def setUp(self):\n super(TestWorkerTaskBase, self).setUp()\n\n def test_resolve_by_name(self):\n '''Assert that resolve_resource_by_name works.'''\n\n worker = TestWorkerPlugin({})\n\n with base.HybridSessionManager():\n session = db_api_base.get_session()\n\n task = worker.resolve_resource_by_name(session, 'task', 1)\n self.assertIsNotNone(task)\n self.assertEqual(1, task.id)\n\n project_group = worker.resolve_resource_by_name(session,\n 'project_group', 1)\n self.assertIsNotNone(project_group)\n self.assertEqual(1, project_group.id)\n\n project = worker.resolve_resource_by_name(session, 'project', 1)\n self.assertIsNotNone(project)\n self.assertEqual(1, project.id)\n\n user = worker.resolve_resource_by_name(session, 'user', 1)\n self.assertIsNotNone(user)\n self.assertEqual(1, user.id)\n\n team = worker.resolve_resource_by_name(session, 'team', 1)\n self.assertIsNotNone(team)\n self.assertEqual(1, team.id)\n\n story = worker.resolve_resource_by_name(session, 'story', 1)\n self.assertIsNotNone(story)\n self.assertEqual(1, story.id)\n\n branch = worker.resolve_resource_by_name(session, 'branch', 1)\n self.assertIsNotNone(branch)\n self.assertEqual(1, branch.id)\n\n milestone = worker.resolve_resource_by_name(session,\n 'milestone', 1)\n self.assertIsNotNone(milestone)\n self.assertEqual(1, milestone.id)\n\n\nclass TestWorkerPlugin(plugin_base.WorkerTaskBase):\n def handle(self, session, author, method, url, path, query_string, status,\n resource, resource_id, sub_resource=None, sub_resource_id=None,\n resource_before=None, resource_after=None):\n pass\n\n def enabled(self):\n return True\n","sub_path":"storyboard/tests/plugin/test_event_worker.py","file_name":"test_event_worker.py","file_ext":"py","file_size_in_byte":2824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"573695135","text":"import serial\n\nser = serial.Serial(\"/dev/cu.usbmodem14201\", 9600)\nhrValues = []\nmiliValues = []\nmilis = []\nValues = []\n\n\ndef analisisHR():\n global hrValues\n global miliValues\n valores = []\n valoresMili = []\n for i in range(0, 97):\n valores.append((hrValues[i]+hrValues[i+1]+hrValues[i+2])/3)\n valoresMili.append((miliValues[i]+miliValues[i+1]+miliValues[i+2])/3)\n subida = True\n palpitacionAnterior = 1\n for i in range(0, len(valores)):\n if (valores[i+1] > valores[i]):\n tiempo = valoresMili[i]\n\n else:\n tiempo = valoresMili[i]-palpitacionAnterior\n\n subida = False\n\n hrValues = hrValues[25:]\n miliValues = miliValues[25:]\n\n\ncount = 0\nleer = True\nwhile(leer):\n lineBytes = ser.readline()\n line = lineBytes.decode(\"ascii\")\n if line[0:2] != \"HR\":\n continue\n line = line.rstrip()\n medidas = line.split(\";\")\n hr = int(medidas[0].split(\":\")[1])\n medidas = int(medidas[0].split(\":\")[1])\n miliValues.append(milis)\n if(len(hrValues) == 100):\n analisisHR()\n Values.append(hr)\n count += 1\n if (count == 1000):\n leer = False\n # print(hr)\n print(count/10, str(\"%\"))\nprint(Values)\n","sub_path":"Python/Procesamiento e incersion/hr-ml copy.py","file_name":"hr-ml copy.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"553409547","text":"#Default Imports\nimport numpy as np\nipl_matches_array =np.genfromtxt(\"data/ipl_matches_small.csv\", dtype=\"|S50\", skip_header=1, delimiter=\",\")\ndef get_all_sixes_filter():\n\n array1=ipl_matches_array[:,16]\n k= (array1=='6')\n return k\n\n\n\n#Your Solution\n","sub_path":"q04_get_all_sixes_filter/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"46347471","text":"\"\"\"\nSim Snatcher is licensed under the Creative Commons Attribution 4.0 International public license (CC BY 4.0).\nhttps://creativecommons.org/licenses/by/4.0/\nhttps://creativecommons.org/licenses/by/4.0/legalcode\n\nCopyright (c) COLONOLNUTTY\n\"\"\"\nfrom typing import List, Tuple, Union\n\nimport services\nfrom sims.sim_info import SimInfo\nfrom sims4communitylib.enums.tags_enum import CommonGameTag\nfrom sims4communitylib.utils.sims.common_sim_situation_utils import CommonSimSituationUtils\nfrom situations.dynamic_situation_goal_tracker import DynamicSituationGoalTracker\nfrom situations.situation_goal import SituationGoal\nfrom situations.situation_goal_targeted_sim import SituationGoalTargetedSim\nfrom situations.situation_goal_tracker import SituationGoalTracker\nfrom whims.whim_set import WhimSetBaseMixin\nfrom sims4communitylib.enums.situations_enum import CommonSituationId\nfrom sims4communitylib.utils.sims.common_sim_utils import CommonSimUtils\n\n\nclass SSCommonSituationUtils:\n \"\"\" Utilities for situations. \"\"\"\n @staticmethod\n def has_leave_situation(sim_info: SimInfo) -> bool:\n \"\"\" Determine if a sim is currently involved in a leaving situation. \"\"\"\n if sim_info is None:\n return False\n return CommonSimSituationUtils.has_situations(sim_info, (CommonSituationId.LEAVE, ))\\\n or SSCommonSituationUtils.is_in_situations_with_any_tags(sim_info, (CommonGameTag.ROLE_LEAVE,))\n\n @staticmethod\n def make_sim_leave(sim_info: SimInfo):\n \"\"\" Make a sim leave the current lot. \"\"\"\n if sim_info is None:\n return\n sim = CommonSimUtils.get_sim_instance(sim_info)\n if sim is None:\n return\n services.get_zone_situation_manager().make_sim_leave(sim)\n\n @staticmethod\n def remove_sim_from_situation(sim_info: SimInfo, situation_id: Union[CommonSituationId, int]) -> bool:\n \"\"\" Remove a sim from the specified situation. \"\"\"\n if sim_info is None or situation_id is None:\n return False\n situation_manager = services.get_zone_situation_manager()\n situation_manager.remove_sim_from_situation(sim_info, situation_id)\n return True\n\n @staticmethod\n def has_situation_job(sim_info: SimInfo, situation_job_id: int) -> bool:\n \"\"\" Determine if a sim is currently assigned to a situation job. \"\"\"\n if sim_info is None:\n return False\n sim_situations = CommonSimSituationUtils.get_situations(sim_info)\n for situation in sim_situations:\n for situation_job in situation.all_jobs_gen():\n assigned_situation_job_id = getattr(situation_job, 'guid64', None)\n if assigned_situation_job_id == situation_job_id:\n return True\n return False\n\n @staticmethod\n def has_situation_jobs(sim_info: SimInfo, situation_job_ids: Tuple[int]) -> bool:\n \"\"\" Determine if a sim is currently assigned any of the specified situation job. \"\"\"\n sim_situations = CommonSimSituationUtils.get_situations(sim_info)\n for situation in sim_situations:\n for situation_job in situation.all_jobs_gen():\n situation_job_id = getattr(situation_job, 'guid64', None)\n if situation_job_id in situation_job_ids:\n return True\n return False\n\n @staticmethod\n def is_in_situations_with_any_tags(sim_info: SimInfo, tags: Tuple[CommonGameTag]) -> bool:\n \"\"\" Determine if a Sim is currently in a situation with any of the specified tags. \"\"\"\n if sim_info is None:\n return False\n tags = set(tags)\n situations = CommonSimSituationUtils.get_situations(sim_info)\n for tag in tags:\n for situation in situations:\n if tag in getattr(situation, 'tags', tuple()):\n return True\n for situation_job in situation.all_jobs_gen():\n if tag in getattr(situation_job, 'tags', tuple()):\n return True\n return False\n\n @staticmethod\n def create_visit_situation(sim_info: SimInfo):\n \"\"\" Create a visit situation for a Non-Player Sim.\"\"\"\n if sim_info is None:\n return\n sim = CommonSimUtils.get_sim_instance(sim_info)\n if sim is None:\n return\n services.get_zone_situation_manager().create_visit_situation(sim)\n\n @staticmethod\n def get_situation_goals(sim_info: SimInfo) -> Tuple[Union[SituationGoal, SituationGoalTargetedSim]]:\n \"\"\" Retrieve the goals of all situations a Sim is currently in. \"\"\"\n if sim_info is None:\n return tuple()\n goal_instances: List[Union[SituationGoal, SituationGoalTargetedSim]] = list()\n for situation in CommonSimSituationUtils.get_situations(sim_info):\n goal_tracker = situation._get_goal_tracker()\n if goal_tracker is None:\n continue\n if isinstance(goal_tracker, SituationGoalTracker):\n if goal_tracker._realized_minor_goals is not None:\n goal_instances.extend(goal_tracker._realized_minor_goals.keys())\n if goal_tracker._realized_main_goal is not None:\n goal_instances.insert(0, goal_tracker._realized_main_goal)\n elif isinstance(goal_tracker, DynamicSituationGoalTracker):\n goal_instances.extend(goal_tracker.goals)\n return tuple(goal_instances)\n\n @staticmethod\n def complete_situation_goal(sim_info: SimInfo, situation_goal_id: int, target_sim_info: SimInfo=None):\n \"\"\" Complete a situation goal for the specified Sim.\"\"\"\n if sim_info is None:\n return\n from sims4communitylib.utils.sims.common_whim_utils import CommonWhimUtils\n goal_instances: List[Union[SituationGoal, SituationGoalTargetedSim, WhimSetBaseMixin]] = list()\n goal_instances.extend(SSCommonSituationUtils.get_situation_goals(sim_info))\n goal_instances.extend(CommonWhimUtils.get_current_whims(sim_info))\n for goal_instance in goal_instances:\n if goal_instance.guid64 != situation_goal_id:\n continue\n goal_instance.force_complete(target_sim=target_sim_info)\n","sub_path":"Scripts/simsnatcher/commonlib/utils/common_situation_utils.py","file_name":"common_situation_utils.py","file_ext":"py","file_size_in_byte":6250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"467157990","text":"import getopt\nimport sys\n\nversion = '1.0'\nverbose = False\noutput_filename = 'default.out'\n\nprint('ARGV :', sys.argv[1:])\n\noptions, remainder = getopt.getopt(\n sys.argv[1:],\n 'o:v',\n ['output=', 'verbose', 'version=']\n)\n\nprint('OPTIONS :', options)\n\nfor opt, arg in options:\n if opt in ('-o', '--output'):\n output_filename = arg\n elif opt in ('-v', '--verbose'):\n verbose = True\n elif opt == '--version':\n version = arg\n\nprint('VERSION :', version)\nprint('VERBOSE :', verbose)\nprint('OUTPUT :', output_filename)\nprint('REMAINING:', remainder)\n\n'''\npython getopt_example.py -o foo\npython getopt_example.py -ofoo\npython getopt_example.py --output foo\npython getopt_example.py --output=foo\n\nARGV : ['--output=foo']\nOPTIONS : [('--output', 'foo')]\nVERSION : 1.0\nVERBOSE : False\nOUTPUT : foo\nREMAINING : []\n'''\n","sub_path":"python/py2/modules/getopt/getopt_example.py","file_name":"getopt_example.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"106716628","text":"#!/usr/bin/python3\r\n# -*- coding: utf-8 -*-\r\n\r\nimport re\r\n\r\n#var meses_31_dias = [\"01\",\"03\",\"05\",\"07\",\"08\",\"10\",\"12\"]\r\n#var meses_30_dias = [\"02\",\"04\",\"06\",\"09\",\"11\"]\r\n\r\nfrom db import DB\r\nfrom datetime import datetime, date\r\nimport os\r\nimport filetype\r\nfrom data_base import *\r\n\r\n\r\ndatabase = DB('localhost',USER_DB,PASS_DB,DB_DB)\r\n\r\n#f = open(\"./proxy.txt\",\"a\")\r\n\r\ndef check_form(formulario):\r\n # primero se revisa que estén los atributos:\r\n valores_correctos = []\r\n errores_final = []\r\n #----- Region\r\n \r\n if \"region\" in formulario.keys():\r\n resultado_region = valida_region(formulario['region'].value)\r\n else:\r\n resultado_region = (False,\"El formulario no contiene región\")\r\n if not resultado_region[0]:\r\n errores_final.append(resultado_region[1])\r\n \r\n #----- Comuna\r\n if \"comuna\" in formulario.keys():\r\n resultado_comuna = valida_comuna(formulario['comuna'].value,resultado_region)\r\n else:\r\n resultado_comuna = (False, \"El formulario no contiene comuna\")\r\n if not resultado_comuna[0]:\r\n errores_final.append(resultado_comuna[1])\r\n #----- Sector\r\n if \"sector\" in formulario.keys():\r\n resultado_sector = valida_sector(formulario['sector'].value)\r\n else:\r\n resultado_sector = (True,\"\")\r\n if not resultado_sector[0]:\r\n errores_final.append(resultado_sector[1])\r\n #----- Nombre\r\n if \"nombre\" in formulario.keys():\r\n resultado_nombre = valida_nombre(formulario['nombre'].value)\r\n else:\r\n resultado_nombre = (False,\"El formulario no contiene nombre\")\r\n if not resultado_nombre[0]:\r\n errores_final.append(resultado_nombre[1])\r\n #----- Email\r\n if \"email\" in formulario.keys():\r\n resultado_email = valida_email(formulario['email'].value)\r\n else:\r\n resultado_email = (False,\"El formulario no contiene email\")\r\n if not resultado_email[0]:\r\n errores_final.append(resultado_email[1])\r\n #----- Celular\r\n if \"celular\" in formulario.keys():\r\n resultado_celular = valida_celular(formulario['celular'].value)\r\n else:\r\n resultado_celular = (True,\"\")\r\n if not resultado_celular[0]:\r\n errores_final.append(resultado_celular[1])\r\n \r\n \r\n\r\n #Ver avistamientos\r\n #------- Fecha\r\n cantidad_fechas = 0\r\n fecha_ok = True\r\n fechas_todas = []\r\n fecha_error = \"\"\r\n \r\n if \"dia-hora-avistamiento\" in formulario.keys():\r\n #f.write(\"medi2da\" + \"\\n\")\r\n #f.write(str(type(formulario['dia-hora-avistamiento'])) + \"\\n\")\r\n #f.write(str(formulario['dia-hora-avistamiento']) + \"\\n\")\r\n \r\n #f.write(\"medid2a\" + \"\\n\")\r\n if type(formulario['dia-hora-avistamiento']) is list:\r\n for fecha in formulario['dia-hora-avistamiento']:\r\n cantidad_fechas += 1\r\n fecha_actual = valida_fecha(fecha.value)\r\n fechas_todas.append(fecha_actual)\r\n fecha_ok = fecha_ok and fecha_actual[0]\r\n resultado_fecha = (fecha_ok,fechas_todas)\r\n if not fecha_ok:\r\n resultado_fecha =(False, \"Una fecha es inválida\")\r\n else:\r\n cantidad_fechas = 1\r\n fecha_actual = valida_fecha(formulario['dia-hora-avistamiento'].value)\r\n fechas_todas.append(fecha_actual)\r\n fecha_ok = fecha_ok and fecha_actual[0]\r\n resultado_fecha = (fecha_ok,fechas_todas)\r\n if not fecha_ok:\r\n resultado_fecha =(False, fecha_actual[1])\r\n else:\r\n resultado_fecha = (False,\"No se ingresaron fechas\")\r\n if not resultado_fecha[0]:\r\n errores_final.append(resultado_fecha[1])\r\n \r\n #f.write(fechas_todas + \"\\n\") \r\n #------- Tipo\r\n cantidad_tipos = 0\r\n tipos_ok = True\r\n tipos_todos = []\r\n tipo_error = \"\"\r\n\r\n if 'tipo-avistamiento' in formulario.keys():\r\n if type(formulario['tipo-avistamiento']) is list:\r\n for tipo in formulario['tipo-avistamiento']:\r\n cantidad_tipos += 1\r\n tipo_actual = valida_tipo(tipo.value)\r\n tipos_todos.append(tipo_actual)\r\n tipos_ok = tipos_ok and tipo_actual[0]\r\n resultado_tipo = (tipos_ok,tipos_todos)\r\n if not tipos_ok:\r\n resultado_tipo = (False,\"Un tipo es inválido\")\r\n else:\r\n cantidad_tipos = 1\r\n tipo_actual = valida_tipo(formulario['tipo-avistamiento'].value)\r\n tipos_todos.append(tipo_actual)\r\n tipos_ok = tipos_ok and tipo_actual[0]\r\n resultado_tipo = (tipos_ok,tipos_todos)\r\n if not tipos_ok:\r\n resultado_tipo = (False,\"Tipo inválido\")\r\n else:\r\n resultado_tipo = (False,\"El formulario no contiene tipos\")\r\n if not resultado_tipo[0]:\r\n errores_final.append(resultado_tipo[1])\r\n \r\n\r\n # ----- fotos \r\n imgs_ok = True\r\n images_paths = []\r\n \r\n\r\n #------- Estado\r\n\r\n cantidad_estados = 0\r\n estados_ok = True\r\n estados_todos = []\r\n estado_error = \"\"\r\n\r\n if 'estado-avistamiento' in formulario.keys():\r\n if type(formulario['estado-avistamiento']) is list:\r\n for estado in formulario['estado-avistamiento']:\r\n cantidad_estados += 1\r\n estado_actual = valida_estado(estado.value)\r\n estados_todos.append(estado_actual)\r\n #f.write(\"---\" + str(estados_ok) + \"\\n\")\r\n estados_ok = estados_ok and estado_actual[0]\r\n resultado_estado = (estados_ok,estados_todos)\r\n if not estados_ok:\r\n resultado_estado = (False,\"Algún estado es inválido\")\r\n else:\r\n cantidad_estados = 1\r\n estado_actual = valida_estado(formulario['estado-avistamiento'].value)\r\n estados_todos.append(estado_actual)\r\n estados_ok = estados_ok and estado_actual[0]\r\n resultado_estado = (estados_ok,estados_todos)\r\n if not estados_ok:\r\n resultado_estado = (False,\"El estado es inválido\")\r\n \r\n else:\r\n resultado_estado = (False,\"El formulario no contiene estados\")\r\n\r\n if not resultado_estado[0]:\r\n errores_final.append(resultado_estado[1])\r\n\r\n resultados_unicos = [resultado_region, resultado_comuna, resultado_sector, resultado_nombre, resultado_email,resultado_celular]\r\n resultado_total = True\r\n errores = \"\"\r\n for resultado in resultados_unicos:\r\n #f.write(\"CalcTotal\" + str(resultado[0]) + \"\\n\")\r\n if not resultado[0]:\r\n errores += \"
  • \" + resultado[1] + \"
  • \"\r\n resultado_total = resultado_total and resultado[0]\r\n \r\n #f.write(\"Tipo :\"+ str(tipo_error)\r\n\r\n id_avistamiento = 0\r\n id_detalle = 0\r\n if (cantidad_fechas == cantidad_tipos == cantidad_estados) and (fecha_ok and tipos_ok and estados_ok) and resultado_total:\r\n # Todas las condiciones anteriores están OK\r\n fotos_paths_actuales = add_fotos(formulario)\r\n if not fotos_paths_actuales[0]:\r\n errores_final.append(fotos_paths_actuales[1])\r\n #f.write(str(fotos_paths_actuales))\r\n if fotos_paths_actuales[0] and len(fotos_paths_actuales[1]) == cantidad_fechas:\r\n # Todo Ok, queda agregar las cosas\r\n #----- Avistamiento\r\n ahora = datetime.now()\r\n avistamiento_add = (resultado_comuna[1],ahora,resultado_sector[1],resultado_nombre[1],resultado_email[1],resultado_celular[1])\r\n id_avistamiento = database.save_avistamiento(avistamiento_add)\r\n i = cantidad_estados - 1\r\n while i >= 0:\r\n id_detalle = database.save_detalle_avistamiento((fechas_todas[i][1],tipos_todos[i][1],estados_todos[i][1],id_avistamiento))\r\n for foto in fotos_paths_actuales[1][i]:\r\n database.save_foto((foto[0],foto[1],id_detalle))\r\n i = i - 1\r\n return (True,[])\r\n else:\r\n #f.write(\"Final false \\n\")\r\n return (False,errores_final)\r\n else:\r\n return (False,errores_final)\r\n\r\n\r\n \r\n \r\ndef valida_region(region):\r\n #f.write(str(region) + \"\\n\")\r\n resultado = database.get_region_id(region)\r\n \r\n if resultado:\r\n return (True,resultado[0])\r\n else:\r\n return (False, \"Región inválida\")\r\n\r\ndef valida_comuna(comuna,region_id):\r\n resultado = database.get_comuna_info(comuna)\r\n if region_id[0]:\r\n if resultado:\r\n if resultado[1] != region_id[1]:\r\n return (False,\"La comuna no corresponde a la region\")\r\n else:\r\n return (True, resultado[0])\r\n else:\r\n return (False, \"Comuna no está en la base de datos\")\r\n else:\r\n if resultado:\r\n return (True, resultado[0])\r\n else:\r\n return (False, \"Comuna no está en la base de datos\")\r\n\r\ndef valida_sector(sector):\r\n regex = \"^[A-zÜÑÁÉÍÓÚáéíóúüñ0-9]+(\\s[A-zÜÑÁÉÍÓÚáéíóúüñ0-9]+)*\"\r\n if (sector == \"\"):\r\n return (True,\"\")\r\n if (len(sector) > 200):\r\n return (False,\"El largo del sector supera los 200 caracteres\")\r\n x = re.search(regex,sector)\r\n if x.span()[1] == len(sector):\r\n return (True,sector)\r\n return (False, \"Sector solo puede usar letras y números\")\r\n\r\ndef valida_nombre(nombre):\r\n regex = \"^(([A-ZÜÑÁÉÍÓÚ]+([a-záéíóúüñ]*))(\\s[A-ZÜÑÁÉÍÓÚ]+([a-záéíóúüñ]*))*)\"\r\n if (nombre == \"\"):\r\n return (False, \"Se requiere un nombre\")\r\n if (len(nombre) > 100):\r\n return (False, \"El nombre no puede superar los 100 caracteres\")\r\n x = re.search(regex,nombre)\r\n if not x:\r\n return (False, \"No se cumple el formato de nombre\")\r\n if x.span()[1] == len(nombre):\r\n return (True,nombre)\r\n return (False,\"Nombre inválido\")\r\n\r\ndef valida_email(email):\r\n regex = \"^[^@]+@[^@]+\\.[a-zA-Z]{2,}$\"\r\n if (email == \"\"):\r\n return (False, \"Email obligatorio\")\r\n x = re.search(regex,email)\r\n if not x:\r\n return (False,\"Email no cumple el formato\")\r\n if x.span()[1] == len(email):\r\n return (True,email)\r\n return (False,\"Email no cumple el formato\")\r\n\r\ndef valida_celular(celular):\r\n regex = \"^\\+569\\d{8}\"\r\n if (celular == \"\"):\r\n return (True,celular)\r\n x = re.search(regex,celular)\r\n if not x:\r\n return (False,\"Celular no cumple el formato\")\r\n if x.span()[1] == len(celular):\r\n return (True,celular)\r\n return (False,\"Celular no cumple el formato\")\r\n\r\ndef valida_fecha(fecha):\r\n regex = \"\\d{4}-((0[1-9])|(1[0-2]))-((0[1-9])|([1-2][0-9])|(3[0-1])) (([0-1][0-9])|(2[0-3])):(([0-5][0-9]))\"\r\n if fecha == \"\":\r\n return (False,\"Se requiere fecha\")\r\n x = re.search(regex,fecha)\r\n if not x:\r\n return (False,\"Formato de fecha inválido\")\r\n if x.span()[1] - x.span()[0] == len(fecha):\r\n anho = fecha[0:4]\r\n mes = fecha[5:7]\r\n dia = fecha[8:10]\r\n anho_numero = int(anho)\r\n if mes == \"02\":\r\n if int(dia) > 29:\r\n return (False,\"Fecha inválida\")\r\n if dia == \"29\":\r\n if ((anho_numero % 4 == 0) and (anho_numero % 100 != 0)) or (anho_numero % 400 == 0):\r\n if datetime.strptime(fecha, '%Y-%m-%d %H:%M') <= datetime.now():\r\n return (True,datetime.strptime(fecha, '%Y-%m-%d %H:%M'))\r\n else:\r\n return (False, \"Fecha aún no ocurre\")\r\n else:\r\n return (False,\"Fecha inválida\")\r\n elif mes in [\"02\",\"04\",\"06\",\"09\",\"11\"] and dia == \"31\":\r\n return (False,\"Fecha inválida\")\r\n else:\r\n if datetime.strptime(fecha, '%Y-%m-%d %H:%M') <= datetime.now():\r\n return (True,datetime.strptime(fecha, '%Y-%m-%d %H:%M'))\r\n else:\r\n return (False, \"Fecha aún no ocurre\")\r\n else:\r\n return (False,\"Fecha inválida\")\r\n \r\n\r\ndef valida_tipo(tipo):\r\n if tipo in ['no sé', 'insecto', 'arácnido', 'miriápodo']:\r\n return (True,tipo)\r\n return (False,\"Tipo inválido\")\r\n\r\ndef valida_estado(estado):\r\n if estado in ['no sé', 'vivo', 'muerto']:\r\n return (True,estado)\r\n return (False,\"Tipo inválido\")\r\n\r\n\r\ndef valida_imagen(fileitem):\r\n if fileitem.filename:\r\n filenames = fileitem.filename\r\n hash_archivo = database.hash_name(filenames)\r\n open('T2/media/'+hash_archivo,'wb').write(fileitem.file.read()) # anakena ../../T2/media/\r\n size = os.fstat(fileitem.file.fileno()).st_size\r\n if size <= 50000:\r\n tipo_real = filetype.guess('T2/media/'+hash_archivo) # anakena ../../T2/media/\r\n if (\"image\" or \"gif\" or \"jpg\") in str(tipo_real).lower() :\r\n img_ok = True\r\n else:\r\n error = \"Tipo de archivo no válido\"\r\n os.remove(\"T2/media/\"+hash_archivo) # anakena ../../T2/media/\r\n else:\r\n error = \"Archivo muy pesado\"\r\n\r\ntest_form = {\r\n \"region\": \"Región del Ñuble\",\r\n \"comuna\":\"Chillan\",\r\n \"sector\":\"\",\r\n \"nombre\":\"Cristóbal\",\r\n \"email\":\"cris@gmail.com\",\r\n \"celular\":\"\",\r\n \"dia-hora-avistamiento\" : [\"2021-03-29 13:21\",\"2021-03-29 13:22\"],\r\n \"tipo-avistamiento\" : [\"no sé\",\"insecto\"],\r\n \"estado-avistamiento\" : [\"vivo\",\"muerto\"]\r\n}\r\n\r\ndef add_fotos(form):\r\n cantidad_fotos = 0\r\n fotos_paths = []\r\n imgs_ok = True\r\n offset_foto = -1\r\n if 'foto-avistamiento' in form.keys():\r\n if type(form['foto-avistamiento']) is list:\r\n for foto in form['foto-avistamiento']:\r\n offset_foto += 1\r\n cantidad_fotos += 1\r\n fileitem = foto\r\n if fileitem.filename:\r\n filenames = fileitem.filename\r\n hash_archivo = database.hash_name(filenames,offset_foto)\r\n path_archivo = 'T2/media/'+hash_archivo # anakena ../../T2/media/\r\n open(path_archivo,'wb').write(fileitem.file.read())\r\n size = os.fstat(fileitem.file.fileno()).st_size\r\n if size <= 12000000:\r\n tipo_real = filetype.guess(path_archivo)\r\n if (\"image\" or \"gif\" or \"jpg\") in str(tipo_real).lower() :\r\n imgs_ok = imgs_ok and True\r\n fotos_paths.append([[hash_archivo,filenames]])\r\n else:\r\n imgs_ok = imgs_ok and False\r\n error = \"El tipo de algún archivo no es válido\"\r\n os.remove(path_archivo)\r\n break\r\n else:\r\n error = \"Algún archivo es muy pesado\"\r\n imgs_ok = imgs_ok and False\r\n break\r\n else:\r\n offset_foto += 1\r\n cantidad_fotos = 1\r\n fileitem = form['foto-avistamiento']\r\n if fileitem.filename:\r\n filenames = fileitem.filename\r\n hash_archivo = database.hash_name(filenames,offset_foto)\r\n path_archivo = 'T2/media/'+hash_archivo # anakena ../../T2/media/\r\n open(path_archivo,'wb').write(fileitem.file.read())\r\n size = os.fstat(fileitem.file.fileno()).st_size\r\n #f.write(\"size: \"+ str(size) + \"\\n\")\r\n if size <= 12000000:\r\n tipo_real = filetype.guess(path_archivo)\r\n if (\"image\" or \"gif\" or \"jpg\") in str(tipo_real).lower() :\r\n imgs_ok = imgs_ok and True\r\n fotos_paths.append([[hash_archivo,filenames]])\r\n else:\r\n error = \"Tipo de archivo no válido\"\r\n os.remove(path_archivo)\r\n imgs_ok = imgs_ok and False\r\n else:\r\n error = \"Archivo muy pesado\"\r\n imgs_ok = imgs_ok and False\r\n else:\r\n return (False, \"No hay fotos\")\r\n\r\n i = 0\r\n if imgs_ok:\r\n while i < cantidad_fotos:\r\n name_form = 'foto-avistamiento-'+str(i) \r\n if name_form in form.keys():\r\n if type(form[name_form]) is list:\r\n if (len(form[name_form]) >= 5):\r\n return (False,\"Hay más de 5 fotos en un avistamiento\")\r\n for foto in form[name_form]:\r\n offset_foto += 1\r\n fileitem = foto\r\n if fileitem.filename:\r\n filenames = fileitem.filename\r\n hash_archivo = database.hash_name(filenames,offset_foto)\r\n path_archivo = 'T2/media/'+hash_archivo # anakena ../../T2/media/\r\n open(path_archivo,'wb').write(fileitem.file.read())\r\n size = os.fstat(fileitem.file.fileno()).st_size\r\n #f.write(\"size: \"+ str(size) + \"\\n\")\r\n if size <= 12000000:\r\n tipo_real = filetype.guess(path_archivo)\r\n if (\"image\" or \"gif\" or \"jpg\") in str(tipo_real).lower() :\r\n imgs_ok = imgs_ok and True\r\n fotos_paths[i] += [[hash_archivo,filenames]]\r\n else:\r\n imgs_ok = imgs_ok and False\r\n error = \"El tipo de algún archivo no es válido\"\r\n os.remove(path_archivo)\r\n break\r\n else:\r\n error = \"Algún archivo es muy pesado\"\r\n imgs_ok = imgs_ok and False\r\n break\r\n else:\r\n offset_foto += 1\r\n fileitem = form[name_form]\r\n if fileitem.filename:\r\n filenames = fileitem.filename\r\n hash_archivo = database.hash_name(filenames,offset_foto)\r\n path_archivo = 'T2/media/'+hash_archivo # anakena ../../T2/media/\r\n open(path_archivo,'wb').write(fileitem.file.read())\r\n size = os.fstat(fileitem.file.fileno()).st_size\r\n #f.write(\"size: \"+ str(size) + \"\\n\")\r\n if size <= 12000000:\r\n tipo_real = filetype.guess(path_archivo)\r\n if (\"image\" or \"gif\" or \"jpg\") in str(tipo_real).lower() :\r\n imgs_ok = imgs_ok and True\r\n fotos_paths[i] += [[hash_archivo,filenames]]\r\n else:\r\n error = \"Tipo de archivo no válido\"\r\n os.remove(path_archivo)\r\n imgs_ok = imgs_ok and False\r\n else:\r\n error = \"Archivo muy pesado\"\r\n imgs_ok = imgs_ok and False\r\n i += 1\r\n \r\n if not imgs_ok:\r\n for group in fotos_paths:\r\n for path_foto in group:\r\n os.remove(\"T2/media/\"+path_foto[0]) # anakena ../../T2/media/\r\n #f.write(\"Error-val\"+str(error)+\"\\n ---\")\r\n return (False,error)\r\n return (True,fotos_paths)\r\n\r\n","sub_path":"cgi-bin/T3/validacion.py","file_name":"validacion.py","file_ext":"py","file_size_in_byte":19829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"36979239","text":"from itertools import permutations, combinations\n\ndef sgn(p):\n s = 0\n for i in range(len(p)):\n for j in range(i + 1, len(p)):\n s += p[i] > p[j]\n return (-1)**(s%2)\n \ndef det(M):\n res = 0\n for p in permutations(range(len(M))):\n s = sgn(p)\n for i, j in enumerate(p):\n s *= M[i][j]\n res += s\n return res\n\ndef geron(a, b, c):\n s = a + b + c\n r = s\n for x in (a, b, c):\n r *= (s - 2*x)\n return (r**0.5)/4\n\nn = int(input())\nfor i in range(n):\n k = [(i, j) for i in range(4) for j in range(i + 1, 4)]\n v = map(int, input().split())\n edges = dict(zip(k, v))\n for i, j in k:\n edges[j, i] = edges[i, j]\n for i in range(4):\n edges[i, i] = 0\n M = [[0] + [1]*4]\n for i in range(4):\n l = [1]\n for j in range(4):\n l.append(edges[i, j]**2)\n M.append(l)\n V = (det(M)/288)**0.5\n S = 0\n for t in combinations(range(4), 3):\n sides = (edges[p] for p in combinations(t, 2))\n S += geron(*sides)\n r = 3*(V/S)\n print('{:.4f}'.format(r))\n","sub_path":"tetra.py","file_name":"tetra.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"613674774","text":"import pandas as pd\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\n\n\"\"\" File contains global variables \"\"\"\n\nbrowser = webdriver.Chrome()\n\n# collects all the extacted matches which will be used for processing at the end of the scraping process\nmatches_df = pd.DataFrame()\n\n# Right after the instertion of the player into the database its database id will be saved into the dictionary\n# so that later code could retrieve the database player ids in a fast and easy manner.\n# Without these the database must be selecting players constantly, NOT GOOD\nplayer_id_cache = {}\n\n# method for visiting new pages with selenium and then extract the new page's content with Beautiful Soup\n# return the newly visited extracted beautiful soup result\ndef goToUrl(url, *params):\n url = url.format(*params)\n browser.get(url)\n return BeautifulSoup(browser.page_source, 'html.parser')\n","sub_path":"globals.py","file_name":"globals.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"171761365","text":"import numpy as np\nfrom astropy.table import Table\nfrom matplotlib import colors, cm, gridspec, pyplot as plt\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable \nimport matplotlib.patches as patches\n\n\ndef distMatches(ax, max_mass, log_age = 8.0, v_low = 66, v_high = 84, target = 'MB980006', \n obs_year = 1998, d_source = 10, read_dir = '', y_label = True, show_bar = True, skip = 2):\n tick_size = 17\n text_size = 25\n\n age_label = str(log_age).replace('.', '_')\n with open('{0}.{1}.dist.mass.txt'.format(read_dir + target, age_label), 'r') as f:\n dist_plot_arr = []\n mass_plot_arr = []\n u_plot_arr = []\n lines = f.readlines()\n for line_i in lines:\n d, r, m = line_i.split(',')\n dist_plot_arr.append(np.float(d))\n mass_plot_arr.append(np.float(m))\n u = np.round(PropMotFromRad(np.float(r) + 2.0, obs_year), 1) #Add 2 because bin width is 4 pixels, Round for plotting purposes\n u_plot_arr.append(u)\n dist_plot_arr = np.array(dist_plot_arr) / 1000 #convert to kpc\n mass_plot_arr = np.array(mass_plot_arr)\n u_plot_arr = np.array(u_plot_arr)\n u_low, u_high = PropMotFromVelArr(v_high, v_low, dist_plot_arr, d_source)\n getMasses(target, u_low, u_high, u_plot_arr, dist_plot_arr, mass_plot_arr)\n\n dist_pad = np.min(dist_plot_arr) / 3\n u_pad = np.min(u_plot_arr) / 3\n\n ax.fill_between(dist_plot_arr, u_low, u_high, alpha = 0.5)\n ax.add_patch(patches.Rectangle((np.min(dist_plot_arr) - dist_pad, 0), \n np.max(dist_plot_arr) + dist_pad, PropMotFromRad(5, obs_year), alpha = 0.3, color = 'grey'))\n\n im = ax.scatter(dist_plot_arr, u_plot_arr, marker = '*', s = 120, c = mass_plot_arr, alpha = 0.5,\n norm = colors.PowerNorm(gamma=1./2., vmax = max_mass))\n divider = make_axes_locatable(ax)\n cax = divider.append_axes(\"right\", size=\"5%\", pad=0.1)\n cbar = plt.colorbar(im, ax = ax, cax = cax)\n if show_bar:\n cbar.set_label('Mass [$M_{\\odot}$]', fontsize = text_size)\n cbar.ax.tick_params(labelsize=tick_size)\n\n u_x, dist_x = getXs(u_plot_arr, dist_plot_arr, obs_year)\n x_im = ax.scatter(dist_x, u_x, marker = 'o', s = 45, c = 'k')\n\n ax.set_xticks(dist_plot_arr)\n ax.set_xticklabels(dist_plot_arr, fontsize = tick_size, rotation = 50)\n ax.set_xlim(np.min(dist_plot_arr) - dist_pad, np.max(dist_plot_arr) + dist_pad)\n ax.set_xlabel(\"Distance to Lens [$kpc$]\", fontsize = text_size)\n ax.set_yticks(np.arange(np.min(0), np.max(u_plot_arr) + 1, skip))\n ax.set_yticklabels(np.arange(np.min(0), np.max(u_plot_arr) + 1, skip), fontsize = tick_size, rotation = 50)\n ax.set_ylim(np.min(0), np.round((np.max(u_high))/10) * 10 + 0.25)\n if y_label:\n ax.set_ylabel(\"Proper Motion [$mas/yr$]\", fontsize = text_size)\n if target == 'MB960005':\n ax.set_title(\"MB 96-5, 100 Myr\", fontsize = text_size)\n elif target == 'MB980006':\n ax.set_title(\"MB 98-6, 100 Myr\", fontsize = text_size)\n return\n\n\ndef isoPlotMB965():\n distMatches(log_age = 8.0, max_mass = 1, v_low = 21, v_high = 31, target = 'MB960005', obs_year = 1996, \n d_source = 10, read_dir = '/Users/haynesstephens1/github/hstephens-python-code/ml/outputs/MB960005/')\n return\n\n\ndef isoPlotMB986():\n distMatches(log_age = 8.0, max_mass = 3, v_low = 56, v_high = 92, target = 'MB980006', obs_year = 1998, \n d_source = 10, read_dir = '/Users/haynesstephens1/github/hstephens-python-code/ml/outputs/MB980006/')\n return\n\n\ndef bothPlots():\n fig = plt.figure(figsize = (18, 7.5)) \n gs = gridspec.GridSpec(1, 2, width_ratios=[1, 1])\n\n ax96 = plt.subplot(gs[0])\n distMatches(ax96, log_age = 8.0, max_mass = 1, v_low = 21, v_high = 31, target = 'MB960005', obs_year = 1996, \n d_source = 10, read_dir = '/Users/haynesstephens1/github/hstephens-python-code/ml/outputs/MB960005/', show_bar = False, skip = 1)\n\n ax98 = plt.subplot(gs[1])\n distMatches(ax98, log_age = 8.0, max_mass = 3, v_low = 56, v_high = 92, target = 'MB980006', obs_year = 1998, \n d_source = 10, read_dir = '/Users/haynesstephens1/github/hstephens-python-code/ml/outputs/MB980006/', y_label = False)\n\n plt.tight_layout()\n plt.savefig('/Users/haynesstephens1/github/hstephens-python-code/ml/outputs/both.iso_plots.pdf')\n plt.savefig('/Users/haynesstephens1/github/hstephens-python-code/ml/outputs/both.iso_plots.png')\n plt.show()\n\n\ndef ageMatches(distance, target = 'MB980006', read_dir = '', output_dir = ''):\n dist_label = str(distance)\n with open('{0}.{1}.age.mass.txt'.format(read_dir + target, dist_label), 'r') as f:\n age_plot_arr, mass_plot_arr = [], []\n lines = f.readlines()\n for line_i in lines:\n log_age, m = line_i.split(',')\n age_plot_arr.append(np.float(log_age))\n mass_plot_arr.append(np.float(m))\n age_plot_arr, mass_plot_arr = np.array(age_plot_arr), np.array(mass_plot_arr)\n plt.figure()\n plt.scatter(age_plot_arr, mass_plot_arr, marker = 'o')\n plt.xlabel(\"Log Age [$base 10$]\")\n plt.ylabel(\"Mass [$M_{\\odot}$]\")\n plt.title(\"Sythentic Isochrones for Distance = {0} pc\".format(dist_label))\n plt.savefig(\"{0}.{1}.age.mass.pdf\".format(output_dir + target, dist_label))\n return\n\n\ndef PropMotFromRad(radius, obs_year, ps = 0.00993):\n time = 2016 - obs_year\n u = (ps * 1000) * radius / time\n return u\n\n\ndef PropMotFromVel(v, d_lens, d_source):\n \"\"\"\n v [km/s]\n d_lens [kpc]\n d_source [kpc]\n \"\"\"\n v = v * 1000 #conver to m/s\n d_lens = d_lens * 3.08567758 * (10 ** 19) #convert to m\n d_source = d_source * 3.08567758 * (10 ** 19) #convert to m\n u = (v * (d_source - d_lens)) / (d_source * d_lens) #[rad/s]\n u = u * 206264806 #[mas/s]\n u = u * 31536000 #[mas/yr]\n return u #[mas/yr]\n\n\ndef PropMotFromVelArr(v_high, v_low, dist_plot_arr, d_source):\n low_arr = []\n high_arr = []\n for d_lens in dist_plot_arr:\n u_low = PropMotFromVel(v_low, d_lens, d_source)\n low_arr.append(u_low)\n u_high = PropMotFromVel(v_high, d_lens, d_source)\n high_arr.append(u_high)\n low_arr = np.array(low_arr)\n high_arr = np.array(high_arr)\n return low_arr, high_arr\n\n\ndef xNotStar(u, dist, u_plot_arr, dist_plot_arr, u_gap):\n for i in range(len(u_plot_arr)):\n dist_i = dist_plot_arr[i]\n u_i = u_plot_arr[i]\n if (abs(u - u_i) <= u_gap) and (dist == dist_i):\n return False\n return True\n\n\ndef getXs(u_plot_arr, dist_plot_arr, obs_year):\n assert len(u_plot_arr) == len(dist_plot_arr), \"Unequal number of u and dist values!\"\n dist_reduced = np.unique(dist_plot_arr)\n rad_arr = np.arange(2,43)\n u_reduced = PropMotFromRad(rad_arr, obs_year)\n u_gap = (u_reduced[1] - u_reduced[0]) / 2\n u_x = []\n dist_x = []\n for u in u_reduced:\n for dist in dist_reduced:\n if xNotStar(u, dist, u_plot_arr, dist_plot_arr, u_gap) and (u >= PropMotFromRad(5, obs_year)):\n u_x.append(u)\n dist_x.append(dist)\n u_x = np.array(u_x)\n dist_x = np.array(dist_x)\n return u_x, dist_x\n\n\ndef getMasses(target, u_low, u_high, u_plot_arr, dist_plot_arr, mass_plot_arr):\n good_u = []\n good_dist = []\n good_mass = []\n assert len(u_low) == len(u_high)\n assert len(u_high) == len(u_plot_arr)\n assert len(u_plot_arr) == len(dist_plot_arr)\n assert len(dist_plot_arr) == len(mass_plot_arr)\n for i in range(len(u_plot_arr)):\n u_i = u_plot_arr[i]\n u_low_i = u_low[i]\n u_high_i = u_high[i]\n mass_i = mass_plot_arr[i]\n dist_i = dist_plot_arr[i]\n if (u_i <= u_high_i) and (u_i >= u_low_i):\n good_u.append(u_i)\n good_dist.append(dist_i)\n good_mass.append(mass_i)\n good_u = np.array(good_u)\n good_dist = np.array(good_dist)\n good_mass = np.array(good_mass)\n print('{0} Mass Range: {1} - {2} Solar Masses'.format(target, np.min(good_mass), np.max(good_mass)))\n return\n\n\n\n\n\n\n\n\n","sub_path":"ml/isochrone/iso_plot.py","file_name":"iso_plot.py","file_ext":"py","file_size_in_byte":8010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"367280753","text":"# Create your views here.\n# -*- encoding=utf-8 -*-\nimport datetime\nimport hashlib\nimport json\nimport time\nfrom utils import Requests as requests\nimport importlib\nfrom urllib.parse import urljoin\nfrom django.http import JsonResponse, HttpResponseServerError, HttpResponseNotFound, HttpResponseBadRequest\nfrom django_redis import get_redis_connection\nimport logging\nfrom rest_framework.views import APIView\nfrom gateway.tasks import write_log\nfrom .router import routing_table, re_routing_list\n\nlogger = logging.getLogger(__name__)\nMETHOD_MAP = {\n 'get': requests.get,\n 'post': requests.post,\n 'put': requests.put,\n 'patch': requests.patch,\n 'delete': requests.delete\n}\n\nredis_conn = get_redis_connection(\"default\")\n\n\nclass GateWay(APIView):\n # comment this line to open the sign verification\n # authentication_classes = ()\n def __get_subpath(self, path):\n tail_slash = ''\n if path.endswith('/'):\n path = path[:-1]\n tail_slash = '/'\n path, key = path.rsplit('/', maxsplit=1)\n path += '/'\n return path, key, tail_slash\n\n def __load_class(self, class_path):\n pos = class_path.rfind('.')\n module_path = class_path[:pos]\n class_name = class_path[pos + 1:]\n mod = importlib.import_module(module_path)\n cls = getattr(mod, class_name)\n return cls\n\n def __dispatch(self, request):\n if request.method.lower() == 'get':\n data = request.GET\n else:\n data = request.data\n path = request.path.replace('/api', '')\n if not path:\n return HttpResponseNotFound()\n key = None\n path_dict = {}\n tail_slash = ''\n api_path = path\n upstream = ''\n if path in routing_table:\n upstream = routing_table[path]\n else:\n subpath, key, tail_slash = self.__get_subpath(path)\n if subpath in routing_table:\n upstream = routing_table[subpath]\n api_path = subpath\n else:\n for re_obj, call_addr in re_routing_list:\n ret = re_obj.search(path)\n if ret:\n upstream = call_addr\n path_dict = ret.groupdict()\n break\n if not upstream:\n return HttpResponseNotFound()\n\n lpc = ''\n url = ''\n if upstream.startswith('LPC::'):\n lpc = upstream.replace('LPC::', '')\n elif routing_table[path].startswith('URL::'):\n url = upstream.replace('URL::', '')\n if key:\n url = urljoin(url, \"/{0}{1}\".format(key, tail_slash))\n else:\n return HttpResponseServerError()\n\n headers = {\n 'Host': request.META['HTTP_HOST'],\n 'User-Agent': request.META['HTTP_USER_AGENT'],\n 'X-Real-IP': request.META['REMOTE_ADDR'],\n 'Path': api_path,\n 'Dev-Platform': request.META.get('HTTP_DEV_PLATFORM', None),\n 'Dev-Model': request.META.get('HTTP_DEV_MODEL', None),\n 'Dev-Version': request.META.get('HTTP_DEV_VERSION', None),\n 'App-Version': request.META.get('HTTP_APP_VERSION', None),\n 'App-Client': request.META.get('HTTP_APP_CLIENT', None),\n 'App-Id': request.META.get('HTTP_X_AUTH_APPID', None),\n 'Path_Dict': path_dict,\n 'open_id': request.META.get('HTTP_AUTHORIZATION', None),\n 'X-MUMWAY-TRACEID': request.META.get('HTTP_X_MUMWAY_TRACEID', None),\n }\n\n # 请求记录\n if not headers[\"X-MUMWAY-TRACEID\"]:\n headers[\"X-MUMWAY-TRACEID\"] = hashlib.md5(\n str(headers[\"Path\"] + str(time.time())).encode('utf-8')\n ).hexdigest()\n redis_conn.set(\"X-MUMWAY-TRACEID\", headers[\"X-MUMWAY-TRACEID\"])\n\n if 'HTTP_X_AUTH_USERTOKEN' in request.META:\n headers['X-AUTH-USERTOKEN'] = request.META['HTTP_X_AUTH_USERTOKEN']\n for k, v in request.FILES.items():\n request.data.pop(k)\n if request.content_type and request.content_type.lower() == 'application/json':\n headers['Content-Type'] = request.content_type\n\n if lpc:\n need_instance = False\n if lpc.endswith('()'):\n need_instance = True\n lpc = lpc.replace('()', '')\n module = self.__load_class(lpc)\n try:\n logger.info(f'{headers[\"X-MUMWAY-TRACEID\"]} call_method {request.method.lower()} url {request.path} data {data}')\n call_method = request.method.lower()\n if call_method == 'get' and not key:\n call_method = 'list'\n if need_instance:\n method = getattr(module(), call_method)\n else:\n method = getattr(module, call_method)\n except Exception as e:\n logger.error(\n f'{headers[\"X-MUMWAY-TRACEID\"]} 请求失败:\\ncall_method {request.method.lower()}\\n url {request.path} \\n headers {headers} ;\\n data {data} \\n error {e} ')\n return HttpResponseBadRequest()\n try:\n res = method(headers=headers, data=data, files=request.FILES, key=key) or {}\n except Exception as e:\n logger.error('{3} {0} \\n {1} \\n{2}'.format(request.path,\n json.dumps(data, ensure_ascii=False),\n str(e),\n headers[\"X-MUMWAY-TRACEID\"]))\n return JsonResponse(status=200, data={'errcode': 50000, 'data': {}, 'errmsg': f'系统错误:{e}'})\n # 请求日志\n write_log.delay(\n traceid=headers[\"X-MUMWAY-TRACEID\"],\n lower=request.method.lower(),\n path=request.path,\n data=json.dumps(data),\n res=res\n )\n return JsonResponse(data=res, status=200)\n if url:\n return METHOD_MAP[request.method.lower()](url, headers=headers, data=data, files=request.FILES)\n\n def get(self, request):\n return self.__dispatch(request)\n\n def post(self, request):\n return self.__dispatch(request)\n\n def put(self, request):\n return self.__dispatch(request)\n\n def patch(self, request):\n return self.__dispatch(request)\n\n def delete(self, request):\n return self.__dispatch(request)\n","sub_path":"gateway/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":6574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"399784056","text":"import re\nimport numpy as np\n# import matplotlib as plt\nfrom os.path import relpath, abspath, isfile\nfrom os import listdir\n\nimport quiver_engine.timeseries_visualization as tsv\n\ndef save_layer_sig(layer_outputs, layer_name, kernel, temp_folder, input_path):\n\n # Generate filenames\n fn_png = get_output_filename(layer_name, temp_folder, input_path, str(kernel), ext='png')\n\n if not isfile(fn_png):\n # Plot and write timeseries per kernel\n tsv.generate_timeseries_image(np.atleast_2d(layer_outputs), fn_png)\n\n # Return path to layer output arrays\n return relpath(fn_png, abspath(temp_folder))\n\ndef get_output_filename(layer_name, temp_folder, input_path, kernel_index='', ext='png'):\n return '{}/{}_{}_{}.{}'.format(temp_folder, layer_name, input_path[:-4], kernel_index, ext)\n\ndef list_sig_npy_files(input_folder):\n image_regex = re.compile(r'.*\\.(npy)$')\n return [\n filename\n for filename in listdir(\n abspath(input_folder)\n )\n if image_regex.match(filename) is not None\n ]\n\ndef list_sig_png_files(input_folder):\n image_regex = re.compile(r'.*\\.(png)$')\n return [\n filename\n for filename in listdir(\n abspath(input_folder)\n )\n if image_regex.match(filename) is not None\n ]\n","sub_path":"quiver_engine/file_utils.py","file_name":"file_utils.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"441416775","text":"from datetime import datetime\nimport yaml\nimport requests\nimport pendulum\nimport json\nimport re\n\nfrom eventbrite import Eventbrite\n\nimport logging\nlogging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s', filename='EventScheduleAdd.log', level=logging.DEBUG, datefmt='%Y-%m-%d %H:%M:%S')\n\nwith open('config.yaml') as f:\n config = yaml.load(f, Loader=yaml.FullLoader)\n\neventbrite_api_token = config['eventbrite']['api_token']\neventbrite_event_id = config['eventbrite']['event_id']\neventbrite_timezone = config['eventbrite']['event_timezone']\neventbrite_event_time = config['eventbrite']['event_time']\n\nregex_time = \"(?P\\d\\d\\d\\d)-(?P\\d\\d)-(?P\\d\\d)T(?P\\d\\d):(?P\\d\\d):(?P\\d\\d)\"\n\neventbrite = Eventbrite(eventbrite_api_token)\n\nsunday = pendulum.now(eventbrite_timezone).next(pendulum.SUNDAY).at(eventbrite_event_time)\nnext_sunday_utc = sunday.in_tz('UTC')\nnext_sunday_utc = re.search(regex_time, next_sunday_utc.to_iso8601_string())\nnext_sunday_utc_regex = \"{}{}{}T{}{}{}Z\".format(\n next_sunday_utc.group('year'), next_sunday_utc.group('month'), next_sunday_utc.group('day'), next_sunday_utc.group('hour'), next_sunday_utc.group('minutes'), next_sunday_utc.group('seconds'))\nnext_sunday_utc = next_sunday_utc_regex\nlogging.info(next_sunday_utc)\nvalues_dict = {\n \"schedule\": {\n \"occurrence_duration\": 5400,\n \"recurrence_rule\": 'DTSTART:{}\\nRRULE:FREQ=WEEKLY;COUNT=1'.format(next_sunday_utc)\n }\n}\nvalues_json = json.dumps(values_dict, indent=2)\n\nheaders = {\n 'Authorization': 'Bearer {}'.format(eventbrite_api_token),\n 'Content-Type': 'application/json'\n}\n\nrequest = requests.post(\n 'https://www.eventbriteapi.com/v3/events/{}/schedules/'.format(eventbrite_event_id), data=values_json, headers=headers)\n\nlogging.info(request.text)\n","sub_path":"eventbrite-add-schedule.py","file_name":"eventbrite-add-schedule.py","file_ext":"py","file_size_in_byte":1813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"561194395","text":"from flask import send_file, render_template, redirect, url_for\nfrom flask_login import login_required\nimport tempfile\nimport os\nimport csv\nimport datetime\nfrom flask_login import current_user\nfrom sqlalchemy.sql import text\nfrom app import telomere, db\n\nfrom app.model.user import User\nfrom app.forms.export import ExportUserErrorsForm\n\n\n@telomere.route('/exports')\n@login_required\ndef export_index():\n return render_template('export_index.html')\n\n\n@telomere.route('/exports/all_measurements')\n@login_required\ndef export_all_measurements():\n f = tempfile.TemporaryFile()\n\n try:\n write_all_measurements_csv(f)\n\n return _send_csv_to_response(f)\n\n finally:\n f.close\n\n\n@telomere.route('/exports/my_errors')\n@login_required\ndef export_my_errors():\n f = tempfile.TemporaryFile()\n\n try:\n _direct_write_user_errors_csv(f, current_user.id)\n\n return _send_csv_to_response(f)\n\n finally:\n f.close\n\n\n@telomere.route(\"/exports/user_errors\")\n@login_required\ndef export_user_errors():\n form = ExportUserErrorsForm()\n users = User.query.order_by(User.code.asc()).all()\n form.operatorUserId.choices = [(u.id, u.GetCodeAndName()) for u in users]\n\n return render_template('export/user_errors.html', form=form)\n\n\n@telomere.route(\"/exports/user_errors/output/\", methods=['POST'])\n@login_required\ndef export_user_errors_output():\n form = ExportUserErrorsForm()\n users = User.query.order_by(User.code.asc()).all()\n form.operatorUserId.choices = [(u.id, u.GetCodeAndName()) for u in users]\n\n if form.validate_on_submit():\n\n f = tempfile.TemporaryFile()\n\n try:\n _direct_write_user_errors_csv(f, form.operatorUserId.data)\n\n return _send_csv_to_response(f)\n\n finally:\n f.close\n\n return redirect(url_for('export_user_errors'))\n\n\ndef _send_csv_to_response(f):\n f.seek(0)\n response = send_file(\n f,\n as_attachment=True,\n attachment_filename=\"telomere_all_measurements_%s.csv\"\n % datetime.datetime.now().strftime('%Y%M%d%H%m%S'),\n add_etags=False\n )\n f.seek(0, os.SEEK_END)\n size = f.tell()\n f.seek(0)\n response.headers.extend({\n 'Content-Length': size,\n 'Cache-Control': 'no-cache'\n })\n\n return response\n\n\ndef write_all_measurements_csv(outputFile):\n COL_BATCH_CODE = 'BatchId'\n COL_PROCESS_TYPE = 'Process Type'\n COL_ROBOT = 'Robot'\n COL_TEMPERATURE = 'Temperature'\n COL_DATE_PROCESSED = 'DateProcessed'\n COL_UPLOADED_BY = 'Uploaded By'\n COL_PLATE_NAME = 'Plate Name'\n COL_HALF_PLATE = 'Half Plate'\n COL_OPERATOR = 'Operator'\n COL_OPERATOR_CODE = 'Operator Code'\n COL_PRIMER_BATCH = 'Primer Batch'\n COL_ENZYME_BATCH = 'Enzyme Batch'\n COL_ROTOR_GENE = 'Rotor Gene'\n COL_HUMIDITY = 'Humidity'\n COL_SAMPLE_CODE = 'Sample Code'\n COL_ERROR_CODE = 'Error Code'\n COL_T_TO = 't_to'\n COL_T_AMP = 't_amp'\n COL_T = 't'\n COL_S_TO = 's_to'\n COL_S_AMP = 's_amp'\n COL_S = 's'\n COL_TS = 'ts'\n COL_CV = 'CV'\n COL_ERRORLOWT_TO = 'Error Low T_TO'\n COL_ERRORHIGHCV = 'Error High CV'\n COL_ERROR_INVALIDSAMPLECOUNT = 'Error Invalid Sample Count'\n\n fieldnames = [\n COL_BATCH_CODE,\n COL_PROCESS_TYPE,\n COL_ROBOT,\n COL_TEMPERATURE,\n COL_DATE_PROCESSED,\n COL_UPLOADED_BY,\n COL_PLATE_NAME,\n COL_HALF_PLATE,\n COL_OPERATOR,\n COL_OPERATOR_CODE,\n COL_PRIMER_BATCH,\n COL_ENZYME_BATCH,\n COL_ROTOR_GENE,\n COL_HUMIDITY,\n COL_SAMPLE_CODE,\n COL_ERROR_CODE,\n COL_T_TO,\n COL_T_AMP,\n COL_T,\n COL_S_TO,\n COL_S_AMP,\n COL_S,\n COL_TS,\n COL_CV,\n COL_ERRORLOWT_TO,\n COL_ERRORHIGHCV,\n COL_ERROR_INVALIDSAMPLECOUNT\n ]\n\n output = csv.DictWriter(outputFile, fieldnames=fieldnames)\n\n output.writer.writerow(output.fieldnames)\n\n cmd = \"\"\"\n SELECT\n b.id AS batchId\n , b.processType\n , b.robot\n , b.temperature\n , b.datetime\n , u.username\n , b.plateName\n , b.halfPlate\n , o.username AS operator_name\n , o.code AS operator_code\n , b.primerBatch\n , b.enzymeBatch\n , b.rotorGene\n , b.humidity\n , s.sampleCode\n , m.errorCode\n , m.t_to\n , m.t_amp\n , m.t\n , m.s_to\n , m.s_amp\n , m.s\n , m.ts\n , m.coefficientOfVariation\n , m.errorLowT_to\n , m.errorHighCv\n , m.errorInvalidSampleCount\n FROM measurement m\n JOIN batch b ON b.id = m.batchId\n JOIN sample s ON s.id = m.sampleId\n JOIN user u ON u.id = b.userId\n JOIN user o ON o.id = b.operatorUserId\n ;\n \"\"\"\n\n measurements = db.engine.execute(text(cmd))\n for m in measurements:\n output.writerow({\n COL_BATCH_CODE: m[0],\n COL_PROCESS_TYPE: m[1],\n COL_ROBOT: m[2],\n COL_TEMPERATURE: m[3],\n COL_DATE_PROCESSED: m[4],\n COL_UPLOADED_BY: m[5],\n COL_PLATE_NAME: m[6],\n COL_HALF_PLATE: m[7],\n COL_OPERATOR: m[8],\n COL_OPERATOR_CODE: m[9],\n COL_PRIMER_BATCH: m[10],\n COL_ENZYME_BATCH: m[11],\n COL_ROTOR_GENE: m[12],\n COL_HUMIDITY: m[13],\n COL_SAMPLE_CODE: m[14],\n COL_ERROR_CODE: m[15],\n COL_T_TO: m[16],\n COL_T_AMP: m[17],\n COL_T: m[18],\n COL_S_TO: m[19],\n COL_S_AMP: m[20],\n COL_S: m[21],\n COL_TS: m[22],\n COL_CV: m[23],\n COL_ERRORLOWT_TO: m[24],\n COL_ERRORHIGHCV: m[25],\n COL_ERROR_INVALIDSAMPLECOUNT: m[26]\n })\n\n\ndef _write_user_errors_csv(outputFile, user_id):\n COL_SAMPLE_CODE = 'Sample Code'\n COL_PLATE_NAME = 'Plate Name'\n COL_WELL = 'Well'\n COL_CONDITION_DESCRIPTION = 'Condition'\n COL_DNA_TEST = 'DNA Test'\n COL_PICO_TEST = 'PICO Test'\n COL_VOLUME = 'Volume'\n COL_ERROR_CODE = 'Error Code'\n COL_ERRORS = 'Other Errors'\n\n fieldnames = [\n COL_SAMPLE_CODE,\n COL_PLATE_NAME,\n COL_WELL,\n COL_CONDITION_DESCRIPTION,\n COL_DNA_TEST,\n COL_PICO_TEST,\n COL_VOLUME,\n COL_ERROR_CODE,\n COL_ERRORS\n ]\n\n output = csv.DictWriter(\n outputFile,\n fieldnames=fieldnames,\n quoting=csv.QUOTE_NONNUMERIC\n )\n\n output.writer.writerow(output.fieldnames)\n\n cmd = \"\"\"\n SELECT\n s.sampleCode\n , b.plateName\n , sp.well\n , sp.conditionDescription\n , sp.dnaTest\n , sp.picoTest\n , sp.volume\n , MAX(m.errorCode) AS errorCode\n , GROUP_CONCAT(DISTINCT oe.description SEPARATOR '; ') AS errors\n FROM measurement m\n JOIN outstandingError oe ON oe.sampleId = m.sampleId\n AND oe.batchId = m.batchId\n JOIN sample s ON s.id = m.sampleId\n JOIN batch b ON b.id = m.batchId\n LEFT JOIN samplePlate sp ON sp.sampleCode = s.sampleCode\n AND sp.plateName = b.plateName\n WHERE oe.description NOT LIKE 'Validated %'\n AND b.operatorUserId = :userId\n AND m.sampleID NOT IN (\n SELECT sampleId\n FROM measurement\n WHERE\n ( t_to IS NOT NULL\n AND t_amp IS NOT NULL\n AND t IS NOT NULL\n AND s_to IS NOT NULL\n AND s_amp IS NOT NULL\n AND s IS NOT NULL\n AND ts IS NOT NULL\n AND coefficientOfVariation IS NOT NULL\n AND errorLowT_to = 0\n AND errorHighCv = 0\n AND errorInvalidSampleCount = 0\n AND errorCode = ''\n ) OR (\n errorCode IN (8,9)\n )\n )\n GROUP BY\n s.sampleCode\n , b.plateName\n , sp.well\n , sp.conditionDescription\n , sp.dnaTest\n , sp.picoTest\n , sp.volume\n ;\n \"\"\"\n\n measurements = db.engine.execute(text(cmd), userId=user_id)\n for m in measurements:\n output.writerow({\n COL_SAMPLE_CODE: m[0],\n COL_PLATE_NAME: m[1],\n COL_WELL: m[2],\n COL_CONDITION_DESCRIPTION: m[3],\n COL_DNA_TEST: m[4],\n COL_PICO_TEST: m[5],\n COL_VOLUME: m[6],\n COL_ERROR_CODE: m[7],\n COL_ERRORS: m[8]\n })\n\n\ndef _direct_write_user_errors_csv(outputFile, user_id):\n COL_SAMPLE_CODE = 'Sample Code'\n COL_PLATE_NAME = 'Plate Name'\n COL_WELL = 'Well'\n COL_CONDITION_DESCRIPTION = 'Condition'\n COL_DNA_TEST = 'DNA Test'\n COL_PICO_TEST = 'PICO Test'\n COL_VOLUME = 'Volume'\n COL_ERRORS = 'Errors'\n\n fieldnames = [\n COL_SAMPLE_CODE,\n COL_PLATE_NAME,\n COL_WELL,\n COL_CONDITION_DESCRIPTION,\n COL_DNA_TEST,\n COL_PICO_TEST,\n COL_VOLUME,\n COL_ERRORS\n ]\n\n output = csv.DictWriter(\n outputFile,\n fieldnames=fieldnames,\n quoting=csv.QUOTE_NONNUMERIC\n )\n\n output.writer.writerow(output.fieldnames)\n\n cmd = \"\"\"\nSELECT\n sampleCode\n , plateName\n , well\n , conditionDescription\n , dnaTest\n , picoTest\n , volume\n , CONCAT_WS(\"; \",\n CASE WHEN errorCode <> ''\n THEN CONCAT(\"Error code = \", CAST(errorCode AS CHAR))\n ELSE NULL END,\n CASE WHEN errorLowT_to = 1\n THEN \"Low t_to\"\n ELSE NULL END,\n CASE WHEN errorHighCv = 1\n THEN \"High coefficient of variation\"\n ELSE NULL END,\n CASE WHEN errorInvalidSampleCount = 1\n THEN \"Incorrect number of samples in batch\"\n ELSE NULL END,\n CASE WHEN missing_data = 1\n THEN \"Missing data\"\n ELSE NULL END\n ) errors\nFROM (\n SELECT\n s.sampleCode\n , b.plateName\n , sp.well\n , sp.conditionDescription\n , sp.dnaTest\n , sp.picoTest\n , sp.volume\n , MAX(m.errorCode) errorCode\n , MAX(m.errorLowT_to) errorLowT_to\n , MAX(m.errorHighCv) errorHighCv\n , MAX(m.errorInvalidSampleCount) errorInvalidSampleCount\n , MAX(CASE WHEN t_to IS NULL OR\n t_amp IS NULL OR\n t IS NULL OR\n s_to IS NULL OR\n s_amp IS NULL OR\n s IS NULL OR\n ts IS NULL OR\n coefficientOfVariation IS NULL\n THEN 1\n ELSE 0\n END) missing_data\n FROM (\n SELECT s.id AS sampleId, MAX(b.datetime) AS datetime\n FROM sample s\n JOIN measurement m ON m.sampleId = s.id\n JOIN batch b ON b.id = m.batchId\n GROUP BY s.id\n ) mrb\n JOIN measurement m ON m.sampleId = mrb.sampleId\n JOIN batch b ON b.id = m.batchId AND b.datetime = mrb.datetime\n AND b.operatorUserId = :userId\n JOIN sample s ON s.id = m.sampleId\n LEFT JOIN samplePlate sp ON sp.sampleCode = s.sampleCode\n AND sp.plateName = b.plateName\n WHERE (\n errorCode <> ''\n OR t_to IS NULL\n OR t_amp IS NULL\n OR t IS NULL\n OR s_to IS NULL\n OR s_amp IS NULL\n OR s IS NULL\n OR errorLowT_to = 1\n OR errorHighCv = 1\n OR errorInvalidSampleCount = 1\n )\n AND m.sampleID NOT IN (\n SELECT sampleId\n FROM measurement\n WHERE\n ( t_to IS NOT NULL\n AND t_amp IS NOT NULL\n AND t IS NOT NULL\n AND s_to IS NOT NULL\n AND s_amp IS NOT NULL\n AND s IS NOT NULL\n AND ts IS NOT NULL\n AND coefficientOfVariation IS NOT NULL\n AND errorLowT_to = 0\n AND errorHighCv = 0\n AND errorInvalidSampleCount = 0\n AND errorCode = ''\n ) OR (\n errorCode IN (8,9)\n )\n )\n GROUP BY\n s.sampleCode\n , b.plateName\n , sp.well\n , sp.conditionDescription\n , sp.dnaTest\n , sp.picoTest\n , sp.volume\n ) x\n;\n \"\"\"\n\n measurements = db.engine.execute(text(cmd), userId=user_id)\n\n for m in measurements:\n output.writerow({\n COL_SAMPLE_CODE: m[0],\n COL_PLATE_NAME: m[1],\n COL_WELL: m[2],\n COL_CONDITION_DESCRIPTION: m[3],\n COL_DNA_TEST: m[4],\n COL_PICO_TEST: m[5],\n COL_VOLUME: m[6],\n COL_ERRORS: m[7]\n })\n","sub_path":"app/views/export.py","file_name":"export.py","file_ext":"py","file_size_in_byte":13325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"212749565","text":"#-*- coding:utf-8 -*-\nfrom mod_page import page, menu #page framework\nfrom mod_debug_tool import dsp # print list or dict\n\nclass Thoughts(object):\n tmpl_prop = (\n (\"ref\" , \"ref code\"), # set = reg_tbl index\n (\"name\" , \"internal name\"),#internal use name \n (\"stat\" , \"status\"), # refer to stat_lib\n (\"typ\" , [\"ref\"]), #a list of types\n (\"lbl\" , [\"label\"]), #a list of lables\n (\"visit\" , 0), # count visit frequency\n (\"count\" , 0), # count presence \n (\"ttl\" , \"title\"), #usr-display name\n (\"abs\" , \"abstract\"),\n (\"cont\" , \"main content\"),\n (\"url\" , [\"url\"]), #a list of urls\n (\"ext\" , [None]), #a list of undefined extension\n )#tuple as template\n \n \n net = [[None],[None],[None]] # [0]parent, [1]child, [2]related \n\n \n #only three states allowed\n net_lib = {0:\"parent\", 1:\"child\", 2:\"relate\", None:\"idle\"}\n # stat refer to the \"hot\" degree, facilitate \n stat_lib = {\n 0:\"focus\", 1:\"active1\", 2:\"active2\",\n 3:\"active3\", \"f\":\"forgot\", \"d\":\"deleted\"\n }\n \n #database\n \"\"\"store ref and internal name\n \"\"\"\n reg_tbl = [] #database of Thoughts elm: \n reg_tbl_itr = 0\n\n \n def __init__(self, *arg, **kwarg):\n self.prop = dict(Thoughts.tmpl_prop) #innitialize properties\n self.ref = 0 # self.prop[\"ref\"] = self.ref = reg_tbl.index\n \n #methods\n def new_empty_tht(self):\n \"\"\"create mew empty tht\n \n assume idle relation, no name, only add to database \n \"\"\"\n #reg new_tht [ref, stat, name]\n tmp = Thoughts() #create a new incidence\n tmp.ref = len(Thoughts.reg_tbl) #make ref = index after regist\n tmp.stat = 0 #default status = focus\n tmp.name = \"New Thought\"\n tmp.addr = tmp #record address \n Thoughts.reg_tbl.append([tmp.ref, tmp.stat, tmp.name, tmp.addr])\n return tmp #only address of tmp incidence\n \n \n def edit_tht(self):\n \"\"\"edit thought\n \n mode limited in net_lib\n \"\"\"\n #display thought\n self.dsp_opt()\n \n #loop editing\n #list editable options\n \n #choose option to edit\n \n #confirm overwrite\n \n return \n\n def edit_net(self):\n \"\"\"edit network of thought\n \n \n \"\"\"\n #display thought net\n\n self.dsp_opt()\n \n #loop editing\n #list editable options\n \n #choose option to edit\n \n #confirm overwrite\n \n return \n \n \n def dsp_opt(self, mode=\"admin\"):\n \"\"\"display option for each modes\n \n modes: admin, user, read \n admin --> full right\n user --> partial right\n read --> for map display\n \n output: \n \"\"\"\n #build full list of Thoughts.prop\n tmp = []\n for elm in Thoughts.tmpl_prop:\n tmp.append(elm[0])\n \n #\"admin\" mode --> full list\n adm_dsp = tmp[:] \n \n #\"usr\" mode --> partial list normal editing\n usr_dsp = []\n for i in (3,4,7,8,9,10): \n usr_dsp.append(adm_dsp[i])\n \n #\"read\" mode --> concise list read-only\n read_dsp = []\n for i in (7,8): \n read_dsp.append(adm_dsp[i])\n \n #display mode key book\n dsp_opt = {\"admin\":adm_dsp,\"usr\":usr_dsp,\"read\":read_dsp}\n \n return dsp_opt[mode] # for display\n \n def dsp_tht(self, opt):\n \"\"\"display tht list with format\n \n modes\n \"\"\"\n pass\n \n \nclass Relations(Thoughts):\n\n def __init__(self, *arg, **kwarg):\n self.prop = dict(Thoughts.tmpl_prop) #innitialize properties\n self.ref = self.prop[\"ref\"] # easy access to self.prop[\"ref\"]\n\nclass Types(Thoughts):\n \n def __init__(self, *arg, **kwarg):\n self.prop = dict(Thoughts.tmpl_prop) #innitialize properties\n self.ref = self.prop[\"ref\"] # easy access to self.prop[\"ref\"]\n\nclass Labels(Thoughts):\n\n def __init__(self, *arg, **kwarg):\n self.prop = dict(Thoughts.tmpl_prop) #innitialize properties\n self.ref = self.prop[\"ref\"] # easy access to self.prop[\"ref\"]\n\n#abbr\nregtb = Thoughts().reg_tbl\ntmpl = Thoughts().tmpl_prop\nnew = Thoughts().new_empty_tht\n\n#generate n empty thoughts\ndef news (n=10):\n a=[]\n for i in range(n):\n a.append(new())\n return a\n#show dsp_opt output list\ndef dspa(x):\n dsp(x.dsp_opt(\"admin\"))\ndef dspu(x):\n dsp(x.dsp_opt(\"usr\"))\ndef dspr(x):\n dsp(x.dsp_opt(\"read\"))\n#main\n\na = new() #new incidence\nb = new()\ns = news(10)\n\n\ndsp(regtb)\n#page().pg_exit()\n\n\n","sub_path":"mindmap.py","file_name":"mindmap.py","file_ext":"py","file_size_in_byte":4836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"418464742","text":"import logging\nfrom bottle import response, Bottle\nfrom backend import NumberFormatException\n\nlogger = logging.getLogger(__name__)\n\nclass BackendRest:\n def __init__(self, backend):\n self.backend = backend\n self.app = Bottle()\n self.app.route('/dial//', callback=self.dial)\n self.app.route('/kill/', callback=self.kill)\n\n def run(self, host='0.0.0.0', port=8080):\n self.app.run(host=host, port=port)\n\n def dial(self, number_a, number_b):\n try:\n return self.backend.verify_and_dial([number_a, number_b])\n except NumberFormatException:\n response.status = 400\n return 'Invalid number'\n except Exception:\n logger.exception('Exception in dial {} {}'.format(number_a, number_b))\n response.status = 500\n return 'Internal error'\n\n def kill(self, conference_id):\n try:\n return self.backend.kill_conference(conference_id)\n except NumberFormatException:\n response.status = 400\n return 'Invalid conference ID'\n except Exception:\n logger.exception('Exception in kill {}'.format(conference_id))\n response.status = 500\n return 'Internal error'\n","sub_path":"phone-backend/backend_rest.py","file_name":"backend_rest.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"529521945","text":"import argparse\n\nfrom .dask import (DEFAULT_MAXIMUM_WORKERS, DEFAULT_MEMORY,\n DEFAULT_MINIMUM_WORKERS, DEFAULT_NUM_CORES, DEFAULT_QUEUE,\n dask_slurm_cluster)\n\n\ndef run_cluster():\n description = 'Run a Dask Slurm cluster'\n parser = argparse.ArgumentParser(description=description)\n parser.add_argument('-q', '--queue', dest='queue',\n default=DEFAULT_QUEUE, type=str,\n help=(f'the Slurm queue to submit to. '\n f'Default: {DEFAULT_QUEUE}'))\n parser.add_argument('-c', '--cores', dest='cores', type=int,\n default=DEFAULT_NUM_CORES,\n help=(f'the number of cores to use per job. '\n f'Default: {DEFAULT_NUM_CORES}'))\n parser.add_argument('-m', '--memory', dest='memory', type=str,\n default=DEFAULT_MEMORY,\n help=(f'the amount of memory to use per job. '\n f'Default: {DEFAULT_MEMORY}'))\n parser.add_argument('--minimum-workers', dest='minimum_workers', type=int,\n default=DEFAULT_MINIMUM_WORKERS,\n help=(f'the minimum number of workers to scale the '\n f'cluster down to in the autoscale mode. '\n f'Default: {DEFAULT_MINIMUM_WORKERS}'))\n parser.add_argument('--maximum-workers',\n dest='maximum_workers', type=int,\n default=DEFAULT_MAXIMUM_WORKERS,\n help=(f'the maximum number of workers to scale the '\n f'cluster up to in the autoscale mode. '\n f'Default: {DEFAULT_MAXIMUM_WORKERS}'))\n\n args = parser.parse_args()\n cluster = dask_slurm_cluster(**args.__dict__)\n return cluster\n\n\nif __name__ == '__main__':\n cluster = run_cluster()\n","sub_path":"atsas_pipelines/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":1947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"223211466","text":"import tensorflow as tf\nfrom util import logic_regularizer\nfrom util import blocks\n\nclass MyModel(object):\n def __init__(self, seq_length, emb_dim, hidden_dim, embeddings, emb_train):\n ## Define hyperparameters\n self.embedding_dim = emb_dim\n self.dim = hidden_dim\n self.sequence_length = seq_length \n\n ## Define the placeholders\n self.premise_x = tf.placeholder(tf.int32, [None, self.sequence_length])\n self.hypothesis_x = tf.placeholder(tf.int32, [None, self.sequence_length])\n self.y = tf.placeholder(tf.int32, [None])\n self.keep_rate_ph = tf.placeholder(tf.float32, [])\n self.pi = tf.placeholder(tf.float32, None)\n\n ## Define parameters\n # self.E = tf.Variable(embeddings, trainable=emb_train)\n\n with tf.device('/cpu:0'):\n self.E = tf.Variable(tf.random_uniform(embeddings.shape, -1.0,1.0),\n trainable=emb_train, name=\"W\")\n self.embedding_placeholder = tf.placeholder(tf.float32, embeddings.shape)\n self.embedding_init = self.E.assign(self.embedding_placeholder)\n \n self.W_mlp = tf.Variable(tf.random_normal([self.dim * 8, self.dim], stddev=0.1))\n self.b_mlp = tf.Variable(tf.random_normal([self.dim], stddev=0.1))\n\n self.W_cl = tf.Variable(tf.random_normal([self.dim, 3], stddev=0.1))\n self.b_cl = tf.Variable(tf.random_normal([3], stddev=0.1))\n \n ## Function for embedding lookup and dropout at embedding layer\n def emb_drop(x):\n emb = tf.nn.embedding_lookup(self.E, x)\n emb_drop = tf.nn.dropout(emb, self.keep_rate_ph)\n return emb_drop\n\n def multiplicative_attention(query, hidden, sizes, hidden_dim, max_size, namespace, reuse):\n with tf.variable_scope('attention_' + namespace, reuse=reuse):\n att_w = tf.get_variable(\"weight\", shape=[hidden_dim, hidden_dim], \n dtype=tf.float32)\n A = tf.matmul(query, att_w)\n B = tf.matmul(hidden, tf.expand_dims(A, 2))\n B = tf.squeeze(B)\n\n mask = tf.sequence_mask(sizes, max_size, dtype=tf.float32)\n exp_B = tf.exp(B)*mask\n denominator = tf.reduce_sum(exp_B, axis=1)\n softmax = tf.div(exp_B, tf.expand_dims(denominator, 1))\n weight_sum = tf.reduce_sum(tf.multiply(hidden, \n tf.expand_dims(softmax, 2)), axis=1)\n return weight_sum, softmax\n \n\n def network(premise, hypothesis, reuse=False):\n # Get lengths of unpadded sentences\n prem_seq_lengths, prem_mask = blocks.length(premise)\n hyp_seq_lengths, hyp_mask = blocks.length(hypothesis)\n\n ### BiLSTM layer ###\n premise_in = emb_drop(premise)\n hypothesis_in = emb_drop(hypothesis)\n\n premise_outs, c1 = blocks.biLSTM(premise_in, dim=self.dim, seq_len=prem_seq_lengths, name='premise',\n reuse=reuse)\n hypothesis_outs, c2 = blocks.biLSTM(hypothesis_in, dim=self.dim, seq_len=hyp_seq_lengths, name='hypothesis',\n reuse=reuse)\n\n premise_bi = tf.concat(premise_outs, axis=2)\n hypothesis_bi = tf.concat(hypothesis_outs, axis=2)\n\n #premise_final = blocks.last_output(premise_bi, prem_seq_lengths)\n #hypothesis_final = blocks.last_output(hypothesis_bi, hyp_seq_lengths)\n\n ### Mean pooling\n premise_sum = tf.reduce_sum(premise_bi, 1)\n premise_ave_old = tf.div(premise_sum, tf.expand_dims(tf.cast(prem_seq_lengths, tf.float32), -1))\n\n hypothesis_sum = tf.reduce_sum(hypothesis_bi, 1)\n hypothesis_ave_old = tf.div(hypothesis_sum, tf.expand_dims(tf.cast(hyp_seq_lengths, tf.float32), -1))\n \n # premise_ave, _ = multiplicative_attention(hypothesis_ave_old, premise_bi, \n # prem_seq_lengths, self.dim*2, \n # self.sequence_length, \"premise\", reuse=reuse)\n\n # hypothesis_ave, _ = multiplicative_attention(premise_ave_old, hypothesis_bi, \n # hyp_seq_lengths, self.dim*2, \n # self.sequence_length, \"hypothesis\", reuse=reuse)\n\n premise_ave = premise_ave_old\n hypothesis_ave = hypothesis_ave_old\n\n ### Mou et al. concat layer ###\n diff = tf.subtract(premise_ave, hypothesis_ave)\n mul = tf.multiply(premise_ave, hypothesis_ave)\n h = tf.concat([premise_ave, hypothesis_ave, diff, mul], 1)\n\n # MLP layer\n h_mlp = tf.nn.relu(tf.matmul(h, self.W_mlp) + self.b_mlp)\n # Dropout applied to classifier\n h_drop = tf.nn.dropout(h_mlp, self.keep_rate_ph)\n\n # Get prediction\n return tf.matmul(h_drop, self.W_cl) + self.b_cl\n\n self.logits = network(self.premise_x, self.hypothesis_x)\n self.reversed_logits = network(self.hypothesis_x, self.premise_x, reuse=True)\n\n self.original_probs = tf.nn.softmax(self.logits)\n self.reverse_probs = tf.nn.softmax(self.reversed_logits)\n\n # semi supervised draft\n\n # supervised_idx = tf.not_equal(self.y, tf.constant(-1))\n #\n # supervised_logits = tf.boolean_mask(self.logits, supervised_idx)\n # supervised_y = tf.boolean_mask(self.y, supervised_idx)\n # total_supervision = tf.reduce_sum(tf.cast(supervised_idx, dtype=tf.float32))\n #\n # self.total_cost = tf.cond(tf.greater_equal(total_supervision, tf.constant(1.0)),\n # lambda: tf.reduce_sum(tf.nn.sparse_softmax_cross_entropy_with_logits(\n # labels=supervised_y, logits=supervised_logits)) / total_supervision,\n # lambda: tf.constant(0.0))\n\n # Define the cost function\n self.total_cost = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(\n labels=self.y, logits=self.logits))\n\n self.inference_value = tf.reduce_mean(logic_regularizer.fuzzy_inference(self.original_probs,\n self.reverse_probs))\n self.neutral_value = tf.reduce_mean(logic_regularizer.fuzzy_neutral(self.original_probs,\n self.reverse_probs))\n self.contradiction_value = tf.reduce_mean(logic_regularizer.semantic_contradiction(self.original_probs,\n self.reverse_probs))\n\n #self.only_one_original_value = tf.reduce_mean(logic_regularizer.semantic_only_one(self.original_probs))\n #self.only_one_reversed_value = tf.reduce_mean(logic_regularizer.semantic_only_one(self.reverse_probs))\n\n self.regularized_loss = self.total_cost + self.pi * (self.inference_value + self.contradiction_value + self.neutral_value)/3.0\n #self.regularized_loss = self.inference_value + self.contradiction_value + self.neutral_value\n","sub_path":"python/models/bilstm.py","file_name":"bilstm.py","file_ext":"py","file_size_in_byte":7378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"107720772","text":"import discord\r\nimport sys\r\nimport asyncio\r\n\r\nimport ffmpy\r\n################################################################################\r\n# sound\r\n################################################################################\r\nasync def sound (bot,ctx,data):\r\n\r\n if ctx.message.author.voice == None:\r\n await ctx.channel.send(\"Heeey.. You are not in a vocal chaan !!\")\r\n return\r\n\r\n\r\n if (len(ctx.message.content.split()) <= 1 ):\r\n await ctx.channel.send(\"Baaakkaaaa ! You forgot to mention the name of the sound !\")\r\n return\r\n\r\n if (ctx.message.content.split()[1] in data.soundList) == False:\r\n await ctx.channel.send(\"Eh ? I did not find \"+ctx.message.content.split()[1]+ \" !!\")\r\n return\r\n\r\n #for voiceClient in client.voice_clients:\r\n # if voiceClient.is_connected():\r\n # voiceClient.disconnect()\r\n\r\n chan = ctx.message.author.voice.channel\r\n vc = await chan.connect()\r\n vc.play(discord.FFmpegPCMAudio(data.path+\"data/sounds/\"+data.soundList[ctx.message.content.split()[1]]))\r\n vc.source = discord.PCMVolumeTransformer(vc.source,data.voiceVolume)\r\n #voiceClient = await client.join_voice_channel(chan)\r\n #soundPlayer = voiceClient.create_ffmpeg_player(data.path+\"data/sounds/\"+data.soundList[message.content.split()[1]],use_avconv=False)\r\n #soundPlayer.volume = data.voiceVolume\r\n #soundPlayer.start()\r\n\r\n #if soundPlayer.is_done():\r\n #await asyncio.sleep(10)\r\n if vc.is_playing == False:\r\n print(\"vc disco yes\")\r\n await vc.disconnect()\r\n return\r\n await asyncio.sleep(10)\r\n await vc.disconnect()\r\n","sub_path":"modules/sound.py","file_name":"sound.py","file_ext":"py","file_size_in_byte":1636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"361568564","text":"from flask import Flask, render_template, jsonify, request\nfrom flask.ext.api import status\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy.inspection import inspect\nfrom flask_cors import CORS, cross_origin\nimport json\n\nimport smtplib\nfrom email.mime.multipart import MIMEMultipart\n#from email.MIMEMultipart import MIMEMultipart\nfrom email.mime.text import MIMEText\n\napp = Flask(__name__)\nCORS(app)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:root@localhost/student_app_db'\ndb = SQLAlchemy(app)\n\nresponse_error = {'status': 'failure'}\n\n\nclass Serializer(object):\n\n def serialize(self):\n return {c: getattr(self, c) for c in inspect(self).attrs.keys()}\n\n @staticmethod\n def serialize_list(l):\n return [m.serialize() for m in l]\n\n\nclass Student(db.Model, Serializer):\n student_id = db.Column(db.Integer, primary_key=True)\n student_first_name = db.Column(db.String(45))\n student_last_name = db.Column(db.String(45))\n student_department = db.Column(db.String(45))\n student_regno = db.Column(db.String(45))\n student_email = db.Column(db.String(45))\n student_gender = db.Column(db.String(45))\n\n def __init__(self, student_first_name, student_last_name, student_department, student_regno, student_email, student_gender):\n self.student_first_name = student_first_name\n self.student_last_name = student_last_name\n self.student_department = student_department\n self.student_regno = student_regno\n self.student_email = student_email\n self.student_gender = student_gender\n\n def serialize(self):\n d = Serializer.serialize(self)\n return d\n\n\nclass Teacher(db.Model, Serializer):\n teacher_id = db.Column(db.Integer, primary_key=True)\n teacher_first_name = db.Column(db.String(45))\n teacher_last_name = db.Column(db.String(45))\n email = db.Column(db.String(45))\n\n def __init__(self, teacher_first_name, teacher_last_name, email):\n self.teacher_first_name = teacher_first_name\n self.teacher_last_name = teacher_last_name\n self.email = email\n\n def serialize(self):\n d = Serializer.serialize(self)\n return d\n\n\nclass User(db.Model, Serializer):\n user_id = db.Column(db.Integer, primary_key=True)\n email = db.Column(db.String(45))\n password = db.Column(db.String(45))\n role_name = db.Column(db.String(45))\n\n def __init__(self, email, password, role_name):\n self.email = email\n self.password = password\n self.role_name = role_name\n\n def serialize(self):\n d = Serializer.serialize(self)\n del d['password']\n return d\n\n\nclass Student_marks(db.Model, Serializer):\n id = db.Column(db.Integer, primary_key=True)\n student_id = db.Column(db.Integer)\n subject_code = db.Column(db.String(45))\n subject_name = db.Column(db.String(45))\n subject_marks = db.Column(db.Integer)\n semester = db.Column(db.Integer)\n\n def __init__(self, student_id, subject_code, subject_name, subject_marks, semester):\n self.student_id = student_id\n self.subject_code = subject_code\n self.subject_name = subject_name\n self.subject_marks = subject_marks\n self.semester = semester\n\n def serialize(self):\n d = Serializer.serialize(self)\n del d['id']\n del d['semester']\n return d\n\n\nclass Student_questions(db.Model, Serializer):\n question_id = db.Column(db.Integer, primary_key=True)\n question_description = db.Column(db.String(250))\n\n def __init__(self, question_id, question_description):\n self.question_id = question_id\n self.question_description = question_description\n\n def serialize(self):\n d = Serializer.serialize(self)\n return d\n\n\nclass Teacher_questions(db.Model, Serializer):\n question_id = db.Column(db.Integer, primary_key=True)\n question_description = db.Column(db.String(250))\n\n def __init__(self, question_id, question_description):\n self.question_id = question_id\n self.question_description = question_description\n\n def serialize(self):\n d = Serializer.serialize(self)\n return d\n\n\nclass Student_answers(db.Model, Serializer):\n id = db.Column(db.Integer, primary_key=True)\n student_id = db.Column(db.Integer)\n question_id = db.Column(db.Integer)\n question_answer = db.Column(db.String(45))\n question_description = db.Column(db.String(250))\n\n def __init__(self, student_id, question_id, question_description):\n self.student_id = student_id\n self.question_id = question_id\n self.question_description = question_description\n\n def serialize(self):\n d = Serializer.serialize(self)\n return d\n\n\nclass Teacher_answers(db.Model, Serializer):\n id = db.Column(db.Integer, primary_key=True)\n teacher_id = db.Column(db.Integer)\n student_id = db.Column(db.Integer)\n question_id = db.Column(db.Integer)\n question_answer = db.Column(db.String(45))\n question_description = db.Column(db.String(250))\n\n def __init__(self, teacher_id, student_id, question_id, question_description):\n self.teacher_id = teacher_id\n self.student_id = student_id\n self.question_id = question_id\n self.question_description = question_description\n\n def serialize(self):\n d = Serializer.serialize(self)\n return d\n\n\n@app.route('/')\ndef home():\n return render_template('home.html')\n\n\n@app.route('/about')\ndef about():\n return render_template('about.html')\n\n\n@app.route('/student/all')\ndef getAllStudents():\n students = Student.query.order_by(Student.student_first_name).all()\n students = Student.serialize_list(students)\n for i in range(0, len(students)):\n semester = Student_marks.query.filter_by(\n student_id=students[i]['student_id'], semester=1).all()\n semester = Student_marks.serialize_list(semester)\n students[i]['student_marks'] = semester\n\n return jsonify(students)\n\n\n@app.route('/student/')\ndef getStudent(student_id):\n student = Student.query.get(student_id)\n response = student.serialize()\n return jsonify(response)\n\n\n@app.route('/student/add', methods=['POST'])\ndef postStudent():\n requestJson = request.json\n student = Student(requestJson['student_first_name'], requestJson['student_last_name'],\n requestJson['student_department'], requestJson['student_regno'])\n db.session.add(student)\n db.session.commit()\n\n return jsonify({'status': 'success'})\n\n\n@app.route('/student/delete/', methods=['DELETE'])\ndef deleteStudent(student_id):\n student = Student.query.get(student_id)\n db.session.delete(student)\n db.session.commit()\n return jsonify({'status': 'success'})\n\n\n@app.route('/status')\ndef getStatus():\n # response.headers['Content-Type'] = 'application/json'\n return jsonify({'status': 'service working'})\n\n\n@app.route('/user/login', methods=['POST'])\ndef loginStudent():\n\n email = request.json['email']\n password = request.json['password']\n student = User.query.filter_by(\n email=email, password=password).first()\n\n if student:\n response = student.serialize()\n return jsonify(response)\n\n response_error['message'] = \"user does not exist\"\n return jsonify(response_error), status.HTTP_404_NOT_FOUND\n\n\n@app.route('/student/marks/')\ndef getStudentMarks(student_id):\n length = 2\n response = list()\n for i in range(0, length):\n semester = Student_marks.query.filter_by(\n student_id=student_id, semester=i+1).all()\n serializedSemester = Student.serialize_list(semester)\n response.append({\n \"semester\": i+1,\n \"semester_details\": serializedSemester\n })\n\n return jsonify(response)\n\n\n@app.route('/student/questions/all')\ndef getAllQuestions():\n questions = Questions.query.all()\n response = Questions.serialize_list(questions)\n return jsonify(response)\n\n\n@app.route('/student/questions/populate')\ndef populateQuestions():\n students = Student.query.order_by(Student.student_first_name).all()\n students = Student.serialize_list(students)\n questions = Student_questions.query.all()\n questions = Student_questions.serialize_list(questions)\n\n for i in range(0, len(students)):\n for j in range(0, len(questions)):\n student = Student_answers(\n students[i]['student_id'], questions[j]['question_id'], questions[j]['question_description'])\n db.session.add(student)\n db.session.commit()\n\n return jsonify({'status': 'success'})\n\n\n@app.route('/teacher/questions/populate')\ndef populateTeacherQuestions():\n teachers = Teacher.query.order_by(Teacher.teacher_first_name).all()\n teachers = Teacher.serialize_list(teachers)\n students = Student.query.order_by(Student.student_first_name).all()\n students = Student.serialize_list(students)\n questions = Teacher_questions.query.all()\n questions = Teacher_questions.serialize_list(questions)\n\n for i in range(0, len(teachers)):\n for j in range(0, len(students)):\n for k in range(0, len(questions)):\n teacher = Teacher_answers(teachers[i]['teacher_id'],\n students[j]['student_id'], questions[k]['question_id'], questions[k]['question_description'])\n db.session.add(teacher)\n db.session.commit()\n\n return jsonify({'status': 'success'})\n\n\n@app.route('/student/questions/')\ndef getStudentQuestions(student_id):\n answers = Student_answers.query.filter_by(student_id=student_id).all()\n response = Student_answers.serialize_list(answers)\n return jsonify(response)\n\n\n@app.route('/teacher/questions/')\ndef getTeacherQuestions(teacher_id):\n student_id = request.args.get('student')\n answers = Teacher_answers.query.filter_by(\n teacher_id=teacher_id, student_id=student_id).all()\n response = Teacher_answers.serialize_list(answers)\n return jsonify(response)\n\n\n@app.route('/student/questions/save', methods=['POST'])\ndef saveStudentAnswer():\n requestJson = request.json\n student_id = requestJson['student_id']\n question_id = requestJson['question_id']\n question_answer = requestJson['question_answer']\n student = Student_answers.query.filter_by(\n student_id=student_id, question_id=question_id).first()\n student.question_answer = question_answer\n db.session.commit()\n return jsonify({'status': 'success'})\n\n\n@app.route('/teacher/questions/save', methods=['POST'])\ndef saveTeacherAnswer():\n requestJson = request.json\n teacher_id = requestJson['teacher_id']\n student_id = requestJson['student_id']\n question_id = requestJson['question_id']\n question_answer = requestJson['question_answer']\n teacher = Teacher_answers.query.filter_by(teacher_id=teacher_id,\n student_id=student_id, question_id=question_id).first()\n teacher.question_answer = question_answer\n db.session.commit()\n return jsonify({'status': 'success'})\n\n\n@app.route('/mail', methods=['POST'])\ndef sendMail():\n requestJson = request.json\n subject = 'Predictive Analysis report from Prophet AI'\n message = requestJson['message']\n recipient_email = requestJson['recipient_email']\n\n msg = MIMEMultipart()\n msg['Subject'] = subject\n message = message\n msg.attach(MIMEText(message))\n\n mailserver = smtplib.SMTP('smtp.gmail.com', 587)\n\n # identify ourselves to smtp gmail client\n mailserver.ehlo()\n # secure our email with tls encryption\n mailserver.starttls()\n # re-identify ourselves as an encrypted connection\n mailserver.ehlo()\n mailserver.login('prophetai.system@gmail.com', 'hackathonhackers')\n mailserver.sendmail('prophetai.system@gmail.com',\n recipient_email, msg.as_string())\n return jsonify({'status': 'success'})\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', debug=True)\n","sub_path":"student-app-backend-development/flaskapp/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":12009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"424702859","text":"import random\n\n\nclass Card():\n\n def __init__(self, suite, name, rank):\n self.suite = suite\n self.name = name\n self.rank = rank\n\n\nclass Deck():\n\n def __init__(self):\n self.cards = []\n\n def addcard(self, card):\n self.cards.append(card)\n\n def delete_card(self, card):\n self.cards.remove(card)\n\n\nclass Dealer():\n\n def __init__(self, deck, bank):\n self.deck_on_hand = deck\n self.bank = bank\n\n def change_bank(self, m_operator, value):\n if m_operator == '+':\n self.bank += value\n elif m_operator == '-':\n self.bank -= value\n\n def collected_points(self):\n player_cards = self.deck_on_hand.cards\n points = 0\n for each in player_cards:\n points += each.rank\n\n return (points, points - 10)\n\n\nclass Player(Dealer):\n\n def __init__(self, deck, bank):\n Dealer.__init__(self, deck, bank)\n self.first_turn = True\n\n\ndef put_cards_in_deck():\n game_deck.cards.clear()\n for card_t in card_suits:\n for card_v in card_values.items():\n c = Card(card_t, card_v[0], card_v[1])\n game_deck.addcard(c)\n\n\ndef get_card(player_cards, show=True):\n random_card = random.choice(game_deck.cards)\n player_cards.append(random_card)\n game_deck.delete_card(random_card)\n\n if show:\n show_cards(player_cards)\n\n\ndef ask_user(message, answers):\n answers_up = [a.upper() for a in answers]\n while True:\n a = input(message).upper()\n if a not in answers_up:\n continue\n else:\n break\n\n return a\n\n\ndef show_cards(cards):\n for each in cards:\n print(each.name + ' <=> ' + each.suite)\n\n\ndef user_turn():\n\n next_card = False\n play_again = False\n dealer_turn = False\n\n player_points = _player.collected_points()\n player_cards = _player.deck_on_hand.cards\n\n if player_points[0] == 21 or player_points[1] == 21:\n pot_win = pot_size * 0.01\n _dealer.change_bank('-', pot_win)\n _player.change_bank('+', pot_win)\n print('P:{}$ D:{}$'.format(_player.bank, _dealer.bank))\n\n print(\"You've won the Game and earn {}$\".format(_player.bank))\n answer = ask_user('Would you like to paly again? ', ('y', 'n'))\n\n if answer == 'Y':\n play_again = True\n\n elif player_points[0] > 21 or player_points[1] > 21:\n pot_win = pot_size * 0.01\n _dealer.change_bank('+', pot_win)\n _player.change_bank('-', pot_win)\n print('P:{}$ D:{}$'.format(_player.bank, _dealer.bank))\n\n print(\"You've lost the Game!\")\n answer = ask_user('Would you like to paly again? ', ('y', 'n'))\n\n if answer == 'Y':\n play_again = True\n\n elif player_points[0] > 21 and player_points[1] < 21:\n answer = ask_user('Would you like to receive a card (your Ace now going to have a rank equal 1)? ', ('y', 'n'))\n\n if answer == 'Y':\n next_card = True\n\n else:\n answer = ask_user('Would you like to receive a card? ', ('y', 'n'))\n\n if answer == 'Y':\n next_card = True\n else:\n dealer_turn = True\n\n if next_card:\n get_card(player_cards)\n\n return {'next_card': next_card,\n 'dealer_turn': dealer_turn,\n 'play_again': play_again}\n\n\ndef dealer_turn():\n\n next_card = False\n play_again = False\n dealer_turn = False\n\n dealer_cards = _dealer.deck_on_hand.cards\n\n while True:\n get_card(dealer_cards, False)\n dealer_points = _dealer.collected_points()\n\n if dealer_points[0] == 21 or dealer_points[1] == 21:\n pot_win = pot_size * 0.01\n _dealer.change_bank('+', pot_win)\n _player.change_bank('-', pot_win)\n print('P:{}$ D:{}$'.format(_player.bank, _dealer.bank))\n\n print(\"Dealer has won the Game and earn {}$\".format(_dealer.bank))\n answer = ask_user('Would you like to paly again? ', ('y', 'n'))\n\n if answer == 'Y':\n play_again = True\n\n break\n\n elif dealer_points[0] > 21 or dealer_points[1] > 21:\n pot_win = pot_size * 0.01\n _dealer.change_bank('-', pot_win)\n _player.change_bank('+', pot_win)\n print('P:{}$ D:{}$'.format(_player.bank, _dealer.bank))\n\n print(\"Dealer has lost the Game and earn {}$\".format(_dealer.bank))\n answer = ask_user('Would you like to paly again? ', ('y', 'n'))\n\n if answer == 'Y':\n play_again = True\n\n break\n\n return {'next_card': next_card,\n 'dealer_turn': dealer_turn,\n 'play_again': play_again}\n\n\ndef prepare_players():\n _player.deck_on_hand.cards.clear()\n _dealer.deck_on_hand.cards.clear()\n\n\ndef gameplay():\n\n # User goes first\n result = user_turn()\n while True:\n\n # result = user_turn()\n\n if result['dealer_turn']:\n result = dealer_turn()\n elif result['next_card']:\n result = user_turn()\n elif result['play_again']:\n prepare_players()\n put_cards_in_deck()\n result = user_turn()\n else:\n break\n\n\n# ### Main Program ### #\n\ncard_suits = ('clubs', 'diamonds', 'hearts', 'spades')\ncard_values = {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8,\n '9': 9, '10': 10, 'J': 10, 'Q': 10, 'K': 10, 'A': 11}\n\npot_size = 100\n\ngame_deck = Deck()\nuser_deck = Deck()\ndealer_deck = Deck()\n\nput_cards_in_deck()\n\nplayer_name = input('Type your name here ::: ')\nprint('Hi', player_name)\nplayer_cash = int(input('How much money do you have? :) ::: '))\nprint('Ok, let\\'s go')\n\n_player = Player(user_deck, player_cash)\n_dealer = Dealer(dealer_deck, pot_size)\n\ngameplay()\n","sub_path":"BlackJackLite.py","file_name":"BlackJackLite.py","file_ext":"py","file_size_in_byte":5788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"28643968","text":"import paho.mqtt.client as mqtt\nfrom datetime import datetime\nfrom kafka import KafkaProducer\n\n\ndef on_connect(client, userdata, flags, rc):\n print(\"MQTT conectado. Cod: \" + str(rc))\n client.subscribe(\"/ibti/kafkaout\")\n\ndef on_message(client, userdata, msg):\n message = ''\n message = str(msg.payload.decode(\"utf-8\"))\n print(message)\n print(\"####\")\n producer = KafkaProducer(bootstrap_servers='localhost:9092')\n producer.send('ibti', bytes(message, 'utf-8'))\n\nclient = mqtt.Client()\nclient.on_connect = on_connect\nclient.on_message = on_message\n\nclient.connect(\"18.217.92.215\", 1883, 60)\n\nclient.loop_forever()\n","sub_path":"LoRa-MQTT/kafka_go.py","file_name":"kafka_go.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"241624953","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nplt.rcParams[\"font.sans-serif\"] = [\"SimHei\"] # 用来正常显示中文标签\nplt.rcParams[\"axes.unicode_minus\"] = False # 用来正常显示负号\n# 中文负号要用 u 修饰字符串\n\nfig = plt.figure(figsize=(4, 4))\naxes = fig.add_subplot(111)\naxes.plot([1, 2, 3, 4], [1, 2, 3, 4])\naxes.set_title(u\"something-这是\")\nplt.show()\n\n# #函数里的参数,是根据我们的例子特定设置的,不同问题,不同的设置,\n# 需要看图片效果,找参数\n\n# #设置刻度范围\n# ax.set_xlim(1,7.1)#x轴从1到7.1\n# ax.set_ylim(40,100)#y轴从40到100\n\n# #设置显示的刻度\n# ax.set_xticks(np.linspace(1,7,7))#np.linspace()函数为等差数列,1至7的7个数组成的等差数列1,2,3,4,5,6,7,\n# ax.set_yticks(np.linspace(50,100,6))#关于等差数列,想了解的可以参看numpy的用法\n\n# #设置刻度标签\n# ax.set_xticklabels([\"星期一\",\"星期二\",\"星期三\",\"星期四\",\"星期五\",\"星期六\",\"星期日\"],fontproperties=\"SimHei\"\\\n# ,fontsize=12)\n# #这里用到了属性fontproperties可以单独设置x轴标签的字体,也可以用fontsize设置字体大小,还可以用color\n# 设置字的颜色\n\n# ax.set_yticklebels([\"50kg\",\"60kg\",\"70kg\",\"80kg\",\"90kg\",\"100kg\"],fontsize=12)","sub_path":"templates/python-matplotlib.py","file_name":"python-matplotlib.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"640598105","text":"# Stdlib imports\nimport re, fnmatch\nfrom datetime import datetime, timedelta\n# Local modules imports\nfrom excepts import ActivityError, CodeUsedError, InvalidCodeError, RecursionError, TaskNotFoundError\n\n\nclass Task(object):\n project = None\n active_task = None\n \n def __init__(self, code, name, supertask=None):\n '''The first task is a project'''\n self.code = str(code)\n if re.search('^\\d+|\\W+', self.code):\n raise InvalidCodeError\n self.name = str(name)\n self.supertask = supertask or Task.project\n self.subtasks = []\n if Task.project is None:\n Task.project = self\n else:\n try:\n self.supertask.get(self.code)\n raise CodeUsedError\n except KeyError:\n pass\n if supertask is None:\n self.supertask.subtasks.append(self)\n self.bookings = []\n \n @property\n def active(self):\n return self.bookings and self.bookings[-1].active\n \n @property\n def all_subtasks(self):\n for t in self.subtasks:\n yield t\n for st in t.all_subtasks:\n yield st\n \n @property\n def last_timer(self):\n return self.bookings[-1].duration if self.bookings else timedelta(0)\n \n @property\n def total_timer(self):\n td = timedelta(0)\n for b in self.bookings:\n td += b.duration\n return td\n \n @property\n def wbs(self):\n if self.supertask != Task.project:\n return '{}.{}'.format(self.supertask.wbs, self.code)\n else:\n return self.code\n \n def add(self, code, name):\n t = Task(code, name, self)\n self.subtasks.append(t)\n return t\n \n def belongs_to(self, supertask):\n return self.supertask == supertask and self in supertask.subtasks\n \n def clear(self):\n self.bookings = []\n \n def delete(self, code):\n t = self.get(code)\n t.supertask.subtasks.remove(t)\n return t\n \n def empty(self):\n self.subtasks = []\n \n def find(self, **kwargs):\n '''Returns a list of matching objects, search is recursive'''\n field, value = kwargs.items()[0]\n pattern = re.compile(r'^{}'.format(fnmatch.translate(value)), re.I)\n return [t for t in self.all_subtasks if pattern.match(getattr(t, field))]\n \n def get(self, code):\n '''Returns an object or an exception if not found, match is exact'''\n if '.' in code:\n attr = 'wbs'\n tset = 'all_subtasks'\n else:\n attr = 'code'\n tset = 'subtasks'\n for t in getattr(self, tset):\n if getattr(t, attr) == code:\n return t\n raise TaskNotFoundError\n \n def move(self, scode, dest):\n # Not working for wbs-determined tasks\n sub = self.get(scode)\n if dest in sub.all_subtasks:\n raise RecursionError\n try:\n dest.get(scode)\n raise CodeUsedError\n except TaskNotFoundError:\n pass\n sub.supertask.subtasks.remove(sub)\n sub.supertask = dest\n dest.subtasks.append(sub)\n return sub\n \n def start(self):\n '''Start the task (create+activate a booking)'''\n if self.active:\n raise ActivityError\n self.bookings.append(Booking(self))\n Task.active_task = self\n \n def stop(self):\n '''Stop the task (close the booking)'''\n if not self.active:\n raise ActivityError\n self.bookings[-1].stop()\n if Task.active_task == self:\n Task.active_task = None\n\n\nclass Booking(object):\n \n def __init__(self, task):\n self.task = task\n self.start = datetime.now()\n self.finish = None\n self.active = True\n \n @property\n def duration(self):\n return (self.finish or datetime.now()) - self.start\n \n def get_duration(self, min_res):\n m = round(self.duration.seconds / 60)\n m -= m % min_res\n return m / 60\n \n def get_start(self, min_res):\n m = self.start.minute % min_res\n return self.start - timedelta(minutes=m)\n \n def stop(self):\n self.active = False\n self.finish = datetime.now()\n\n def display(self, frmt='std', min_res=1):\n if frmt == 'std':\n return '{0} {1:%Y-%m-%d}: {1:%H:%M} - {2:%H:%M}'.format(\n self.task.wbs, self.start, datetime.now() if self.active else self.finish )\n elif frmt == 'tj':\n return 'actual:booking {0} {1:%Y-%m-%d-%H:%M} + {2:.1f}h {{overtime 2}}'.format(\n self.task.wbs, self.get_start(min_res), self.get_duration(min_res))","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"575615475","text":"\"\"\"\nHXRSnD IPython Shell\n\"\"\"\nimport logging\nimport os # noqa\nimport socket\nimport warnings\nfrom importlib import reload # noqa\nfrom pathlib import Path # noqa\n\n# Ignore python warnings (Remove when ophyd stops warning about 'signal_names')\nwarnings.filterwarnings('ignore')\n\nlogger = logging.getLogger(__name__)\n\ntry:\n from snd_devices import * # noqa\n\n # Success\n logger.debug(\"Successfully created SplitAndDelay class on '{0}'\".format(\n socket.gethostname()))\nexcept Exception as e:\n logger.error(\"Failed to create SplitAndDelay class on '{0}'. Got error: \"\n \"{1}\".format(socket.gethostname(), e))\n raise\n\n# Try importing from the scripts file if we succeeded at making the snd object\nelse:\n try:\n from scripts import * # noqa\n logger.debug(\"Successfully loaded scripts.\")\n # There was some problem in the file\n except Exception as e:\n logger.warning(\"Failed to load scripts file, got the following error: \"\n \"{0}\".format(e))\n raise\n # Notify the user that everything went smoothly\n else:\n logger.info(\"Successfully initialized new SnD session on '{0}'\".format(\n socket.gethostname()))\n","sub_path":"bin/run_snd.py","file_name":"run_snd.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"268907175","text":"#!/usr/bin/env python\n\n'''\nInstalls the code in ./robot to a FRC cRio-based Robot via FTP\n\nUsage: run install.py, and it will upload \n'''\n\nimport os\nimport ftplib\nimport sys\nfrom optparse import OptionParser\n\n\n\ndef get_robot_host(team_number):\n '''Given a team number, determine the address of the robot'''\n return '10.%d.%d.2' % (team_number / 100, team_number % 100 )\n\n\nclass RobotCodeInstaller(object):\n \"\"\"\n Use this class to create programs that automatically upload your \n python code to the robot in the right place without having\n to deal with an FTP client\n \n Example:\n \n from install import RobotCodeInstaller, get_robot_host\n \n installer = None\n my_team_number = 2423\n \n try:\n installer = RobotCodeInstaller( get_robot_host( my_team_number ) )\n except Exception as e:\n print(\"Could not connect to robot FTP server %s: %s\" % (robot_host, e))\n exit(1)\n \n installer.upload_directory( '/py', '.')\n \n installer.close()\n \"\"\"\n\n def __init__(self, robot_host, username='FRC', password='FRC', timeout=5):\n self.ftp = ftplib.FTP(robot_host, username, password, '', timeout)\n \n def close(self):\n self.ftp.quit()\n \n def upload_directory( self, remote_root, local_root, recursive=True, verbose=False ):\n '''\n Parameters:\n \n remote_root:\n The remote directory to upload files to \n \n local_root:\n The local directory to upload files from\n \n recursive:\n Set to true to recursively walk local_root to upload files\n \n verbose:\n Set to true to output the name of each file as it is \n being uploaded\n '''\n\n # save cwd\n cwd = os.path.abspath( os.getcwd() )\n \n if not os.path.isdir( local_root ):\n print(\"ERROR: Local root directory %s does not exist\" % local_root )\n return False\n \n os.chdir( local_root )\n \n try:\n self.ftp.cwd( remote_root )\n except ftplib.error_perm as msg:\n print(\"ERROR: Accessing remote directory %s failed: %s\" % (remote_root, msg))\n return False\n \n has_error = False\n \n for root, dirs, files in os.walk( '.' ):\n \n sys.stdout.write(root + ': ')\n \n remote_files = []\n \n try:\n remote_files = self.ftp.nlst( root )\n except ftplib.error_perm:\n # directory must not exist, right?\n try:\n self.ftp.mkd( root )\n if verbose:\n print( 'MKDIR ' + root )\n except ftplib.error_perm as msg:\n print(\"ERROR: Creating directory %s failed: %s\" % (root, msg))\n break\n \n for fn in files:\n \n filename = os.path.join( root, fn )\n r, ext = os.path.splitext( fn )\n \n # if this accidentally got in there, don't upload it\n if ext == '.pyc':\n continue\n \n # for each py file, delete a pyc file associated with it\n if ext == '.py' and (r + '.pyc') in remote_files:\n try:\n self.ftp.delete( r + '.pyc' )\n if verbose:\n print('DELETE ' + r + '.pyc')\n except Exception:\n pass\n \n # upload the file already!\n with open(filename, 'rb') as stor_file:\n try:\n #\n self.ftp.storbinary( 'STOR ' + filename, stor_file )\n \n if verbose:\n print( 'STOR ' + filename )\n else:\n sys.stdout.write('.')\n sys.stdout.flush()\n except ftplib.error_perm as msg:\n print(\"ERROR writing %s: %s\" % (filename, msg ))\n has_error = True\n break\n except IOError as msg:\n print(\"ERROR reading from %s: %s\" % (filename, msg))\n has_error = True\n break\n \n sys.stdout.write('\\n')\n \n if has_error or not recursive:\n break\n \n # restore local cwd\n os.chdir( cwd )\n return True\n\n\n\nif __name__ == '__main__':\n\n parser = OptionParser('Usage: %program [remote_host]')\n parser.add_option('-v', '--verbose', dest='verbose', \n help='Verbose output', action='store_true', default=False)\n parser.add_option('-t', '--team', dest='team_number', help='Team number', default=None)\n \n \n parser.add_option('--remote-root', dest='remote_root', \n help='Remote root directory (default: %default)', \n default='/')\n \n parser.add_option('--local-root', dest='local_root', \n help='Local root directory (default: %default)', \n default=os.path.join( os.path.dirname(__file__), 'robot' ) )\n \n (options, args) = parser.parse_args()\n\n robot_host = None\n \n if len(args) == 1:\n robot_host = args[1]\n elif len(args) != 0:\n parser.error(\"Invalid arguments passed\")\n\n # banner message\n print( \"Robot code uploader v1.0\" )\n \n \n if robot_host is None:\n # if the team number hasn't been specified in an option, then\n # ask the user for the team number. \n team_number = options.team_number\n \n while team_number is None:\n try:\n team_number = int(input('Team number? '))\n except ValueError:\n pass\n \n # determine the host name from the team number\n robot_host = '10.%d.%d.2' % (team_number / 100, team_number % 100 )\n \n # ok, we're ready. Process the manifest and upload it \n \n try:\n installer = RobotCodeInstaller( robot_host )\n except Exception as e:\n print(\"Could not connect to robot FTP server %s: %s\" % (robot_host, e))\n exit(1)\n \n installer.upload_directory( options.remote_root, options.local_root, verbose=options.verbose )\n \n installer.close()\n ","sub_path":"test/python/installer/install.py","file_name":"install.py","file_ext":"py","file_size_in_byte":6842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"546793669","text":"\"\"\"\n Imports:\n requests:\n HTTP library\n pytesseract:\n Optical Character Recognition (OCR) library\n PIL:\n Image processing library\n\"\"\"\n\n\nimport requests\nimport pytesseract\ntry:\n from PIL import Image\nexcept ImportError:\n import Image\n\nURL = 'http://158.69.76.135/level5.php'\ncaptcha_url = 'http://158.69.76.135/captcha.php'\nwindows_user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'\nheader = {\n 'User-Agent': windows_user_agent,\n 'Referer': URL\n}\napi_key = '174faff8fbc769e94a5862391ecfd010'\n\nfor i in range(5):\n try:\n # start request session\n with requests.Session() as s:\n # get the response object\n response = s.get(URL, headers=header)\n\n # get image response object\n image = s.get(captcha_url, headers=header)\n\n # write captcha file\n image_file = open('captcha.png', 'wb')\n image_file.write(image.content)\n image_file.close()\n\n # Resolve captcha with pytesseract\n captcha = pytesseract.image_to_string(Image.open('captcha.png'))\n captcha = captcha.replace(\" \", \"\").strip()\n print(' - Captcha solved!')\n\n # get key from cookies\n site_key = response.cookies['HoldTheDoor']\n\n # compose the data that will send\n payload = {\n 'id': '1',\n 'key': site_key,\n 'captcha': captcha,\n 'holdthedoor': 'submit'\n }\n # send data\n send = s.post(URL, headers=header, data=payload)\n print('Post Request made with status: {}'.format(send.status_code))\n print('--------------------------------------')\n except Exception as err:\n print('Something went wrong =(')\n i -= 1","sub_path":"level_5/level_5.py","file_name":"level_5.py","file_ext":"py","file_size_in_byte":1932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"303062957","text":"from .header import *\n\n'''\nBERT for text matching (trained by negative sampling)\nDeep mining the relations among the sentences: logic modeling; using the transformers\n'''\n\nclass BERTRetrieval_Multi(nn.Module):\n\n def __init__(self, nipt=768, nhead=8, dim_feedforward=512, dropout=0.5, nlayers=6):\n super(BERTRetrieval_Multi, self).__init__()\n self.model = BertModel.from_pretrained(\n 'bert-base-chinese')\n # the dataloader already makes sure the turn_size is consistent [NO PAD, NO MASK]\n self.nipt = nipt\n encoder_layer = nn.TransformerEncoderLayer(nipt, nhead, dim_feedforward, dropout)\n self.trs_encoder = nn.TransformerEncoder(encoder_layer, nlayers)\n # classification\n self.classifier = nn.Linear(nipt, 2)\n\n def forward(self, inpts, sep_index):\n '''\n inpts: [batch, seq]\n sep_index: batch*[turn_size list]\n '''\n # Obtain the Bert embedding of all the utterances (include response)\n seq_size = inpts.shape[-1]\n attn_mask = generate_attention_mask(inpts)\n output = self.model(\n input_ids=inpts,\n attention_mask=attn_mask)[0] # [batch, seq, 768]\n rest = []\n for item, sidx in zip(output, sep_index):\n # item: [seq, 768]; sidx: [turn_size]\n if_pad = True if sum(sidx) < seq_size else False\n if if_pad:\n sidx.append(seq_size - sum(sidx))\n sequences = item.split(sidx, dim=0)[:-1] # sequence: [sub_seq, 768]\n else:\n sequences = item.split(sidx, dim=0)\n sequences = torch.stack(\n [torch.mean(seq, dim=0) for seq in sequences]) # sequence: [turn, 768]\n rest.append(sequences)\n rest = torch.stack(rest).permute(1, 0, 2) # [batch, turn, 768] -> [turn, batch, 768]\n # transformer encoder\n output = self.trs_encoder(F.relu(rest))[-1] # [turn, batch, 768] -> [batch, 768]\n logits = self.classifier(output) # [batch, 2]\n return logits \n\nclass BERTRetrievalMultiAgent(RetrievalBaseAgent):\n\n '''\n Support Multi GPU, for example '1,2'\n '''\n\n def __init__(self, multi_gpu, run_mode='train', lang='zh', kb=False):\n super(BERTRetrievalMultiAgent, self).__init__(kb=kb)\n # hyperparameters\n try:\n self.gpu_ids = list(range(len(multi_gpu.split(',')))) \n except:\n raise Exception(f'[!] multi gpu ids are needed, but got: {multi_gpu}')\n self.args = {\n 'lr': 3e-5,\n 'nipt': 768,\n 'nhead': 8,\n 'dim_feedforward': 512,\n 'dropout': 1.0,\n 'nlayers': 6,\n 'grad_clip': 3.0,\n 'samples': 10,\n 'multi_gpu': self.gpu_ids,\n 'talk_samples': 512,\n 'vocab_file': 'data/vocab/vocab_small',\n 'pad': 0,\n }\n # hyperparameters\n self.vocab = BertTokenizer.from_pretrained('bert-base-chinese')\n self.model = BERTRetrieval_Multi(\n nipt=self.args['nipt'],\n nhead=self.args['nhead'],\n dim_feedforward=self.args['dim_feedforward'],\n dropout=self.args['dropout'],\n nlayers=self.args['nlayers'])\n if torch.cuda.is_available():\n self.model.cuda()\n self.model = DataParallel(self.model, device_ids=self.gpu_ids)\n # bert model is too big, try to use the DataParallel\n self.optimizer = transformers.AdamW(\n self.model.parameters(), \n lr=self.args['lr'])\n self.criterion = nn.CrossEntropyLoss()\n\n self.show_parameters(self.args)\n\n def train_model(self, train_iter, mode='train', recoder=None):\n self.model.train()\n total_loss, batch_num = 0, 0\n correct, s = 0, 0\n with tqdm(total=len(train_iter)) as pbar:\n for idx, batch in enumerate(train_iter):\n # label: [batch]\n cid, label, sep_index = batch\n self.optimizer.zero_grad()\n output = self.model(cid, sep_index) # [batch, 2]\n loss = self.criterion(\n output, \n label.view(-1))\n if mode == 'train':\n loss.backward()\n clip_grad_norm_(self.model.parameters(), self.args['grad_clip'])\n self.optimizer.step()\n \n total_loss += loss.item()\n batch_num += 1\n \n now_correct = torch.max(F.softmax(output, dim=-1), dim=-1)[1] # [batch]\n now_correct = torch.sum(now_correct == label).item()\n correct += now_correct\n s += len(label)\n\n pbar.set_description(f'[!] batch: {batch_num}; train loss: {round(loss.item(), 4)}; acc: {round(now_correct/len(label), 4)}|{round(correct/s, 4)}')\n pbar.update(len(label))\n print(f'[!] overall acc: {round(correct/s, 4)}')\n return round(total_loss / batch_num, 4)\n\n def test_model(self, test_iter, path):\n self.model.eval()\n total_loss, batch_num = 0, 0\n rest = []\n with torch.no_grad():\n with tqdm(total=len(test_iter)) as pbar:\n for idx, batch in enumerate(train_iter):\n cid, label = batch\n output = self.model(cid)\n loss = self.criterion(output, label.view(-1))\n total_loss += loss.item()\n batch_num += 1\n \n # output: [batch, 2]\n # only use the positive score as the final score\n output = F.softmax(output, dim=-1)[:, 1] # [batch]\n preds = [i.tolist() for i in torch.split(output, self.args['samples'])]\n labels = [i.tolist() for i in torch.split(label, self.args['samples'])]\n for label, pred in zip(labels, preds):\n pred = np.argsort(pred, axis=0)[::-1]\n rest.append(([0], pred.tolist()))\n pbar.update(len(label))\n print(f'[!] test loss: {round(total_loss/batch_num, 4)}')\n p_1, r2_1, r10_1, r10_2, r10_5, MAP, MRR = cal_ir_metric(rest)\n print(f'[TEST] P@1: {p_1}; R2@1: {r2_1}; R10@1: {r10_1}; R10@2: {r10_2}; R10@5: {r10_5}; MAP: {MAP}; MRR: {MRR}')\n return round(total_loss/batch_num, 4)\n\n def talk(self, topic, msgs):\n with torch.no_grad():\n # retrieval and process\n utterances_, ids = self.process_utterances(topic, msgs)\n # rerank, ids: [batch, seq]\n output = self.model(ids) # [batch, 2]\n output = F.softmax(output, dim=-1)[:, 1] # [batch]\n item = torch.argmax(output).item()\n msg = utterances_[item]\n return msg\n","sub_path":"models/bert_retrieval_multi.py","file_name":"bert_retrieval_multi.py","file_ext":"py","file_size_in_byte":7021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"79465996","text":"#!/usr/bin/env python3\n\nimport sys\nimport zmq\n\nport = \"5556\"\nif len(sys.argv) > 1:\n port = sys.argv[1]\n int(port)\n\nif len(sys.argv) > 2:\n port1 = sys.argv[2]\n int(port1)\n\n# Socket to talk to server\ncontext = zmq.Context()\nsocket = context.socket(zmq.SUB)\n\nprint(\"Collecting updates...\")\nsocket.connect (\"tcp://localhost:%s\" % port)\n\nif len(sys.argv) > 2:\n socket.connect (\"tcp://localhost:%s\" % port1)\n\ntopicfilter = \"event\"\nsocket.setsockopt_string(zmq.SUBSCRIBE, topicfilter)\n\n# Process 5 updates\ntotal_value = 0\nwhile True:\n string = socket.recv()\n topic, messagedata = string.split()\n print(topic, messagedata)\n","sub_path":"maintcal/eventhandler.py","file_name":"eventhandler.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"111490384","text":"\"\"\"\nВ этой задаче вам нужно будет много раз отвечать на запрос «Найдите сумму чисел на отрезке в массиве».\nФормат ввода\nВ первой строке записано два целых числа\nn и q (1 ≤ n, q ≤ 3 * 10**5) - размер массива и количество запросов.\nВо второй строке записаны n целых чисел a.i (1 ≤ a.i ≤ 10**9) - сам массив.\nДалее в q строках описаны запросы к массиву. Каждый запрос описывается двумя числами\nl, r (1 ≤ l ≤ r ≤ n) - левой и правой границей отрезка, на котором нужно найти сумму.\n\nФормат вывода\nДля каждого запроса в отдельной строке выведите единственное число - сумму на соответствующем отрезке.\n\"\"\"\n\nn, q = map(int, input().split())\n\nnums = list(map(int, input().split()))\n\nprefix_sum = [0] * (n + 1)\nfor i in range(1, n + 1):\n prefix_sum[i] = prefix_sum[i - 1] + nums[i - 1]\n\nfor i in range(q):\n question = list(map(int, input().split()))\n print(prefix_sum[question[1]] - prefix_sum[question[0] - 1])\n","sub_path":"lessons_5_6/task_5a.py","file_name":"task_5a.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"232164223","text":"import pytest\nfrom flask import url_for\n\nfrom src.comm.sms_utils import single_sms_sender\nfrom src.config.msgconfig import Msg\n\n\n@pytest.mark.skip(reason=\"skip\")\ndef test_liantong_sender():\n \"\"\" 联通发送短信测试\n \"\"\"\n result, error = single_sms_sender(\n channel_code=\"liantong\",\n receiver=\"18582554687\",\n template_content=\"你好,你的订单:{1},请及时查收\",\n params=[\"88888888\"],\n template_content_code=\"\",\n conf_params={\"CorpID\": \"CDJS006669\", \"Pwd\": \"xxxxx\"},\n sign_name=\"涌泉贷\",\n )\n assert result is True\n\n\n@pytest.mark.skip(reason=\"skip\")\ndef test_check_app_temp(client, sms_app, sms_app_template):\n \"\"\"测试应用模板是否有效\n \"\"\"\n sms_app[\"channel_code\"] = \"tx\"\n client.post(url_for(\"smsappapi\"), json=sms_app)\n client.post(url_for(\"smsapptemplateapi\"), json=sms_app_template)\n result = client.post(\n url_for(\"smsapptemplatecheckapi\"),\n json={\"phone\": \"18582554687\", \"app_template_id\": 1, \"params\": [1, 2]},\n ).json\n\n assert result[\"code\"] == Msg.ERROR\n","sub_path":"xxw/chaos/test/test_sms_sender.py","file_name":"test_sms_sender.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"211738603","text":"def codex (phrase, key): \r\n \"\"\" La fonction code la phrase insérée avec la clé insérée, \r\n en se basant sur la valeur décimale des caractères \"\"\"\r\n \r\n phraseList = [] # Liste contenant la phrase entrée\r\n keyList = [] # Liste contenant la clé entrée\r\n outList = [] # Liste de sortie\r\n \r\n # Création de la liste phrase\r\n i = 0\r\n while i < len(phrase) :\r\n phraseList.append(phrase[i])\r\n i += 1\r\n \r\n # Création de la liste key\r\n i = 0\r\n while i < len(key) :\r\n keyList.append(key[i])\r\n i += 1\r\n \r\n # Génération du code\r\n i = 0\r\n while i < len(phraseList) :\r\n if ord(phraseList[i]) == 32 : # Si rencontre un espace\r\n outList.append(chr(32)) # Ajout d'un espace en sortie\r\n i += 1\r\n continue # Reprise de la boucle\r\n elif ord(phraseList[i]) == 39 :\r\n \"\"\"Si rencontre une apostrophe\"\"\"\r\n outList.append(chr(39)) # Ajout d'un espace en sortie\r\n i += 1\r\n continue\r\n \r\n valeurPhrase = ord(phraseList[i]) \r\n \"\"\"Valeur de la lettre à l'emplacement i de la phrase\"\"\"\r\n valeurKey = ord(keyList[i])\r\n \"\"\"Valeur de la lettre à l'emplacement i de la clé\"\"\"\r\n outRange = (valeurPhrase + valeurKey) - 122 \r\n \"\"\"Valeur de sortie\"\"\"\r\n \r\n if outRange < 97 : # Intervalle alphabet = ]97:122[\r\n outRange += 26\r\n \r\n outList.append(chr(outRange))\r\n \"\"\"Transforme valeur de sortie en caractère + insertion \r\n dans liste\"\"\" \r\n i += 1\r\n \r\n outChaine = \" \".join(outList) # Conversion liste en chaine\r\n \r\n return outChaine # Sortie de la chaine de sortie","sub_path":"coder.py","file_name":"coder.py","file_ext":"py","file_size_in_byte":1742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"443428484","text":"# -*- coding: utf-8 -*-\n\n\"\"\" Return a map with all the keys and tuples for the values\n\"\"\"\ndef dictDiff(a, b):\n if not isinstance(a, dict) or not isinstance(b, dict):\n raise ValueError(\"a and b must be dict\")\n diff = dict()\n for key in set().union(a.keys()).union(b.keys()):\n aValue = a.get(key, None)\n bValue = b.get(key, None)\n diff[key] = (aValue, bValue)\n return diff\n","sub_path":"sourcerer/diffutils.py","file_name":"diffutils.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"254365497","text":"import os\nimport platform\n\nfrom pyot.conf.pipeline import activate_pipeline, PipelineConf\nfrom pyot.conf.model import activate_model, ModelConf\n\n\nif platform.system() == 'Windows':\n from pyot.utils.runtime import silence_proactor_pipe_deallocation\n silence_proactor_pipe_deallocation()\n\n\n@activate_model(\"riot\")\nclass RiotModel(ModelConf):\n default_platform = \"na1\"\n default_region = \"americas\"\n default_version = \"latest\"\n default_locale = \"en_us\"\n\n\n@activate_model(\"lol\")\nclass LolModel(ModelConf):\n default_platform = \"na1\"\n default_region = \"americas\"\n default_version = \"latest\"\n default_locale = \"en_us\"\n\n\n@activate_pipeline(\"lol\")\nclass LolPipeline(PipelineConf):\n name = \"lol_main\"\n default = True\n stores = [\n {\n \"backend\": \"pyot.stores.omnistone.Omnistone\",\n \"log_level\": 30,\n \"expirations\": {\n \"summoner_v4_by_name\": 100,\n \"match_v4_match\": 600,\n \"match_v4_timeline\": 600,\n }\n },\n {\n \"backend\": \"pyot.stores.merakicdn.MerakiCDN\",\n \"log_level\": 30,\n \"error_handler\": {\n 404: (\"T\", []),\n 500: (\"R\", [3])\n }\n },\n {\n \"backend\": \"pyot.stores.cdragon.CDragon\",\n \"log_level\": 30,\n \"error_handler\": {\n 404: (\"T\", []),\n 500: (\"R\", [3])\n }\n },\n {\n \"backend\": \"pyot.stores.riotapi.RiotAPI\",\n \"log_level\": 30,\n \"api_key\": os.environ[\"RIOT_API_KEY\"],\n \"rate_limiter\": {\n \"backend\": \"pyot.limiters.redis.RedisLimiter\",\n # \"limiting_share\": 1,\n \"host\": \"127.0.0.1\",\n \"port\": 6379,\n \"db\": 0,\n },\n \"error_handler\": {\n 400: (\"T\", []),\n 503: (\"E\", [3, 3])\n }\n }\n ]\n","sub_path":"test/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"516426370","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nsample_data = pd.read_csv(\"August_2018_Nationwide_Airplane_Delay_Statistic.csv\")\n\nx = sample_data[\"DEP_DELAY (HHMM)\"]\ny = sample_data[\"ARR_DELAY (HHMM)\"]\n\nDEP_DELAY_COUNT, DEP_DELAY_BIN = np.histogram(x,bins=10)\nARR_DELAY_COUNT, ARR_DELAY_BIN = np.histogram(y,bins=10)\n\nDEP_DELAY_PDF = DEP_DELAY_COUNT / sum(DEP_DELAY_COUNT)\nDEP_DELAY_CDF = np.cumsum(DEP_DELAY_PDF)\nARR_DELAY_PDF = ARR_DELAY_COUNT / sum(ARR_DELAY_COUNT)\nARR_DELAY_CDF = np.cumsum(ARR_DELAY_PDF)\n\nfigure, DEP_DELAY = plt.subplots(1,2,figsize=(18,9),sharey=True)\nDEP_DELAY[0].set_title(\"Departure Delay Time (Probability Density Function (PDF))\")\nDEP_DELAY[0].set_xlabel(\"Departure Delay Time (HHMM)\")\nDEP_DELAY[0].set_ylabel(\"The Probability of the plane will gain departure delay\")\nDEP_DELAY[0].plot(DEP_DELAY_BIN[1:],DEP_DELAY_PDF,color=\"red\")\nDEP_DELAY[0].legend()\n\nDEP_DELAY[1].set_title(\"Departure Delay Time (Cumulative Probability Function (CDF))\")\nDEP_DELAY[1].set_xlabel(\"Departure Delay Time (HHMM)\")\nDEP_DELAY[1].set_ylabel(\"The Probability of the plane will gain departure delay\")\nDEP_DELAY[1].plot(DEP_DELAY_BIN[1:],DEP_DELAY_CDF,color=\"red\")\nDEP_DELAY[1].legend()\n\nfigure, ARR_DELAY = plt.subplots(1,2,figsize=(18,9),sharey=True)\nARR_DELAY[0].set_title(\"Arrival Delay Time (Probability Density Function (PDF))\")\nARR_DELAY[0].set_xlabel(\"Arrival Delay Time (HHMM)\")\nARR_DELAY[0].set_ylabel(\"The Probability of the plane will gain arrival delay\")\nARR_DELAY[0].plot(ARR_DELAY_BIN[1:],ARR_DELAY_PDF,color=\"red\")\nARR_DELAY[0].legend()\n\nARR_DELAY[1].set_title(\"Arrival Delay Time (Cumulative Probability Function (CDF))\")\nARR_DELAY[1].set_xlabel(\"Arrival Delay Time (HHMM)\")\nARR_DELAY[1].set_ylabel(\"The Probability of the plane will gain arrival delay\")\nARR_DELAY[1].plot(ARR_DELAY_BIN[1:],ARR_DELAY_CDF,color=\"red\")\nARR_DELAY[1].legend()\n\nplt.show()","sub_path":"ProbStat_HW3_ID62010694/Lab03_Probability_Density_Function.py","file_name":"Lab03_Probability_Density_Function.py","file_ext":"py","file_size_in_byte":1897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"143902972","text":"\"\"\"# Regime Detection\"\"\"\r\n\r\n\r\nfrom pandas_datareader import data as pdr\r\nimport quantstats as qs\r\nimport strategies\r\nimport yfinance as yf\r\nfrom tqdm import tqdm\r\nfrom datetime import datetime\r\nfrom datetime import date,timedelta\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\nimport statsmodels.api as sm\r\nimport numpy as np; np.random.seed(0)\r\nimport seaborn as sns; sns.set()\r\nfrom hmmlearn import hmm\r\nfrom sklearn.decomposition import PCA\r\nimport time\r\n\r\ndef percentile_data(X,period=3,extend=False):\r\n try:\r\n start=X.index[0].replace(year=X.index[0].year+period)\r\n except:\r\n start=X.index[0].replace(year=X.index[0].year+period,day=28)\r\n startDate=X.loc[:start].index[-1]\r\n dfIdx=X.loc[startDate:].index\r\n dfPercentile=pd.DataFrame(columns=X.columns,index=dfIdx)\r\n if extend:\r\n for i in dfIdx:\r\n dfPercentile.loc[i]=X.loc[:i].rank(pct=True).iloc[-1]\r\n else:\r\n for i in dfIdx:\r\n try:\r\n dfPercentile.loc[i]=X.loc[i.replace(year=i.year-period):i].rank(pct=True).iloc[-1]\r\n except:\r\n dfPercentile.loc[i]=X.loc[i.replace(year=i.year-period,day=28):i].rank(pct=True).iloc[-1]\r\n return dfPercentile\r\n\r\ndef fix_states(states, dataHMMTemp):\r\n tempList=[[0,dataHMMTemp[states==0].mean()]]\r\n tempList.append([1,dataHMMTemp[states==1].mean()])\r\n tempList.append([2,dataHMMTemp[states==2].mean()])\r\n ary=np.array(tempList)[np.argsort(np.array(tempList)[:, 1])]\r\n return pd.Series(states).replace(ary[:,0],[0,1,2]).values\r\n\r\ndef desc_by_state(mySeries,states):\r\n #rtnM=rtnMoney[mySeries.index]\r\n #descIndex=['Return','Std.','Sharpe','Skewness']\r\n descIndex=['Return','Std.','Skewness','Kurtosis','Count','T-Count']\r\n descColumns=['Seeking','Neutral','Aversion']\r\n df=pd.DataFrame(columns=descColumns,index=descIndex)\r\n for i in range(3):\r\n tempSeries=mySeries[states==i]\r\n df.iloc[0,i]=tempSeries.mean()*252\r\n df.iloc[1,i]=tempSeries.std()*np.sqrt(252)\r\n df.iloc[2,i]=tempSeries.skew()\r\n df.iloc[3,i]=tempSeries.kurtosis()\r\n df.iloc[4,i]=tempSeries.size\r\n df.iloc[5,[0,1]]=count_transaction(list(states))\r\n return df.astype(float).round(5)\r\n\r\ndef desc_by_threshold(mySeries,riskIndex,threshold=[0,0.25,0.55,1]):\r\n #rtnM=rtnMoney[mySeries.index]\r\n #descIndex=['Return','Std.','Sharpe','Skewness']\r\n descIndex=['Return','Std.','Skewness','Kurtosis','Count']\r\n descColumns=['Seeking','Neutral','Aversion']\r\n df=pd.DataFrame(columns=descColumns,index=descIndex)\r\n for i in range(3):\r\n tempSeries=mySeries[(riskIndex>threshold[i]) & (riskIndex<=threshold[i+1])]\r\n df.iloc[0,i]=tempSeries.mean()*252\r\n df.iloc[1,i]=tempSeries.std()*np.sqrt(252)\r\n df.iloc[2,i]=tempSeries.skew()\r\n df.iloc[3,i]=tempSeries.kurtosis()\r\n df.iloc[4,i]=tempSeries.size\r\n return df.astype(float).round(5)\r\n\r\ndef count_transaction(States):\r\n count=0\r\n count_half=0\r\n states=[i/2 for i in States]\r\n for i in range(len(states)-1):\r\n temp=states[i+1]-states[i]\r\n count=count+(temp>0)+(temp<0)\r\n count_half=abs(temp)+count_half\r\n return count,count_half\r\n\r\n\r\ndef trade_by_state(mySeries0,states):\r\n nv=[1]\r\n cash=1\r\n pos=0\r\n if states[0]==0.5:\r\n cash=0.5\r\n pos=0.5*(1-0.001)\r\n elif states[0]==1:\r\n cash=0\r\n pos=1-0.001\r\n nv.append(cash+pos*mySeries0[1]+pos)\r\n\r\n for i in range(1,states.size-1):\r\n if states[i]-states[i-1]==1:\r\n pos=cash*(1-0.001)\r\n cash=0\r\n elif states[i]-states[i-1]==0.5:\r\n if pos==0:\r\n pos=cash/2*(1-0.001)\r\n cash=cash/2\r\n else:\r\n pos=pos+cash*(1-0.001)\r\n cash=0\r\n elif states[i]-states[i-1]==-0.5:\r\n if cash==0:\r\n cash=pos/2*(1-0.001)\r\n pos=pos/2\r\n else:\r\n cash=cash+pos*(1-0.001)\r\n pos=0\r\n elif states[i]-states[i-1]==-1:\r\n cash=pos*(1-0.001)\r\n pos=0\r\n pos=pos*(1+mySeries0.iloc[i+1])\r\n nv.append(cash+pos)\r\n return pd.Series([i for i in nv],index=mySeries0.index).astype(float)\r\n\r\n\r\ndef rtn_by_year(rtnSeries):\r\n yearS=rtnSeries.index[0].year\r\n yearE=rtnSeries.index[-1].year\r\n descColumns=['Return','Std.','Sharpe','Skewness','MDD']\r\n df=pd.DataFrame(index=range(yearS,yearE+1),columns=descColumns)\r\n for i in df.index:\r\n tempData=rtnSeries.loc[rtnSeries.index.year==i]\r\n df.loc[i,'Return']=tempData.mean()*252\r\n df.loc[i,'Std.']=tempData.std()*np.sqrt(252)\r\n if df.loc[i,'Return']==0 or df.loc[i,'Std.']==0:\r\n df.loc[i,'Sharpe']=0\r\n else:\r\n df.loc[i,'Sharpe']=df.loc[i,'Return']/df.loc[i,'Std.']\r\n df.loc[i,'Skewness']=tempData.skew()\r\n tempCumValue=np.exp(tempData.cumsum())\r\n df.loc[i,'MDD']=min([(tempCumValue[j]-tempCumValue[:j].max())/tempCumValue[:j].max() for j in tempCumValue.index])\r\n #df.loc[i,'']\r\n df.loc['Overall']=np.nan\r\n df.iloc[-1,0]=rtnSeries.mean()*252\r\n df.iloc[-1,1]=rtnSeries.std()*np.sqrt(252)\r\n df.iloc[-1,2]=df.iloc[-1,0]/df.iloc[-1,1]\r\n cumValue=np.exp(rtnSeries.cumsum())\r\n df.iloc[-1,3]=rtnSeries.skew()\r\n df.iloc[-1,4]=min([(cumValue[j]-cumValue[:j].max())/cumValue[:j].max() for j in cumValue.index])\r\n return df","sub_path":"regimeDetection.py","file_name":"regimeDetection.py","file_ext":"py","file_size_in_byte":5474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"166718175","text":"from django.shortcuts import render\nimport requests\nimport xml.etree.ElementTree as ET\nimport numpy as np\nimport json\nimport math\n\n# Create your views here.\nfrom django.http import HttpResponse\nfrom django.shortcuts import redirect\nfrom .models import Store\n\nimport django_filters\nfrom rest_framework import viewsets, filters, status\nfrom .serializer import StoreSerializer\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view\nfrom django.core import serializers\n\n# Create your views here.\n\ndef index(request):\n str_out = \"*** app02 ***

    \"\n str_out += \"こんにちは

    \"\n str_out += \"Apr/02 PM 20:35

    \"\n return HttpResponse(str_out)\n\n@api_view(['GET', 'POST'])\ndef search(request):\n address = request.GET.get(\"param\")\n key = ''\n target_url = 'https://maps.googleapis.com/maps/api/geocode/json?'\n print(address)\n p = {\n 'address': address,\n 'key': key\n }\n result = json.loads(requests.get(target_url, params=p).text)\n if result is None:\n return Response({}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)\n lat = result['results'][0]['geometry']['location']['lat']\n lng = result['results'][0]['geometry']['location']['lng']\n stores = Store.objects.all()\n if len(stores) > 0: \n exist_store = __find_close_store(stores, lat, lng)\n\n if exist_store is not None:\n store = Store.objects.get(id=exist_store[0], status=1)\n close_stores = []\n for s in stores:\n close_store = __find_close_store_by_main_store(store, s)\n if close_store is not None:\n obj = {\n 'lat': str(close_store.lat),\n 'lng': str(close_store.lng),\n 'name': str(close_store.name),\n 'address': str(close_store.address),\n 'url': str(close_store.url),\n }\n close_stores.append(obj)\n d = {\n 'lat': str(store.lat),\n 'lng': str(store.lng),\n 'name': str(store.name),\n 'address': str(store.address),\n 'url': str(store.url),\n 'close_stores': close_stores,\n }\n return Response(d)\n\n d = {\n 'lat': lat,\n 'lng': lng\n }\n # return render(request, 'result.html', d)\n return Response(d)\n\n@api_view(['POST'])\ndef admin(request):\n params = json.loads(request.body.decode())\n for p in params['data']:\n store = Store()\n store.name = p['name']\n store.address = p['address']\n store.lat = p['lat']\n store.lng = p['lng']\n store.place_id = p['placeId']\n store.save()\n return Response()\n\n@api_view(['POST'])\ndef admin_edit(request):\n param = json.loads(request.body.decode())['store']\n store = Store.objects.get(id=param['id'])\n if store is None:\n return Response({}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)\n\n store.name = param['name']\n store.address = param['address']\n store.lat = param['lat']\n store.lng = param['lng']\n store.status = param['status']\n store.place_id = param['placeId']\n store.save()\n return Response()\n\n@api_view(['GET'])\ndef list(request):\n stores = Store.objects.all()\n data = []\n for store in stores:\n obj = {\n 'id': store.id,\n 'name': store.name,\n 'address': store.address,\n 'lat': store.lat,\n 'lng': store.lng,\n 'status': store.status,\n 'placeId': store.place_id\n }\n data.append(obj)\n return Response(data)\n\ndef __find_close_store(stores, lat, lng):\n target = np.array([float(lat), float(lng)])\n x = np.zeros((0,2))\n for store in stores:\n s_lat = float(store.lat)\n s_lng = float(store.lng)\n store_pos = np.array([s_lat, s_lng])\n diff = target - store_pos\n x = np.append(x, [[store.id, np.linalg.norm(diff)]], axis=0)\n\n result = x[np.argmin(np.hsplit(x, 2)[1])]\n return result\n\ndef __find_close_store_by_main_store(store1, target):\n lat1 = store1.lat\n lng1 = store1.lng\n lat2 = target.lat\n lng2 = target.lng\n\n radlat1 = math.radians(lat1)\n radlng1 = math.radians(lng1)\n radlat2 = math.radians(lat2)\n radlng2 = math.radians(lng2)\n\n r = 6378137.0\n\n averageLat = (radlat1 - radlat2) / 2\n averageLng = (radlng1 - radlng2) / 2\n\n dirc = r * 2 * math.asin(math.sqrt(math.pow(math.sin(averageLat), 2) + math.cos(radlat1) * math.cos(radlat2) * math.pow(math.sin(averageLng), 2)))\n\n if dirc > 0 and dirc < 10000:\n return target\n else:\n return None\n\ndef __get_map_url(lat, lng):\n pass\n\nclass StoreViewSet(viewsets.ModelViewSet):\n queryset = Store.objects.all()\n serializer_class = StoreSerializer\n","sub_path":"api/store/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"623447035","text":"import config\n\nfrom flask_ask import statement\n\n\n# These are errors that will not be handled by Amazon Pay; Merchant must handle\ndef handleErrors(request):\n\terrorMessage \t\t\t\t\t= ''\n\tpermissionsError \t\t\t\t= False\n\tactionResponseStatusCode \t\t= request['status']['code']\n\tactionResponseStatusMessage \t= request['status']['message']\n\tactionResponsePayloadMessage\t= ''\n\tif 'errorMessage' in request['payload']:\n\t\tactionResponsePayloadMessage = request['payload']['errorMessage']\n\n\tknownPermissionError = {\n\t\t# Permissions errors - These must be resolved before a user can use Amazon Pay\n\t\t'ACCESS_DENIED',\n\t\t'ACCESS_NOT_REQUESTED',\n\t\t'FORBIDDEN'\n\t}\n\tknownIntegrationOrRuntimeError = {\n\t\t# Integration errors - These must be resolved before Amazon Pay can run\n\t\t'BuyerEqualsSeller',\n\t\t'InvalidParameterValue',\n\t\t'InvalidSandboxCustomerEmail',\n\t\t'InvalidSellerId',\n\t\t'UnauthorizedAccess',\n\t\t'UnsupportedCountryOfEstablishment',\n\t\t'UnsupportedCurrency',\n\n\t\t# Runtime errors - These must be resolved before a charge action can occur\n\t\t'DuplicateRequest',\n\t\t'InternalServerError',\n\t\t'InvalidAuthorizationAmount',\n\t\t'InvalidBillingAgreementId',\n\t\t'InvalidBillingAgreementStatus',\n\t\t'InvalidPaymentAction',\n\t\t'PeriodicAmountExceeded',\n\t\t'ProviderNotAuthorized',\n\t\t'ServiceUnavailable'\n\t}\n\tif actionResponseStatusMessage in knownPermissionError:\n\t\tpermissionsError = True\n\t\terrorMessage = config.enablePermission\n\telif actionResponseStatusMessage in knownIntegrationOrRuntimeError:\n\t\terrorMessage = config.errorMessage + config.errorStatusCode + actionResponseStatusCode + '.' + config.errorStatusMessage + actionResponseStatusMessage + '.' + config.errorPayloadMessage + actionResponsePayloadMessage\n\telse:\t\n\t\terrorMessage = config.errorUnknown\n\n\tdebug('handleErrors', request)\n\n\t# If it is a permissions error send a permission consent card to the user, otherwise .speak() error to resolve during testing\n\tif permissionsError:\n\t return statement(errorMessage).consent_card(config.scope)\n\telse:\n\t return statement(errorMessage)\n\n\n# If billing agreement equals any of these states, you need to get the user to update their payment method\n# Once payment method is updated, billing agreement state will go back to OPEN and you can charge the payment method\ndef handleBillingAgreementState( billingAgreementStatus, request):\n\terrorMessage = ''\n\n\tknownStatus = {\n\t\t'CANCELED',\n\t\t'CLOSED',\n\t\t'SUSPENDED'\n\t}\n\tif billingAgreementStatus in knownStatus:\n\t\terrorMessage = config.errorBillingAgreement + billingAgreementStatus + config.errorBillingAgreementMessage\n\telse:\n\t\terrorMessage = config.errorUnknown\n\n\tdebug('handleBillingAgreementState', request)\n\n\treturn statement(errorMessage)\n\n\n# Ideal scenario in authorization decline is that you save the session, allow the customer to fix their payment method, \n# and allow customer to resume session. This is just a simple message to tell the user their order was not placed.\ndef handleAuthorizationDeclines( authorizationStatusReasonCode, request):\n\terrorMessage = ''\n\t\n\tknownReasonCode = {\n\t\t'AmazonRejected',\n\t\t'InvalidPaymentMethod',\n\t\t'ProcessingFailure',\n\t\t'TransactionTimedOut'\n\t} \n\tif authorizationStatusReasonCode in knownReasonCode:\n\t \terrorMessage = config.authorizationDeclineMessage\n\telse:\n\t\terrorMessage = config.errorUnknown\n\n\tdebug('handleAuthorizationDeclines', request)\n\n\treturn statement(errorMessage)\n\n\n# Output object to console for debugging purposes\ndef debug(funcName, request ):\n\tprint('ERROR in %s --- %s\\n' % (funcName, str(request)))\n\n","sub_path":"samples/payment_integration/error_handler.py","file_name":"error_handler.py","file_ext":"py","file_size_in_byte":3498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"257050271","text":"from game_concepts.Cutscene import *\n\nenemy_nr = [0]\n\n# todo do something with weakness and strengths and the battle options\n# todo in screen the armor needs to change when different armor is collected (also the animation)\n# todo tavern cutscene and item\n# todo final boss\n\n\ndef battle(opponent, attack_type):\n # each time a battle event button is chosen (a,b,c) in main it redirects here\n # the attack type is different for each button but for soldiers its always the same\n # its overwritten in the soldier class by inheritance\n # with each battle event button the enemy is set inside the knight or soldier class\n # the speed is determining who goes first\n # the latter is assigned a counter attack and then in update this is checked\n # when it is true there will be a pause before the counter attack is launched\n\n # combat_key_allowed prevents button bashing\n combat_key_allowed[0] = False\n\n cur_pl[0].enemy = opponent\n cur_pl[0].attack_type = attack_type\n opponent.enemy = cur_pl[0]\n if cur_pl[0].speed >= opponent.speed:\n cur_pl[0].attack()\n opponent.counter_attack = True\n else:\n opponent.attack()\n cur_pl[0].counter_attack = True\n\n\nclass Knight(pygame.sprite.Sprite):\n\n def __init__(self, pos, color, image):\n pygame.sprite.Sprite.__init__(self)\n self.color = color\n # is the self.image\n self.image = image\n # defines the rectangle of the image\n self.rect = self.image.get_rect()\n self.rect.center = (tile[pos].get_coordinates()[0] + half_tile_size,\n tile[pos].get_coordinates()[1] + half_tile_size)\n self.pos = pos\n self.new_pos = pos\n self.moving_speed = moving_speed\n self.facing = right\n self.step_count = 0\n self.ticks_wait = 30\n self.last_update = pygame.time.get_ticks()\n self.motion_state = 'staying'\n\n # battle traits\n self.base_attack_damage = 20\n self.speed = 100\n self.base_hp = 100\n\n self.attack_damage = self.base_attack_damage\n self.hp = self.base_hp\n self.visible_hp = self.base_hp\n\n self.enemy_traits_visible = True\n\n # items are also images\n self.weapons = []\n\n self.drink = 0\n\n # for fight/battle screen pos\n self.battle_h_pos = -300\n self.battle_v_pos = 300\n\n self.counter_attack = False\n self.attack_delay = False\n self.attack_type = None\n self.enemy = None\n self.defeated = False\n\n # for slash animation\n self.show_combat_effect = None\n # starting pos for anim\n self.starting_slash_anim_pos_hor = 800 # 800\n self.starting_slash_anim_pos_ver = 60 # made it 60 was 67: screen_height - hud_height - knight_height\n self.combat_effect_pos_hor = self.starting_slash_anim_pos_hor\n self.combat_effect_pos_ver = self.starting_slash_anim_pos_ver\n\n def print_stats(self):\n print(self,\n ' speed:', self.speed,\n ' att:', self.attack_damage,\n ' hp:', self.hp)\n\n def drink(self):\n self.drink += 1\n\n def reset_combat_effect(self):\n # this resets the position of the animations\n self.show_combat_effect = None\n self.combat_effect_pos_hor = self.starting_slash_anim_pos_hor\n self.combat_effect_pos_ver = self.starting_slash_anim_pos_ver\n\n # this is needed to be able to attack again\n if self.counter_attack is False and self.enemy.counter_attack is False:\n combat_key_allowed[0] = True\n\n def add_new_weapon(self, weapon):\n # adds a new item to the knight or soldiers (assigned at the instantiation)\n # sight is a odd one as it allows the player to see the strengths and weaknesses of the soldiers\n # if a weapon is acquired the weapon stats (attack, hp, speed) are added to the knight or soldier\n # if a weapon has -hp only the base_hp a.k.a max_hp is being lowered to prevent from going below 0 when acquired\n\n if weapon is sight_wp:\n self.enemy_traits_visible = True\n else:\n self.weapons.append(weapon)\n self.attack_damage += weapon.attack_damage\n self.speed += weapon.speed\n if weapon.hp < 0:\n self.base_hp += weapon.hp\n else:\n self.hp += weapon.hp\n self.base_hp += weapon.hp\n\n def set_image(self, new_image):\n self.image = new_image\n\n def set_new_pos(self, where):\n # self.pos + where is the same as desired position in direction but i am changing it so that its clear\n self.new_pos = self.pos + where\n self.facing = where\n\n if self == p1:\n self.motion_state = 'moving'\n\n def move(self, side, x=True, y=True, xplus=True, yplus=True):\n # in self.direction(side) a new_pos is set\n # if this is set. moving_logic() that is constantly updating is checking to see if a new poss set\n # by seeing if the current pos is different than the new pos\n # if this is true in move() the new pos tile is checked vs all sides of the player\n # if one of the sides matches (True) the player will be moved to the side until it matches the new_pos\n if self.new_pos == self.pos + side:\n # now starts the movement\n self.motion_state = 'moving'\n # if x is True then horizontal movement\n if x:\n if xplus:\n self.rect.x += self.moving_speed\n else:\n self.rect.x -= self.moving_speed\n # if y is True than vertical movement\n if y:\n if yplus:\n self.rect.y += self.moving_speed\n else:\n self.rect.y -= self.moving_speed\n\n def moving_logic(self):\n # the new_pos is constantly checked by updating it\n # see if current_pos is different than the new_pos.\n if self.pos != self.new_pos:\n # if the moving center equals the new_pos center it stops and exits the loop\n if self.rect.center == (tile[self.new_pos].get_coordinates()[0] + half_tile_size,\n tile[self.new_pos].get_coordinates()[1] + half_tile_size):\n self.motion_state = 'staying'\n self.pos = self.new_pos\n self.step_count += 1\n # if it does not equal the new pos then check the new pos and which side that matches to\n # it will start moving to the side it where the new pos is\n else:\n # within the move function it will check if it matches the new pos\n # see the direction it needs to move\n # l_up | up | r_up\n # left | X | right\n # l_down | down | r_down\n\n # self.move(left, x=True, y=False, xplus=False, yplus=False)\n # is the same as:\n # if self.direction(left):\n # self.rect.x -= moving_speed\n # self.moving = True\n\n self.move(left, x=True, y=False, xplus=False, yplus=False)\n self.move(up, x=False, y=True, xplus=False, yplus=False)\n self.move(right, x=True, y=False, xplus=True, yplus=False)\n self.move(down, x=False, y=True, xplus=False, yplus=True)\n self.move(l_up, x=True, y=True, xplus=False, yplus=False)\n self.move(r_up, x=True, y=True, xplus=True, yplus=False)\n self.move(l_down, x=True, y=True, xplus=False, yplus=True)\n self.move(r_down, x=True, y=True, xplus=True, yplus=True)\n\n def direction(self, where):\n desired_pos = self.pos + where\n\n # can't walk to top map limit\n if desired_pos < 0:\n print('Can\\'t go there')\n\n # can't walk to left map limit\n elif self.pos % tiles_amount_width == 0 \\\n and desired_pos % tiles_amount_width == tiles_amount_width - 1:\n print('Can\\'t go there')\n\n # can't walk to right map limit\n elif self.pos % tiles_amount_width == tiles_amount_width - 1 \\\n and desired_pos % tiles_amount_width == 0:\n print('Can\\'t go there')\n\n # can't walk to bottom map limit\n elif self.pos >= (amount_tiles - tiles_amount_width) \\\n and desired_pos >= amount_tiles:\n print('Can\\'t go there')\n\n # this allows mob to walk in an obstacle (castle)\n elif cur_pl[0] == mob1:\n self.set_new_pos(where)\n\n # can't walk into obstacles but certain obstacles create cutscene\n elif desired_pos in mapfile.map_obstacles:\n\n # House is a special obstacle\n if desired_pos in mapfile.house_obstacles:\n # wanted to use a lambda function even though not needed. checks to see\n # if step_count + 1 and 2 and 3 not in turn_enemy_spawn\n check = (lambda x: x + self.step_count not in turn_enemy_spawn)\n if check(3) and check(2) and check(1):\n if self.hp < self.base_hp:\n self.step_count += 3\n to_cutscene(house_cutscene1)\n self.hp += (self.base_hp - self.hp)\n else:\n print('Your hp is high enough')\n else:\n print('You hear something closing in! Be on your guard')\n\n # Well is a special obstacle\n elif desired_pos in mapfile.well_obstacles:\n if self.step_count + 1 < turn_enemy_spawn[0]:\n if self.hp < self.base_hp:\n self.step_count += 1\n to_cutscene(well_cutscene1)\n if self.hp <= (self.base_hp - 20):\n self.hp += 20\n else:\n self.hp += (self.base_hp - self.hp)\n else:\n print('You hp is high enough')\n\n # still to fix\n else:\n print('You hear something closing in! Be on your guard')\n # cur_pl[0].step_count + 1 >= turn_enemy_spawn[0]:\n\n # self.draw_text(hud_font, 'You hear something closing in! Be on your guard!', 100,\n # int(screen_height - (screen_height / 7)), yellow, hudwindow=True)\n\n # Well is a special obstacle\n elif desired_pos in mapfile.tavern_obstacles:\n to_cutscene(tavern_cutscene1)\n if self.drink == 0:\n print('drink')\n elif self.drink == 1:\n print('Your confidence is rising')\n tavern_cutscene1.text = 'Your confidence is rising'\n self.hp += 10\n self.visible_hp += 10\n elif self.drink == 2:\n print('You feel almighty! and a bit tipsy?')\n tavern_cutscene1.text = 'You feel almighty! and a bit tipsy?'\n self.speed -= 10\n self.hp += 20\n self.visible_hp += 20\n elif self.drink == 3:\n tavern_cutscene1.text = 'You overheard a conversation about soldiers'\n self.add_new_weapon(sight_1)\n elif self.drink == 4:\n tavern_cutscene1.text = 'You don\\'t feel so good and decide to call it a night'\n self.speed += 10\n self.hp -= 20\n self.visible_hp -= 20\n elif self.drink > 4:\n tavern_cutscene1.text = 'You should probably head out'\n\n else:\n # set the new pos\n # this causes p1 to move to the given pos\n self.set_new_pos(where)\n # After the new pos is set the moving_logic keeps checking if it is different\n\n def motion(self):\n if self == p1:\n if self.motion_state == 'moving':\n knight_animation[0] = animation_walking_obj[return_int_for_side[self.facing]]\n elif self.motion_state == 'staying':\n knight_animation[0] = animation_staying_obj[return_int_for_side[self.facing]]\n\n def defeat(self):\n # when the defeated bool is set to true, in update the defeat function is triggered\n # this checks to see who is defeated and what the follow up should be\n # the weapon that the soldier had is taken by the player\n # counter attack is set to false for the next battle\n # for soldiers here is where it moves on from the defeated soldier to the next the enemy_nr[0] += 1\n\n if self == cur_pl[0]:\n to_cutscene(game_over_cutscene)\n elif self == mob1:\n print('you won')\n # to_cutscene(win)\n elif self == soldier_lst[enemy_nr[0]]:\n cur_pl[0].add_new_weapon(soldier_lst[enemy_nr[0]].weapons[0])\n\n print('adding new weapon to player', soldier_lst[enemy_nr[0]].weapons[0].weapon_type)\n cur_pl[0].print_stats()\n print(' + weapon stats: ')\n soldier_lst[enemy_nr[0]].weapons[0].print_weapons_stats()\n\n cur_pl[0].counter_attack = False\n enemy_nr[0] += 1\n back_to_board() # has combat_key_allowed[0] = True\n\n def attack(self):\n # for the slash effect\n self.show_combat_effect = self.attack_type\n\n # if enemy has hp after attack\n if self.enemy.hp - self.attack_damage > 0:\n self.enemy.hp -= self.attack_damage\n\n # if enemy has 0 hp after attack\n else:\n self.enemy.hp = 0\n self.enemy.defeated = True\n\n def update(self):\n self.moving_logic()\n self.motion()\n # for hp display\n now = pygame.time.get_ticks()\n if now - self.last_update > self.ticks_wait:\n self.last_update = now\n\n if self.attack_delay:\n self.ticks_wait = 30\n if self.counter_attack:\n self.attack()\n # reset\n self.counter_attack = False\n # reset\n self.attack_delay = False\n\n elif self.attack_delay is False:\n if self.visible_hp < self.hp:\n self.visible_hp += 1\n elif self.visible_hp > self.hp:\n self.visible_hp -= 1\n elif self.visible_hp == self.hp:\n if self.defeated:\n self.defeat() # has combat_key_allowed[0] = True\n elif self.counter_attack:\n self.ticks_wait = 1000\n self.attack_delay = True\n\n\nclass Mob(Knight):\n\n def __init__(self, pos):\n super().__init__(pos, color=red, image=boss_left)\n pygame.sprite.Sprite.__init__(self)\n self.moving_speed = 2\n\n self.attack_type = 'Attack back'\n\n\nclass Soldier(Knight):\n\n def __init__(self, pos, color, image, weapon):\n super().__init__(pos, color, image)\n pygame.sprite.Sprite.__init__(self)\n\n # unique to Soldiers for now\n self.strength_txt = ''\n self.weakness_txt = ''\n\n self.attack_type = 'Attack back'\n # self.weapon = weapon\n self.add_new_weapon(weapon)\n\n # if self.item == armor_1:\n # self.strength_txt = 'Armor'\n # self.weakness_txt = 'Speed'\n # elif self.item == shield_1:\n # self.strength_txt = 'Defense'\n # self.weakness_txt = None\n # elif self.item == sword_1:\n # self.strength_txt = 'Attack'\n # self.weakness_txt = None\n # elif self.item == speed_1:\n # self.strength_txt = 'Speed & Attack'\n # self.weakness_txt = 'Defense'\n # elif self.item == courage_1:\n # self.strength_txt = 'Speed & Defense'\n # self.weakness_txt = 'Attack'\n # elif self.item == toughness_1:\n # self.strength_txt = 'Attack & Defense'\n # self.weakness_txt = 'Speed'\n # elif self.item == armor_2:\n # self.strength_txt = 'Armor'\n # self.weakness_txt = 'Speed'\n # elif self.item == shield_2:\n # self.strength_txt = 'Defense'\n # self.weakness_txt = None\n # elif self.item == sword_2:\n # self.strength_txt = 'Attack'\n # self.weakness_txt = None\n\n if self.color == yellow:\n self.rank = 1\n self.rank_txt = 'Yellow'\n self.attack_damage -= 10\n elif self.color == blue:\n self.rank = 2\n self.rank_txt = 'Blue'\n # default self.attack_damage = 20\n elif self.color == red:\n self.rank = 3\n self.rank_txt = 'Red'\n self.attack_damage += 10\n\n # Not unique but different than Knights\n self.facing = left\n\n self.battle_h_pos = screen_width\n self.battle_v_pos = 800\n\n\nclass Weapon:\n\n def __init__(self, weapon_type, image, att=0, spd=0, hp=0):\n self.weapon_type = weapon_type\n self.image = image\n self.attack_damage = att\n self.speed = spd\n self.hp = hp\n\n # self.enemy_traits_visible = True\n\n def weapon_stats(self):\n return self.attack_damage, self.speed, self.hp\n\n def print_weapons_stats(self):\n print(self.weapon_type,\n ' speed:', self.speed,\n ' att:', self.attack_damage,\n ' hp:', self.hp)\n\n\nsword_wp_1 = Weapon('Sword', sword_1, att=10)\nsword_wp_2 = Weapon('S Sword', sword_1, att=20)\nshield_wp_1 = Weapon('Shield', shield_1, hp=20)\nshield_wp_2 = Weapon('S Shield', shield_2, hp=40)\narmor_wp_1 = Weapon('Armor', armor_1, spd=-10, hp=30)\narmor_wp_2 = Weapon('S Armor', armor_2, spd=-20, hp=60)\nspeed_wp = Weapon('Speed', speed_1, att=10, spd=20, hp=-20)\ncourage_wp = Weapon('Courage', courage_1, att=-10, spd=20, hp=20)\ntoughness_wp = Weapon('Toughness', toughness_1, att=10, spd=-20, hp=20)\nsight_wp = Weapon('Sight', sight_1)\n\n\nsoldier_1 = Soldier(tile_coor(3, 12), yellow, yellow_knight, weapon=armor_wp_1)\nsoldier_2 = Soldier(tile_coor(3, 13), yellow, yellow_knight, weapon=shield_wp_1)\nsoldier_3 = Soldier(tile_coor(3, 14), yellow, yellow_knight, weapon=sword_wp_1)\n\nsoldier_4 = Soldier(tile_coor(3, 15), blue, blue_knight, weapon=toughness_wp)\nsoldier_5 = Soldier(tile_coor(3, 16), blue, blue_knight, weapon=courage_wp)\nsoldier_6 = Soldier(tile_coor(3, 17), blue, blue_knight, weapon=speed_wp)\n\nsoldier_7 = Soldier(tile_coor(3, 18), red, red_knight, weapon=armor_wp_2)\nsoldier_8 = Soldier(tile_coor(3, 19), red, red_knight, weapon=shield_wp_2)\nsoldier_9 = Soldier(tile_coor(3, 20), red, red_knight, weapon=sword_wp_2)\n\nsoldier_lst_T1 = [soldier_1, soldier_2, soldier_3]\nsoldier_lst_T2 = [soldier_4, soldier_5, soldier_6]\nsoldier_lst_T3 = [soldier_7, soldier_8, soldier_9]\n\nsoldier_lst = []\n\n\ndef add_to_lst(lst):\n random.shuffle(lst)\n for s in lst:\n soldier_lst.append(s)\n\n\nadd_to_lst(soldier_lst_T1)\nadd_to_lst(soldier_lst_T2)\nadd_to_lst(soldier_lst_T3)\n\np1 = Knight(tile_start_players[0], red, default_knight)\n\n\"\"\"\np2 = Knights(yellow, default_knight, tile_start_players[1])\np3 = Knights(blue, default_knight, tile_start_players[2])\np4 = Knights(black, default_knight, tile_start_players[3])\n\"\"\"\n\nmob1 = Mob(tile_start_mob[0])\n\nif __name__ == \"__main__\":\n pass\n # print(soldier_1.rank_txt)\n","sub_path":"game_concepts/Factions.py","file_name":"Factions.py","file_ext":"py","file_size_in_byte":19660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"600447967","text":"# -*- coding: utf-8 -*-\n\n# 国際化の手順 --------------------------------------------------->\n# 国際化対応のコードを書く\n# コードから翻訳対象を抽出する\n# 翻訳対象を言語ごとに翻訳する\n# 翻訳したものをコンパイルする\n# コンパイルしたものを国際化対応のコードで利用する\n\n\n# gettextモジュール\n# pythonでは、babel モジュールのセットアップ\n# $ easy_install babel\n\n# 国際化対応のコードを書く\nimport gettext\n# 翻訳インスタンスの作成\nt = gettext.translation('message', '.', languages=('ja',))\n_ = t.ugettext # 翻訳対象を指定する関数のエイリアス\nprint(_(\"Hello\"))\n\n\n\n# 翻訳ファイルを作る\n# $ pybabel extract -o ./28_international.pot .\n# pybabel extract -o 抽出結果のファイルコードのディレクトリ\n# potファイルができる\n\n\n\n# 翻訳対象を言語ごとに翻訳する\n# pybabel init -i 抽出結果のファイル -d 翻訳ファイルのルートディレクトリ -l 言語\n# ja -> LC_MESSAGE -> messages.po\n\n\n\n# 翻訳したものをコンパイルする\n# pybabel compile -d . -l ja\n# pybabel compile -d 翻訳ファイルのルートディレクトリ -l 言語\n# ja -> LC_MESSAGE -> messages.mo\n\n\n\n# コンパイルしたものを国際か対応コードで利用する\n\n","sub_path":"python_ex/refer/28_international.py","file_name":"28_international.py","file_ext":"py","file_size_in_byte":1342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"23671999","text":"#############\n# This script is for part 2 of my prompt to give some 2d visualization.\n# I hope to have it visually update itself throughout the years, but due to time constraints version 1 will have it be static. (2d-BasicHistogram.py)\n#\n# Author: Clay Bellou\n#############\n\nimport sys\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\ncolor1 = \"blue\"\ncolor2 = \"orange\"\n\n# Handle the color-picking accessibility option!\nif len(sys.argv) == 2:\n print(\"To few color arguments! Using default colors\")\nelif len(sys.argv) == 3:\n print(\"Using colors \",sys.argv[1], \" and \", sys.argv[2], \" instead of the default colors!\")\n print(\"(Default colors for this visualization are blue and orange)\")\n color1 = sys.argv[1]\n color2 = sys.argv[2]\nelif len(sys.argv) > 3:\n print(\"To many color arguments! Using default colors\")\n\n#read database files into a table in memory\nearthquakes = pd.read_csv(\"EarthquakeDataWithCountries.csv\")\nsuicides = pd.read_csv(\"SuicideDataContriesConverted.csv\")\n\ntargetCountriesList = [\"United States\",\"Russia\",\"Japan\",\"Mexico\",\"Chile\",\"New Zealand\",\"Australia\"]\n\n############ Begin Earthquake data calculations ####################################\nearthquake_avg_magnitude_country = dict()\nearthquake_total_country = dict()\nearthquake_2d_array = dict()\ngraph_earthquake_array = [0.0] * len(targetCountriesList)\ngraph_total_earthquake_array = [0] * len(targetCountriesList)\nfor country in targetCountriesList:\n earthquake_2d_array[country] = []\n earthquake_total_country[country] = 0\n earthquake_avg_magnitude_country[country] = float(0.0)\n\n# Fill the 2d array with all magnitude values for earthquakes in each country.\ncount = 0\nfor rowCountryRaw in earthquakes['country']:\n if count != 0:\n validCountry = 0\n rowCountry = str(rowCountryRaw)\n for targetCountry in targetCountriesList:\n if rowCountry == targetCountry:\n validCountry = 1\n break\n if validCountry == 1:\n magnitude = float(earthquakes['Magnitude'].iloc[count])\n earthquake_2d_array[rowCountry].append(magnitude)\n earthquake_total_country[rowCountry] += 1\n\n count += 1\n\n\n#calculate average for each country using all magnitude values in 2d array\nindex = 0\nfor country in targetCountriesList:\n totalNum = len(earthquake_2d_array[country])\n total = float(0.0)\n for magnitudeStr in earthquake_2d_array[country]:\n total += float(magnitudeStr)\n average = total / float(totalNum)\n earthquake_avg_magnitude_country[country] = average\n graph_earthquake_array[index] = average\n graph_total_earthquake_array[index] = earthquake_total_country[country]\n index += 1\n\n\n########### Begin Suicide data calculations ######################################################\nsuicides_avg_per_country = dict()\nsuicide_2d_array = dict()\ngraph_suicide_array = [0.0] * len(targetCountriesList)\n\nfor country in targetCountriesList:\n suicide_2d_array[country] = []\n suicides_avg_per_country[country] = float(0.0)\n\n# Fill the 2d array with all suicides per 100k pop for each country\ncount = 0\nfor rowCountryRaw in suicides['country']:\n if count != 0:\n rowCountry = str(rowCountryRaw)\n validCountry = 0\n for targetCountry in targetCountriesList:\n if rowCountry == targetCountry:\n validCountry = 1\n break\n if validCountry == 1:\n suicide_2d_array[rowCountry].append(float(suicides['suicides/100k pop'].iloc[count]))\n count += 1\n\n\n#calculate average for each country using all suicide float values in 2d array\nindex = 0\nfor country in targetCountriesList:\n totalNum = len(suicide_2d_array[country])\n total = float(0.0)\n for suicideStr in suicide_2d_array[country]:\n total += float(suicideStr)\n average = total / float(totalNum)\n suicides_avg_per_country[country] = average\n graph_suicide_array[index] = average\n index += 1\n\n########### Begin plotting/animating the graph #############\nfig = plt.figure(figsize=(12,6))\n#creating a subplot\nax1 = fig.add_subplot(1,1,1)\n\n# This and 2 lines below will be used to make the graph visually transition through the years, if time permits.\n# Currently does nothing and isn't fleshed out.\ndef animate(i):\n ax1.clear()\n\n np.linspace\n\n plot1Color = color1\n plot2Color = color2\n\n # Histogram of average magnitude of all earthquakes in each country\n # plt.hist(targetCountriesList,weights=graph_earthquake_array, label=\"total earthquakes\", color=plot1Color,bins=2020,alpha=0.5,ec='black',width=0.9,align='right')\n # Histogram of total earthquakes in each country\n plt.hist(targetCountriesList, weights=graph_total_earthquake_array, label=\"total earthquakes\", color=plot1Color,\n bins=2020, alpha=0.5, ec='black', width=0.9, align='right')\n\n plt.axis([-1, len(targetCountriesList), 0, 2500])\n plt.xlabel('Country', fontsize=14)\n ax1.set_xticks(np.arange(len(targetCountriesList)))\n ax1.set_xticklabels(targetCountriesList)\n plt.ylabel('Total Earthquakes Per Country since 1985', color=plot1Color, fontsize=14)\n plt.legend(loc='upper left')\n plt.title('Side-By-Side of Total Earthquakes and Suicides per 100k Population Over the Years')\n\n plot2 = plt.twinx()\n plot2.hist(targetCountriesList, weights=graph_suicide_array, label=\"suicides per 100k pop\", color=plot2Color,\n bins=2020, alpha=0.5, ec='black', width=0.9, align='right')\n plot2.set_ylabel(\"Average Suicides per 100k Population since 1985\", color=plot2Color, fontsize=14)\n plot2.set_xticks(np.arange(len(targetCountriesList)))\n plot2.set_xticklabels(targetCountriesList)\n plt.axis([-1, len(targetCountriesList), 0, 40])\n plot2.legend(loc='upper right')\n\nani = animation.FuncAnimation(fig, animate, interval=1000)\nplt.show()\n\n\n\nplt.show()","sub_path":"2d-UpdatingHistogram.py","file_name":"2d-UpdatingHistogram.py","file_ext":"py","file_size_in_byte":5911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"204321280","text":"import requests\nimport json\nimport matplotlib.pyplot as plot\nimport time\nimport sys\n\ndef pretty_print_POST(req):\n print('{}\\n{}\\n{}\\n\\n{}'.format(\n '-----------POST Request-----------',\n req.method + ' ' + req.url,\n '\\n'.join('{}: {}'.format(k, v) for k, v in req.headers.items()),\n req.body,\n ))\n\ndef parseValue(data):\n\tfor res in data:\n\t\tif res is None:\n\t\t\tprint(\"Skipped\")\n\t\t\tcontinue\n\t\ttry:\n\t\t\treturn res[\"Value\"]\n\t\texcept:\n\t\t\tprint(\"Exception when parsing value\")\n\t\t\tprint(\"Bad Response:\")\n\t\t\tprint(res)\n\t\t\tprint(\"Complete Data:\")\n\t\t\tprint(data)\t\n\n# #GET request working\n# print(\"-----------GET Request-----------\")\n# r_get = requests.Request('GET', \"http://localhost/ODataConnector/rest/RealtimeData?PointName=svrsim:sine double med -100 100\")\n# prepared = r_get.prepare()\n# s = requests.Session()\n# res = s.send(prepared)\n# print(res.text)\n\nheaders = {\n'Content-Type': 'application/json',\n'Host' : 'localhost',\n'Connection' : 'keep-alive',\n'Cache-Control' : 'no-cache',\n'Accept' : '*/*',\n'Accept-Encoding' : 'gzip, deflate, bar',\n'Accept-Language' : 'en-US,en;q=0.8',\n'User-Agent' : 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'\n}\n#POST request to get an example value, defined header\n# r_post = requests.Request('POST', \"http://localhost/ODataConnector/rest/RealtimeData\", headers = headers, data=json.dumps(payload))\n# prepared = r_post.prepare()\n# pretty_print_POST(prepared)\n# s = requests.Session()\n# res = s.send(prepared)\n# print(res.text)\n\ndef startSimulation(start):\n\tstart = int(start)\n\tpayload = [ { \"PointName\": \"@Matrikon.OPC.Simulation.1\\\\EPSimServer.EnergyPlus.Control.Start.Value\", \"Value\": start }]\n\tr = requests.post(\"http://localhost/ODataConnector/rest/RealtimeData/Write\", headers= headers, data = json.dumps(payload))\n\ndef control_bridge(value):\n\tpayload = [ { \"PointName\": \"@Matrikon.OPC.Simulation.1\\\\EPSimServer.EnergyPlus.Control.Status.Value\", \"Value\": value }]\n\tr = requests.post(\"http://localhost/ODataConnector/rest/RealtimeData/Write\", headers= headers, data = json.dumps(payload))\n\ndef write_time(time):\n\tpayload = [ { \"PointName\": \"@Matrikon.OPC.Simulation.1\\\\EPSimServer.EnergyPlus.Control.TimeStep.Value\", \"Value\": time }]\n\tr = requests.post(\"http://localhost/ODataConnector/rest/RealtimeData/Write\", headers= headers, data = json.dumps(payload))\n\ndef write_days(days):\n\tpayload = [ { \"PointName\": \"@Matrikon.OPC.Simulation.1\\\\EPSimServer.EnergyPlus.Control.SimDays.Value\", \"Value\": days }]\n\tr = requests.post(\"http://localhost/ODataConnector/rest/RealtimeData/Write\", headers= headers, data = json.dumps(payload))\n\n\ndef write_cw_lil_clg(cw, lil, clg):\n\tpayload = [ { \"PointName\": \"@Matrikon.OPC.Simulation.1\\\\EPSimServer.EnergyPlus.Inputs.clgsetp.Value\", \"Value\": clg }, \n\t{ \"PointName\": \"@Matrikon.OPC.Simulation.1\\\\EPSimServer.EnergyPlus.Inputs.lilsetp.Value\", \"Value\": lil },\n\t{ \"PointName\": \"@Matrikon.OPC.Simulation.1\\\\EPSimServer.EnergyPlus.Inputs.cwsetp.Value\", \"Value\": cw }]\n\tr = requests.post(\"http://localhost/ODataConnector/rest/RealtimeData/Write\", headers= headers, data = json.dumps(payload))\n\ndef write_everything(cw, lil, clg, time):\n\tpayload = [ { \"PointName\": \"@Matrikon.OPC.Simulation.1\\\\EPSimServer.EnergyPlus.Inputs.clgsetp.Value\", \"Value\": clg }, \n\t{ \"PointName\": \"@Matrikon.OPC.Simulation.1\\\\EPSimServer.EnergyPlus.Inputs.lilsetp.Value\", \"Value\": lil },\n\t{ \"PointName\": \"@Matrikon.OPC.Simulation.1\\\\EPSimServer.EnergyPlus.Inputs.cwsetp.Value\", \"Value\": cw },\n\t{ \"PointName\": \"@Matrikon.OPC.Simulation.1\\\\EPSimServer.EnergyPlus.Control.TimeStep.Value\", \"Value\": time }]\n\tr = requests.post(\"http://localhost/ODataConnector/rest/RealtimeData/Write\", headers= headers, data = json.dumps(payload))\n\n\ndef get_power():\n\tr_get = requests.get(\"http://localhost/ODataConnector/rest/RealtimeData?PointName=@Matrikon.OPC.Simulation.1\\\\EPSimServer.EnergyPlus.Outputs.WholeBuilding.FacilityTotalElectricDemandPower.Value\")\n\tdata = json.loads(r_get.text)\n\treturn parseValue(data)\n\n\n\ndef get_status():\n\tr_get = requests.get(\"http://localhost/ODataConnector/rest/RealtimeData?PointName=@Matrikon.OPC.Simulation.1\\\\EPSimServer.EnergyPlus.Control.Status.Value\")\n\tdata = json.loads(r_get.text)\n\treturn parseValue(data)\n\n\ndef get_sim_time():\n\tr_get = requests.get(\"http://localhost/ODataConnector/rest/RealtimeData?PointName=@Matrikon.OPC.Simulation.1\\\\EPSimServer.EnergyPlus.Outputs.EMS.TimeOfDay.Value\")\n\tdata = json.loads(r_get.text)\n\treturn parseValue(data)\n\n\ndef get_sim_day():\n\tr_get = requests.get(\"http://localhost/ODataConnector/rest/RealtimeData?PointName=@Matrikon.OPC.Simulation.1\\\\EPSimServer.EnergyPlus.Outputs.EMS.DayOfWeek.Value\")\n\tdata = json.loads(r_get.text)\n\treturn parseValue(data)\n\ndef sim_total_days():\n\tr_get = requests.get(\"http://localhost/ODataConnector/rest/RealtimeData?PointName=@Matrikon.OPC.Simulation.1\\\\EPSimServer.EnergyPlus.Control.SimDays.Value\")\n\tdata = json.loads(r_get.text)\n\treturn parseValue(data)\n\n\nif len(sys.argv) > 1 :\n\tstart = time.clock()\n\tstatus = int(get_status())\n\tend = time.clock()\n\tprint(end-start)\n\tcommand = sys.argv[1]\n\n\tif command == \"setup\":\n\t\tif status is 2 or status is 1:\n\t\t\tcontrol_bridge(3)\n\t\t\ttime.sleep(2)\n\t\tcontrol_bridge(0)\n\t\tprint(\"Bridge is Ready\")\n\telif command == \"close\":\n\t\tcontrol_bridge(3)\n\t\tprint(\"Bridge has been Closed\")\n\telif command == \"kill\":\n\t\tcontrol_bridge(4)\n\t\tprint(\"Bridge has been Burned\")\n\t\ttime.sleep(2)\n\t\tcontrol_bridge(0)\n\telif command == \"days\":\n\t\tnum_days = int(sys.argv[2])\n\t\twrite_days(num_days)\n\t\tprint(\"Number of Simulation Days: \" + str(num_days))\n\n\nelse:\n\tstatus = int(get_status())\n\tprint(status)\n\tif status is not 0:\n\t\tprint(\"Bridge is not Ready. Call setup first before running the simulation\")\n\t\tsys.exit(0)\n\tcontrol_bridge(1)\n\ttimeSteps = 0\n\twrite_time(timeSteps)\n\toutputs = []\n\ttimes = []\n\tday = 0\n\ti = 0\n\tsum_write_time = 0.0\n\tsum_read_time = 0.0\t\n\tsum_time_time = 0.0\n\n\tstart_sim_time = time.clock()\n\tdays = int(sim_total_days())\n\n\ttimeSteps = 0\n\twhile timeSteps < 288 * days:\n\t\tif timeSteps % 12 == 0:\n\t\t\tprint(timeSteps)\n\n\n\t\t# print(\"Grabbing Time\")\n\t\t# sim_day = get_sim_day()\n\t\t# sim_time = get_sim_time()\n\t\t# if sim_day is not None or sim_time is not None:\n\t\t# \tsim_day = int(sim_day)\n\t\t# \tif day is not sim_day:\n\t\t# \t\tprint(\"New Day: \" + str(sim_day) + \" \" + str(timeSteps))\n\t\t# \t\tday = sim_day\n\n\t\t# \ttimes.append(sim_time)\n\t\t# \tif sim_time.is_integer():\n\t\t# \t\tprint(\"Hour: \" + str(sim_time) + \" \" + str(timeSteps))\n\n\n\t\tstart_w = time.clock()\n\n\t\tif timeSteps % 288 < 12 * 14:\n\t\t\twrite_everything(6.3, 0.8, 26, timeSteps)\n\t\telif timeSteps % 288 < 12 * 16:\n\t\t\twrite_everything(8, 0.8, 28, timeSteps)\n\t\telse:\n\t\t\twrite_everything(6.3, 0.8, 26, timeSteps)\n\t\t\n\n\n\n\n\t\tend_w = time.clock()\n\t\tsum_write_time = sum_write_time + (end_w-start_w)\n\t\ti = i+1\n\n\t\t# start_t = time.clock()\n\t\t# write_time(timeSteps)\n\t\t# end_t = time.clock()\n\t\t# sum_time_time = sum_time_time + (end_t - start_t)\t\t\n\t\ttimes.append(timeSteps)\n\t\ttimeSteps = timeSteps + 1\n\n\n\t\tstart_r = time.clock()\n\t\t\n\n\t\tpower = get_power()\n\t\toutputs.append(power)\n\n\n\n\t\tend_r = time.clock()\t\t\n\t\tsum_read_time = sum_read_time + (end_r - start_r)\n\t\toutputs.append(power)\n\n\tend_sim_time = time.clock()\n\tcontrol_bridge(2)\n\tplot.plot(outputs)\n\tplot.show()\n\n\tprint(\"AVERAGE Write Time: \" + str(sum_write_time/float(i)))\n\tprint(\"AVERAGE Read Time: \" + str(sum_read_time/float(i)))\t\n\tprint(\"AVERAGE Time Time: \" + str(sum_time_time/float(i)))\n\tprint(\"Total Simulation Time: \" + str(end_sim_time-start_sim_time))\n\n\n#POST request to write 2 values, to a different URL\n# r_post = requests.Request('POST', \"http://localhost/ODataConnector/rest/RealtimeData/Write HTTP/1.1\", headers = headers, data=json.dumps(payload))\n# pretty_print_POST(prepared)\n# s = requests.Session()\n# res = s.send(prepared)\n# print(res.text)","sub_path":"odata-test.py","file_name":"odata-test.py","file_ext":"py","file_size_in_byte":7833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"443966461","text":"\"\"\"\nImplementation of the adaptive voter model as presented in\n\nHolme, Petter, and M. E. J. Newman. “Nonequilibrium Phase Transition in the\nCoevolution of Networks and Opinions.” Physical Review E 74, no. 5 (November\n10, 2006): 056108. https://doi.org/10.1103/PhysRevE.74.056108.\n\"\"\"\nfrom itertools import combinations\nimport numpy as np\nimport networkx as nx\nfrom collections import Counter\nimport os\nimport shutil\n\n\nclass AVM():\n \"\"\"Implementation of the adaptive voter model.\"\"\"\n\n def __init__(self, N=100, M=250, G=8, phi=0, noise_level = 0):\n \"\"\"\n Initialize a random network topology with the specified parameters.\n\n Parameters\n ----------\n\n N : int\n The number of nodes in the network.\n M : int\n The number of edges in the network.\n G : int\n The number of possible opinions.\n phi : float\n The rewiring probability.\n \"\"\"\n # Set up the network, i.e., neighborhood structure\n possible_edges = np.array(list(combinations(range(N), 2)))\n edges = possible_edges[np.random.choice(len(possible_edges), M, replace=False)]\n\n graph = nx.Graph(phi=phi)\n graph.add_nodes_from(range(N))\n graph.add_edges_from(edges)\n\n opinions = {i: np.random.randint(G) for i in range(N)}\n nx.set_node_attributes(graph, opinions, 'opinion')\n\n self._graph = graph\n self._steps = 0\n self.noise_level = noise_level\n self.G = G\n\n\n def current_number_of_opinions(self):\n \"\"\"The number of opinions still present in the network.\n\n Returns\n -------\n int\n The number of remaining opinions.\n \"\"\"\n opinions = [data for node, data in self._graph.nodes(data='opinion')]\n return len(set(opinions))\n\n\n def is_consensus(self):\n \"\"\"Check if the model has converged into its consensus state.\n\n Consensus is reached if only one opinion is left or the network\n fragments into disconnected components with one unique opinion each.\n\n Returns\n -------\n bool\n True if consensus is reached, False otherwise\n \"\"\"\n graph = self._graph\n\n for i, j in graph.edges():\n if graph.nodes[i]['opinion'] != graph.nodes[j]['opinion']:\n return False\n\n return True\n\n\n def _one_update(self):\n \"\"\"\n Perform one update for one randomly selected pair of nodes i and j.\n\n With probability phi the link between i and j is removed if their\n opinions differ and a new link is established between i and a\n previously disconnected node k such that i and k have the same opinion.\n\n With probability 1-phi i copies the opinion of j.\n \"\"\"\n graph = self._graph\n self._steps += 1\n\n # Pick one node at random\n active_node = np.random.choice(graph.nodes())\n active_opinion = graph.nodes[active_node]['opinion']\n\n if not graph.degree(active_node):\n return\n\n # Pick one neighbor at random\n nbs = graph[active_node]\n random_nbr = np.random.choice(list(nbs))\n\n # Rewire the network structure with probability 'phi'\n if np.random.random() < graph.graph[\"phi\"]:\n\n # Get the set of unconnected neighbors with same opinion\n new_neighbor = []\n for node, data in graph.nodes(data='opinion'):\n if (data == active_opinion) and (node not in nbs) and (node != active_node):\n new_neighbor.append(node)\n\n if not new_neighbor:\n return\n\n # Select a new neighbor with same opinion at random and update\n # network\n new_neighbor = np.random.choice(new_neighbor)\n\n graph.remove_edge(active_node, random_nbr)\n graph.add_edge(active_node, new_neighbor)\n\n # Update opinions with probability 1-phi\n else:\n graph.nodes[active_node]['opinion'] = graph.nodes[random_nbr]['opinion']\n\n # change opinion at random\n if np.random.random() < self.noise_level:\n graph.nodes[active_node]['opinion'] = np.random.randint(self.G)\n\n\n def number_of_cross_links(self):\n graph = self._graph\n count = 0\n for i, j in graph.edges():\n if graph.nodes[i]['opinion'] != graph.nodes[j]['opinion']:\n count += 1\n\n return count\n\n\n def run(self, steps=1000):\n \"\"\"\n Integrate the model forward.\n\n Parameters\n ----------\n steps : int\n The number of integration steps.\n \"\"\"\n if not steps:\n steps = self.number_of_cross_links()\n print(\"#steps not specified. Intelligently using \", steps, \"steps\")\n\n for _ in range(steps):\n self._one_update()\n\n\n def current_steps(self):\n \"\"\"\n The current number of total integration steps.\n\n Returns\n -------\n int\n The current number of total integration steps.\n \"\"\"\n return self._steps\n\n\n def cluster_size_distribution(self):\n \"\"\"\n The frequency of cluster sizes.\n\n Returns\n -------\n dict\n Keys are the size of a cluster, corresponding values give the\n frequency of that cluster size.\n \"\"\"\n opinions = [data for _, data in self._graph.nodes(data='opinion')]\n frequency = Counter(opinions)\n size_distribution = Counter(frequency.values())\n return dict(size_distribution)\n\n\n def get_opinions(self):\n return [self._graph.nodes[n]['opinion'] for n in self._graph.nodes()]\n\n \n def get_edgelist(self):\n return self._graph.edges()\n\n\ndef main():\n\n filename = \"adaptive_voter_model_phi0\"\n \n if not os.path.exists(\"output/\"+filename):\n os.makedirs(\"output/\"+filename)\n\n # The same settings as in the Paper\n N = int(3200/16)\n M = int(6400/16)\n gamma = 10\n G = int(N / gamma)\n\n if filename == \"adaptive_voter_model_phi0\":\n phi = 0\n steps = N\n elif filename == \"secretmodel2\":\n phi = 1\n steps = 250\n elif filename == \"secretmodel3\":\n phi = 0.25\n steps = 2500\n elif filename == \"secretmodel4\":\n phi = 0.75\n steps = 500\n\n foldername = \"output/\" + filename + \"/\"\n if os.path.exists(foldername):\n shutil.rmtree(foldername)\n os.makedirs(foldername)\n \n filename = foldername + filename\n\n print(phi, steps)\n model = AVM(N=N, M=M, G=G, phi=phi)\n\n counter = 0\n np.savetxt(filename+'_opinions_t{0}.txt'.format(counter), model.get_opinions(), fmt=\"%i\")\n np.savetxt(filename+'_edges_t{0}.txt'.format(counter), model.get_edgelist(), fmt=\"%i\")\n\n while not model.is_consensus():\n counter += 1\n model.run(steps=steps)\n print(counter, model.current_steps(), model.current_number_of_opinions())\n np.savetxt(filename+'_opinions_t{0}.txt'.format(counter), model.get_opinions(), fmt=\"%i\")\n np.savetxt(filename+'_edges_t{0}.txt'.format(counter), model.get_edgelist(), fmt=\"%i\")\n\n print(Counter(model.get_opinions()))\n #print(model.cluster_size_distribution())\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"data/Synthetisch/avm_final_5k/adaptive_voter_model.py","file_name":"adaptive_voter_model.py","file_ext":"py","file_size_in_byte":7292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"324381879","text":"# coding=utf-8\n\nfrom pyspark import SparkContext\nfrom pyspark.sql import HiveContext\nfrom pyspark.sql.functions import concat\nimport os\nimport sys\n\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\nos.environ[\"SPARK_HOME\"] = \"/opt/cloudera/parcels/CDH-5.16.2-1.cdh5.16.2.p0.8/lib/spark\"\n\n# 获取spark的上下文\nsc = SparkContext.getOrCreate()\nhive_context = HiveContext(sc)\n\n# 生成查询的SQL语句,这个跟hive的查询语句一样,所以也可以加where等条件语句\nhive_database = \"db_hive_test\"\nhive_table = \"hive_movies\"\nhive_read = \"select * from {}.{}\".format(hive_database, hive_table)\n \n# 通过SQL语句在hive中查询的数据直接是dataframe的形式\nread_df = hive_context.sql(hive_read)\n\n# 过滤所有空值\nread_df = read_df.na.drop()\n\nread_df.show()\nread_df.printSchema()\n\n# read_df = read_df.select(concat(*read_df.columns).alias('data'))\n# read_df.write.format(\"text\").option(\"header\", \"false\").mode(\"append\").save(\"hdfs://s0:8020/input/myjson\")\n\n# read_df.write.format(\"com.databricks.spark.csv\").save(\"hdfs://s0:8020/input/mycsv.csv\")\n\nread_df.write.format(\"json\").save(\"hdfs://s0:8020/input/myjson.json\")\n","sub_path":"src/spark2/Demo5.py","file_name":"Demo5.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"286836118","text":"__author__ = 'Brenden'\r\nfrom openpyxl import Workbook\r\nfrom DetailandCommission import *\r\n\r\nclass ExportHours(DetailandCommission):\r\n def __init__(self, db_name):\r\n super(ExportHours, self).__init__(db_name)\r\n\r\n def to_excel(self):\r\n fo = open(\"weekly_table.txt\", \"r+\")\r\n table_name = fo.read(20)\r\n excel_name = table_name\r\n excel_date = excel_name\r\n excel_name += \".xlsx\"\r\n # Close opened file\r\n fo.close()\r\n self.confirm_export_frame = Toplevel()\r\n try:\r\n wb = Workbook()\r\n name_list1 = []\r\n\r\n dest_filename = excel_name\r\n\r\n ws1 = wb.active\r\n ws1.title = \"Weekly Hours\"\r\n\r\n ws1['E1'] = excel_date\r\n\r\n ws1['A3'] = \"Name\"\r\n ws1['B3'] = \"Production\"\r\n ws1['C3'] = \"Production Tips\"\r\n ws1['D3'] = \"Detail\"\r\n ws1['E3'] = \"Detail Tips\"\r\n ws1['F3'] = \"Cashier\"\r\n ws1['G3'] = \"Cashier Tips\"\r\n ws1['H3'] = \"Sales\"\r\n ws1['I3'] = \"Commission\"\r\n ws1['J3'] = \"Total\"\r\n\r\n # dictionary of commands to do\r\n command = [\"SELECT Production FROM '%s'\" % table_name, \"SELECT Production_Tips FROM '%s'\" % table_name,\r\n \"SELECT Detail FROM '%s'\" % table_name, \"SELECT Det_Tips FROM '%s'\" % table_name,\r\n \"SELECT Cashier FROM '%s'\" % table_name, \"SELECT Cash_Tips FROM '%s'\" % table_name,\r\n \"SELECT Sales FROM '%s'\" % table_name, \"SELECT Commission FROM '%s'\" % table_name,\r\n \"SELECT Total FROM '%s'\" % table_name]\r\n\r\n i = 0\r\n while i < 9:\r\n self.c2.execute(command[i])\r\n a_list = self.c2.fetchall()\r\n for x in a_list:\r\n if x[0] is not None:\r\n print(i)\r\n i += 1\r\n\r\n self.c2.execute(\"SELECT * FROM '%s'\" % table_name)\r\n for row in self.c2.fetchall():\r\n name_col = row[0]\r\n\r\n name_list1.append(name_col)\r\n\r\n # alphabetically sort name list\r\n name_list1 = sorted(name_list1, key=lambda j: j.split()[1])\r\n\r\n count = 4\r\n for employee1 in name_list1:\r\n self.c2.execute(\"SELECT * FROM '%s' WHERE Name='%s'\" % (table_name, employee1))\r\n for row in self.c2.fetchall():\r\n name_col = employee1\r\n production_col = row[1]\r\n pro_tips_col = row[2]\r\n detail_col = row[3]\r\n det_tips_col = row[4]\r\n cashier_col = row[5]\r\n cash_tips_col = row[6]\r\n sales_col = row[7]\r\n commission_col = row[8]\r\n total_col = row[9]\r\n\r\n name_loc = 'A' + str(count)\r\n pro_loc = 'B' + str(count)\r\n pro_tip_loc = 'C' + str(count)\r\n det_loc = 'D' + str(count)\r\n det_tip_loc = 'E' + str(count)\r\n cashier_loc = 'F' + str(count)\r\n cash_tip_loc = 'G' + str(count)\r\n sales_loc = 'H' + str(count)\r\n comm_loc = 'I' + str(count)\r\n total_loc = 'J' + str(count)\r\n\r\n ws1[name_loc] = name_col\r\n ws1[pro_loc] = production_col\r\n ws1[pro_tip_loc] = pro_tips_col\r\n ws1[det_loc] = detail_col\r\n ws1[det_tip_loc] = det_tips_col\r\n ws1[cashier_loc] = cashier_col\r\n ws1[cash_tip_loc] = cash_tips_col\r\n ws1[sales_loc] = sales_col\r\n ws1[comm_loc] = commission_col\r\n ws1[total_loc] = total_col\r\n\r\n count += 1\r\n\r\n wb.save(filename=dest_filename)\r\n Label(self.confirm_export_frame, text='Data has been exported to excel').pack()\r\n #os.system('start excel.exe \"%s\\\\%s\"' % (sys.path[0], excel_name))\r\n except:\r\n Label(self.confirm_export_frame, text='Data could not be exported to excel', bg='red').pack()\r\n Label(self.confirm_export_frame, text='excel file named \" %s \" must already exist' % table_name).pack()\r\n #os.system('start excel.exe \"%s\\\\%s\"' % (sys.path[0], excel_name))\r\n\r\n # daily excel function\r\n def to_excel_daily(self):\r\n self.confirm_daily_export_frame = Toplevel()\r\n clockout_value = self.verify_day_clockout()\r\n if clockout_value == 1:\r\n\r\n #excel_name = self.db_name.split(\".\")\r\n #excel_name = excel_name[0]\r\n\r\n excel_name = self.date_to_display\r\n # print(\"after split: \" + excel_name)\r\n excel_date = excel_name\r\n excel_name += \".xlsx\"\r\n print(\"after adding xlsx: \" + excel_name)\r\n\r\n try:\r\n wb = Workbook()\r\n name_list = []\r\n\r\n dest_filename = excel_name\r\n print(\"excel daily database name is: \" + dest_filename)\r\n\r\n ws1 = wb.active\r\n ws1.title = \"Daily Hours\"\r\n\r\n ws1['E1'] = excel_date\r\n\r\n ws1['A3'] = \"Name\"\r\n ws1['B3'] = \"Clock In\"\r\n ws1['C3'] = \"Production\"\r\n ws1['D3'] = \"Sales\"\r\n ws1['E3'] = \"Cashier\"\r\n ws1['F3'] = \"Detail\"\r\n ws1['G3'] = \"Break\"\r\n ws1['H3'] = \"Clock Out\"\r\n ws1['I3'] = \"Total\"\r\n\r\n # dictionary of commands to do\r\n command = [\"SELECT ClockIn FROM Employee\", \"SELECT Production FROM Employee\",\r\n \"SELECT Sales FROM Employee\", \"SELECT Cashier FROM Employee\",\r\n \"SELECT Detail FROM Employee\", \"SELECT Break FROM Employee\",\r\n \"SELECT ClockOut FROM Employee\", \"SELECT Total FROM Employee\"]\r\n\r\n i = 0\r\n while i < 8:\r\n self.c.execute(command[i])\r\n a_list = self.c.fetchall()\r\n for x in a_list:\r\n if x[0] is not None:\r\n print(i)\r\n i += 1\r\n\r\n self.c.execute(\"SELECT * FROM Employee\")\r\n for row in self.c.fetchall():\r\n name_col = row[0]\r\n\r\n name_list.append(name_col)\r\n\r\n # alphabetically sort name list\r\n name_list = sorted(name_list, key=lambda j: j.split()[1])\r\n print(name_list)\r\n\r\n count = 4\r\n for employee in name_list:\r\n self.c.execute(\"SELECT * FROM Employee WHERE Name='%s'\" % employee)\r\n for row in self.c.fetchall():\r\n name_col = employee\r\n clockin_col = row[1]\r\n production_col = row[2]\r\n sales_col = row[3]\r\n cashier_col = row[4]\r\n detail_col = row[5]\r\n break_col = row[6]\r\n clockout_col = row[9]\r\n total_col = row[10]\r\n\r\n name_loc = 'A' + str(count)\r\n clockin_loc = 'B' + str(count)\r\n pro_loc = 'C' + str(count)\r\n sales_loc = 'D' + str(count)\r\n cashier_loc = 'E' + str(count)\r\n detail_loc = 'F' + str(count)\r\n break_loc = 'G' + str(count)\r\n clockout_loc = 'H' + str(count)\r\n total_loc = 'I' + str(count)\r\n\r\n ws1[name_loc] = name_col\r\n ws1[clockin_loc] = clockin_col\r\n ws1[pro_loc] = production_col\r\n ws1[sales_loc] = sales_col\r\n ws1[cashier_loc] = cashier_col\r\n ws1[detail_loc] = detail_col\r\n ws1[break_loc] = break_col\r\n ws1[clockout_loc] = clockout_col\r\n ws1[total_loc] = total_col\r\n\r\n count += 1\r\n\r\n print(\"starting department database\")\r\n self.c.execute(\"SELECT Hours FROM Departments WHERE Department='Detail'\")\r\n for i in self.c.fetchall():\r\n total_detail = i[0]\r\n print(\"total detail: \" + total_detail)\r\n self.c.execute(\"SELECT Hours FROM Departments WHERE Department='Cashier'\")\r\n for i in self.c.fetchall():\r\n total_cashier = i[0]\r\n print(total_cashier)\r\n self.c.execute(\"SELECT Hours FROM Departments WHERE Department='Sales'\")\r\n for i in self.c.fetchall():\r\n total_sales = i[0]\r\n print(total_sales)\r\n self.c.execute(\"SELECT Hours FROM Departments WHERE Department='Production'\")\r\n for i in self.c.fetchall():\r\n total_production = i[0]\r\n print(total_production)\r\n self.c.execute(\"SELECT Hours FROM Departments WHERE Department='Break'\")\r\n for i in self.c.fetchall():\r\n total_break = i[0]\r\n print(total_break)\r\n self.c.execute(\"SELECT Hours FROM Departments WHERE Department='Total'\")\r\n for i in self.c.fetchall():\r\n total_total = i[0]\r\n print(total_total)\r\n\r\n total_final_loc = \"A\" + str(count)\r\n print(total_final_loc)\r\n total_detail_loc = \"F\" + str(count)\r\n total_cashier_loc = \"E\" + str(count)\r\n total_sales_loc = \"D\" + str(count)\r\n total_production_loc = \"C\" + str(count)\r\n total_break_loc = \"G\" + str(count)\r\n total_total_loc = \"I\" + str(count)\r\n ws1[total_final_loc] = 'Total'\r\n ws1[total_detail_loc] = total_detail\r\n ws1[total_cashier_loc] = total_cashier\r\n ws1[total_sales_loc] = total_sales\r\n ws1[total_production_loc] = total_production\r\n ws1[total_break_loc] = total_break\r\n ws1[total_total_loc] = total_total\r\n\r\n wb.save(filename=dest_filename)\r\n Label(self.confirm_daily_export_frame, text='Data has been exported to excel', font=(\"Helvetica\", 12), height=2).pack()\r\n #os.system('start excel.exe \"%s\\\\%s\"' % (sys.path[0], excel_name))\r\n except:\r\n Label(self.confirm_daily_export_frame, text='Data could not be exported to excel', bg='red', font=(\"Helvetica\", 12), height=2).pack()\r\n Label(self.confirm_daily_export_frame, text='excel file named \" %s \" must already exist' % excel_name, font=(\"Helvetica\", 12), height=2).pack()\r\n #os.system('start excel.exe \"%s\\\\%s\"' % (sys.path[0], excel_name))db_name\r\n else:\r\n Label(self.confirm_daily_export_frame, text='Not all employees have clocked out', bg='red', font=(\"Helvetica\", 12), height=2).pack()\r\n Label(self.confirm_daily_export_frame, text='go into \"Change Hours\" to manually clock them out', bg='red', font=(\"Helvetica\", 12), height=2).pack()\r\n\r\n\r\n # checks to make sure eveyone has clocked out\r\n # used for tips because if everyone hasnt clocked out yet then the production and cashier hours might not be correct\r\n def verify_day_clockout(self):\r\n self.c.execute(\"SELECT * FROM Employee\")\r\n for row in self.c.fetchall():\r\n name_col = row[0]\r\n clockout_col = row[9]\r\n if clockout_col is None:\r\n print(name_col + \" is not clocked out\")\r\n return 0\r\n else:\r\n print(name_col + \" has clocked out at \" + str(clockout_col))\r\n return 1\r\n\r\n\r\n","sub_path":"ExportHours.py","file_name":"ExportHours.py","file_ext":"py","file_size_in_byte":12194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"90081570","text":"import binascii\nimport socket\nimport struct\nimport sys\nimport hashlib\n\nUDP_IP = '127.0.0.1'\nUDP_PORT = 5006\nunpacker = struct.Struct('I I 8s 32s')\n\n\n#Create the socket and listen\nsock = socket.socket(socket.AF_INET, # Internet\n socket.SOCK_DGRAM) # UDP\nsock.bind((UDP_IP, UDP_PORT))\nprint(\"Server set-up and listening at: \", UDP_IP)\n\nwhile True:\n #Receive Data\n data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes\n UDP_Packet = unpacker.unpack(data)\n\n # Prints out received UDP packet\n print('received from:', addr)\n print('received message:', UDP_Packet)\n\n # assigns variables to hold ack and sequence numbers to make it easy to reference later\n ack = UDP_Packet[0]\n seq = UDP_Packet[1]\n app_data = UDP_Packet[2]\n\n #Create the Checksum for comparison\n values = (ack,seq,app_data)\n packer = struct.Struct('I I 8s')\n packed_data = packer.pack(*values)\n chksum = bytes(hashlib.md5(packed_data).hexdigest(), encoding='UTF-8')\n\n # creates response ack\n respAck = 1\n\n #Compare Checksums to test for corrupt data\n if UDP_Packet[3] == chksum:\n print('CheckSums Match, Packet OK')\n print('Packet data: ', app_data.decode(\"utf-8\"))\n\n # Creates checksum for response\n response = (respAck,seq)\n UDP_Data = struct.Struct('I I')\n resp_data = UDP_Data.pack(*response)\n respChksum = bytes(hashlib.md5(resp_data).hexdigest(), encoding='UTF-8')\n\n # Puts response into UDP Packet\n response = (respAck,seq,respChksum)\n print(\"Response sent: \", response)\n UDP_Data = struct.Struct('I I 32s')\n UDP_Packet = UDP_Data.pack(*response)\n\n # Sends same Ack to receiver to show that it is not corrupted\n sock.sendto(UDP_Packet,addr)\n else:\n print('Checksums Do Not Match, Packet Corrupt')\n\n # Sends previous or different Ack to receiver to show that it is corrupted\n if seq == 1:\n seq = 0\n else:\n seq = 1\n\n # Creates checksum for response\n response = (respAck,seq)\n UDP_Data = struct.Struct('I I')\n resp_data = UDP_Data.pack(*response)\n respChksum = bytes(hashlib.md5(resp_data).hexdigest(), encoding='UTF-8')\n\n # Puts response into UDP Packet\n response = (respAck,seq,respChksum)\n print(\"Response sent: \", response)\n UDP_Data = struct.Struct('I I 32s')\n UDP_Packet = UDP_Packet_Data.pack(*response)\n\n # Sends different ACK to indicate corrupted data\n sock.sendto(UDP_Packet,addr) ","sub_path":"another assignment/UDP_server.py","file_name":"UDP_server.py","file_ext":"py","file_size_in_byte":2577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"450296065","text":"import cv2\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\nfrom moviepy.editor import VideoFileClip\n\nfrom collections import deque\n\nSMOOTH_FRAMES = 7\n\n\nclass LaneFinder(object):\n def __init__(self, calibrator, image_processor):\n self.calibrator = calibrator\n self.image_processor = image_processor\n self.left_fits = deque() # left_fit history\n self.right_fits = deque() # right_fit history\n self.left_fit = None\n self.right_fit = None\n\n def calc_lane(self, image):\n # Take a histogram of the bottom half the image\n histogram = np.sum(image[image.shape[0] // 2:, :], axis=0)\n\n # Create an output image to draw on and visualize the result\n out_img = np.dstack((image, image, image)) * 255\n\n # Find the peak of the left and right halves of the histogram\n # These will be the starting point for the left and right lines\n midpoint = np.int(histogram.shape[0] // 2)\n leftx_base = np.argmax(histogram[:midpoint])\n rightx_base = np.argmax(histogram[midpoint:]) + midpoint\n\n # Choose the number of sliding windows\n nwindows = 9\n\n # Set height of windows\n window_height = np.int(image.shape[0] / nwindows)\n\n # Identify the x and y positions of all nonzero pixels in the image\n nonzero = image.nonzero()\n\n nonzeroy = np.array(nonzero[0])\n nonzerox = np.array(nonzero[1])\n\n # Current positions to be updated for each window\n leftx_current = leftx_base\n rightx_current = rightx_base\n\n # Set the width of the windows +/- margin\n margin = 100\n\n # Set minimum number of pixels found to recenter window\n minpix = 50\n\n # Create empty lists to receive left and right lane pixel indices\n left_lane_idxs = []\n right_lane_idxs = []\n\n # Step through the windows one by one\n for window in range(nwindows):\n # Identify window boundaries in xclclip.write_videofile(white_output, audio=False)ip.write_videofile(white_output, audio=False) and y (and right and left)\n win_y_low = image.shape[0] - (window + 1) * window_height\n win_y_high = image.shape[0] - window * window_height\n win_xleft_low = leftx_current - margin\n win_xleft_high = leftx_current + margin\n win_xright_low = rightx_current - margin\n win_xright_high = rightx_current + margin\n\n # Draw the windows on the visualization image\n cv2.rectangle(out_img, (win_xleft_low, win_y_low), (win_xleft_high, win_y_high), (0, 255, 0), 2)\n cv2.rectangle(out_img, (win_xright_low, win_y_low), (win_xright_high, win_y_high), (0, 255, 0), 2)\n\n # Identify the nonzero pixels in x and y within the window\n good_left_idxs = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & (nonzerox >= win_xleft_low) & (\n nonzerox < win_xleft_high)).nonzero()[0]\n good_right_idxs = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & (nonzerox >= win_xright_low) & (\n nonzerox < win_xright_high)).nonzero()[0]\n\n # Append these indices to the lists\n left_lane_idxs.append(good_left_idxs)\n right_lane_idxs.append(good_right_idxs)\n\n # If you found > minpix pixels, recenter next window on their mean position\n if len(good_left_idxs) > minpix:\n leftx_current = np.int(np.mean(nonzerox[good_left_idxs]))\n if len(good_right_idxs) > minpix:\n rightx_current = np.int(np.mean(nonzerox[good_right_idxs]))\n\n # Concatenate the arrays of indices\n left_lane_idxs = np.concatenate(left_lane_idxs)\n right_lane_idxs = np.concatenate(right_lane_idxs)\n\n # Extract left and right line pixel positions\n leftx = nonzerox[left_lane_idxs]\n lefty = nonzeroy[left_lane_idxs]\n rightx = nonzerox[right_lane_idxs]\n righty = nonzeroy[right_lane_idxs]\n\n # Fit a second order polynomial to each\n left_fit = np.polyfit(lefty, leftx, 2)\n right_fit = np.polyfit(righty, rightx, 2)\n\n # Smooth the fitting polynomial parameters by looking at previous frame's results\n self.smooth_fit_parameters(left_fit, right_fit)\n\n # Generate x and y values for plotting\n ploty = np.linspace(0, image.shape[0] - 1, image.shape[0])\n left_fitx = self.left_fit[0] * ploty ** 2 + self.left_fit[1] * ploty + self.left_fit[2]\n right_fitx = self.right_fit[0] * ploty ** 2 + self.right_fit[1] * ploty + self.right_fit[2]\n\n out_img[nonzeroy[left_lane_idxs], nonzerox[left_lane_idxs]] = [255, 0, 0]\n out_img[nonzeroy[right_lane_idxs], nonzerox[right_lane_idxs]] = [0, 0, 255]\n\n # cv2.imshow('img', out_img)\n # cv2.waitKey(0)\n # cv2.imwrite('images/pipeline_polyfit.jpg', out_img)\n\n # plt.imshow(out_img)\n # plt.plot(left_fitx, ploty, color='yellow')\n # plt.plot(right_fitx, ploty, color='yellow')\n # plt.xlim(0, 1280)\n # plt.ylim(720, 0)\n # plt.show()\n\n # Estimate lane curvature and car's offset to lane center\n y_eval = np.max(ploty)\n # Define conversions in x and y from pixels space to meters\n ym_per_pix = 30 / 300 # meters per pixel in y dimension\n xm_per_pix = 3.7 / 900 # meters per pixel in x dimension\n\n # Fit new polynomials to x,y in world space\n left_fit_cr = np.polyfit(lefty * ym_per_pix, leftx * xm_per_pix, 2)\n right_fit_cr = np.polyfit(righty * ym_per_pix, rightx * xm_per_pix, 2)\n\n # Calculate the new rad of curvature\n left_curverad = ((1 + (2 * left_fit_cr[0] * y_eval * ym_per_pix + left_fit_cr[1]) ** 2) ** 1.5) / np.absolute(2 * left_fit_cr[0])\n right_curverad = ((1 + (2 * right_fit_cr[0] * y_eval * ym_per_pix + right_fit_cr[1]) ** 2) ** 1.5) / np.absolute(2 * right_fit_cr[0])\n\n # Now our radius of curvature is in meters\n # print(left_curverad, 'm', right_curverad, 'm')\n\n # Estimate car's offset to lane center\n lane_left_bottom_y = image.shape[0] - 1\n lane_left_bottom_x = self.left_fit[0] * lane_left_bottom_y ** 2 + self.left_fit[1] * lane_left_bottom_y + self.left_fit[2]\n\n lane_right_bottom_y = image.shape[0] - 1\n lane_right_bottom_x = self.right_fit[0] * lane_right_bottom_y ** 2 + self.right_fit[1] * lane_right_bottom_y + self.right_fit[2]\n\n # print(lane_left_bottom_x)\n # print(lane_left_bottom_y)\n\n lane_middle_x = lane_left_bottom_x * 0.5 + lane_right_bottom_x * 0.5\n car_lane_middle_offset = abs(lane_middle_x - image.shape[1] / 2) * xm_per_pix\n\n # print(lane_middle_x)\n # print(image.shape[1] / 2)\n # print(car_lane_middle_offset)\n\n return left_fitx, right_fitx, ploty, left_curverad, right_curverad, car_lane_middle_offset\n\n def smooth_fit_parameters(self, left_fit, right_fit):\n if len(self.left_fits) == SMOOTH_FRAMES:\n self.left_fits.popleft()\n self.left_fits.append(left_fit)\n\n if len(self.right_fits) == SMOOTH_FRAMES:\n self.right_fits.popleft()\n self.right_fits.append(right_fit)\n\n if self.left_fit is None:\n self.left_fit = left_fit\n self.right_fit = right_fit\n return\n\n # Use O(5) instead of O(1) for better readability\n self.left_fit[0] = sum(fit[0] for fit in self.left_fits) / SMOOTH_FRAMES\n self.left_fit[1] = sum(fit[1] for fit in self.left_fits) / SMOOTH_FRAMES\n self.left_fit[2] = sum(fit[2] for fit in self.left_fits) / SMOOTH_FRAMES\n \n self.right_fit[0] = sum(fit[0] for fit in self.right_fits) / SMOOTH_FRAMES\n self.right_fit[1] = sum(fit[1] for fit in self.right_fits) / SMOOTH_FRAMES\n self.right_fit[2] = sum(fit[2] for fit in self.right_fits) / SMOOTH_FRAMES\n\n def draw_lane_on_image(self, undist, warped, left_fitx, right_fitx, ploty):\n # Create an image to draw the lines on\n color_warp = np.zeros_like(warped).astype(np.uint8)\n\n # Recast the x and y points into usable format for cv2.fillPoly()\n pts_left = np.array([np.transpose(np.vstack([left_fitx, ploty]))])\n pts_right = np.array([np.flipud(np.transpose(np.vstack([right_fitx, ploty])))])\n pts = np.hstack((pts_left, pts_right))\n\n # Draw the lane onto the warped blank image\n cv2.fillPoly(color_warp, np.int_([pts]), (0, 255, 0))\n\n # Warp the blank back to original image space using inverse perspective matrix (Minv)\n unwarp_lane = self.image_processor.unwarp(color_warp)\n\n # Combine the result with the original image\n return cv2.addWeighted(undist, 1, unwarp_lane, 0.3, 0)\n\n def draw_info_on_image(self, image, left_curvature, right_curvature, car_lane_middle_offset):\n font = cv2.FONT_HERSHEY_SIMPLEX\n curvature_text = \"Curvature Radius(m): \" + str(left_curvature * 0.5 + right_curvature * 0.5)\n cv2.putText(image, curvature_text, (10, 30), font, 1, (255, 255, 255), 2)\n offset_text = \"Car's offset to lane center(m): \" + str(car_lane_middle_offset)\n cv2.putText(image, offset_text, (10, 60), font, 1, (255, 255, 255), 2)\n return image\n\n def find_lane(self, image):\n # cv2.imwrite('images/pipeline_original.jpg', image)\n\n # Undistort image\n undist = self.calibrator.undistort(image)\n # cv2.imwrite('images/pipeline_undistorted.jpg', undist)\n\n # Perspective transform image\n warped = self.image_processor.warp(undist)\n # cv2.imshow('img', warped)\n # cv2.waitKey(0)\n # cv2.imwrite('images/pipeline_warped.jpg', warped)\n\n # Edge detection into binary image\n binary = self.image_processor.to_binary_edge(warped)\n # cv2.imshow('img', binary * 255)\n # cv2.waitKey(0)\n # cv2.imwrite('images/pipeline_binary.jpg', binary * 255)\n\n # Fit polynomial line\n left_fitx, right_fitx, ploty, left_curvature, right_curvature, car_lane_middle_offset = self.calc_lane(binary)\n\n # Draw line back to image\n lane_image = self.draw_lane_on_image(undist, warped, left_fitx, right_fitx, ploty)\n cv2.imwrite('images/pipeline_lane.jpg', lane_image)\n\n # Draw curvature on image\n result = self.draw_info_on_image(lane_image, left_curvature, right_curvature, car_lane_middle_offset)\n\n return result\n\n def find_lane_from_image(self, image_path, output_path):\n image = cv2.imread(image_path)\n result = self.find_lane(image)\n\n filename = os.path.basename(image_path)\n cv2.imwrite(os.path.join(output_path, filename), result)\n\n def find_lane_from_video(self, video_path, output_path):\n video = VideoFileClip(video_path)\n result = video.fl_image(self.find_lane)\n\n filename = os.path.basename(video_path)\n result.write_videofile(os.path.join(output_path, filename), audio=False)\n\n","sub_path":"lane_finder.py","file_name":"lane_finder.py","file_ext":"py","file_size_in_byte":11024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"583440374","text":"import glob\r\nimport os\r\nimport string\r\nimport os.path\r\nimport sys\r\nimport shutil\r\nimport xlrd\r\nimport csv\r\nimport argparse\r\nimport xlsxwriter\r\nimport pptx\r\n#import antigravity\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib as plt\r\nimport seaborn as sns\r\nimport tkinter as tk\r\nfrom tkinter.filedialog import *\r\nfrom tkinter.messagebox import *\r\nfrom pptx import Presentation\r\nfrom pptx.util import Inches\r\nfrom datetime import date\r\nfrom pathlib import Path\r\n\r\n\r\n# Part 1: How to import all the files we want\r\n\r\n\r\n# Define random useful functions here\r\n\r\n\r\n# Precondition: s is a single character string.\r\n# Postcondition: float(s) is the single character string changed to a float and s is the single character string returned as a string.\r\n\r\n\r\ndef maybe_float(s):\r\n\ttry:\r\n\t\treturn float(s)\r\n\texcept (ValueError, TypeError):\r\n\t\treturn s\r\n\r\n\r\n# Precondition: extensionlist is a full list of filenames containing the extension (.jpg, .png, .heic, etc...) at the end.\r\n# Postcondition: filenames is a full list of filenames without the extension at the end.\r\n\r\n\r\ndef stem_list(extensionlist):\r\n\tnoextensionlist = []\r\n\r\n\tfor file in extensionlist:\r\n\t\ty = Path(file).stem\r\n\t\tnoextensionlist.append(y)\r\n\r\n\treturn noextensionlist\r\n\r\n\r\n# Define useful script specific functions here\r\n\r\n\r\n# Precondition: function is tied to a button input.\r\n# Postcondition: function will take all the images from all the subdirectories within a directory and add them all onto a different slide per subdirectory.\r\n\r\n\r\ndef sortcondition():\r\n\r\n\tlocation = askdirectory(title = \"Select post condition folder.\")\r\n\tif(not location):\r\n\t\tsys.exit(0)\r\n\r\n\tsplitlocationpath = os.path.split(location)\r\n\tpostcondition = splitlocationpath[1]\r\n\r\n\tcondition = os.scandir(location)\r\n\r\n\tsavename = savenameentry.get()\r\n\r\n\tpptx_location = askopenfilename(filetypes = [(\"Powerpoint Files\", \"*.pptx\")], title = \"Select Powerpoint Template File.\")\r\n\tif not(pptx_location):\r\n\t\tsys.exit(0)\r\n\r\n\tprs = Presentation(pptx_location)\r\n\r\n\tfor folder in condition:\r\n\t\tif folder.is_dir():\r\n\t\t\timagefiles = []\r\n\r\n\t\t\tos.chdir(folder)\r\n\t\t\tfilenames = glob.glob(\"*.jpg\")\r\n\r\n\t\t\tfor file in filenames:\r\n\t\t\t\timagefiles.append(file)\r\n\r\n\t\t\taddimages(folder, postcondition, pptx_location, prs, imagefiles)\r\n\r\n\tsave_location = askdirectory(title = \"Select location to save presentation.\")\r\n\tos.chdir(save_location)\r\n\tprs.save(str(savename)+\".pptx\")\r\n\r\n\r\n# Precondition: pptx_location is the location of the powerpoint file template. prs is the powerpoint presentation. modulelist is the list of images from the given subdirectory.\r\n# Postcondition: function will all all the images from a certain directory to a new slide.\r\n\r\n\r\ndef addimages(folder, postcondition, pptx_location, prs, modulelist):\r\n\r\n\tlyt_1 = prs.slide_layouts[0]\r\n\tlyt_2 = prs.slide_layouts[1]\r\n\tlyt_3 = prs.slide_layouts[2]\r\n\tlyt_4 = prs.slide_layouts[3]\r\n\tlyt_5 = prs.slide_layouts[4]\r\n\tlyt_6 = prs.slide_layouts[5]\r\n\tlyt_7 = prs.slide_layouts[6]\r\n\tlyt_8 = prs.slide_layouts[7]\r\n\r\n\tpictureslides = prs.slides.add_slide(lyt_5)\r\n\tpictureslidestitle = pictureslides.shapes.title\r\n\r\n\tnewfolder = str(folder)\r\n\tfoldername = newfolder[newfolder.find(\"'\")+1:newfolder.rfind(\"'\")]\r\n\r\n\tpictureslidestitle.text = str(foldername)+\" @ \"+str(postcondition)\r\n\r\n\twidth_full_standard_slide = Inches(10)\r\n\twidth_full_widescreen_slide = Inches(13.333)\r\n\theight_full_slide = Inches(7.5)\r\n\ttop_margin = Inches(1.5)\r\n\tside_margin = Inches(0.1)\r\n\tmargin_in_between = Inches(0.5)\r\n\r\n\ttop_6_1 = top_margin\r\n\tleft_6_1 = side_margin\r\n\ttop_6_2 = (height_full_slide/2)+(1.5*margin_in_between)\r\n\tleft_6_2 = (width_full_widescreen_slide/3)+left_6_1\r\n\tleft_6_3 = (2*(width_full_widescreen_slide/3))+left_6_1\r\n\twidth_6 = (width_full_widescreen_slide/3)-(2*left_6_1)\r\n\theight_6 = (height_full_slide/2)-top_6_1\r\n\r\n\tfor image in modulelist:\r\n\t\tpictureslides.shapes.add_picture(image, left_6_2, top_6_1)\r\n\r\n\r\n# Part 3: Create the GUI\r\n\r\n\r\npowerpointgui = tk.Tk()\r\n\r\n\r\n# Create homepage screen.\r\n\r\n\r\npowerpointcanvas = tk.Canvas(powerpointgui, width = 400, height = 220)\r\npowerpointcanvas.pack()\r\n\r\n\r\n# Create boxes to take user input.\r\n\r\n\r\nsavenameentry = tk.Entry(powerpointgui)\r\npowerpointcanvas.create_window(200, 90, window = savenameentry)\r\n\r\nsavenamelabel = tk.Label(text = \"Powerpoint File Name\")\r\npowerpointcanvas.create_window(200, 50, window = savenamelabel)\r\n\r\n\r\n# Create buttons to select powerpoint formatting.\r\n\r\n\r\nsortconditionbutton = tk.Button(text = \"Format Powerpoint by Post Condition\", command = sortcondition)\r\npowerpointcanvas.create_window(200, 130, window = sortconditionbutton)\r\n\r\npowerpointgui.mainloop()","sub_path":"pptCodeFolderPath.py","file_name":"pptCodeFolderPath.py","file_ext":"py","file_size_in_byte":4612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"460341796","text":"__author__ = 'vasiliy'\nfrom pymongo import MongoClient\nimport re\nimport vk_api\n\n\ndef isClub(link):\n m = re.search(\"club[0-9]+\", link)\n if m is not None:\n return True\n else:\n return False\n\n\ndef isPublic(link):\n m = re.search(\"public[0-9]+\", link)\n if m is not None:\n return True\n else:\n return False\n\n\ndef get_public_id(public):\n m = re.search(\"[0-9]*$\", public)\n id = m.group()\n return id\n\n\ndef get_club_id(club):\n \"\"\"\n club e.g. = http://vk.com/club12842\n we need club id (12842)\n :param club:\n :return:\n \"\"\"\n m = re.search(\"[0-9]*$\", club)\n id = m.group()\n return id\n\n\ndef get_domain(vk_link):\n \"\"\"\n :param vk_link:\n :return:\n \"\"\"\n res = vk_link.rfind('/')\n return vk_link[res+1:]\n\n\ndef isValid(link, vk):\n valid = False\n if isClub(link):\n club_id = get_club_id(link)\n request = vk_api.VkApi(vk)\n try:\n response = request.method('groups.getById', {'group_id': str(club_id)})\n except Exception as error:\n print(error)\n else:\n valid = True\n if isPublic(link):\n public_id = get_public_id(link)\n request = vk_api.VkApi(vk)\n try:\n response = request.method('groups.getById', {'group_id': str(public_id)})\n except Exception as error:\n print(error)\n else:\n valid = True\n else:\n domain = get_domain(link)\n request = vk_api.VkApi(vk)\n try:\n response = request.method('groups.getById', {'group_id': str(domain)})\n except Exception as error:\n print(error)\n else:\n valid = True\n\n return valid\n\ndef get_login_pswd(flag):\n file = open(\"/home/vasiliy/Study/VkData/logpswd.txt\", 'r')\n login = file.readline()\n login = re.sub(r'\\n', '', login)\n pswd = file.readline()\n pswd = re.sub(r'\\n', '', pswd)\n if flag == \"l\":\n return login\n else:\n return pswd\n\n\ndef auth():\n print(\"authorization\")\n login = get_login_pswd(\"l\")\n pswd = get_login_pswd(\"p\")\n vk_akk = vk_api.VkApi(login, pswd)\n try:\n vk_akk.authorization()\n except vk_api.AuthorizationError as error_msg:\n print(\"Error auth\", error_msg)\n return vk_akk\n\n\nif __name__ == \"__main__\":\n vk = auth()\n links_list = []\n client = MongoClient()\n db = client['vk_db']\n collection = db['vk_valid_links']\n result = collection.find()\n i = 0\n\n for link in result:\n links_list.append(link[str(i)])\n\n ids = []\n for link in links_list:\n if isPublic(link):\n id = get_public_id(link)\n try:\n response = request.method('groups.getById', {'group_id': str(id), 'fields': \"members_count\"})\n except Exception as err:\n print(err)\n print(\"public id= \", id)\n for resp in response:\n weight = resp[\"members_count\"]\n name = resp[\"name\"]\n ids.append(id)\n if isClub(link):\n id = get_club_id(link)\n try:\n response = request.method('groups.getById', {'group_id': str(id), 'fields': \"members_count\"})\n except Exception as err:\n print(err)\n print(\"club id = \", id)\n for resp in response:\n weight = resp[\"members_count\"]\n name = resp[\"name\"]\n ids.append(id)\n else:\n domain = get_domain(link)\n request = vk_api.VkApi(vk)\n try:\n response = request.method('groups.getById', {'group_id': str(domain), 'fields': \"members_count\"})\n for resp in response:\n id = resp[\"id\"]\n weight = resp[\"members_count\"]\n name = resp[\"name\"]\n ids.append(id)\n except Exception as err:\n print(err)\n print(\"domain = \", domain)\n\n collection = db['name_id_weight']\n result = collection.insert({\"link\": link, \"name\": name, \"id\": id, \"weight\": weight})\n # print(\"count of all valid ids is \", len(ids))\n\n #collection = db['valid_ids']\n #i = 0\n #for each in ids:\n # result = collection.insert({str(i): each})\n # i += 1\n","sub_path":"VkLinksProcess.py","file_name":"VkLinksProcess.py","file_ext":"py","file_size_in_byte":4312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"539753540","text":"import logging\nimport time\nimport config\n\nFLAGS = config.flags.FLAGS\n\ninput_file = str(FLAGS.f_n).split('.')[0]\nnow = time.localtime()\ns_time = \"%02d%02d-%02d%02d%02d\" % (now.tm_mon, now.tm_mday, now.tm_hour, now.tm_min, now.tm_sec)\nfilename = \"r-\"+input_file+\"-\"+\"-\"+str(FLAGS.n_h)+\"-\"+str(FLAGS.depth)\\\n + \"-\" + str(FLAGS.h_size)+\"-\"+str(FLAGS.n_e)+\"-\"+str(FLAGS.b_s)+\"-\"+str(FLAGS.dropout_rate)+\"-\"+s_time\n\n# === Logging setup === #\nlogger = logging.getLogger('Energy')\nlogger.setLevel(logging.INFO)\nfh = logging.FileHandler(\"./result/eval2/\"+filename+\".log\")\nsh = logging.StreamHandler()\nfm = logging.Formatter('%(message)s')\nfh.setFormatter(fm)\nsh.setFormatter(fm)\nlogger.addHandler(fh)\nlogger.addHandler(sh)\n\n# now = time.localtime()\n# s_time = \"%02d%02d-%02d%02d%02d\" % (now.tm_mon, now.tm_mday, now.tm_hour, now.tm_min, now.tm_sec)\n# result = logging.getLogger('Result')\n# result.setLevel(logging.INFO)\n# result_fh = logging.FileHandler(\"./result/r-\" + s_time + \".txt\")\n# result_fm = logging.Formatter('[%(filename)s:%(lineno)s] %(asctime)s\\t%(message)s')\n# result_fh.setFormatter(result_fm)\n# result.addHandler(result_fh)\n","sub_path":"log_result.py","file_name":"log_result.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"581488175","text":"#!/usr/bin/env python\r\n# _*_ coding: utf-8 _*_\r\n\r\nimport configparser\r\nimport os\r\nimport sys\r\n\r\nfrom tkinter import *\r\nimport tkinter.filedialog\r\n\r\n\r\nclass Run(object):\r\n def __init__(self):\r\n self.data_name = ''\r\n self.local_name = ''\r\n self.xshell_name = ''\r\n self.config = configparser.ConfigParser()\r\n self.filename = '%s\\\\config.ini' % os.path.split(os.path.realpath(__file__))[0]\r\n self.config_text = '[global]\\ndata_dir=\\nlocal_dir=\\nxshell_path=\\n'\r\n self.root = Tk()\r\n self.root.title(\"连接工具\")\r\n self.root.geometry(\"800x400\")\r\n self.title = Label(self.root, text='连接工具', font=('Arial', 20)) # 标题\r\n self.title.pack()\r\n\r\n self.frm = Frame(self.root)\r\n self.frm_l = Frame(self.frm)\r\n self.frm_r = Frame(self.frm)\r\n # self.frm_data = Frame(self.frm)\r\n # self.frm_xshell = Frame(self.frm)\r\n\r\n self.data_var = Label(self.frm_r, text=self.get_config()['data_dir'], font=(\"宋体\",11), height=2)\r\n self.data_btn = Button(self.frm_l, text='选择数据目录', font=(\"宋体\",11), height=2, width=15, command=self.data)\r\n self.local_var = Label(self.frm_r, text=self.get_config()['local_dir'], font=(\"宋体\", 11), height=2)\r\n self.local_btn = Button(self.frm_l, text='选择本地目录', font=(\"宋体\", 11), height=2, width=15, command=self.local)\r\n self.xshell_var = Label(self.frm_r, text=self.get_config()['xshell_path'], font=(\"宋体\",11), height=2)\r\n self.xshell_btn = Button(self.frm_l, text='选择xshell程序', font=(\"宋体\",11), height=2, width=15, command=self.xshell)\r\n\r\n self.start = Button(self.root, text='启动', font=(\"黑体\",15), height=2, width=15, command=self.start)\r\n self.info = Label(self.root, text='', font=(\"宋体\",12), height=4)\r\n self.blank = Label(self.root, text='', font=(\"宋体\",11), height=4)\r\n\r\n self.frm.pack()\r\n # self.frm_data.pack()\r\n self.frm_l.pack(side=LEFT)\r\n self.frm_r.pack(side=RIGHT)\r\n\r\n self.data_var.pack(side=TOP)\r\n self.data_btn.pack(side=TOP)\r\n self.local_var.pack(side=TOP)\r\n self.local_btn.pack(side=TOP)\r\n # self.frm_xshell.pack()\r\n self.xshell_var.pack(side=TOP)\r\n self.xshell_btn.pack(side=TOP)\r\n\r\n self.info.pack(side=BOTTOM)\r\n self.blank.pack(side=BOTTOM)\r\n self.start.pack(side=BOTTOM)\r\n\r\n def get_config(self):\r\n if not os.path.isfile(self.filename):\r\n f = open(self.filename, 'a+')\r\n try:\r\n f.writelines(self.config_text)\r\n f.close()\r\n except Exception as e:\r\n print(e)\r\n try:\r\n self.config.read(self.filename)\r\n data_dir = self.config.get('global', 'data_dir')\r\n local_dir = self.config.get('global', 'local_dir')\r\n xshell_path = self.config.get('global', 'xshell_path')\r\n # print('data_dir, xshell', self.data_dir, self.xshell)\r\n return {'data_dir': data_dir, 'local_dir': local_dir, 'xshell_path': xshell_path}\r\n except Exception as e:\r\n print('配置文件读取失败!')\r\n print(e)\r\n\r\n def set_config(self, section, key, value):\r\n if not os.path.isfile(self.filename):\r\n f = open(self.filename, 'a+')\r\n try:\r\n f.writelines(self.config_text)\r\n f.close()\r\n except Exception as e:\r\n print(e)\r\n try:\r\n # self.config = configparser.ConfigParser()\r\n self.config.read(self.filename)\r\n self.config.set(section, key, value)\r\n # self.config.set('global', 'data_dir', self.data_name)\r\n # self.config.set('global', 'local_dir', self.local_name)\r\n # self.config.set('global', 'xshell_path', self.xshell_name)\r\n with open(self.filename, 'w') as f:\r\n self.config.write(f)\r\n except Exception as e:\r\n self.info.config(text=e, fg='red')\r\n\r\n def data(self):\r\n self.data_name = tkinter.filedialog.askdirectory()\r\n if self.data_name != '':\r\n self.data_var.config(text=self.data_name)\r\n self.set_config('global', 'data_dir', self.data_name)\r\n else:\r\n pass\r\n\r\n def local(self):\r\n self.local_name = tkinter.filedialog.askdirectory()\r\n if self.local_name != '':\r\n self.local_var.config(text=self.local_name)\r\n self.set_config('global', 'local_dir', self.local_name)\r\n else:\r\n pass\r\n\r\n def xshell(self):\r\n self.xshell_name = tkinter.filedialog.askopenfilename()\r\n if self.xshell_name != '':\r\n self.xshell_var.config(text=self.xshell_name)\r\n self.set_config('global', 'xshell_path', self.xshell_name)\r\n else:\r\n pass\r\n\r\n def start(self):\r\n self.info.config(text='拉取数据目录中', fg='green')\r\n # config = configparser.ConfigParser()\r\n self.config.read(self.filename)\r\n if self.get_config()['data_dir'] == '':\r\n if self.data_name == '':\r\n self.info.config(text='数据目录不能为空!', fg='red')\r\n else:\r\n self.config.set('global', 'data_dir', self.data_name)\r\n # if self.data_name == '':\r\n # self.info.config(text='数据目录不能为空!', fg='red')\r\n # elif self.local_name == '':\r\n # self.info.config(text='本地目录不能为空!', fg='red')\r\n # elif self.xshell_name == '':\r\n # self.info.config(text='xshell路径不能为空!', fg='red')\r\n # else:\r\n # config.set('global', 'data_dir', self.data_name)\r\n elif self.get_config()['local_dir'] == '':\r\n if self.local_name == '':\r\n self.info.config(text='本地目录不能为空!', fg='red')\r\n else:\r\n self.config.set('global', 'local_dir', self.local_name)\r\n # if self.data_name == '':\r\n # self.info.config(text='数据目录不能为空!', fg='red')\r\n # elif self.local_name == '':\r\n # self.info.config(text='本地目录不能为空!', fg='red')\r\n # elif self.xshell_name == '':\r\n # self.info.config(text='xshell路径不能为空!', fg='red')\r\n # else:\r\n # config.set('global', 'local_dir', self.local_name)\r\n elif self.get_config()['xshell_path'] == '':\r\n if self.xshell_name == '':\r\n self.info.config(text='xshell路径不能为空!', fg='red')\r\n else:\r\n self.config.set('global', 'xshell_path', self.xshell_name)\r\n # if self.data_name == '':\r\n # self.info.config(text='数据目录不能为空!', fg='red')\r\n # elif self.local_name == '':\r\n # self.info.config(text='本地目录不能为空!', fg='red')\r\n # elif self.xshell_name == '':\r\n # self.info.config(text='xshell路径不能为空!', fg='red')\r\n # else:\r\n # config.set('global', 'xshell_path', self.xshell_name)\r\n else:\r\n self.info.config(text='拉取数据目录中', fg='green')\r\n self.get_data()\r\n\r\n with open(self.filename, 'w') as f:\r\n self.config.write(f)\r\n\r\n def get_data(self):\r\n command = 'xcopy \"' + self.get_config()['data_dir'].replace('/', '\\\\') + '\" \"' + self.get_config()['local_dir'].replace('/', '\\\\') + '\" /d/i/y/e'\r\n # for i in os.listdir(self.data_name):\r\n # print(i)\r\n print(command)\r\n run = os.system(command)\r\n if run == 0:\r\n self.info.config(text='拉取成功,启动xshell', fg='green')\r\n self.start_xshell()\r\n elif run == 1:\r\n self.info.config(text='没有找到要复制的文件', fg='red')\r\n elif run == 4:\r\n self.info.config(text='内存或磁盘空间不足,或无效的驱动器名称或语法', fg='red')\r\n elif run == 5:\r\n self.info.config(text='磁盘写入错误', fg='red')\r\n else:\r\n self.info.config(text='拉取失败,%s' % run, fg='red')\r\n\r\n def start_xshell(self):\r\n try:\r\n os.startfile(self.get_config()['xshell_path'])\r\n sys.exit(0)\r\n except Exception as e:\r\n self.info.config(text='启动xshell失败, %s' % e, fg='red')\r\n\r\ndef main():\r\n Run()\r\n mainloop()\r\n\r\nif __name__== \"__main__\":\r\n main()","sub_path":"share_xshell_session.py","file_name":"share_xshell_session.py","file_ext":"py","file_size_in_byte":8673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"113127278","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 17 10:28:04 2020\n\n@author: amitkumar\n\"\"\"\n\n#Import the libraries\nimport numpy as np\nimport pandas as pd\nimport re\nfrom nltk.stem import WordNetLemmatizer\nfrom sklearn.model_selection import train_test_split,cross_val_score\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC\nfrom sklearn.ensemble import RandomForestClassifier\nfrom nltk.corpus import stopwords\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.metrics import classification_report\n\n#Import the dataset\ndata = pd.read_csv('Restaurant_Reviews.tsv', delimiter='\\t')\nX = data['Review']\ny = data['Liked']\n\n#Checking the missing data if any\nprint(data.isnull().mean())\n\n#reading stop words\nstop_words = set(stopwords.words('english'))\n\n#clean the data\ncorpus = []\nfor i in range(len(X)):\n review = re.sub('[^a-zA-Z]', ' ', X[i])\n review = review.lower()\n review = review.split()\n lemmatizer = WordNetLemmatizer()\n review = [lemmatizer.lemmatize(word) for word in review if not word in stop_words]\n review = ' '.join(review)\n corpus.append(review)\n \n#Create the data frame of corpus\nX = pd.DataFrame(data = corpus, columns = ['Review'])\n\n#Split the data to train and test set\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20)\n\n#Creating train and test corpus\ntrain_corpus = [row for row in X_train['Review']]\ntest_corpus = [row for row in X_test['Review']]\n\n#Applying TFIDF\n#tfidf = TfidfVectorizer()\n#tfidf.fit(X_train)\n#X_train = tfidf.transform(train_corpus).toarray()\n#X_test = tfidf.transform(test_corpus).toarray()\n\n#Applying Bag of words model\nvectorizer = CountVectorizer()\nvectorizer.fit(train_corpus)\nX_train = vectorizer.transform(train_corpus).toarray()\nX_test = vectorizer.transform(test_corpus).toarray()\n\n#Train the Logistic Regression model\nclassifier = LogisticRegression()\nclassifier.fit(X_train, y_train)\n\n#Train the SVC model\n#classifier = SVC(kernel='rbf')\n#classifier.fit(X_train, y_train)\n\n\n\n#Train the Random Forest Model\n#classifier = RandomForestClassifier(n_estimators=200, criterion='entropy')\n#classifier.fit(X_train, y_train)\n\n#Predicting the test set result\ny_pred = classifier.predict(X_test)\n\n#Making classification report\nprint(classification_report(y_test, y_pred))\nprint(classification_report(y_train, classifier.predict(X_train)))\n\n#Applying k-cross fold\naccuracies = cross_val_score(estimator=classifier, X=X_train, y=y_train, \n scoring = 'accuracy', cv =10, n_jobs=-1)\naccuracy = accuracies.mean()\n\n\n","sub_path":"Restuarnt_Review/Restaurant_Reviews.py","file_name":"Restaurant_Reviews.py","file_ext":"py","file_size_in_byte":2658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"200572979","text":"import hashlib\nimport itertools\nimport os\nimport shutil\nimport json\nimport logging\nimport checksumdir\nimport yaml\nimport packtivity.utils as utils\nlog = logging.getLogger(__name__)\n\nclass MountedFSState(object):\n '''\n Local Filesyste State consisting of a number of readwrite and readonly directories\n '''\n def __init__(self,readwrite = None,readonly = None, dependencies = None, identifier = 'unidentified_state', mountspec = None):\n self._identifier = identifier\n self.readwrite = list(readwrite if readwrite else [])\n self.readonly = list(readonly if readonly else [])\n self.dependencies = dependencies or []\n self.mountspec = mountspec\n\n @property\n def metadir(self):\n return '{}/_packtivity'.format(self.readwrite[0])\n\n def identifier(self):\n return self._identifier\n\n def add_dependency(self,depstate):\n pass\n\n def reset(self):\n raise NotImplementedError('reset not implemented')\n\n def state_hash(self):\n raise NotImplementedError('hash not implemented')\n\n def contextualize_data(self,data):\n '''\n contextualizes string data by string interpolation.\n replaces '{workdir}' placeholder with first readwrite directory\n '''\n try: \n workdir = self.readwrite[0]\n return data.format(workdir = workdir)\n except AttributeError:\n return data\n\n\n def json(self):\n return {\n 'state_type': 'mountedfs',\n 'identifier': self.identifier(),\n 'readwrite': self.readwrite,\n 'readonly': self.readonly,\n 'dependencies': [x.json() for x in self.dependencies],\n 'mountspec': self.mountspec\n\n }\n\n @classmethod\n def fromJSON(cls,jsondata):\n return cls(\n readwrite = jsondata['readwrite'],\n readonly = jsondata['readonly'],\n identifier = jsondata['identifier'],\n dependencies = [MountedFSState.fromJSON(x) for x in jsondata['dependencies']],\n mountspec = jsondata['mountspec']\n )\n\ndef _merge_states(lhs,rhs):\n return MountedFSState(lhs.readwrite + rhs.readwrite,lhs.readonly + rhs.readonly, mountspec = lhs.mountspec)\n\nclass MountedFSProvider(object):\n def __init__(self, mountspec, *base_states, **kwargs):\n self.mountspec = mountspec\n base_states = list(base_states)\n self.nest = kwargs.get('nest', True)\n\n first = base_states.pop()\n assert first\n\n self.base = first\n\n while base_states:\n next_state = base_states.pop()\n if not next_state:\n continue\n self.base = _merge_states(self.base,next_state)\n\n def new_provider(self,name):\n new_base_ro = self.base.readwrite + self.base.readonly\n new_base_rw = [os.path.join(self.base.readwrite[0],name)]\n return MountedFSProvider(self.mountspec,MountedFSState(new_base_rw,new_base_ro, mountspec = self.mountspec), nest = self.nest)\n\n\n def new_state(self,name):\n '''\n creates a new context from an existing context.\n\n if subdir is True it declares a new read-write nested under the old\n context's read-write and adds all read-write and read-only locations\n of the old context as read-only. This is recommended as it makes rolling\n back changes to the global state made in this context easy.\n\n else the same readwrite/readonly configuration as the parent context is used\n\n '''\n\n if self.base is None:\n new_readwrites = [os.path.abspath(name)]\n else:\n new_readwrites = ['{}/{}'.format(self.base.readwrite[0],name)] if self.nest else self.base.readwrite\n\n if self.nest:\n # for nested directories, we want to have at lease read access to all data in parent context\n new_readonlies = [ro for ro in itertools.chain(self.base.readonly,self.base.readwrite)] if self.base else []\n else:\n new_readonlies = self.base.readonly if self.base else []\n\n log.debug('new context is: rw: %s, ro: ', new_readwrites, new_readonlies)\n new_identifier = name.replace('/','_') # replace in case name is nested path\n newstate = MountedFSState(readwrite = new_readwrites, readonly = new_readonlies, identifier = new_identifier, mountspec = self.mountspec)\n\n return newstate\n\n def json(self):\n return {\n 'state_provider_type': 'mountedfs_provider',\n 'base_state': self.base.json(),\n 'nest': self.nest,\n 'mountspec': self.mountspec\n }\n\n @classmethod\n def fromJSON(cls,jsondata):\n return cls(MountedFSState.fromJSON(jsondata['mountspec'],jsondata['base_state']), nest = jsondata['nest'])\n\ndef setup_provider(dataarg,dataopts):\n mountspec = dataopts.get('mountspec',None)\n if mountspec:\n mountspec = yaml.load(open(mountspec))\n return MountedFSProvider(mountspec, MountedFSState([os.path.join('/',dataarg)]))\n","sub_path":"mounted_state/mounted_posix.py","file_name":"mounted_posix.py","file_ext":"py","file_size_in_byte":5041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"66055945","text":"import numpy as np\nimport pandas as pd\nfrom numba import jit\n\n\ndef pandas_update(state, root_cov, measurement, loadings, meas_var):\n \"\"\"Update *state* and *root_cov* with with a *measurement*.\n Args:\n state (pd.Series): pre-update estimate of the unobserved state vector\n root_cov (pd.DataFrame): lower triangular matrix square-root of the\n covariance matrix of the state vector before the update\n measurement (float): the measurement to incorporate\n loadings (pd.Series): the factor loadings\n meas_var(float): variance of the measurement error\n Returns:\n updated_state (pd.Series)\n updated_root_cov (pd.DataFrame)\n \"\"\"\n expected_measurement = state.dot(loadings)\n residual = measurement - expected_measurement\n f_star = root_cov.T.dot(loadings)\n first_row = pd.DataFrame(\n data=[np.sqrt(meas_var)] + [0] * len(loadings),\n index=[0] + list(state.index)).T\n other_rows = pd.concat([f_star, root_cov.T], axis=1)\n m = pd.concat([first_row, other_rows])\n r = np.linalg.qr(m, mode='r')\n root_sigma = r[0, 0]\n kalman_gain = pd.Series(r[0, 1:], index=state.index) / root_sigma\n updated_root_cov = pd.DataFrame(\n data=r[1:, 1:],\n columns=state.index,\n index=state.index,\n ).T\n updated_state = state + kalman_gain * residual\n\n return updated_state, updated_root_cov\n\n\ndef pandas_batch_update(states, root_covs, measurements, loadings, meas_var):\n \"\"\"Call pandas_update repeatedly.\n Args:\n states (pd.DataFrame)\n root_covs (list)\n measurements (pd.Series)\n loadings (pd.Series)\n meas_var (float)\n Returns:\n updated_states (pd.DataFrame)\n updated_root_covs (list)\n \"\"\"\n out_states = []\n out_root_covs = []\n for i in range(len(states)):\n updated_state, updated_root_cov = pandas_update(\n state=states.loc[i],\n root_cov=root_covs[i],\n measurement=measurements[i],\n loadings=loadings,\n meas_var=meas_var\n )\n out_states.append(updated_state)\n out_root_covs.append(updated_root_cov)\n out_states = pd.concat(out_states, axis=1).T\n return out_states, out_root_covs\n\n\ndef fast_batch_update_np(states, root_covs, measurements, loadings, meas_var):\n \"\"\"Update state estimates for a whole dataset by numpy.\n Let nstates be the number of states and nobs the number of observations.\n Args:\n states (np.ndarray): 2d array of size (nobs, nstates)\n root_covs (np.ndarray): 3d array of size (nobs, nstates, nstates)\n measurements (np.ndarray): 1d array of size (nobs)\n loadings (np.ndarray): 1d array of size (nstates)\n meas_var (float):\n Returns:\n updated_states (np.ndarray): 2d array of size (nobs, nstates)\n updated_root_covs (np.ndarray): 3d array of size (nobs, nstates, nstates)\n \"\"\"\n residuals = measurements - np.dot(states, loadings)\n\n f_star = np.dot(root_covs.transpose((0, 2, 1)), loadings).reshape(len(states), len(loadings), 1)\n m_left = np.concatenate([np.full((len(states), 1, 1), np.sqrt(meas_var)), f_star], axis=1)\n m_right = np.concatenate([np.zeros((len(states), 1, len(loadings))), root_covs.transpose((0, 2, 1))], axis=1)\n m = np.concatenate([m_left, m_right], axis=2)\n\n updated_states = np.zeros((len(states), len(loadings)))\n updated_root_covs = np.zeros((len(states), len(loadings), len(loadings)))\n for i in range(len(states)):\n r = np.linalg.qr(m[i], mode='r')\n root_sigma = r[0, 0]\n kalman_gain = r[0, 1:] / root_sigma\n updated_root_covs[i] = r[1:, 1:].T\n updated_states[i] = states[i] + np.dot(kalman_gain, residuals[i])\n\n return updated_states, updated_root_covs\n\n\n@jit(nopython=True, cache=True)\ndef fast_batch_update(states, root_covs, measurements, loadings, meas_var):\n \"\"\"Update state estimates for a whole dataset by numba.\n Let nstates be the number of states and nobs the number of observations.\n Args:\n states (np.ndarray): 2d array of size (nobs, nstates)\n root_covs (np.ndarray): 3d array of size (nobs, nstates, nstates)\n measurements (np.ndarray): 1d array of size (nobs)\n loadings (np.ndarray): 1d array of size (nstates)\n meas_var (float):\n Returns:\n updated_states (np.ndarray): 2d array of size (nobs, nstates)\n updated_root_covs (np.ndarray): 3d array of size (nobs, nstates, nstates)\n \"\"\"\n residuals = measurements - np.dot(states, loadings)\n\n f_star = np.zeros((len(states), len(loadings), 1))\n for i in range(len(root_covs)):\n f_star[i] = np.dot(root_covs[i].T, loadings.reshape(len(loadings), 1))\n\n m_left = np.zeros((len(states), len(loadings)+1, 1))\n m_left[:, :1, :] = np.full((len(states), 1, 1), np.sqrt(meas_var))\n m_left[:, 1:, :] = f_star\n m_right = np.zeros((len(states), len(loadings)+1, len(loadings)))\n m_right[:, :1, :] = np.zeros((len(states), 1, len(loadings)))\n m_right[:, 1:, :] = root_covs.transpose((0, 2, 1))\n m = np.zeros((len(states), len(loadings)+1, len(loadings)+1))\n m[:, :, :1] = m_left\n m[:, :, 1:] = m_right\n\n updated_states = np.zeros((len(states), len(loadings)))\n updated_root_covs = np.zeros((len(states), len(loadings), len(loadings)))\n for i in range(len(states)):\n q, r = np.linalg.qr(m[i])\n root_sigma = r[0, 0]\n kalman_gain = r[0, 1:] / root_sigma\n updated_root_covs[i] = r[1:, 1:].T\n updated_states[i] = states[i] + kalman_gain * residuals[i]\n\n return updated_states, updated_root_covs\n","sub_path":"src/model_code/update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":5636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"10669375","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2015, ParaTools, Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n# (1) Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n# (2) Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n# (3) Neither the name of ParaTools, Inc. nor the names of its contributors may\n# be used to endorse or promote products derived from this software without\n# specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n\"\"\"TAU Commander command line interface (CLI).\n\nExtensions to :any:`argparse` to support the TAU Commander command line interface.\n\"\"\"\n\nimport os\nimport argparse\nimport textwrap\nfrom operator import attrgetter\nfrom tau import logger, util\n\nSUPPRESS = argparse.SUPPRESS\n\"\"\"Suppress attribute creation in parsed argument namespace.\"\"\"\n\nREMAINDER = argparse.REMAINDER\n\"\"\"All the remaining command-line arguments are gathered into a list.\"\"\"\n\nSTORAGE_LEVEL_FLAG = \"@\"\n\"\"\"Command line flag that indicates storage level.\"\"\"\n\n\nclass MutableGroupArgumentParser(argparse.ArgumentParser):\n \"\"\"Argument parser with mutable groups and better help formatting.\n\n :py:class:`argparse.ArgumentParser` doesn't allow groups to change once set \n and generates \"scruffy\" looking help, so we fix this problems in this subclass.\n \"\"\"\n # We're changing the behavior of the superclass so we need to access protected members\n # pylint: disable=protected-access\n\n def add_argument_group(self, *args, **kwargs):\n \"\"\"Returns an argument group.\n \n If the group doesn't exist it will be created.\n \n Args:\n *args: Positional arguments to pass to :any:`ArgumentParser.add_argument_group`\n **kwargs: Keyword arguments to pass to :any:`ArgumentParser.add_argument_group`\n\n Returns:\n An argument group object.\n \"\"\"\n title = kwargs.get('title', args[0])\n for group in self._action_groups:\n if group.title == title:\n return group\n return super(MutableGroupArgumentParser, self).add_argument_group(*args, **kwargs)\n\n def format_help(self):\n \"\"\"Format command line help string.\"\"\"\n formatter = self._get_formatter()\n formatter.add_usage(self.usage, self._actions, self._mutually_exclusive_groups)\n formatter.add_text(self.description)\n for action_group in self._sorted_groups():\n formatter.start_section(action_group.title)\n formatter.add_text(action_group.description)\n formatter.add_arguments(sorted(action_group._group_actions, key=attrgetter('option_strings')))\n formatter.end_section()\n formatter.add_text(self.epilog)\n return formatter.format_help()\n\n def _sorted_groups(self):\n \"\"\"Iterate over action groups.\"\"\"\n positional_title = 'positional arguments'\n optional_title = 'optional arguments'\n groups = sorted(self._action_groups, key=lambda x: x.title.lower())\n for group in groups:\n if group.title == positional_title:\n yield group\n break\n for group in groups:\n if group.title == optional_title:\n yield group\n break\n for group in groups:\n if group.title not in [positional_title, optional_title]:\n yield group\n \n def merge(self, parser, group_title=None, include_positional=True, include_optional=True, include_storage=False):\n group = self.add_argument_group(group_title) if group_title else self\n for action in parser._actions:\n optional = bool(action.option_strings)\n storage = '-'+STORAGE_LEVEL_FLAG in action.option_strings\n if ((not include_storage and storage) or \n (not include_optional and optional) or \n (not include_positional and not optional)):\n continue\n try:\n group._add_action(action)\n except argparse.ArgumentError:\n pass\n\n\nclass ArgparseHelpFormatter(argparse.RawDescriptionHelpFormatter):\n \"\"\"Custom help string formatter for argument parser.\n \n Provide proper help message alignment, line width, and formatting.\n Uses console line width (:any:`logger.LINE_WIDTH`) to format help \n messages appropriately so they don't wrap in strange ways.\n \n Args:\n prog (str): Name of the program.\n indent_increment (int): Number of spaces to indent wrapped lines.\n max_help_position (int): Column on which to begin subsequent lines of wrapped help strings.\n width (int): Maximum help message length before wrapping.\n \"\"\"\n\n def __init__(self, prog, indent_increment=2, max_help_position=30, width=logger.LINE_WIDTH):\n super(ArgparseHelpFormatter, self).__init__(prog, indent_increment, max_help_position, width)\n\n def _split_lines(self, text, width):\n parts = []\n for line in text.splitlines():\n parts.extend(textwrap.wrap(line, width))\n return parts\n\n def _get_help_string(self, action):\n indent = ' ' * self._indent_increment\n helpstr = action.help\n choices = getattr(action, 'choices', None)\n if choices:\n helpstr += '\\n%s- %s: %s' % (indent, action.metavar, ', '.join(choices))\n if '%(default)' not in action.help:\n if action.default is not argparse.SUPPRESS:\n defaulting_nargs = [argparse.OPTIONAL, argparse.ZERO_OR_MORE]\n if action.option_strings or action.nargs in defaulting_nargs:\n if isinstance(action.default, list):\n default_str = ', '.join(action.default)\n else:\n default_str = str(action.default)\n helpstr += '\\n%s' % indent + '- default: %s' % default_str\n return helpstr\n\n\nclass ParsePackagePathAction(argparse.Action):\n \"\"\"Argument parser action for software package paths.\n \n This action checks that an argument's value is one of these cases:\n 1) The path to an existing software package installation.\n 2) The path to an archive file containing the software package.\n 3) A URL to an archive file containing the software package.\n 4) The magic word \"download\" or value that parses to True via :any:`tau.util.parse_bool`.\n 5) A value that parses to False via :any:`parse_bool`.\n \"\"\"\n # pylint: disable=too-few-public-methods\n\n def __call__(self, parser, namespace, flag, unused_option_string=None):\n \"\"\"Sets the `self.dest` attribute in `namespace` to the parsed value of `flag`.\n \n If `flag` parses to a boolean True value then the attribute value is 'download'.\n If `flag` parses to a boolean False value then the attribute value is ``None``.\n Otherwise the attribute value is the value of `flag`.\n \n Args:\n parser (str): Argument parser object this group belongs to.\n namespace (object): Namespace to receive parsed value via setattr.\n flag (str): Value parsed from the command line.\n \"\"\"\n try:\n flag_as_bool = util.parse_bool(flag, additional_true=['download'])\n except TypeError:\n if util.is_url(flag):\n value = flag\n else:\n value = os.path.abspath(os.path.expanduser(flag))\n if not (os.path.isdir(value) or util.file_accessible(value)):\n raise argparse.ArgumentError(self, \"Boolean, 'download', valid path, or URL required: %s\" % value)\n else:\n if flag_as_bool == True:\n value = 'download'\n elif flag_as_bool == False:\n value = None\n setattr(namespace, self.dest, value)\n\n\nclass ParseBooleanAction(argparse.Action):\n \"\"\"Argument parser action for boolean values.\n \n Essentially a wrapper around :any:`tau.util.parse_bool`.\n \"\"\"\n # pylint: disable=too-few-public-methods\n\n def __call__(self, parser, namespace, flag, unused_option_string=None):\n \"\"\"Sets the `self.dest` attribute in `namespace` to the parsed value of `flag`.\n \n If `flag` parses to a boolean via :any:`tau.util.parse_bool` then the \n attribute value is that boolean value.\n \n Args:\n parser (str): Argument parser object this group belongs to.\n namespace (object): Namespace to receive parsed value via setattr.\n flag (str): Value parsed from the command line/\n \"\"\"\n try:\n setattr(namespace, self.dest, util.parse_bool(flag))\n except TypeError:\n raise argparse.ArgumentError(self, 'Boolean value required')\n\n\ndef get_parser(prog=None, usage=None, description=None, epilog=None):\n \"\"\"Builds an argument parser.\n \n The returned argument parser accepts no arguments.\n Use :any:`argparse.ArgumentParser.add_argument` to add arguments.\n \n Args:\n prog (str): Name of the program.\n usage (str): Description of the program's usage.\n description (str): Text to display before the argument help.\n epilog (str): Text to display after the argument help.\n\n Returns:\n MutableGroupArgumentParser: The customized argument parser object.\n \"\"\"\n return MutableGroupArgumentParser(prog=prog,\n usage=usage,\n description=description,\n epilog=epilog,\n formatter_class=ArgparseHelpFormatter)\n\n\ndef get_parser_from_model(model, use_defaults=True, prog=None, usage=None, description=None, epilog=None):\n \"\"\"Builds an argument parser from a model's attributes.\n \n The returned argument parser will accept arguments as defined by the model's `argparse` \n attribute properties, where the arguments to :any:`argparse.ArgumentParser.add_argument` \n are specified as keyword arguments.\n \n Examples:\n Given this model attribute:\n ::\n \n 'openmp': {\n 'type': 'boolean', \n 'description': 'application uses OpenMP',\n 'default': False, \n 'argparse': {'flags': ('--openmp',),\n 'metavar': 'T/F',\n 'nargs': '?',\n 'const': True,\n 'action': ParseBooleanAction},\n }\n\n The returned parser will accept the ``--openmp`` flag accepting zero or one arguments \n with 'T/F' as the metavar. If ``--openmp`` is omitted the default value of False will\n be used. If ``--openmp`` is provided with zero arguments, the const value of True will\n be used. If ``--openmp`` is provided with one argument then the provided argument will\n be passed to a ParseBooleanAction instance to generate a boolean value. The argument's\n help description will appear as \"application uses OpenMP\" if the ``--help`` argument is given.\n \n Args:\n model (Model): Model to construct arguments from.\n use_defaults (bool): If True, use the model attribute's default value \n as the argument's value if argument is not specified. \n prog (str): Name of the program.\n usage (str): Description of the program's usage.\n description (str): Text to display before the argument help.\n epilog (str): Text to display after the argument help.\n\n Returns:\n MutableGroupArgumentParser: The customized argument parser object. \n \"\"\"\n parser = MutableGroupArgumentParser(prog=prog,\n usage=usage,\n description=description,\n epilog=epilog,\n formatter_class=ArgparseHelpFormatter)\n groups = {}\n for attr, props in model.attributes.iteritems():\n try:\n options = dict(props['argparse'])\n except KeyError:\n continue\n if use_defaults:\n options['default'] = props.get('default', argparse.SUPPRESS) \n else:\n options['default'] = argparse.SUPPRESS\n try:\n options['help'] = props['description']\n except KeyError:\n pass\n try:\n group_name = options['group'] + ' arguments'\n except KeyError:\n group_name = model.name.lower() + ' arguments'\n else:\n del options['group']\n group = groups.setdefault(group_name, parser.add_argument_group(group_name))\n try:\n flags = options['flags']\n except KeyError:\n flags = (attr,)\n else:\n del options['flags']\n options['dest'] = attr\n group.add_argument(*flags, **options)\n return parser\n\ndef add_storage_flags(parser, action, object_name, plural=False, exclusive=True):\n \"\"\"Add flags to indicate target storage container.\n \n Args:\n parser (MutableGroupArgumentParser): The parser to modify.\n action (str): The action that will be taken by the command, e.g. \"delete\" or \"list\"\n object_name (str): The type of object that will be manipulated, e.g. \"application\" or \"measurement\"\n plural (bool): Pluralize help message if True.\n exclusive (bool): Only one storage level may be specified if True.\n \"\"\"\n from tau.storage.levels import ORDERED_LEVELS\n help_parts = [\"%s %ss\" if plural else \"%s the %s\",\n \" at the specified storage \",\n \"level\" if exclusive else \"levels\"]\n help_str = \"\".join(help_parts) % (action, object_name)\n nargs = 1 if exclusive else '+'\n choices = [container.name for container in ORDERED_LEVELS]\n default = [ORDERED_LEVELS[0].name]\n parser.add_argument('-'+STORAGE_LEVEL_FLAG,\n help=help_str,\n metavar=\"\", \n nargs=nargs, \n choices=choices,\n default=default)\n","sub_path":"packages/tau/cli/arguments.py","file_name":"arguments.py","file_ext":"py","file_size_in_byte":15262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"546685026","text":"#!/usr/bin/env python\n#\n\n# This python script plots vorticity swaths overlaid from different ensemble members\n# produced from a pyencommas run. Its intent is for an ensemble tornado prediction study.\n\n# Import needed libraries\n\nfrom optparse import OptionParser\nimport glob\nimport json\nimport time\nimport netCDF4 as ncdf\nimport os, sys\nfrom numpy import *\nimport numpy as N\nimport datetime as DT\nimport matplotlib.pyplot as P\nimport matplotlib\nimport matplotlib.cm as cm\nfrom matplotlib import ticker\nfrom scipy.interpolate import griddata\nfrom mpl_toolkits.basemap import Basemap\nfrom mpl_toolkits.axes_grid import AxesGrid\nfrom mpl_toolkits.axes_grid.inset_locator import inset_axes\nimport ctables\nfrom matplotlib.offsetbox import AnchoredText\nfrom scipy import signal\n\nimport Plotting.cbook2 as cbook\nimport ctables\nimport ens\nfrom matplotlib.colors import BoundaryNorm\n\nfrom state_vector import vswath\nfrom Plotting import shapefiles\n\nimport fsrc.cressman as cress\n\n#===================================================================================================\ndef gauss_kern(size, sizey=None):\n \"\"\" Returns a normalized 2D gauss kernel array for convolutions \"\"\"\n size = int(size)\n if not sizey:\n sizey = size\n else:\n sizey = int(sizey)\n x, y = N.mgrid[-size:size+1, -sizey:sizey+1]\n g = N.exp(-(x**2/float(size) + y**2/float(sizey)))\n return g / g.sum()\n\n#===================================================================================================\ndef gauss_prob(im, n, ny=None):\n \"\"\" blurs the image by convolving with a gaussian kernel of typical\n size n. The optional keyword argument ny allows for a different\n size in the y direction.\n \"\"\"\n\n g = gauss_kern(n/2)\n\n nx = im.shape[0]\n ny = im.shape[1]\n buf = n / 2\n improc = N.zeros(im.shape)\n\n improc[buf:nx-buf,buf:ny-buf] = signal.convolve2d(im, g, mode='valid')\n\n return(improc)\n\n#===================================================================================================\ndef nearest_N_prob(im, n):\n \"\"\"\n Uses a 2D convolution operator to see if any N x N neighbors have a non-zero entry\n \"\"\"\n\n g = N.ones([n,n])\n g /= g.sum()\n\n nx = im.shape[0]\n ny = im.shape[1]\n buf = n / 2\n improc = N.zeros(im.shape)\n\n improc[buf:nx-buf,buf:ny-buf] = signal.convolve2d(im, g, mode='valid')\n\n return( N.where(improc > 0.0, 1.0, 0.0) )\n \n#---------------------------------------------------------------------------------------------------\n# PARAMETERS\n\n_yes_plot = True\n_write_prob = False # set this to True if you want to write prob data out to a file\n\n_plotpcolormesh = False\n_plotfilename = \"par_2km\"\n_runname = 'par_2km' # Runname prefix\n_threshold = 0.005 # threshold of vorticity\n_threshold2 = -0.010\nmember_start = 1\nmember_end = 40\nmember_step = 1\nens_size = (member_end - member_start + 1) / member_step # Number of ensemble members\nlevel = 8 # Vertical model level to plot\n_neighbor = 4\n\n# _default_color_table = cm.jet\n# _default_color_table = ctables.__getattribute__(\"Sobash\")\n_default_color_table = cm.OrRd\n# _default_color_table = ctables.__getattribute__(\"Thomas\")\n# _default_color_table = ctables.__getattribute__(\"WoF\")member_start = 1\n\n# Set domain boundaries\n#-----------------------\n# Trim out the plot...zoomed in view\nxplot = [-100000.,60000,4000.]\nyplot = [-50000.,110000.,4000.]\n# Trim out the plot...zoomed in view\nxplot = [-120000.,20000,4000.]\nyplot = [-20000.,120000.,4000.]\n\n\n# Stuff for overlays from DBZ files\n#-----------------------\ndbz_threshold = 40\n_overlayfile = [\"PAR_1min_DBZ_F2020_Valid_T+30min.nc\"]\n_overlayfile = [\"PAR_5min_DBZ_F2020_Valid_T+10min.nc\"]\n_overlayfile = [\"PAR_5min_DBZ_F2020_Valid_T+20min.nc\"]\n_overlayfile = [\"PAR_5min_DBZ_F2020_Valid_T+30min.nc\"]\n_overlayfile = None\n\n#===================================================================================================\ndef mtokm(val,pos):\n \"\"\"Convert m to km for formatting axes tick labels\"\"\"\n val=val/1000.0\n return '%i' % val\n \n#===================================================================================================\n# Read U & V and compute return vorticity\n\ndef CM1_get_Wz(files, exper):\n\n xoffset = exper['xoffset']\n yoffset = exper['yoffset']\n\n wz_ens = N.zeros((ens_size,level,exper['cm1namelist'][0][2],exper['cm1namelist'][1][2]))\n \n for n, file in enumerate(files[0:ens_size]):\n f = ncdf.Dataset(file, \"r\")\n if n == 0:\n xc = f.variables['xh'][:] + xoffset\n yc = f.variables['yh'][:] + yoffset\n \n wz_ens[n] = ens.ComputeWZ(xc, yc, f.variables['ua'][0:level], f.variables['va'][0:level])\n \n return wz_ens, xc, yc\n\n#===================================================================================================\n# Main function defined to return correct sys.exit() calls\n\nfig_type = 'pdf' # Figure type (pdf, png, eps, etc.)\n\nprint(\"\\n<<<<<===========================================================================================>>>>>>\")\nprint(\"\\n\\n VORT SWATH PLOT \\n\\n\")\n\nusage = \"usage: %prog [options] arg\"\nparser = OptionParser(usage)\n\nparser.add_option(\"-d\", \"--dir\", dest=\"dir\", default=None, type=\"string\", help = \"Experiment directory - looks for a *.exp file in this directory\")\nparser.add_option(\"-e\", \"--exp\", dest=\"exp\", default=None, type=\"string\", help = \"Path to the json experiment file generated by run\")\nparser.add_option(\"-t\", \"--time\", dest=\"datetime\", default=None, type= \"string\", help = \"Usage: --time 2003,5,8,21,0,0\")\nparser.add_option( \"--fcst\", dest=\"fcst\", default=None, type=\"int\", nargs=2, help=\"Length of time, in model secs for swatch and number of sec between analysis times\")\nparser.add_option( \"--title\", dest=\"title\", default=None, type=\"string\", help=\"name of plot\")\nparser.add_option( \"--noshow\", dest=\"noshow\", default=False, action=\"store_true\", help=\"Turn off screen plotting\")\n\n(options, args) = parser.parse_args()\n\nif options.exp == None:\n options.exp = glob.glob(os.path.join(options.dir, \"*.exp\" ))[0]\n print(\"\\n ==> ENS_MAIN: found experiment files %s\" % options.exp)\n\nif options.exp == None:\n parser.print_help()\n print(\"\\n ==> ENS_MAIN: ERROR --> Experiment's filename not supplied..EXITING!!!\")\n sys.exit(-1)\nelse:\n with open(options.exp, 'rb') as f:\n exper = json.load(f)\n if options.dir:\n exper['base_dir'] = options.dir\n\nif options.datetime == None:\n parser.print_help()\n print(\"\\n ==> ENS_MAIN: ERROR --> time for files not supplied..EXITING!!!\")\n sys.exit(-1)\nelse:\n dt = [int(i) for i in options.datetime.split(',')]\n myDT = DT.datetime(dt[0],dt[1],dt[2],dt[3],dt[4],dt[5])\n\nif options.title:\n plotfilename = options.title\n if plotfilename.find(\"VP\") == -1:\n plotfilename = plotfilename+\"_VP\"\nelse:\n plotfilename = options.dir+\"_VP\"\n\nif options.fcst == None:\n parser.print_help()\n print(\"\\n ==> ENS_MAIN: ERROR -->forecast time for files and secs between forecast times not supplied..EXITING!!!\")\n sys.exit(-1)\nelse:\n fcstlen, dt_files = options.fcst[0], options.fcst[1]\n ntimes = 1 + fcstlen/dt_files\n\nprint(\"\\nStarting time of the forecast: %s\" % myDT.strftime(\"%H:%M:%S\"))\nprint(\"\\nEndding time of the forecast: %d\" % fcstlen)\nprint(\"\\nTime between files to be read in: %d\" % dt_files)\nprint(\"\\nNumber of files to be read in: %d\" % ntimes)\nprint(\"\\nSize of the ensemble be read in: %d\" % ens_size)\n\n# Create masterlist of files and date and times\n\nmaster_list = []\nmaster_DT = []\n\nfor n in N.arange(ntimes):\n master_DT.append(myDT + DT.timedelta(seconds=int(n*dt_files)))\n master_list.append(ens.FindRestartFiles(exper, master_DT[n], ret_exp=False, ret_DT=False))\n\nny, nx = exper['cm1namelist'][1][2],exper['cm1namelist'][0][2]\ndx, dy = exper['cm1namelist'][3][2],exper['cm1namelist'][4][2]\nlat0, lon0 = exper['lat0'], exper['lon0']\n\nvvort = N.zeros((ntimes,ens_size,level,ny,nx))\nvvmean = N.zeros((ntimes,ens_size,ny,nx))\n\nfor n in N.arange(ntimes):\n print(\"Reading and computing Vert. Vort for ensemble at time %s\" % master_DT[n].strftime(\"%H:%M:%S\"))\n vvort[n], xc, yc = CM1_get_Wz(master_list[n], exper)\n vvmean[n] = vvort[n].mean(axis=1)\n \n# Coming out of this, you now have VVort(ntimes, nens, 0:level, ny, nx), VVmean[ntimes,nens, ny, nx], xx[ntimes,ny,nx], yy[ntimes,ny,nx]\n\nif xplot:\n x_swath = xplot[0] + xplot[2]*N.arange(1+N.int((xplot[1]-xplot[0])/xplot[2]))\n y_swath = yplot[0] + yplot[2]*N.arange(1+N.int((yplot[1]-yplot[0])/yplot[2]))\nelse:\n x_swath = xc\n y_swath = yc\n \nvort = N.zeros((x_swath.size,y_swath.size), order='F')\nxx, yy = N.meshgrid(xc, yc)\n \nfor n in N.arange(ens_size):\n\n for m in N.arange(ntimes):\n \n if m == 0:\n xobs = xx.flatten()\n yobs = yy.flatten()\n obs = vvmean[m,n].flatten()\n xobs2 = xx.flatten()\n yobs2 = yy.flatten()\n obs2 = vvmean[m,n].flatten()\n else:\n xobs = N.concatenate((xobs,xx.flatten()))\n yobs = N.concatenate((yobs,yy.flatten()))\n obs = N.concatenate((obs,vvmean[m,n].flatten()))\n xobs2 = N.concatenate((xobs,xx.flatten()))\n yobs2 = N.concatenate((yobs,yy.flatten()))\n obs2 = N.concatenate((obs,vvmean[m,n].flatten()))\n\n mask1 = where(obs > _threshold)\n obs[mask1] = 1.0\n\n if obs[mask1].size > 0:\n vort = vort + cress.cressman(xobs[mask1], yobs[mask1], obs[mask1], x_swath, y_swath, _neighbor*dx)\n\nprob1 = (vort.transpose()/ens_size)*100.\n# \nprint(\"\\nMax probability is: \",prob1.max(),\"\\n\")\nprint(\"\\nMin probability is: \",prob1.min(),\"\\n\")\n\n\n#-----------------\nif _yes_plot:\n\n fig, ax = P.subplots(1, 1, figsize=(12,10), sharex=True, sharey=True)\n\n# Create map coordinates\n#-------------------\n\n map = ens.mymap(x_swath, y_swath, lat0, lon0, ax = ax, shape_env=shapefiles, counties=True, noticks=False)\n lon2d, lat2d, x2d, y2d = map.makegrid(x_swath.size, y_swath.size, returnxy=True)\n\n clevels = [0.0, 9., 10., 20, 30., 40., 50., 60., 70., 80., 90., 100.]\n clevels = [0.0, 25., 30., 40.0, 45., 50., 55., 60., 65., 70., 75., 80., 85., 90., 95., 100.]\n clevels = [1., 10., 20., 40., 60., 80., 100.]\n\n cmap = _default_color_table\n plot = map.contourf(x2d, y2d, prob1, cmap=cmap, levels=clevels, ax=ax)\n cbar = map.colorbar(plot,location='bottom',pad=\"5%\")\n cbar.set_label('Ensemble Mean Probability of Vert. Vort > %4.4f %s' % (_threshold, \"$s^{-1}$\"))\n \n# plot = map.contour(xx, yy, prob1.transpose(), colors='k', alpha=0.2, levels=[10.])\n# plot = map.contour(xx, yy, prob1.transpose(), colors='k', alpha=0.3, levels=[50.])\n# plot = map.contour(xx, yy, prob1.transpose(), colors='k', alpha=1.0, levels=[90.])\n\n if _threshold2 > 0.0:\n vlat, vlon = cbook.dxy_2_dll(xobs2, yobs2, lat0, lon0, degrees=True)\n xx2, yy2 = map(vlon, vlat)\n map.plot(xx2, yy2, 'o', markersize=2, markerfacecolor='blue')\n \n\n# OVERLAY dBZ information\n#-------------------------\n if _overlayfile != None:\n\n fover = netcdf.Dataset(overlayfile, \"r\")\n prob_dbz = fover.variables['PROB'][...]\n mean_dbz = fover.variables['MEAN'][...]\n obs_dbz = fover.variables['OBS'][...]\n\n # Plot mean threshold contour (using negatives to automatically get dashed contour)\n plot = map.contour(xx, yy, mean_dbz, colors='r', linewidths=2.0, levels=[-dbz_threshold])\n \n # Plot Actual thresholded reflectivity from radar\n plot = map.contour(xx, yy, obs_dbz, colors='r', linewidths=4.0, levels=[dbz_threshold])\n plot = map.contourf(xx, yy, obs_dbz, colors='r', alpha = 0.1, levels=[dbz_threshold,80.])\n fover.close()\n\n# Label some things\n#------------------\n\n DTstart = master_DT[0]\n DTend = master_DT[-1]\n DT_yymmdd = DTstart.strftime(\"%m-%d-%Y\")\n DT_hhmmss = DTstart.strftime(\"%H:%M\")\n DTend_hhmmss = DTend.strftime(\"%H:%M\")\n\n title = \"%s\\n%d minute FCST (%s to %s UTC)\\n Mean Vertical Vorticity computed in layer below %3.2f KM\" \\\n % (DT_yymmdd, fcstlen/60, DT_hhmmss, DTend_hhmmss, 1.) \n \n ax.set_title(title, size='x-large')\n ax.set_aspect('equal')\n\n at = AnchoredText(\"Max Probability: %d %s\" % (prob1.max(),\"%\"), loc=4, prop=dict(size=10), frameon=True,)\n at.patch.set_boxstyle(\"round,pad=0.,rounding_size=0.2\")\n ax.add_artist(at)\n\n at = AnchoredText(\"%s\" % (plotfilename), loc=2, prop=dict(size=8), frameon=True,)\n at.patch.set_boxstyle(\"round,pad=0.,rounding_size=0.2\")\n ax.add_artist(at)\n\n# End Plot Section\n#-----------------\n# Write file\n\nif _write_prob and not probfile:\n if threshold2 > 0.0 and xobs2.size > 0:\n write_prob(plotfilename, lat2d, lon2d, prob1, threshold, 1000., coards, starttime, endtime, \\\n thres2 = threshold2, xlats = xobs2, ylats = yobs2)\n else:\n write_prob(plotfilename, lat2d, lon2d, prob1, threshold, 1000., coards, starttime, endtime)\n\n# Save fig\n#---------\n\nif _yes_plot:\n P.savefig(plotfilename+\".pdf\",dpi=300)\n\n if not options.noshow:\n P.show()\n\n#########################################################################\n# Fortran90 Code for Cressman routine\n#\n# compile the fortran cressman.f90 routine with...\n# \n# f2py --fcompiler=\"gnu95\" --f90flags='-m64 -O3 -funroll-loops' -DF2PY_REPORT_ON_ARRAY_COPY -c -m cressman cressman.f90\n\n#subroutine cressman(x, y, ob, xg, yg, roi, anal, nobs, nx, ny)\n# implicit none\n# integer :: nobs, nx, ny\n# real(8) :: x(nobs), y(nobs), ob(nobs)\n# real(8) :: xg(nx), yg(ny)\n# real(8), intent(out) :: anal(nx,ny)\n# real(8) :: roi\n#\n#!f2py real(8), intent(in), dimension(nobs) :: x\n#!f2py real(8), intent(in), dimension(nobs) :: y\n#!f2py real(8), intent(in), dimension(nobs) :: ob\n#!f2py real(8), intent(in), dimension(nx) :: xg\n#!f2py real(8), intent(in), dimension(ny) :: yg\n#!f2py real(8), intent(out), dimension(nx,ny) :: anal\n#!f2py real, intent(in) :: roi\n#!f2py integer, intent(in) :: nobs, nx, ny\n#\n# integer n, i, j\n# real dis, R2, w_sum, top, wk, rk2\n# real, parameter :: hsp = 1.33\n#\n# R2 = roi**2.0\n#\n#! print *, 'Maxval of anal before: ', maxval(anal)\n#\n# DO j = 1,ny\n# DO i = 1,nx\n# w_sum = 0.0\n# top = 0.0 \n#! anal(i,j) = 0.0\n# DO n = 1,nobs\n# dis = sqrt( (xg(i) - x(n))**2 + (yg(j)-y(n))**2 )\n# IF (dis .le. roi) THEN\n# rk2 = dis**2.0\n# wk = (R2-rk2) / (R2+rk2)\n# top = top + wk*ob(n)\n# w_sum = w_sum + wk\n# ENDIF\n#\n#! IF (dis .le. 4.*roi) THEN\n#! wk = exp( -((dis/(hsp*roi))**2) )\n#! top = top + wk*ob(n)\n#! w_sum = w_sum + wk\n#! ENDIF\n#\n# ENDDO\n#\n# IF (w_sum .ge. 0.0001) THEN\n# anal(i,j) = anal(i,j) + min(top/w_sum,1.0)\n# ENDIF\n#\n# ENDDO\n# ENDDO\n#\n#! print *, 'Maxval of anal after: ', maxval(anal)\n#end subroutine cressman\n","sub_path":"vort_prob_CM1.py","file_name":"vort_prob_CM1.py","file_ext":"py","file_size_in_byte":14956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"600518487","text":"#project 3 by Jessica Stuart\n\n# code developed by Jackie Cohen; revised by Paul Resnick\n# further revised by Colleen van Lent for Python3\nimport nltk # requires some downloading/installing dependencies to use all its features; numpy is especially tricky to install\nimport random\n\n#import nltk\nnltk.download('punkt')\n#nltk.download()\n\nfrom nltk import word_tokenize,sent_tokenize\nfrom nltk.text import Text\nfrom nltk.corpus import gutenberg\n\ndebug = False #True\n\n# get file from user to make mad lib out of\nif debug:\n\tprint (\"Getting information from file madlib_test.txt...\\n\")\n\nfname = \"austen-sense.txt\" # need a file with this name in directory\n\nf = open(fname, 'r')\npara = f.read()\n\ntokens = nltk.word_tokenize(para)\n#print(\"TOKENS\")\n#print(tokens[:151])\ntagged_tokens = nltk.pos_tag(tokens) # gives us a tagged list of tuples\n#print(\"TAGGED TOKENS\")\n#print(tagged_tokens)\nif debug:\n\tprint (\"First few tagged tokens are:\")\n\tfor tup in tagged_tokens[:151]:\n\t\tprint (tup)\nx = []\nfor each in tagged_tokens[:151]:\n\tx.append(each[0])\n\nprint ( \" \". join(x))\n\ntagmap = {\"NN\":\"a noun\",\"NNS\":\"a plural noun\",\"VB\":\"a verb\",\"JJ\":\"an adjective\", \"PRP\": \"a preposition\"}\nsubstitution_probabilities = {\"NN\":.15,\"NNS\":.10,\"VB\":.10,\"JJ\":.10, \"PRP\":.10}\n\ndef spaced(word):\n\tif word in [\",\", \".\", \"?\", \"!\", \":\"]:\n\t\treturn word\n\telse:\n\t\treturn \" \" + word\n\nfinal_words = []\n\ncount = 0 \nfor (word, tag) in tagged_tokens:\n\tif count <= 151: \n\t\tif tag not in substitution_probabilities or random.random() > substitution_probabilities[tag]:\n\t\t\tfinal_words.append(spaced(word))\n\t\telse:\n\t\t\tnew_word = input(\"Please enter %s:\\n\" % (tagmap[tag]))\n\t\t\tfinal_words.append(spaced(new_word))\n\t\t\tcount +=1\n\t\t\tcontinue \n\nprint (\"\".join(final_words))","sub_path":"madlibhw3.py","file_name":"madlibhw3.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"648151296","text":"from datastore.models import *\nfrom datastore import db\nimport random\n\ndef product(*args):\n return reduce(lambda x,y: x*y, args[0])\n\nmapping = {\n 1:sum,\n 2:product\n}\n\nlist_of_db_tables = []\nfor key in locals().keys():\n if \"Data\" in key:\n list_of_db_tables.append(locals()[key])\n\nfor Data in list_of_db_tables:\n num_params = 0\n for i in dir(Data):\n if \"param\" in i:\n num_params += 1\n for i in xrange(10000):\n params = [random.randint(0,200) for elem in xrange(num_params)]\n result = sum(params)\n data = params + [result]\n d = Data(*data)\n db.session.add(d)\n db.session.commit()\n","sub_path":"code/intro_to_ml/generate_data.py","file_name":"generate_data.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"581335912","text":"import json\nimport os\nimport numpy as np\nimport tensorflow as tf\nimport pickle as pkl\nimport modeling\nimport collections\n\nfrom tensorflow.contrib import tpu\nfrom tqdm import tqdm\n\nimport optimization\nfrom EvalHook import EvalHook\nfrom run_classifier import FLAGS\nfrom utils import PRF, eval_reranker, print_metrics\nfrom CQAModel import DoubleModel, DoubleModelUpGradeLoss\n\nos.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = '2'\n\n\nclass InputFeatures(object):\n \"\"\"A single set of features of data.\"\"\"\n\n def __init__(self, input1_ids, input2_ids,\n input1_mask, input2_mask,\n segment1_ids, segment2_ids,\n q_type, label_id):\n self.input1_ids = input1_ids\n self.input2_ids = input2_ids\n\n self.input1_mask = input1_mask\n self.input2_mask = input2_mask\n\n self.segment1_ids = segment1_ids\n self.segment2_ids = segment2_ids\n self.q_type = q_type\n self.label_id = label_id\n\n\ndef input_fn_builder(features, seq_length, is_training, drop_remainder):\n \"\"\"Creates an `input_fn` closure to be passed to TPUEstimator.\"\"\"\n\n all_input1_ids = []\n all_input1_mask = []\n all_segment1_ids = []\n\n all_input2_ids = []\n all_input2_mask = []\n all_segment2_ids = []\n\n all_q_type = []\n all_label_ids = []\n\n for feature in features:\n all_input1_ids.append(feature.input1_ids)\n all_input1_mask.append(feature.input1_mask)\n all_segment1_ids.append(feature.segment1_ids)\n\n all_input2_ids.append(feature.input2_ids)\n all_input2_mask.append(feature.input2_mask)\n all_segment2_ids.append(feature.segment2_ids)\n\n all_q_type.append(feature.q_type)\n all_label_ids.append(feature.label_id)\n\n def input_fn(params):\n \"\"\"The actual input function.\"\"\"\n batch_size = params[\"batch_size\"]\n print(batch_size)\n num_examples = len(features)\n\n # This is for demo purposes and does NOT scale to large data sets. We do\n # not use Dataset.from_generator() because that uses tf.py_func which is\n # not TPU compatible. The right way to load data is with TFRecordReader.\n d = tf.data.Dataset.from_tensor_slices({\n \"input1_ids\":\n tf.constant(\n all_input1_ids, shape=[num_examples, seq_length],\n dtype=tf.int32),\n \"input1_mask\":\n tf.constant(\n all_input1_mask,\n shape=[num_examples, seq_length],\n dtype=tf.int32),\n \"segment1_ids\":\n tf.constant(\n all_segment1_ids,\n shape=[num_examples, seq_length],\n dtype=tf.int32),\n\n \"input2_ids\":\n tf.constant(\n all_input2_ids, shape=[num_examples, seq_length],\n dtype=tf.int32),\n \"input2_mask\":\n tf.constant(\n all_input2_mask,\n shape=[num_examples, seq_length],\n dtype=tf.int32),\n \"segment2_ids\":\n tf.constant(\n all_segment1_ids,\n shape=[num_examples, seq_length],\n dtype=tf.int32),\n\n \"q_type\":\n tf.constant(all_q_type, shape=[num_examples], dtype=tf.int32),\n \"label_ids\":\n tf.constant(all_label_ids, shape=[num_examples], dtype=tf.int32),\n })\n\n if is_training:\n d = d.repeat()\n d = d.shuffle(buffer_size=100)\n\n d = d.batch(batch_size=batch_size, drop_remainder=drop_remainder)\n return d\n\n return input_fn\n\n\ndef _creat_bert(is_training, features, bert_config, use_one_hot_embeddings, init_checkpoint):\n global initialized_variable_names\n input1_ids = features[\"input1_ids\"]\n input2_ids = features[\"input2_ids\"]\n input1_mask = features[\"input1_mask\"]\n input2_mask = features[\"input2_mask\"]\n segment1_ids = features[\"segment1_ids\"]\n segment2_ids = features[\"segment2_ids\"]\n q_type = features[\"q_type\"]\n label_ids = features[\"label_ids\"]\n\n model1 = modeling.BertModel(\n config=bert_config,\n is_training=is_training,\n input_ids=input1_ids,\n input_mask=input1_mask,\n token_type_ids=segment1_ids,\n use_one_hot_embeddings=use_one_hot_embeddings)\n model2 = modeling.BertModel(\n config=bert_config,\n is_training=is_training,\n input_ids=input2_ids,\n input_mask=input2_mask,\n token_type_ids=segment2_ids,\n use_one_hot_embeddings=use_one_hot_embeddings)\n\n tvars = tf.trainable_variables()\n\n scaffold_fn = None\n if init_checkpoint:\n (assignment_map,\n initialized_variable_names) = modeling.get_assigment_map_from_checkpoint(tvars, init_checkpoint)\n\n tf.train.init_from_checkpoint(init_checkpoint, assignment_map)\n\n # tf.logging.info(\"**** Trainable Variables ****\")\n # residue = []\n # for var in tvars:\n # init_string = \"\"\n # if var.name in initialized_variable_names:\n # init_string = \", *INIT_FROM_CKPT*\"\n # else:\n # residue.append(var)\n # tf.logging.info(\" name = %s, shape = %s%s\", var.name, var.shape,\n # init_string)\n\n output1_layer = model1.get_all_encoder_layers()[-1]\n output2_layer = model2.get_all_encoder_layers()[-1]\n\n predictions = {\"sent1\": output1_layer,\n \"sent1_mask\": input1_mask,\n\n \"sent2\": output2_layer,\n \"sent2_mask\": input2_mask,\n\n \"q_type\": q_type,\n \"label_ids\": label_ids}\n\n return predictions\n\n\ndef _create_cqa_modules(is_training, predictions):\n num_labels = 2\n q_type = predictions[\"q_type\"]\n labels = predictions[\"label_ids\"]\n\n sent1 = predictions[\"sent1\"]\n sent2 = predictions[\"sent2\"]\n\n sent1_mask = tf.cast(predictions[\"sent1_mask\"], tf.float32)\n sent2_mask = tf.cast(predictions[\"sent2_mask\"], tf.float32)\n\n mark0 = sent1[:, 0]\n mark1 = sent2[:, 0]\n\n model = DoubleModel(is_training=is_training,\n sent1=sent1, sent2=sent2,\n sent1_mask=sent1_mask, sent2_mask=sent2_mask,\n mark0=mark0, mark1=mark1)\n result = model.get_output() # (B, dim)\n\n hidden_size = result.shape[-1].value\n\n output_weights = tf.get_variable(\n \"output_weights_v2\", [num_labels, hidden_size],\n initializer=tf.truncated_normal_initializer(stddev=0.02))\n\n output_bias = tf.get_variable(\n \"output_bias_v2\", [num_labels], initializer=tf.zeros_initializer())\n\n with tf.variable_scope(\"loss\"):\n if is_training:\n # I.e., 0.1 dropout\n result = tf.nn.dropout(result, keep_prob=0.9)\n\n logits = tf.matmul(result, output_weights, transpose_b=True)\n logits = tf.nn.bias_add(logits, output_bias)\n log_probs = tf.nn.log_softmax(logits, axis=-1)\n\n one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32)\n\n per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)\n total_loss = tf.reduce_mean(per_example_loss)\n\n return total_loss, logits\n\n\ndef _create_cqa_modules_loss(is_training, predictions):\n num_labels = 2\n q_type = predictions[\"q_type\"]\n labels = predictions[\"label_ids\"]\n\n sent1 = predictions[\"sent1\"]\n sent2 = predictions[\"sent2\"]\n\n sent1_mask = tf.cast(predictions[\"sent1_mask\"], tf.float32)\n sent2_mask = tf.cast(predictions[\"sent2_mask\"], tf.float32)\n\n mark0 = sent1[:, 0]\n mark1 = sent2[:, 0]\n\n model = DoubleModelUpGradeLoss(is_training=is_training,\n sent1=sent1, sent2=sent2,\n sent1_mask=sent1_mask, sent2_mask=sent2_mask,\n mark0=mark0, mark1=mark1)\n output = model.get_output() # (B, k, dim+1)\n k = output.shape[1].value\n dim_plus = output.shape[-1].value\n result = output[:, :, :dim_plus-1]\n probs = output[:, :, dim_plus-1] # (B, k)\n\n hidden_size = result.shape[-1].value\n\n output_weights = tf.get_variable(\n \"output_weights_v2\", [num_labels, hidden_size],\n initializer=tf.truncated_normal_initializer(stddev=0.02))\n\n output_bias = tf.get_variable(\n \"output_bias_v2\", [num_labels], initializer=tf.zeros_initializer())\n\n with tf.variable_scope(\"loss\"):\n if is_training:\n # I.e., 0.1 dropout\n result = tf.nn.dropout(result, keep_prob=0.9)\n result = tf.reshape(result, [-1, hidden_size])\n logits = tf.matmul(result, output_weights, transpose_b=True)\n logits = tf.nn.bias_add(logits, output_bias)\n log_probs = tf.nn.log_softmax(logits, axis=-1)\n\n logits = tf.reshape(logits, [-1, k, 2])\n log_probs = tf.reshape(log_probs, [-1, k, 2])\n\n one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32) # (B, 2)\n one_hot_labels = tf.expand_dims(one_hot_labels, axis=1)\n\n per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1) # (B, k)\n out_indices = tf.argmin(per_example_loss, axis=1, output_type=tf.int32) # (B,)\n per_example_loss = tf.reduce_min(per_example_loss, axis=1)\n\n another_label = tf.one_hot(out_indices, k, dtype=tf.float32)\n another_per_loss = -tf.reduce_sum(another_label * probs, axis=-1)\n\n lambda_para = 0.5\n total_loss = tf.reduce_mean(per_example_loss) + lambda_para * tf.reduce_mean(another_per_loss)\n\n output_indices = tf.argmin(probs, axis=1, output_type=tf.int32)\n output_indices = tf.reshape(output_indices, [-1, 1])\n logits = tf.batch_gather(logits, output_indices)\n return total_loss, logits\n\n\ndef model_fn_builder(bert_config, num_labels, init_checkpoint, learning_rate,\n num_train_steps, num_warmup_steps, use_tpu,\n use_one_hot_embeddings):\n \"\"\"Returns `model_fn` closure for TPUEstimator.\"\"\"\n\n def model_fn(features, labels, mode, params): # pylint: disable=unused-argument\n \"\"\"The `model_fn` for TPUEstimator.\"\"\"\n\n global initialized_variable_names\n # tf.logging.info(\"*** Features ***\")\n # for name in sorted(features.keys()):\n # tf.logging.info(\" name = %s, shape = %s\" % (name, features[name].shape))\n\n is_training = (mode == tf.estimator.ModeKeys.TRAIN)\n\n predictions = _creat_bert(is_training, features, bert_config, use_one_hot_embeddings, init_checkpoint)\n\n # the concatenate of predictions is the output of bert encoder\n # and it will be seen as input of other modules\n total_loss, logits = _create_cqa_modules(is_training, predictions)\n\n scaffold_fn = None\n if mode == tf.estimator.ModeKeys.TRAIN:\n train_op = optimization.create_optimizer(\n total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu)\n\n output_spec = tpu.TPUEstimatorSpec(\n mode=mode,\n loss=total_loss,\n train_op=train_op,\n scaffold_fn=scaffold_fn)\n\n elif mode == tf.estimator.ModeKeys.PREDICT:\n output_spec = tpu.TPUEstimatorSpec(\n mode=mode,\n predictions=logits,\n scaffold_fn=scaffold_fn)\n else:\n raise ValueError(\"Only TRAIN and EVAL modes are supported: %s\" % (mode))\n\n return output_spec\n\n return model_fn\n\n\ndef main():\n tf.logging.set_verbosity(tf.logging.INFO)\n\n bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)\n\n if FLAGS.max_seq_length > bert_config.max_position_embeddings:\n raise ValueError(\n \"Cannot use sequence length %d because the BERT model \"\n \"was only trained up to sequence length %d\" %\n (FLAGS.max_seq_length, bert_config.max_position_embeddings))\n\n tf.gfile.MakeDirs(FLAGS.output_dir)\n\n tpu_cluster_resolver = None\n if FLAGS.use_tpu and FLAGS.tpu_name:\n tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(\n FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)\n\n is_per_host = tpu.InputPipelineConfig.PER_HOST_V2\n run_config = tpu.RunConfig(\n cluster=tpu_cluster_resolver,\n master=FLAGS.master,\n model_dir=FLAGS.output_dir,\n save_checkpoints_steps=FLAGS.save_checkpoints_steps,\n tpu_config=tpu.TPUConfig(\n iterations_per_loop=FLAGS.iterations_per_loop,\n num_shards=FLAGS.num_tpu_cores,\n per_host_input_for_training=is_per_host))\n\n session_config = tf.ConfigProto(log_device_placement=True)\n session_config.gpu_options.allow_growth = True\n run_config.replace(session_config=session_config)\n\n with open('cqa_data2.pkl', 'rb') as fr:\n train_features, dev_cid, dev_features = pkl.load(fr)\n dev_label = [feature.label_id for feature in dev_features]\n\n num_train_steps = None\n num_warmup_steps = None\n\n if FLAGS.do_train:\n num_train_steps = int(\n len(train_features) / FLAGS.train_batch_size * FLAGS.num_train_epochs)\n num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion)\n\n model_fn = model_fn_builder(\n bert_config=bert_config,\n num_labels=2,\n init_checkpoint=FLAGS.init_checkpoint,\n learning_rate=FLAGS.learning_rate,\n num_train_steps=num_train_steps,\n num_warmup_steps=num_warmup_steps,\n use_tpu=FLAGS.use_tpu,\n use_one_hot_embeddings=FLAGS.use_tpu)\n\n # If TPU is not available, this will fall back to normal Estimator on CPU\n # or GPU.\n estimator = tpu.TPUEstimator(\n use_tpu=FLAGS.use_tpu,\n model_fn=model_fn,\n config=run_config,\n # params={'batch_size': FLAGS.train_batch_size},\n train_batch_size=FLAGS.train_batch_size,\n predict_batch_size=FLAGS.eval_batch_size)\n\n tf.logging.info(\"***** Running evaluation *****\")\n tf.logging.info(\" Num examples = %d\", len(dev_features))\n tf.logging.info(\" Batch size = %d\", FLAGS.eval_batch_size)\n\n eval_drop_remainder = True if FLAGS.use_tpu else False\n if FLAGS.do_train:\n tf.logging.info(\"***** Running training *****\")\n tf.logging.info(\" Num examples = %d\", len(train_features))\n tf.logging.info(\" Batch size = %d\", FLAGS.train_batch_size)\n tf.logging.info(\" Num steps = %d\", num_train_steps)\n train_input_fn = input_fn_builder(\n features=train_features,\n seq_length=FLAGS.max_seq_length,\n is_training=True,\n drop_remainder=True)\n\n estimator.train(input_fn=train_input_fn,\n max_steps=num_train_steps,\n hooks=[EvalHook(estimator=estimator,\n _input_fn_builder=input_fn_builder,\n dev_features=dev_features,\n dev_label=dev_label,\n dev_cid=dev_cid,\n max_seq_length=FLAGS.max_seq_length,\n eval_steps=FLAGS.save_checkpoints_steps,\n checkpoint_dir=FLAGS.output_dir)])\n\n if FLAGS.do_eval:\n tf.logging.info(\"***** Running evaluation *****\")\n tf.logging.info(\" Num examples = %d\", len(dev_features))\n tf.logging.info(\" Batch size = %d\", FLAGS.eval_batch_size)\n\n # This tells the estimator to run through the entire set.\n eval_steps = None\n # However, if running eval on the TPU, you will need to specify the\n # number of steps.\n if FLAGS.use_tpu:\n # Eval will be slightly WRONG on the TPU because it will truncate\n # the last batch.\n eval_steps = int(len(dev_features) / FLAGS.eval_batch_size)\n\n eval_drop_remainder = True if FLAGS.use_tpu else False\n eval_input_fn = input_fn_builder(\n features=dev_features,\n seq_length=FLAGS.max_seq_length,\n is_training=False,\n drop_remainder=eval_drop_remainder)\n\n predictions = estimator.predict(eval_input_fn, yield_single_examples=False)\n res = np.concatenate([a for a in predictions], axis=0)\n print(res.shape, np.array(dev_label).shape)\n metrics = PRF(np.array(dev_label), res.argmax(axis=-1))\n # print((np.array(dev_label) != res.argmax(axis=-1))[:1000])\n MAP, AvgRec, MRR = eval_reranker(dev_cid, dev_label, res[:, 0])\n metrics['MAP'] = MAP\n metrics['AvgRec'] = AvgRec\n metrics['MRR'] = MRR\n\n print_metrics(metrics, 'dev')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"cqa_joint_split.py","file_name":"cqa_joint_split.py","file_ext":"py","file_size_in_byte":16831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"480814631","text":"\nimport sys\nsys.path.append(\"/home/kevin/projects/Codes\")\nimport ntpy.strchg as st\nimport numpy as np\n\n# String change\nstrchange = dict({'KPT' : str(kpt[0])+ '\\t'+ str(kpt[1])+ '\\t'+ \\\n\t\t\t\t\t\t str(kpt[2]),\n\t\t\t\t 'MASS' : str(mass)\n\t\t\t\t })\n\nst.sed(strchange, orig, new)\n# Grep out eigenvectors\n\neigvec = np.zeros( (3 * num_atoms_cell, 3 * num_atoms_cell) )\n","sub_path":"ld/gulp.eig.py","file_name":"gulp.eig.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"560945254","text":"#!/usr/bin/env python\n\n\"\"\"\nRun timing test (GPU) scaled over number of LPUs.\n\"\"\"\n\nimport csv\nimport re\nimport subprocess\nimport sys\n\nimport numpy as np\n\nout_file = sys.argv[1]\nscript_name = 'timing_demo_gpu.py'\ntrials = 3\n\nf = open(out_file, 'w', 0)\nw = csv.writer(f)\nfor spikes in xrange(250, 7000, 250):\n for lpus in xrange(2, 9):\n for i in xrange(trials):\n out = subprocess.check_output(['srun', '-n', '1', '-c', str(lpus),\n '-p', 'huxley',\n '--gres=gpu:%i' % lpus,\n 'python', script_name,\n '-u', str(lpus), '-s', str(spikes/(lpus-1)),\n '-g', '0', '-m', '50'])\n average_step_sync_time, runtime_all, runtime_main, \\\n runtime_loop = out.strip('()\\n\\\"').split(', ')\n w.writerow([lpus, spikes, average_step_sync_time,\n runtime_all, runtime_main, runtime_loop])\nf.close()\n","sub_path":"examples/timing/run_lpu_gpu.py","file_name":"run_lpu_gpu.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"130612897","text":"# -*- coding: utf-8 -*-\n\nfrom six import with_metaclass\nimport json\n\nfrom flask import request, url_for, make_response\nfrom flask.views import MethodViewType, MethodView\nfrom marshmallow_jsonapi.exceptions import IncorrectTypeError\n\nfrom flask_rest_jsonapi.data_layers import SqlalchemyDataLayer, MongoDataLayer\nfrom flask_rest_jsonapi.errors import ErrorFormatter\nfrom flask_rest_jsonapi.querystring import QueryStringManager as QSManager\nfrom flask_rest_jsonapi.pagination import paginate_result\nfrom flask_rest_jsonapi.exceptions import EntityNotFound\nfrom flask_rest_jsonapi.decorators import disable_method\n\nDATA_LAYERS = {\n 'sqlalchemy': SqlalchemyDataLayer,\n 'mongo': MongoDataLayer\n}\n\n\nclass ResourceMeta(MethodViewType):\n\n def __init__(cls, name, bases, nmspc):\n super(ResourceMeta, cls).__init__(name, bases, nmspc)\n meta = nmspc.get('Meta')\n\n if meta is not None:\n data_layer = getattr(meta, 'data_layer')\n\n if data_layer is None or not isinstance(data_layer, dict):\n raise Exception(\"You must provide data layer informations as dictionary\")\n\n if data_layer.get('name') is None:\n raise Exception(\"You must provide a data layer name\")\n\n try:\n data_layer_cls = DATA_LAYERS[data_layer['name']]\n except KeyError:\n raise Exception(\"Data layer not found\")\n\n data_layer_kwargs = {}\n data_layer_kwargs['resource_cls'] = cls\n data_layer_kwargs.update(data_layer.get('kwargs', {}))\n cls.data_layer = type('DataLayer', (data_layer_cls, ), {})(**data_layer_kwargs)\n\n not_allowed_methods = getattr(meta, 'not_allowed_methods', [])\n for not_allowed_method in not_allowed_methods:\n if hasattr(cls, not_allowed_method.lower()):\n setattr(cls, not_allowed_method.lower(), disable_method(getattr(cls, not_allowed_method.lower())))\n\n\nclass ResourceListMeta(ResourceMeta):\n\n def __init__(cls, name, bases, nmspc):\n super(ResourceListMeta, cls).__init__(name, bases, nmspc)\n meta = nmspc.get('Meta')\n\n if meta is not None:\n data_layer = getattr(meta, 'data_layer')\n cls.data_layer.configure(data_layer)\n\n get_decorators = getattr(meta, 'get_decorators', [])\n post_decorators = getattr(meta, 'post_decorators', [])\n\n for get_decorator in get_decorators:\n cls.get = get_decorator(cls.get)\n\n for post_decorator in post_decorators:\n cls.post = post_decorator(cls.post)\n\n\nclass ResourceDetailMeta(ResourceMeta):\n\n def __init__(cls, name, bases, nmspc):\n super(ResourceDetailMeta, cls).__init__(name, bases, nmspc)\n meta = nmspc.get('Meta')\n\n if meta is not None:\n get_decorators = getattr(meta, 'get_decorators', [])\n patch_decorators = getattr(meta, 'patch_decorators', [])\n delete_decorators = getattr(meta, 'delete_decorators', [])\n\n for get_decorator in get_decorators:\n cls.get = get_decorator(cls.get)\n\n for patch_decorator in patch_decorators:\n cls.patch = patch_decorator(cls.patch)\n\n for delete_decorator in delete_decorators:\n cls.delete = delete_decorator(cls.delete)\n\n\nclass Resource(MethodView):\n \"\"\"Base Resource class to serialize the response of the resource internal methods (get, post, patch, delete).\n According to jsonapi reference, returns a json string and the right status code.\n \"\"\"\n def __new__(cls):\n assert hasattr(cls, 'resource_type')\n assert hasattr(cls, 'schema_cls')\n return super(Resource, cls).__new__(cls)\n\n def dispatch_request(self, *args, **kwargs):\n meth = getattr(self, request.method.lower(), None)\n if meth is None and request.method == 'HEAD':\n meth = getattr(self, 'get', None)\n assert meth is not None, 'Unimplemented method %r' % request.method\n\n resp = meth(*args, **kwargs)\n\n if isinstance(resp, tuple):\n data, status_code = resp\n else:\n data = resp\n status_code = 200\n\n return make_response(json.dumps(data), status_code)\n\n\nclass ResourceList(with_metaclass(ResourceListMeta, Resource)):\n\n def __new__(cls):\n assert hasattr(cls, 'collection_endpoint')\n return super(ResourceList, cls).__new__(cls)\n\n def get(self, *args, **kwargs):\n \"\"\"Retrieve a collection of items\n \"\"\"\n qs = QSManager(request.args)\n\n try:\n item_count, items = self.data_layer.get_items(qs, **kwargs)\n except EntityNotFound as e:\n return ErrorFormatter.format_error([e.message]), e.status_code\n\n schema_kwargs = {}\n if qs.fields.get(self.resource_type):\n schema_kwargs = {'only': set(self.schema_cls._declared_fields.keys()) & set(qs.fields[self.resource_type])}\n schema_kwargs['only'].add('id')\n schema = self.schema_cls(many=True, **schema_kwargs)\n\n result = schema.dump(items)\n\n if hasattr(self, 'collection_endpoint_request_view_args')\\\n and self.collection_endpoint_request_view_args is True:\n endpoint_kwargs = request.view_args\n else:\n endpoint_kwargs = {}\n paginate_result(result.data, item_count, qs, url_for(self.collection_endpoint, **endpoint_kwargs))\n\n return result.data\n\n def post(self, *args, **kwargs):\n \"\"\"Create an item\n \"\"\"\n json_data = request.get_json()\n\n schema = self.schema_cls()\n try:\n data, errors = schema.load(json_data)\n except IncorrectTypeError as err:\n return err.messages, 409\n\n if errors:\n return errors, 422\n\n try:\n item = self.data_layer.create_and_save_item(data, **kwargs)\n except EntityNotFound as e:\n return ErrorFormatter.format_error([e.message]), e.status_code\n\n return schema.dump(item).data, 201\n\n\nclass ResourceDetail(with_metaclass(ResourceDetailMeta, MethodView)):\n\n def get(self, *args, **kwargs):\n \"\"\"Get item details\n \"\"\"\n try:\n item = self.data_layer.get_item(**kwargs)\n except EntityNotFound as e:\n return ErrorFormatter.format_error([e.message]), e.status_code\n\n qs = QSManager(request.args)\n\n schema_kwargs = {}\n if qs.fields.get(self.resource_type):\n schema_kwargs = {'only': set(self.schema_cls._declared_fields.keys()) & set(qs.fields[self.resource_type])}\n schema_kwargs['only'].add('id')\n schema = self.schema_cls(**schema_kwargs)\n\n result = schema.dump(item)\n\n return result.data\n\n def patch(self, *args, **kwargs):\n \"\"\"Update an item\n \"\"\"\n json_data = request.get_json()\n\n try:\n if json_data['data']['id'] is None:\n raise KeyError\n except KeyError:\n return ErrorFormatter.format_error([\"You must provide id of the entity\"]), 422\n\n schema = self.schema_cls(partial=True)\n try:\n data, errors = schema.load(json_data)\n except IncorrectTypeError as err:\n return err.messages, 409\n\n if errors:\n return errors, 422\n\n try:\n item = self.data_layer.get_item(**kwargs)\n except EntityNotFound as e:\n return ErrorFormatter.format_error([e.message]), e.status_code\n\n self.data_layer.update_and_save_item(item, data, **kwargs)\n\n result = schema.dump(item)\n\n return result.data\n\n def delete(self, *args, **kwargs):\n \"\"\"Delete an item\n \"\"\"\n try:\n item = self.data_layer.get_item(**kwargs)\n except EntityNotFound as e:\n return ErrorFormatter.format_error([e.message]), e.status_code\n\n self.data_layer.delete_item(item)\n\n return '', 204\n","sub_path":"flask_rest_jsonapi/resource.py","file_name":"resource.py","file_ext":"py","file_size_in_byte":8010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"111896069","text":"from NetDeepHDR import DeepHDRNet\nfrom matplotlib import pyplot as plt\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom utils import *\nimport os\nimport glob\nimport numpy as np\nimport sys\nsys.path.append('../pyflow/')\nimport pyflow\nimport time\n\n\nTestInputDataDir = '../data/Testset/Test/004/'\n# MyTrainedModelPath = '../models/models_aws/ModelRepMainWe1.pth'\nMyTrainedModelPath = '../models/models_aws/All18We_Ihvhighhopes1.pth'\nUseCuda = torch.cuda.is_available()\nDevice = torch.device(\"cuda\" if UseCuda else \"cpu\")\nNumOut = 9\nGroundTruthExists = True\n\ndef CeLiuOpticalFlow(Image1, Image2, ExposureRestoreFactor):\n # Flow Options:\n alpha = 0.012\n ratio = 0.75\n minWidth = 20\n nOuterFPIterations = 7\n nInnerFPIterations = 1\n nSORIterations = 30\n colType = 0 # 0 or default:RGB, 1:GRAY\n\n u, v, WarpedIm2 = pyflow.coarse2fine_flow(Image1, Image2, alpha, ratio, minWidth, \n nOuterFPIterations, nInnerFPIterations,nSORIterations, colType)\n WarpedIm2 = WarpedIm2*ExposureRestoreFactor\n plt.imshow(u)\n plt.show()\n plt.imshow(v)\n plt.show()\n return WarpedIm2\n\n# Load pre-trained model of official implementation\nModel = DeepHDRNet(NumOut)\nModel = Model.to(Device)\nOptimizer = torch.optim.Adam(Model.parameters(), 1e-5)\nModel, Optimizer = load_checkpoint(MyTrainedModelPath, Model, Optimizer)\n\nTestFlowDataList = glob.glob(TestInputDataDir + \"*.tif\" )\nTestFlowDataList.sort()\nImage1 = ReadRawImage(TestFlowDataList[0])\nImage2 = ReadRawImage(TestFlowDataList[1])\nImage3 = ReadRawImage(TestFlowDataList[2])\nImage1 = Normalize(Image1, np.min(Image1), np.max(Image1))\nImage2 = Normalize(Image2, np.min(Image2), np.max(Image2))\nImage3 = Normalize(Image3, np.min(Image3), np.max(Image3))\n\nExpFile = open(TestInputDataDir + \"exposure.txt\")\nExposures = ExpFile.readlines()\nExposures = np.array(Exposures).astype(float)\n# print(Exposures)\n\n# Normalize input images\nExposure1 = (2 ** (Exposures[1] - Exposures[0])) ** (1 / 2.2)\nExposure3 = (2 ** (Exposures[1] - Exposures[2])) ** (1 / 2.2)\nImage1_e = Exposure1 * Image1\nImage3_e = Exposure3 * Image3\n\nAlignedImagesLDR = []\nIm1w = CeLiuOpticalFlow(Image2, Image1_e, 1 / Exposure1)\n# SaveImage(Im1w, \"temptest/\" + \"%03d\"%(Idx) + \"_1.png\")\nAlignedImagesLDR.append(Im1w.copy())\nAlignedImagesLDR.append(Image2.copy())\nIm3w = CeLiuOpticalFlow(Image2, Image3_e, 1 / Exposure3)\nAlignedImagesLDR.append(Im3w.copy())\nAlignedImagesLDR = np.array(AlignedImagesLDR)\n\nSaveImage(Im1w, 'temp1.png')\nSaveImage(Im3w, 'temp2.png')\n\nstart = time.time()\n# SaveImage(Im3w, \"temp/\" + \"%03d\"%(Idx) + \"_3.png\")\n# np.save(DefaultOutputFolder + \"%03d\"%(Idx) + \".npy\", Results)\nExposures = 2 ** (np.array(Exposures).astype(float))\nAlignedImagesHDR = LDRToHDR(AlignedImagesLDR, Exposures)\nAlignedImagesLDR = np.concatenate((AlignedImagesLDR[0], AlignedImagesLDR[1], AlignedImagesLDR[2]), axis = -1)\nAlignedImagesHDR = np.concatenate((AlignedImagesHDR[0], AlignedImagesHDR[1], AlignedImagesHDR[2]), axis = -1)\nInpImages = np.concatenate((AlignedImagesLDR, AlignedImagesHDR), axis = -1)\nInpImages = np.transpose(InpImages, (2, 0, 1))\n\nTestInput = torch.tensor(InpImages)\nTestInput = torch.unsqueeze(TestInput, 0)\nTestInput = TestInput.float().to(Device)\nModel.eval()\nwith torch.no_grad():\n Prediction = Model(TestInput)\n\n# if NumOut == 9:\n# print(\"FML\")\n# print(Prediction.shape)\n# I1 = TestInput[:, 0:3, 6:-6, 6:-6].cpu().numpy()\n# I2 = TestInput[:, 3:6, 6:-6, 6:-6].cpu().numpy()\n# I3 = TestInput[:, 6:9, 6:-6, 6:-6].cpu().numpy()\n\n# W1 = Prediction[:, 0:3].cpu().numpy()\n# W2 = Prediction[:, 3:6].cpu().numpy()\n# W3 = Prediction[:, 6:9].cpu().numpy()\n\n# Prediction = (W1 * I1 + W2 * I2 + W3 * I3) / (W1 + W2 + W3 + 1e-3)\n\nPrediction = Prediction[0].cpu().numpy()\nPrediction = np.transpose(Prediction, (1, 2, 0))\nPrediction = Normalize(Prediction, np.min(Prediction), np.max(Prediction))\n# Prediction = ToneMapImage(Prediction)\nplt.imshow(Prediction)\nplt.show()\nif GroundTruthExists:\n HDRImg = np.load(TestInputDataDir + \"HDRImg.npy\")\n HDRImg = HDRImg[6:-6,6:-6]\n HDRImg = ToneMapImage(HDRImg)\n Mse = np.mean((Prediction - HDRImg) ** 2)\n plt.imshow(HDRImg)\n plt.show()\n print(Mse)\n print(time.time() - start)","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"288542186","text":"#===============================================================================\n# Imports\n#===============================================================================\n\nimport random\n\nfrom numpy import mean\n\nfrom utils import NumContainer, calc_f1_score\nimport settings\n\n\n#===============================================================================\n# Functions\n#===============================================================================\n\ndef generate_corpus(size, **kwargs):\n corpus = set()\n \n while len(corpus) < size:\n corpus.add(NestedList.generate_random_instance(**kwargs))\n \n return corpus\n\n\n#===============================================================================\n# Classes\n#===============================================================================\n\nclass NestedListManager(object):\n\n class ACTIONS(object):\n ADD_CHILD_LEAF = 0\n ADD_CHILD_NODE = 1\n RETURN_TO_PARENT = 2\n \n def __init__(self):\n self.root = NestedList()\n self.current_node = self.root\n \n def add_child_leaf(self, token):\n self.current_node.append(token)\n \n def add_child_node(self, token):\n new_node = NestedList(parent=self.current_node)\n self.current_node.append(new_node)\n self.current_node = new_node\n \n def return_to_parent(self, token):\n # fail silently when the network performs illegal data structure actions\n if self.current_node.parent != None:\n self.current_node = self.current_node.parent\n \n def do_action(self, action, token):\n \n func_dict = {self.ACTIONS.ADD_CHILD_LEAF: self.add_child_leaf,\n self.ACTIONS.ADD_CHILD_NODE: self.add_child_node,\n self.ACTIONS.RETURN_TO_PARENT: self.return_to_parent}\n \n func_dict[action](token) \n\n\nclass NestedList(list):\n \n def __init__(self, *args, **kwargs):\n parent = kwargs.pop(\"parent\", None)\n super(NestedList, self).__init__(*args, **kwargs)\n self.parent = parent\n \n @classmethod\n def generate_random_instance(cls, \n p_continue=0.6, \n p_new_list=0.3, \n min_num=settings.MIN_NUMERICAL_ITEMS, \n max_num=settings.MAX_NUMERICAL_ITEMS, \n current_num=None):\n \n if current_num == None:\n current_num = NumContainer()\n \n new_instance = cls([current_num.num])\n current_num.num += 1\n \n while (current_num.num < min_num) or (random.random() <= p_continue and current_num.num < max_num):\n if random.random() <= p_new_list:\n new_item = cls.generate_random_instance(p_continue, p_new_list, min_num, max_num, current_num)\n else:\n new_item = current_num.num\n current_num.num += 1\n \n new_instance.append(new_item)\n \n return new_instance\n \n def get_tokens(self):\n \n yield \"[\"\n for item in self:\n if hasattr(item, \"get_tokens\"):\n for t in item.get_tokens():\n yield t\n else:\n yield item\n yield \"]\"\n \n def calc_score(self, gold_standard):\n \"\"\"\n See Klien (2005), 'The Unsupervised Learning Of Natural Language Structure', section 2.2.2.\n \"\"\"\n brackets = self.get_brackets()\n gold_brackets = gold_standard.get_brackets() \n klien_score = calc_f1_score(brackets, gold_brackets)\n \n descendents = set(self.get_descendents())\n gold_descendents = set(gold_standard.get_descendents())\n descendents_score = calc_f1_score(descendents, gold_descendents)\n \n return mean([klien_score, descendents_score])\n\n\n def get_descendents(self):\n \n for item in self:\n if hasattr(item, \"get_descendents\"):\n for t in item.get_descendents():\n yield t\n else:\n yield item\n \n def get_brackets(self):\n \n result = set()\n \n for item in self:\n if hasattr(item, \"get_brackets\"):\n result |= item.get_brackets()\n \n descendents = list(self.get_descendents())\n \n if len(descendents) == 0:\n # Gold standard Nested lists generated with generate_random_instance never contain\n # empty sets. But the ANN can generate empty sets. In such a case we denote these\n # redundant brackets as (-1,-1) which never exists in the gold standard and hence \n # reduces the f1 score of the network\n descendents.append(-1)\n \n result.add( (min(descendents), max(descendents)) )\n \n return result\n \n def __hash__(self):\n return hash(tuple(self))\n","sub_path":"experiment1/NestedList.py","file_name":"NestedList.py","file_ext":"py","file_size_in_byte":4969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"287804951","text":"import unittest\nfrom unittest.mock import patch\nfrom models import Employee\n\n\nclass TestEmployee(unittest.TestCase):\n def setUp(self):\n self.employee = Employee(1, 'Test Tester', 'test@test.com', 'plant', 1)\n\n def test_generate_dict(self):\n self.assertIn('id', self.employee._generate_dict())\n self.assertEqual(self.employee._generate_dict()['id'], 1)\n self.assertEqual(self.employee._generate_dict()['department_type'], 'plant')\n\n @patch('models.Employee.get_file_data')\n def test_get_by_id(self, fileDataMock):\n fileDataMock.return_value = [{\"id\": 1, \"email\": \"lubomur.luzhnuy@gmail.com\", \"name\": \"Liubomyr Luzhnyi\", \"department_type\": \"plant\", \"department_id\": 1}, {\"id\": 2, \"email\": \"anton@gmail.com\", \"name\": \"Anton\", \"department_type\": \"plant\", \"department_id\": 2}]\n self.assertEqual(self.employee.get_by_id(1)['email'], \"lubomur.luzhnuy@gmail.com\")\n self.assertIn('id', self.employee.get_by_id(1))\n","sub_path":"lectures/tests2/ReneeMontoyaApp/test_employee.py","file_name":"test_employee.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"578234310","text":"import sys\nimport json\n\nimport OpenCOR\n\n\ndef main(stimulus_period):\n s = OpenCOR.openSimulation('/home/opencor/models/action-potential.xml')\n\n d = s.data()\n\n # Set integration range\n d.setPointInterval(10) # ms\n d.setEndingPoint(100000) # ms\n\n # print('Setting stimulus period to:', stimulus_period)\n c = d.constants()\n c['membrane/period'] = stimulus_period # ms\n\n # Run the simulation\n s.run()\n\n r = s.results()\n\n json_format = json.dumps({'membrane': {'v': r.states()['membrane/v'].values().tolist()}})\n print(json_format)\n\n\nif __name__ == \"__main__\":\n args = sys.argv\n args.pop(0) # Script name.\n try:\n period = float(args.pop(0))\n except ValueError:\n print(\"Usage: docker run hsorby/opencor-python \")\n print(\" where is the stimulation period in milliseconds as a decimal number.\")\n sys.exit(2)\n\n main(period)\n","sub_path":"run_model.py","file_name":"run_model.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"303644575","text":"import App\ndef CreateAI(pShip, pTargetGroup):\n\n\t#########################################\n\t# Creating CompoundAI BasicAttackTargets at (141, 106)\n\timport AI.Compound.BasicAttack\n\tpBasicAttackTargets = AI.Compound.BasicAttack.CreateAI(pShip, pTargetGroup, Easy_Difficulty = 0.23, Difficulty = 0.51, FollowTargetThroughWarp = 1, Hard_Difficulty = 0.8)\n\t# Done creating CompoundAI BasicAttackTargets\n\t#########################################\n\t#########################################\n\t# Creating PreprocessingAI AvoidObstacles at (112, 175)\n\t## Setup:\n\timport AI.Preprocessors\n\tpScript = AI.Preprocessors.AvoidObstacles()\n\t## The PreprocessingAI:\n\tpAvoidObstacles = App.PreprocessingAI_Create(pShip, \"AvoidObstacles\")\n\tpAvoidObstacles.SetInterruptable(1)\n\tpAvoidObstacles.SetPreprocessingMethod(pScript, \"Update\")\n\tpAvoidObstacles.SetContainedAI(pBasicAttackTargets)\n\t# Done creating PreprocessingAI AvoidObstacles\n\t#########################################\n\treturn pAvoidObstacles\n","sub_path":"scripts/Maelstrom/Episode6/E6M1/E6M1_AI_Keldon.py","file_name":"E6M1_AI_Keldon.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"53705490","text":"\"\"\"\n读取配置\n\"\"\"\nimport configparser\n\nfrom common.Container import Container\n\n\nclass Config(object):\n\n def __init__(self):\n self.config = {}\n self.set_all_config()\n\n def set_all_config(self):\n conf = configparser.ConfigParser()\n conf.read(Container.PATH + 'config\\\\config.ini')\n for section in conf.sections():\n self.config[section] = {}\n for item in conf.items(section):\n self.config[section][item[0]] = item[1]\n\n def get_config(self, section, item):\n try:\n conf = self.config[section][item]\n return True, conf\n except KeyError:\n return False, '没有' + section + '或者' + item\n","sub_path":"common/Config.py","file_name":"Config.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"574712668","text":"from rest_framework import viewsets\nfrom rest_framework.generics import *\nfrom rest_framework.mixins import *\nfrom .serializers import *\nfrom django.shortcuts import get_object_or_404\nfrom rest_framework.permissions import IsAuthenticated\n\n\nclass BookView(viewsets.ViewSet):\n permission_classes = [IsAuthenticated]\n serializer_class = BookSerializer\n model = Book\n\n def list(self, request):\n queryset = self.model.objects.all()\n serializer = self.serializer_class(queryset, many=True)\n return Response(serializer.data)\n\n def retrieve(self, request, pk=None):\n queryset = self.model.objects.all()\n user = get_object_or_404(queryset, pk=pk)\n serializer = self.serializer_class(user)\n return Response(serializer.data)\n\n def create(self, request):\n model_obj = request.data.copy()\n model_obj['owner'] = request.user.id\n serializer = self.serializer_class(data=model_obj)\n serializer.is_valid(raise_exception=True)\n model_obj_saved = serializer.save()\n return Response({\"success\": \"Object '{}' created successfully\".format(model_obj_saved)})\n\n def update(self, request, pk=None):\n model_obj = get_object_or_404(self.model.objects.all(), pk=pk)\n if model_obj.owner != request.user.id:\n return Response(\"Access denied\")\n data = request.data.copy()\n serializer = self.serializer_class(instance=model_obj, data=data, partial=True)\n serializer.is_valid(raise_exception=True)\n model_obj_saved = serializer.save()\n return Response({\n \"success\": \"Object '{}' updated successfully\".format(model_obj_saved)\n })\n\n def destroy(self, request, pk=None):\n model_obj = get_object_or_404(self.model.objects.all(), pk=pk)\n if model_obj.owner != request.user.id:\n return Response(\"Access denied\")\n model_obj.delete()\n return Response({\n \"success\": \"Object deleted successfully\"\n })\n\n\nclass ReaderView(BookView):\n serializer_class = ReaderSerializer\n model = Reader\n\n\nclass IssuingAInstanceView(BookView):\n serializer_class = IssuingAInstanceSerializer\n model = IssuingAInstance\n\n\nclass InstanceOfBookView(BookView):\n serializer_class = InstanceOfBookSerializer\n model = InstanceOfBook\n\n\nclass ReadingRoomView(BookView):\n serializer_class = ReadingRoomSerializer\n model = ReadingRoom\n\n\nclass InstanceOfBookInReadingRoomView(BookView):\n serializer_class = InstanceOfBookInReadingRoomSerializer\n model = InstanceOfBookInReadingRoom\n\n\nclass RegistersView(BookView):\n serializer_class = RegistersSerializer\n model = Registers\n","sub_path":"students/K33401/laboratory_works/Тарасов_Артём/laboratory_work_3/djangoProject/library/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"514957882","text":"import re\nimport math\n\ndef chromosomeToCycle(chromosome):\n nodes = [0] * (2 * len(chromosome))\n for j in range(1, len(chromosome) + 1):\n i = int(chromosome[j-1])\n if i > 0:\n nodes[2*j - 1 - 1] = 2*i - 1\n nodes[2*j - 1] = 2*i\n else:\n nodes[2*j - 1 - 1] = -2*i\n nodes[2*j - 1] = -2*i - 1\n\n return nodes\n\n\ndef nodeToCycleInd(nodeNum):\n return int(math.ceil(nodeNum/2) - 1)\n\n\ndef findEdge(num, edges):\n for edge in edges:\n if num in edge:\n return edge\n\ndef findCycles_single_chrom(coloredEdges, max_val):\n cycle_ind_array = [i for i in range(max_val // 2)]\n for edge in coloredEdges:\n start, end = edge[0], edge[1]\n start_ind = nodeToCycleInd(start)\n end_ind = nodeToCycleInd(end)\n\n orig_start = cycle_ind_array[start_ind]\n orig_end = cycle_ind_array[end_ind]\n\n cycle_ind_array[start_ind] = min(cycle_ind_array[start_ind], cycle_ind_array[end_ind])\n cycle_ind_array[end_ind] = min(cycle_ind_array[start_ind], cycle_ind_array[end_ind])\n\n for i, elem in enumerate(cycle_ind_array):\n if elem == orig_start or elem == orig_end:\n cycle_ind_array[i] = cycle_ind_array[start_ind]\n\n return cycle_ind_array\n\n\ndef flipNode(num):\n flip = num - 1 if num % 2 == 0 else num + 1\n return flip\n\n\ndef nodeExists(start, edges):\n for elem in edges:\n if elem[0] == start or elem[1] == start:\n return True\n return False\n\n\ndef findNextEdge(start, edges):\n for i, elem in enumerate(edges):\n if elem[0] == start or elem[1] == start:\n return elem, i\n\n\ndef edgesToChromosomes(coloredEdges):\n chromosomes = []\n currChrom = []\n edges_copy = coloredEdges.copy()\n startEdge = edges_copy[0]\n currChrom += [startEdge[1]]\n\n start = flipNode(startEdge[1])\n\n while edges_copy:\n if nodeExists(start, edges_copy):\n startEdge, edge_ind = findNextEdge(start, edges_copy)\n del edges_copy[edge_ind]\n if start == startEdge[0]:\n currChrom += startEdge\n start = flipNode(startEdge[1])\n else:\n currChrom += startEdge[::-1]\n start = flipNode(startEdge[0])\n else:\n chromosomes.append(currChrom)\n currChrom = []\n startEdge = edges_copy[0]\n currChrom += [startEdge[1]]\n\n start = flipNode(startEdge[1])\n chromosomes.append(currChrom)\n\n return chromosomes\n\n\ndef edgesToChromosomes_OLD(coloredEdges):\n max_val = max(max(coloredEdges, key=lambda tup:max(tup)))\n\n cycle_ind_array = findCycles_single_chrom(coloredEdges, max_val)\n\n cycle_ind_distinct = list(set(cycle_ind_array))\n\n cycle_count = len(cycle_ind_distinct)\n\n chromosomes = [[] for _ in range(cycle_count)]\n\n # iterate by 2, starting with 1\n for i in range(1, max_val + 1, 2):\n edge = findEdge(i, coloredEdges)\n cycle_ind = cycle_ind_distinct.index(cycle_ind_array[nodeToCycleInd(i)])\n\n if i == edge[1]:\n chromosomes[cycle_ind].append(i)\n chromosomes[cycle_ind].append(i + 1)\n else:\n chromosomes[cycle_ind].append(i + 1)\n chromosomes[cycle_ind].append(i)\n\n return chromosomes\n\n\ndef numToStr(num):\n if num < 0:\n return str(num)\n else:\n return '+' + str(num)\n\n\ndef chromosomeToCycle(chromosome):\n nodes = [0] * (2 * len(chromosome))\n for j in range(1, len(chromosome) + 1):\n i = int(chromosome[j-1])\n if i > 0:\n nodes[2*j - 1 - 1] = 2*i - 1\n nodes[2*j - 1] = 2*i\n else:\n nodes[2*j - 1 - 1] = -2*i\n nodes[2*j - 1] = -2*i - 1\n\n return nodes\n\ndef coloredEdges_poly(chroms):\n edges = []\n for chrom in chroms:\n nodes = chromosomeToCycle(chrom)\n nodes += [nodes[0]]\n for j in range(1, len(chrom) + 1):\n edges.append((nodes[2*j - 1], nodes[2*j]))\n\n edges_sorted = sorted(edges, key=lambda tup: tup[0])\n\n str_edges_sorted = [str(elem) for elem in edges_sorted]\n\n # print(', '.join(str_edges_sorted))\n return edges_sorted\n\ndef findCycles_double_chrom(coloredEdges, max_val):\n cycle_ind_array = [i for i in range(max_val)]\n for edge in coloredEdges:\n start, end = edge[0] - 1, edge[1] - 1\n orig_start = cycle_ind_array[start]\n orig_end = cycle_ind_array[end]\n cycle_ind_array[start] = min(cycle_ind_array[start], cycle_ind_array[end])\n cycle_ind_array[end] = min(cycle_ind_array[start], cycle_ind_array[end])\n for i, elem in enumerate(cycle_ind_array):\n if elem == orig_start or elem == orig_end:\n cycle_ind_array[i] = cycle_ind_array[start]\n\n return cycle_ind_array\n\ndef two_break_on_genome_graph(colored_edges, coords):\n new_edges = []\n start1 = 0\n start2 = 0\n end1 = 0\n end2 = 0\n\n for edge in colored_edges:\n if edge[0] == coords[0]:\n start1 = coords[0]\n end1 = coords[2]\n continue\n elif edge[0] == coords[1]:\n start2 = coords[1]\n end2 = coords[3]\n continue\n elif edge[0] == coords[2]:\n start1 = coords[2]\n end1 = coords[0]\n continue\n elif edge[0] == coords[3]:\n start2 = coords[3]\n end2 = coords[1]\n continue\n else:\n new_edges.append((edge[0], edge[1]))\n\n new_edges.append((coords[0], coords[2]))\n new_edges.append((coords[1], coords[3]))\n\n return new_edges\n\ndef cycleToChromosome(nodes):\n chrom = [''] * int(len(nodes) / 2)\n for j in range(1, len(chrom) + 1):\n if nodes[2*j - 1 - 1] < nodes[2*j - 1]:\n chrom[j - 1] = numToStr(nodes[2*j - 1] // 2)\n else:\n chrom[j - 1] = numToStr(-(nodes[2*j - 1 - 1 ] // 2))\n\n return chrom\n\n\ndef graphToGenome(coloredEdges):\n cycles = edgesToChromosomes(coloredEdges)\n\n chromosomes = []\n for cycle in cycles:\n chromosomes.append(cycleToChromosome(cycle))\n\n return chromosomes\n\n\ndef two_break_on_genome(colored_edges, coords):\n new_edges = two_break_on_genome_graph(colored_edges, coords)\n return graphToGenome(new_edges)\n\n\n\ndef hasNonTrivialCycles(edges):\n b, ind = findNonTrivialCycles(edges)\n return b\n\n\n# returns the number of the set that represents the cycle\ndef findNonTrivialCycles(edges):\n max_val = max(max(edges, key=lambda tup:max(tup)))\n\n cycle_ind_array = findCycles_double_chrom(edges, max_val)\n\n cycle_dict = {}\n\n set = None\n\n for elem in cycle_ind_array:\n if elem in cycle_dict:\n cycle_dict[elem] += 1\n if cycle_dict[elem] > 2:\n set = elem\n else:\n cycle_dict[elem] = 0\n\n return set, cycle_ind_array\n\n\ndef findEnd(edges, start):\n for i, edge in enumerate(edges):\n if start == edge[0]:\n return edge[1], i\n elif start == edge[1]:\n return edge[0], i\n\n\ndef printGraph(P):\n for graph in P:\n print('(' + ' '.join(graph) + ')', end='')\n print()\n\n\ndef two_break_sorting(P, Q):\n printGraph(P)\n\n redEdges = coloredEdges_poly(P)\n blueEdges = coloredEdges_poly(Q)\n\n total_edges = redEdges + blueEdges\n coords = [0]*4\n\n while hasNonTrivialCycles(total_edges) is not None:\n set, cycle_ind_array = findNonTrivialCycles(total_edges)\n original_red = list(redEdges)\n for edge in blueEdges:\n if cycle_ind_array[edge[1] - 1] == set:\n coords[0], coords[2] = edge[0], edge[1]\n coords[1], ind1 = findEnd(redEdges, coords[0])\n coords[3], ind2 = findEnd(redEdges, coords[2])\n\n # Account for deletion of first edge here\n if ind2 > ind1:\n ind2 -= 1\n\n del redEdges[ind1]\n del redEdges[ind2]\n\n if ind2 >= ind1:\n ind2 += 1\n\n redEdges.insert(ind1, (coords[0], coords[2]))\n redEdges.insert(ind2, (coords[1], coords[3]))\n\n break\n\n total_edges = redEdges + blueEdges\n\n P = two_break_on_genome(original_red, coords)\n printGraph(P)\n\n\nwith open('rosalind_ba6d.txt', 'r+') as f:\n genomeP = f.readline().rstrip()\n spP = re.split('[()]', genomeP)\n chromsP = [chrom.split() for chrom in spP if chrom]\n\n genomeQ = f.readline().rstrip()\n spQ = re.split('[()]', genomeQ)\n chromsQ = [chrom.split() for chrom in spQ if chrom]\n\n two_break_sorting(chromsP, chromsQ)","sub_path":"ShortestRearrangement.py","file_name":"ShortestRearrangement.py","file_ext":"py","file_size_in_byte":8625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"189713368","text":"import requests\n\ndef data_from_url(request,url, filter={}):\n '''\n MAIN FUNCTION TO GET DATA FROM DRCHRONO API\n '''\n data = []\n headers = {'Authorization': 'Bearer %s' %request.session['access_token'],}\n while url:\n page = requests.get(url, filter, headers=headers).json()\n data.extend(page['results'])\n url = page['next']\n return data\n","sub_path":"drchrono/get_drchrono_data.py","file_name":"get_drchrono_data.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"238482347","text":"# -*- encoding: utf-8 -*-\n\nfrom openerp import models, fields, api\nfrom openerp.osv import fields, osv\nfrom openerp.addons.sale import sale\nfrom openerp.tools.translate import _\n\n\nfrom datetime import datetime\n\nclass view_crm_survey_statistics(osv.osv):\n\n\n _name = \"view.crm.survey.statistics\"\n\n\n _description = \"Survey statics\"\n _auto = False\n _columns = {\n 'id': fields.integer('ID', readonly=True),\n 'invoice_id': fields.many2one('account.invoice', 'Factura'),\n 'section_id': fields.many2one('crm.case.section', 'Team'),\n 'user_id': fields.many2one('survey.user.input', 'User'),\n 'survey_response_id': fields.many2one('res.users', 'Survey'),\n 'quizz_mark': fields.int( 'Value'),\n 'creation_date': fields.datetime('creation date'),\n\n\n }\n\n def init(self, cr):\n tools.sql.drop_view_if_exists(cr, 'view_crm_survey_statistics')\n\n cr.execute(\"\"\"create or replace view view_crm_survey_statistics as (\n select l.id, i.id as invoice_id, i.section_id, i.user_id ,survey_response_id ,cast(quizz_mark as int) as quizz_mark,\n l.write_uid,l.date_create,l.value_number,l.write_date,l.create_uid,l.create_date \n from account_invoice i\n join survey_user_input_line l on i.survey_response_id= l.user_input_id\n where survey_response_id > 1 and l.question_id=39\n )\"\"\")\n\n\n\n\n\n","sub_path":"account_invoice.py","file_name":"account_invoice.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"102396298","text":"import os\nimport re\nimport urllib.request\nimport time\nimport sys\nfrom bs4 import BeautifulSoup\nfrom replaceSpecialCh import replaceSpecialCh\n\npath = \"D:/Touhou/doujin/ghap2\"\nlogfile = \"log.log\"\nhtml_footer = \"\\n\\n\"\ncatRegex = re.compile('(동방)')\ncodeRegex = re.compile('[0-9]*')\n\ndef writeLog(msg):\n\twith open(\"%s/%s\"%(path,logfile),\"a\",encoding=\"utf-8\") as a:\n\t\ta.write(msg)\n\ndef ghap(dirList):\n\tfor dirs in dirList:\n\t\tprint(\"%s start\" %(dirs))\n\t\twith open(gitPath+\"/\"+dirs,\"r\",encoding=\"utf-8\") as f:\n\t\t\tcontent = f.read()\n\n\t\tsoup = BeautifulSoup(content,\"html.parser\")\n\t\tcategory = soup.find(\"h1\",class_=\"header\").find_all(\"a\",class_=\"page-title-link\")\n\t\ttmp = \"\"\n\t\tfor i in range(len(category)):\n\t\t\ttmp = tmp + category[i].text\n\t\t\tif i < len(category)-1:\n\t\t\t\ttmp = tmp + \"/\"\n\t\tcategory = tmp\n\t\ttitle = soup.find(\"h1\",class_=\"article-title\").text.strip()\n\t\tdate = soup.find(\"time\").text\n\n\t\ttitleWin = replaceSpecialCh(title)\n\t\tcode = date+\"_\"+titleWin\n\t\tcode = replaceSpecialCh(code).replace(\"+\",\"+\")\n\t\tdoc = \"%s/%s\" %(path,code)\n\t\tif not os.path.isdir(\"%s_%s\" %(doc,titleWin)):\n\t\t\ttry:\n\t\t\t\tos.mkdir(\"%s_%s\" %(doc,titleWin))\n\t\t\texcept:\n\t\t\t\twriteLog(\"Making \\'%s_%s\\' folder fail\\n\" %(doc,titleWin))\n\t\t\t\tcontinue\n\n\t\ttry:\n\t\t\tf = open(doc+\".html\",\"w\",encoding=\"utf-8\")\n\t\texcept:\n\t\t\twriteLog(\"Making \\'%s\\' file fail\\n\" %(title))\n\t\t\tf.close()\n\t\t\tcontinue\n\n\t\thtml_header = \"\\n\\n\\t%s\\n\\n\\n\\t

    %s


    \\n\" %(title, title)\n\t\tf.write(html_header)\n\t\tf.write(str(soup.find(\"link\",rel=\"canonical\"))+\"\\n\")\n\t\tf.write(\"
    %s

    \\n\" %(category))\n\t\tf.write(\"
    %s

    \\n\" %(date))\n\t\t\n\t\tarticle = soup.find(\"div\",class_=\"article-entry\")\n\t\tp = article.find_all(\"img\")\n\t\tf.write(\"
    \\n\")\n\t\tnum = 1\n\t\tfor i in p:\n\t\t\timgSrc = i[\"src\"]\n\t\t\tfileExt = \"jpg\"\n\t\t\tfileName = \"%03d.%s\" %(num,fileExt)\n\t\t\t\"\"\"\n\t\t\ttry:\n\t\t\t\timgBuf = urllib.request.urlopen(imgSrc)\n\t\t\texcept:\n\t\t\t\twriteLog(\"%s_%s/%s open fail\\n\" %(code,titleWin,fileName))\n\t\t\t\tcontinue\n\n\t\t\ttry:\n\t\t\t\timgBuf = imgBuf.read()\n\t\t\texcept:\n\t\t\t\twriteLog(\"%s_%s/%s reading fail\\n\" %(code,titleWin,fileName))\n\t\t\t\tcontinue\n\n\t\t\ttry:\n\t\t\t\timgFile = open(\"%s_%s/%s\" %(doc,titleWin,fileName), \"wb\")\n\t\t\texcept:\n\t\t\t\twriteLog(\"Making %s_%s/%s fail\\n\" %(code,titleWin,fileName))\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\timgFile.write(imgBuf)\n\t\t\tfinally:\n\t\t\t\timgFile.close()\n\t\t\t\"\"\"\n\t\t\ti[\"src\"] = \"%s_%s/%s\" %(code,titleWin,fileName)\n\t\t\tnum+=1\n\t\tf.write(str(article))\n\t\tf.write(\"

    \\n\")\n\t\t\n\t\ttag = soup.find(\"div\",class_=\"article-tag\")\n\t\tf.write(\"
    \\n\")\n\t\tif tag is not None:\n\t\t\ttag = tag.find_all(\"a\")\n\t\t\tf.write(\"\\t

    태그:

    \\n\\t\\t
      \\n\")\n\t\t\tfor i in tag:\n\t\t\t\tf.write(\"\\t\\t\\t
    • %s
    • \\n\"%(i.text))\n\t\t\tf.write(\"\\t\\t
    \\n

    \\n\")\n\n\t\tf.write(html_footer)\n\t\tf.close()\n\t\tprint(\"%s end\" %(dirs))\n\nfor i in range(1,len(sys.argv)):\n\tghap([sys.argv[i]])","sub_path":"ghap2.py","file_name":"ghap2.py","file_ext":"py","file_size_in_byte":2926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"552797363","text":"import argparse\nimport json\nimport os\n\nfrom parse_controls import parse_controls\nfrom parse_mappings import parse_mappings\n\n\ndef save_bundle(bundle, path):\n \"\"\"helper function to write a STIX bundle to file\"\"\"\n print(f\"{'overwriting' if os.path.exists(path) else 'writing'} {path}... \", end=\"\", flush=True)\n with open(path, \"w\", encoding=\"utf-8\") as outfile:\n bundle.fp_serialize(outfile, indent=4, sort_keys=True, ensure_ascii=False)\n print(\"done!\")\n\n\ndef main(in_controls=os.path.join(\"input\", \"nist800-53-r4-controls.tsv\"),\n in_mappings=os.path.join(\"input\", \"nist800-53-r4-mappings.tsv\"),\n out_controls=os.path.join(\"stix\", \"nist800-53-r4-controls.json\"),\n out_mappings=os.path.join(\"stix\", \"nist800-53-r4-mappings.json\"),\n config_location=os.path.join(\"input\", \"config.json\")):\n \"\"\"\n parse the NIST 800-53 revision 4 controls and ATT&CK mappings into STIX2.0 bundles\n :param in_controls: tsv file of NIST 800-53 revision 4 controls\n :param in_mappings: tsv file mapping NIST 800-53 revision 4 controls to ATT&CK\n :param out_controls: output STIX bundle file for the controls. If this file already exists,\n the STIX IDs within will be reused in the replacing file so that they\n don't change between consecutive executions of this script.\n :param out_mappings: output STIX bundle file for the mappings.\n :param config_location: the filepath to the configuration JSON file.\n\n :returns tuple: containing the output controls and mappings (out_controls, out_mappings)\n \"\"\"\n\n # build control ID helper lookups so that STIX IDs don't get replaced on each rebuild\n control_ids = {}\n control_relationship_ids = {}\n if os.path.exists(out_controls):\n # parse idMappings from existing output so that IDs don't change when regenerated\n with open(out_controls, \"r\") as f:\n bundle = json.load(f)\n for sdo in bundle[\"objects\"]:\n if not sdo[\"type\"] == \"relationship\":\n from_id = sdo[\"external_references\"][0][\"external_id\"]\n to_id = sdo[\"id\"]\n control_ids[from_id] = to_id\n else:\n # parse relationships\n from_ids = f\"{sdo['source_ref']}---{sdo['target_ref']}\"\n to_id = sdo[\"id\"]\n control_relationship_ids[from_ids] = to_id\n\n # build controls in STIX\n controls = parse_controls(\n in_controls,\n control_ids,\n control_relationship_ids,\n config_location,\n )\n\n # build mapping ID helper lookup so that STIX IDs don't get replaced on each rebuild\n mapping_relationship_ids = {}\n if os.path.exists(out_mappings):\n with open(out_mappings, \"r\") as f:\n bundle = json.load(f)\n for sdo in bundle[\"objects\"]:\n from_ids = f\"{sdo['source_ref']}---{sdo['target_ref']}\"\n to_id = sdo[\"id\"]\n mapping_relationship_ids[from_ids] = to_id\n\n # build mappings in STIX\n mappings = parse_mappings(\n in_mappings,\n controls,\n mapping_relationship_ids,\n config_location,\n )\n\n save_bundle(controls, out_controls)\n save_bundle(mappings, out_mappings)\n\n return out_controls, out_mappings\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=\"parse the NIST 800-53 revision 4 controls and ATT&CK mappings into STIX2.0 bundles\"\n )\n parser.add_argument(\"-input-controls\",\n dest=\"in_controls\",\n help=\"tsv file of NIST 800-53 revision 4 controls\",\n default=os.path.join(\"input\", \"nist800-53-r4-controls.tsv\"))\n parser.add_argument(\"-input-mappings\",\n dest=\"in_mappings\",\n help=\"tsv file mapping NIST 800-53 revision 4 controls to ATT&CK\",\n default=os.path.join(\"input\", \"nist800-53-r4-mappings.tsv\"))\n parser.add_argument(\"-output-controls\",\n dest=\"out_controls\",\n help=\"output STIX bundle file for the controls. If this file already exists, \"\n \"the STIX IDs within will be reused in the replacing file so that they \"\n \"don't change between consecutive executions of this script.\",\n default=os.path.join(\"stix\", \"nist800-53-r4-controls.json\"))\n parser.add_argument(\"-output-mappings\",\n dest=\"out_mappings\",\n help=\"output STIX bundle file for the mappings.\",\n default=os.path.join(\"stix\", \"nist800-53-r4-mappings.json\"))\n parser.add_argument(\"-config-location\",\n dest=\"config_location\",\n help=\"filepath to the configuration for the framework\",\n default=os.path.join(\"input\", \"config.json\"))\n\n args = parser.parse_args()\n\n main(**vars(args))\n","sub_path":"frameworks/ATT&CK-v9.0/nist800-53-r4/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":4995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"55072369","text":"# Databricks notebook source\n# MAGIC \n# MAGIC %md-sandbox\n# MAGIC \n# MAGIC
    \n# MAGIC \"Databricks\n# MAGIC
    \n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC # JDBC Connections\n# MAGIC \n# MAGIC **Technical Accomplishments:**\n# MAGIC - Read Data from Relational Database\n# MAGIC - Write data to relational database\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ##![Spark Logo Tiny](https://files.training.databricks.com/images/105/logo_spark_tiny.png) Getting Started\n# MAGIC \n# MAGIC Run the following cell to configure our \"classroom.\"\n\n# COMMAND ----------\n\n# MAGIC %run \"./Includes/Classroom-Setup\"\n\n# COMMAND ----------\n\n# MAGIC %run \"./Includes/Utility-Methods\"\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ##![Spark Logo Tiny](https://files.training.databricks.com/images/105/logo_spark_tiny.png) Reading from JDBC\n# MAGIC \n# MAGIC Working with a JDBC data source is significantly different than any of the other data sources.\n# MAGIC * Configuration settings can be a lot more complex.\n# MAGIC * Often required to \"register\" the JDBC driver for the target database.\n# MAGIC * We have to juggle the number of DB connections.\n# MAGIC * We have to instruct Spark how to partition the data.\n# MAGIC \n# MAGIC **NOTE:** The database is read-only\n# MAGIC * For security reasons.\n# MAGIC * The notebook demonstrates writing to a JDBC database (**instructor only**).\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC \n# MAGIC * For examples of writing via JDBC, see\n# MAGIC * Connecting to SQL Databases using JDBC\n# MAGIC * JDBC To Other Databases\n\n# COMMAND ----------\n\n# MAGIC %scala\n# MAGIC \n# MAGIC // Ensure that the driver class is loaded.\n# MAGIC // Seems to be necessary sometimes.\n# MAGIC Class.forName(\"org.postgresql.Driver\")\n\n# COMMAND ----------\n\ntableName = \"training.people_1m\"\njdbcURL = \"jdbc:postgresql://54.213.33.240/training\"\n\n# Username and Password w/read-only rights\nconnProperties = {\n \"user\" : \"training\",\n \"password\" : \"training\"\n}\n\n# And for some consistency in our test to come\nspark.conf.set(\"spark.sql.shuffle.partitions\", \"8\")\n\n# COMMAND ----------\n\nexampleOneDF = spark.read.jdbc(\n url=jdbcURL, # the JDBC URL\n table=tableName, # the name of the table\n properties=connProperties) # the connection properties\n\nexampleOneDF.printSchema()\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC **Question:** Compared to CSV and even Parquet, what is missing here?\n# MAGIC \n# MAGIC **Question:** Based on the answer to the previous question, what are the ramifications of the missing...?\n# MAGIC \n# MAGIC **Question:** Before you run the next cell, what's your best guess as to the number of partitions?\n\n# COMMAND ----------\n\nprint(\"Partitions: \" + str(exampleOneDF.rdd.getNumPartitions()) )\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ##![Spark Logo Tiny](https://files.training.databricks.com/images/105/logo_spark_tiny.png) That's not Parallelized\n# MAGIC \n# MAGIC Let's try this again, and this time we are going to increase the number of connections to the database.\n# MAGIC \n# MAGIC ** *Note:* ** *If any one of these properties is specified, they must all be specified:*\n# MAGIC * `partitionColumn` - the name of a column of an integral type that will be used for partitioning.\n# MAGIC * `lowerBound` - the minimum value of columnName used to decide partition stride.\n# MAGIC * `upperBound` - the maximum value of columnName used to decide partition stride\n# MAGIC * `numPartitions` - the number of partitions/connections\n# MAGIC \n# MAGIC To quote the Spark SQL, DataFrames and Datasets Guide:\n# MAGIC > These options must all be specified if any of them is specified. They describe how to partition the table when reading in parallel from multiple workers. `partitionColumn` must be a numeric column from the table in question. Notice that `lowerBound` and `upperBound` are just used to decide the partition stride, not for filtering the rows in a table. So all rows in the table will be partitioned and returned. This option applies only to reading.\n\n# COMMAND ----------\n\njdbcURL = \"jdbc:postgresql://54.213.33.240/training\"\n\nexampleTwoDF = spark.read.jdbc(\n url=jdbcURL, # the JDBC URL\n table=tableName, # the name of the table\n column=\"id\", # the name of a column of an integral type that will be used for partitioning.\n lowerBound=1, # the minimum value of columnName used to decide partition stride.\n upperBound=200000, # the maximum value of columnName used to decide partition stride\n numPartitions=8, # the number of partitions/connections\n properties=connProperties) # the connection properties\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC Let's start with checking how many partitions we have (it should be 8)\n\n# COMMAND ----------\n\nprint(\"Partitions: \" + str(exampleTwoDF.rdd.getNumPartitions()) )\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC But how many records were loaded per partition?\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC Using the utility method we created above we can print the per-partition count.\n\n# COMMAND ----------\n\nprintRecordsPerPartition(exampleTwoDF)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC That might be a problem... notice how many records are in the last partition?\n# MAGIC \n# MAGIC **Question:** What are the performance ramifications of leaving our partitions like this?\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ##![Spark Logo Tiny](https://files.training.databricks.com/images/105/logo_spark_tiny.png) That's Not [Well] Distributed\n# MAGIC \n# MAGIC And this is one of the little gotchas when working with JDBC - to properly specify the stride, we need to know the minimum and maximum value of the IDs.\n\n# COMMAND ----------\n\nfrom pyspark.sql.functions import *\n\nminimumID = (exampleTwoDF\n .select(min(\"id\")) # Compute the minimum ID\n .first()[\"min(id)\"] # Extract as an integer\n)\nmaximumID = (exampleTwoDF\n .select(max(\"id\")) # Compute the maximum ID\n .first()[\"max(id)\"] # Extract as an integer\n)\nprint(\"Minimum ID: \" + str(minimumID))\nprint(\"Maximum ID: \" + str(maximumID))\nprint(\"-\"*80)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC Now, let's try this one more time... this time with the proper stride:\n\n# COMMAND ----------\n\nexampleThree = spark.read.jdbc(\n url=\"jdbc:postgresql://54.213.33.240/training\", # the JDBC URL\n table=tableName, # the name of the table\n column=\"id\", # the name of a column of an integral type that will be used for partitioning.\n lowerBound=minimumID, # the minimum value of columnName used to decide partition stride.\n upperBound=maximumID, # the maximum value of columnName used to decide partition stride\n numPartitions=8, # the number of partitions/connections\n properties=connProperties) # the connection properties\n\nprintRecordsPerPartition(exampleThree)\nprint(\"-\"*80)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC And of course we can view that data here:\n\n# COMMAND ----------\n\ndisplay(exampleThree)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC Spark’s partitions dictate the number of connections used to push data through the JDBC API. You can control the parallelism by calling `coalesce()` or `repartition()` depending on the existing number of partitions. Call `coalesce` when reducing the number of partitions, and `repartition` when increasing the number of partitions.\n\n# COMMAND ----------\n\n# MAGIC %md\n\n# COMMAND ----------\n\n# MAGIC %md\n\n# COMMAND ----------\n\n# MAGIC %md\n\n# COMMAND ----------\n\n# MAGIC %md\n\n# COMMAND ----------\n\n# MAGIC %md\n\n# COMMAND ----------\n\n# MAGIC %md-sandbox\n# MAGIC © 2019 Databricks, Inc. All rights reserved.
    \n# MAGIC Apache, Apache Spark, Spark and the Spark logo are trademarks of the Apache Software Foundation.
    \n# MAGIC
    \n# MAGIC Privacy Policy | Terms of Use | Support\n","sub_path":"Databricks/core-partners-2.0.4/Python/Optional/Reading-Data-06-JDBC.py","file_name":"Reading-Data-06-JDBC.py","file_ext":"py","file_size_in_byte":8671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"147318183","text":"#https://codelabs.developers.google.com/codelabs/build-your-first-android-app-kotlin/#7\n\nimport requests\nfrom bs4 import BeautifulSoup\nfrom webcrawl.models import LatestInfoTbl, RssDataTbl\nimport sys\n\nclass CrawlClass:\n # Sql query\n sqlQuery = { \n 'existMaster' : \"SELECT COUNT(*) FROM information_schema.tables WHERE table_name=?;\",\n 'createLatestInfoTbl' : \"CREATE TABLE LatestInfoTbl(FileName nvarchar(100) PRIMARY KEY, Date nvarchar(100));\",\n 'updateLatestInfo' : \"UPDATE LatestInfoTbl SET Date = ? WHERE FileName = ?;\",\n 'insertLatestInfo' : \"INSERT INTO LatestInfoTbl (FileName, Date) VALUES (?,?);\",\n 'selectDateLatestInfo' : \"SELECT Date FROM LatestInfoTbl WHERE FileName=?;\",\n 'createRssTbl' : \"CREATE TABLE RssTable(No INT PRIMARY KEY, Title nvarchar(MAX), Link nvarchar(MAX), Category nvarchar(MAX), Author nvarchar(MAX), PubDate nvarchar(100), Article nvarchar(MAX));\",\n 'selectTop1RssTbl' : \"SELECT Top 1 No FROM RssTable ORDER BY No DESC;\"\n } \n \n # Create LatestInfoTbl if not exist \n\n def __InsertRss(self, bsObject, RssDataTbl):\n \n dictRss = {}\n for item in bsObject.findAll('item'): \n dictRss[item.no.string] = {\n item.title.name : item.title.string, \n item.link.name : item.link.string,\n item.category.name : item.category.string,\n item.author.name : item.author.string,\n item.pubDate.name : item.pubDate.string,\n item.description.name : item.description.string } \n \n top1Value = 0\n\n try:\n top1Entry = RssDataTbl.objects.order_by('-pk')\n top1Value = top1Entry.no\n except: \n top1Value = 0\n\n for dictRssKey in dictRss:\n if int(dictRssKey) > top1Value :\n insert = RssDataTbl( \n no=dictRssKey, \n title=dictRss[dictRssKey]['title'], link=dictRss[dictRssKey]['link'], \n category=dictRss[dictRssKey]['category'],\n author=dictRss[dictRssKey]['author'], pubDate=dictRss[dictRssKey]['pubDate'],\n article=dictRss[dictRssKey]['description'] ) \n insert.save() \n \n \n def ParseRss(self, LatestInfoTbl, RssDataTbl): \n\n # Request RSS\n \n html = requests.get(\"http://file.mk.co.kr/news/rss/rss_30000001.xml\")\n bsObject = BeautifulSoup(html.content, 'xml') \n lastBuildData = bsObject.find('lastBuildDate')\n \n selectRes, created = LatestInfoTbl.objects.get_or_create(fileName = 'rss_30000001.xml', pubDate=lastBuildData.string.strip()) \n if not created :\n if selectRes.pubDate > lastBuildData.string.strip() :\n return\n selectRes.objects.filter(fileName = 'rss_30000001.xml').update(pubDate=lastBuildData.string.strip()) \n selectRes.save() \n \n self.__InsertRss(bsObject, RssDataTbl)\n \n def ShowRssTable(self):\n '''\n self.cur.execute(\"SELECT * FROM RssTable;\")\n rows = self.cur.fetchall()\n for row in rows:\n print(row)\n print(\"\\n\")\n '''\n","sub_path":"Soultion/webcrawl/SongCrawl.py","file_name":"SongCrawl.py","file_ext":"py","file_size_in_byte":4046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"202844697","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 12 14:42:00 2021\n\n@author: hp\n\"\"\"\nimport os\nimport numpy as np\nimport keras\nfrom tensorflow.keras.applications.vgg16 import VGG16\nimport cv2\n\nconv_base = VGG16(weights='imagenet',\n include_top=False,\n input_shape=(150, 150, 3))\n\n\n\n\nX_train = []\nY_train = []\n\nclasses=['speech', 'music', 'm+s']\ninput_path = f'/home/hp/.config/spyder-py3/music-speech/wavfile/train_data/' \nfor clas in classes:\n files = os.listdir(input_path + clas)\n for file in files:\n filePath = input_path + clas + '/' + file\n img = cv2.imread(filePath)\n img = np.expand_dims(img, axis=0)\n X_train.append(np.squeeze(img))\n Y_train.append(classes.index(clas))\n \nX_train = np.asarray(X_train)\nY_train = np.asarray(Y_train)\nprint(X_train.shape)\n\n#x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1]*x_train.shape[2]*x_train.shape[3]))\nnp.save(f'/home/hp/.config/spyder-py3/music-speech/wavfile/train_data/X_train.npy', X_train)\nnp.save(f'/home/hp/.config/spyder-py3/music-speech/wavfile/train_data/Y_train.npy', Y_train)\n\n\ninput_path = f'/home/hp/.config/spyder-py3/music-speech/wavfile/test_data/' \n\nX_test = []\nY_test = []\n\n\nfor clas in classes:\n files = os.listdir(input_path + clas)\n for file in files:\n filePath = input_path + clas + '/' + file\n img = cv2.imread(filePath)\n img = np.expand_dims(img, axis=0)\n X_test.append(np.squeeze(img))\n Y_test.append(classes.index(clas))\n\n\nX_test = np.asarray(X_test)\nY_test = np.asarray(Y_test)\nprint(X_test.shape)\n\n#x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1]*x_test.shape[2]*x_test.shape[3]))\nnp.save(f'/home/hp/.config/spyder-py3/music-speech/wavfile/test_data/X_test.npy', X_test)\nnp.save(f'/home/hp/.config/spyder-py3/music-speech/wavfile/test_data/Y_test.npy', Y_test) \n\n\n\n\n\n\n\n\n","sub_path":"CNN_data.py","file_name":"CNN_data.py","file_ext":"py","file_size_in_byte":1919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"293974638","text":"#\n# Running ERM with sci-learn kit\n# gd_log.py\n# author: Thong T. Nguyen\n# date Dec 25, 2014\n#\nimport numpy as np\nimport pandas as pd\nfrom sklearn.cross_validation import KFold\n\ndef drawNoise(d, mag):\n x = np.random.normal(size=(d,1))\n x = x / np.sqrt( np.sum(x*x) )\n return x * np.random.gamma(d, scale=1.0/mag)\n\ndef CL(w, x, y, a, b, c):\n z = y * np.dot(x, w)\n gz = -1.0 / (1+np.exp(z))\n return 2* np.dot(a, w) + b + c * np.dot(np.transpose(x), y*gz)\n\ndef gradient_descent(X, y, eta, epsilon, numSteps):\n (n, numcol) = np.shape(X)\n theta = np.zeros( (numcol, 1) )\n\n ep = 1.0* epsilon / numSteps;\n delta = 2.0 / n;\n b = np.zeros( (numcol,1))\n\n for it in range(numSteps):\n gd = CL(theta, X, y, 1.0/(n**2), b, 1.0/n)\n noise = drawNoise(numcol, ep /delta)\n\n theta = theta - eta(it+1) * ( gd + noise )\n\n return theta\n\ndef logisticTest(theta, X, y):\n t = y * np.dot(X, theta)\n return 1.0*np.sum(t < 0)/len(y)\n\ndef main():\n# lists of data sets\n dataset = ['BANKING', 'ADULT', 'IPUMS-BR2000', 'IPUMS-US2000']\n NUM_ITER = 10;\n\n for idx in range(1, 2):\n name = dataset[idx-1]\n print(\"Dataset #%s\" % name)\n\n out = open(\"%d_LOG_2.txt\" % idx, \"w\")\n\n # load and normalize data\n table = pd.read_table(\"Data/Data%d.dat\" % idx, sep='\\s+', header=None)\n (datarow, datacol) = table.shape\n rawdata = np.asfarray(table)\n datamin= np.min(rawdata, axis=0)\n datamax= np.max(rawdata, axis=0)\n # -> [0, 1] domain\n newdata = (rawdata - np.ones((datarow,1))*datamin) / (np.ones((datarow,1))*(datamax-datamin))\n newdata = (newdata - .5)*2 # -> [-1, 1] domain\n normX = np.column_stack( (newdata[:,0:-1], np.ones((datarow, 1))) ) # add bias\n #normX = normX / np.sqrt(np.max(np.sum((normX**2), 1))) # normalization\n Data = np.column_stack( (normX, newdata[:, -1]) )\n (DataRow, DataCol) = Data.shape\n\n X = Data[:, 0:-1]\n y = Data[:, [-1]]\n\n for it in range(NUM_ITER):\n print(\"iter #%d\" % (it+1))\n kf = KFold(DataRow, n_folds=5, shuffle=True)\n\n fold = 0\n for train, test in kf:\n fold = fold + 1\n X_train, X_test, y_train, y_test = X[train], X[test], y[train], y[test]\n eta = lambda t: 1.0/(np.sqrt(t))\n\n theta = gradient_descent(X_train, y_train, eta, 1, 90)\n\n err = logisticTest(theta, X_test, y_test)\n\n out.write(\"%d %d %d %f\\n\" % (idx, it, fold, err) )\n out.flush()\n print(\"## %d, error rate=%f\" % (fold,err))\n\n out.close()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"python/gd_log.py","file_name":"gd_log.py","file_ext":"py","file_size_in_byte":2727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"173634962","text":"from survey.models import Interviewer, LocationType\nimport operator\n\n\nclass ExportInterviewersService:\n\n def __init__(self, export_fields):\n self.interviewers = Interviewer.objects.all()\n self.HEADERS = export_fields\n\n def formatted_responses(self):\n _formatted_responses = []\n headers = [loc_type.name.upper()\n for loc_type in LocationType.in_between()]\n headers.extend([entry.upper() for entry in self.HEADERS])\n _formatted_responses.append(','.join(headers))\n interviewer_records = []\n for interviewer in self.interviewers:\n info = {}\n info['mobile_numbers'] = ','.join(\n [access.user_identifier for access in interviewer.ussd_access])\n info['odk_id'] = ','.join(\n [access.user_identifier for access in interviewer.odk_access])\n row = [str(loc.name) for loc in interviewer.ea.parent_locations()]\n row.extend(['\"%s\"' % str(getattr(interviewer, entry,\n info.get(entry, ''))) for entry in self.HEADERS])\n interviewer_records.append(row)\n interviewer_records = sorted(\n interviewer_records, key=operator.itemgetter(*range(len(headers))))\n _formatted_responses.extend(\n map(lambda row: ','.join(row), interviewer_records))\n return _formatted_responses\n","sub_path":"survey/services/export_interviews.py","file_name":"export_interviews.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"577148090","text":"import json\nimport argparse\nimport pymongo\nfrom AppStoreConnectReporter import *\nfrom AppStoreConnectReporterErrors import *\n\n\ndef AppSalesReportItemToDictAsPreparationForDocumentConvertion(item: Union[AppSalesReportItem, AppSalesReportExtrapolatedDetailItem]) -> Dict[str, Any]:\n logging.debug(\"Type of item: \"+str(type(item)))\n logging.debug(\"item is: \"+str(item))\n newItem = {\n \"Provider\": item.Provider,\n \"ProviderCountry\": item.ProviderCountry,\n \"SKU\": item.SKU,\n \"Developer\": item.Developer,\n \"Title\": item.Title,\n \"Version\": item.Version,\n \"ProductTypeIdentifier\": item.ProductTypeIdentifier,\n \"BeginDate\": item.BeginDate,\n \"EndDate\": item.EndDate,\n \"CustomerCurrency\": item.CustomerCurrency,\n \"CountryCode\": item.CountryCode,\n \"CurrencyOfProceeds\": item.CurrencyOfProceeds,\n \"AppleIdentifier\": item.AppleIdentifier,\n \"PromoCode\": item.PromoCode,\n \"ParentIdentifier\": item.ParentIdentifier,\n \"Subscription\": item.Subscription,\n \"Period\": item.Period,\n \"Category\": item.Category,\n \"CMB\": item.CMB,\n \"Device\": item.Device,\n \"SupportedPlatforms\": item.SupportedPlatforms,\n \"Client\": item.Client,\n \"OrderType\": item.OrderType\n }\n if type(item) == AppSalesReportItem:\n newItem[\"Units\"] = item.Units\n newItem[\"ProceedsReason\"] = item.ProceedsReason\n newItem[\"PreservedPricing\"] = item.PreservedPricing\n newItem[\"CustomerPrice\"] = item.CustomerPrice\n newItem[\"DeveloperProceeds\"] = item.DeveloperProceeds\n\n return newItem\n\n\ndef getReport(date: datetime.datetime, *, period: DateType, forVendorId: str) -> List[AppSalesReportItem]:\n try:\n report = AppStoreConnectSalesReporter().getReport(\n vendorId=forVendorId,\n type=SalesReportType.sales,\n subType=SalesReportSubType.summary,\n dateType=period,\n date=date\n )\n return report\n\n except InvalidVendor as ex:\n logging.exception(ex)\n\n except ReportsDelayed as ex:\n logging.exception(ex)\n\n except ReportNoLongerAvailable as ex:\n logging.exception(ex)\n return []\n\n except ReportNotAvailableYet as ex:\n logging.exception(ex)\n\n except ReportNotAvailableYetUnexpected as ex:\n logging.exception(ex)\n\n except Exception as ex:\n logging.exception(ex)\n raise ex\n\n\ndef getReportAsDocumentForMongo(report: List[AppSalesReportItem]) -> List[Dict[str, Any]]:\n reportDictList = []\n for item in report:\n reportDict = AppSalesReportItemToDictAsPreparationForDocumentConvertion(item)\n reportDictList.append(reportDict)\n return reportDictList\n\n\ndef insertToMongoDBOverwritingEntireCollection(mongoconnection: str, database: str, collection: str, document: List):\n mongoClient = pymongo.MongoClient(mongoconnection)\n mongoDatabase = mongoClient[database]\n mongoCollection = mongoDatabase[collection]\n\n if document is not None and len(document) >= 1: # dont insert an empty list as that would fail\n mongoCollection.insert_many(document)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Load data from App Store Connect to a database.')\n parser.add_argument('--yesterday-daily', help='Import daily data from yesterday.', action='store_true')\n parser.add_argument('--year', help='The year for the report.', type=int, default=datetime.datetime.now().year)\n parser.add_argument('--month', help='The month for the report.', type=int, default=1)\n parser.add_argument('--day', help='The day for the report.', type=int, default=1)\n parser.add_argument(\n '--period',\n help='The period for the report.',\n type=str, choices=[\"yearly\", \"monthly\", \"weekly\", \"daily\"],\n default=\"daily\"\n )\n parser.add_argument('--log-level', help='The log level to use.', type=int, choices=[\"DEBUG\"])\n parser.add_argument('--print', help='Display the report data on screen.', action='store_true')\n parser.add_argument('--dry-run', help='Dont load data into a database.', action='store_true')\n shellParameters = parser.parse_args()\n\n if shellParameters.log_level is not None:\n logging.basicConfig(level=logging.DEBUG)\n\n with open(\"config.json\", \"r\") as f:\n configObject = json.JSONDecoder().decode(f.read())\n\n date = None\n if shellParameters.yesterday_daily is True:\n today = datetime.datetime.now()\n yesterday = today - datetime.timedelta(days=1)\n date = yesterday\n else:\n date = datetime.datetime(\n year=shellParameters.year,\n month=shellParameters.month,\n day=shellParameters.day\n )\n logging.debug(\"Using date: \"+str(date))\n\n report = getReport(\n date,\n period=DateType[shellParameters.period],\n forVendorId=configObject[\"vendorId\"]\n )\n\n reportSummaryAsMongoDocument = getReportAsDocumentForMongo(report)\n\n also_extrapolate_detail = configObject[\"also_extrapolate_detail\"]\n if also_extrapolate_detail == True:\n reportExtapolatedDetail = AppStoreConnectSalesReporter.extrapolateDetailReportFromAppleSummaryFormat(report)\n reportDetailAsMongoDocument = getReportAsDocumentForMongo(reportExtapolatedDetail)\n\n if shellParameters.print is True:\n print(\"Summary:\")\n print(reportSummaryAsMongoDocument)\n if shellParameters.print is True and also_extrapolate_detail:\n print(\"Detail:\")\n print(reportDetailAsMongoDocument)\n\n if shellParameters.dry_run is False:\n logging.debug(\"Writing to Database.\")\n configDB = configObject[\"db\"]\n insertToMongoDBOverwritingEntireCollection(\n mongoconnection=configDB[\"connectionString\"],\n database=configDB[\"database\"],\n collection=configDB[\"collection_summary\"],\n document=reportSummaryAsMongoDocument\n )\n if also_extrapolate_detail:\n insertToMongoDBOverwritingEntireCollection(\n mongoconnection=configDB[\"connectionString\"],\n database=configDB[\"database\"],\n collection=configDB[\"collection_detail_extrapolated\"],\n document=reportDetailAsMongoDocument\n )","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"14035209","text":"#!/usr/env/python python3\n# -*- coding: utf-8 -*-\n# @File : prep_binary.py\n# @Time : 19-8-12 下午10:12 \n# @Software : PyCharm\n\nimport face_alignment\nimport cv2\nimport numpy as np\nfrom glob import glob\nfrom pathlib import PurePath, Path\nfrom matplotlib import pyplot as plt\n\ndir_faceA = \"./faceA\"\ndir_faceB = \"./faceB\"\ndir_bm_faceA_eyes = \"./binary_masks/faceA_eyes\"\ndir_bm_faceB_eyes = \"./binary_masks/faceB_eyes\"\n\nfns_faceA = glob(f\"{dir_faceA}/*.*\")\nfns_faceB = glob(f\"{dir_faceB}/*.*\")\n\nfa = face_alignment.FaceAlignment(face_alignment.LandmarksType._2D, flip_input=False)\n\n# !mkdir -p binary_masks/faceA_eyes\nPath(f\"binary_masks/faceA_eyes\").mkdir(parents=True, exist_ok=True)\n# !mkdir -p binary_masks/faceB_eyes\nPath(f\"binary_masks/faceB_eyes\").mkdir(parents=True, exist_ok=True)\n\nfns_face_not_detected = []\n\nfor idx, fns in enumerate([fns_faceA, fns_faceB]):\n if idx == 0:\n save_path = dir_bm_faceA_eyes\n elif idx == 1:\n save_path = dir_bm_faceB_eyes\n\n # create binary mask for each training image\n for fn in fns:\n raw_fn = PurePath(fn).parts[-1]\n\n x = plt.imread(fn)\n x = cv2.resize(x, (256, 256))\n preds = fa.get_landmarks(x)\n\n if preds is not None:\n preds = preds[0]\n mask = np.zeros_like(x)\n\n # Draw right eye binary mask\n pnts_right = [(preds[i, 0], preds[i, 1]) for i in range(36, 42)]\n hull = cv2.convexHull(np.array(pnts_right)).astype(np.int32)\n mask = cv2.drawContours(mask, [hull], 0, (255, 255, 255), -1)\n\n # Draw left eye binary mask\n pnts_left = [(preds[i, 0], preds[i, 1]) for i in range(42, 48)]\n hull = cv2.convexHull(np.array(pnts_left)).astype(np.int32)\n mask = cv2.drawContours(mask, [hull], 0, (255, 255, 255), -1)\n\n # Draw mouth binary mask\n # pnts_mouth = [(preds[i,0],preds[i,1]) for i in range(48,60)]\n # hull = cv2.convexHull(np.array(pnts_mouth)).astype(np.int32)\n # mask = cv2.drawContours(mask,[hull],0,(255,255,255),-1)\n\n mask = cv2.dilate(mask, np.ones((13,13), np.uint8), iterations=1)\n mask = cv2.GaussianBlur(mask, (7,7), 0)\n\n else:\n mask = np.zeros_like(x)\n print(f\"No faces were detected in image '{fn}''\")\n fns_face_not_detected.append(fn)\n\n plt.imsave(fname=f\"{save_path}/{raw_fn}\", arr=mask, format=\"jpg\")\n\n\nnum_faceA = len(glob(dir_faceA+\"/*.*\"))\nnum_faceB = len(glob(dir_faceB+\"/*.*\"))\n\nprint(\"Nuber of processed images: \"+ str(num_faceA + num_faceB))\nprint(\"Number of image(s) with no face detected: \" + str(len(fns_face_not_detected)))\n\nface = np.random.choice([\"A\",\"B\"])\n\ndir_face = dir_faceA if face == \"A\" else dir_faceB\nfns_face = fns_faceA if face == \"A\" else fns_faceB\nnum_face = len(glob(dir_face+\"/*.*\"))\nrand_idx = np.random.randint(num_face)\nrand_fn = fns_face[rand_idx]\nraw_fn = PurePath(rand_fn).parts[-1]\nmask_fn = f\"{dir_bm_faceA_eyes}/{raw_fn}\" if face == \"A\" else f\"{dir_bm_faceB_eyes}/{raw_fn}\"\nim = plt.imread(rand_fn)\nmask = plt.imread(mask_fn)\n\nif rand_fn in fns_face_not_detected:\n print(\"========== No faces were detected in this image! ==========\")\n\nfig = plt.figure(figsize=(15,6))\nplt.subplot(1,3,1)\nplt.grid('off')\nplt.imshow(im)\nplt.subplot(1,3,2)\nplt.grid('off')\nplt.imshow(mask)\nplt.subplot(1,3,3)\nplt.grid('off')\n# plt.imshow((mask/255*im).astype(np.uint8))\n\n#fa.get_landmarks(x)\n\nnum_no_face_img = len(fns_face_not_detected)\n# rand_idx = np.random.randint(num_no_face_img)\n# x = plt.imread(fns_face_not_detected[rand_idx])\n#x = cv2.resize(x, (256,256))\n\n# plt.grid('off')\n# plt.imshow(x)\n","sub_path":"prep_binary.py","file_name":"prep_binary.py","file_ext":"py","file_size_in_byte":3669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"354159283","text":"from typing import Optional\n\nfrom hypothesis import strategies\nfrom sqlalchemy.sql.sqltypes import (BigInteger,\n Boolean,\n Date,\n DateTime,\n Enum,\n Float,\n Integer,\n Interval,\n LargeBinary,\n SmallInteger,\n String,\n Time)\nfrom sqlalchemy.sql.type_api import TypeEngine\n\nfrom hypothesis_sqlalchemy import enumerable\nfrom hypothesis_sqlalchemy.hints import Strategy\nfrom hypothesis_sqlalchemy.utils import sql_identifiers\n\n\ndef strings_factory(lengths: Strategy[int] =\n strategies.integers(min_value=0,\n # Postgres VARCHAR max size\n max_value=10485760)\n ) -> Strategy[TypeEngine]:\n return strategies.builds(String,\n length=lengths)\n\n\ndef binary_strings_factory(lengths: Strategy[int] =\n strategies.integers(min_value=0,\n # MySQL BLOB max size\n max_value=65535)\n ) -> Strategy[TypeEngine]:\n return strategies.builds(LargeBinary,\n length=lengths)\n\n\ndef primary_keys_factory() -> Strategy[TypeEngine]:\n types = [SmallInteger, Integer, BigInteger]\n return strategies.one_of(*map(strategies.builds, types))\n\n\ndef enums_factory(*,\n values: Strategy[str] = sql_identifiers,\n min_size: int = 1,\n max_size: Optional[int] = None) -> Strategy[TypeEngine]:\n enums_keys = values.filter(enumerable.is_valid_key)\n return ((strategies.tuples(enumerable.factory(keys=enums_keys,\n min_size=min_size,\n max_size=max_size))\n | strategies.lists(values,\n min_size=min_size,\n max_size=max_size))\n .map(lambda type_values: Enum(*type_values)))\n\n\ndef factory(*,\n string_types: Strategy[TypeEngine] = strings_factory(),\n binary_string_types: Strategy[TypeEngine] =\n binary_strings_factory(),\n enum_types: Strategy[TypeEngine] = enums_factory(),\n primary_keys_types: Strategy[TypeEngine] = primary_keys_factory()\n ) -> Strategy[TypeEngine]:\n extra_types = [Float(asdecimal=True), Boolean(),\n Date(), DateTime(), Interval(), Time()]\n return strategies.one_of(string_types,\n binary_string_types,\n enum_types,\n primary_keys_types,\n strategies.sampled_from(extra_types))\n","sub_path":"hypothesis_sqlalchemy/columnar/types.py","file_name":"types.py","file_ext":"py","file_size_in_byte":3102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"400027128","text":"import copy\n# base.py\ntrain_cfg = {}\ntest_cfg = {}\noptimizer_config = dict() # grad_clip, coalesce, bucket_size_mb\n# yapf:disable\nlog_config = dict(\n interval=10,\n hooks=[\n dict(type='TextLoggerHook'),\n dict(type='TensorboardLoggerHook')\n ])\n# yapf:enable\n# runtime settings\ndist_params = dict(backend='nccl')\ncudnn_benchmark = True\nlog_level = 'INFO'\nload_from = None\nresume_from = None\nworkflow = [('train', 1)]\n# model settings\nmodel = dict(\n type='SiameseSupernetsNATS',\n pretrained=None,\n base_momentum=0.99,\n pre_conv=True,\n backbone=dict(\n type='SupernetNATS',\n target='cifar10', # cifar10/cifar100 on nats\n ),\n start_block=0,\n num_block=3,\n neck=dict(\n type='NonLinearNeckSimCLR',\n in_channels=2048,\n hid_channels=4096,\n out_channels=256,\n num_layers=2,\n sync_bn=False,\n with_bias=True,\n with_last_bn=False,\n with_avg_pool=True),\n head=dict(type='LatentPredictHead',\n size_average=True,\n predictor=dict(type='NonLinearNeckSimCLR',\n in_channels=256, hid_channels=4096,\n out_channels=256, num_layers=2, sync_bn=False,\n with_bias=True, with_last_bn=False, with_avg_pool=False)))\n# dataset settings\ndata_source_cfg = dict(type='NATSCifar10', root='../data/cifar/', return_label=False)\ntrain_dataset_type = 'BYOLDataset'\ntest_dataset_type = 'StoragedBYOLDataset'\nimg_norm_cfg = dict(mean=[0.4914, 0.4822, 0.4465], std=[0.2023, 0.1994, 0.201])\ntrain_pipeline = [\n dict(type='RandomCrop', size=32, padding=4),\n dict(type='RandomHorizontalFlip'),\n]\n# prefetch\nprefetch = False\nif not prefetch:\n train_pipeline.extend([dict(type='ToTensor'), dict(type='Normalize', **img_norm_cfg)])\ntrain_pipeline1 = copy.deepcopy(train_pipeline)\ntrain_pipeline2 = copy.deepcopy(train_pipeline)\n\ntest_pipeline1 = copy.deepcopy(train_pipeline1)\ntest_pipeline2 = copy.deepcopy(train_pipeline2)\ndata = dict(\n imgs_per_gpu=256, # total 256*4(gpu)*4(interval)=4096\n workers_per_gpu=2,\n train=dict(\n type=train_dataset_type,\n data_source=dict(split='train', **data_source_cfg),\n pipeline1=train_pipeline1, pipeline2=train_pipeline2),\n val=dict(\n type=test_dataset_type,\n data_source=dict(split='test', **data_source_cfg),\n pipeline1=test_pipeline1, pipeline2=test_pipeline2,),\n test=dict(\n type=test_dataset_type,\n data_source=dict(split='test', **data_source_cfg),\n pipeline1=test_pipeline1, pipeline2=test_pipeline2,))\n\n# optimizer\noptimizer = dict(type='LARS', lr=0.48, weight_decay=0.000001, momentum=0.9,\n paramwise_options={\n '(bn|gn)(\\d+)?.(weight|bias)': dict(weight_decay=0., lars_exclude=True),\n 'bias': dict(weight_decay=0., lars_exclude=True)})\n# apex\nuse_fp16 = True\n# interval for accumulate gradient\nupdate_interval = 4\noptimizer_config = dict(update_interval=update_interval, use_fp16=use_fp16)\n\n# learning policy\nlr_config = dict(\n policy='CosineAnnealing',\n min_lr=0.,\n warmup='linear',\n warmup_iters=2,\n warmup_ratio=0.0001, # cannot be 0\n warmup_by_epoch=True)\ncheckpoint_config = dict(interval=1)\n# runtime settings\ntotal_epochs = 150\n# additional hooks\ncustom_hooks = [\n dict(type='BYOLHook', end_momentum=1., update_interval=update_interval),\n dict(type='FairPathHook'),\n dict(\n type='ValNATSPathHook',\n dataset=data['val'],\n bn_dataset=data['train'],\n initial=True,\n interval=10,\n optimizer_cfg=optimizer,\n lr_cfg=lr_config,\n imgs_per_gpu=256,\n workers_per_gpu=4,\n epoch_per_stage=50,\n resume_best_path='') # e.g. 'path_rank/bestpath_2.yml'\n]\n# resume_from = 'checkpoints/stage3_epoch3.pth'\nresume_optimizer = False","sub_path":"searching/configs/nats_c10_bs256_accumulate4_gpus4.py","file_name":"nats_c10_bs256_accumulate4_gpus4.py","file_ext":"py","file_size_in_byte":3911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"305449513","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\n# ____ _ _ \n# | _ \\ ___| |_ __ | |__ __ _ ___ \n# | | | |/ _ \\ | '_ \\| '_ \\ / _` |/ _ \\\n# | |_| | __/ | |_) | | | | (_| | __/\n# |____/ \\___|_| .__/|_| |_|\\__,_|\\___|\n# |_| \n\n# Program will retrieve the RIPE data corresponding to the IP address of this device\n# It only uses standard libraries urllib2 and json\n# So it will run on all kind of devices that support Python\n\n\n__version__ = \"1.02\"\n__date__ = \"2016-12-25\"\n\n\nimport urllib2,json\nimport sys\nimport socket\n\n#get my ipaddress\n\nif len(sys.argv)==1:\n param=''\nelse:\n param=sys.argv[1]\n\n'''\nipapiurl = 'http://ip-api.com/json/'+host\nipapidata = json.loads(urllib2.urlopen(ipapiurl).read())\nipaddress=ipapidata['query'] \n'''\n\nif param=='':\n ipinfo = json.loads(urllib2.urlopen('http://ipinfo.io/json').read())\n ipaddress = ipinfo['ip']\nelse:\n ipaddress = socket.gethostbyname(param)\n ipinfo = json.loads(urllib2.urlopen('http://ipinfo.io/'+ipaddress+'/json').read())\n ipaddress = ipinfo['ip']\n \n \nfqdn = socket.gethostbyaddr(ipaddress)[0]\n \nprint\nprint ('\\033[34;1mRIPE information\\033[0m')\nprint (\"%-15s%s\" % ('IP address', ipaddress))\nprint (\"%-15s%s\" % ('Hostname',fqdn))\nprint ('-'*55) \nprint \n\n#get data from RIPE\nripeurl = 'http://rest.db.ripe.net/search.json?query-string='+ipaddress\ntry:\n response = urllib2.urlopen(ripeurl).read()\nexcept:\n print ('Invalid IP address')\n sys.exit()\nripedata = json.loads(response)\n\n#extract the data\nripeobjects = ripedata['objects']['object']\n \n#transform data to a flat dict of dicts\nripe = {} \nfor item in ripeobjects:\n attribute = item['attributes']['attribute']\n name = attribute[0]['name']\n ripe[name] = dict([(attrib['name'], attrib['value']) for attrib in attribute])\n\n#print in correct order\n#for ripekey in ['inetnum','route','organisation','role']:\nfor ripekey in ['inetnum','route']:\n print (\"\\033[34;1m%s\\033[0m\" % ripekey)\n try:\n for key, val in ripe[ripekey].items():\n print (\"%-15s%s\" % (key, val))\n except:\n print ('No information')\n pass\n print\n \n\n ","sub_path":"RIPE-json.py","file_name":"RIPE-json.py","file_ext":"py","file_size_in_byte":2222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"483944926","text":"import sys\nimport tkinter as tk\nfrom tkinter import scrolledtext, Canvas\nfrom tkinter.filedialog import askopenfilename\nfrom tkinter.font import Font\nfrom PIL import ImageTk,Image\nimport webbrowser\nimport os\n\n\nprevious_text_starts_at=0\n\n\ndef open_git_page(event):\n webbrowser.open_new(r\"https://github.com/sairash/text_game_maker\")\n\ndef open_file():\n \"\"\"Open a file for editing.\"\"\"\n filepath = askopenfilename(\n filetypes=[(\"Text Files\", \"*.tgm\")]\n )\n if not filepath:\n return\n txt_edit.delete(1.0, tk.END)\n with open(filepath, \"r\") as input_file:\n text = input_file.read()\n txt_edit.insert(tk.END, text)\n window.title(f\"Text Game Maker - {filepath}\")\n\n\n\ndef save_file():\n \"\"\"Save the current file as a new file.\"\"\"\n with open('game.tgm', \"w\") as output_file:\n text = txt_edit.get(1.0, tk.END).split(\"\\n\")\n text = \"\\n\".join(text[:-1])\n if text != '\\r':\n output_file.write(text)\n window.title(f\"Text Game Maker\")\n\n\ndef run_file():\n os.system('cmd /k \"python --version\"')\n\n\ndef key_binds(event):\n txt_edit.tag_delete('here')\n global previous_text_starts_at, previous_text_ends_at\n if event.keysym == 'o':\n open_file()\n elif event.keysym == 's':\n save_file()\n\n for syntax_line in range(int(float(txt_edit.index('end')))):\n print(syntax_line)\n index = txt_edit.search(r'\\[*\\]', str(float(syntax_line)), tk.END, regexp=True)\n txt_edit.tag_add(\"here\", str(float(syntax_line)+0.1), index)\n \n txt_edit.tag_config(\"here\", foreground=\"green\")\n\ndef make_bold():\n\n # tk.TclError exception is raised if not text is selecte\n try:\n txt_edit.tag_add(\"BOLD\", \"sel.first\", \"sel.last\")\n except tk.TclError:\n pass\n\n\n\n\nwindow = tk.Tk()\nwindow.title(\"Text Game Maker\")\nwindow.rowconfigure(0, minsize=800, weight=1)\nwindow.columnconfigure(1, minsize=800, weight=1)\n\n \nphoto = ImageTk.PhotoImage(file = \"book_logo_tU5_icon.ico\")\nwindow.iconphoto(False, photo)\n\n\ntxt_edit = scrolledtext.ScrolledText(window, wrap = tk.WORD, font = (\"Times New Roman\", 15))\n\nfr_buttons = tk.Frame(window, relief=tk.RAISED, bd=2)\ncanvas = Canvas(fr_buttons, width = 100, height = 124.4, cursor=\"hand2\")\n\ngit_sairash = tk.Label( fr_buttons, text='git: @sairash' , cursor=\"hand2\")\nbtn_new = tk.Button(fr_buttons, text=\"New\", command=save_file, cursor=\"hand2\")\nbtn_open = tk.Button(fr_buttons, text=\"Open\", command=open_file, cursor=\"hand2\")\nbtn_save = tk.Button(fr_buttons, text=\"Save\", command=save_file, cursor=\"hand2\")\nbtn_run = tk.Button(fr_buttons, text=\"Run\", command=run_file, cursor=\"hand2\")\n\ncanvas.grid(row=0, column=0, sticky=\"ew\", padx=5, pady=5)\nbtn_new.grid(row=1, column=0, sticky=\"ew\", padx=5)\nbtn_open.grid(row=2, column=0, sticky=\"ew\", padx=5, pady=5)\nbtn_save.grid(row=3, column=0, sticky=\"ew\", padx=5)\nbtn_run.grid(row=4, column=0, sticky=\"ew\", padx=5)\ngit_sairash.grid(row=5, column=0, sticky=\"ew\", padx=5)\n\nfr_buttons.grid(row=0, column=0, sticky=\"ns\")\ntxt_edit.grid(row=0, column=1, sticky=\"nsew\")\n\nimage = Image.open('book_logo.png')\nimage = image. resize((100, 124), Image. ANTIALIAS) \nimg = ImageTk.PhotoImage(image)\ncanvas.create_image(5,5, anchor='nw', image=img) \n\ngit_sairash.bind(\"\", open_git_page)\ncanvas.bind(\"\", open_git_page)\nwindow.bind(\"\", key_binds)\nwindow.bind(\"\", key_binds)\ntxt_edit.bind(\"[\",key_binds)\n\ntxt_edit.focus_set()\n\nwindow.mainloop()","sub_path":"making__/text_game_maker_editor/text_editor.py","file_name":"text_editor.py","file_ext":"py","file_size_in_byte":3458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"526085086","text":"import tensorflow as tf\nimport numpy as np\nimport sys\nsys.path.append(\"/home/a_parida/MantaFlow/manta/tensorflow/tools/\")\nimport uniio\nimport glob\nimport random\nimport scipy.misc\nimport os\nbasePath = 'data/' # path where data is availabe;\n\ntrainingEpochs = 1500\nbatchSize = 150\ninSize = 64 * 64 * 2\n######################################################\n# Ex 2.1 – Saving and Loading Training Data\n#####################################################\n\nvel_files= glob.glob('./data/**/*.uni', recursive=True)\n# load data\nvelocities = []\n\nfor uniPath in vel_files:\n header, content = uniio.readUni(uniPath)# returns [Z,Y,X,C] np array\n h = header['dimX']\n w = header['dimY']\n arr = content[:, ::-1, :, :-1] # reverse order of Y axis\n arr = np.reshape(arr, [w, h, 2])# discard Z from [Z,Y,X]\n velocities.append( arr )\n\nloadNum = len(velocities)\nif loadNum<200:\n\tprint(\"Error - use at least two full sims, generate data by running 'manta ./manta_genSimSimple.py' a few times...\"); exit(1)\n\nvelocities = np.reshape( velocities, (len(velocities), 64,64,2) )\n\nprint(\"Read uni files, total data \" + format(velocities.shape) )\nvaliSize = max(100, int(loadNum * 0.1)) # at least 1 full sim...\nvaliData = velocities[loadNum-valiSize:loadNum,:]\nvelocities = velocities[0:loadNum-valiSize,:]\nprint(\"Split into %d training and %d validation samples\" % (velocities.shape[0], valiData.shape[0]) )\nloadNum = velocities.shape[0]\n\n############################################################\n\n##############################################################\n# Ex 2.2– First Network Architecture\n##############################################################\n\ndef convolution2d(input, biases, weights, strides, padding_kind='SAME'):\n input = tf.nn.conv2d(input, weights, strides, padding=padding_kind)\n input = tf.nn.bias_add(input, biases)\n input = tf.nn.leaky_relu(input)\n return input\n\ndef velocityFieldToPng(frameArray):\n \"\"\" Returns an array that can be saved as png with scipy.misc.toimage\n from a velocityField with shape [height, width, 2].\"\"\"\n outputframeArray = np.zeros((frameArray.shape[0], frameArray.shape[1], 3))\n for x in range(frameArray.shape[0]):\n for y in range(frameArray.shape[1]):\n # values above/below 1/-1 will be truncated by scipy\n frameArray[y][x] = (frameArray[y][x] * 0.5) + 0.5\n outputframeArray[y][x][0] = frameArray[y][x][0]\n outputframeArray[y][x][1] = frameArray[y][x][1]\n return outputframeArray\n\n# the network structure\nxIn = tf.placeholder(tf.float32, shape=[None, 64,64, 2])\n\ny = tf.placeholder(tf.float32, shape=[None, 64,64,2])\nxOut=tf.reshape(y, shape=[-1, 64*64*2])\n\n#layer1: Convolution\nweights1=tf.Variable(tf.random_normal([12,12,2,2], stddev=0.01))#weights==filters\n#[filter_height, filter_width, in_channels, out_channels]\n#bias=out_channels\nbias1=tf.Variable(tf.random_normal([2], stddev=0.01))\nstride1=[1,4,4,1]\nout1=convolution2d(xIn,bias1,weights1,stride1)\n\n#layer2: Convolution\nweights2=tf.Variable(tf.random_normal([6,6,2,4], stddev=0.01))#weights==filters\n#[filter_height, filter_width, in_channels, out_channels]\n#bias=out_channels\nbias2=tf.Variable(tf.random_normal([4], stddev=0.01))\nstride2=[1,4,4,1]\nout2=convolution2d(out1,bias2,weights2,stride2)\n\n#layer3: Fully Connected Network\nout2 = tf.reshape(out2, shape=[-1, 64 ]) # flatten\nfc_1weights = tf.Variable(tf.random_normal([64, 64*64*2], stddev=0.01))\nfc_1bias = tf.Variable(tf.random_normal([64*64*2], stddev=0.01))\nfc1 = tf.add(tf.matmul(out2, fc_1weights), fc_1bias)\nfc1 = tf.nn.tanh(fc1)\n\n# cost and Optimistion\ncost = tf.nn.l2_loss(fc1 - xOut)\nopt = tf.train.AdamOptimizer(0.0001).minimize(cost)\n\n#creating Seesion starting training\nprint(\"Starting training...\")\nsess = tf.InteractiveSession()\nsess.run(tf.global_variables_initializer())\n\n# lets train for all epochs\nfor epoch in range(trainingEpochs):\n\tbatch = []\n\tfor currNo in range(0, batchSize):\n\t\tr = random.randint(0, loadNum-1)\n\t\tbatch.append( velocities[r] )\n\n\t_ , currentCost = sess.run([opt, cost], feed_dict={xIn: batch, y: batch})\n\tif epoch%10==9 or epoch==trainingEpochs-1:\n\t\t[valiCost,vout] = sess.run([cost, fc1], feed_dict={xIn: valiData, y: valiData})\n\t\tprint(\"Epoch %d/%d: cost %f , validation cost %f \" % (epoch, trainingEpochs, currentCost, valiCost) )\n\n\t\tif epoch==trainingEpochs-1:\n\t\t\toutDir = \"./test_simple/ConvConvFC/\"\n\t\t\tif not os.path.exists(outDir): os.makedirs(outDir)\n\t\t\tprint(\"\\n Training done. Writing %d images from validation data to directory %s...\" % (len(valiData),outDir) )\n\t\t\tfor i in range(len(valiData)):\n\t\t\t\tval_in=velocityFieldToPng(valiData[i])\n\t\t\t\tval_out=velocityFieldToPng(vout[i].reshape((64, 64,2)))\n\t\t\t\tscipy.misc.toimage( np.reshape(val_in, [64, 64, 3]) , cmin=0.0, cmax=1.0).save(\"%s/in_%d.png\" % (outDir,i))\n\t\t\t\tscipy.misc.toimage( np.reshape(val_out, [64, 64, 3]) , cmin=0.0, cmax=1.0).save(\"%s/out_%d.png\" % (outDir,i))\n\nprint(\"Done...\")\n\ntotal_parameters = 0\nfor variable in tf.trainable_variables():\n # shape is an array of tf.Dimension\n shape = variable.get_shape()\n variable_parameters = 1\n for dim in shape:\n variable_parameters *= dim.value\n #print(variable_parameters)\n total_parameters += variable_parameters\nprint(\"Total No. Learnable Parameters Conv & Fully Connected:\",total_parameters)\n############################################################\n","sub_path":"Assignment2/FirstNetworkArchitecture.py","file_name":"FirstNetworkArchitecture.py","file_ext":"py","file_size_in_byte":5406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"593220495","text":"import sys\nimport csv\nfrom LALR_parser import *\nimport global_vars as g\n\nleader_instructions = [\n \"ifgoto\",\n \"return\",\n \"label\",\n \"call\",\n \"print_int\",\n \"scan_int\",\n \"goto\",\n \"func\",\n \"begin_func\",\n \"end_func\"\n]\n\nreg_descriptor = dict()\n\n\nreg_descriptor[\"ebx\"] = set()\nreg_descriptor[\"ecx\"] = set()\nreg_descriptor[\"esi\"] = set()\nreg_descriptor[\"edi\"] = set()\nreg_descriptor[\"edx\"] = set()\nreg_descriptor[\"eax\"] = set()\n\nfunc_symbol_table = None\n\ndef is_temp_var(symbol):\n if symbol[0] == \"_\":\n return True\n return False\n\ndef reset_live_and_next_use():\n for symbol in g.symbol_table.keys():\n g.symbol_table[symbol].live = True\n g.symbol_table[symbol].next_use = None\n return g.symbol_table\n\ndef is_valid_number(symbol):\n if symbol[0] == \"-\":\n return True\n return symbol.isdigit()\n\ndef is_valid_sym(symbol):\n if type(symbol) != type(''):\n return False\n elif symbol != None and symbol[0] == \"'\" and symbol[-1] == \"'\" and len(symbol) > 2:\n return False\n elif symbol != None and symbol[0] == \"`\" and symbol[-1] == \"`\" and len(symbol) > 3:\n return False\n elif symbol != None and not is_valid_number(symbol):\n return True\n return False\n\nclass SymbolTableEntry:\n def __init__(self):\n # self.value = None\n self.live = True\n self.next_use = None\n self.array_size = None\n self.address_descriptor_mem = set()\n self.address_descriptor_reg = set()\n\n\nclass Instruction:\n def __init__(self, statement):\n self.line_no = int(statement[0].strip())\n self.label_to_be_added = False\n self.inp1 = None\n self.array_index_i1 = None\n self.inp2 = None\n self.array_index_i2 = None\n self.out = None\n self.array_index_o = None\n self.operation = None\n self.instr_type = None\n self.label_name = None\n self.jmp_to_line = None\n self.jmp_to_label = None\n self.table = None\n self.per_inst_next_use = dict()\n self.build(statement)\n self.populate_per_inst_next_use()\n self.arg_set = []\n\n def add_to_symbol_table(self, symbols, is_array_dec=False):\n '''\n Add the symbol into symbol table if not already exists\n '''\n if not is_array_dec:\n for symbol in symbols:\n if is_valid_sym(symbol):\n if is_temp_var(symbol):\n g.temp_var_set.add(symbol)\n global func_symbol_table\n if symbol not in func_symbol_table.keys():\n func_symbol_table[symbol] = SymbolTableEntry()\n if is_temp_var(symbol):\n func_symbol_table[symbol].address_descriptor_mem.add(symbol)\n else:\n # an array is declared: arr[100]\n # store 'symbols[0]` in symbol table if not already present\n # set size of array to `symbols[1]`\n if is_valid_sym(symbols[0]):\n if symbols[0] not in func_symbol_table.keys():\n func_symbol_table[symbols[0]] = SymbolTableEntry()\n func_symbol_table[symbols[0]].array_size = symbols[1]\n\n\n def handle_array_notation(self, symbol):\n '''\n Given a symbol, possibly in the form of a[i],\n split into `a` and index `i`\n '''\n index = symbol.find(\"[\")\n if index != -1:\n return symbol[:index], symbol[index + 1:-1]\n else:\n return symbol, None\n\n\n def build(self, statement):\n '''\n Populate appropriate entries of Instruction class\n according to instruction type\n '''\n instr_type = statement[1].strip()\n if instr_type == \"ifgoto\":\n # 10, ifgoto, leq, a, 50, 2\n self.instr_type = \"ifgoto\"\n self.operation = statement[2].strip()\n\n self.inp1, self.array_index_i1 = self.handle_array_notation(statement[3].strip())\n self.inp2, self.array_index_i2 = self.handle_array_notation(statement[4].strip())\n self.add_to_symbol_table([\n self.inp1, self.array_index_i1,\n self.inp2, self.array_index_i2\n ])\n\n jmp_location = statement[-1].strip()\n if jmp_location.isdigit():\n self.jmp_to_line = jmp_location\n else:\n self.jmp_to_label = jmp_location\n\n elif instr_type == \"goto\":\n self.instr_type = \"goto\"\n\n jmp_location = statement[-1].strip()\n if jmp_location.isdigit():\n self.jmp_to_line = jmp_location\n else:\n self.jmp_to_label = jmp_location\n\n elif instr_type == \"print_INT\":\n # 10, print, variable\n self.instr_type = \"print_int\"\n self.inp1, self.array_index_i1 = self.handle_array_notation(statement[-1].strip())\n self.add_to_symbol_table([self.inp1, self.array_index_i1])\n\n elif instr_type == \"print_CHAR\":\n self.instr_type = \"print_char\"\n self.inp1, self.array_index_i1 = self.handle_array_notation(statement[-1].strip())\n if self.inp1[0] == \"'\" and self.inp1[-1] == \"'\" and self.inp1[1] == \"\\\\\":\n self.inp1 = \"`\" + self.inp1[1] + self.inp1[2] + \"`\"\n self.add_to_symbol_table([self.inp1, self.array_index_i1])\n\n elif instr_type == \"input\":\n # 10, input, variable\n self.instr_type = \"scan_int\"\n self.out, self.array_index_o = self.handle_array_notation(statement[-1].strip())\n self.add_to_symbol_table([self.out, self.array_index_o])\n\n elif instr_type in [\"~\",\"!\",\"++\",\"--\"]:\n #10, ++, out, variable\n self.operation = instr_type\n self.instr_type = \"unary\"\n self.inp1, self.array_index_i1 = self.handle_array_notation(statement[-1].strip())\n self.out, self.array_index_o = self.handle_array_notation(statement[2].strip())\n self.add_to_symbol_table([\n self.inp1, self.array_index_i1,\n self.out, self.array_index_o\n ])\n elif instr_type == \"param\":\n self.instr_type = \"param\"\n self.inp1 = statement[-1].strip()\n\n elif instr_type == \"call\":\n # 10, call, label_name\n # OR\n # 10, call, label_name, optional_return, no.of params\n self.instr_type = \"func_call\"\n if len(statement) == 3:\n self.jmp_to_label = statement[-1].strip()\n else:\n self.jmp_to_label = statement[2].strip()\n self.out = statement[3].strip()\n self.inp1 = statement[-1].strip()\n self.add_to_symbol_table([self.out])\n\n elif instr_type == \"label\":\n # 10, label, label_name\n self.instr_type = \"label\"\n self.label_name = statement[-1].strip()\n\n elif instr_type == \"func\":\n self.instr_type = \"func\"\n self.label_name = statement[-1].strip()\n\n elif instr_type == \"begin\":\n self.instr_type = \"begin_scope\"\n self.label_name = statement[-1].strip()\n\n elif instr_type == \"arg\":\n self.instr_type = \"arg\"\n self.inp1 = statement[-1].strip()\n self.add_to_symbol_table([self.inp1])\n\n elif instr_type == \"end\":\n self.instr_type = \"end_scope\"\n self.label_name = statement[-1].strip()\n\n elif instr_type == \"ret\":\n self.instr_type = \"return\"\n if len(statement) == 3:\n self.inp1 = statement[-1].strip()\n\n elif instr_type == \"=\":\n # 10, =, a, 2\n self.instr_type = \"assignment\"\n self.operation = \"=\"\n self.inp1, self.array_index_i1 = self.handle_array_notation(statement[-1].strip())\n self.out, self.array_index_o = self.handle_array_notation(statement[2].strip())\n self.add_to_symbol_table([\n self.inp1, self.array_index_i1,\n self.out, self.array_index_o\n ])\n\n elif instr_type == \"decl_array\":\n self.instr_type = \"array_declaration\"\n self.inp1, self.array_index_i1 = self.handle_array_notation(statement[-1].strip())\n self.add_to_symbol_table([self.inp1, self.array_index_i1], True)\n\n elif instr_type in [\"|\", \"||\", \"&\", \"&&\", \"^\", \"~\", \"!\"]:\n # 10, &&, a, a, b\n self.instr_type = \"logical\"\n self.inp1, self.array_index_i1 = self.handle_array_notation(statement[3].strip())\n self.inp2, self.array_index_i2 = self.handle_array_notation(statement[4].strip())\n self.out, self.array_index_o = self.handle_array_notation(statement[2].strip())\n self.add_to_symbol_table([\n self.inp1, self.array_index_i1,\n self.inp2, self.array_index_i2,\n self.out, self.array_index_o\n ])\n self.operation = statement[1].strip()\n\n else:\n # 10, +, a, a, b\n self.instr_type = \"arithmetic\"\n self.inp1, self.array_index_i1 = self.handle_array_notation(statement[3].strip())\n self.inp2, self.array_index_i2 = self.handle_array_notation(statement[4].strip())\n self.out, self.array_index_o = self.handle_array_notation(statement[2].strip())\n self.add_to_symbol_table([\n self.inp1, self.array_index_i1,\n self.inp2, self.array_index_i2,\n self.out, self.array_index_o\n ])\n self.operation = statement[1].strip()\n\n\n def populate_per_inst_next_use(self):\n return\n '''\n for each symbol in instruction, initialize the next use\n and liveness parameters\n '''\n symbols = [\n self.inp1, self.array_index_i1,\n self.inp2, self.array_index_i2,\n self.out, self.array_index_o\n ]\n for symbol in symbols:\n if is_valid_sym(symbol):\n self.per_inst_next_use[symbol] = SymbolTableEntry()\n\n\ndef read_three_address_code(filename):\n '''\n Given a csv file `filename`, read the file\n and find the basic blocks. Also store each instruction\n as an instance of Instruction class in a list `IR_code`\n '''\n leader = set()\n leader.add(1)\n IR_code = []\n last_func = None\n arg_set = None\n with open(filename, 'r') as csvfile:\n instruction_set = list(csv.reader(csvfile, delimiter=','))\n index_label_to_be_added = set()\n for i,statement in enumerate(instruction_set):\n if len(statement) == 0:\n continue\n IR = Instruction(statement)\n IR_code.append(IR)\n line_no = IR.line_no\n instr_type = IR.instr_type\n\n if instr_type == \"begin_scope\":\n if instruction_set[i+1][1].strip() == \"func\":\n IR_code[i].instr_type = \"begin_func\"\n arg_set = []\n global func_symbol_table\n func_symbol_table = dict()\n last_func = {\n 'label' : statement[2],\n 'index' : i\n }\n\n if instr_type == \"arg\":\n arg_set.append(IR.inp1)\n\n if instr_type == \"end_scope\":\n if statement[2] == last_func['label']:\n IR_code[i].instr_type = \"end_func\"\n IR_code[last_func['index']].table = func_symbol_table\n IR_code[last_func['index']].arg_set = arg_set\n last_func = None\n func_symbol_table = None\n\n instr_type = IR_code[i].instr_type\n if instr_type in leader_instructions:\n if instr_type != \"label\" and instr_type != \"print_int\" and instr_type != \"scan_int\" and instr_type != \"func\":\n line_no += 1\n\n leader.add(line_no)\n\n if instr_type == \"ifgoto\" or instr_type == \"goto\":\n goto_line = statement[-1].strip()\n if goto_line.isdigit():\n goto_line = int(goto_line)\n leader.add(goto_line)\n index_label_to_be_added.add(goto_line - 1)\n # IR_code[goto_line - 1].label_to_be_added = True\n for index in index_label_to_be_added:\n IR_code[index].label_to_be_added = True\n leader.add(len(IR_code)+1)\n\n return (sorted(leader), IR_code)\n","sub_path":"Final_project/src/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":12648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"385184095","text":"from compute_projections import construct_update_projection_hdf5\nimport sys\n\ntry:\n\tnproc = int(sys.argv[1])\n\tprint('running with nproc='+str(nproc))\nexcept:\n\tprint('running in serial mode')\n\tnproc=1\n\nbasepath = '../../hose_runs/'\n\nfid_Rg15_V120 = 'fid-dispPoly-fg0.1-hose-Rg15.0-Rate1.0-Rh0.2-Vel120.0'\nfid_Rg15_V160 = 'fid-dispPoly-fg0.1-hose-Rg15.0-Rate1.0-Rh0.2-Vel160.0'\n\npair_list = [(fid_Rg15_V120, 'lvl4'),\n (fid_Rg15_V160, 'lvl4')]\n\nname_list = [ p[0] + '-' + p[1] for p in pair_list]\npath_list = [basepath + p[0] + '/' + p[1] for p in pair_list]\n \nfor name, path in zip(name_list, path_list):\n construct_update_projection_hdf5(name, path, nproc=nproc, output_dir='data-hose/')\n","sub_path":"plots/movie_5panel/run_projections-hose.py","file_name":"run_projections-hose.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"1071617","text":"# !/usr/bin/python3\n# -*- coding: utf-8 -*-\nimport socket\nimport time\nimport struct\nfrom pprint import pprint\n\n\nCACHE = {}\n\n\ndef get_ttl(b):\n \"\"\"Get ttl by b\"\"\"\n try:\n return b[6:10]\n except:\n return b\"\\x00\\x00\\x00\\x00\"\n\n\ndef parse_records(name, data, counts):\n \"\"\"Parse 'count' records in data\"\"\"\n records = []\n pointer = 0\n datas = data[2:].split(b\"\\xc0\\x0c\")\n for count in counts:\n rrs = []\n for i in range(count):\n try:\n rrs.append(RR(name, b\"\\xc0\\x0c\" + datas[pointer + i], time.time()))\n except IndexError:\n break\n records.append(rrs)\n pointer += count\n return records\n\n\ndef ask(data, addr):\n \"\"\"Ask 'addr' about 'data'\"\"\"\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n sock.settimeout(0.1)\n with sock:\n try:\n sock.sendto(data, addr)\n response = sock.recv(4096)\n return DNSPacket(response)\n except socket.error:\n return ask(data, ('8.8.8.8', 53))\n\n\nclass DNSPacket:\n \"\"\"DNSPacket class\"\"\"\n def __init__(self, data):\n self._bytes = data\n self.header = list(struct.unpack(\"!HHHHHH\", self._bytes[0:12]))\n self._qname = None\n self._qname = self.qname\n oth = data[12 + len(self.qname) + 5:]\n self.records = parse_records(self.qname, oth, self.header[3:])\n\n @property\n def id(self):\n return self.header[0]\n\n @id.setter\n def id(self, packet_id):\n self.header[0] = packet_id\n\n @property\n def qname(self):\n if not self._qname:\n ln = self._bytes[12:].find(b'\\x00')\n self.len_name = ln\n name = self._bytes[12:12 + ln]\n return struct.unpack(str(ln) + 's', name)[0]\n return self._qname\n\n def __bytes__(self):\n ln = len(self.qname)\n b_header = struct.pack(\"!HHHHHH\", *self.header)\n off = 13 + ln\n b_name = struct.pack(str(ln) + \"s\", self.qname) + b\"\\x00\"\n b_rrs = b\"\".join([bytes(r) for rrs in self.records for r in rrs])\n return b_header + b_name + self._bytes[off:off + 4] + b_rrs\n\n def set_ttl(self, ctime, cttl):\n for record in [r for rrs in self.records for r in rrs]:\n record.rttl = int(cttl - time.time() + ctime)\n\n\nclass RR:\n \"\"\"Resource record class\"\"\"\n def __init__(self, name, data, ctime):\n self.bytes = data\n self.rname = name\n self.ctime = ctime\n self.rttl = struct.unpack('!I', get_ttl(data))[0]\n\n def __bytes__(self):\n return self.bytes\n\n def up_ttl(self):\n self.rttl = int(self.rttl - time.time() + self.ctime)\n\n\nclass Server:\n \"\"\"Server class\"\"\"\n def __init__(self, f_addr, sock):\n self.forwarder = f_addr\n self.sock = sock\n\n def forward(self, data, key):\n pack = ask(data, self.forwarder)\n # now key - question name, value - records, not whole packet\n CACHE[key] = pack.records\n return bytes(pack)\n\n def request(self, data, client):\n pack = DNSPacket(data)\n key = pack.qname\n if key in CACHE:\n packet = self.pack_packet(key, data)\n self.sock.sendto(packet, client)\n else:\n print(\"Ask forwarder\")\n self.sock.sendto(self.forward(data, key), client)\n\n def pack_packet(self, key, data):\n pack = DNSPacket(data)\n cdata = CACHE[key]\n for recs in cdata:\n for r in recs:\n if not time.time() - r.ctime <= r.rttl:\n print(\"Ask forwarder (%s [too old])\" % bytes(r))\n return self.forward(data, key)\n else:\n r.up_ttl()\n print(\"From cache\")\n ind = 12 + data[12:].find(b\"\\x00\") + 5\n question = data[12:ind]\n counts = struct.pack(\"!HHHH\", 1, len(cdata[0]), len(cdata[1]), len(cdata[2]))\n recs = b\"\".join([bytes(r) for rrs in cdata for r in rrs])\n packet = data[:2] + b\"\\x81\\x80\" + counts + question + recs\n return packet\n\n","sub_path":"PythonProjects/dnscache/dnscache.py","file_name":"dnscache.py","file_ext":"py","file_size_in_byte":4073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"114092436","text":"import concurrent\nimport pyfiglet\nimport sys\nimport socket\nfrom datetime import datetime\nimport concurrent.futures\n\nascii_banner = pyfiglet.figlet_format(\"PORT SCANNER\")\nprint(ascii_banner)\n\n# Defining a target\nif len(sys.argv) == 2:\n\n # translate hostname to IPv4\n target = socket.gethostbyname(sys.argv[1])\nelse:\n print(\"Invalid ammount of Argument\")\n\n# Add Banner\nprint(\"-\" * 50)\nprint(\"Scanning Target: \" + target)\nprint(\"Scanning started at:\" + str(datetime.now()))\nprint(\"-\" * 50)\n\ndef multi_port(port):\n try:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n socket.setdefaulttimeout(1)\n\n # returns an error indicator\n result = s.connect_ex((target, port))\n if result == 0:\n print(\"Port {} is open\".format(port))\n s.close()\n\n except KeyboardInterrupt:\n print(\"\\n Exitting Program !!!!\")\n sys.exit()\n except socket.gaierror:\n print(\"\\n Hostname Could Not Be Resolved !!!!\")\n sys.exit()\n except socket.error:\n print(\"\\ Server not responding !!!!\")\n sys.exit()\n\nwith concurrent.futures.ThreadPoolExecutor() as executor:\n results = [executor.submit(multi_port, port) for port in range(1,65535)]\n","sub_path":"portscanner.py","file_name":"portscanner.py","file_ext":"py","file_size_in_byte":1227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"198610871","text":"#!/usr/bin/env python3\n\n\nclass Dog:\n\n kind = 'Animal' # class variable shared by all instances\n\n def __init__(self, name, age):\n self.name = name # instance variable unique to each instance\n self.age = age\n\n\nd1 = Dog('Fido', '5')\nprint(d1.name, d1.age, d1.kind)\n\nd2 = Dog('Pippi', '8')\nprint(d2.name, d2.age, d2.kind)\n","sub_path":"class01.py","file_name":"class01.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"513395806","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport random\nimport pandas as pd \n\n\nfrom pyrolysis_general.src.pyrolysis import PyrolysisParallel\n\n\n\nT = np.linspace(300,1400,101) \nT_0 = 300\ntau = 6.1\ntime0 = (T - T_0)/(tau/60)\n\ntest = PyrolysisParallel(temp_0=T_0, temp_end=T[-1], time = time0, beta=tau, n_points=101)\n\ntest.react_reader(filename=\"fake_scheme.json\")\ntest.param_reader(filename=\"fake_scheme.json\")\n\ntest.solve_system()\nplt.figure(1)\ntest.plot_solid_density()\n\nplt.figure(2)\nrho_solid = test.get_density()\ndrho_solid = test.get_drho_solid()\ntemperature = test.get_temperature()\n\nstd_y=0.00001\n\nnum_data = len(drho_solid)\nrn_data=np.zeros((1, num_data))\nfor i in range(0, num_data):\n rn_data[0,i]=random.gauss(0, std_y)\n drho_solid_pert = drho_solid + rn_data[0,:]\n\t\t\n\t\t\nplt.plot(temperature, drho_solid_pert, 'o')\n\nmyfile = {'time': time0, 'temperature': T, 'rho': rho_solid, 'dRho': drho_solid_pert, 'std_dRho': std_y} \ndf = pd.DataFrame(myfile, columns=['time', 'temperature', 'rho', 'dRho', 'std_dRho'])\n\n\ndf.to_csv(\"fakePyroData.csv\")\n\nplt.show()\n\t\n\n","sub_path":"pyrolysis_multiple/data/generateDataFile.py","file_name":"generateDataFile.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"259089179","text":"# USAGE\n# python video_template.py\n\n# import the necessary packages\nfrom __future__ import print_function\nfrom imutils.object_detection import non_max_suppression\nfrom imutils import paths\nimport numpy as np\nimport argparse\nimport imutils\nimport cv2\nfrom GUI_MySQL_class import MySQL\n\n\n# construct the argument parse and parse the arguments\nap = argparse.ArgumentParser()\nap.add_argument(\"-v\", \"--video\", help=\"path to the (optional) video file\")\nargs = vars(ap.parse_args())\n\n# if a video path was not supplied, grab the reference to the webcam\nif not args.get(\"video\", False):\n\tcamera = cv2.VideoCapture(0)\n\n# otherwise, grab a reference to the video file\nelse:\n\tcamera = cv2.VideoCapture(args[\"video\"])\n\n# initialize the HOG descriptor/person detector\nhog = cv2.HOGDescriptor()\nhog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())\n\nmysql = MySQL()\n\n# keep looping\nwhile True:\n\t# grab the current frame\n\t(grabbed, frame) = camera.read()\n\n\t# if we are viewing a video and we did not grab a\n\t# frame, then we have reached the end of the video\n\tif args.get(\"video\") and not grabbed:\n\t\tbreak\n\t\n\tframe = imutils.resize(frame, width=500)\n\t\n\t\n\n\t# detect people in the image\n\t(rects, weights) = hog.detectMultiScale(frame, winStride=(4, 4),\n padding=(8, 8), scale=1.05)\n\n # apply non-maxima suppression to the bounding boxes using a\n # fairly large overlap threshold to try to maintain overlapping\n # boxes that are still people\n\trects = np.array([[x, y, x + w, y + h] for (x, y, w, h) in rects])\n\tpick = non_max_suppression(rects, probs=None, overlapThresh=0.65)\n\n\tif (len(pick)!=0):\n\t\tmysql.insertdata(1)\n\n\telse:\n\t\tcontinue\n\t\t\n # draw the final bounding boxes\n\tfor (xA, yA, xB, yB) in pick:\n cv2.rectangle(frame, (xA, yA), (xB, yB), (155, 255, 0), 4)\n\n\n\tcv2.imshow(\"video\", frame)\n\tkey = cv2.waitKey(1) & 0xFF\n\n\t# if the 'q' key is pressed, stop the loop\n\tif key == ord(\"q\"):\n\t\tbreak\n\n# cleanup the camera and close any open windows\ncamera.release()\ncv2.destroyAllWindows()\n","sub_path":"video.py","file_name":"video.py","file_ext":"py","file_size_in_byte":2072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"143046141","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 27 17:48:19 2019\n\nThis is a modification of the class created by Raman Ganti\n\"\"\"\n\nimport os\nimport glob\nimport shutil\nimport sys\nsys.path.append(os.path.join(os.path.dirname(__file__), '../../../')) #This falls into Utilities path\nimport Lammps.core_functions as cf\n\n\ndef sec_to_pbs_time(seconds, nodays=False):\n \"\"\"\n clean solution from\n https://stackoverflow.com/questions/21323692/convert-seconds-to-weeks-days-hours-minutes-seconds-in-python\n \"The idea behind this is that the number of seconds in your answer is the remainder after dividing \n them in minutes; minutes are the remainder of dividing all minutes into hours etc... This version \n is better because you can easily adjust it to months, years, etc...\"\n \"\"\"\n minutes, seconds = divmod(seconds, 60)\n hours, minutes = divmod(minutes, 60)\n if nodays:\n return \"{0:02d}:{1:02d}:{2:02d}\".format(int(hours), int(minutes), int(seconds))\n else:\n days, hours = divmod(hours, 24)\n return \"{0:02d}:{1:02d}:{2:02d}:{3:02d}\".format(int(days), int(hours), int(minutes), int(seconds))\n \n \n \nclass simulation_launcher(object):\n def __init__(self, home, template, name, initial_conf=None):\n \"\"\"\n Attributes:\n home is where the folder for all the simulation is going to be created\n template points to the folder where the template is hosted\n name ex. DP_0020, the name of the folder that contains everything\n initial_conf is the initial configuration file if it is required\n has_qsub: True if the template has qsub file\n \"\"\"\n self.initial_conf = initial_conf\n self.home = home\n self.template = template\n self.name = name\n self.has_qsub = False\n\n def clean_template(self, keep_qsub = True):\n \"\"\"\n Clean the template files except for in* or optionally the qsub file\n \n Args:\n keep_qsub: if there is a qsub file in the template, it keeps it\n \"\"\"\n useful_files = glob.glob(self.template+'/in*')\n \n\n qsub_file = glob.glob(self.template+'/*.qsub')\n \n if qsub_file and keep_qsub == True:\n self.qsub_file = os.path.basename(qsub_file[0])\n self.has_qsub = True\n useful_files.extend(glob.glob(self.template+'/*.qsub'))\n \n all_files = glob.glob(self.template+'/*')\n \n remove_files = [f for f in all_files if f not in useful_files]\n \n for fil in remove_files:\n os.remove(fil)\n \n \n def create_folder(self, keep_qsub = True):\n \"\"\"\n Copies the template and adds the input configuration to the folder\n \"\"\"\n \n #Deletes innecesary files and folders in template\n self.clean_template(keep_qsub)\n \n #Copy the template\n self.folder = self.home+'/%s'%self.name\n\n #Copy the template folder\n shutil.copytree(self.template,self.folder)\n \n #Copy the initial configuration\n if self.initial_conf != None:\n shutil.copy(self.initial_conf, self.folder)\n\n \n def create_qsub(self,queue_type, nodes, cores, wall_time, lammps_script,lammps_version='/home/sr802/Programs/lammps-12Dec18/src/lmp_dexter'):\n \n self.qsub = BuildPBSScript(queue_type,nodes,cores,wall_time,\"input.lmp\")\n self.qsub.writePBSscript(self.folder+'/run.qsub',self.name)\n \n \n def run_simulation(self):\n print(\"running the file\")\n os.chdir(self.folder)\n cf.bash_command(\"\"\"qsub run.qsub\"\"\")\n return 0\n\n\n\n \nclass BuildPBSScript(object):\n \"\"\"\n This is a completely general class, it does not and should not know anything about the naming conventions\n and structures of any particular library. If any such knowledge is necessary please make a derived class\n and overload the member functions \n *queue_type [string]\n *nodes [int]\n *core [int] processors per node\n *walltime [hours]\n *command [string]: command line to execute e.g. python parallel_tempering.py args\n *outdir is the directory where to redirect the standard output\n \"\"\"\n\n\n def __init__(self, queue_type, nodes, cores, wall_time, lammps_input, output_dir=None, no_days=False, spatial=False,\n out_dir=None,lmp_version='/home/sr802/Programs/mylammps/src/lmp_mpi'):\n self.qtype = queue_type\n self.nodes = nodes\n self.cores = cores\n self.s_wtime = wall_time * 60 * 60 # convert hours to seconds\n self.dhms_wtime = sec_to_pbs_time(self.s_wtime, nodays=no_days) # DD:HH:MM:SS time\n self.lammps_input = lammps_input\n self.pbs_ready = False\n if out_dir and not os.path.isabs(out_dir):\n out_dir = os.path.abspath(out_dir)\n self.out_dir = out_dir\n self.current_dir = os.getcwd()\n self.output_dir = output_dir\n self.lammps_input=lammps_input\n self.lmp_version=lmp_version\n\n\n def writePBSscript(self, fname, job_name, spatial=False):\n \"\"\"\n *fname [string]: name of the pbs bash script where to write\n *job_name [string]: name of the pbs job\n \"\"\"\n print(\"writing PBS file with %s nodes in %s cores and walltime %s\"%(self.nodes, self.cores, self.dhms_wtime))\n# if \".sh\" not in fname:\n# fname += \".sh\"\n f = open(fname, 'w')\n f.write('#PBS -N {0} \\n'.format(job_name))\n f.write('#PBS -q {0} \\n'.format(self.qtype))\n f.write('#PBS -l nodes={0}:ppn={1} \\n'.format(self.nodes, self.cores))\n f.write('#PBS -l walltime={0} \\n'.format(self.dhms_wtime))\n f.write('#PBS -o output.pbs \\n') # this directive places all the outputs in that file\n f.write('#PBS -e error.pbs \\n') # this directive places all the outputs in that file\n f.write('cd $PBS_O_WORKDIR')\n if self.out_dir!=None:\n f.write('#PBS -o {0} \\n'.format(self.out_dir))\n f.write('\\n')\n f.write('cd {0}\\n'.format(self.output_dir))\n f.write('\\n')\n f.write('echo Starting job $PBS_JOBID \\n')\n f.write('echo\\n')\n f.write('echo PBS assigned me this node: \\n')\n f.write('cat $PBS_NODEFILE \\n')\n f.write('echo \\n')\n f.write('echo \\\"Running ${job_name}\\\" \\n')\n f.write('echo \\n')\n # f.write('mkdir {0}\\n'.format(self.output_dir))\n # f.write('cp {0} {1}\\n'.format(self.lammps_script, self.output_dir))\n # f.write('cd {0}\\n'.format(self.output_dir))\n # f.write('cp {0} {1} \\n'.format(self.lammps_script, self.output_dir))\n \n f.write('mpirun -np {0} {1} -in {2}\\n'.format(self.nodes * self.cores,self.lmp_version,\n self.lammps_input))\n\n f.write('echo \\n')\n f.write('echo \\\"Job finished. PBS details are:\\\" \\n')\n f.write('echo \\n')\n f.write('qstat -f ${PBS_JOBID} \\n')\n f.write('echo \\n')\n f.write('echo Finished at \\`date\\` \\n')\n f.close()\n self.pbs_ready = True\n\n\n","sub_path":"Lammps/simulation_utilities.py","file_name":"simulation_utilities.py","file_ext":"py","file_size_in_byte":7179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"19952982","text":"import collections\n\n\nclass Solution:\n def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:\n d1 = collections.Counter(nums1)\n d2 = collections.Counter(nums2)\n res = []\n for item in d1:\n if item in d2:\n res += [item] * min(d1[item], d2[item])\n return res\n","sub_path":"map/350_Intersection_of_Two_Arrays_II.py","file_name":"350_Intersection_of_Two_Arrays_II.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"206897125","text":"from pf import app\n#from .hello_world import app\nfrom flask import request, make_response, jsonify, Response, redirect\nfrom datetime import datetime\nfrom pf import dbfunc as db\nfrom pf import jwtdecodenoverify as jwtnoverify\nfrom dateutil import tz\nfrom datetime import datetime\nfrom datetime import date\nfrom multiprocessing import Process\n\nimport psycopg2\nimport json\nimport jwt\nimport time\n\n@app.route('/funddatafetch',methods=['GET','POST','OPTIONS'])\ndef funddatafetch():\n#This is called by fund data fetch service\n if request.method=='OPTIONS':\n print(\"inside FUNDDATAFETCH options\")\n return make_response(jsonify('inside FUNDDATAFETCH options'), 200) \n\n elif request.method=='POST':\n print(\"inside PFDATAFETCH GET\")\n \n print((request)) \n print(request.headers)\n userid,entityid=jwtnoverify.validatetoken(request)\n print(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))\n print(userid,entityid)\n payload= request.get_json()\n print(payload)\n print('after')\n con,cur=db.mydbopncon()\n\n print(con)\n print(cur)\n teee='%'+payload+'%'\n #cur.execute(\"select row_to_json(art) from (select a.*, (select json_agg(b) from (select * from pfstklist where pfportfolioid = a.pfportfolioid ) as b) as pfstklist, (select json_agg(c) from (select * from pfmflist where pfportfolioid = a.pfportfolioid ) as c) as pfmflist from pfmaindetail as a where pfuserid =%s ) art\",(userid,))\n #command = cur.mogrify(\"select row_to_json(art) from (select a.*,(select json_agg(c) from (select * from webapp.fundsipdt where sipfndnatcode = a.fndnatcode ) as c) as fnsipdt from webapp.fundmaster as a where fnddisplayname like %s) art\",(teee,))\n command = cur.mogrify(\"select row_to_json(art) from (select a.fndnatcode,a.fndschcdfrmbse,a.fnddisplayname,a.fndminpuramt,a.fndaddpuramt,a.fndmaxpuramt,a.fndpuramtinmulti,a.fndpurcutoff,a.fndamcnatcode, (select json_agg(c) from (select sipfreq,sipfreqdates,sipminamt,sipmaxamt,sipmulamt,sipmininstal,sipmaxinstal,sipmingap from webapp.fundsipdt where sipfndnatcode = a.fndnatcode ) as c) as fnsipdt from webapp.fundmaster as a where UPPER(fnddisplayname) like (%s)) art\",(teee,))\n cur, dbqerr = db.mydbfunc(con,cur,command)\n print(command)\n print(cur)\n print(dbqerr)\n print(type(dbqerr))\n print(dbqerr['natstatus'])\n\n if cur.closed == True:\n if(dbqerr['natstatus'] == \"error\" or dbqerr['natstatus'] == \"warning\"):\n dbqerr['statusdetails']=\"pf Fetch failed\"\n resp = make_response(jsonify(dbqerr), 400)\n return(resp)\n\n\n #Model to follow in all fetch\n records=[]\n for record in cur: \n records.append(record[0]) \n print(records)\n print(\"Fund details returned for user: \"+userid)\n\n for record in records:\n print(\"--------------\")\n print(record)\n print(\"--------------\")\n if record.get('fnsipdt') != None:\n for sipdt in record.get('fnsipdt'):\n print(sipdt)\n mydate=int(datetime.now().strftime('%d'))+10\n mymnt=int(datetime.now().strftime('%m'))\n mynxtmnt=int(datetime.now().strftime('%m'))+1\n myyr=datetime.now().strftime('%Y')\n sipdates=sipdt.get('sipfreqdates').split(',')\n print(sipdt['sipfreqdates'])\n sipdt['sipfreqdates']=[]\n for sipdate in sipdates:\n print(type(sipdate))\n print(type(mydate))\n if(int(sipdate)>mydate):\n now = (datetime.strptime((str(sipdate)+'/'+str(mymnt)+'/'+str(myyr)), '%d/%m/%Y').date()).strftime('%d-%b-%Y') \n \n print(now)\n print(type(now))\n \n #sipdt['sipfreqdates'].append(str(sipdate)+'/'+str(mymnt)+'/'+str(myyr))\n sipdt['sipfreqdates'].append(now)\n \n else:\n #sipdt['sipfreqdates'].append(str(sipdate)+'/'+str(mynxtmnt)+'/'+str(myyr))\n #now = datetime.strptime((str(sipdate)+'/'+str(mynxtmnt)+'/'+str(myyr)), '%d/%m/%Y').date()\n now1=(datetime.strptime((str(sipdate)+'/'+str(mynxtmnt)+'/'+str(myyr)), '%d/%m/%Y').date()).strftime('%d-%b-%Y')\n print(now1) \n print(type(now1))\n sipdt['sipfreqdates'].append(now1)\n\n\n print(sipdt['sipfreqdates'])\n \n \n\n\n \n resp = json.dumps(records)\n \n return resp\n","sub_path":"pf/fund.py","file_name":"fund.py","file_ext":"py","file_size_in_byte":4961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"447416467","text":"#Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution(object):\n def mergeKLists(self, lists):\n \"\"\"\n :type lists: List[ListNode]\n :rtype: ListNode\n \"\"\"\n head = ptemp = None\n lists = filter(lambda x: x, lists)\n if not lists:\n return\n self.buildheap(lists)\n while 1:\n if len(lists) == 1:\n if ptemp == None:\n head = ptemp = lists[0]\n else:\n ptemp.next = lists[0]\n return head\n else:\n tmp = lists[0]\n lists[0] = lists[0].next or lists.pop()\n self.heapfy(lists, 0)\n\n if ptemp == None:\n head = ptemp = tmp\n else:\n ptemp.next = tmp\n ptemp = tmp\n\n return head\n\n def buildheap(self, lists):\n nums = len(lists)\n for i in range(nums/2-1, -1, -1):\n self.heapfy(lists, i)\n\n def heapfy(self, lists, n):\n left, right, num = 2*n+1, 2*n+2, len(lists)\n if left < num and lists[left].val < lists[n].val:\n minval = left\n else:\n minval = n\n \n if right < num and lists[right].val < lists[minval].val:\n minval = right\n \n if minval != n:\n lists[n], lists[minval] = lists[minval], lists[n]\n self.heapfy(lists, minval)\n","sub_path":"023_Merge_k_Sorted_Lists/merge_k_sorted_lists.py","file_name":"merge_k_sorted_lists.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"374567501","text":"import string\nfrom psycopg2.errors import ForeignKeyViolation, UniqueViolation\nfrom sqlalchemy.exc import DBAPIError, IntegrityError\nfrom sqlalchemy.schema import UniqueConstraint\n\nfrom stronk.constants import DATABASE_ERROR_MSG, USER_NOT_FOUND_MSG, PROGRAM_NOT_FOUND_MSG, WORKOUT_NOT_FOUND_MSG\n\nfrom stronk import db\nfrom stronk.errors.bad_attributes import BadAttributes\nfrom stronk.errors.conflict import Conflict\nfrom stronk.errors.not_found import NotFound\nfrom stronk.errors.unexpected_error import UnexpectedError\nfrom stronk.models.user import User\n\n\nclass Program(db.Model):\n __table_args__ = (UniqueConstraint('author', 'name',\n name='unique_program_names_for_author'),)\n id = db.Column(db.Integer, primary_key=True)\n author = db.Column(db.String(),\n db.ForeignKey(f'{User.__tablename__}.id'),\n index=True,\n nullable=False)\n name = db.Column(db.String(128), index=True, nullable=False, unique=False)\n # id of the parent program; none if this is completely original\n parent_id = db.Column(db.Integer)\n duration = db.Column(db.Integer, nullable=False)\n description = db.Column(db.String(256), nullable=False)\n\n @staticmethod\n def create(author, name, duration, description):\n program = Program(author=author,\n name=string.capwords(name),\n duration=duration,\n description=description)\n\n try:\n db.session.add(program)\n db.session.commit()\n\n return program\n except IntegrityError as err:\n if isinstance(err.orig, UniqueViolation):\n raise Conflict(\"Name already used by another program\")\n elif isinstance(err.orig, ForeignKeyViolation):\n raise BadAttributes(USER_NOT_FOUND_MSG)\n else:\n raise UnexpectedError(DATABASE_ERROR_MSG)\n except DBAPIError as err:\n raise UnexpectedError(DATABASE_ERROR_MSG)\n \n @staticmethod\n def find_by_author(author):\n return Program.query.filter_by(author=author).all()\n\n @staticmethod\n def try_find_by_id(id: int):\n return Program.query.filter_by(id=id).first()\n\n @staticmethod\n def find_by_id(id: int):\n program = Program.try_find_by_id(id)\n if not program:\n raise NotFound(PROGRAM_NOT_FOUND_MSG)\n return program\n\n def to_dict(self):\n \"\"\"Returns a dictionary representing the attributes of the program.\n Key is the name of the attribute and value is the value of the\n attribute. \"\"\"\n return {\n \"id\": self.id,\n \"author\": self.get_author(),\n \"name\": self.name,\n \"duration\": self.duration,\n \"description\": self.description\n }\n\n def get_author(self):\n \"\"\"Returns the User object for the author of the program.\"\"\"\n return User.query.filter_by(id=self.author).first().to_dict()\n\n def update(self, attrs):\n \"\"\"Updates model given attrs.\n\n Params:\n attrs: Dictionary containing attributes to update. Key is the \n attribute name and value is the new value.\n \"\"\"\n if attrs.get('author'):\n self.author = attrs.get('author')\n if attrs.get('name'):\n self.name = string.capwords(attrs.get('name'))\n if attrs.get('duration'):\n self.duration = attrs.get('duration')\n if attrs.get('description'):\n self.description = attrs.get('description')\n\n try:\n db.session.add(self)\n db.session.commit()\n except IntegrityError as err:\n if isinstance(err.orig, ForeignKeyViolation):\n raise BadAttributes(\"Author does not exist.\")\n elif isinstance(err.orig, UniqueViolation):\n raise Conflict(\"Program with name already exists.\")\n except DBAPIError as err:\n raise UnexpectedError(DATABASE_ERROR_MSG)\n\n def delete(self):\n try:\n db.session.delete(self)\n db.session.commit()\n except DBAPIError as err:\n raise UnexpectedError(DATABASE_ERROR_MSG)\n\n def clone(self, user_id: int):\n new_program = Program.create(\n author=user_id,\n name=self.name,\n duration=self.duration,\n description=self.description\n )\n\n new_program.parent_id = self.id\n return new_program\n","sub_path":"stronk/models/program.py","file_name":"program.py","file_ext":"py","file_size_in_byte":4551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"50844105","text":"# -*- coding: utf-8 -*-\n# __author__ = 'XingHuan'\n# 6/20/2018\n\n# Copyright 2018 XingHuan\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\nimport os\nimport sys\nfrom sins.module.sqt import *\nfrom sins.ui.widgets.label import ThumbnailLabel\nfrom sins.ui.main.template.detail import DetailWidget\nfrom sins.config.data_view_configs import VersionConfig\n\nTHUMBNAIL_SIZE = [80, 45]\n\n\nclass VersionItemWidget(QWidget):\n def __init__(self,\n version=None,\n show_info_label=True,\n view_fields=['name', 'status', 'submit_type'],\n *args, **kwargs):\n super(VersionItemWidget, self).__init__(*args, **kwargs)\n\n self.version = version\n self.show_info_label = show_info_label\n self.view_fields = view_fields\n self.is_current_version = False\n\n self.init_ui()\n\n self.setCursor(Qt.PointingHandCursor)\n\n def init_ui(self):\n self.backLabel = QLabel(self)\n\n self.thumbnailLabel = ThumbnailLabel(parent=self,\n dynamic=True,\n background='rgb(20, 35, 40)')\n self.thumbnailLabel.setFixedSize(THUMBNAIL_SIZE[0], THUMBNAIL_SIZE[1])\n # self.thumbnailLabel.setStyleSheet('background:gray')\n self.thumbnailLayout = QVBoxLayout()\n self.thumbnailLayout.addWidget(self.thumbnailLabel)\n self.thumbnailLayout.addStretch()\n\n self.infoWidget = DetailWidget(label_text_color='rgb(200, 200, 200, 200)',\n show_info_label=self.show_info_label)\n self.infoWidget.masterLayout.setContentsMargins(0, 0, 0, 0)\n # self.infoWidget.masterLayout.setSpacing(0)\n self.infoWidget.load_config(VersionConfig())\n self.infoWidget.set_view_fields(self.view_fields)\n self.infoWidget.init_ui()\n\n self.masterLayout = QHBoxLayout()\n self.masterLayout.setContentsMargins(10, 10, 5, 5)\n self.masterLayout.setAlignment(Qt.AlignTop)\n self.masterLayout.addLayout(self.thumbnailLayout)\n self.masterLayout.addWidget(self.infoWidget)\n self.setLayout(self.masterLayout)\n\n self.setSizePolicy(QSizePolicy(QSizePolicy.Minimum,\n QSizePolicy.Maximum))\n\n def set_version(self, version):\n self.version = version\n\n def add_view_fields(self, names):\n for name in names:\n self.infoWidget.add_view_field(name)\n\n self.resize_rows()\n\n def update_data(self):\n if self.version is not None:\n self.infoWidget.set_instance(self.version)\n self.infoWidget.update_data()\n uploaded_movie = self.version.uploaded_movie\n if uploaded_movie is not None:\n if os.path.exists(uploaded_movie.host_path):\n self.thumbnailLabel.create_preview(uploaded_movie.host_path)\n\n self.resize_rows()\n\n def resize_rows(self):\n min_h = 0\n for i, cell_widget in enumerate(self.infoWidget.edit_widgets):\n # print cell_widget.sizeHint().height(), cell_widget.height()\n min_h += cell_widget.height() + self.infoWidget.masterLayout.spacing()\n min_h += self.masterLayout.contentsMargins().top() + self.masterLayout.contentsMargins().bottom()\n\n # print min_h\n # self.setMinimumHeight(min_h)\n self.setFixedHeight(min_h)\n\n def set_background(self):\n if self.is_current_version:\n self.backLabel.setStyleSheet('background:rgb(160, 160, 160, 50)')\n else:\n self.backLabel.setStyleSheet('background:transparent')\n\n def resizeEvent(self, event):\n super(VersionItemWidget, self).resizeEvent(event)\n self.backLabel.setFixedSize(self.size())\n\n\nclass VersionTreeItem(QTreeWidgetItem):\n def __init__(self, version=None, tree=None, *args, **kwargs):\n super(VersionTreeItem, self).__init__(*args, **kwargs)\n\n self.version = version\n self.tree = tree\n\n def set_current(self, is_current=True):\n # print 'set current'\n version_item_widget = self.tree.itemWidget(self, 0)\n version_item_widget.is_current_version = is_current\n version_item_widget.set_background()\n\n\n\nif __name__ == '__main__':\n from sins.db.models import Version\n app = QApplication(sys.argv)\n window = VersionItemWidget(Version.get(id=12724))\n window.show()\n window.update_data()\n window.adjustSize()\n sys.exit(app.exec_())\n","sub_path":"sins/ui/widgets/version_player/version_item.py","file_name":"version_item.py","file_ext":"py","file_size_in_byte":5001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"52352005","text":"import bpy\n\nselected_objects = bpy.context.selected_objects\n\nfor item in selected_objects:\n bpy.ops.object.select_all(action='DESELECT')\n \n bpy.context.view_layer.objects.active = item\n item.select_set(True)\n \n bpy.ops.object.modifier_add(type='SUBSURF')\n bpy.context.object.modifiers[\"Subdivision\"].levels = 2\n","sub_path":"faq/add_modifier_on_selection.py","file_name":"add_modifier_on_selection.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"283735312","text":"import discord\nfrom helpers import get_gif\nimport random\n\ncommands = [\"schiff\", \"couple\"]\nrequires_mention = True\naccepts_mention = True\ndescription = \"Menschen ~~verschiffen~~ shippen\"\n\n\nasync def execute(message: discord.Message):\n if len(message.mentions) != 2:\n await message.channel.send(\"Wen denn? o.O\\n(Bitte gib zwei gültige Nutzer an)\")\n return\n\n name_a = message.guild.get_member(message.mentions[0].id).display_name\n name_b = message.guild.get_member(message.mentions[1].id).display_name\n\n ship_name = name_a[:int(len(name_a) / 2)] + name_b[int(len(name_b) / 2):]\n random.seed(message.mentions[0].id+message.mentions[1].id)\n love_calc = random.randint(0, 100)\n\n e = discord.Embed()\n e.title = ':heart: Lovely Shipping! :heart:'\n e.description = f\"Shipping Name: **{ship_name}**\\n\" \\\n f\"Liebe zwischen {name_a} & {name_b}: **{love_calc}%**\"\n\n await message.channel.send(embed=e)\n","sub_path":"actions/ship.py","file_name":"ship.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"291576876","text":"# Import the necessary packages\nfrom __future__ import print_function\nimport datetime\nimport cv2\nimport numpy as np\nimport tensorflow as tf\nfrom object_detection.utils import label_map_util\nfrom object_detection.utils import visualization_utils as viz_utils\nimport warnings\n\nwarnings.filterwarnings('ignore') # Suppressing Matplotlib warnings\n\nprint(\"[INFO] starting cameras...\")\nwebcam1 = cv2.VideoCapture(0)\nwebcam1.set(3,120)\nwebcam1.set(4,160)\nwebcam2 = cv2.VideoCapture(2)\nwebcam2.set(3,120)\nwebcam2.set(4,160)\n\nprint(\"[INFO] Loading Detection Model...\")\nCLASSES = [\"Barrel\", \"Bicycle\", \"Bus\", \"Car\", \"Chair\", \"Dog\", \"Fire hydrant\", \"Horse\", \"Palm tree\", \"Person\", \"Sculpture\", \"Street light\", \"Table\", \"Traffic light\", \"Traffic sign\", \"Tree\", \"Pozo\", \"Baliza\", \"Cono\"]\n\nPATH_TO_LABELS = \"../models/final_model/label_map.pbtxt\"\nPATH_TO_SAVED_MODEL = \"../models/final_model/saved_model\"\n\nnet = tf.saved_model.load(PATH_TO_SAVED_MODEL)\n\ncategory_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS, use_display_name=True)\n\ndef detect_objects(images, net):\n final_result = []\n image_np_with_detections = np.array(images[1]).copy()\n \n for image in images:\n result = []\n image_np = np.array(image)\n input_tensor = tf.convert_to_tensor(image_np)\n input_tensor = input_tensor[tf.newaxis, ...]\n detections = net(input_tensor)\n\n num_detections = int(detections.pop('num_detections'))\n detections = {key: value[0, :num_detections].numpy() for key, value in detections.items()}\n detections['num_detections'] = num_detections\n\n # Detection_classes should be ints.\n detections['detection_classes'] = detections['detection_classes'].astype(np.int64)\n\n filtered_detections={'detection_anchor_indices': [], 'detection_scores': [],\n 'detection_boxes': [],\n 'detection_classes': [], 'raw_detection_boxes': [],\n 'detection_multiclass_scores': [],\n 'raw_detection_scores': [], 'num_detections': 0}\n\n for i in np.arange(0, detections['num_detections']):\n if detections['detection_scores'][i] > 0.40:\n filtered_detections['detection_anchor_indices'].append(detections['detection_anchor_indices'][i])\n filtered_detections['detection_scores'].append(detections['detection_scores'][i])\n filtered_detections['detection_boxes'].append(detections['detection_boxes'][i].tolist())\n filtered_detections['detection_classes'].append(detections['detection_classes'][i])\n filtered_detections['raw_detection_boxes'].append(detections['raw_detection_boxes'][i].tolist())\n filtered_detections['detection_multiclass_scores'].append(detections['detection_multiclass_scores'][i].tolist())\n filtered_detections['raw_detection_scores'].append(detections['raw_detection_scores'][i].tolist())\n filtered_detections['num_detections'] = filtered_detections['num_detections'] + 1\n\n result.append({\"class\": CLASSES[detections['detection_classes'][i]-1],\n \"confidence\": detections['detection_scores'][i]*100,\n \"coordinates\": detections['detection_boxes'][i]})\n final_result.append(result)\n\n viz_utils.visualize_boxes_and_labels_on_image_array(\n image_np_with_detections,\n np.array(filtered_detections['detection_boxes']),\n filtered_detections['detection_classes'],\n filtered_detections['detection_scores'],\n category_index,\n use_normalized_coordinates=True,\n max_boxes_to_draw=20,\n min_score_thresh=.40,\n agnostic_mode=False)\n\n print(final_result)\n\n return final_result, image_np_with_detections\n\nprint(\"[INFO] Beggining...\")\nwhile True:\n # Initialize the list of frames that have been processed\n frames = []\n cams = [webcam1, webcam2]\n rotations = [cv2.ROTATE_90_COUNTERCLOCKWISE, cv2.ROTATE_90_CLOCKWISE]\n \n # Loop over the frames and their respective motion detectors\n for index in [0,1]:\n rval, frame = cams[index].read()\n\n frames.append(cv2.rotate(frame,rotations[index]))\n\n res, frame = detect_objects([frames[0],frames[1]], net)\n \n timestamp = datetime.datetime.now()\n ts = timestamp.strftime(\"%A %d %B %Y %I:%M:%S%p\")\n\n cv2.putText(frame, ts, (10, frame.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1)\n cv2.imshow(\"Cam\", frame)\n key = cv2.waitKey(1) & 0xFF\n\n # If the `q` key was pressed, break from the loop\n if key == ord(\"q\"):\n break\n\n# Do a bit of cleanup\nprint(\"[INFO] cleaning up...\")\ncv2.destroyAllWindows()\n","sub_path":"testing/Detection/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"598957864","text":"import Planchette\nimport Empilement\n\ndef cree():\n\t\"\"\"\n\tCréé une liste d'empilement, qui correspond à une Pile\n\t\"\"\"\n\treturn []\n\ndef estVide(pile):\n\tif len(pile) == 0:\n\t\treturn True\n\telse:\n\t\treturn False\n\ndef sommet(pile):\n\tif estVide(pile) == True :\n\t\treturn None\n\telse:\n\t\treturn pile[-1]\n\ndef empile(pile, planchette, decalage):\n\tif estVide(pile) == True :\n\t\tpile.append(Empilement.cree(planchette, decalage))\n\telse:\n\t\tpile.append(Empilement.cree(planchette, decalage+Empilement.centreGeometrique(sommet(pile))))\n\ndef versChaine(pile):\n\tstring = '---------------------\\n'\n\tfor empilement in pile :\n\t\tstring += str(Empilement.versChaine(empilement))+'\\n'\n\tstring += '^^^^^^^^^^^^^^^^^^^^'\n\treturn string\n\ndef empileEtCalcule(pile, planchette, decalage):\n\tempile(pile, planchette, decalage)\n\tcalculeCentresGravite(pile)\n\tcalculeEquilibre(pile)\n\ndef calculeCentresGravite(pile):\n\tfor i in range(len(pile)-1, 0, -1) :\n\t\tmasse_dessus = pile[i][2]['masse']\n\t\tlongueur = pile[i-1][0][0]\n\t\tcentre = pile[i-1][1]\n\t\tcentreG_dessus = pile[i][2]['centreGravite']\n\n\t\tmasse = longueur + masse_dessus\n\t\tcentreG = (longueur*centre+masse_dessus*centreG_dessus)/masse\n\n\t\tpile[i-1][2]['masse'] = masse\n\t\tpile[i-1][2]['centreGravite'] = centreG\n\ndef calculeEquilibre(pile):\n\tfor i in range(len(pile)-1, 0, -1) :\n\t\tif abs(pile[i][2]['centreGravite']-pile[i-1][1]) > pile[i-1][0][0]/2 :\n\t\t\tpile[i][2]['desequilibre'] = True\n","sub_path":"Pile.py","file_name":"Pile.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"403662454","text":"from flask import Flask,request, url_for, redirect, render_template\nimport pickle\nimport pandas as pd\napp = Flask(__name__)\n\n#loading the Random Forest model\nmodel = pickle.load(open(\"fetal_classification_trained_model.pickle\", \"rb\"))\n\n#Index.html will be returned for the input\n@app.route('/')\ndef hello_world():\n return render_template(\"index.html\")\n\n# predict function, POST method to take in inputs\n@app.route('/predict', methods = ['POST','GET'])\ndef predict(): # take inputs for all the attributes through the HTML form\n FHR_base_value = request.form['1']\n accelerations = request.form['2']\n fetal_movement = request.form['3']\n uterine_contractions = request.form['4']\n light_decelerations = request.form['5']\n severe_decelerations = request.form['6']\n prolongued_decelerations = request.form['7']\n time_STV = request.form['8']\n val_STV = request.form['9']\n time_LTV = request.form['10']\n val_LTV = request.form['11']\n\n #form a dataframe with the inputs\n test_df = pd.DataFrame([pd.Series([FHR_base_value,accelerations,fetal_movement,uterine_contractions,\n light_decelerations,severe_decelerations,prolongued_decelerations,\n time_STV,val_STV,time_LTV,val_LTV ]) ])\n print(test_df)\n\n # predict the class of the fetal health\n prediction = model.predict(test_df)[0]\n if prediction==1.0:\n return render_template('result.html', pred = 'The fetal health is quite normal.'\n '\\nNothing to be worried about :)')\n elif prediction==2.0:\n return render_template('result.html', pred='The fetal health seems a bit suspicious.'\n '\\nBest would be to supervise it now.')\n else:\n return render_template('result.html', pred='The fetal health is Pathological.\\nNeeds Urgent attention!!!')\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"315325214","text":"import logging\nfrom django.conf import settings\nfrom sendcloud import APIBaseClass\n\nfrom .conf import (\n member_list,\n member_update,\n member_get,\n member_add,\n member_delete,\n)\n\nlogger = logging.getLogger('sendcloud')\n\n\nclass SendCloudAddressList(APIBaseClass):\n def __init__(self, fail_silently=False, *args, **kwargs):\n mail_list_addr, member_addr = (kwargs.pop('mail_list_addr', None),\n kwargs.pop('member_addr', None))\n try:\n self._mail_list_addr = mail_list_addr or getattr(settings,\n 'MAIL_LIST')\n except AttributeError:\n if fail_silently:\n self._mail_list_addr = None\n else:\n raise\n\n self._member_addr = member_addr\n self.fail_silently = fail_silently\n # self.add_member_url = 'http://sendcloud.sohu.com/webapi/list_member.add.json'\n # self.update_member_url = 'http://sendcloud.sohu.com/webapi/list_member.update.json'\n # self.delete_member_url = 'http://sendcloud.sohu.com/webapi/list_member.delete.json'\n # self.get_member_url = 'http://sendcloud.sohu.com/webapi/list_member.get.json'\n # self.get_list_url = 'http://sendcloud.sohu.com/webapi/list.get.json'\n self.create_list_url = 'http://sendcloud.sohu.com/webapi/list.create.json'\n\n self.get_list_url = member_list()\n self.add_member_url = member_add()\n self.update_member_url = member_update()\n self.delete_member_url = member_delete()\n self.get_member_url = member_get()\n\n super(SendCloudAddressList, self).__init__(*args, **kwargs)\n\n @property\n def mail_list_addr(self):\n return self._mail_list_addr\n\n @property\n def member_addr(self):\n return self._member_addr\n\n def create_list(self, list_name):\n data = {\n 'api_user': self.api_user,\n 'api_key': self.api_key,\n 'mail_list_addr': list_name,\n 'member_addr': self.member_addr,\n }\n return self.post_api(self.create_list_url, data)\n\n def get_list(self, start=0, limit=100):\n data = {\n 'apiUser': self.api_user,\n 'apiKey': self.api_key,\n 'address': self.mail_list_addr,\n 'start': start,\n 'limit': limit,\n }\n res = self.post_api(self.get_list_url, data)\n logger.info(res)\n return res['info']\n\n def get_or_create(self, name):\n member = self.get()\n if member:\n return member\n return self.add_member(name)\n\n def get(self):\n data = {\n 'apiUser': self.api_user,\n 'apiKey': self.api_key,\n 'address': self.mail_list_addr,\n 'members': self.member_addr,\n }\n res = self.post_api(self.get_member_url, data)\n logger.info(res)\n return res\n\n def add_member(self, names=None, vars={}):\n data = {\n 'apiUser': self.api_user,\n 'apiKey': self.api_key,\n 'address': self.mail_list_addr,\n 'members': self.member_addr,\n # 'vars': vars,\n }\n if names:\n data.update({\n \"names\": names\n })\n return self.post_api(self.add_member_url, data)\n\n def update_member(self, name='', member_addr='', mai_list_addr='', vars=''):\n data = {\n 'apiUser': self.api_user,\n 'apiKey': self.api_key,\n 'address': mai_list_addr or self.mail_list_addr,\n 'members': member_addr or self.member_addr,\n }\n if name:\n data['names'] = name\n # if member_addr:\n # data['member_addr'] = member_addr\n if vars:\n data[vars] = vars\n return self.post_api(self.update_member_url, data)\n\n def delete_member(self):\n data = {\n 'apiUser': self.api_user,\n 'apiKey': self.api_key,\n 'address': self.mail_list_addr,\n 'members': self.member_addr,\n }\n return self.post_api(self.delete_member_url, data)\n","sub_path":"sendcloud/address_list.py","file_name":"address_list.py","file_ext":"py","file_size_in_byte":4152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"264039845","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nfrom polyFeatures import poly_features\n\n\ndef plot_fit(min_x, max_x, mu, sigma, theta, p):\n \"\"\"\n plot a polynomial fit\n \"\"\" \n x = np.arange(min_x-15, max_x+25, 0.05)\n X_poly = poly_features(x, p)\n X_poly -= mu\n X_poly /= sigma\n X_poly = np.c_[np.ones(x.size), X_poly]\n plt.plot(x, np.dot(X_poly, theta))\n","sub_path":"plotFit.py","file_name":"plotFit.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"266746629","text":"#!/usr/bin/env python\n\"\"\"\nDetermines contributors for geojson files and makes CONTRIBUTORS.md file\n\nPhillip J. Wolfram\n04/05/2016\n\"\"\"\n\nimport os\nimport subprocess\nimport shutil\nimport datetime\nimport re\n\n\ndef append_to_file(aline, afile):\n \"\"\" appends aline to afile \"\"\"\n with open(afile, \"a\") as fid:\n fid.write(aline)\n if aline[-1] != '\\n':\n fid.write('\\n')\n\ndef build_contrib_file():\n \"\"\" builds the contributor file CONTRIBUTORS.md \"\"\"\n # get file directories\n gitroot = subprocess.check_output(['git', 'rev-parse', '--show-toplevel']).replace('\\n', '')\n contribdir = gitroot + '/contributors'\n contribfile = contribdir + '/CONTRIBUTORS.md'\n\n # go to git root\n os.chdir(gitroot)\n\n # build up contrib file\n shutil.copyfile(contribdir + '/CONTRIBUTORS_HEADER', contribfile)\n\n append_to_file('List populated on %s:'%\n (datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M\")), contribfile)\n append_to_file('\\n', contribfile)\n\n gitgrep = subprocess.check_output(['git', 'grep', 'author', '--', '*.geojson'])\n authors = set(re.findall(r'\"author\": \"(.*?)\"', gitgrep))\n for author in sorted(authors):\n append_to_file(' * ' + author, contribfile)\n\nif __name__ == \"__main__\":\n build_contrib_file()\n\n# vim: foldmethod=marker ai ts=4 sts=4 et sw=4 ft=python\n","sub_path":"contributors/list_contributors.py","file_name":"list_contributors.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"378367036","text":"\"\"\"This module does wrap League of Legends API.\"\"\"\n\nimport requests\n\nimport api\n\n\nclass Client:\n \"\"\"Gives method to use RiotGames Api.\"\"\"\n\n api_key = \"\"\n region = \"\"\n\n def __init__(self, api_key, region=api.REGIONS['north_america']):\n \"\"\"Init region and api_key.\"\"\"\n self.api_key = api_key\n self.region = region\n\n def _request(self, api_url, params={}):\n \"\"\"Wrap request made to Riot API.\"\"\"\n args = {'api_key': self.api_key}\n for key, value in params.items():\n if key not in args:\n args[key] = value\n\n response = requests.get(\n api.URL['base'].format(\n proxy=self.region,\n region=self.region,\n url=api_url\n ),\n params=args\n )\n\n return response\n\n def get_player_by_name(self, name):\n \"\"\"Get player info by name.\"\"\"\n api_url = api.URL['summoner_by_name'].format(\n version=api.API_VERSIONS['summoner'],\n names=name\n )\n\n return self._request(api_url)\n\n def get_live_game(self, id):\n \"\"\"Get player current game info.\"\"\"\n api_url = api.URL['current_game_by_id'].format(\n ids=id,\n platform=api.PLATFORMS['north_america']\n )\n return self._spectator_request(api_url)\n\n def get_recent_games(self, id):\n \"\"\"Get player recent game info.\"\"\"\n api_url = api.URL['game_by_summoner'].format(\n version=api.API_VERSIONS['game'],\n ids=id\n )\n return self._request(api_url)\n","sub_path":"src/server/client/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"304691194","text":"import time\nimport json\nimport requests\nfrom Token import access_token\n\nv = '5.102'\n\nclass User:\n\n def __init__(self, access_token):\n self.access_token = access_token\n self.friends = []\n self.id_socials = []\n self.socials = set()\n self.groups_of_friends = []\n self.socials_of_friends = set()\n self.info_list = []\n self.info_dict = {}\n self.repeat = True\n\n\n\n def input_user_id(self):\n self.short_name = input('Введите id или короткое имя (screen name) пользователя: ')\n if not self.short_name.isdigit():\n self.short_name = self.get_id()\n\n def get_id(self):\n try:\n self.id = requests.get (\n 'https://api.vk.com/method/users.get',\n params = {\n 'user_ids': self.short_name,\n 'access_token': access_token,\n 'v': v\n }\n ).json ()[ 'response' ][ 0 ][ 'id' ]\n except KeyError:\n return 'Пользователь не найден!'\n\n def get_friends(self):\n while self.repeat:\n self.friends = requests.get(\n 'https://api.vk.com/method/friends.get',\n params={\n 'user_id': self.short_name,\n 'access_token': access_token,\n 'v': v\n }\n ).json()['response']['items']\n print('Получаем список друзей')\n if 'error' in self.friends and 'error_code' in self.friends['error'] and self.friends['error']['error_code'] == 6:\n time.sleep(2)\n else:\n self.repeat = False\n\n def get_socials(self):\n while self.repeat:\n self.id_socials = requests.get(\n 'https://api.vk.com/method/groups.get',\n params={\n 'user_id': self.short_name,\n 'access_token': access_token,\n 'v': v\n }\n ).json()['response']['items']\n print('Получаем список сообществ')\n if 'error' in self.id_socials and 'error_code' in self.id_socials['error'] and self.id_socials['error']['error_code'] == 6:\n time.sleep(2)\n else:\n self.repeat = False\n return self.id_socials\n\n def get_socials_of_friends(self):\n user_socials = set(self.id_socials)\n for friend in self.friends:\n self.groups_of_friends = requests.get(\n 'https://api.vk.com/method/groups.get',\n params={\n 'user_id': friend,\n 'access_token': self.access_token,\n 'v': v\n }\n )\n if 'response' in self.groups_of_friends.json():\n for items in self.groups_of_friends.json()['response']['items']:\n self.socials.add(items)\n self.socials_of_friends = user_socials.difference(self.socials)\n print('.')\n\n\n def get_members_of_group(self,id):\n self.id = id\n response = requests.get (\n 'https://api.vk.com/method/groups.getMembers',\n params = {\n 'group_id': id,\n 'access_token': self.access_token,\n 'v': v\n }\n )\n print ('Получаем количество человек в каждой группе')\n return response.json()['response']['count']\n\n def get_name_of_group(self):\n for group in self.socials_of_friends:\n response = requests.get(\n 'https://api.vk.com/method/groups.getById',\n params={\n 'group_ids': group,\n 'access_token': access_token,\n 'v': v\n }\n )\n print ('Получаем названия групп')\n self.info_dict = {'name': response.json()['response'][0]['name'],\n 'id': response.json()['response'][0]['id'],\n 'member_count': self.get_members_of_group(group)}\n self.info_list.append(self.info_dict)\n\n def write_to_json(self):\n with open ('result.json', 'w') as file:\n print('Записываем результат в файл json')\n json.dump (self.info_list, file, indent = 4, ensure_ascii = False)\n\n def main(self):\n self.input_user_id()\n self.get_friends()\n self.get_socials()\n self.get_socials_of_friends()\n self.get_name_of_group()\n self.write_to_json()\n\n\nuser1 = User(access_token)\nif __name__ == '__main__':\n user1.main()\n","sub_path":"double.py","file_name":"double.py","file_ext":"py","file_size_in_byte":4792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"426915063","text":"import json\nimport logging\n\nfrom peano.paths import Gate, PathsGenerator\nfrom peano.fast_fractions import FastFraction\n\nfrom perebor import perebor\n\nlogging.basicConfig(level=logging.DEBUG)\n\n#input = 'gates-322.txt.sorted'\ninput = 'gates-223.txt.sorted'\n\n\n\ndef get_pt(pt_str):\n xjs = []\n for xj in pt_str.strip('()').split(','):\n if '/' in xj:\n n, d = xj.split('/')\n xjf = FastFraction(int(n), int(d))\n else:\n xjf = FastFraction(int(xj), 1)\n xjs.append(xjf)\n return tuple(xjs)\n\n\ndef get_gate(gate_str):\n entr_str, exit_str = gate_str.split('->')\n return Gate(entrance=get_pt(entr_str), exit=get_pt(exit_str))\n\n\ngates_list = []\nwith open(input) as ifh:\n for line in ifh:\n gate_strs = json.loads(line.replace(\"'\", '\"'))\n gates = [get_gate(gs) for gs in gate_strs]\n gates_list.append(gates)\n\npattern_count = len(gates_list[0])\n\ndef is_vertex(pt):\n if any(FastFraction(0, 1) < xj < FastFraction(1, 1) for xj in pt):\n return False\n return True\n\ndef cnt_bnd_coords(pt):\n return len(list(xj for xj in pt if xj == FastFraction(0, 1) or xj == FastFraction(1, 1)))\n\nfor idx, gates in enumerate(gates_list):\n pts = []\n for g in gates:\n pts += [g.entrance, g.exit]\n vertex_count = len(list(pt for pt in pts if is_vertex(pt)))\n if vertex_count != 0:\n continue\n\n total_bnd_coords = sum(cnt_bnd_coords(gate.entrance) + cnt_bnd_coords(gate.exit) for gate in gates)\n add_bnd_coords = total_bnd_coords - 2 * pattern_count\n if add_bnd_coords != 0:\n continue\n\n conf = {\n 'dim': 2,\n 'div': 2,\n 'ratio_func_name': 'linf',\n #'ratio_func_name': 'l2',\n 'gates': gates,\n 'rel_tol_inv': 10000,\n 'upper_bound': FastFraction(5, 1),\n #'upper_bound': FastFraction(51, 10),\n }\n print('GATE:', idx, [str(g) for g in gates])\n perebor(conf)\n print('===')\n print('')\n","sub_path":"gates-perebor.py","file_name":"gates-perebor.py","file_ext":"py","file_size_in_byte":1956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"549942448","text":"from flask import Flask, render_template, redirect, session, url_for, flash, request, logging, Response\nimport sqlite3 as lite\nimport time\nimport os\nimport RPi.GPIO as GPIO\nimport tkinter\n\napp = Flask(__name__)\n\ndef getData():\n\tconn = lite.connect('../humidityTemp_data.db')\n\tcurs = conn.cursor()\n\t\n\tfor row in curs.execute(\"SELECT * FROM DHT_data ORDER BY timestamp\"):\n\t\ttime = str(row[0])\n\t\ttemperature = row[1]\n\t\thumidity = row[2]\n\tconn.close()\n\treturn time, temperature, humidity\n\ndef adcPi():\n\t#!/usr/bin/python\n\n\t#Analog Input with ADC0832 chip\n\n\tGPIO.setmode(GPIO.BCM)\n\n\t#SPI Port on the ADC \n\tPIN_CLK = 23\n\tPIN_DO = 27\n\tPIN_DI = 22\n\tPIN_CS = 18\n\n\t#Set up the SPI interface pins\n\tGPIO.setup(PIN_DI, GPIO.OUT)\n\tGPIO.setup(PIN_DO, GPIO.IN)\n\tGPIO.setup(PIN_CLK, GPIO.OUT)\n\tGPIO.setup(PIN_CS, GPIO.OUT)\n\n\t#Read SPI data from ADC8032\n\tdef getADC(channel):\n\t\t#1. CS LOW\n\t\tGPIO.output(PIN_CS, True) #cLear Last transmission\n\t\tGPIO.output(PIN_CS, False) #bring CS low\n\n\t\t#2. Start clock\n\t\tGPIO.output(PIN_CLK, False)\n\n\t\t#3. Input MUX address\n\t\tfor i in [1,1,channel]: #start bit + mux assignment\n\t\t\tif(i == 1):\n\t\t\t\tGPIO.output(PIN_DI, True)\n\n\t\t\telse:\n\t\t\t\tGPIO.output(PIN_DI, False)\n\n\t\t\tGPIO.output(PIN_CLK, True)\n\t\t\tGPIO.output(PIN_CLK, False)\n\n\t\t#4. read ADC bits\n\t\tad = 0\n\t\tfor i in range(8):\n\t\t\tGPIO.output(PIN_CLK, True)\n\t\t\tGPIO.output(PIN_CLK, False)\n\t\t\tad <<= 1 #shifr bit\n\t\t\tif(GPIO.input(PIN_DO)):\n\t\t\t\tad |= 0x1 #set first bit\n\n\t\t#5. reset\n\t\tGPIO.output(PIN_CS, True)\n\n\t\treturn ad\n\n\tif __name__ == \"__main__\":\n\t\twhile True:\n\t\t\tprint(\"ADC[0]: {}\\t ADC[1]: {}\".format(getADC(0), getADC(1)))\n\t\t\ttime.sleep(1)\n\t\t\treturn getADC(1)\n\n\t\t\n\n@app.route('/')\n@app.route('/index')\ndef index():\n\treturn render_template('index.html')\n\n@app.route('/about')\ndef about():\n\treturn render_template('about.html', title=\"ABOUT\")\n\n@app.route('/hello')\ndef hello():\n\t\n\tvalue = adcPi()\n\n\ttime, temperature, humidity = getData()\n\ttemplateData = {\n\t\t'time':time,\n\t\t'temperature':temperature,\n\t\t'humidity':humidity,\n\t\t'value': value\n\t}\n\treturn render_template('hello.html', title=\"DATA\", **templateData)\n\n@app.route('/pumpon')\ndef pumpon():\n\tGPIO.setwarnings(False)\n\tGPIO.setmode(GPIO.BCM)\n\tGPIO.setup(26, GPIO.OUT)\n\n\tGPIO.output(26, True)\n\treturn render_template('pumpon.html', title=\"PUMPON\")\n\n@app.route('/pumpoff')\ndef pumpoff():\n\tGPIO.setwarnings(False)\n\tGPIO.setmode(GPIO.BCM)\n\tGPIO.setup(26, GPIO.OUT)\n\n\tGPIO.output(26, False)\n\n\tGPIO.cleanup()\n\treturn redirect(url_for('index'))\n\n@app.route('/login')\ndef login():\n\treturn render_template('login.html', title=\"LOGIN\")\n\t\nif __name__ == '__main__':\n\tapp.secret_key='12345secret'\n\tapp.run(debug=True, port=3330, host='0.0.0.0')\n\n\n","sub_path":"SensorDb/Smart_agro/smart_agro.py","file_name":"smart_agro.py","file_ext":"py","file_size_in_byte":2665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"475359500","text":"# https://www.hackerrank.com/challenges/special-multiple?h_r=next-challenge&h_v=zen\r\n\r\ndef specialM():\r\n for _ in range(int(input())):\r\n i = 1\r\n c = int(input())\r\n while True:\r\n j = int(bin(i)[2:].replace('1','9'))\r\n if j % c == 0:\r\n break\r\n i+=1\r\n print(j)\r\nspecialM()","sub_path":"HackerRankExercise/maths/SpecialMultiple.py","file_name":"SpecialMultiple.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"256815896","text":" \nfrom flask import Flask, render_template, request, make_response, redirect\nimport storage\nfrom outlet_chatter import OutletChatter\n\n\napp = Flask(__name__)\n\n\"\"\"\"\"\n\nRoutes to set up zones and outlets\n\n\"\"\"\"\"\n\n@app.route(\"/add-off\", methods=['GET', 'POST'])\ndef add_off():\n if request.method == \"GET\":\n Zones = storage.GetZones()\n\n Response = make_response(render_template(\"add_off.html\", Zones=Zones))\n return Response\n elif request.method == \"POST\":\n OutletName = request.form.get(\"outletname\")\n OffSelect = request.form.get(\"addoff\")\n\n Chatter = OutletChatter()\n OffId = Chatter.GetOffId()\n \n storage.AddOffId(OffSelect, OffId, OutletName)\n\n Response = make_response(redirect(\"/add-off\"))\n return Response\n\n@app.route(\"/add-on\", methods=['GET', 'POST'])\ndef add_on():\n if request.method == \"GET\":\n Zones = storage.GetZones()\n\n Response = make_response(render_template(\"add_on.html\", Zones=Zones))\n return Response\n elif request.method == \"POST\":\n OutletName = request.form.get(\"outletname\")\n OnSelect = request.form.get(\"addon\")\n\n Chatter = OutletChatter()\n OnId = Chatter.GetOnId()\n \n storage.AddOnId(OnSelect, OnId, OutletName)\n\n Response = make_response(redirect(\"/add-off\"))\n return Response\n\n@app.route(\"/add-zone\", methods=['GET', 'POST'])\ndef add_zone():\n if request.method == \"GET\":\n Response = make_response(render_template(\"add_zone.html\"))\n return Response\n elif request.method == \"POST\":\n ZoneName = request.form.get(\"zonename\")\n\n storage.AddZone(ZoneName)\n\n Response = make_response(redirect(\"/\"))\n\n return Response\n\n@app.route('/', methods=['GET', 'POST'])\ndef main():\n if request.method == 'GET':\n ZoneInformation = storage.GetLandingPageInformation()\n\n Response = make_response(render_template(\"index.html\", Information=ZoneInformation))\n return Response\n elif request.method == 'POST':\n values = request.form.getlist(\"OnOffSwitch\")\n for item in values:\n print(item)\n return render_template('index.html')\n\nif __name__ == '__main__':\n app.run()","sub_path":"KHE2019.py","file_name":"KHE2019.py","file_ext":"py","file_size_in_byte":2237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"77024267","text":"def dice_coefficient1(a, b):\n \"\"\"dice coefficient 2nt/na + nb.\"\"\"\n a_bigrams = set(a)\n b_bigrams = set(b)\n overlap = len(a_bigrams & b_bigrams)\n return overlap * 2.0/(len(a_bigrams) + len(b_bigrams))\n\n\"\"\" more orthodox and robust implementation \"\"\"\ndef dice_coefficient2(a, b):\n \"\"\"dice coefficient 2nt/na + nb.\"\"\"\n if not len(a) or not len(b): return 0.0\n if len(a) == 1: a=a+u'.'\n if len(b) == 1: b=b+u'.'\n\n a_bigram_list=[]\n for i in range(len(a)-1):\n a_bigram_list.append(a[i:i+2].lower())\n b_bigram_list=[]\n for i in range(len(b)-1):\n b_bigram_list.append(b[i:i+2].lower())\n\n a_bigrams = set(a_bigram_list)\n b_bigrams = set(b_bigram_list)\n overlap = len(a_bigrams & b_bigrams)\n dice_coeff = overlap * 2.0/(len(a_bigrams) + len(b_bigrams))\n return dice_coeff\n\n\"\"\" duplicate bigrams in a word should be counted distinctly\n(per discussion), otherwise 'AA' and 'AAAA' would have a\ndice coefficient of 1...\n\"\"\"\ndef dice_coefficient3(a,b):\n if not len(a) or not len(b): return 0.0\n \"\"\" quick case for true duplicates \"\"\"\n if a == b: return 1.0\n \"\"\" if a != b, and a or b are single chars, then they can't possibly match \"\"\"\n if len(a) == 1 or len(b) == 1: return 0.0\n\n \"\"\" use python list comprehension, preferred over list.append() \"\"\"\n a_bigram_list = [a[i:i+2].lower() for i in range(len(a)-1)]\n b_bigram_list = [b[i:i+2].lower() for i in range(len(b)-1)]\n a_bigram_list.sort()\n b_bigram_list.sort()\n\n # assignments to save function calls\n lena = len(a_bigram_list)\n lenb = len(b_bigram_list)\n # initialize match counters\n matches = i = j = 0\n while (i < lena and j < lenb):\n if a_bigram_list[i] == b_bigram_list[j]:\n matches += 2\n i += 1\n j += 1\n elif a_bigram_list[i] < b_bigram_list[j]:\n i += 1\n else:\n j += 1\n score = float(matches)/float(lena + lenb)\n return score\n\n","sub_path":"data/string_similarity.py","file_name":"string_similarity.py","file_ext":"py","file_size_in_byte":1969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"645708135","text":"from openpyxl import Workbook\nfrom openpyxl.styles import Alignment, Border, Font, Side, Protection\nfrom openpyxl.utils import get_column_letter\nfrom datetime import datetime\nfrom read import a, b, c, d, f, g, h, i, j, k, l, m, n, n01, n02, p\n\nwhile True:\n\n wb = Workbook()\n ws = wb.active\n\n data = (\n\n ['KLIENT', ],\n\n ['Imię', b],\n ['Nazwisko', c],\n ['PESEL', d],\n ['Ulica', f],\n ['nr ul.', ],\n ['nr m.', ],\n ['Kod poczt.', g],\n ['Miasto', h],\n ['Nazwa firmy', a],\n ['Regon', ],\n ['NIP', ],\n ['Data pr. jazdy', ],\n ['tel', i],\n ['e-mail', j],\n [' ', ],\n\n ['POJAZD', ],\n\n ['Rodzaj', ],\n ['Marka', k],\n ['Model', l],\n ['Typ', ],\n ['Nr rej.', m],\n ['VIN', ],\n ['Rok prod.', n],\n ['I - rej', ],\n ['Paliwo', ],\n ['Poj.silnika', ],\n ['cm3', ],\n ['Moc kW', ],\n ['Przebieg', ],\n ['Sprowadzony', ],\n ['SU', ],\n ['Koniec OC', ],\n ['TU', n01],\n ['Rodzaj ub.', n02],\n ['Nr polisy', p],\n ['Dzieci', ],\n ['Współwłaściciel', ],\n ['Leasing', ],\n ['Cesja', ],\n )\n\n for row in data:\n ws.append(row)\n\n ws.merge_cells('A1:B1')\n ws.merge_cells('A17:B17')\n\n for x in d[:] :\n\n if len(d) <= 8:\n cs = ws['B4']\n cs.value = d\n if len(d) == 9: # regon\n cs = ws['B11']\n cs.value = d\n if len(d) == 10: # NIP\n cs = ws['B12']\n cs.value = d\n if len(d) >= 11: # pesel\n cs = ws['B4']\n cs.value = d\n\n\n\n # ===============================================================================\n # for i, row in enumerate(data):\n # ws.cell(row=i+3, column=1).value = row\n # ===============================================================================\n # r = 2\n # for row in data:\n # ws.cell(row=r, column=2).value = row\n # r += 1\n # ===============================================================================\n\n # ===============================================================================\n # Dopasowuje szerokość kolumny do stringa\n # ===============================================================================\n column_widths = []\n for row in data :\n for x, cell in enumerate(row) :\n if len(column_widths) > x :\n if len(cell) > column_widths[x] :\n column_widths[x] = len(cell)\n else :\n column_widths = column_widths + [len(cell)]\n\n for x, column_width in enumerate(column_widths) :\n ws.column_dimensions[get_column_letter(x + 1)].width = column_width\n # ===============================================================================\n\n for cell in ws[\"A\"]:\n cell.font = Font(bold=True)\n cell.alignment = Alignment(horizontal='right')\n\n cs = ws['A1']\n cs.alignment = Alignment(horizontal='center')\n\n cs = ws['A17']\n cs.alignment = Alignment(horizontal='center')\n medium_border = Border(bottom=Side(style='medium'))\n\n ws.cell(row=1, column=1).border = medium_border\n ws.cell(row=1, column=2).border = medium_border\n\n ws.cell(row=17, column=1).border = medium_border\n ws.cell(row=17, column=2).border = medium_border\n\n\n\n # print()\n # print()\n # print(b)\n # print(c)\n # print(d)\n # print(f)\n # print(g)\n # print(h)\n # print(a)\n # print(i)\n # print(j)\n # print(k)\n # print(l)\n # print(m)\n # print(n)\n # print(n01)\n # print(n02)\n # # print(o)\n # print(p)\n # print()\n # print()\n\n\n\n datestring = datetime.strftime(datetime.now(), '%d.%m.%Y')\n\n wb.save((input(\"Gdzie zapisać dane?:\"))+'\\dane z Bazy ' + datestring + '.xlsx')\n\n from pyperclip import *\n\n ws = wb['Sheet']\n column = ws['B']\n\n list = ''\n for x in range(len(column)) :\n a = ''\n if column[x].value is None:\n column[x].value = a\n if column[x].value is 'None':\n column[x].value = a\n if column[x].value is 'b/d':\n column[x].value = a\n\n list = list + str(column[x].value) + '\\n'\n\n copy(list)\n\n","sub_path":"Read_2.0/.gitignore/tabela_Baza.py","file_name":"tabela_Baza.py","file_ext":"py","file_size_in_byte":4295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"522106465","text":"import webapp2\n\nSTATIC_SITE_PATH = \"static_site\"\n\n\ndef file_path_to_string(path):\n with open(\"{}/{}\".format(STATIC_SITE_PATH, path), 'r') as f:\n s = f.read()\n return s\n\n\nto_str = file_path_to_string\n\n\ndef cache_page(response):\n response.headers['Cache-Control'] = \"max-age=600\"\n return response\n\n\nclass Main(webapp2.RequestHandler):\n def get(self):\n self.response.headers['Content-Type'] = 'text/html'\n cache_page(self.response)\n self.response.write(to_str('index.html'))\n\n\nclass Styles(webapp2.RequestHandler):\n def get(self, file_name):\n extension = file_name.split(\".\")[1]\n if extension == 'svg':\n content_type = 'image/svg+xml'\n else:\n content_type = 'text/{}'.format(extension)\n self.response.headers['Content-Type'] = content_type\n cache_page(self.response)\n self.response.write(to_str('static/{}'.format(file_name)))\n\n\nclass Icons(webapp2.RequestHandler):\n def get(self, file_name):\n extension = file_name.split(\".\")[1]\n if extension == 'svg':\n content_type = 'image/x-icon'\n else:\n content_type = 'image/{}'.format(extension)\n self.response.headers['Content-Type'] = content_type\n cache_page(self.response)\n self.response.write(to_str('static/icons/{}'.format(file_name)))\n\n\nclass About(webapp2.RequestHandler):\n def get(self):\n self.response.headers['Content-Type'] = 'text/html'\n cache_page(self.response)\n self.response.write(to_str('about.html'))\n\n\nclass Keybase(webapp2.RequestHandler):\n def get(self):\n self.response.headers['Content-Type'] = 'plain/text'\n cache_page(self.response)\n self.response.write(to_str('keybase.txt'))\n\n\nclass Contact(webapp2.RequestHandler):\n def get(self):\n self.response.headers['Content-Type'] = 'text/html'\n cache_page(self.response)\n self.response.write(to_str('contact.html'))\n\n\nclass BlogHome(webapp2.RequestHandler):\n def get(self):\n self.response.headers['Content-Type'] = 'text/html'\n cache_page(self.response)\n self.response.write(to_str('blog.html'))\n\n\nclass BlogPost(webapp2.RequestHandler):\n def get(self, slug):\n self.response.headers['Content-Type'] = 'text/html'\n cache_page(self.response)\n self.response.write(to_str('blog/{}.html'.format(slug)))\n\n\nclass RSS(webapp2.RequestHandler):\n def get(self):\n self.response.headers['Content-Type'] = 'application/rss+xml'\n cache_page(self.response)\n self.response.write(to_str('rss.xml'))\n\n\napp = webapp2.WSGIApplication([\n ('/', Main),\n ('/static/([\\w\\d\\-\\.]+)', Styles),\n ('/static/icons/([\\w\\d\\-\\.]+)', Icons),\n ('/about/', About),\n ('/keybase.txt', Keybase),\n ('/contact/', Contact),\n ('/blog/([\\w\\d\\-]+)/', BlogPost),\n ('/blog/', BlogHome),\n ('/rss/', RSS),\n], debug=True)\n","sub_path":"helloworld/helloworld.py","file_name":"helloworld.py","file_ext":"py","file_size_in_byte":2925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"40644394","text":"# coding: utf-8\nfrom __future__ import unicode_literals\n\nimport re\n\nfrom .common import InfoExtractor\nfrom ..utils import ExtractorError, clean_html, int_or_none, try_get\nfrom ..compat import compat_etree_fromstring, compat_str\n\n\nclass DamtomoIE(InfoExtractor):\n IE_NAME = 'clubdam:damtomo'\n _VALID_URL = r'https?://(www\\.)?clubdam\\.com/app/damtomo/(?:SP/)?karaokeMovie/StreamingDkm\\.do\\?karaokeMovieId=(?P\\d+)'\n _TEST = {\n 'url': 'https://www.clubdam.com/app/damtomo/karaokeMovie/StreamingDkm.do?karaokeMovieId=2414316',\n 'info_dict': {\n 'id': '2414316',\n 'uploader': 'Kドロン',\n 'uploader_id': 'ODk5NTQwMzQ',\n 'song_title': 'Get Wild',\n 'song_artist': 'TM NETWORK(TMN)',\n 'upload_date': '20201226',\n }\n }\n\n def _real_extract(self, url):\n video_id = self._match_id(url)\n webpage, handle = self._download_webpage_handle(\n 'https://www.clubdam.com/app/damtomo/karaokeMovie/StreamingDkm.do?karaokeMovieId=%s' % video_id, video_id,\n encoding='sjis')\n\n if handle.url == 'https://www.clubdam.com/sorry/':\n raise ExtractorError('You are rate-limited. Try again later.', expected=True)\n if '

    予期せぬエラーが発生しました。

    ' in webpage:\n raise ExtractorError('There is a error in server-side. Try again later.', expected=True)\n\n # NOTE: there is excessive amount of spaces and line breaks, so ignore spaces around these part\n description = self._search_regex(r'(?m)
    \\s*

    \\s*([^<]*?)\\s*

    ', webpage, 'description', default=None)\n uploader_id = self._search_regex(r'(.+?)', webpage)}\n data_dict = {k: re.sub(r'\\s+', ' ', v) for k, v in data_dict.items() if v}\n # print(json.dumps(data_dict))\n\n # since videos do not have title, name the video like '%(song_title)s-%(song_artist)s-%(uploader)s' for convenience\n data_dict['user_name'] = re.sub(r'\\s*さん', '', data_dict['user_name'])\n title = '%(song_title)s-%(song_artist)s-%(user_name)s' % data_dict\n\n stream_xml = self._download_webpage(\n 'https://www.clubdam.com/app/damtomo/karaokeMovie/GetStreamingDkmUrlXML.do?movieSelectFlg=2&karaokeMovieId=%s' % video_id, video_id,\n note='Requesting stream information', encoding='sjis')\n try:\n stream_tree = compat_etree_fromstring(stream_xml)\n m3u8_url = try_get(stream_tree, lambda x: x.find(\n './/d:streamingUrl',\n {'d': 'https://www.clubdam.com/app/damtomo/karaokeMovie/GetStreamingDkmUrlXML'}).text.strip(), compat_str)\n if not m3u8_url or not isinstance(m3u8_url, compat_str):\n raise ExtractorError('There is no streaming URL')\n except ValueError: # Python <= 2, ValueError: multi-byte encodings are not supported\n m3u8_url = self._search_regex(r'\\s*(.+?)\\s*', stream_xml, 'm3u8 url')\n formats = self._extract_m3u8_formats(\n m3u8_url, video_id,\n ext='mp4', entry_protocol='m3u8_native', m3u8_id='hls')\n self._sort_formats(formats)\n\n return {\n 'id': video_id,\n 'title': title,\n 'uploader_id': uploader_id,\n 'description': description,\n 'formats': formats,\n 'uploader': data_dict['user_name'],\n 'upload_date': try_get(data_dict, lambda x: self._search_regex(r'(\\d\\d\\d\\d/\\d\\d/\\d\\d)', x['date'], 'upload_date', default=None).replace('/', ''), compat_str),\n 'view_count': int_or_none(self._search_regex(r'(\\d+)', data_dict['audience'], 'view_count', default=None)),\n 'like_count': int_or_none(self._search_regex(r'(\\d+)', data_dict['nice'], 'like_count', default=None)),\n 'song_title': data_dict['song_title'],\n 'song_artist': data_dict['song_artist'],\n }\n","sub_path":"youtube_dl/extractor/damtomo.py","file_name":"damtomo.py","file_ext":"py","file_size_in_byte":4371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"36188434","text":"import numpy as np\r\nimport pandas as pd\r\nimport pyarrow\r\n# import pandavro as pdx\r\nimport os\r\nimport cv2\r\nimport librosa\r\nfrom moviepy.editor import *\r\nimport pickle\r\n\r\nclass FlokDataFrame:\r\n def __init__(self):\r\n self.__dfList = []\r\n self.__counter = 0\r\n self.__modelInputPath = []\r\n self.__modelOutputPath = []\r\n\r\n def getSize(self):\r\n return len(self.__dfList)\r\n\r\n def getData(self):\r\n if len(self.__dfList) == 0:\r\n print(\"DataFrame is empty!\")\r\n return self.__dfList\r\n\r\n def get(self, index):\r\n if index >= self.getSize():\r\n print(\"FloKDataFrame out of index:\")\r\n print(index)\r\n return self.__dfList[index]\r\n\r\n def addDF(self, newdf):\r\n self.__dfList.append(newdf)\r\n\r\n def addModelInputPath(self, path):\r\n self.__modelInputPath.append(path)\r\n\r\n def addModelOutputPath(self, path):\r\n self.__modelOutputPath.append(path)\r\n\r\n def getModelInputPath(self, index):\r\n if index >= len(self.__modelInputPath):\r\n print(\"FloKDataFrame's model input paths list out of index:\" + index)\r\n return self.__modelInputPath[index]\r\n\r\n def getModelOutputPath(self, index):\r\n if index >= len(self.__modelOutputPath):\r\n print(\"FloKDataFrame's model output paths list out of index:\" + index)\r\n return self.__modelOutputPath[index]\r\n\r\n def getModelSize(self):\r\n return len(self.__modelOutputPath)\r\n\r\n def next(self):\r\n if self.__counter < len(self.__dfList):\r\n data = self.__dfList[self.__counter]\r\n self.__counter += 1\r\n return data\r\n else:\r\n print(\"write data: list index out of range\")\r\n\r\nclass FlokAlgorithmLocal:\r\n def pandasDfToNpArray(self, pandasDfList):\r\n npArrayList = []\r\n for i in range(0, len(pandasDfList)):\r\n npArray = pandasDfList[i].values\r\n npArrayList.append(npArray)\r\n return npArrayList\r\n def npArrayToPandasDf(self, npArrayList):\r\n pandasDfList = []\r\n for i in range(0, len(npArrayList)):\r\n pandasDf = pd.DataFrame(npArrayList[i])\r\n pandasDfList.append(pandasDf)\r\n return pandasDfList\r\n def read(self, inputPaths, inputTypes, inputLocation, outputPaths, outputTypes):\r\n globalInputType = \"\"\r\n if len(inputPaths) > 0 and inputPaths[0] == \"\":\r\n return\r\n if len(inputPaths) != len(inputLocation):\r\n print(\"len(inputPaths) != len(inputLocation)\")\r\n return\r\n if len(inputPaths) != len(inputTypes):\r\n if len(inputTypes) >= 1:\r\n globalInputType = inputTypes[0]\r\n else:\r\n print(\"InputType length need to be equal with InputPath length, or just set one input type\")\r\n flokDM = FlokDataFrame()\r\n inputLen = len(inputPaths)\r\n for i in range(0, inputLen):\r\n if inputLocation[i] == \"local_fs\":\r\n if globalInputType == \"\":\r\n globalInputType = inputTypes[i]\r\n if globalInputType == \"csv\":\r\n data = pd.read_csv(inputPaths[i], sep='|')\r\n elif globalInputType == \"parquet\":\r\n data = pd.read_parquet(inputPaths[i], engine='pyarrow')\r\n elif globalInputType == \"orc\":\r\n data = pd.read_orc(inputPaths[i], engine='pyarrow')\r\n elif globalInputType == \"avro\":\r\n pass # data = pdx.read_avro(inputPaths[i])\r\n elif globalInputType == \"model\":\r\n flokDM.addModelInputPath(inputPaths[i])\r\n elif globalInputType == \"txt\" or globalInputType == \"json\":\r\n with open(inputPaths[i], 'rb') as f:\r\n data = pickle.load(f)\r\n elif globalInputType == \"jpg\" or globalInputType == \"png\" or globalInputType == \"bmp\":\r\n #读取pickle文件,将python对象取出来\r\n with open(inputPaths[i],'rb') as f:\r\n data=pickle.load(f)\r\n elif globalInputType == \"mp3\" or globalInputType == \"wav\" or globalInputType == \"ogg\":\r\n with open(inputPaths[i], 'rb') as f:\r\n data = pickle.load(f)\r\n elif globalInputType == \"mp4\" or globalInputType == \"avi\":\r\n dot_id=inputPaths[i].rfind('.')\r\n dir_path=inputPaths[i][:dot_id]\r\n file_list=os.listdir(dir_path)\r\n data={}\r\n for file_name in file_list:\r\n file_path = os.path.join(dir_path, file_name)\r\n try:#有可能有其他非视频文件\r\n video=VideoFileClip(file_path)\r\n data[file_name]=video\r\n except:\r\n pass\r\n else:\r\n print(\"data type not existing\" + globalInputType)\r\n elif inputLocation[i] == \"hdfs\":\r\n if globalInputType == \"\":\r\n globalInputType = inputTypes[i]\r\n if globalInputType == \"csv\":\r\n data = Hdfs(inputPaths[i]).readhdfs(deli='|')\r\n elif globalInputType == \"txt\" or globalInputType == \"json\":\r\n # 设置本地临时文件名\r\n file_name = inputPaths[i].split('/')[-1]\r\n local_tmp_path = \"/tmp/flok-tmp/\" + file_name\r\n # 从hdfs复制到本地\r\n os.system(\"hadoop fs -cp %s file://%s\" % (inputPaths[i], local_tmp_path))\r\n # 在本地把pickle转换为数据\r\n with open(local_tmp_path, 'rb') as f:\r\n data = pickle.load(f)\r\n # 删除本地临时文件\r\n os.system('rm -r' + local_tmp_path)\r\n elif globalInputType == \"jpg\" or globalInputType == \"png\" or globalInputType == \"bmp\":\r\n #设置本地临时文件名\r\n file_name = inputPaths[i].split('/')[-1]\r\n local_tmp_path = \"/tmp/flok-tmp/\" + file_name\r\n #从hdfs复制到本地\r\n os.system(\"hadoop fs -cp %s file://%s\" % (inputPaths[i], local_tmp_path))\r\n #在本地把pickle转换为数据\r\n with open(local_tmp_path,'rb') as f:\r\n data=pickle.load(f)\r\n #删除本地临时文件\r\n os.system('rm -r'+local_tmp_path)\r\n elif globalInputType == \"mp3\" or globalInputType == \"wav\" or globalInputType == \"ogg\":\r\n # 设置本地临时文件名\r\n file_name = inputPaths[i].split('/')[-1]\r\n local_tmp_path = \"/tmp/flok-tmp/\" + file_name\r\n # 从hdfs复制到本地\r\n os.system(\"hadoop fs -cp %s file://%s\" % (inputPaths[i], local_tmp_path))\r\n # 在本地把pickle转换为数据\r\n with open(local_tmp_path, 'rb') as f:\r\n data = pickle.load(f)\r\n # 删除本地临时文件\r\n os.system('rm -r' + local_tmp_path)\r\n elif globalInputType == \"mp4\" or globalInputType == \"avi\":\r\n # 获取hdfs文件夹路径\r\n dot_id=inputPaths[i].rfind('.')\r\n hdfs_forder_path=inputPaths[i][:dot_id]\r\n local_tmp_path = \"/tmp/flok-tmp/\" + hdfs_forder_path.split('/')[-1]\r\n # 从hdfs复制到本地\r\n os.system(\"hadoop fs -cp %s file://%s\" % (hdfs_forder_path, local_tmp_path))\r\n # 在本地读取所有文件\r\n file_list = os.listdir(local_tmp_path)\r\n data = {}\r\n for file_name in file_list:\r\n file_path = os.path.join(local_tmp_path, file_name)\r\n try: # 有可能有其他非视频文件\r\n video = VideoFileClip(file_path)\r\n data[file_name] = video\r\n except:\r\n pass\r\n # 删除本地临时文件\r\n os.system('rm -r' + local_tmp_path)\r\n else:\r\n print(\"inputLocation not existing\")\r\n flokDM.addDF(data)\r\n outputLen = len(outputPaths)\r\n for i in range(0, outputLen):\r\n if outputTypes[i] == \"model\":\r\n flokDM.addModelOutputPath(outputPaths[i])\r\n return flokDM\r\n def write(self, outputPaths, outputData, outputTypes, outputLocation):\r\n if outputData is None:\r\n print(\"Algorithm without output data\")\r\n return\r\n if (len(outputPaths) != outputData.getSize() + outputData.getModelSize()) or (\r\n len(outputPaths) != len(outputTypes)):\r\n print(\"OutData's number \" + str(\r\n outputData.getSize() + outputData.getModelSize()) + \" is not equals to output's number \" + str(\r\n len(outputPaths)))\r\n return\r\n outputLen = len(outputPaths)\r\n if (outputLen != len(outputLocation)):\r\n print(\"outputPathLen is not equal to outputLocationLen\")\r\n return\r\n for i in range(0, outputLen):\r\n outData = outputData.next()\r\n if outputLocation[i] == \"local_fs\":\r\n if outputTypes[i] == \"csv\":\r\n dir = outputPaths[i].rfind(\"/\")\r\n dirpath = outputPaths[i][:dir]\r\n if (os.path.exists(dirpath) is not True):\r\n os.mkdir(dirpath)\r\n outData.to_csv(outputPaths[i], sep=\"|\", header=True, index=False)\r\n elif outputTypes[i] == \"parquet\":\r\n outData.to_parquet(outputPaths[i], engine='pyarrow')\r\n elif outputTypes[i] == \"avro\":\r\n outData.to_avro(outputPaths[i], outData)\r\n # outData.to_parquet(outputPaths[i], engine = 'fastparquet')\r\n elif outputTypes[i] == \"model\":\r\n print(\"how to write model file\")\r\n elif outputTypes[i] == \"txt\" or outputTypes[i] == \"json\":\r\n dir = outputPaths[i].rfind(\"/\")\r\n dirpath = outputPaths[i][:dir]\r\n if not os.path.exists(dirpath):\r\n os.mkdir(dirpath)\r\n with open(outputPaths[i],'wb') as f:\r\n pickle.dump(outData,f)\r\n #输出的类型只会是特定的某一种,在新建配置->存储配置可以查看。数据库为data_format。\r\n elif outputTypes[i] == \"jpg\" or outputTypes[i] == \"png\" or outputTypes[i] == \"bmp\":\r\n #检测路径是否存在\r\n dir = outputPaths[i].rfind(\"/\")\r\n dirpath = outputPaths[i][:dir]\r\n if not os.path.exists(dirpath):\r\n os.mkdir(dirpath)\r\n # cv2.imwrite(outputPaths[i].replace(\".output\", \".\" + outputTypes[i]), outData)\r\n #outData为python对象,将其序列化,并存储\r\n with open(outputPaths[i],'wb') as f:\r\n pickle.dump(outData,f)\r\n elif outputTypes[i] == \"wav\" or outputTypes[i] == \"mp3\" or outputTypes[i] == \"ogg\":\r\n # 检测路径是否存在\r\n dir = outputPaths[i].rfind(\"/\")\r\n dirpath = outputPaths[i][:dir]\r\n if not os.path.exists(dirpath):\r\n os.mkdir(dirpath)\r\n # cv2.imwrite(outputPaths[i].replace(\".output\", \".\" + outputTypes[i]), outData)\r\n # outData为python对象,将其序列化,并存储\r\n with open(outputPaths[i], 'wb') as f:\r\n pickle.dump(outData, f)\r\n elif outputTypes[i] == \"mp4\" or outputTypes[i] == \"avi\":\r\n # 检测路径是否存在\r\n dot_id=outputPaths[i].rfind('.')\r\n dirpath = outputPaths[i][:dot_id]\r\n if not os.path.exists(dirpath):\r\n #创建多级dir\r\n os.makedirs(dirpath)\r\n # 将mp4文件写入路径。\r\n for video_name,video in outData.items():\r\n new_name=os.path.join(dirpath,video_name)\r\n video.write_videofile(new_name)\r\n else:\r\n print(\"data type not existing \" + outputTypes[i])\r\n elif outputLocation[i] == \"hdfs\":\r\n if outputTypes[i] == \"csv\":\r\n Hdfs(outputPaths[i]).writehdfs(deli='|', data=outData)\r\n elif outputTypes[i] == \"txt\" or outputTypes[i] == \"json\":\r\n ip = outputPaths[i].split(':')[1][2:]\r\n tmp = outputPaths[i].split(':')[2]\r\n port = tmp[:tmp.index('/')]\r\n file_path = tmp[tmp.index('/'):]\r\n hdfs = pyarrow.hdfs.connect(host=ip, port=int(port))\r\n # 检查文件夹是否存在,如果不存在创建\r\n idofslash = file_path.rfind('/')\r\n dir = file_path[:idofslash]\r\n file_name = file_path[idofslash + 1:]\r\n if not hdfs.exists(dir):\r\n hdfs.mkdir(dir)\r\n local_tmp_path = '/tmp/flok-tmp/' + file_name\r\n with open(local_tmp_path, 'wb') as f:\r\n pickle.dump(outData, f)\r\n # 上传文件到hdfs\r\n cmd = \"hadoop fs -cp file://%s %s\" % (local_tmp_path, outputPaths[i])\r\n os.system(cmd)\r\n # 删除本地文件\r\n cmd = \"rm -r \" + local_tmp_path\r\n os.system(cmd)\r\n elif outputTypes[i] == \"jpg\" or outputTypes[i] == \"png\" or outputTypes[i] == \"bmp\":\r\n ip = outputPaths[i].split(':')[1][2:]\r\n tmp = outputPaths[i].split(':')[2]\r\n port = tmp[:tmp.index('/')]\r\n file_path = tmp[tmp.index('/'):]\r\n hdfs = pyarrow.hdfs.connect(host=ip, port=int(port))\r\n #检查文件夹是否存在,如果不存在创建\r\n idofslash=file_path.rfind('/')\r\n dir=file_path[:idofslash]\r\n file_name=file_path[idofslash+1:]\r\n if not hdfs.exists(dir):\r\n hdfs.mkdir(dir)\r\n local_tmp_path='/tmp/flok-tmp/'+file_name\r\n with open(local_tmp_path,'wb') as f:\r\n pickle.dump(outData,f)\r\n #上传文件到hdfs\r\n cmd = \"hadoop fs -cp file://%s %s\" % (local_tmp_path, outputPaths[i])\r\n os.system(cmd)\r\n # 删除本地文件\r\n cmd = \"rm -r \" + local_tmp_path\r\n os.system(cmd)\r\n elif outputTypes[i] == \"mp3\" or outputTypes[i] == \"wav\" or outputTypes[i] == \"ogg\":\r\n ip = outputPaths[i].split(':')[1][2:]\r\n tmp = outputPaths[i].split(':')[2]\r\n port = tmp[:tmp.index('/')]\r\n file_path = tmp[tmp.index('/'):]\r\n hdfs = pyarrow.hdfs.connect(host=ip, port=int(port))\r\n # 检查文件夹是否存在,如果不存在创建\r\n idofslash = file_path.rfind('/')\r\n dir = file_path[:idofslash]\r\n file_name = file_path[idofslash + 1:]\r\n if not hdfs.exists(dir):\r\n hdfs.mkdir(dir)\r\n local_tmp_path = '/tmp/flok-tmp/' + file_name\r\n with open(local_tmp_path, 'wb') as f:\r\n pickle.dump(outData, f)\r\n # 上传文件到hdfs\r\n cmd = \"hadoop fs -cp file://%s %s\" % (local_tmp_path, outputPaths[i])\r\n os.system(cmd)\r\n # 删除本地文件\r\n cmd = \"rm -r \" + local_tmp_path\r\n os.system(cmd)\r\n elif outputTypes[i] == \"mp4\" or outputTypes[i] == \"avi\":\r\n ip = outputPaths[i].split(':')[1][2:]\r\n tmp = outputPaths[i].split(':')[2]\r\n port = tmp[:tmp.index('/')]\r\n file_path = tmp[tmp.index('/'):]\r\n hdfs = pyarrow.hdfs.connect(host=ip, port=int(port))\r\n # 检查文件夹是否存在,如果不存在创建\r\n dot_id = file_path.rfind('.')\r\n dir = file_path[:dot_id]\r\n #被保存的文件夹名字,在airflow_services里面生成\r\n folder_name=dir.split('/')[-1]\r\n if not hdfs.exists(dir):\r\n hdfs.mkdir(dir)\r\n local_tmp_path = '/tmp/flok-tmp/' + folder_name\r\n os.mkdir(local_tmp_path)\r\n #先写到本地\r\n for video_name,video in outData.items():\r\n new_name=os.path.join(local_tmp_path,video_name)\r\n video.write_videofile(new_name)\r\n # 上传文件到hdfs\r\n # 获取hdfs文件夹整体路径\r\n dot_id = outputPaths[i].rfind('.')\r\n os.system(\"hadoop fs -cp file://%s %s\" % (local_tmp_path+'/*', outputPaths[i][:dot_id]))\r\n # 删除本地文件\r\n os.system(\"rm -r \" + local_tmp_path)\r\n else:\r\n print(\"outputLocation not existing\")\r\n\r\n def run(self, inputDataSets, params):\r\n print(\"waiting for override\")\r\n\r\n\r\nclass Hdfs():\r\n def __init__(self, path):\r\n ip = path.split(':')[1][2:]\r\n tmp = path.split(':')[2]\r\n port = tmp[:tmp.index('/')]\r\n self.filename = tmp[tmp.index('/'):]\r\n self.hdfs = pyarrow.hdfs.connect(host=ip, port=int(port))\r\n\r\n def put(self, filename, path, chunk=2 ** 16, replication=0):\r\n \"\"\" Copy local file to path in HDFS \"\"\"\r\n with self.hdfs.open(path, 'wb', replication=replication) as target:\r\n with open(filename, 'rb') as source:\r\n while True:\r\n out = source.read(chunk)\r\n if len(out) == 0:\r\n break\r\n target.write(out)\r\n\r\n def getmerge(self, path, filename):\r\n \"\"\" Concat all files in path (a directory) to local output file \"\"\"\r\n files = self.hdfs.ls(path)\r\n idx = 0\r\n with open(filename, 'wb') as fout:\r\n for apath in files:\r\n with self.hdfs.open(apath, 'rb') as fin:\r\n data = fin.read().splitlines(True)\r\n if (idx == 0 and len(data)!=0):\r\n fout.writelines(data[0:])\r\n idx+=1\r\n else:\r\n fout.writelines(data[1:])\r\n\r\n def readhdfs(self, deli):\r\n self.getmerge(path=self.filename, filename='tmp.csv') # 获取制定目录下的所有文件,复制合并到本地文件\r\n df = pd.read_csv(\"tmp.csv\", deli)\r\n os.system(\"rm tmp.csv\")\r\n return df\r\n\r\n def writehdfs(self, deli, data):\r\n data.to_csv(\"tmp_write.csv\", sep=deli, header=True, index=False)\r\n self.put(\"tmp_write.csv\", path=self.filename) # 将本地的文件上传\r\n os.system(\"rm tmp_write.csv\")","sub_path":"FlokAlgorithmLocal.py","file_name":"FlokAlgorithmLocal.py","file_ext":"py","file_size_in_byte":19946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"387857912","text":"import itertools\n\nimport numpy as np\n\nfrom ml.initializers import random_uniform\nfrom optimization.optimization_function import OptimizationFunction, BoxConstrainedQuadratic\nfrom optimization.line_search import ArmijoWolfeLineSearch, BacktrackingLineSearch\nfrom utils import iter_mini_batches\n\n\nclass Optimizer:\n\n def __init__(self, f, wrt=random_uniform, batch_size=None, eps=1e-6, max_iter=1000, verbose=False, plot=False):\n \"\"\"\n\n :param f: the objective function.\n :param wrt: ([n x 1] real column vector): the point where to start the algorithm from.\n :param eps: (real scalar, optional, default value 1e-6): the accuracy in the stopping\n criterion: the algorithm is stopped when the norm of the gradient is less\n than or equal to eps.\n :param max_iter: (integer scalar, optional, default value 1000): the maximum number of iterations.\n :param verbose: (boolean, optional, default value False): print details about each iteration\n if True, nothing otherwise.\n :param plot: (boolean, optional, default value False): plot the function's surface and its contours\n if True and the function's dimension is 2, nothing otherwise.\n \"\"\"\n if not isinstance(f, OptimizationFunction):\n raise TypeError('f is not an optimization function')\n self.f = f\n if callable(wrt):\n self.wrt = wrt(f.n)\n elif not np.isrealobj(wrt):\n raise ValueError('x not a real vector')\n else:\n self.wrt = np.asarray(wrt, dtype=float)\n self.n = self.wrt.size\n self.batch_size = batch_size\n if not np.isscalar(eps):\n raise ValueError('eps is not a real scalar')\n if not eps > 0:\n raise ValueError('eps must be > 0')\n self.eps = eps\n if not np.isscalar(max_iter):\n raise ValueError('max_iter is not an integer scalar')\n if not max_iter > 0:\n raise ValueError('max_iter must be > 0')\n self.max_iter = max_iter\n self.iter = 1\n self.verbose = verbose\n self.plot = plot\n if batch_size is None:\n self.args = itertools.repeat(f.args())\n else:\n self.args = (i for i in iter_mini_batches(f.args(), batch_size))\n\n def minimize(self):\n raise NotImplementedError\n\n\nclass BoxConstrainedOptimizer(Optimizer):\n def __init__(self, f, eps=1e-6, max_iter=1000, verbose=False, plot=False):\n if not isinstance(f, BoxConstrainedQuadratic):\n raise TypeError('f is not a box-constrained quadratic function')\n super().__init__(f, f.ub / 2, # start from the middle of the box\n eps=eps, max_iter=max_iter, verbose=verbose, plot=plot)\n\n\nclass LineSearchOptimizer(Optimizer):\n\n def __init__(self, f, wrt=random_uniform, batch_size=None, eps=1e-6, max_iter=1000, max_f_eval=1000, m1=0.01,\n m2=0.9, a_start=1, tau=0.9, sfgrd=0.01, m_inf=-np.inf, min_a=1e-16, verbose=False, plot=False):\n \"\"\"\n\n :param f: the objective function.\n :param wrt: ([n x 1] real column vector): the point where to start the algorithm from.\n :param eps: (real scalar, optional, default value 1e-6): the accuracy in the stopping\n criterion: the algorithm is stopped when the norm of the gradient is less\n than or equal to eps.\n :param max_f_eval: (integer scalar, optional, default value 1000): the maximum number of\n function evaluations (hence, iterations will be not more than max_f_eval\n because at each iteration at least a function evaluation is performed,\n possibly more due to the line search).\n :param m1: (real scalar, optional, default value 0.01): first parameter of the\n Armijo-Wolfe-type line search (sufficient decrease). Has to be in (0,1).\n :param m2: (real scalar, optional, default value 0.9): typically the second parameter\n of the Armijo-Wolfe-type line search (strong curvature condition). It should\n to be in (0,1); if not, it is taken to mean that the simpler Backtracking\n line search should be used instead.\n :param a_start: (real scalar, optional, default value 1): starting value of alpha in the\n line search (> 0).\n :param tau: (real scalar, optional, default value 0.9): scaling parameter for the line\n search. In the Armijo-Wolfe line search it is used in the first phase: if the\n derivative is not positive, then the step is divided by tau (which is < 1,\n hence it is increased). In the Backtracking line search, each time the step is\n multiplied by tau (hence it is decreased).\n :param sfgrd: (real scalar, optional, default value 0.01): safeguard parameter for the line search.\n To avoid numerical problems that can occur with the quadratic interpolation if the\n derivative at one endpoint is too large w.r.t. The one at the other (which leads to\n choosing a point extremely near to the other endpoint), a *safeguarded* version of\n interpolation is used whereby the new point is chosen in the interval\n [as * (1 + sfgrd) , am * (1 - sfgrd)], being [as , am] the current interval, whatever\n quadratic interpolation says. If you experience problems with the line search taking\n too many iterations to converge at \"nasty\" points, try to increase this.\n :param m_inf: (real scalar, optional, default value -inf): if the algorithm determines a value for\n f() <= m_inf this is taken as an indication that the problem is unbounded below and\n computation is stopped (a \"finite -inf\").\n :param min_a: (real scalar, optional, default value 1e-16): if the algorithm determines a step size\n value <= min_a, this is taken as an indication that something has gone wrong (the gradient\n is not a direction of descent, so maybe the function is not differentiable) and computation\n is stopped. It is legal to take min_a = 0, thereby in fact skipping this test.\n :param verbose: (boolean, optional, default value False): print details about each iteration\n if True, nothing otherwise.\n :param plot: (boolean, optional, default value False): plot the function's surface and its contours\n if True and the function's dimension is 2, nothing otherwise.\n \"\"\"\n super().__init__(f, wrt, batch_size, eps, max_iter, verbose, plot)\n if not np.isscalar(m_inf):\n raise ValueError('m_inf is not a real scalar')\n self.m_inf = m_inf\n if 0 < m2 < 1:\n self.line_search = ArmijoWolfeLineSearch(f, max_f_eval, m1, m2, a_start, tau, sfgrd, min_a, verbose)\n else:\n self.line_search = BacktrackingLineSearch(f, max_f_eval, m1, a_start, min_a, tau, verbose)\n","sub_path":"optimization/optimizer.py","file_name":"optimizer.py","file_ext":"py","file_size_in_byte":7528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"323566492","text":"# -*- coding: utf-8 -*-\n'''\nCreated on 2015年6月16日\n这是对象和数据库的ORM\nField类,定义数据库表字段与类属性直接的关系,Field为基类,可以将数据库中的类型扩充完。\nModelMetaclass类,是原数据类\n@author: gaokang\n'''\n\nimport db\n\nclass Field(object):\n _count = 0\n def __init__(self,**kw):\n self.name = kw.get('name',None)\n self._default = kw.get('default',None)\n self.nullable = kw.get('nullable',False)\n self.primary_key = kw.get('primary_key',False)\n self._order = Field._count\n Field._count = Field._count + 1\n self.ddl = kw.get('ddl','')\n \n#@property把方法变成属性调用user.name\n @property\n def default(self):\n d = self._default\n return d() if callable(d) else d\n def __str__(self):\n s = ['<%s:%s,%s,default(%s),' % (self.__class__.__name__,self.name,self.ddl,self._default)]\n self.nullable and s.append('N')\n s.append('>')\n return ''.join(s)\n \nclass StringField(Field):\n def __init__(self,**kw):\n if not 'default' in kw:\n kw['default'] = ''\n if not 'ddl' in kw:\n kw['ddl'] = 'varchar(250)'\n super(StringField,self).__init__(**kw)\n\nclass IntegerField(Field):\n def __init__(self, **kw):\n if not 'ddl' in kw:\n kw['ddl']='bigint'\n super(IntegerField, self).__init__(**kw)\n\n'''\n先定义metaclass,就可以创建类,最后创建实例。\nPython解释器在创建Model时,要通过ModelMetaclass.__new__()来创建类\n__new__()方法接收到的参数依次是:\n1.当前准备创建的类的对象;\n2.类的名字;\n3.类继承的父类集合;\n4.类的方法集合。\n''' \nclass ModelMetaclass(type):\n def __new__(cls,name,bases,attrs):\n if name == 'Model':\n return type.__new__(cls,name,bases,attrs)\n #print ('Found model: %s' % name)\n mappings = dict()\n primary_key = None\n for k,v in attrs.iteritems():\n if isinstance(v,Field):\n if not v.name:\n v.name = k\n if v.primary_key:\n if primary_key:\n raise TypeError('Cannot define more than one primary key in class: %s' % name)\n if v.nullable:\n v.nullable = False\n primary_key = v\n mappings[k] = v\n if not primary_key:\n raise TypeError('Primary key not defined in class: %s' % name)\n for k in mappings.iterkeys():\n attrs.pop(k)\n attrs['__table__'] = name.lower()\n attrs['__mappings__'] = mappings\n attrs['__primary_key__'] = primary_key\n return type.__new__(cls,name,bases,attrs)\n \nclass Model(dict):\n __metaclass__ = ModelMetaclass # 指示使用ModelMetaclass来定制类 它指示Python解释器在创建Model时,要通过ModelMetaclass.__new__()来创建,在此,我们可以修改类的定义,比如,加上新的方法,然后,返回修改后的定义。\n\n def __init__(self,**kw):\n super(Model,self).__init__(**kw)\n\n def __getattr__(self,key):\n try:\n return self[key]\n except KeyError:\n raise AttributeError(r\"'Model' object has no attribute '%s'\" % key) \n \n def __setattr__(self,key,value):\n self[key] = value\n #print '%s: %s' % self,value\n \n def save(self):\n fields = []\n params = []\n args = []\n mapping={}\n for k, v in self.__mappings__.iteritems():\n fields.append(v.name)\n params.append('?')\n args.append(getattr(self, k, None))\n mapping[v.name]=getattr(self, k, None)\n #sql = 'insert into %s (%s) values (%s)' % (self.__table__, ','.join(fields), ','.join(params))\n #print('SQL: %s' % sql)\n #print('ARGS: %s' % str(args))\n #db.update(sql,args)\n \n #print mapping\n db.insert(self.__table__,**mapping)\n \n def update(self): \n sets=[]\n setArgs=[]\n condition=[]\n conditionArgs=[]\n for k,v in self.__mappings__.iteritems():\n if(v.primary_key):\n condition.append(v.name+'=? ')\n conditionArgs.append(getattr(self, k, None))\n else:\n sets.append(v.name+'=? ') \n setArgs.append(getattr(self, k, None))\n sql='update %s set %s where %s' % (self.__table__, ','.join(sets), ' and '.join(condition))\n #print('SQL: %s' % sql)\n args=[]\n args.extend(setArgs)\n args.extend(conditionArgs)\n #print('ARGS: %s' % str(args))\n db.update(sql,*args)\n \n def delete(self):\n primary_key_name=self.__primary_key__.name\n primary_key_value=getattr(self, primary_key_name, None)\n primary_key={}\n primary_key[primary_key_name]=primary_key_value\n db.delete(self.__table__,**primary_key)\n \n def queryById(self):\n primary_key_name=self.__primary_key__.name\n primary_key_value=getattr(self, primary_key_name, None)\n sql=\"select * from %s where %s =? \" % (self.__table__,primary_key_name)\n res=db.row(sql,primary_key_value);\n for k in self.__mappings__.iterkeys():\n setattr(self,k,getattr(res, k, None))\n \n ","sub_path":"first-python-webapp/src/com/gaokang/common/db/orm.py","file_name":"orm.py","file_ext":"py","file_size_in_byte":5388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"218190361","text":"#!/usr/bin/python\n\nimport numpy as np\nimport se3\nimport collections\nimport matplotlib.pyplot as plt\nfrom scipy.stats import chi2\n\nPoseWithCov = collections.namedtuple('PoseWithCov', 'pose cov')\n\ntau = np.array([0,0,0,0,0,0])\nsigma = 0.03\n\n# Initial state (mean)\nr = 1\nT0 = se3.exp(tau)\nE0 = np.zeros((6,6))\nT0[0,3] = r\n\n# Uncertainty on in-plane rotation\ndef get_uncertainty(sigma):\n sigma_sq = np.power(sigma, 2)\n E = np.diag(sigma_sq)\n return sigma, E\n\n# Compute the confidence ellipse\ndef confidence_ellipse(pose, cov, confidence=0.95):\n # Compute eigenvalues and eigenvectors\n eig_val, eig_vec = np.linalg.eig(cov)\n # Sort in ascending order\n idx = eig_val.argsort()[::-1] \n eig_val = eig_val[idx]\n eig_vec = eig_vec[:,idx]\n # Get the angle between major\n # axis and x axis\n phi = np.arctan2(eig_vec[-1][1], eig_vec[-1][0])\n # Clip angle\n if phi < 0: phi = phi + 2*np.pi\n # \n chi_sqr_val = np.sqrt(chi2.ppf(confidence, cov.shape[0]))\n # 2d rotation matrix\n R = np.array([[np.cos(phi), np.sin(phi)], [-np.sin(phi), np.cos(phi)]])\n # Compute axis length\n a = chi_sqr_val * np.sqrt(eig_val[-1]) \n b = chi_sqr_val * np.sqrt(eig_val[0])\n theta_grid = np.linspace(0, 2*np.pi)\n ellipse_x = a * np.cos(theta_grid)\n ellipse_y = b * np.sin(theta_grid)\n ellipse = np.dot(R, np.array([ellipse_x, ellipse_y]))\n return ellipse[0,:] + pose[0], ellipse[1,:] + pose[1]\n \n \n \n# Simulate 1000 samples for 100 steps\nN = 1000\nK = 100\nsamples = [[PoseWithCov for j in range(K)] for i in range(N)]\nfor i in range(N):\n Tk = np.eye(4,4)\n Ek = E0\n samples[i][0] = PoseWithCov(pose=Tk, cov=Ek) \n random_sigs = np.random.uniform(low=-sigma, high=sigma, size=(K))\n for j in range(1, K):\n # Random sampling\n Psi, E = get_uncertainty(np.array([0.1, 0, 0, 0, 0, random_sigs[j]]))\n Adj = se3.adj(Tk)\n # Update mean\n Tk = np.linalg.multi_dot((Tk, se3.exp(Psi), T0))\n # Update covariances\n Ek = samples[i][j-1].cov + np.linalg.multi_dot((Adj, E, np.transpose(Adj)))\n samples[i][j] = PoseWithCov(pose=Tk, cov=Ek)\n\n# Draw\nplt.figure(0)\nfor i in range(N-1, N):\n x = []\n y = []\n for j in range(K):\n pose2d = samples[i][j].pose[0:2,3]\n cov2d = samples[i][j].cov[0:2, 0:2]\n x.append(pose2d[0])\n y.append(pose2d[1])\n xe, ye = confidence_ellipse(pose2d, cov2d)\n plt.plot(xe, ye)\n plt.scatter(x,y)\nplt.xlim((-5, 105))\nplt.xlabel(\"X (m)\")\nplt.ylabel(\"Y (m)\")\nplt.grid()\nplt.show()\n\n","sub_path":"test_se3.py","file_name":"test_se3.py","file_ext":"py","file_size_in_byte":2423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"482704630","text":"\"\"\"Decorator Pattern example\"\"\"\n\n\ndef greenwich(decoratee):\n setattr(decoratee, 'greenwich', (51.4826, 0.0077))\n return decoratee\n\n\nclass LatLng(object):\n \"\"\"A class represention location coordinates\"\"\"\n\n def __init__(self, lat, lng):\n self.latitude = lat\n self.longitude = lng\n\n\ncoords = LatLng(30, 45)\n\nprint(getattr(coords, 'greenwich', None)) # None\n\ngreenwich(coords)\n\nprint(getattr(coords, 'greenwich')) # (51.4826, 0.0077)\n","sub_path":"PythonFlow_March2018/Examples/_06_Python_Design_patterns/_8_decorator_pattern_2.py","file_name":"_8_decorator_pattern_2.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"488086888","text":"# -*- coding: utf-8 -*-\n\nimport templates.reminders as remindersTemplate\n\nclass Reminders:\n\tkeys = {\n\t\t'this_week': '{ESTA_SEMANA}',\n\t\t'next_week': '{PROXIMAS_SEMANAS}',\n\t\t'reminder_title': '{R_TITLE}',\n\t\t'reminder_link': '{R_LINK}'\n\t}\n\n\tdef __init__(self):\n\t\tself.reminders_template = remindersTemplate.Reminders()\n\t\tself.this_week = []\n\t\tself.next_week = []\n\n\tdef addReminderThisWeek(self, title, link):\n\t\tself.this_week.append(Reminder(title, link))\n\tdef addReminderNextWeek(self, title, link):\n\t\tself.next_week.append(Reminder(title, link))\n\n\tdef createReminderThisWeek(self):\n\t\thtml = ''\n\n\t\tfor r in self.this_week:\n\t\t\treminder = self.reminders_template.getReminderTemplate()\n\t\t\treminder = reminder.replace(self.keys['reminder_title'], r.title)\n\t\t\treminder = reminder.replace(self.keys['reminder_link'], r.link)\n\t\t\thtml+= reminder\n\n\t\treturn html\n\n\tdef createReminderNextWeek(self):\n\t\thtml = ''\n\n\t\tfor r in self.next_week:\n\t\t\treminder = self.reminders_template.getReminderTemplate()\n\t\t\treminder = reminder.replace(self.keys['reminder_title'], r.title)\n\t\t\treminder = reminder.replace(self.keys['reminder_link'], r.link)\n\t\t\thtml+= reminder\n\n\t\treturn html\n\n\tdef output(self):\n\t\tself.reminders_template.replaceTemplate(self.keys['this_week'], self.createReminderThisWeek())\n\t\tself.reminders_template.replaceTemplate(self.keys['next_week'], self.createReminderNextWeek())\n\t\treturn self.reminders_template.getTemplate()\n\nclass Reminder:\n\tdef __init__(self, title, link):\n\t\tself.title = title\n\t\tself.link = link","sub_path":"core/reminders.py","file_name":"reminders.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"547138184","text":"import os\nimport random\nfrom collections import defaultdict\nfrom typing import Optional, List\n\nimport torch\nfrom torch import Tensor\nimport datasets as ds\nfrom pytorch_lightning import LightningDataModule\nfrom stl_text.ops.tokenizers import WhitespaceTokenizer\nfrom stl_text.ops.transforms import LabelTransform\nfrom torch.nn.utils.rnn import pad_sequence\nfrom stl_text.ops.samplers import PoolBatchSampler\n\n\ndef assert_padded_tensor3d_equal_to_list3d(list_val, tensor_val):\n \"\"\"\n Asserts if all values in a list match the tensor values. \n \"\"\"\n for i, seq1 in enumerate(list_val):\n for j, seq2 in enumerate(seq1):\n seq = seq2\n if isinstance(seq, torch.Tensor):\n seq = seq.tolist()\n\n for k, val in enumerate(seq):\n assert val == tensor_val[i,j,k].data.item()\n \n\nclass DPRRetrieverDataModule(LightningDataModule):\n \"\"\"\n This reads a jsonl file with json objects from the original DPR data obtained from https://github.com/facebookresearch/DPR/blob/master/data/download_data.py.\n \"\"\"\n def __init__(self, data_path: str, \n vocab_path: Optional[str] = None, \n batch_size: int = 32,\n max_positive: int = 1, # currently, like the original paper only 1 is supported\n max_negative: int = 7,\n ctxs_random_sample: bool = True, \n limit_eval: bool = False, # Limits pos_neg with test\n drop_last: bool = False,\n num_proc_in_map: int = 1, \n distributed: bool = False, \n load_from_cache_file: bool = True,\n vocab_trainable:bool = False):\n super().__init__()\n self.data_path = data_path\n self.vocab_path = vocab_path\n self.vocab_trainable = vocab_trainable\n self.batch_size = batch_size\n self.drop_last = drop_last\n self.num_proc_in_map = num_proc_in_map\n self.distributed = distributed\n self.load_from_cache_file = load_from_cache_file\n\n if max_positive>1:\n raise ValueError(\"Only 1 positive example is supported. Update the loss accordingly to support more than 1!\")\n \n self.max_positive = max_positive\n self.max_negative = max_negative\n self.ctxs_random_sample = ctxs_random_sample\n self.limit_eval = limit_eval\n\n self.text_transform = None\n self.datasets = {}\n\n\n def setup(self, stage):\n self.text_transform = WhitespaceTokenizer(vocab_path=self.vocab_path, trainable=self.vocab_trainable)\n\n for split in (\"train\", \"valid\", \"test\"):\n dataset_split = ds.Dataset.load_from_disk(os.path.join(self.data_path, split)) # raw dataset\n dataset_split = dataset_split.map(function=lambda x: {'query_ids': self.text_transform(x)},\n input_columns='question', num_proc=self.num_proc_in_map,\n load_from_cache_file=self.load_from_cache_file)\n dataset_split = dataset_split.map(function=lambda ctxs: {'contexts_pos_ids': [self.text_transform(x[\"text\"]) for x in ctxs]},\n input_columns='positive_ctxs', num_proc=self.num_proc_in_map,\n load_from_cache_file=self.load_from_cache_file)\n dataset_split = dataset_split.map(function=lambda ctxs: {'contexts_neg_ids': [self.text_transform(x[\"text\"]) for x in ctxs]},\n input_columns='negative_ctxs', num_proc=self.num_proc_in_map,\n load_from_cache_file=self.load_from_cache_file)\n dataset_split = dataset_split.map(function=lambda x: {'query_seq_len': len(x)},\n input_columns='query_ids', num_proc=self.num_proc_in_map,\n load_from_cache_file=self.load_from_cache_file)\n dataset_split.set_format(type='torch', columns=['query_ids', 'query_seq_len', \n 'contexts_pos_ids', 'contexts_neg_ids'])\n \n self.datasets[split] = dataset_split\n\n def forward(self, text):\n return self.text_transform(text)\n\n def train_dataloader(self):\n # sample data into `num_batches_in_page` sized pool. In each pool, sort examples by sequence length, batch them\n # with `batch_size` and shuffle batches\n train_dataset = self.datasets[\"train\"]\n batch_sampler = PoolBatchSampler(train_dataset, batch_size=self.batch_size,\n drop_last=self.drop_last, \n #key=lambda r: r[\"query_seq_len\"]\n )\n return torch.utils.data.DataLoader(train_dataset, batch_sampler=batch_sampler,\n num_workers=1,\n collate_fn=self.collate_train)\n\n def valid_dataloader(self):\n return torch.utils.data.DataLoader(self.datasets[\"valid\"], shuffle=True, batch_size=self.batch_size,\n num_workers=1,\n collate_fn=self.collate_eval)\n\n def test_dataloader(self):\n return torch.utils.data.DataLoader(self.datasets[\"test\"], shuffle=False, batch_size=self.batch_size,\n num_workers=1,\n collate_fn=self.collate_eval)\n\n def collate_eval(self, batch):\n return self.collate(batch, False)\n\n def collate_train(self, batch):\n return self.collate(batch, True)\n\n def collate(self, batch, is_train):\n \"\"\"\n Combines pos and neg contexts. Samples randomly limited number of pos/neg contexts if is_train is True.\n \"\"\"\n for row in batch:\n # sample positive contexts\n contexts_pos_ids = row[\"contexts_pos_ids\"]\n if (is_train or self.limit_eval) and self.max_positive > 0:\n if is_train and self.ctxs_random_sample:\n contexts_pos_ids = random.sample(contexts_pos_ids, min(len(contexts_pos_ids),self.max_positive))\n else: \n contexts_pos_ids = contexts_pos_ids[:self.max_positive]\n \n # sample negative contexts\n contexts_neg_ids = row[\"contexts_neg_ids\"]\n if (is_train or self.limit_eval) and self.max_negative > 0:\n if is_train and self.ctxs_random_sample:\n contexts_neg_ids = random.sample(contexts_neg_ids, self.max_negative) \n else:\n contexts_neg_ids = contexts_neg_ids[:self.max_negative]\n \n row[\"contexts_ids\"] = contexts_pos_ids + contexts_neg_ids\n row[\"contexts_is_pos\"] = torch.Tensor([1] * len(contexts_pos_ids) + [0] * len(contexts_neg_ids))\n\n row.pop(\"contexts_pos_ids\")\n row.pop(\"contexts_neg_ids\")\n\n return self._collate(batch, pad_columns=('query_ids',\n 'contexts_is_pos'),\n pad_columns_2d=('contexts_ids',)\n )\n\n def pad_sequence_2d(self, sequences:List[List[Tensor]], \n batch_first:bool=False, \n padding_value=0.0):\n # type: (List[List[Tensor]], bool, float) -> Tensor\n r\"\"\"Pad a list of variable length Tensors with ``padding_value``\n\n ``pad_sequence`` stacks a list of Tensors along a new dimension,\n and pads them to equal length. For example, if the input is list of\n sequences with size ``L x *`` and if batch_first is False, and ``T x B x *``\n otherwise.\n\n `B` is batch size. It is equal to the number of elements in ``sequences``.\n `T` is length of the longest sequence.\n `L` is length of the sequence.\n `*` is any number of trailing dimensions, including none.\n\n Example:\n >>> from torch.nn.utils.rnn import pad_sequence\n >>> a = torch.ones(25, 300)\n >>> b = torch.ones(22, 300)\n >>> c = torch.ones(15, 300)\n >>> pad_sequence([a, b, c]).size()\n torch.Size([25, 3, 300])\n\n Note:\n This function returns a Tensor of size ``T x B x *`` or ``B x T x *``\n where `T` is the length of the longest sequence. This function assumes\n trailing dimensions and type of all the Tensors in sequences are same.\n\n Arguments:\n sequences (list[Tensor]): list of variable length sequences.\n batch_first (bool, optional): output will be in ``B x T x *`` if True, or in\n ``T x B x *`` otherwise\n padding_value (float, optional): value for padded elements. Default: 0.\n\n Returns:\n Tensor of size ``T x B x *`` if :attr:`batch_first` is ``False``.\n Tensor of size ``B x T x *`` otherwise\n \"\"\"\n\n # assuming trailing dimensions and type of all the Tensors\n # in sequences are same and fetching those from sequences[0]\n \n max_len = max([len(s) for s in sequences])\n max_dim = max([max([s2.size(0) for s2 in s1]) for s1 in sequences])\n batch_size = len(sequences)\n if batch_first:\n out_dims = (batch_size, max_len, max_dim)\n else:\n out_dims = (max_len, batch_size, max_dim)\n\n out_tensor = sequences[0][0].new_full(out_dims, padding_value)\n for i, tensor_list in enumerate(sequences):\n # use index notation to prevent duplicate references to the tensor\n for i2, tensor in enumerate(tensor_list):\n length = tensor.size(0)\n # batch first\n out_tensor[i, i2, :length] = tensor\n \n return out_tensor\n\n def _collate(self, batch, pad_columns, pad_columns_2d):\n columnar_data = defaultdict(list)\n for row in batch:\n for column, value in row.items():\n columnar_data[column].append(value)\n\n padded = {}\n for column, v in columnar_data.items():\n if pad_columns_2d and column in pad_columns_2d:\n padded[column] = self.pad_sequence_2d(v, batch_first=True)\n elif pad_columns and column in pad_columns:\n padded[column] = pad_sequence(v, batch_first=True)\n else:\n padded[column] = torch.tensor(v, dtype=torch.long)\n return padded\n","sub_path":"stl_text/datamodule/dpr.py","file_name":"dpr.py","file_ext":"py","file_size_in_byte":10788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"37738256","text":"from serial import *\r\nfrom time import *\r\n\r\nstring = \"Hallo\"\r\nbitZ = 0.5\r\n\r\ns = Serial('com1')\r\n\r\nfor c in string:\r\n binChar = format(ord(c), '#08b')\r\n s.setRTS(1)\r\n sleep(bitZ)\r\n for i in range(8):\r\n s.setRTS(binChar[i] == '1')\r\n sleep(bitZ)\r\n#s.setRTS(0)\r\n \r\n\r\ns.setRTS(0)\r\nprint(\"Fertig!\")\r\n","sub_path":"Netzwerke/Serial/Sender.py","file_name":"Sender.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"229286729","text":"import pymongo, gridfs\ndef main():\n client = pymongo.MongoClient(\"mongodb+srv://erinruby:colorado18@yame-project-6ex3z.mongodb.net/test?retryWrites=true\") #ERIN's LOGIN\n db = client.prototype #name of the db\n col = client.people #name of the collection\n db.people.delete_many({})\n\n fs=gridfs.GridFS(db)\n db.fs.files.delete_many({})\n db.fs.chunks.delete_many({})\n\nif __name__ == '__main__':\n main()\n","sub_path":"db/clear_db.py","file_name":"clear_db.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"374889275","text":"#For road segmentation\nimport torch\nimport argparse\nimport os\nimport torchvision\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data.sampler import SubsetRandomSampler\nfrom torchvision.utils import save_image\nfrom torch import nn, optim\nfrom torchvision.transforms import transforms\nfrom torch.optim import lr_scheduler\nfrom ESPNET import ESPNet,ESPNet_Encoder\nfrom dataset import RoadDataset\nfrom metrics import RunningConfusionMatrix\nfrom IOUEval import iouEval\nimport numpy as np\nimport PIL.Image as Image\nimport matplotlib.pyplot as plt\nimport cv2\n\n# 是否使用cuda\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nx_main = transforms.Compose([\n transforms.Resize((256,512)),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406],std=[0.229, 0.224, 0.225]),\n #\n ])\nx_scale1 = transforms.Compose([\n transforms.Resize((768,1536)), \n #transforms.RandomCrop(128),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406],std=[0.229, 0.224, 0.225]),\n #\n ])\nx_scale2 = transforms.Compose([\n transforms.Resize((720,1280)), \n #transforms.RandomCrop(64),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406],std=[0.229, 0.224, 0.225]),\n #\n ])\nx_scale3 = transforms.Compose([\n transforms.Resize((512,1024)), \n #transforms.RandomCrop(32),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406],std=[0.229, 0.224, 0.225]),\n #\n ])\nx_scale4 = transforms.Compose([\n transforms.Resize((384, 768)), \n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406],std=[0.229, 0.224, 0.225]),\n #\n ])\nx_val = transforms.Compose([\n transforms.Resize((256, 512)),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406],std=[0.229, 0.224, 0.225]),\n #\n ])\n#y_transforms = transforms.ToTensor()\ny_main = transforms.Compose([\n transforms.Resize((256,512)),]) \ny_scale1 = transforms.Compose([\n transforms.Resize((768,1536)),])\ny_scale2 = transforms.Compose([\n transforms.Resize((720,1280)),])\ny_scale3 = transforms.Compose([\n transforms.Resize((512,1024)),])\ny_scale4 = transforms.Compose([\n transforms.Resize((384,768)),])\ny_val = transforms.Compose([\n transforms.Resize((256,512)),])\nnclass=12 # 0 background\nIGNORE_LABEL = 0\ndef validation(epoch,model, criterion, optimizer, val_loader):\n iouEvalVal = iouEval(nclass)\n model.eval()\n step=0\n epoch_loss = 0\n epoch_mIOU = 0\n epoch_acc = 0. \n dt_size = len(val_loader.dataset)\n with torch.no_grad():\n for x, y in val_loader:\n step += 1\n inputs = x.to(device)\n labels = y.to(device)\n # zero the parameter gradients\n # forward\n outputs = model(inputs)\n loss = criterion(outputs, labels)\n epoch_loss += loss.item()\n print(\"%d/%d,val_loss:%0.5f \" % (step, len(val_loader), loss.item()))\n #mIOU\n output = torch.softmax(outputs,dim=1)\n iouEvalVal.addBatch(output.max(1)[1].data, labels.data)\n overall_acc, per_class_acc, per_class_iou, mIOU = iouEvalVal.getMetric()\n print(\"epoch %d val_loss:%0.5f \" % (epoch+1, epoch_loss/step))\n print(\"overall_acc :\",overall_acc)\n print(\"per_class_acc :\",per_class_acc)\n print(\"per_class_iou :\",per_class_iou)\n print(\"mIOU :\",mIOU)\n return epoch_loss/step , overall_acc, per_class_acc, per_class_iou, mIOU\n\n\ndef train_model(model, criterion, optimizer, train_loader, scheduler, epoch, num_epochs):\n iouEvalTrain = iouEval(nclass)\n #scheduler.step()\n dt_size = len(train_loader.dataset)\n epoch_loss = 0\n step = 0\n #num_correct = 0\n for x, y in train_loader:\n num_correct = 0\n step += 1\n inputs = x.to(device)\n labels = y.to(device)\n # zero the parameter gradients\n optimizer.zero_grad()\n # forward\n outputs = model(inputs)\n loss = criterion(outputs, labels)\n loss.backward()\n optimizer.step()\n epoch_loss += loss.item()\n \n output = torch.softmax(outputs,dim=1)\n iouEvalTrain.addBatch(output.max(1)[1].data, labels.data)\n \n print(\"%d/%d,train_loss:%0.5f \" % (step, len(train_loader), loss.item()))\n overall_acc, per_class_acc, per_class_iou, mIOU = iouEvalTrain.getMetric()\n print(\"overall_acc :\",overall_acc)\n print(\"per_class_acc :\",per_class_acc)\n print(\"per_class_iou :\",per_class_iou)\n print(\"mIOU :\",mIOU)\n \n torch.save(model.state_dict(), 'ESPNet_Line_multiscale_256_512_weights_epoch_%d.pth' % num_epochs)\n return epoch_loss/step, overall_acc, per_class_acc, per_class_iou, mIOU\n\n#训练模型\ndef train(args):\n num_epochs = 30\n step_size = 50\n gamma = 0.5\n model = ESPNet(12, p=2, q=3).to(device)\n batch_size = args.batch_size\n optimizer = optim.Adam(model.parameters(), weight_decay=1e-5)\n scheduler = lr_scheduler.StepLR(optimizer, step_size=step_size, gamma=gamma) # decay LR by a factor of 0.5 every 30 epochs\n #criterion = nn.CrossEntropyLoss(ignore_index=IGNORE_LABEL,reduction='mean')\n criterion = nn.CrossEntropyLoss()\n road_dataset= RoadDataset(\"./data/training/\",transform=x_main,target_transform=y_main)\n road_dataset_scale1 = RoadDataset(\"./data/training/\",transform=x_scale1,target_transform=y_scale1)\n road_dataset_scale2 = RoadDataset(\"./data/training/\",transform=x_scale2,target_transform=y_scale2)\n road_dataset_scale3 = RoadDataset(\"./data/training/\",transform=x_scale3,target_transform=y_scale3)\n road_dataset_scale4 = RoadDataset(\"./data/training/\",transform=x_scale4,target_transform=y_scale4)\n road_dataset_val = RoadDataset(\"./data/training/\",transform=x_val,target_transform=y_val)\n #split training and validation\n validation_split = .2\n shuffle_dataset = True\n dataset_size = len(road_dataset)\n indices = list(range(dataset_size))\n split = int(np.floor(validation_split * dataset_size))\n if shuffle_dataset :\n #np.random.seed(random_seed)\n np.random.shuffle(indices)\n train_indices, val_indices = indices[split:], indices[:split]\n train_sampler = SubsetRandomSampler(train_indices)\n valid_sampler = SubsetRandomSampler(val_indices)\n #multi-scale dataloader\n train_loader = DataLoader(road_dataset, batch_size=batch_size, sampler=train_sampler)\n train_loaderscale1 = DataLoader(road_dataset_scale1, batch_size=batch_size, sampler=train_sampler)\n train_loaderscale2 = DataLoader(road_dataset_scale2, batch_size=batch_size, sampler=train_sampler)\n train_loaderscale3 = DataLoader(road_dataset_scale3, batch_size=batch_size, sampler=train_sampler)\n train_loaderscale4 = DataLoader(road_dataset_scale4, batch_size=batch_size, sampler=train_sampler)\n validation_loader = DataLoader(road_dataset_val, batch_size=batch_size,sampler=valid_sampler)\n \n for epoch in range(num_epochs):\n print(\"epoch: %d/%d\" %(epoch+1,num_epochs)) \n print(\"scale : 768x1536\")\n train_model(model, criterion, optimizer, train_loaderscale1, scheduler, epoch, num_epochs)\n print(\"scale : 720x1280\")\n train_model(model, criterion, optimizer, train_loaderscale2, scheduler, epoch, num_epochs)\n print(\"scale : 512x1024\")\n train_model(model, criterion, optimizer, train_loaderscale3, scheduler, epoch, num_epochs)\n print(\"scale : 384x768\")\n train_model(model, criterion, optimizer, train_loaderscale4, scheduler, epoch, num_epochs)\n print(\"scale : 256x512\")\n epoch_loss, overall_acc, per_class_acc, per_class_iou, mIOU = train_model(model, criterion, optimizer, train_loader,scheduler, epoch, num_epochs)\n print(\"scale : 256x512\")\n valepoch_loss,valoverall_acc, valper_class_acc, valper_class_iou, valmIOU = validation(epoch, model, criterion, optimizer, validation_loader)\n \n fp = open(\"ESPNet_Line_multiscale_256_512_epoch_%d.txt\" % num_epochs, \"a\")\n fp.write(\"epoch %d train_loss:%0.3f \\n\" % (epoch+1, epoch_loss))\n fp.write(\"train overall_acc:%0.3f \\n\"%(overall_acc))\n fp.write(\"train per_class_acc: \")\n fp.write(str(per_class_acc))\n fp.write(\"\\n\")\n fp.write(\"train per_class_iou: \")\n fp.write(str(per_class_iou))\n fp.write(\"\\n\")\n fp.write(\"train mIOU:%0.3f\\n\"% (mIOU))\n fp.write(\"epoch %d val_loss:%0.3f \\n\" % (epoch+1, valepoch_loss))\n fp.write(\"val overall_acc:%0.3f \\n\" % (valoverall_acc))\n fp.write(\"val per_class_acc: \")\n fp.write(str(valper_class_acc))\n fp.write(\"\\n\")\n fp.write(\"vak per_class_iou: \")\n fp.write(str(valper_class_iou))\n fp.write(\"\\n\")\n fp.write(\"val mIOU:%0.3f\\n\"% (valmIOU))\n fp.write(\"\\n\")\n fp.close()\ndef Val(args):\n model = ESPNet(12, p=2, q=3).to(device)\n model.load_state_dict(torch.load(args.ckpt,map_location='cpu'))\n batch_size = args.batch_size\n criterion = nn.CrossEntropyLoss()\n optimizer = optim.Adam(model.parameters(), weight_decay=1e-5)\n road_dataset= RoadDataset(\"./data/training/\",transform=x_transforms,target_transform=y_transforms)\n validation_split = .2\n shuffle_dataset = True\n dataset_size = len(road_dataset)\n indices = list(range(dataset_size))\n split = int(np.floor(validation_split * dataset_size))\n if shuffle_dataset :\n np.random.seed(42)\n np.random.shuffle(indices)\n train_indices, val_indices = indices[split:], indices[:split]\n valid_sampler = SubsetRandomSampler(val_indices)\n validation_loader = DataLoader(road_dataset, batch_size=batch_size,\n sampler=valid_sampler)\n overall_acc, per_class_acc, per_class_iu, mIOU = validation(1, model, criterion, optimizer, validation_loader)\n print(\"overall_acc:%0.3f per_class_acc:%0.3f per_class_iu:%0.3f, mIOU:%0.3f\"%(overall_acc, per_class_acc, per_class_iu, mIOU))\ndef Generate(args):\n model = ESPNet(12, p=2, q=3).to(device)\n model.load_state_dict(torch.load(args.ckpt,map_location='cpu'))\n model.eval()\n count=0\n root = './data/testing/'\n print(\"Generate...\")\n import time\n tStart = time.time()\n for filename in os.listdir(root):\n if filename == '.ipynb_checkpoints':\n continue\n imgroot=os.path.join(root+filename)\n name = filename[:-4]\n print(\"Image Processing: \",name)\n img = Image.open(imgroot)\n img = x_transforms(img)\n img = img.view(1,3,256,512) #forreference\n #img = img.view(1,3,1080,1920) #forreference\n img = img.to(device)\n with torch.no_grad():\n output = model(img)\n output = torch.softmax(output,dim=1)\n N, _, h, w = output.shape\n pred = output.transpose(0, 2).transpose(3, 1).reshape(-1, 12).argmax(axis=1).reshape(N, h, w) #class 12\n pred = pred.squeeze(0)\n print(np.unique(pred.cpu()))\n Decode_image(pred,name)\n tEnd = time.time()#計時結束\n #列印結果\n print (\"It cost %f sec\" % (tEnd - tStart))#會自動做近位\n\ndef Decode_image(img_n,name):\n pallete = [[0,0,0] , \n [255, 0, 255], [128, 0, 128], [0, 64, 64], [0, 0, 0], [0, 0, 0], \n [255, 0, 0], [0, 255, 0], [255, 0, 0], [0, 0, 255], [255, 255, 0], \n [255, 0, 255]]\n img_n = img_n.cpu()\n img_ans=np.zeros((img_n.shape[0],img_n.shape[1],3), dtype=np.int) #class 12\n for idx in range(len(pallete)):\n [b, g, r] = pallete[idx]\n img_ans[img_n == idx] = [b, g, r] \n im_ans = Image.fromarray(np.uint8(img_ans)).convert('RGB') \n im_ans = cv2.cvtColor(np.array(im_ans),cv2.COLOR_RGB2BGR) \n #return im_ans \n cv2.imwrite(\"./Result/\"+name+\"_espnet_pred_30_nojitter.png\",im_ans)\nif __name__ == '__main__':\n #参数解析\n parse=argparse.ArgumentParser()\n parse = argparse.ArgumentParser()\n parse.add_argument(\"action\", type=str, help=\"train or test\")\n parse.add_argument(\"--batch_size\", type=int, default=16)\n parse.add_argument(\"--ckpt\", type=str, help=\"the path of model weight file\")\n args = parse.parse_args()\n\n if args.action==\"train\":\n train(args)\n elif args.action==\"test\":\n test(args)\n elif args.action==\"model\":\n Model_visualization(args)\n elif args.action==\"generate\":\n Generate(args)\n elif args.action==\"oonx\":\n oonx(args)\n elif args.action==\"check\":\n check_label(args)\n elif args.action==\"iou\":\n Val(args)\n \n\n\n","sub_path":"trainespnet.py","file_name":"trainespnet.py","file_ext":"py","file_size_in_byte":12949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"173293634","text":"# -*- coding: utf-8 -*-\nimport pika\nimport logging\nimport traceback\nimport json\nimport se.api\nfrom bs4 import BeautifulSoup\n\n\nclass Dullu:\n RABBITMQ_QUEUE_URL_NAME = 'dullu_url_queue'\n RABBITMQ_QUEUE_ENTITY_NAME = 'dull_entity_queue'\n\n # Entity queue, up for change though. Other side not coded.\n JSON_KEY__ENTITYQ__ID = 'Id'\n JSON_KEY__ENTITYQ__TYPE = 'PostTypeId'\n JSON_KEY__ENTITYQ__BODY = 'Body'\n\n # URL queue\n JSON_KEY__URLQ__ENTITY_ID = 'entity_id'\n JSON_KEY__URLQ__ENTITY_TYPE = 'entity_type'\n JSON_KEY__URLQ__ATTEMPTS = 'attempts'\n JSON_KEY__URLQ__URL = 'url'\n JSON_KEY__URLQ__LAST_TEST_CODE = 'last_code'\n JSON_KEY__URLQ__LAST_TEST_STAMP = 'last_stamp'\n JSON_KEY__URLQ__LAST_CHECKBOT = 'last_checker'\n\n def __init__(self, broker_address='localhost'):\n self.broker_address = broker_address\n\n def callback_scan_entity_for_urls(self, ch, method, properties, body):\n logging.debug(\"Received entity from broker.\")\n\n try:\n json_dict = json.loads(body.decode())\n except json.decoder.JSONDecodeError as jsonde:\n logging.error(\"Oops! Couldn't decode that request. Caught {0}. Body = [{1}]. \".format(jsonde, body))\n\n ch.basic_reject(delivery_tag=method.delivery_tag, requeue=False)\n return\n\n if not all(k in json_dict for k in (self.JSON_KEY__ENTITYQ__ID, self.JSON_KEY__ENTITYQ__TYPE, self.JSON_KEY__ENTITYQ__BODY)):\n logging.error(\"Rejecting request. Missing information ({k1}:{v1},{k2}:{v2},{k3}:{v3}).\".format(\n k1=self.JSON_KEY__ENTITYQ__ID,\n k2=self.JSON_KEY__ENTITYQ__TYPE,\n k3=self.JSON_KEY__ENTITYQ__BODY,\n v1=self.JSON_KEY__ENTITYQ__ID in json_dict,\n v2=self.JSON_KEY__ENTITYQ__TYPE in json_dict,\n v3=self.JSON_KEY__ENTITYQ__BODY in json_dict))\n\n ch.basic_reject(delivery_tag=method.delivery_tag, requeue=False)\n return\n\n \"\"\"\n We currently only process certain different types of entities. questions/answers (hopefully comments and docs)\n in the future. We may need special handling for them depending on how eridu ends up working.\n \"\"\"\n\n try:\n entity_type = se.api.PostType(json_dict[self.JSON_KEY__ENTITYQ__TYPE])\n except ValueError as ve:\n logging.error(\"Received an entity we're unwilling to process [{0}]. \".format(json_dict[self.JSON_KEY__ENTITYQ__TYPE]))\n ch.basic_reject(delivery_tag=method.delivery_tag, requeue=False)\n return\n\n urls = get_all_urls(json_dict[self.JSON_KEY__ENTITYQ__BODY])\n\n url_dict = {self.JSON_KEY__URLQ__ENTITY_ID: json_dict[self.JSON_KEY__ENTITYQ__ID],\n self.JSON_KEY__URLQ__ENTITY_TYPE: json_dict[self.JSON_KEY__ENTITYQ__TYPE]}\n\n for url in urls:\n url_dict[self.JSON_KEY__URLQ__URL] = url\n self.channel.basic_publish(exchange=\"\",\n routing_key=Dullu.RABBITMQ_QUEUE_URL_NAME,\n body=json.dumps(url_dict))\n\n ch.basic_ack(delivery_tag=method.delivery_tag)\n\n\n def run(self):\n \"\"\"\n This will set up the link bot and connect to the broker. If the channel doesn't yet exist, it will create it\n on the broker (shouldn't actually happen unless someone runs things in the wrong order).\n\n channel.start_consuming is a blocking function.\n :return:\n \"\"\"\n logging.info(\"Attempting to connect to broker at: {0}.\".format(self.broker_address))\n connection = pika.BlockingConnection(pika.ConnectionParameters(self.broker_address))\n\n try:\n self.channel = connection.channel()\n\n # Connect to url queue\n self.channel.queue_declare(queue=self.RABBITMQ_QUEUE_URL_NAME, durable=True)\n\n # Connect to entity queue\n self.channel.queue_declare(queue=self.RABBITMQ_QUEUE_ENTITY_NAME, durable=True)\n self.channel.basic_consume(self.callback_scan_entity_for_urls, queue=self.RABBITMQ_QUEUE_ENTITY_NAME, no_ack=False)\n self.channel.basic_qos(prefetch_count=1)\n logging.info(\"Ready to start consuming\")\n self.channel.start_consuming()\n except Exception as e:\n logging.warning(\"Exception detected.\")\n logging.error(traceback.format_exc())\n raise e\n finally:\n logging.info(\"Dullu instance terminating...\")\n connection.close()\n logging.debug(\"Fin.\")\n\ndef get_all_urls(s):\n \"\"\"\n Find all the urls in the text and stick them in a list for later processing.\n\n :param s: Input string\n :return: List of links\n \"\"\"\n soup = BeautifulSoup(s, \"html.parser\")\n return [link.get('href') for link in soup.find_all('a')]\n","sub_path":"dullu/dullu.py","file_name":"dullu.py","file_ext":"py","file_size_in_byte":4857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"373411266","text":"from item import Item\n\n\n# This is the key object\nclass OldKey(Item):\n def __init__(self):\n self.name = \"old key\"\n super().__init__(self.name)\n\n @staticmethod\n def description():\n print(\"\\nThis is an old key. You wonder what it opens...\\n\")\n\n\nif __name__ == \"__main__\":\n key = OldKey()\n key.description()\n print(key)","sub_path":"CS 467/Capstone Project/oldKey.py","file_name":"oldKey.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"533199926","text":"import numpy as np \nimport cv2\nimport sys\nimport cPickle as pickle\nimport scipy.signal\n\nf=open('videorecord.txt', 'r')\n\nrows,cols = 480,640\nn=0\nN = 2\nframe = np.zeros((480,640,3))\nframe1 = np.zeros((480,640,3))\nsampledCb = np.zeros((rows,cols)) #subsample Matrix\nsampledCr = np.zeros((rows,cols))\n\nfilt1=np.ones((N,N))/N;\nfilt2=scipy.signal.convolve2d(filt1,filt1)/N\n\nvideolist=np.load(f)\n\nfftMr=np.ones((rows,1)) # FFT matrix\nfftMr[int(rows/8.0):int(rows-rows/8.0),0]=np.zeros(int(3.0/4.0*rows))\nfftMc=np.ones((1,cols)) \nfftMc[0,int(cols/8.0):int(cols-cols/8.0)]=np.zeros(int(3.0/4.0*cols));\nfftM=np.dot(fftMr,fftMc)\n\nwhile(True):\n\n Y,Cb,Cr = videolist[n*3],videolist[n*3+1],videolist[n*3+2] #convert YCbCr to rgb\n n = n+1;\n sampledCb[0::N,0::N] = Cb\n sampledCr[0::N,0::N] = Cr\n Cb=scipy.signal.convolve2d(sampledCb,filt1,mode='same')\n Cr=scipy.signal.convolve2d(sampledCr,filt1,mode='same')\n\n\n #cv2.imshow('Y',Y)\n #cv2.imshow('cb',Cb)\n #cv2.imshow('cr',Cr)\n\n Y = Y*255\n Cb = Cb*255-128\n Cr = Cr*255-128\n\n r = (Y+Cr*1.4025)\n g = (Y+Cb*(-0.34434)+Cr*(-0.7144))\n b = (Y+Cb*1.7731)\n\n frame[:,:,0],frame[:,:,1],frame[:,:,2] = b,g,r\n\n cv2.imshow('Video',frame/255)\n\n if cv2.waitKey(40) & 0xFF == ord('q'):\n break\n\ncv2.destroyAllWindows()\n","sub_path":"Seminar 4/decoder.py","file_name":"decoder.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"349990770","text":"from selenium import webdriver\nfrom lxml import html\nfrom datetime import datetime\nimport time, platform, sys\n\ndef is_Prime(is3):\n if(is3):\n prime = input(\"Is this a prime account? \")\n else:\n prime = raw_input(\"Is this a prime account? \")\n\n if(prime == \"Y\" or prime == \"y\" or prime == \"Yes\" or prime == \"yes\"):\n return True\n elif(prime == \"N\" or prime == \"n\" or prime == \"No\" or prime == \"no\"):\n return False\n else:\n return is_Prime(is3)\n\ndef is_valid(input):\n if((verify != 'y') and (verify != 'Y') and (verify != 'Yes') and (verify != \"yes\")):\n return False\n else:\n return True\n\ndef second_Cart(interval, tree, i):\n cart = tree.xpath('//input[@id=\"bb_atc_button\"]')\n if(len(cart) > 0):\n search = br.find_element_by_xpath('//input[@id=\"bb_atc_button\"]')\n if(search.is_displayed()):\n search.click()\n return True\n else:\n return watch_Cart(interval, i)\n else:\n return watch_Cart(interval, i)\n\ndef watch_Cart(interval, i):\n if(i == 0):\n print(\"\\nAssuming this item is not available yet and are waiting for pre-order.\")\n print(\"Software will check page every \" +str(interval)+ \" seconds.\")\n print(\"If this is not the case, please exit the software and try again.\")\n else:\n print(\"\\nRefresh page count: \"+str(i)+\" at \"+str(datetime.now()))\n time.sleep(interval)\n return False\n\ndef click_Card(tree, br):\n time.sleep(2)\n button = tree.xpath('//span[@class=\"a-button-inner\"]')\n if(len(button) > 0):\n search = br.find_element_by_xpath('//span[@class=\"a-button-inner\"]')\n search.click()\n return False\n else:\n return click_Shipping(tree, br)\n\ndef click_Shipping(tree, br):\n time.sleep(2)\n button = tree.xpath('//span[@class=\"a-button-inner\"]')\n if(len(button) > 0):\n search = br.find_element_by_xpath('//span[@class=\"a-button-inner\"]')\n search.click()\n return False\n else:\n print(\"\\nWARNING: The Amazon order page has changed. Please contact the software developer\")\n exit(0)\n\n#-----------------------------------------------------------------------------------------------------------------------\n#************** END OF DEFINED FUNCTIONS *******************************************************************************\n#-----------------------------------------------------------------------------------------------------------------------\n\n# check python version before we get input\nv = str(sys.version)\nis3 = False\nif(v[0] == '3'):\n is3 = True\n\nprint(\"\\nWelcome to the Amazon buying utility!\\n\")\nprint(\"Note 1: Please note that by using this software you accept that\")\nprint(\"it probably violates Amazon's terms of service and that\")\nprint(\"I am in no way responsible for what happens to you if you\")\nprint(\"choose to use it. Thanks!\\n\")\n\nprint(\"Note 2: This utility assumes that the default mailing address\")\nprint(\"and payment option are being used. PLEASE CHECK THAT THE\")\nprint(\"DEFAULT SHIPPING ADDRESS AND PAYMENT OPTION ARE THE ONES\")\nprint(\"YOU WISH TO USE!!!!!!!!\\n\")\n\nprint(\"Note 3: Make sure you set your laptop to not sleep\")\nprint(\"or the utility will fail!\\n\\n\")\n\n# use python version for input or raw_input\n# NOTE: warnings are SUPPRESSED. Check here for errors!\nif(is3):\n username = input(\"Please enter your Amazon Email: \")\n password = input(\"Please enter your Amazon password: \")\n prime = is_Prime(is3)\n productPage = input(\"Please enter the product URL: \")\n quantity = int(input(\"Please enter how many you want to buy: \"))\n updateInterval = int(input(\"Please enter the page refresh interval in seconds: \"))\nelse:\n username = raw_input(\"Please enter your Amazon Email: \")\n password = raw_input(\"Please enter your Amazon password: \")\n prime = is_Prime(is3)\n productPage = raw_input(\"Please enter the product URL: \")\n quantity = int(raw_input(\"Please enter how many you want to buy: \"))\n updateInterval = int(raw_input(\"Please enter the page refresh interval in seconds: \"))\n\n# start it up. Check host OS. Set Chromedriver path for Windows\nos = platform.platform()\nif('Windows' in os):\n br = webdriver.Chrome(executable_path='C:\\chromedriver.exe')\nelse:\n br = webdriver.Chrome()\n\nbr.implicitly_wait(3) # wait for the page to get done loading before it does anything with it\ntry:\n br.get('https://www.amazon.com/ap/signin?_encoding=UTF8&openid.assoc_handle=usflex&openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.identity=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.mode=checkid_setup&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&openid.ns.pape=http%3A%2F%2Fspecs.openid.net%2Fextensions%2Fpape%2F1.0&openid.pape.max_auth_age=0&openid.return_to=https%3A%2F%2Fwww.amazon.com%2F%3Fref_%3Dnav_signin')\nexcept:\n print(\"WARNING: The Amazon login page URL has changed. Please contact the software developer\")\n exit(0)\n\n# Log in to Amazon\ntry:\n search = br.find_element_by_name('email')\n search.send_keys(username)\nexcept:\n print(\"WARNING: The Amazon login page has changed. Please contact the software developer\")\n exit(0)\ntry:\n search = br.find_element_by_name('password')\n search.send_keys(password)\nexcept:\n print(\"WARNING: The Amazon login page has changed. Please contact the software developer\")\n exit(0)\ntry:\n search = br.find_element_by_xpath('//input[@id=\"signInSubmit-input\"]')\n search.click()\nexcept:\n print(\"WARNING: The Amazon login page has changed. Please contact the software developer\")\n exit(0)\n\ntry:\n br.get(productPage)\nexcept:\n print(\"WARNING: The URL you entered is not valid. Please restart the software and try again\")\n exit(0)\n\nif(is3):\n verify = str(input(\"\\nIs this the correct product? [Y/n] \"))\n\n while(not is_valid(verify)):\n productPage = input(\"Please enter the product URL: \")\n br.get(productPage)\n verify = str(input(\"\\nIs this the correct product? [Y/n] \"))\nelse:\n verify = str(raw_input(\"\\nIs this the correct product? [Y/n] \"))\n\n while(not is_valid(verify)):\n productPage = raw_input(\"Please enter the product URL: \")\n br.get(productPage)\n verify = str(raw_input(\"\\nIs this the correct product? [Y/n] \"))\n\nx = 0\n\n# this is where the looping starts to add and buy an amount of product\nwhile(quantity > 0):\n # This is where shit gets done (items get added to cart)\n isAdded = False\n i = 0\n\n # Checks if an item gets added to cart or watches product until it does\n while(not isAdded):\n try:\n br.get(productPage)\n except:\n print(\"WARNING: The URL you entered is not valid. Please restart the software and try again\")\n exit(0)\n\n html_source = br.page_source\n tree = html.fromstring(html_source)\n cart = tree.xpath('//input[@id=\"add-to-cart-button\"]')\n\n if(len(cart) > 0):\n search = br.find_element_by_xpath('//input[@id=\"add-to-cart-button\"]')\n if(search.is_displayed()):\n search.click()\n isAdded = True\n else:\n isAdded = second_Cart(updateInterval, tree, i)\n else:\n isAdded = second_Cart(updateInterval, tree, i)\n i += 1\n\n # get the page source checking for popups\n time.sleep(1) #THIS NEEDS TO BE HERE TO LET THE POPUPS LOAD!!!!!\n html_source = br.page_source\n tree = html.fromstring(html_source)\n\n # hit the continue button if it shows up\n button = tree.xpath('//img[@id=\"intl_pop_continue\"]')\n if(len(button) > 0):\n search = br.find_element_by_xpath('//img[@id=\"intl_pop_continue\"]')\n search.click()\n\n # hit the protection plan button if it shows up. Defaults to no protection plan\n button = tree.xpath('//button[@id=\"siNoCoverage-announce\"]')\n if(len(button)>0):\n search = br.find_element_by_xpath('//button[@id=\"siNoCoverage-announce\"]')\n search.click()\n\n # didya know there's a different protection plan button?? :D -__-\n button = tree.xpath('//a[@id=\"siNoCoverage\"]')\n if(len(button)>0):\n search = br.find_element_by_xpath('//a[@id=\"siNoCoverage\"]')\n search.click()\n\n # continue to checkout\n try:\n br.get('https://www.amazon.com/gp/cart/view.html/ref=lh_co_dup?ie=UTF8&proceedToCheckout.x=129&cartInitiateId=1428287116210&hasWorkingJavascript=1')\n except:\n print(\"\\nWARNING: The Amazon checkout URL has changed. Please contact the software developer\")\n exit(0)\n\n # Click the correct shipping option. FREE shipping for non-prime, 2 Day shipping for prime\n time.sleep(1) # let the order page load\n html_source = br.page_source\n tree = html.fromstring(html_source)\n if(prime):\n button = tree.xpath('//input[@value=\"second\"]')\n if(len(button) > 0):\n search = br.find_element_by_xpath('//input[@value=\"second\"]')\n search.click()\n else:\n button = tree.xpath('//input[@title=\"FREE Shipping\"]')\n if(len(button) > 0):\n search = br.find_element_by_xpath('//input[@title=\"FREE Shipping\"]')\n search.click()\n\n # finish order ASSUMES THE MAILING ADDRESS AND PAYMENT IS THE DEFAULT OPTIONS\n try:\n if(prime):\n search = br.find_element_by_xpath('//input[@class=\"a-button-input\"]')\n search.click()\n except:\n pass # because this is throwing an exception for no reason\n\n # the prime check out page is more difficult than the non-prime page\n if(prime):\n orderFinished = False\n while(not orderFinished):\n time.sleep(2.5) # let the dropdown load. 3s seems pretty stable\n html_source = br.page_source\n tree = html.fromstring(html_source)\n button = tree.xpath('//span[@class=\"a-button a-button-primary continue-button place-order-button-link buy-button-height\"]')\n if(len(button) > 0):\n search = br.find_element_by_xpath('//span[@class=\"a-button a-button-primary continue-button place-order-button-link buy-button-height\"]')\n #search.click() # to actually buy the product\n print(\"\\nPurchase button echo: \"+str(search.id)) # for testing purposes\n orderFinished = True\n else:\n orderFinished = click_Card(tree, br)\n else:\n try:\n time.sleep(1)\n search = br.find_element_by_xpath('//input[@name=\"placeYourOrder1\"]')\n #print(\"\\nPurchase button echo: \"+str(search.id)) # for testing\n search.click() # to actually buy\n except:\n pass\n\n print(\"\\nPurchased item count: \" +str(x+1)+\" at \"+str(datetime.now()))\n\n x += 1\n quantity -= 1\n\nprint(\"\\nScript is complete! You are now probably broke!\")\nexit(0)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"262364562","text":"\"\"\"\nWrite a Python program to match a string that contains\nonly upper and lowercase letters, numbers, and underscores.\n\n\nWrite a Python program where a string will start with a specific number\n\n\nWrite a Python program to check for a number at the end of a string\n\n\"\"\"\n\nimport re\ndef startnumber(text):\n pattern='^[0-9]+'\n if re.search(pattern,text):\n return \"string starts with a specific number \" + text\n else:\n return \"\"\n\n\ndef endnumber(text):\n pattern='[0-9]+$'\n if re.search(pattern,text):\n return \"string ends with a specific number \" + text\n else:\n return \"\"\n\n\n\ndef text_match(text):\n pattern='^[a-zA-Z0-9_]*$'\n if re.search(pattern,text):\n return \"only upper and lowercase letters, numbers, and underscores. \" + text\n else:\n return \"\"\n\n\nprint(text_match(\"The quick brown fox jumps over the lazy dog.\"))\nprint(text_match(\"Python_Exercises_1\"))\nprint\nprint(startnumber(\"23The quick brown fox jumps over the lazy dog.\"))\nprint(startnumber(\"5-2345861\"))\nprint(startnumber(\"The quick brown fox jumps over the lazy dog.\"))\nprint\nprint(endnumber(\"23The quick brown fox jumps over the lazy dog.\"))\nprint(endnumber(\"5-2345861\"))\nprint(endnumber(\"The quick brown fox jumps over the lazy dog.\"))","sub_path":"regex/regex8.py","file_name":"regex8.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"417549980","text":"from django.conf import settings\nfrom django.shortcuts import render, get_object_or_404\n\nfrom djlime.utils.pagination import paginator_factory\n\nfrom models import News\n\nNEWS_LIST_TEMPLATE = \\\ngetattr(settings, 'NEWS_LIST_TEMPLATE', 'news/news_list.html')\nNEWS_DETAIL_TEMPLATE = \\\ngetattr(settings, 'NEWS_DETAIL_TEMPLATE', 'news/news_detail.html')\nNEWS_PER_PAGE = \\\ngetattr(settings, 'NEWS_PER_PAGE', 4)\n\ndef news_list(request):\n news_objects = paginator_factory(request, News.objects.all(), NEWS_PER_PAGE)\n return render(request, NEWS_LIST_TEMPLATE, {'news_list': news_objects})\n\ndef news_detail(request, news_id):\n news = get_object_or_404(News, id=news_id)\n return render(request, NEWS_DETAIL_TEMPLATE, {'news': news})\n","sub_path":"news/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"585881876","text":"# This spider will crawl an entire website to see if there are any broken links\n\n\nfrom scrapy.spiders import CrawlSpider, Rule\nfrom scrapy.linkextractors import LinkExtractor\n\nfrom brokenlink.items import BrokenlinkItem\n\n\nclass BrokenLink(CrawlSpider):\n name = 'broken'\n start_urls = ['http://localhost:8081/']\n\n rules = (\n Rule(LinkExtractor(), callback='parse_item', follow=True),\n )\n\n def parse_item(self, response):\n # Testing purposes\n if response.status == 200:\n print('ok BRO !')\n\n if response.status == 404:\n item = BrokenlinkItem()\n item['url'] = response.url\n item['status'] = response.status\n\n yield item\n","sub_path":"brokenlink/spiders/BrokenLink.py","file_name":"BrokenLink.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"587871093","text":"import logging\n\nfrom invoke import task, run\n\nimport aws\nimport utils\nimport config\n\nlogger = logging.getLogger(__name__)\nlogging.basicConfig(level=logging.INFO)\n\n@task\ndef requirements(upgrade=True):\n cmd = 'pip install -r requirements.txt'\n if upgrade:\n cmd += ' --upgrade'\n run(cmd)\n\n@task\ndef apify(filename, tablename=None):\n tablename = tablename or utils.get_name(filename)\n logger.info('Importing {0} to table {1}'.format(filename, tablename))\n utils.drop_table(tablename)\n utils.load_table(filename, tablename)\n utils.index_table(tablename, config.CASE_INSENSITIVE)\n logger.info('Finished importing {0}'.format(filename))\n\n@task\ndef fetch_bucket(bucket_name=None):\n aws.fetch_bucket(bucket_name)\n","sub_path":"tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"390961940","text":"import pymongo\nimport time\n\nfrom appium import webdriver\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.common.exceptions import NoSuchElementException\n\nPLATFORM = \"Android\"\nDEVICE_NAME = \"\"\nAPP_PACKAGE = \"com.rong360.app\"\nAPP_ACTIVITY = \".activity.GuideActivity\"\n\nDRIVER_SERVER = \"http://localhost:4723/wd/hub\"\nTIMEOUT = 5\n\n\nclass Action(object):\n def __init__(self):\n self.desired_caps = {\n \"platformName\": PLATFORM,\n \"deviceName\": DEVICE_NAME,\n \"appPackage\": APP_PACKAGE,\n \"appActivity\": APP_ACTIVITY\n }\n self.driver = webdriver.Remote(DRIVER_SERVER, self.desired_caps)\n self.wait = WebDriverWait(self.driver, TIMEOUT)\n\n def evalute(self):\n fuck = self.driver.find_element_by_id(\"com.rong360.app:id/title_tv\").text\n if \"卖萌求好评,你到底是不是真的喜欢我们\" in fuck:\n self.driver.tap([(350, 957)])\n return True\n else:\n return False\n\n def enter(self):\n time.sleep(5)\n self.driver.tap([(442, 1290)])\n time.sleep(5)\n self.driver.swipe(619, 538, 205, 549)\n time.sleep(1)\n self.driver.tap([(682, 535)])\n time.sleep(3)\n\n def gogogo(self):\n\n # 50一次\n for i in range(50):\n time.sleep(2)\n self.driver.swipe(361, 1200, 361, 160, duration=400)\n time.sleep(2)\n self.driver.swipe(361, 1200, 361, 160, duration=400)\n time.sleep(2)\n self.driver.swipe(361, 1200, 361, 160, duration=400)\n # time.sleep(2)\n print(i)\n\n def work(self):\n for i in range(4):\n h = 120*i + 280\n self.driver.tap([(160, h)])\n time.sleep(3)\n\n pre_title = \"\"\n repeat = 0 # title重复次数\n\n num = 0\n\n self.gogogo()\n\n while True:\n\n title = self.driver.find_element_by_xpath(\"//android.widget.TextView[@resource-id='com.rong360.app:id/luntan_list_title']\")\n print(title.text.strip())\n now_title = title.text.strip()\n\n if now_title != pre_title:\n num += 1\n print(num)\n repeat = 0\n title.click()\n time.sleep(2)\n\n try:\n reply_num = self.driver.find_element_by_id(\"com.rong360.app:id/tv_reply_num\")\n for j in range(int(reply_num.text) // 20):\n time.sleep(2)\n self.driver.swipe(361, 1200, 361, 160, duration=400)\n time.sleep(2)\n self.driver.swipe(361, 1200, 361, 160, duration=400)\n time.sleep(2)\n self.driver.swipe(361, 1200, 361, 160, duration=400)\n time.sleep(2)\n self.driver.swipe(361, 1200, 361, 160, duration=400)\n time.sleep(3)\n except NoSuchElementException:\n pass\n\n detail_back = self.driver.find_element_by_id(\"com.rong360.app:id/activity_bbs_view_thread_back\")\n detail_back.click()\n time.sleep(1)\n\n try:\n self.evalute()\n except:\n pass\n else:\n repeat += 1\n if repeat == 6:\n back = self.driver.find_element_by_id(\"com.rong360.app:id/btn_back\")\n back.click()\n break\n self.driver.swipe(58, 714, 58, 545)\n time.sleep(1)\n pre_title = now_title\n\n\nif __name__ == '__main__':\n action = Action()\n action.enter()\n action.work()\n","sub_path":"rong_bbs.py","file_name":"rong_bbs.py","file_ext":"py","file_size_in_byte":3921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"270024945","text":"from flask import Flask, render_template, redirect, request, session\r\napp = Flask(__name__)\r\napp.secret_key = 'admin'\r\n\r\nimport random\r\n\r\n@app.route('/')\r\ndef index():\r\n if 'game' in session:\r\n print('Session #:', session['game'])\r\n pass\r\n else:\r\n game = random.randrange(0, 101)\r\n session['game'] = game\r\n print('New Random #:', session['game'])\r\n return render_template('index.html')\r\n\r\n@app.route('/guess', methods=['POST'])\r\ndef guess():\r\n print('--Guess Received!--')\r\n session['guess'] = request.form['guess']\r\n guess = int(session['guess'])\r\n print('Player Guess is:', guess)\r\n # print(type(guess))\r\n # print(type(session['game']))\r\n if guess == session['game']:\r\n session['answer'] = 1\r\n print(session['answer'])\r\n if guess > session['game']:\r\n session['answer'] = 2\r\n if guess < session['game']:\r\n session['answer'] = 0\r\n return redirect('/')\r\n\r\n@app.route('/reset')\r\ndef reset():\r\n session.pop('game')\r\n session.pop('guess')\r\n session.pop('answer')\r\n return redirect('/')\r\n\r\nif __name__==\"__main__\":\r\n app.run(debug=True)","sub_path":"Great_Number_Game/Greatnumbergame.py","file_name":"Greatnumbergame.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"222199011","text":"\nfrom .models import myCourseInstructor\nfrom .models import myCourse\nfrom .models import myAccount\n\nclass assignCourseInstructor:\n def assignCourseInstructor(courseNumber, instructorUserName):\n errorMessage = \"\"\n if not (courseNumber.isnumeric()):\n errorMessage = \"Invalid Course Number!\"\n else:\n existingCourseInstructor = list(myCourseInstructor.objects.filter(courseNumber=courseNumber))\n existingCourse = list(myCourse.objects.filter(courseNumber=courseNumber))\n existingInstructor = list(\n myAccount.objects.filter(userName=instructorUserName, userType=\"Instructor\"))\n if ((len(existingCourse) == 0) and (len(existingInstructor) == 0)):\n errorMessage = \"Invalid Course Number And Instructor Username!\"\n elif ((len(existingCourse) == 0)):\n errorMessage = \"Invalid Course Number!\"\n elif ((len(existingInstructor) == 0)):\n errorMessage = \"Invalid Instructor Username!\"\n elif ((len(existingCourseInstructor) != 0)):\n errorMessage = \"This Course Already Has An Instructor!\"\n if (errorMessage != \"\"):\n return errorMessage\n else:\n newAssignment = myCourseInstructor(courseNumber=courseNumber,instructorUserName=instructorUserName)\n newAssignment.save()\n\n course = list(myCourse.objects.filter(courseNumber=courseNumber))[0]\n course.instructorUserName = instructorUserName\n course.save()\n return errorMessage","sub_path":"TA_Scheduler/assignCourseInstructor.py","file_name":"assignCourseInstructor.py","file_ext":"py","file_size_in_byte":1583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"238042967","text":"from requests import get\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nfrom typing import List, Tuple\nfrom dataclasses import dataclass, field\nfrom datetime import datetime, timedelta\nimport matplotlib.pyplot as plt\n\n\n#billboard's date format\ndate_format = '%Y-%m-%d'\n\n# homepage of hot 100 (current week)\n# prefix to all weeks\nbase_url = \"https://www.billboard.com/charts/hot-100\"\n\n# base_name of the class which contains the tracks\nbase_name = \"chart-list-item\"\n\n\n#if there is no last_week/ peek_pos or weeks_on_chart then set to -1\n@dataclass \nclass Song:\n\n title: str\n artist: str\n rank: int\n last_week: int = 500\n peak_pos: int = 500\n weeks_on_chart:int = -1\n\n@dataclass\nclass Week:\n date: datetime\n songs: List[Song] = field(default_factory=list)\n\n\n# parse html for a url\ndef simple_get(url):\n return BeautifulSoup(get(url).text, 'html.parser')\n\n# format date returned by datetime to billboard's url format\ndef format_date(date):\n return datetime.strftime(date, date_format)\n\n# go back num_days from the start\ndef date_shift(start, num_days):\n return start - timedelta(days=num_days)\n\ndef get_one_week(givendate) -> List[Song]:\n # the ratings come out on Saturday (sat is 5)\n # if the start date is not a saturday, shift and find the nearest saturday\n shift = (givendate.weekday() - 5) % 7\n chartdate = date_shift(givendate, shift)\n suffix = format_date(chartdate)\n\n html = simple_get(base_url + '/' + suffix)\n mydivs = html.findAll(\"div\", {\"class\": base_name})\n\n songs = []\n # div.attrs is a dictionary\n for div in mydivs:\n attrs = div.attrs\n s = Song(attrs['data-title'], attrs['data-artist'], int(attrs['data-rank']))\n\n s.peak_pos = int(div.find(\"div\", {\"class\": \"chart-list-item__weeks-at-one\"}).string)\n s.weeks_on_chart = int(div.find(\"div\", {\"class\": \"chart-list-item__weeks-on-chart\"}).string)\n try:\n s.last_week = int(div.find(\"div\", {\"class\": \"chart-list-item__last-week\"}).string)\n except ValueError:\n s.last_week = 500\n\n songs.append(s)\n\n return Week(datetime.strftime(chartdate, date_format),songs)\n\n# get num_weeks' data back from and including start date\ndef get_multiple_weeks(start, num_weeks)->List[Week]:\n\n weeks = []\n for i in range(num_weeks):\n week=get_one_week(start)\n weeks.append(week)\n start = date_shift(start, 7)\n\n return weeks\n\n\n#TESTING HERE\n# for song in get_curr_week():\n# print(song)\n\ntoday = datetime.today()\n\n#need nested loops to check correctness\nweeks = get_multiple_weeks(today, 1)\nprint(weeks)\n\ndef one_week_pandas(w: Week):\n df = pd.DataFrame(columns=[\"week\", \"title\", \"artist\", \"rank\", \"last_week\", \"peak_pos\", \"weeks_on_chart\"])\n df.astype({'week': 'str', \"title\": \"str\", \"artist\": \"str\", \"rank\": \"int64\", \"last_week\": \"int64\",\"peak_pos\": \"int64\", \"weeks_on_chart\": \"int64\"})\n for song in w.songs:\n s = vars(song)\n s['week'] = w.date\n df = df.append(s, ignore_index=True)\n return df\n\nw=get_one_week(today)\nchart_df = one_week_pandas(w)\nchart_df.to_csv(\"bill_week.csv\")\n\n''' everything below is matplotlib '''\n\ncolors = {\"red\": \"#FF0000\", \"green\": \"#00FF00\", \"blue\": \"#0000FF\"}\nfig = plt.figure(figsize=(20, 6), dpi=80)\nax = fig.add_subplot(111)\n\nfor i in range(0,100):\n curr_rank = chart_df[\"rank\"].loc[i]\n curr_last_week = chart_df[\"last_week\"].loc[i]\n curr_weeks_on_chart = chart_df[\"weeks_on_chart\"].loc[i]\n if curr_rank == curr_last_week:\n color = colors[\"blue\"]\n elif curr_rank > curr_last_week:\n color = colors[\"red\"]\n else:\n color = colors[\"green\"]\n ax.scatter(curr_rank, curr_weeks_on_chart, color=color)\n\nplt.xticks(chart_df[\"rank\"], chart_df.apply(lambda x : x[\"title\"] + \" \" + str(x[\"rank\"]), axis = 1), rotation='vertical')\n\nplt.xlabel(\"Ranks and titles\")\nplt.ylabel(\"# Weeks on the chart\")\nplt.show()\nplt.savefig('testplot.png')\n\n\n","sub_path":"billboard.py","file_name":"billboard.py","file_ext":"py","file_size_in_byte":3923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"567211987","text":"#!/usr/bin/python\n# @lint-avoid-python-3-compatibility-imports\n#\n# tcprtt Summarize TCP RTT as a histogram. For Linux, uses BCC, eBPF.\n#\n# USAGE: tcprtt [-h] [-T] [-D] [-m] [-i INTERVAL] [-d DURATION]\n# [-p SPORT] [-P DPORT] [-a SADDR] [-A DADDR]\n#\n# Copyright (c) 2020 zhenwei pi\n# Licensed under the Apache License, Version 2.0 (the \"License\")\n#\n# 23-AUG-2020 zhenwei pi Created this.\n\nfrom __future__ import print_function\nfrom bcc import BPF\nfrom time import sleep, strftime\nimport socket, struct\nimport argparse\n\n# arguments\nexamples = \"\"\"examples:\n ./tcprtt # summarize TCP RTT\n ./tcprtt -i 1 -d 10 # print 1 second summaries, 10 times\n ./tcprtt -m -T # summarize in millisecond, and timestamps\n ./tcprtt -p # filter for source port\n ./tcprtt -P # filter for destination port\n ./tcprtt -a # filter for source address\n ./tcprtt -A # filter for destination address\n ./tcprtt -D # show debug bpf text\n\"\"\"\nparser = argparse.ArgumentParser(\n description=\"Summarize TCP RTT as a histogram\",\n formatter_class=argparse.RawDescriptionHelpFormatter,\n epilog=examples)\nparser.add_argument(\"-i\", \"--interval\",\n help=\"summary interval, seconds\")\nparser.add_argument(\"-d\", \"--duration\", type=int, default=99999,\n help=\"total duration of trace, seconds\")\nparser.add_argument(\"-T\", \"--timestamp\", action=\"store_true\",\n help=\"include timestamp on output\")\nparser.add_argument(\"-m\", \"--milliseconds\", action=\"store_true\",\n help=\"millisecond histogram\")\nparser.add_argument(\"-p\", \"--sport\",\n help=\"source port\")\nparser.add_argument(\"-P\", \"--dport\",\n help=\"destination port\")\nparser.add_argument(\"-a\", \"--saddr\",\n help=\"source address\")\nparser.add_argument(\"-A\", \"--daddr\",\n help=\"destination address\")\nparser.add_argument(\"-D\", \"--debug\", action=\"store_true\",\n help=\"print BPF program before starting (for debugging purposes)\")\nparser.add_argument(\"--ebpf\", action=\"store_true\",\n help=argparse.SUPPRESS)\nargs = parser.parse_args()\nif not args.interval:\n args.interval = args.duration\n\n# define BPF program\nbpf_text = \"\"\"\n#ifndef KBUILD_MODNAME\n#define KBUILD_MODNAME \"bcc\"\n#endif\n#include \n#include \n#include \n#include \n#include \n\nBPF_HISTOGRAM(hist_srtt);\n\nint trace_tcp_rcv(struct pt_regs *ctx, struct sock *sk, struct sk_buff *skb)\n{\n struct tcp_sock *ts = tcp_sk(sk);\n u32 srtt = ts->srtt_us >> 3;\n const struct inet_sock *inet = inet_sk(sk);\n\n SPORTFILTER\n DPORTFILTER\n SADDRFILTER\n DADDRFILTER\n FACTOR\n\n hist_srtt.increment(bpf_log2l(srtt));\n\n return 0;\n}\n\"\"\"\n\n# filter for source port\nif args.sport:\n bpf_text = bpf_text.replace(b'SPORTFILTER',\n b\"\"\"u16 sport = 0;\n bpf_probe_read_kernel(&sport, sizeof(sport), (void *)&inet->inet_sport);\n if (ntohs(sport) != %d)\n return 0;\"\"\" % int(args.sport))\nelse:\n bpf_text = bpf_text.replace(b'SPORTFILTER', b'')\n\n# filter for dest port\nif args.dport:\n bpf_text = bpf_text.replace(b'DPORTFILTER',\n b\"\"\"u16 dport = 0;\n bpf_probe_read_kernel(&dport, sizeof(dport), (void *)&inet->inet_dport);\n if (ntohs(dport) != %d)\n return 0;\"\"\" % int(args.dport))\nelse:\n bpf_text = bpf_text.replace(b'DPORTFILTER', b'')\n\n# filter for source address\nif args.saddr:\n bpf_text = bpf_text.replace(b'SADDRFILTER',\n b\"\"\"u32 saddr = 0;\n bpf_probe_read_kernel(&saddr, sizeof(saddr), (void *)&inet->inet_saddr);\n if (saddr != %d)\n return 0;\"\"\" % struct.unpack(\"=I\", socket.inet_aton(args.saddr))[0])\nelse:\n bpf_text = bpf_text.replace(b'SADDRFILTER', b'')\n\n# filter for source address\nif args.daddr:\n bpf_text = bpf_text.replace(b'DADDRFILTER',\n b\"\"\"u32 daddr = 0;\n bpf_probe_read_kernel(&daddr, sizeof(daddr), (void *)&inet->inet_daddr);\n if (daddr != %d)\n return 0;\"\"\" % struct.unpack(\"=I\", socket.inet_aton(args.daddr))[0])\nelse:\n bpf_text = bpf_text.replace(b'DADDRFILTER', b'')\n\n# show msecs or usecs[default]\nif args.milliseconds:\n bpf_text = bpf_text.replace('FACTOR', 'srtt /= 1000;')\n label = \"msecs\"\nelse:\n bpf_text = bpf_text.replace('FACTOR', '')\n label = \"usecs\"\n\n# debug/dump ebpf enable or not\nif args.debug or args.ebpf:\n print(bpf_text)\n if args.ebpf:\n exit()\n\n# load BPF program\nb = BPF(text=bpf_text)\nb.attach_kprobe(event=\"tcp_rcv_established\", fn_name=\"trace_tcp_rcv\")\n\nprint(\"Tracing TCP RTT... Hit Ctrl-C to end.\")\n\n# output\nexiting = 0 if args.interval else 1\ndist = b.get_table(\"hist_srtt\")\nseconds = 0\nwhile (1):\n try:\n sleep(int(args.interval))\n seconds = seconds + int(args.interval)\n except KeyboardInterrupt:\n exiting = 1\n\n print()\n if args.timestamp:\n print(\"%-8s\\n\" % strftime(\"%H:%M:%S\"), end=\"\")\n\n dist.print_log2_hist(label, \"srtt\")\n dist.clear()\n\n if exiting or seconds >= args.duration:\n exit()\n","sub_path":"tools/tcprtt.py","file_name":"tcprtt.py","file_ext":"py","file_size_in_byte":4970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"416247544","text":"import json\nimport logging\nfrom time import sleep\nfrom ulauncher.api.client.Extension import Extension\nfrom ulauncher.api.client.EventListener import EventListener\nfrom ulauncher.api.shared.event import KeywordQueryEvent, ItemEnterEvent\nfrom ulauncher.api.shared.item.ExtensionResultItem import ExtensionResultItem\nfrom ulauncher.api.shared.action.RenderResultListAction import RenderResultListAction\nfrom ulauncher.api.shared.action.ExtensionCustomAction import ExtensionCustomAction\nfrom ulauncher.api.shared.action.HideWindowAction import HideWindowAction\nfrom conv import l_to_ebc, srm_to_ebc\n\nlogger = logging.getLogger(__name__)\n\n\nclass DemoExtension(Extension):\n\n def __init__(self):\n super(DemoExtension, self).__init__()\n self.subscribe(KeywordQueryEvent, KeywordQueryEventListener())\n self.subscribe(ItemEnterEvent, ItemEnterEventListener())\n\n\nclass KeywordQueryEventListener(EventListener):\n\n def l_to_ebc(self, query):\n return '%s °L = %s EBC' % (query, l_to_ebc(query)) if query and query.isdigit() else ''\n\n def srm_to_ebc(self, query):\n return '%s SRM = %s EBC' % (query, srm_to_ebc(query)) if query and query.isdigit() else ''\n\n def on_event(self, event, extension):\n query = event.get_argument()\n items = [\n ExtensionResultItem(icon='images/icon.png',\n name='°L -> EBC',\n description='Lovibind to EBC',\n on_enter=ExtensionCustomAction({'res': self.l_to_ebc(query)}, keep_app_open=True)),\n ExtensionResultItem(icon='images/icon.png',\n name='SRM -> EBC',\n description='SRM to EBC',\n on_enter=ExtensionCustomAction({'res': self.srm_to_ebc(query)}, keep_app_open=True))\n ]\n logger.info('preferences %s' % json.dumps(extension.preferences))\n return RenderResultListAction(items)\n\n\nclass ItemEnterEventListener(EventListener):\n\n def on_event(self, event, extension):\n data = event.get_data()\n return RenderResultListAction([ExtensionResultItem(icon='images/icon.png',\n name=data['res'],\n on_enter=HideWindowAction())])\n\n\nif __name__ == '__main__':\n DemoExtension().run()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"7986017","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport json\nfrom base_data.items import *\n\nclass CityCodesSpider(scrapy.Spider):\n name = 'city_codes'\n allowed_domains = ['amap.com']\n\n def __init__(self, amap_key):\n self.start_urls = ['http://restapi.amap.com/v3/config/district?keywords=中国&subdistrict=3&key=' + amap_key]\n\n @classmethod\n def from_crawler(cls, crawler, *args, **kwargs):\n settings = crawler.settings\n return cls(\n amap_key = settings.get('AMAP_KEY')\n )\n\n def parse(self, response):\n items = []\n json_data = json.loads(response.body.decode('utf-8'))\n\n # 省份\n for province in json_data['districts'][0]['districts']:\n provinceItem = FullDistrictItem()\n provinceItem['level'] = province['level']\n provinceItem['province_adcode'] = province['adcode']\n provinceItem['province_name'] = province['name']\n provinceItem['province_center'] = [float(coord) for coord in province['center'].split(',')]\n items.append(provinceItem)\n # 城市\n for city in province['districts']:\n cityItem = FullDistrictItem()\n cityItem['level'] = city['level']\n cityItem['province_adcode'] = province['adcode']\n cityItem['province_name'] = province['name']\n cityItem['province_center'] = [float(coord) for coord in province['center'].split(',')]\n cityItem['city_adcode'] = city['adcode']\n cityItem['city_citycode'] = city['citycode']\n cityItem['city_name'] = city['name']\n cityItem['city_center'] = [float(coord) for coord in city['center'].split(',')]\n items.append(cityItem)\n # 行政区\n for district in city['districts']:\n districtItem = FullDistrictItem()\n districtItem['level'] = district['level']\n districtItem['province_adcode'] = province['adcode']\n districtItem['province_name'] = province['name']\n districtItem['province_center'] = [float(coord) for coord in province['center'].split(',')]\n districtItem['city_adcode'] = city['adcode']\n districtItem['city_citycode'] = city['citycode']\n districtItem['city_name'] = city['name']\n districtItem['city_center'] = [float(coord) for coord in city['center'].split(',')]\n districtItem['district_adcode'] = district['adcode']\n districtItem['district_citycode'] = district['citycode']\n districtItem['district_name'] = district['name']\n districtItem['district_center'] = [float(coord) for coord in district['center'].split(',')]\n items.append(districtItem)\n\n return items\n","sub_path":"python/data_cleaner/crawler/base_data/base_data/spiders/city_codes.py","file_name":"city_codes.py","file_ext":"py","file_size_in_byte":3110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"530430096","text":"\n\nfrom xai.brain.wordbase.nouns._tit import _TIT\n\n#calss header\nclass _TITS(_TIT, ):\n\tdef __init__(self,): \n\t\t_TIT.__init__(self)\n\t\tself.name = \"TITS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"tit\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_tits.py","file_name":"_tits.py","file_ext":"py","file_size_in_byte":217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"488810036","text":"class Solution:\n def prisonAfterNDays(self, cells, N: int):\n # in maximum, we have 2 ^ 8 different situations\n # PS there are also solutions which are using the fact that if there is a loop,\n # it will always have length 14 (or divisor of it).\n if N <= 0:\n return cells\n days = N\n count = 0\n d = {tuple(cells): 0}\n while days > 0:\n prev_cells = cells.copy()\n for i in range(8):\n if i == 0 or i == 7:\n cells[i] = 0\n else:\n cells[i] = int(prev_cells[i - 1] == prev_cells[i + 1])\n count += 1\n days -= 1\n if tuple(cells) in d.keys():\n break\n d[tuple(cells)] = count\n if days == 0:\n return cells\n else:\n cycle_length = count - d[tuple(cells)]\n days = (N - d[tuple(cells)]) % cycle_length\n while days > 0:\n prev_cells = cells.copy()\n for i in range(8):\n if i == 0 or i == 7:\n cells[i] = 0\n else:\n cells[i] = int(prev_cells[i - 1] == prev_cells[i + 1])\n days -= 1\n return cells\n\n\nif __name__ == '__main__':\n s = Solution()\n print(s.prisonAfterNDays([0, 1, 0, 1, 1, 0, 0, 1], 7))\n print(s.prisonAfterNDays([1, 0, 0, 1, 0, 0, 1, 0], 1000000000))\n","sub_path":"LeetCode31DaysChallenge-202007/Prison Cells After N Days.py","file_name":"Prison Cells After N Days.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"466611334","text":"# https://nucleisegmentationbenchmark.weebly.com/dataset.html\n\nimport os, sys\nif not os.path.exists('Annotations.zip') or not os.path.exists('Tissue images.zip'):\n sys.exit('Please download the zips from https://nucleisegmentationbenchmark.weebly.com/dataset.html')\n\nimport shutil\nimport subprocess\n\noutdir = 'miccai2018'\nshutil.rmtree(outdir, ignore_errors=True)\nshutil.rmtree('temp', ignore_errors=True)\nos.mkdir('temp')\n\nsubprocess.call(['unzip', 'Annotations.zip', '-d', 'temp'])\nsubprocess.call(['unzip', 'Tissue images.zip', '-d', 'temp'])\n\nimport xml.etree.ElementTree as ET\nfrom skimage.draw import polygon\nfrom skimage.io import imread\nimport numpy as np\n\nimg_files = sorted(os.listdir('temp/Tissue images'))\nmask_files = sorted(os.listdir('temp/Annotations'))\nX = []\nY = []\n\nfor img_file, mask_file in zip(img_files, mask_files):\n print(img_file, mask_file)\n x = imread(os.path.join('temp/Tissue images', img_file))\n\n y = np.zeros((1000, 1000), dtype=np.uint16)\n root = ET.parse(os.path.join('temp/Annotations', mask_file)).getroot()\n annotation1 = root[0]\n regions = annotation1.findall('.//Region')\n i = 0\n for region in regions:\n vertices = region.findall('.//Vertex')\n r = np.array([min(999, round(float(v.attrib['Y']))) for v in vertices])\n c = np.array([min(999, round(float(v.attrib['X']))) for v in vertices])\n if len(vertices) == 2 or np.all(r[0] == r) or np.all(c[0] == c):\n print('Warning: mal-formed region %d in file %s, ignore' % (i, mask_file))\n print(r, c)\n continue\n rr, cc = polygon(r, c)\n y[rr, cc] = i\n i += 1\n X.append(x)\n Y.append(y)\n\nX = np.array(X)\nY = np.array(Y)\n\nos.mkdir(outdir)\nnp.save(os.path.join(outdir, 'X.npy'), X)\nnp.save(os.path.join(outdir, 'Y.npy'), Y)\nshutil.rmtree('temp', ignore_errors=True)\n\nprint('Loaded:')\nprint(X.shape, X.dtype, X.min(), X.max())\nprint(Y.shape, Y.dtype, Y.min(), Y.max())\n","sub_path":"images/segmentation/instance/miccai2018.py","file_name":"miccai2018.py","file_ext":"py","file_size_in_byte":1960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"615175506","text":"from django.http import HttpRequest, HttpResponse\n\nfrom activities.models import TimelineEvent\nfrom activities.services import TimelineService\nfrom api import schemas\nfrom api.decorators import identity_required\nfrom api.pagination import MastodonPaginator\nfrom api.views.base import api_router\n\n\n@api_router.get(\"/v1/notifications\", response=list[schemas.Notification])\n@identity_required\ndef notifications(\n request: HttpRequest,\n response: HttpResponse,\n max_id: str | None = None,\n since_id: str | None = None,\n min_id: str | None = None,\n limit: int = 20,\n account_id: str | None = None,\n):\n # Types/exclude_types use weird syntax so we have to handle them manually\n base_types = {\n \"favourite\": TimelineEvent.Types.liked,\n \"reblog\": TimelineEvent.Types.boosted,\n \"mention\": TimelineEvent.Types.mentioned,\n \"follow\": TimelineEvent.Types.followed,\n }\n requested_types = set(request.GET.getlist(\"types[]\"))\n excluded_types = set(request.GET.getlist(\"exclude_types[]\"))\n if not requested_types:\n requested_types = set(base_types.keys())\n requested_types.difference_update(excluded_types)\n # Use that to pull relevant events\n queryset = TimelineService(request.identity).notifications(\n [base_types[r] for r in requested_types if r in base_types]\n )\n paginator = MastodonPaginator(TimelineEvent)\n pager = paginator.paginate(\n queryset,\n min_id=min_id,\n max_id=max_id,\n since_id=since_id,\n limit=limit,\n )\n pager.jsonify_notification_events(identity=request.identity)\n\n if pager.results:\n response.headers[\"Link\"] = pager.link_header(request, [\"limit\", \"account_id\"])\n\n return pager.json_results\n","sub_path":"api/views/notifications.py","file_name":"notifications.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"84352642","text":"from pathlib import Path\n\nfrom website.content import Content\nfrom website.templates import get_templates\n\n\ndef build(templates_dir: Path, content_dir: Path, build_dir: Path) -> None:\n templates = get_templates(directory=templates_dir)\n all_content = Content.get(directory=content_dir, templates=templates)\n\n for _path, content in all_content.items():\n path = build_dir / f\"{_path}.html\"\n path.parent.mkdir(parents=True, exist_ok=True)\n\n with path.open(\"w\") as file:\n file.write(\n content.template.render(all_content=all_content, content=content)\n )\n","sub_path":"website/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"490188990","text":"import tensorflow as tf\n# basic params\nimage_size = 224\nimage_channel = 3\nnum_steps = 5\nbatch_size = 16\n\n# train params\nepoch = 500\nlr = 1e-5\nattr_num = 4\nloss_fn = tf.square\n\n# data params\ntest_large_label = [0, 4, 7]\ntrain_large_label = [1, 2, 3, 5, 6]\ntest_label_num = 3\ntrain_label_num = 5\ndata_path = '/home/unreal/gelsight/fuse2/fuse/data/gel_rand3_224'\n\n\n# file params\nName = '4real_attribute_rand1'\nparams_file_name = Name + '.npz'\nconfusion_matrix_name = Name + '.jpeg'\nlog_name = Name + '.txt'\ndef should_record(i):\n return i % 5 == 0 and i != 0\n","sub_path":"config/config_4real_attribute_rand1.py","file_name":"config_4real_attribute_rand1.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"309025503","text":"import random \nsecure_Random = random.SystemRandom()\nhands01 = []\nhands02 = []\nclass Card:\n def __init__(self, colors, values):\n self.colors = colors\n self.values = values\n \n def __repr__(self):\n return self.colors + self.values\n\nclass Deck:\n def __init__(self):\n self.colors = [\"D\",\"C\",\"H\",\"S\"]\n self.values = [\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"J\",\"Q\",\"K\",\"A\"]\n self.list_of_cards = []\n \n def make_deck(self):\n for color in self.colors:\n for value in self.values:\n self.list_of_cards.append(Card(color,value))\n # return len(self.list_of_cards)\n\n def shuffle(self):\n secure_Random.shuffle(self.list_of_cards) \n # return self.list_of_cards[0].__repr__()\n\n def choice_card(self):\n return self.list_of_cards.pop()\n\n\ndef fill_up_hands():\n deck = Deck()\n deck.make_deck()\n for item in range(1,6):\n deck.shuffle()\n hands01.append(deck.choice_card())\n deck.shuffle()\n hands02.append(deck.choice_card())\n return hands01, hands02\n\n\ndef elements():\n fill_up_hands()\n output1 = {}\n output2 = {}\n print(hands01)\n for letter in hands01:\n if letter in output1:\n output1[letter] +=1\n else:\n output1[letter] = 1 \n for letter in hands02:\n if letter in output2:\n output2[letter] +=1\n else:\n output2[letter] = 1\n return output1, output2\n print(output1)\nelements()\n \n# def fill_up_hands(self):\n # for i in range(1, 6):\n # self.list_of_cards.append(self.create_random_card())\n # return len(self.list_of_cards)\n\n\n\n\n","sub_path":"week-06/day-02/poker.py","file_name":"poker.py","file_ext":"py","file_size_in_byte":1693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"126967542","text":"# -*- coding: utf-8 -*-\nimport csv\r\n\r\n'''\r\n按照用户把源文件分成33个用户文件,每个文件记录着用户的行为\r\n'''\r\ndef split_file():\r\n in_file = file('C:/Users/xu/Desktop/recommendation_project/data/format_data\\\r\n/userid-timestamp-artid-artname-traid-traname-format.csv','r')\r\n reader = csv.reader(in_file)\r\n\r\n file_name = 'user_000001'\r\n out_file = file('C:/Users/xu/Desktop/recommendation_project/data/format_data\\\r\n/user_data/'+file_name+'.txt','ab')\r\n writer = csv.writer(out_file)\r\n\r\n for line in reader:\r\n if(line[0] == file_name):\r\n writer.writerow(line)\r\n else:\r\n file_name = line[0]\r\n out_file = file('C:/Users/xu/Desktop/recommendation_project/data/format_data/user_data/'+file_name+'.txt','ab')\r\n writer = csv.writer(out_file)\r\n writer.writerow(line)\r\n \r\n'''\r\n主函数\r\n''' \r\nif __name__ == '__main__':\r\n split_file()","sub_path":"code/data_format/file_split_by_user.py","file_name":"file_split_by_user.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"226093411","text":"#!/bin/python\r\n\r\nfrom util import subprocess_grab\r\n\r\nSEARCH = \"https://www.google.co.uk/search?q=\"\r\n#SEARCH = \"https://www.bing.com/search?q=\"\r\n\r\ndef get_links_lynx(search_terms):\r\n search = SEARCH + search_terms\r\n got = subprocess_grab([\"lynx\", \"-listonly\", \"-dump\", search])\r\n return got\r\n\r\nget_links = get_links_lynx\r\n","sub_path":"python/darts/get_links.py","file_name":"get_links.py","file_ext":"py","file_size_in_byte":330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"423275782","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 25 19:36:16 2016\n\n@author: canalli\n\"\"\"\nimport sys\nimport json\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom pandas import DataFrame\n\nresults = []\nindexed_results = {}\niterations_training_losses = {}\niterations_validation_losses = {}\niterations_training_accs = {}\niterations_validation_accs = {}\niterations_best_epochs = {}\niterations_epochs = {}\niterations_best_losses = {}\niterations_test_losses = {}\niterations_best_accs = {}\niterations_test_accs = {}\n\ndef build_mean_of_lists(lists):\n\n\tmax_len = 0\n\tfor i in range(len(lists)):\n\t\tif len(lists[i]) > max_len:\n\t\t\tmax_len = len(lists[i])\n\n\tmean_list = np.zeros(max_len)\n\n\tfor j in range(max_len):\n\t\titems = []\n\t\tfor i in range(len(lists)):\n\t\t\tif j < len(lists[i]):\n\t\t\t\titems.append(lists[i][j])\n\t\tmean_list[j] = np.mean(np.array(items))\n\n\treturn mean_list.tolist()\n\ndef plot(hidden_size, activation_function, i=None, k=None):\n\n\ttitle = \"\"\n\n\tif (i == None) and (k == None):\n\t\t# use mean of iterations\n\t\ttl = indexed_results[(hidden_size, activation_function)]['training_loss']\n\t\tvl = indexed_results[(hidden_size, activation_function)]['validation_loss']\n\n\t\ttitle = \"Hidden Size: %d\\nActivation Function: %s\\nMean of iterations and folds\" % (hidden_size, activation_function)\n\telif (i != None) and (k == None):\n\t\t# use mean of folds\n\t\ttl = indexed_results[(hidden_size, activation_function, i)]['mean_training_loss']\n\t\tvl = indexed_results[(hidden_size, activation_function, i)]['mean_validation_loss']\n\n\t\ttitle = \"Hidden Size: %d\\nActivation Function: %s\\nIteration: %d\\nMean of folds\" % (hidden_size, activation_function, i)\n\telif (i != None) and (k != None):\n\t\t# use specific fold in iteration\n\t\ttl = indexed_results[(hidden_size, activation_function, i)]['folds'][k]['training_loss']\n\t\tvl = indexed_results[(hidden_size, activation_function, i)]['folds'][k]['validation_loss']\n\n\t\ttitle = \"Hidden Size: %d\\nActivation Function: %s\\nIteration: %d\\nFold: %d\" % (hidden_size, activation_function, i, k)\n\telse:\n\t\tprint(\"You cannot specify the fold (k) without the iteration (i)\")\n\t\treturn None\n\n\tfig = plt.figure()\n\tfig.subplots_adjust(top=0.8)\n\tfig.suptitle(title, fontsize=14, fontweight='bold')\n\tplt.xlabel('Epochs')\n\tplt.ylabel('MSE')\n\n\tx = np.arange(len(tl))\n\n\tplt.gca().set_color_cycle(['red', 'blue', 'black'])\n\n\tplt.plot(x, tl)\n\tplt.plot(x, vl)\n\tplt.legend(['training loss', 'validation loss', 'best validation loss'], loc='upper left')\n\n\tplt.show()\n\ndef rprint(k=100, sort_by='best_loss'):\n\tmean_results = []\n\tfor r in indexed_results.items():\n\t\tif len(r[0]) == 2:\n\t\t\tmean_results.append(r)\n\tmean_results = sorted(mean_results, key=lambda r: (r[0][0], r[1][sort_by]))\n\n\tdf = DataFrame(columns=('HU', 'FN', 'EPOCHS', 'BEST_EPOCH', 'VAL_LOSS', 'TEST_LOSS', 'VAL_ACC', 'TEST_ACC'))\n\n\tif (k > len(mean_results)):\n\t\tk = len(mean_results)\n\tfor i in range(k):\n\t\tr = mean_results[i]\n\t\thidden_size = r[0][0]\n\t\tactivation_funtion = r[0][1]\n\n\t\tif 'best_acc' not in r[1]:\n\t\t\tr[1]['best_acc'] = 'N/A'\n\t\tif 'test_acc' not in r[1]:\n\t\t\tr[1]['test_acc'] = 'N/A'\n\n\t\tdf.loc[i] = [hidden_size, activation_funtion, r[1]['epochs'], r[1]['best_epoch'], r[1]['best_loss'], r[1]['test_loss'], r[1]['best_acc'], r[1]['test_acc']]\n\t\t\"\"\"\n\t\tif activation_funtion[0] == 'bihip':\n\t\t\tprint('[%d]\\t' % hidden_size, activation_funtion[0], activation_funtion[1], activation_funtion[2], '\\ttest_loss=%.5f' % r[1]['test_loss'], '\\tmean_epochs=%.2f' % r[1]['epochs'], '\\tbest_validation_loss=%.5f' % r[1]['best_loss'], '\\tbest_validation_epoch=%.2f' % r[1]['best_epoch'])\n\t\telif activation_funtion[0] == 'tanh':\n\t\t\tprint('[%d]\\t' % hidden_size, activation_funtion[0], '\\t\\ttest_loss=%.5f' % r[1]['test_loss'], '\\tmean_epochs=%.2f' % r[1]['epochs'], '\\tbest_validation_loss=%.5f' % r[1]['best_loss'], '\\tbest_validation_epoch=%.2f' % r[1]['best_epoch'])\n\t\telse:\n\t\t\tprint('[%d]\\t' % hidden_size, activation_funtion[0], '\\ttest_loss=%.5f' % r[1]['test_loss'], '\\tmean_epochs=%.2f' % r[1]['epochs'], '\\tbest_validation_loss=%.5f' % r[1]['best_loss'], '\\tbest_validation_epoch=%.2f' % r[1]['best_epoch'])\n\t\t\"\"\"\n\tprint(df)\ndef __main__(argv):\n\n\tpaths = sys.argv[1:]\n\tfor path in paths:\n\t\twith open(path, 'r') as fp:\n\t\t\tfor line in fp:\n\t\t\t\tr = json.loads(line)\n\t\t\t\tresults.append(r)\n\n\tfor r in results:\n\n\t\t#calculate mean losses for k-fold\n\t\tr['mean_best_loss'] = np.mean(np.array([f['best_loss'] for f in r['folds']]))\n\t\tr['mean_test_loss'] = np.mean(np.array([f['test_loss'] for f in r['folds']]))\n\t\tr['mean_best_epoch'] = np.mean(np.array([f['best_epoch'] for f in r['folds']]))\n\t\tr['mean_epochs'] = np.mean(np.array([f['epochs'] for f in r['folds']]))\n\t\tr['mean_validation_loss'] = build_mean_of_lists([f['validation_loss'] for f in r['folds']])\n\t\tr['mean_training_loss'] = build_mean_of_lists([f['training_loss'] for f in r['folds']])\n\n\n\t\ttry:\n\t\t\tr['mean_best_acc'] = np.mean(np.array([f['best_acc'] for f in r['folds']]))\n\t\t\tr['mean_test_acc'] = np.mean(np.array([f['test_acc'] for f in r['folds']]))\n\t\t\tr['mean_validation_acc'] = build_mean_of_lists([f['validation_acc'] for f in r['folds']])\n\t\t\tr['mean_training_acc'] = build_mean_of_lists([f['training_acc'] for f in r['folds']])\n\t\texcept KeyError:\n\t\t\tNone\n\n\t\t#create a reverse index results for easy using\n\t\tidx = (r['hidden_size'], r['activation_function'], r['iteration'])\n\t\tindexed_results[idx] = r\n\n\t\t#extract the configuration\n\t\tconf = (r['hidden_size'], r['activation_function'])\n\n\t\t#create partial entries for reverse index. Used to not specify iteration\n\t\tif conf not in indexed_results:\n\t\t\tindexed_results[conf] = {}\n\n\t\t#create a list for each configuration\n\t\tif conf not in iterations_best_losses:\n\t\t\titerations_best_losses[conf] = []\n\n\t\tif conf not in iterations_test_losses:\n\t\t\titerations_test_losses[conf] = []\n\n\t\tif conf not in iterations_best_accs:\n\t\t\titerations_best_accs[conf] = []\n\n\t\tif conf not in iterations_test_accs:\n\t\t\titerations_test_accs[conf] = []\n\n\t\tif conf not in iterations_best_epochs:\n\t\t\titerations_best_epochs[conf] = []\n\n\t\tif conf not in iterations_epochs:\n\t\t\titerations_epochs[conf] = []\n\n\t\tif conf not in iterations_validation_losses:\n\t\t\titerations_validation_losses[conf] = []\n\n\t\tif conf not in iterations_training_losses:\n\t\t\titerations_training_losses[conf] = []\n\n\t\tif conf not in iterations_validation_accs:\n\t\t\titerations_validation_accs[conf] = []\n\n\t\tif conf not in iterations_training_accs:\n\t\t\titerations_training_accs[conf] = []\n\n\t\t# save iterations results for each configuration\n\t\titerations_best_losses[conf].append(r['mean_best_loss'])\n\t\titerations_test_losses[conf].append(r['mean_test_loss'])\n\t\titerations_best_epochs[conf].append(r['mean_best_epoch'])\n\t\titerations_epochs[conf].append(r['mean_epochs'])\n\t\titerations_validation_losses[conf].append(r['mean_validation_loss'])\n\t\titerations_training_losses[conf].append(r['mean_training_loss'])\n\n\n\t\ttry:\n\t\t\titerations_validation_accs[conf].append(r['mean_validation_acc'])\n\t\t\titerations_training_accs[conf].append(r['mean_training_acc'])\n\t\t\titerations_best_accs[conf].append(r['mean_best_acc'])\n\t\t\titerations_test_accs[conf].append(r['mean_test_acc'])\n\t\texcept KeyError:\n\t\t\tNone\n\n\n\t# calculate mean of iterations for index itens without specific iteration\n\tfor conf in indexed_results:\n\t\tif len(conf) == 2:\n\t\t\tindexed_results[conf]['best_loss'] = np.mean(np.array(iterations_best_losses[conf]))\n\t\t\tindexed_results[conf]['test_loss'] = np.mean(np.array(iterations_test_losses[conf]))\n\t\t\tindexed_results[conf]['best_acc'] = np.mean(np.array(iterations_best_accs[conf]))\n\t\t\tindexed_results[conf]['test_acc'] = np.mean(np.array(iterations_test_accs[conf]))\n\t\t\tindexed_results[conf]['best_epoch'] = np.mean(np.array(iterations_best_epochs[conf]))\n\t\t\tindexed_results[conf]['epochs'] = np.mean(np.array(iterations_epochs[conf]))\n\t\t\tindexed_results[conf]['validation_loss'] = build_mean_of_lists(iterations_validation_losses[conf])\n\t\t\tindexed_results[conf]['training_loss'] = build_mean_of_lists(iterations_training_losses[conf])\n\t\t\tindexed_results[conf]['validation_acc'] = build_mean_of_lists(iterations_validation_accs[conf])\n\t\t\tindexed_results[conf]['training_acc'] = build_mean_of_lists(iterations_training_accs[conf])\n\n\trprint()\n\nif __name__ == \"__main__\":\n __main__(sys.argv[1:])\n","sub_path":"ann/open_results.py","file_name":"open_results.py","file_ext":"py","file_size_in_byte":8211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"209686730","text":"# -*- coding: utf-8 -*-\nimport paddle\nfrom paddle import fluid\nimport math\nfrom paddle.fluid.layers.learning_rate_scheduler import _decay_step_counter\nfrom paddle.fluid.initializer import init_on_cpu\nimport paddle.fluid.layers.ops as ops\nfrom paddle.fluid.layers import control_flow\n\ndef cosine_decay_v2(learning_rate, totalsteps):\n \"\"\"Applies cosine decay to the learning rate.\n lr = 0.05 * (math.cos(global_step * (math.pi / totalsteps)) + 1)\n decrease lr for every mini-batch.\n \"\"\"\n global_step = _decay_step_counter()\n\n with init_on_cpu():\n decayed_lr = learning_rate * \\\n (ops.cos(global_step * (math.pi / float(totalsteps))) + 1)/2\n return decayed_lr\n\n\ndef cosine_decay_v2_with_warmup(learning_rate, warmupsteps, totalsteps):\n \"\"\"Applies cosine decay to the learning rate.\n lr = 0.05 * (math.cos(epoch * (math.pi / 120)) + 1)\n decrease lr for every mini-batch and start with warmup.\n \"\"\"\n global_step = _decay_step_counter()\n lr = fluid.layers.tensor.create_global_var(\n shape=[1],\n value=0.0,\n dtype='float32',\n persistable=True,\n name=\"learning_rate\")\n\n with init_on_cpu():\n with control_flow.Switch() as switch:\n with switch.case(global_step < warmupsteps):\n decayed_lr = learning_rate * (global_step / float(warmupsteps))\n fluid.layers.tensor.assign(input=decayed_lr, output=lr)\n with switch.default():\n decayed_lr = learning_rate * \\\n (ops.cos((global_step - warmupsteps) * (math.pi / (totalsteps))) + 1)/2\n fluid.layers.tensor.assign(input=decayed_lr, output=lr)\n return lr\n\n\ndef optimizer_setting(params, args):\n ls = params[\"learning_strategy\"]\n assert ls[\"name\"] in [\n \"piecewise_decay\", \"cosine_decay\", \"cosine_decay_with_warmup\"\n ]\n base_lr = params[\"lr\"]\n\n if ls['name'] == \"piecewise_decay\":\n bd = [int(e) for e in ls[\"lr_steps\"].split(',')]\n lr = [base_lr * (0.1**i) for i in range(len(bd) + 1)]\n lrs = fluid.layers.piecewise_decay(boundaries=bd, values=lr)\n elif ls['name'] == \"cosine_decay\":\n lrs = cosine_decay_v2(base_lr, args.total_iter_num)\n elif ls['name'] == \"cosine_decay_with_warmup\":\n lrs = cosine_decay_v2_with_warmup(base_lr, args.warmup_iter_num,\n args.total_iter_num)\n\n #相对于SGD ,使用Momentum 加快收敛速度而不影响收敛效果。如果用Adam,或者RMScrop收敛可以更快,但在imagenet上收敛有损失\n optimizer = fluid.optimizer.Momentum(\n learning_rate=lrs,\n momentum=0.9,\n regularization=fluid.regularizer.L2Decay(1e-4))\n return optimizer\n\n\n","sub_path":"image_feature/metric_learning/learning_rate.py","file_name":"learning_rate.py","file_ext":"py","file_size_in_byte":2758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"648516721","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# autor: Tysamnca.\n#\n##############################################################################\n\nfrom odoo import fields, models\n\nclass ResParther(models.Model):\n _inherit = 'res.partner'\n\n property_county_wh_payable = fields.Many2one('account.account',\n company_dependent=True,\n string=\"Cuenta de Compra para Impuesto Municipal\",\n oldname=\"property_county_wh_payable\",\n help=\"This account will be used debit local withholding amount\",\n )\n\n property_county_wh_receivable = fields.Many2one('account.account',\n company_dependent=True,\n string=\"Cuenta de Venta para Impuesto Municipal\",\n oldname=\"property_county_wh_receivable\",\n help=\"This account will be used credit local withholding amount\",\n )\n\n wh_muni_agent = fields.Boolean('Se le Aplica Impuesto Municipal?')\n wh_muni = fields.Float('Porcentaje de Retencion')","sub_path":"l10n_ve_withholding_municipal/model/partner.py","file_name":"partner.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"160147556","text":"from django.http import HttpResponse\nfrom django.db.utils import IntegrityError\n\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view\nfrom rest_framework import status\n\nfrom LoadList.services import ListsSet, List\nfrom CreateList.services import InsertManager\nfrom UpdateList.services import UpdateManager\nfrom DeleteList.services import DeleteManager\nfrom ExistenceList.services import ExistenceManager\n\n\n@api_view([\"GET\"])\ndef get_all_lists(request):\n if request.method == \"GET\":\n data = ListsSet().get_as_list()\n return Response(data, status=status.HTTP_200_OK)\n\n\n@api_view([\"GET\"])\ndef get_list(request, title):\n if request.method == \"GET\":\n try:\n data = List(title).get_as_list()\n except AttributeError:\n return HttpResponse(\"There are no '%s'\" % title)\n return Response(data, status=status.HTTP_200_OK)\n\n\n@api_view([\"POST\"])\ndef insert_list(request):\n if request.method == \"POST\":\n try:\n mngr = InsertManager()\n mngr.insert(request.data)\n return Response({}, status=status.HTTP_201_CREATED)\n except IntegrityError:\n return Response({}, status=status.HTTP_200_OK)\n\n\n@api_view([\"POST\"])\ndef update_list(request):\n if request.method == \"POST\":\n mngr = UpdateManager()\n mngr.update(request.data)\n return Response({}, status=status.HTTP_200_OK)\n\n\n@api_view([\"POST\"])\ndef delete_list(request):\n if request.method == \"POST\":\n del_obj = DeleteManager()\n del_obj.delete(request.data)\n return Response({}, status=status.HTTP_200_OK)\n\n\n@api_view([\"GET\"])\ndef does_list_exists(request, title):\n if request.method == \"GET\":\n mngr = ExistenceManager()\n result = mngr.exists(title)\n return Response({\"exists\": result}, status=status.HTTP_200_OK)\n","sub_path":"Server/Api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"13902524","text":"from django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('auction', '0003_item'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='BidHistory',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('bidder', models.TextField(blank=True, max_length=200)),\n ('price', models.IntegerField(blank=True, null=True)),\n ('date', models.DateTimeField(verbose_name='date published')),\n ('item', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='auction.Item')),\n ],\n ),\n ]\n","sub_path":"CS3450/Repo-1.00/cs3450/auction/migrations/0004_bidhistory.py","file_name":"0004_bidhistory.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"346645235","text":"import subprocess\nfrom setuptools import setup, find_packages\nfrom setuptools.command.install import install\n\n\nEVALUATION_REQUIREMENTS = [\n 'ds-gear',\n 'flask',\n 'flask_restful',\n 'pillow']\n\nTRAINING_REQUIREMENTS = [\n 'numpy',\n 'gdown',\n 'pandas',\n 'scikit-learn',\n 'matplotlib',\n 'jupyter',\n 'tensorflow',\n 'opencv-python',\n 'wget',\n 'gdown',\n 'requests']\n\n\nclass InstallCommand(install):\n \"\"\"\n will call activate githooks for install mode\n \"\"\"\n def run(self):\n subprocess.call(\"git config core.hooksPath .githooks/\", shell=True)\n install.run(self)\n\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\n\nsetup(name='marabou',\n packages=find_packages(include=['commons', 'marabou.*']),\n author='Marouen Azzouz, Youssef Azzouz',\n author_email='azzouz.marouen@gmail.com, youssef.azzouz1512@gmail.com',\n description=\"Marabou is a python pipeline to perform training\\\n and evaluation for different deep learning scenarios. \\\n It is distributed under the Mit license.\",\n long_description=long_description,\n version='0.1.10',\n install_requires=EVALUATION_REQUIREMENTS,\n include_package_data=True,\n zip_safe=False,\n extras_require={\n 'train': TRAINING_REQUIREMENTS,\n },\n entry_points={\n 'console_scripts': ['marabou-train-sentiment-analysis =\\\n marabou.training.scripts.train_sentiment_analysis:main [train]',\n 'marabou-train-topic-detection =\\\n marabou.training.scripts.train_topic_classifier:main [train]',\n 'marabou-train-named-entity-recognition =\\\n marabou.training.scripts.train_named_entity_recognition:main [train]',\n 'marabou-train-fashion-classifier =\\\n marabou.training.scripts.train_fashion_classifier:main [train]',\n 'marabou-train-collect-data-fashion-classifier =\\\n marabou.training.scripts.cnn_classifier_dataset_collection:main [train]',\n 'marabou-eval-server = marabou.evaluation.app:main'\n ]\n },\n cmdClass={\n 'install': InstallCommand\n })\n","sub_path":"marabou/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"26223958","text":"import pygame\r\nimport math, cmath\r\nfrom time import sleep\r\nimport random\r\n\r\n\r\ndef a(path, t, n):\r\n phase = -1 * n * 2 * math.pi * 1j * t / (len(path))\r\n unit_pos = cmath.exp(phase)\r\n tp = (complex(path[t][0], path[t][1]) * unit_pos)\r\n return tp\r\n\r\ndef intg(path, n):\r\n tot = 0\r\n for i in range(len(path)):\r\n tot += a(path, i, n)\r\n\r\n tot /= len(path)\r\n \r\n return tot\r\n\r\npygame.init()\r\n\r\nwin_wd = 1080\r\nwin_ht = 720\r\nwin = pygame.display.set_mode((win_wd,win_ht))\r\nBLACK = (0,0,0)\r\nWHITE = (255,255,255)\r\nGREEN = (0,255,0)\r\nclock = pygame.time.Clock()\r\nfont_1 = pygame.font.Font(r\"C:\\WINDOWS\\Fonts\\ARIALN.TTF\", 36)\r\ntrace = pygame.Rect(win_wd - 100, 20, 100, 50)\r\nprec = pygame.Rect(win_wd - 100, 100, 100, 50)\r\nreset = pygame.Rect(win_wd - 100, 180, 100, 50)\r\n\r\ndef draw_circle(win, center, radius):\r\n try:\r\n pygame.draw.circle(win, WHITE, (center[0], center[1]), radius, 2)\r\n except ValueError:\r\n pygame.draw.circle(win, WHITE, (center[0], center[1]), 0, 0)\r\n\r\ndef draw_line(win, radius, angle, start):\r\n end = (int(radius * math.cos(angle) + start[0]), int(radius * math.sin(angle) + start[1]))\r\n pygame.draw.line(win, WHITE, start, end, 2)\r\n return end\r\n\r\n\r\nrun = True\r\nsteps = 0\r\nendpts = []\r\nprecision = 1\r\nstep_size = 0.05\r\n\r\nstart = True\r\ndrawing = False\r\ntracing = True\r\n\r\nwhile run:\r\n clock.tick(24)\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n quit()\r\n\r\n elif event.type == pygame.MOUSEBUTTONDOWN:\r\n if trace.collidepoint(event.pos) and not start:\r\n if tracing == True:\r\n tracing = False\r\n elif tracing == False:\r\n tracing = True\r\n\r\n elif prec.collidepoint(event.pos) and not drawing:\r\n pass\r\n\r\n elif reset.collidepoint(event.pos) and not drawing:\r\n pass\r\n\r\n else:\r\n drawing = True\r\n start = False\r\n win.fill(BLACK)\r\n path = [event.pos]\r\n\r\n elif event.type == pygame.MOUSEBUTTONUP:\r\n if trace.collidepoint(event.pos) and not drawing:\r\n pass\r\n\r\n elif reset.collidepoint(event.pos) and not drawing:\r\n win.fill(BLACK)\r\n steps = 0\r\n endpts = []\r\n precision = 1\r\n\r\n start = True\r\n drawing = False\r\n tracing = True\r\n\r\n elif prec.collidepoint(event.pos) and not drawing:\r\n precision += 1\r\n coeffs = []\r\n steps = 0\r\n endpts = []\r\n for i in range(precision):\r\n if i % 2 == 0:\r\n coeffs.append(intg(path, -(i//2)))\r\n elif i % 2 == 1:\r\n coeffs.append(intg(path, (i+1)//2))\r\n\r\n angle = [cmath.phase(c) for c in coeffs]\r\n radius = [int(abs(c)) for c in coeffs]\r\n \r\n else:\r\n drawing = False\r\n path = [(i[0] - win_wd//2, i[1] - win_ht//2) for i in path]\r\n coeffs = []\r\n steps = 0\r\n endpts = []\r\n for i in range(precision):\r\n if i % 2 == 0:\r\n coeffs.append(intg(path, -(i//2)))\r\n elif i % 2 == 1:\r\n coeffs.append(intg(path, (i+1)//2))\r\n\r\n angle = [cmath.phase(c) for c in coeffs]\r\n radius = [int(abs(c)) for c in coeffs]\r\n\r\n if drawing:\r\n path.append(pygame.mouse.get_pos())\r\n pygame.draw.line(win, WHITE, path[-1], path[-2], 1)\r\n \r\n if not drawing and not start:\r\n win.fill(BLACK)\r\n end = (win_wd//2, win_ht//2)\r\n for i in range(precision):\r\n if i % 2 == 0:\r\n angle_change = -step_size * (i//2)\r\n elif i % 2 == 1:\r\n angle_change = step_size * ((i+1)//2)\r\n\r\n draw_circle(win, end, radius[i])\r\n end = draw_line(win, radius[i], angle[i], end)\r\n angle[i] += angle_change\r\n\r\n pygame.draw.rect(win, WHITE, trace)\r\n win.blit(font_1.render(\"TRACE\", True, BLACK), trace)\r\n\r\n pygame.draw.rect(win, WHITE, prec)\r\n win.blit(font_1.render(\"PREC\", True, BLACK), prec)\r\n\r\n pygame.draw.rect(win, WHITE, reset)\r\n win.blit(font_1.render(\"RESET\", True, BLACK), reset)\r\n \r\n endpts.append(end)\r\n steps += 1\r\n if steps >= 2*math.pi//step_size:\r\n steps = 0\r\n endpts = []\r\n if tracing:\r\n for i in range(1, len(endpts)):\r\n pygame.draw.line(win, GREEN, endpts[i], endpts[i-1], 2)\r\n \r\n \r\n pygame.display.update()\r\n\r\n\r\n","sub_path":"Four-yay.py","file_name":"Four-yay.py","file_ext":"py","file_size_in_byte":4881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"644190944","text":"\"\"\"分析apache访问日志\n1. 统计每个客户端访问apache服务器的次数\n2. 将统计信息通过字典的方式显���出来\n3. 分别统计客户端是Firefox和MSIE的访问次数\n4. 分别使用函数式编程和面向对象编程的方式实现\"\"\"\nfrom collections import Counter\nimport re\n\nclass Patt:\n def __init__(self,patt):\n self.patt = re.compile(patt)\n\n def count_patt(self,fname):\n result = Counter() #定义一个统计对象\n with open(fname) as fobj:\n for line in fobj:\n m = self.patt.search(line)\n if m:\n result.update([m.group()]) #将读取的数据放入统计对象中,数据需要用[]括起,以列表的形式传入统计对象\n return result\n\nif __name__ == \"__main__\":\n fname = 'access_log'\n ip = Patt('^(\\d+.){3}(\\d+)') #创建一个实例\n access = ip.count_patt(fname) #调用类中的count_patt方法\n print(access)\n print(access.most_common(3)) #输出字典中的前三项\n","sub_path":"python/day8/apache_log_by_classmudle.py","file_name":"apache_log_by_classmudle.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"103084570","text":"from napalm import get_network_driver\n\n\ndef napalm_connection(task=None, timeout=60, optional_args=None):\n \"\"\"\n This tasks connects to the device using the NAPALM driver and sets the\n relevant connection.\n\n Arguments:\n timeout (int, optional): defaults to 60\n optional_args (dict, optional): defaults to `{\"port\": task.host[\"nornir_network_api_port\"]}`\n\n Inventory:\n napalm_options: maps directly to ``optional_args`` when establishing the connection\n network_api_port: maps to ``optional_args[\"port\"]``\n \"\"\"\n host = task.host\n\n parameters = {\n \"hostname\": host.host,\n \"username\": host.username,\n \"password\": host.password,\n \"timeout\": timeout,\n \"optional_args\": optional_args or host.get(\"napalm_options\", {}),\n }\n\n platform = host.nos\n api_platforms = [\"nxos\", \"eos\", \"iosxr\", \"junos\"]\n ssh_platforms = [\"nxos_ssh\", \"ios\"]\n\n # If port is set in optional_args that will control the port setting (else look to inventory)\n if \"port\" not in parameters[\"optional_args\"]:\n if platform in api_platforms and host.network_api_port:\n parameters[\"optional_args\"][\"port\"] = host.network_api_port\n elif platform in ssh_platforms and host.ssh_port:\n parameters[\"optional_args\"][\"port\"] = host.ssh_port\n\n # Setting host.nos to 'nxos' is potentially ambiguous\n if platform == \"nxos\":\n if not host.network_api_port:\n if host.ssh_port or parameters[\"optional_args\"].get(\"port\") == 22:\n platform == \"nxos_ssh\"\n\n # Fallback for community drivers (priority api_port over ssh_port)\n if platform not in (api_platforms + ssh_platforms):\n if host.network_api_port:\n parameters[\"optional_args\"][\"port\"] = host.network_api_port\n elif host.ssh_port:\n parameters[\"optional_args\"][\"port\"] = host.ssh_port\n\n network_driver = get_network_driver(platform)\n host.connections[\"napalm\"] = network_driver(**parameters)\n host.connections[\"napalm\"].open()\n","sub_path":"nornir/plugins/tasks/connections/napalm_connection.py","file_name":"napalm_connection.py","file_ext":"py","file_size_in_byte":2094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"98850558","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nSpyder Editor\r\n\r\nThis is a temporary script file.\r\n\"\"\"\r\nimport pandas as pd\r\nimport numpy as np\r\nimport os, sys, re\r\n\r\ndef DOS_transfer(filename):\r\n \r\n dos_file = open(filename, 'r')\r\n lines = dos_file.readlines()\r\n dos_file.close()\r\n len_dos = len(lines)\r\n \r\n dos_file = open(filename, 'r')\r\n DOS_data = []\r\n line_num = 0\r\n while(1):\r\n line = dos_file.readline()\r\n if line != '\\n':\r\n DOS_data.append([float(s) for s in line.rstrip('\\n').split()])\r\n line_num += 1\r\n else:\r\n break\r\n NEDOS = line_num\r\n DOS_data = np.asarray(DOS_data)\r\n DOS_case = int(len_dos/(NEDOS+1))\r\n for t in range(DOS_case-1):\r\n pDOS = []\r\n for i in range(NEDOS):\r\n pDOS.append([float(s) for s in dos_file.readline().rstrip('\\n').split()])\r\n pDOS = np.asarray(pDOS)\r\n DOS_data = np.concatenate((DOS_data, pDOS), axis=1)\r\n DOS_data = np.delete(DOS_data, -2, axis=1)\r\n # skip the space line\r\n dos_file.readline()\r\n \r\n # write the split DOS into csv file\r\n df = pd.DataFrame(DOS_data)\r\n df.to_csv('{}.csv'.format(filename[0:-4]), index=False, header=False)\r\n\r\n\r\nif __name__==\"__main__\":\r\n \r\n filename = sys.argv[1]\r\n DOS_transfer(filename)\r\n ","sub_path":"DOS_transfer.py","file_name":"DOS_transfer.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"541103334","text":"import torch\nimport numpy as np\n\ntorch.manual_seed(120)\nfrom tqdm import tqdm\n# from pytorch3d.loss import chamfer_distance\nfrom NURBSDiff.surf_eval import SurfEval\nimport matplotlib.pyplot as plt\nfrom torch.autograd import Variable\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\nimport sys\nimport copy\n\nfrom geomdl import NURBS, multi, exchange\nfrom geomdl.visualization import VisMPL\nfrom geomdl.exchange import export_smesh, import_smesh\n# import CPU_Eval as cpu\n\n\ndef chamfer_distance_one_side(pred, gt, side=1):\n \"\"\"\n Computes average chamfer distance prediction and groundtruth\n but is one sided\n :param pred: Prediction: B x N x 3\n :param gt: ground truth: B x M x 3\n :return:\n \"\"\"\n if isinstance(pred, np.ndarray):\n pred = Variable(torch.from_numpy(pred.astype(np.float32))).cuda()\n\n if isinstance(gt, np.ndarray):\n gt = Variable(torch.from_numpy(gt.astype(np.float32))).cuda()\n\n pred = torch.unsqueeze(pred, 1)\n gt = torch.unsqueeze(gt, 2)\n\n diff = pred - gt\n diff = torch.sum(diff ** 2, 3)\n if side == 0:\n cd = torch.mean(torch.min(diff, 1)[0], 1)\n elif side == 1:\n cd = torch.mean(torch.min(diff, 2)[0], 1)\n cd = torch.mean(cd)\n return cd\n\n\ndef main():\n uEvalPtSize = 32\n vEvalPtSize = 64\n device = 'cpp'\n dataFileName = 'data.41.txt'\n smeshInFileName = 'smesh.41.in.dat'\n smeshOutFileName = \"smesh.41.out.dat\"\n surface = import_smesh(smeshInFileName)[0]\n\n # surface1 = import_smesh(\"smesh.41.in.dat\")[0]\n # surface2 = import_smesh(\"smesh.45.in.dat\")[0]\n #\n # surface1CP = np.reshape(np.array(surface.ctrlptsw), [surface1.ctrlpts_size_u, surface1.ctrlpts_size_v, 4])\n # surface2CP = np.reshape(np.array(surface.ctrlptsw), [surface1.ctrlpts_size_u, surface1.ctrlpts_size_v, 4])\n #\n # surface1CP[0,:,:] = surface2CP[0,:,:]\n # export_smesh(surface1, \"smesh.46.in.dat\")\n\n\n dimension = surface.dimension\n degree = [surface.degree_u, surface.degree_v]\n CtrlPtsCountUV = [surface.ctrlpts_size_u, surface.ctrlpts_size_v]\n CtrlPtsTotal = CtrlPtsCountUV[0] * CtrlPtsCountUV[1]\n\n knotU = surface.knotvector_u\n knotV = surface.knotvector_v\n\n CtrlPts = np.array(surface.ctrlptsw)\n\n CtrlPtsNoW = np.reshape(CtrlPts[:, :3], [CtrlPtsCountUV[0], CtrlPtsCountUV[1], 3])\n target = torch.from_numpy(np.genfromtxt(dataFileName, delimiter='\\t', dtype=np.float32))\n mumPoints = target.cpu().shape\n\n layer = SurfEval(CtrlPtsCountUV[0], CtrlPtsCountUV[1], knot_u=knotU, knot_v=knotV, dimension=3,\n p=degree[0], q=degree[1], out_dim_u=uEvalPtSize, out_dim_v=vEvalPtSize, dvc=device)\n\n if device == 'cuda':\n inpCtrlPts = torch.nn.Parameter(torch.from_numpy(copy.deepcopy(CtrlPtsNoW)).cuda())\n inpWeight = torch.ones(1, CtrlPtsCountUV[0], CtrlPtsCountUV[1], 1).cuda()\n else:\n inpCtrlPts = torch.nn.Parameter(torch.from_numpy(copy.deepcopy(CtrlPtsNoW)))\n inpWeight = torch.ones(1, CtrlPtsCountUV[0], CtrlPtsCountUV[1], 1)\n base_out = layer(torch.cat((inpCtrlPts.unsqueeze(0), inpWeight), axis=-1))\n\n BaseAreaSurf = base_out.detach().cpu().numpy().squeeze()\n\n base_length_u = ((BaseAreaSurf[:-1, :-1, :] - BaseAreaSurf[1:, :-1, :]) ** 2).sum(-1).squeeze()\n base_length_v = ((BaseAreaSurf[:-1, :-1, :] - BaseAreaSurf[:-1, 1:, :]) ** 2).sum(-1).squeeze()\n surf_areas_base = np.multiply(base_length_u, base_length_v)\n surf_areas_base_torch = torch.from_numpy(surf_areas_base).cuda()\n base_length_u1 = np.sum(base_length_u[:, -1])\n base_area = np.sum(surf_areas_base)\n\n base_der11 = ((2 * base_out[:, 1:-1, 1:-1, :] - base_out[:, 0:-2, 1:-1, :] - base_out[:, 2:, 1:-1, :]) ** 2).sum(-1).squeeze()\n base_der22 = ((2 * base_out[:, 1:-1, 1:-1, :] - base_out[:, 1:-1, 0:-2, :] - base_out[:, 1:-1, 2:, :]) ** 2).sum(-1).squeeze()\n base_der12 = ((2 * base_out[:, 1:-1, 1:-1, :] - base_out[:, 0:-2, 1:-1, :] - base_out[:, 1:-1, 2:, :]) ** 2).sum(-1).squeeze()\n base_der21 = ((2 * base_out[:, 1:-1, 1:-1, :] - base_out[:, 1:-1, 0:-2, :] - base_out[:, 2:, 1:-1, :]) ** 2).sum(-1).squeeze()\n base_surf_curv11 = torch.max(base_der11)\n base_surf_curv22 = torch.max(base_der22)\n base_surf_curv12 = torch.max(base_der12)\n base_surf_curv21 = torch.max(base_der21)\n\n print('\\nBase surface area: ',base_area)\n print('Max curvatures: ')\n print(base_surf_curv11.detach().cpu().numpy().squeeze(), base_surf_curv12.detach().cpu().numpy().squeeze())\n print(base_surf_curv21.detach().cpu().numpy().squeeze(), base_surf_curv22.detach().cpu().numpy().squeeze())\n\n opt = torch.optim.Adam(iter([inpCtrlPts]), lr=1e-3)\n # opt = torch.optim.LBFGS(iter([inpCtrlPts]), lr=0.5, max_iter=5)\n scheduler = torch.optim.lr_scheduler.MultiStepLR(opt, milestones=[50,100,150,200,250,300], gamma=0.1)\n pbar = tqdm(range(10000))\n for i in pbar:\n \n def closure():\n opt.zero_grad()\n\n out = layer(torch.cat((inpCtrlPts.unsqueeze(0), weight), axis=-1))\n\n length_u = ((out[:, :-1, :-1, :] - out[:, 1:, :-1, :]) ** 2).sum(-1).squeeze()\n length_v = ((out[:, :-1, :-1, :] - out[:, :-1, 1:, :]) ** 2).sum(-1).squeeze()\n length_u1 = length_u[:,-1]\n surf_areas = torch.multiply(length_u, length_v)\n\n der11 = ((2*out[:, 1:-1, 1:-1, :] - out[:, 0:-2, 1:-1, :] - out[:, 2:, 1:-1, :]) ** 2).sum(-1).squeeze()\n der22 = ((2*out[:, 1:-1, 1:-1, :] - out[:, 1:-1, 0:-2, :] - out[:, 1:-1, 2:, :]) ** 2).sum(-1).squeeze()\n der12 = ((2*out[:, 1:-1, 1:-1, :] - out[:, 0:-2, 1:-1, :] - out[:, 1:-1, 2:, :]) ** 2).sum(-1).squeeze()\n der21 = ((2*out[:, 1:-1, 1:-1, :] - out[:, 1:-1, 0:-2, :] - out[:, 2:, 1:-1, :]) ** 2).sum(-1).squeeze()\n surf_curv11 = torch.max(der11)\n surf_curv22 = torch.max(der22)\n surf_curv12 = torch.max(der12)\n surf_curv21 = torch.max(der21)\n surf_max_curv = torch.sum(torch.tensor([surf_curv11,surf_curv22,surf_curv12,surf_curv21]))\n\n # lossVal = 0\n if device == 'cuda':\n lossVal = chamfer_distance_one_side(out.view(1, uEvalPtSize * vEvalPtSize, 3), target.view(1, mumPoints[0], 3).cuda())\n else:\n lossVal = chamfer_distance_one_side(out.view(1, uEvalPtSize * vEvalPtSize, 3), target.view(1, mumPoints[0], 3))\n\n # loss, _ = chamfer_distance(target.view(1, 360, 3), out.view(1, evalPtSize * evalPtSize, 3))\n # if (i < 5):\n # lossVal += (1) * torch.abs(torch.sum(length_u1)-base_length_u1)\n\n # Local area change\n # lossVal += (1) * torch.sum(torch.abs(surf_areas - surf_areas_base_torch))\n # Total area change\n lossVal += (1) * torch.abs(surf_areas.sum() - base_area)\n\n # Minimize maximum curvature\n lossVal += (10) * torch.abs(surf_max_curv)\n # Minimize length of u=1\n # lossVal += (.01) * torch.abs(torch.sum(length_u1) - base_length_u1)\n\n # Back propagate\n lossVal.backward(retain_graph=True)\n return lossVal\n\n if device == 'cuda':\n weight = torch.ones(1, CtrlPtsCountUV[0], CtrlPtsCountUV[1], 1).cuda()\n else:\n weight = torch.ones(1, CtrlPtsCountUV[0], CtrlPtsCountUV[1], 1)\n\n # Optimize step\n lossVal = opt.step(closure)\n scheduler.step()\n out = layer(torch.cat((inpCtrlPts.unsqueeze(0), weight), axis=-1))\n\n # Fixing U = 0 Ctrl Pts\n inpCtrlPts.data[0,:,:] = torch.from_numpy(copy.deepcopy(CtrlPtsNoW[0,:,:]))\n # Constraining the seam of the cylindrical patch\n temp = 0.5*(inpCtrlPts.data[:,0,:] + inpCtrlPts.data[:,-1,:])\n inpCtrlPts.data[:,0,:] = temp\n inpCtrlPts.data[:,-1,:] = temp\n\n for j in range(5):\n tempdir1 = inpCtrlPts.data[j][1] - inpCtrlPts.data[j][0]\n tempdir2 = inpCtrlPts.data[j][-1] - inpCtrlPts.data[j][-2]\n avgDir = 0.5*(tempdir1+tempdir2)\n inpCtrlPts.data[j][1] = inpCtrlPts.data[j][0] + avgDir\n inpCtrlPts.data[j][-2] = inpCtrlPts.data[j][0] - avgDir\n\n if i % 100 == 0:\n fig = plt.figure(figsize=(4, 4))\n ax = fig.add_subplot(111, projection='3d', adjustable='box', proj_type='ortho')\n\n target_cpu = target.cpu().numpy().squeeze()\n predicted = out.detach().cpu().numpy().squeeze()\n predCtrlPts = inpCtrlPts.detach().cpu().numpy().squeeze()\n\n surf1 = ax.scatter(target_cpu[:, 0], target_cpu[:, 1], target_cpu[:, 2], s=3.0, color='red')\n surf2 = ax.plot_surface(predicted[:, :, 0], predicted[:, :, 1], predicted[:, :, 2], color='green', alpha=0.5)\n # surf3 = ax.plot_wireframe(predCtrlPts[:, :, 0], predCtrlPts[:, :, 1], predCtrlPts[:, :, 2], linewidth=1, linestyle='dashed', color='orange')\n ax.plot(CtrlPtsNoW[0, :, 0], CtrlPtsNoW[0, :, 1], CtrlPtsNoW[0, :, 2], linewidth=3, linestyle='solid', color='green')\n\n ax.azim = -90\n ax.dist = 6.5\n ax.elev = 120\n ax.set_xticks([])\n ax.set_yticks([])\n ax.set_zticks([])\n # ax.set_box_aspect([0.1, 1, 0.1])\n ax.xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))\n ax.yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))\n ax.zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))\n ax._axis3don = False\n # ax.legend()\n\n # ax.set_aspect(1)\n fig.subplots_adjust(hspace=0, wspace=0)\n fig.tight_layout()\n plt.show()\n\n pbar.set_description(\"Total loss is %s: %s\" % (i + 1, lossVal.item()))\n pass\n\n\n predCtrlPts = torch.cat((inpCtrlPts.unsqueeze(0), weight), axis=-1).detach().cpu().numpy().squeeze()\n surface.ctrlptsw = (np.reshape(predCtrlPts,(CtrlPtsCountUV[0]*CtrlPtsCountUV[1], 4)).tolist())\n export_smesh(surface, smeshOutFileName)\n # surface.evaluate()\n # vis_config = VisMPL.VisConfig(legend=False, axes=False, ctrlpts=False)\n # vis_comp = VisMPL.VisSurface(vis_config)\n # surface.vis = vis_comp\n # surface.render()\n pass\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"examples/ValveReconstruction/ValveReconstruct.py","file_name":"ValveReconstruct.py","file_ext":"py","file_size_in_byte":10228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"195732142","text":"import asyncio\nimport capnp\n\nimport taskloaf.serialize\nfrom taskloaf.refcounting import Ref\nfrom taskloaf.object_ref import put, is_ref, ObjectRef\n\ndef setup_plugin(worker):\n worker.promises = dict()\n worker.protocol.add_msg_type(\n 'TASK',\n type = TaskMsg,\n handler = task_handler\n )\n worker.protocol.add_msg_type(\n 'SETRESULT',\n type = TaskMsg,\n handler = set_result_handler\n )\n worker.protocol.add_msg_type(\n 'AWAIT',\n type = TaskMsg,\n handler = await_handler\n )\n\ndef await_handler(worker, args):\n pr = args[0]\n req_addr = worker.cur_msg.sourceAddr\n async def await_wrapper(worker):\n result_ref = await pr._get_future()\n worker.send(req_addr, worker.protocol.SETRESULT, [pr, result_ref])\n worker.run_work(await_wrapper)\n\nclass Promise:\n def __init__(self, worker, running_on):\n def on_delete(_id):\n del worker.promises[_id]\n self.ref = Ref(worker, on_delete)\n self.running_on = running_on\n self.ensure_future_exists()\n\n @property\n def worker(self):\n return self.ref.worker\n\n def encode_capnp(self, msg):\n self.ref.encode_capnp(msg.ref)\n msg.runningOn = self.running_on\n\n @classmethod\n def decode_capnp(cls, worker, msg):\n out = Promise.__new__(Promise)\n out.ref = Ref.decode_capnp(worker, msg.ref)\n out.running_on = msg.runningOn\n return out\n\n def ensure_future_exists(self):\n self.worker.promises[self.ref._id] = asyncio.Future(\n loop = self.worker.ioloop\n )\n\n def _get_future(self):\n return self.worker.promises[self.ref._id]\n\n def __await__(self):\n if self.worker.addr != self.ref.owner:\n self.ensure_future_exists()\n self.worker.send(self.ref.owner, self.worker.protocol.AWAIT, [self])\n result_ref = yield from self._get_future().__await__()\n out = yield from result_ref.get().__await__()\n if isinstance(out, TaskExceptionCapture):\n raise out.e\n return out\n\n def set_result(self, result):\n self._get_future().set_result(result)\n\n def then(self, f, to = None):\n async def wait_to_start(worker):\n v = await self\n return f(worker, v)\n return task(self.worker, wait_to_start, to = to)\n\n def next(self, f, to = None):\n return self.then(lambda x: f(), to)\n\nclass TaskExceptionCapture:\n def __init__(self, e):\n self.e = e\n\ndef task_runner(worker, pr, in_f, *in_args):\n async def task_wrapper(worker):\n f = await ensure_obj(in_f)\n args = []\n for a in in_args:\n args.append(await ensure_obj(a))\n try:\n result = await worker.wait_for_work(f, *args)\n # catches all exceptions except system-exiting exceptions that inherit\n # from BaseException\n except Exception as e:\n worker.log.warning('exception during task', exc_info = True)\n result = TaskExceptionCapture(e)\n _unwrap_promise(worker, pr, result)\n worker.run_work(task_wrapper)\n\ndef _unwrap_promise(worker, pr, result):\n if isinstance(result, Promise):\n def unwrap_then(worker, x):\n _unwrap_promise(worker, pr, x)\n result.then(unwrap_then)\n else:\n result_ref = put(worker, result)\n if pr.ref.owner == worker.addr:\n pr.set_result(result_ref)\n else:\n worker.send(pr.ref.owner, worker.protocol.SETRESULT, [pr, result_ref])\n\ndef task_handler(worker, args):\n task_runner(worker, args[0], args[1], *args[2:])\n\ndef set_result_handler(worker, args):\n args[0].set_result(args[1])\n\n# f and args can be provided in two forms:\n# -- a python object (f should be callable or awaitable)\n# -- a dref to a serialized object in the memory manager\n# if f is a function and the task is being run locally, f is never serialized, but when the task is being run remotely, f is entered into the\ndef task(worker, f, *args, to = None):\n if to is None:\n to = worker.addr\n out_pr = Promise(worker, to)\n if to == worker.addr:\n task_runner(worker, out_pr, f, *args)\n else:\n msg_objs = [\n out_pr,\n ensure_ref(worker, f)\n ] + [ensure_ref(worker, a) for a in args]\n worker.send(to, worker.protocol.TASK, msg_objs)\n return out_pr\n\nasync def ensure_obj(maybe_ref):\n if is_ref(maybe_ref):\n return await maybe_ref.get()\n else:\n return maybe_ref\n\ndef ensure_ref(worker, v):\n if is_ref(v):\n return v\n return put(worker, v)\n\nclass TaskMsg:\n @staticmethod\n def serialize(args):\n pr = args[0]\n objrefs = args[1:]\n\n m = taskloaf.message_capnp.Message.new_message()\n m.init('task')\n\n pr.encode_capnp(m.task.promise)\n\n m.task.init('objrefs', len(objrefs))\n for i, ref in enumerate(objrefs):\n ref.encode_capnp(m.task.objrefs[i])\n return m\n\n @staticmethod\n def deserialize(worker, msg):\n out = [\n Promise.decode_capnp(worker, msg.task.promise)\n ]\n for i in range(len(msg.task.objrefs)):\n out.append(ObjectRef.decode_capnp(\n worker, msg.task.objrefs[i]\n ))\n return out\n\ndef when_all(ps, to = None):\n worker = ps[0].worker\n if to is None:\n to = ps[0].running_on\n async def wait_for_all(worker):\n results = []\n for i, p in enumerate(ps):\n results.append(await p)\n return results\n return task(worker, wait_for_all, to = to)\n","sub_path":"taskloaf/promise.py","file_name":"promise.py","file_ext":"py","file_size_in_byte":5613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"60290721","text":"from selenium import webdriver\r\nimport os\r\nimport xlwings as xw\r\nimport time\r\nimport re\r\n\r\nstep = str(input(\"Step to Run (1 or 2 and press Enter):\"))\r\n\r\nif step == '2':\r\n print(\"Running Website seach\")\r\n\r\n # Open saved workbook\r\n wb = xw.Book(os.path.expanduser(\"~\") +\r\n \"\\\\Desktop\\\\Contact Details.xlsx\")\r\n sht = wb.sheets[0]\r\n\r\n driver = webdriver.Chrome(os.path.expanduser(\r\n '~') + \"\\\\Desktop\\\\chromedriver.exe\")\r\n\r\n driver.set_page_load_timeout(15)\r\n\r\n def fetchInfo(link):\r\n email, phone = [], []\r\n\r\n try:\r\n driver.get(link)\r\n except:\r\n pass\r\n try:\r\n all_visible_text = driver.find_element_by_tag_name('body').text\r\n except:\r\n return [], []\r\n email = re.findall(\r\n r\"[a-zA-Z0-9_.+-]+@[a-zA-Z-]+\\.[a-zA-Z.]+\", all_visible_text)\r\n if len(email) == 0:\r\n email = re.findall(\r\n r\"[a-zA-Z0-9_.+-]+@[a-zA-Z-]+\\.[a-zA-Z.]+\\.[a-zA-Z.]\", all_visible_text)\r\n # phone = re.findall(r\"\\+[-()\\s\\d]+?(?=\\s*[+<])\", all_visible_text)\r\n all_digit_stram = re.findall('([()\\+0-9 -]+)\\n', all_visible_text)\r\n\r\n for no in all_digit_stram:\r\n no = str(no)\r\n no = no.replace(\"-\", \" \")\r\n no = no.strip()\r\n \r\n if len(no) == 0:\r\n continue\r\n if \"12345\" not in no:\r\n if \"---\" not in no:\r\n if \"-\" != no[0]:\r\n if len(no) > 10:\r\n phone = str(no)\r\n break\r\n if \"bloomberg\" in link or \"yello\" in link or \"zoominfo\" in link:\r\n print(email, phone)\r\n return email, phone\r\n \r\n if len(email) == 0:\r\n try:\r\n contact_link = driver.find_element_by_partial_link_text(\r\n \"Contact\").click()\r\n except:\r\n try:\r\n contact_link = driver.find_element_by_partial_link_text(\r\n \"CONTACT\").click()\r\n except:\r\n try:\r\n contact_link = driver.find_element_by_partial_link_text(\r\n \"touch\").click()\r\n except:\r\n try:\r\n contact_link = driver.find_element_by_partial_link_text(\r\n \"Touch\").click()\r\n except:\r\n pass\r\n try:\r\n all_visible_text = driver.find_element_by_tag_name('body').text\r\n except:\r\n return [], []\r\n email = re.findall(\r\n r\"[a-zA-Z0-9_.+-]+@[a-zA-Z-]+\\.[a-zA-Z.]+\", all_visible_text)\r\n if len(email) == 0:\r\n email = re.findall(\r\n r\"[a-zA-Z0-9_.+-]+@[a-zA-Z-]+\\.[a-zA-Z.]+\\.[a-zA-Z.]+\", all_visible_text)\r\n # phone = re.findall(r\"\\+[-()\\s\\d]+?(?=\\s*[+<])\", all_visible_text)\r\n all_digit_stram = re.findall('([()\\+0-9 -]+)\\n', all_visible_text)\r\n for no in all_digit_stram:\r\n no = str(no)\r\n no = no.replace(\"-\", \" \")\r\n no = no.strip()\r\n \r\n if len(no) == 0:\r\n continue\r\n if \"12345\" not in no:\r\n if \"---\" not in no:\r\n if \"-\" != no[0]:\r\n if len(no) > 10:\r\n phone = str(no)\r\n break\r\n print(email, phone)\r\n return email, phone\r\n\r\n r = 1\r\n count = 1\r\n i = 2\r\n while sht.range(\"B\" + str(i)).value is not None:\r\n if sht.range(\"E\" + str(i)).value == \"Googled\":\r\n companyName = sht.range(\"B\" + str(i)).value\r\n prevName = sht.range(\"B\" + str(i - 1)).value\r\n print(i, end=\" \")\r\n if companyName != prevName:\r\n for col in [\"F\",\"G\",\"H\",\"I\",\"J\",\"K\",\"L\",\"M\",\"N\",\"O\",\"P\",\"Q\",\"R\",\"S\",\"T\",\"U\"]:\r\n if sht.range(col + str(i)).value is None:\r\n continue\r\n\r\n if sht.range(col + str(i)).api.Font.Bold:\r\n link = sht.range(col + str(i)).value\r\n \r\n link = link.split(\"\\n\")[1]\r\n output = fetchInfo(link)\r\n r += 1\r\n sht.range(\"X\" + str(i)).value = \";\".join(output[0])\r\n if len(output[0]) != 0:\r\n for m in output[0]:\r\n m = m.lower().strip()\r\n if \".png\" not in m:\r\n if \".gif\" not in m:\r\n if \"panjiva\" not in m:\r\n if \"domain\" not in m:\r\n if \"example\" not in m:\r\n if \"name\" not in m:\r\n sht.range(\r\n \"C\" + str(i)).value = m\r\n count += 1\r\n break\r\n sht.range(\"Y\" + str(i)).value = str(output[1])\r\n if len(output[1]) != 0 and sht.range(\"D\" + str(i)).value is None:\r\n sht.range(\"D\" + str(i)).value = str(output[1])\r\n sht.range(\"E\" + str(i)).value = \"Site Searched\"\r\n break\r\n i += 1\r\n #break\r\n print(\"Done\", count, \" out of\", i)\r\n driver.close()\r\n\r\nif step == '1':\r\n print(\"Running google seach results\")\r\n\r\n wb = xw.Book(os.path.expanduser(\"~\") +\r\n \"\\\\Desktop\\\\Contact Details.xlsx\")\r\n sht = wb.sheets[0]\r\n\r\n driver = webdriver.Chrome(os.path.expanduser(\r\n '~') + \"\\\\Desktop\\\\chromedriver.exe\")\r\n\r\n\r\n def duckduck(companyName):\r\n\r\n url = \"https://duckduckgo.com/?q=\" + \\\r\n companyName.replace(\"& \", \"\")\r\n url = url.replace(' ', '+')\r\n driver.get(url)\r\n elems = driver.find_elements_by_tag_name(\"h2\")\r\n href_links = []\r\n\r\n for i in elems:\r\n try:\r\n link = i.text + \"\\n\" + \\\r\n i.find_elements_by_tag_name('a')[0].get_attribute(\"href\")\r\n except:\r\n break\r\n\r\n if \"linked\" in link:\r\n continue\r\n if \"panjiva\" in link:\r\n continue\r\n if \"facebook\" in link:\r\n continue\r\n\r\n href_links.append(link)\r\n\r\n return href_links\r\n\r\n\r\n def ecosia(companyName):\r\n\r\n url = \"https://www.ecosia.org/search?q=\" + \\\r\n companyName.replace(\"& \", \"\")\r\n url = url.replace(' ', '+')\r\n driver.get(url)\r\n elems = driver.find_elements_by_tag_name(\"h2\")\r\n\r\n href_links = []\r\n\r\n for i in elems:\r\n try:\r\n link = i.text + \"\\n\" + \\\r\n i.find_elements_by_tag_name('a')[0].get_attribute(\"href\")\r\n except:\r\n continue\r\n\r\n if \"linked\" in link:\r\n continue\r\n if \"panjiva\" in link:\r\n continue\r\n if \"facebook\" in link:\r\n continue\r\n if \"merriam\" in link:\r\n continue\r\n\r\n href_links.append(link)\r\n\r\n return href_links\r\n\r\n\r\n def googleSearchTile(driver, phone):\r\n '''\r\n url = \"https://www.google.com/search?q=\" + \\\r\n companyName.replace(\"& \", \"\") + \" Contact Us\"\r\n url = url.replace(' ', '+')\r\n driver.get(url)\r\n '''\r\n\r\n all_visible_text = driver.find_element_by_tag_name('body').text\r\n if len(str(phone)) < 4:\r\n try:\r\n phone = re.search(\"Phone: ([+0-9- ]+)\", all_visible_text).group(1)\r\n except:\r\n phone = \"\"\r\n\r\n email = re.findall(\r\n r\"[a-zA-Z0-9_.+-]+@[a-zA-Z-]+\\.[a-zA-Z.]+\", all_visible_text)\r\n\r\n if len(email) == 0:\r\n email = re.findall(\r\n r\"[a-zA-Z0-9_.+-]+@[a-zA-Z-]+\\.[a-zA-Z.]+\\.[a-zA-Z]+\", all_visible_text)\r\n\r\n website = \"\"\r\n\r\n for ele in driver.find_elements_by_xpath(\"//a[@role='button']\"):\r\n if \"Website\" == ele.text:\r\n website = ele.get_attribute(\"href\")\r\n try:\r\n title = driver.find_elements_by_xpath(\r\n \"//h2[@data-attrid='title']\")[0].text\r\n except:\r\n title = \"\"\r\n\r\n emailStr = \"\"\r\n\r\n if len(email) != 0:\r\n emailStr = \";\".join(email)\r\n\r\n if len(title) == 0:\r\n title = \"\"\r\n if len(website) == 0:\r\n website = \"\"\r\n\r\n tile = title + \"\\n\" + website + \"\\n\" + emailStr + \"\\n\" + phone\r\n\r\n return tile, phone\r\n\r\n\r\n def google(companyName):\r\n\r\n url = \"https://www.google.com/search?q=\" + \\\r\n companyName.replace(\"& \", \"\") # + \" Contact us\"\r\n url = url.replace(' ', '+')\r\n driver.get(url)\r\n elems = driver.find_elements_by_tag_name(\"a\")\r\n\r\n href_links = []\r\n\r\n for i in elems:\r\n try:\r\n link = i.find_elements_by_tag_name(\r\n 'h3')[0].text + \"\\n\" + i.get_attribute(\"href\")\r\n except:\r\n continue\r\n\r\n if \"linked\" in link:\r\n continue\r\n if \"panjiva\" in link:\r\n continue\r\n if \"facebook\" in link:\r\n continue\r\n if \"merriam\" in link:\r\n continue\r\n\r\n href_links.append(link)\r\n\r\n tile, phone = googleSearchTile(driver, \"0\")\r\n\r\n iffound = tile.split(\"\\n\")[2]\r\n '''\r\n if len(iffound) < 4:\r\n url = \"https://www.google.com/search?q=\" + \\\r\n companyName.replace(\"& \", \"\") + \" email\"\r\n driver.get(url)\r\n tile, phone = googleSearchTile(driver, phone)\r\n iffound = tile.split(\"\\n\")[2]\r\n\r\n if len(iffound) < 4:\r\n url = \"https://www.google.com/search?q=\" + \\\r\n companyName.replace(\"& \", \"\") + \" Contact Us\"\r\n driver.get(url)\r\n tile, phone = googleSearchTile(driver, phone)\r\n '''\r\n return tile, href_links\r\n\r\n\r\n found = 0\r\n i = 2\r\n while sht.range(\"B\" + str(i)).value is not None:\r\n if i % 3 == 0:\r\n driver.close()\r\n driver = webdriver.Chrome(os.path.expanduser(\r\n '~') + \"\\\\Desktop\\\\chromedriver.exe\")\r\n\r\n if sht.range(\"C\" + str(i)).value is None and sht.range(\"G\" + str(i)).value is None:\r\n companyName = sht.range(\"B\" + str(i)).value\r\n prevName = sht.range(\"B\" + str(i - 1)).value\r\n if companyName != prevName:\r\n\r\n output = google(companyName)\r\n\r\n sht.range(\"F\" + str(i)).value = output[0]\r\n\r\n got = output[0].split(\"\\n\")\r\n if sht.range(\"C\" + str(i)).value is None:\r\n sht.range(\"C\" + str(i)).value = got[2]\r\n if sht.range(\"D\" + str(i)).value is None:\r\n sht.range(\"D\" + str(i)).value = got[3]\r\n print(i, found, got[2:])\r\n found += 1\r\n sht.range(\"G\" + str(i)).value = output[1]\r\n\r\n sht.range(\"E\" + str(i)).value = \"Googled\"\r\n\r\n i += 1\r\n # break\r\n wb.save()\r\n driver.close()\r\n\r\n print('Done')\r\nelse:\r\n print(\"Hi Hi Hi, Wrong input :;\")\r\n time.sleep(5)\r\n","sub_path":"ContactAutoV0.2.py","file_name":"ContactAutoV0.2.py","file_ext":"py","file_size_in_byte":11777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"376970375","text":"from kanlian import constant\nfrom kanlian.models import Record, Rank\n\ndef create_record_task(**kwargs):\n pic_id = kwargs.get(\"pic_id\")\n if not pic_id:\n return False, \"invalid pic id\"\n up = 0\n down = 1.0\n spacing = 1.0\n record = Record(up=up, down=down, pic_id=pic_id, spacing=spacing)\n record.save()\n return True, \"record created\"\n\ndef create_rank_task(record_obj):\n if record_obj.spacing > constant.RECORD_ACCURACY:\n return False, \"too much spacing\"\n ## create rank from record object\n try:\n rank = Rank.objects.get(pic=record_obj.pic)\n except Rank.DoesNotExist:\n rank = Rank(pic=record_obj.pic)\n rank.order = record_obj.down\n rank.save()\n #from kanlian.utilities.rank import refresh_rank\n #refresh_rank()\n record_obj.publish = False\n record_obj.save()\n","sub_path":"kanlian/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"81468977","text":"import math\nfrom collections import defaultdict\n\nfrom dd.autoref import Function\n\nfrom famapy.core.operations.abstract_operation import Operation\n\nfrom famapy.metamodels.fm_metamodel.models.fm_configuration import FMConfiguration\nfrom famapy.metamodels.fm_metamodel.models.feature_model import FeatureModel\n\nfrom famapy.metamodels.bdd_metamodel.models.bdd_model import BDDModel\n\n\nclass ProductDistribution(Operation):\n \"\"\"The Product Distribution (PD) algorithm determines the number of products having a given number of features.\n\n It accounts for how many products have no features, one features, two features, ..., all features.\n\n It uses Bryant's method to traverse the BDD in post-order.\n \n Ref.: [Heradio et al. 2019. Supporting the Statistical Analysis of Variability Models. SPLC. (https://doi.org/10.1109/ICSE.2019.00091)]\n \"\"\"\n\n def __init__(self) -> None:\n self.result = []\n self.bdd_model = None\n \n def execute(self, model: BDDModel) -> 'ProductDistribution':\n self.bdd_model = model\n self.result = self.product_distribution()\n return self\n\n def get_result(self) -> list[FMConfiguration]:\n return self.result\n\n def product_distribution(self) -> list[int]:\n \"\"\"It accounts for how many products have no features, one features, two features, ..., all features.\n\n It uses Bryant's method to traverse the BDD in post-order \n by calling the auxiliary function `get_prod_dist` with the BDD root as argument.\n From the terminals to the root, it progressively obtains the partial distributions that correspond to the subBDDs\n rooted by each node, being the final distribution placed at the root.\n \"\"\"\n self.mark = defaultdict(bool) # boolean mark for every node being either all true or all false.\n self.dist = {0: [], 1: [1]} # distribution vectors: `node` -> `list[int]`\n self.negates = defaultdict(int)\n root = self.bdd_model.root\n if root.negated:\n root = ~root\n self.get_prod_dist(root)\n #print(f'DIST: {self.get_node_dist(root, False)}')\n return self.dist[self.get_node_id(root, False)] \n\n def get_prod_dist(self, n: Function):\n self.mark[n.node] = not self.mark[n.node]\n\n if not self.bdd_model.is_terminal_node(n):\n low = n.low\n high = n.high\n if low.negated:\n low = ~low\n\n # Traverse\n #low = self.bdd_model.get_low_node(n)\n if self.mark[n.node] != self.mark[low.node]:\n self.get_prod_dist(low)\n \n # Compute low_dist to account for the removed nodes through low\n removed_nodes = self.var(low) - self.var(n) - 1\n low_dist = [0] * (removed_nodes + len(self.dist[self.get_node_id(low, True)]))\n for i in range(removed_nodes+1):\n for j in range(len(self.dist[self.get_node_id(low, True)])):\n low_dist[i+j] = low_dist[i+j] + self.dist[self.get_node_id(low, True)][j] * math.comb(removed_nodes, i)\n\n # Traverse\n #high = self.bdd_model.get_high_node(n)\n if self.mark[n.node] != self.mark[high.node]:\n self.get_prod_dist(high)\n \n # Compute high_dist to account for the removed nodes through high\n removed_nodes = self.var(high) - self.var(n) - 1\n high_dist = [0] * (removed_nodes + len(self.dist[self.get_node_id(high, False)]))\n for i in range(removed_nodes+1):\n for j in range(len(self.dist[self.get_node_id(high, False)])):\n high_dist[i+j] = high_dist[i+j] + self.dist[self.get_node_id(high, False)][j] * math.comb(removed_nodes, i)\n\n print(f'Dists: {self.dist}')\n # Combine low and high distributions\n if len(low_dist) > len(high_dist):\n #dist_length = len(self.dist[low.node])\n dist_length = len(low_dist) + 1\n else:\n #dist_length = len(self.dist[high.node]) + 1\n dist_length = len(high_dist) + 1\n\n self.dist[n.node] = [0] * dist_length\n for i in range(len(low_dist)):\n self.dist[n.node][i] = low_dist[i]\n for i in range(len(high_dist)):\n self.dist[n.node][i+1] = self.dist[n.node][i+1] + high_dist[i]\n\n def var(self, n: Function) -> int:\n if self.bdd_model.is_terminal_node(n):\n return len(self.bdd_model.bdd.vars)\n else:\n return n.level\n\n def get_node_id(self, n: Function, is_low: bool) -> int:\n if self.bdd_model.is_terminal_node(n):\n if n.node == 1:\n if n.negated:\n return 0\n else:\n return 1\n else:\n if n.negated:\n return 1\n else:\n return 0\n else:\n return n.node\n\n","sub_path":"famapy/metamodels/bdd_metamodel_withObjects/operations/others/uned_product_distribution.py","file_name":"uned_product_distribution.py","file_ext":"py","file_size_in_byte":4998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"635877215","text":"#!/usr/bin/env python\n\nmary_in = open('DATA/mary.txt', 'r')\n# ...\nmary_in.close()\n\nwith open('DATA/mary.txt') as mary_in:\n for raw_line in mary_in:\n line = raw_line.rstrip()\n print(line)\nprint('-' * 60)\n\nwith open('DATA/mary.txt') as mary_in:\n contents = mary_in.read()\n print(contents)\n print(\"=\" * 10)\n print(repr(contents))\nprint('-' * 60)\n\nwith open('DATA/mary.txt') as mary_in:\n lines = mary_in.readlines()\n print(lines)\nprint('-' * 60)\n\nwith open('DATA/mary.txt') as mary_in:\n lines = [line.rstrip() for line in mary_in]\n print(lines)\nprint('-' * 60)\n\nwith open('DATA/mary.txt') as mary_in:\n lines = (line.rstrip() for line in mary_in)\n print(lines)\nprint('-' * 60)\n\n\nwith open('DATA/words.txt') as words_in:\n total = 0\n count = 0\n for line in words_in:\n length = len(line.rstrip())\n total += length\n count += 1\n\n if count == 0:\n print(\"Uh-oh\")\n exit()\n\n average_length = total / count\n\n print(\"average is {:.2f}\".format(average_length))\n\n","sub_path":"reading_text_files.py","file_name":"reading_text_files.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"585161971","text":"import json\nimport os\nimport re\nimport ssl\nfrom urllib.parse import quote, urlencode\nimport requests\nimport aiohttp\nfrom connaisseur.image import Image\nfrom connaisseur.validators.notaryv1.trust_data import TrustData\nfrom connaisseur.validators.notaryv1.tuf_role import TUFRole\nfrom connaisseur.exceptions import (\n NotFoundException,\n InvalidFormatException,\n UnknownTypeException,\n PathTraversalError,\n)\n\n\nclass Notary:\n\n name: str\n host: str\n pub_root_keys: list\n is_acr: bool\n auth: dict\n cert: str\n\n CERT_PATH = \"/app/connaisseur/certs/{}.crt\"\n\n def __init__(\n self,\n name: str,\n host: str,\n trust_roots: list,\n is_acr: bool = False,\n auth: dict = None,\n cert: str = None,\n **kwargs,\n ): # pylint: disable=unused-argument\n \"\"\"\n Creates a Notary object from a dictionary.\n \"\"\"\n\n self.name = name\n self.host = host\n self.pub_root_keys = trust_roots or []\n self.is_acr = is_acr\n if auth is None:\n auth = {}\n self.auth = {\"login\" if k == \"username\" else k: v for k, v in auth.items()}\n self.cert = self.__get_context(cert) if cert else None\n\n def __get_context(self, cert: str):\n try:\n return ssl.create_default_context(cadata=cert)\n except Exception:\n return None\n\n def get_key(self, key_name: str = None):\n \"\"\"\n Returns the public root key with name `key_name` in DER format, without any\n whitespaces. If `key_name` is None, the top most element of the public root key\n list is returned.\n\n Raises `NotFoundException` if no top most element can be found.\n \"\"\"\n\n key_name = key_name or \"default\"\n try:\n key = next(\n key[\"key\"] for key in self.pub_root_keys if key[\"name\"] == key_name\n )\n except StopIteration as err:\n msg = (\n 'Trust root \"{key_name}\" not configured for validator \"{notary_name}\".'\n )\n raise NotFoundException(\n message=msg, key_name=key_name, notary_name=self.name\n ) from err\n return \"\".join(key)\n\n @property\n def healthy(self):\n if self.is_acr:\n return True\n\n try:\n url = f\"https://{self.host}/_notary_server/health\"\n request_kwargs = {\"url\": url, \"verify\": self.cert}\n response = requests.get(**request_kwargs)\n\n return response.status_code == 200\n except Exception:\n return False\n\n async def get_trust_data(self, image: Image, role: TUFRole, token: str = None):\n im_repo = f\"{image.repository}/\" if image.repository else \"\"\n url = (\n f\"https://{self.host}/v2/{image.registry}/{im_repo}\"\n f\"{image.name}/_trust/tuf/{str(role)}.json\"\n )\n\n async with aiohttp.ClientSession() as session:\n request_kwargs = {\n \"url\": url,\n \"ssl\": self.cert,\n \"headers\": ({\"Authorization\": f\"Bearer {token}\"} if token else None),\n }\n async with session.get(**request_kwargs) as response:\n status = response.status\n if (\n status == 401\n and not token\n and (\"www-authenticate\" in [k.lower() for k in response.headers])\n ):\n auth_url = self.__parse_auth(\n {k.lower(): v for k, v in response.headers.items()}[\n \"www-authenticate\"\n ]\n )\n token = await self.__get_auth_token(auth_url)\n return await self.get_trust_data(image, role, token)\n\n if status == 404:\n msg = \"Unable to get {tuf_role} trust data from {notary_name}.\"\n raise NotFoundException(\n message=msg, notary_name=self.name, tuf_role=str(role)\n )\n\n response.raise_for_status()\n data = await response.text()\n return TrustData(json.loads(data), str(role))\n\n async def get_delegation_trust_data(\n self, image: Image, role: TUFRole, token: str = None\n ):\n try:\n return await self.get_trust_data(image, role, token)\n except Exception as ex:\n if os.environ.get(\"LOG_LEVEL\", \"INFO\") == \"DEBUG\":\n raise ex\n return None\n\n def __parse_auth(self, header: str):\n \"\"\"\n Generates an URL from the 'Www-authenticate' header, where a token can be\n requested.\n \"\"\"\n auth_types = [\n \"Basic\",\n \"Bearer\",\n \"Digest\",\n \"HOBA\",\n \"Mutual\",\n \"Negotiate\",\n \"OAuth\",\n \"SCRAM-SHA-1\",\n \"SCRAM-SHA-256\",\n \"vapid\",\n ]\n auth_type_re = re.compile(f'({\"|\".join(auth_types)}) realm')\n params_re = re.compile(r'(\\w+)=\"?([\\w./:\\-_]+)\"?')\n\n auth_type = next(iter(auth_type_re.findall(header)), None)\n params_dict = dict(params_re.findall(header))\n\n if not auth_type or auth_type != \"Bearer\":\n msg = (\n \"{auth_type} is an unsupported authentication\"\n \" type in notary {notary_name}.\"\n )\n raise UnknownTypeException(\n message=msg, auth_type=auth_type, notary_name=self.name\n )\n\n try:\n realm = quote(params_dict.pop(\"realm\"), safe=\"/:\")\n except KeyError as err:\n msg = (\n \"Unable to find authentication realm in auth\"\n \" header for notary {notary_name}.\"\n )\n raise NotFoundException(\n message=msg, notary_name=self.name, auth_header=params_dict\n ) from err\n params = urlencode(params_dict, safe=\"/:\")\n\n url = f\"{realm}?{params}\"\n\n if not url.startswith(\"https\"):\n msg = (\n \"authentication through insecure channel \"\n \"for notary {notary_name} is prohibited.\"\n )\n raise InvalidFormatException(\n message=msg, notary_name=self.name, auth_url=url\n )\n\n if \"..\" in url or url.count(\"//\") > 1:\n msg = (\n \"Potential path traversal in authentication\"\n \" url for notary {notary_name}.\"\n )\n raise PathTraversalError(message=msg, notary_name=self.name, auth_url=url)\n\n return url\n\n async def __get_auth_token(self, url: str):\n \"\"\"\n Return the JWT from the given `url`, using user and password from\n environment variables.\n\n Raises an exception if a HTTP error status code occurs.\n \"\"\"\n async with aiohttp.ClientSession() as session:\n request_kwargs = {\n \"url\": url,\n \"ssl\": self.cert,\n \"auth\": (aiohttp.BasicAuth(**self.auth) if self.auth else None),\n }\n async with session.get(**request_kwargs) as response:\n if response.status >= 500:\n msg = \"Unable to get authentication token from {auth_url}.\"\n raise NotFoundException(\n message=msg, notary_name=self.name, auth_url=url\n )\n\n response.raise_for_status()\n\n try:\n token_key = \"access_token\" if self.is_acr else \"token\"\n token = (await response.json())[token_key]\n except KeyError as err:\n msg = \"Unable to retrieve authentication token from {auth_url} response.\"\n raise NotFoundException(\n message=msg, notary_name=self.name, auth_url=url\n ) from err\n\n token_re = (\n r\"^[A-Za-z0-9-_=]+\\.[A-Za-z0-9-_=]+\\.?[A-Za-z0-9-_.+/=]*$\" # nosec\n )\n\n if not re.match(token_re, token):\n msg = \"{validation_kind} has an invalid format.\"\n raise InvalidFormatException(\n message=msg,\n validation_kind=\"Authentication token\",\n notary_name=self.name,\n auth_url=url,\n )\n return token\n","sub_path":"connaisseur/validators/notaryv1/notary.py","file_name":"notary.py","file_ext":"py","file_size_in_byte":8498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"177950582","text":"import BreezyBarb.Futures.folder as crff\nfrom BreezyBarb.Utilities.folder import opj\nimport BreezyBarb.Utilities.frames as cruf\nimport BreezyBarb.Utilities.filters as crtf\nimport BreezyBarb.Utilities.pkgstdy as crup\nimport numpy as np\n\n# test = crff.cr_ft_hs_ar.retrieve('es')\n#\n# crff.cr_ft_hs.name\n#\n# testd = sorted(list(set(test['Date'].values)))\n\nx = opj(crff.cr_ft_hs.name, 'ES.npz')\nx = cruf.DataFrame.from_bin(x)\n\n# dummy data\nx = np.random.random(20)\nx[0:4] = np.nan\nm = 5\n\nimport BreezyBarb.Stocks.folder as crsf\n\nx = crsf.cr_pr_cl.retrieve('SPY')\n\nInput = x['Close'].values\nPeriods = 50\nUseLog = 0\nBarCount = Input.shape[0]\nPeriodsInt = int(Periods)\nLambda = 2/(Periods+1)\n\nYg = np.empty(BarCount)*np.nan\nWg = np.empty(BarCount)*np.nan\nYm = np.empty(BarCount)*np.nan\nY = np.empty(BarCount)*np.nan\nValue = Input.copy()\nWgCs = np.empty(BarCount)*np.nan\n\nfor i in range(0, BarCount):\n # i = -1\n # i += 1\n if i == 0:\n Yg[i] = Value[i]\n Wg[i] = 1\n Ym[i] = Yg[i]\n else:\n for j in range(0, i):\n Wg[j] *= 1-Lambda\n if Input[i] <= Yg[0]: # insert beginning\n Yg_ = Yg.copy()\n Wg_ = Wg.copy()\n for j in range(0, i):\n Yg[j+1] = Yg_[j]\n Wg[j+1] = Wg_[j]\n Yg[0] = Value[i]\n Wg[0] = 1\n else:\n if Value[i] >= Yg[i-1]: # insert end\n Yg[i] = Value[i]\n Wg[i] = 1\n else: # insert at the middle\n jIdx = None\n for j in range(1, i):\n if (Value[i] >= Yg[j-1]) and (Value[i] <=Yg[j]):\n jIdx = j\n break\n Yg_ = Yg.copy()\n Wg_ = Wg.copy()\n for j in range(jIdx, i):\n Yg[j+1] = Yg_[j]\n Wg[j+1] = Wg_[j]\n Yg[jIdx] = Value[i]\n Wg[jIdx] = 1\n for j in range(0, i+1):\n if j == 0:\n WgCs[0] = Wg[0]\n WgSm = Wg[0]\n else:\n WgCs[j] = WgCs[j-1]+Wg[j]\n WgSm += WgCs[j]\n WgCs /= WgCs[i] # bug before\n jIdx = i\n for j in range(0, i+1):\n if WgCs[j] > 0.5:\n jIdx = j\n break\n if abs(WgCs[jIdx-1]-0.5) < 1e-10:\n Ym[i] = Yg[jIdx-1]\n elif abs(WgCs[jIdx]-0.5) < 1e-10:\n Ym[i] = Yg[jIdx]\n else:\n Ym[i] = ((0.5-WgCs[jIdx-1])*Yg[jIdx]+(WgCs[jIdx]-0.5)*Yg[jIdx-1])/(WgCs[jIdx]-WgCs[jIdx-1])\n if i-1 > PeriodsInt:\n Y[i] = Ym[i]\n\n\n\n\n print(i)\n print(Value[0:20])\n print(Yg[0:20])\n print(Wg[0:20])\n print(WgCs[0:20])\n print(jIdx)\n print(WgCs[jIdx])\n print(Ym[0:25])\n print(Y[0:25])\n\ncrup.plot_ts(x['Date'].values, Input)\ncrup.plot_ts(x['Date'].values, Y)\nY2 = crtf.ema(Input, Periods)\ncrup.plot_ts(x['Date'].values, Y2)\n\n\n\n\n#\n# def mma(x, m, lg=False):\n# n = x.shape[0]\n# ny = crtf.fst_nan(x)\n# mi = int(m)\n# x1 = crtf.fill(x)\n# y = np.empty(n)*np.nan\n# ym = np.empty(n)*np.nan\n# yg = np.empty(n-ny)*np.nan\n# wg = np.empty(n-ny)*np.nan\n# # wgcs = np.empty(n-ny)*np.nan\n# lmb = 2/(m+1)\n# if lg:\n# x1 = np.log(x1)\n# if ny < n and mi < n-ny+1:\n# for i in range(ny, n):\n# # i = n-1\n# if i == ny:\n# yg[0] = x1[i]\n# wg[0] = 1\n# ym[i] = yg[0]\n# else:\n# # multiply previous weights by lmb\n# wg[0:i-ny] *= (1-lmb)\n# if x1[i] >= yg[i-ny-1]: # add at the end\n# yg[i-ny] = x1[i]\n# wg[i-ny] = 1\n# elif x1[i] <= yg[0]: # add at the beginning\n# yg[1:i-ny+1] = yg[0:i-ny] # push everything\n# wg[1:i-ny+1] = wg[0:i-ny]\n# yg[0] = x1[i]\n# wg[0] = 1\n# else:\n# for j in range(1, i-ny):\n# if yg[j-1] <= x1[i] <= yg[j]:\n# # insert in between\n# yg[j+1:i-ny+1] = yg[j:i-ny]\n# wg[j+1:i-ny+1] = wg[j:i-ny]\n# yg[j] = x1[i]\n# wg[j] = 1\n# break\n# # now calculate the median\n# wgcs = np.cumsum(wg/np.nansum(wg))\n# widx = np.where(wgcs[0:i-ny+1] <= 0.5)[0][-1]\n# if abs(wgcs[widx]-0.5) < 1e-10:\n# ym[i] = yg[widx]\n# else:\n# ym[i] = ((0.5-wgcs[widx])*yg[widx+1]+(wgcs[widx+1]-0.5)*yg[widx])/(wgcs[widx+1]-wgcs[widx])\n# if i-ny+2 > mi:\n# y[i] = ym[i]\n# if lg:\n# y = np.exp(y)\n# return y\n#\n\n\n\n\n\n\n\n","sub_path":"BreezyBarb/Tests/testfutclass.py","file_name":"testfutclass.py","file_ext":"py","file_size_in_byte":4900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"362672032","text":"# -*- coding: utf-8 -*-\n# 国家企业信用信息系统(广西) 企业经营异常名录-列入\nimport scrapy\nimport time\nimport re\nfrom scrapy_migrate_project.items import crawler114\n\nclass Gx019InSpider(scrapy.Spider):\n name = 'crawler114_19'\n allowed_domains = ['gx.gsxt.gov.cn']\n start_urls = ['http://gx.gsxt.gov.cn/xxgg/xxggAction!queryGgxx.dhtml?vchr_bmdm=¬itype=11¬iceTitle=%E8%AF%B7%E8%BE%93%E5%85%A5%E9%9C%80%E8%A6%81%E6%9F%A5%E8%AF%A2%E4%BF%A1%E6%81%AF&pageNos=1']\n\n # 列表页\n def parse(self, response):\n li_list = response.xpath('//table[@class=\"noticelist-t\"]/tr')\n for li in li_list:\n item = crawler114()\n title = li.xpath('./td[1]/a/text()').extract_first()\n\n href = li.xpath('./td[1]/a/@href').extract_first()\n href = 'http://gx.gsxt.gov.cn' + href\n item['pun_org'] = li.xpath('./td[2]/text()').extract_first()\n pun_date = li.xpath('./td[3]/text()').extract_first()\n item['pun_date'] = pun_date\n item['ent_name'] = title.replace(u'关于将', '').replace(u'列入经营异常名录的公告', '')\n hashcode = hash(title + pun_date)\n item['data_id'] = 'gx' + '-' + str(hashcode)\n yield scrapy.Request(href,\n callback=self.parse_detail,\n meta={'item': item})\n\n # 翻页\n url = response.url\n cur_page = url.split('pageNos=')[-1]\n\n total_pages = response.xpath('//div[@class=\"pages\"]/span[2]/text()').extract_first()\n total_pages = total_pages.replace(u'\\xa0', u' ')\n total_pages = re.findall('.*?(\\d+).*?', total_pages)[0]\n\n if int(cur_page) < int(total_pages):\n next_page = int(cur_page) + 1\n next_href ='http://gx.gsxt.gov.cn/xxgg/xxggAction!queryGgxx.dhtml?vchr_bmdm=¬itype=11¬iceTitle=%E8%AF%B7%E8%BE%93%E5%85%A5%E9%9C%80%E8%A6%81%E6%9F%A5%E8%AF%A2%E4%BF%A1%E6%81%AF&pageNos='+str(next_page)\n yield scrapy.Request(next_href,\n callback=self.parse)\n\n # 详情页\n def parse_detail(self, response):\n item = response.meta['item']\n url = response.url\n item['source_url'] = url\n item['spider_name'] = self.name\n data = response.text\n item['source_page'] = data\n item['pun_reason'] = response.xpath('//div[@class=\"box\"]/div/p[1]/span/text()').extract_first().replace(u'\\xa0', u' ')\n item['data_source'] = self.name\n item['del_flag'] = '0'\n item['op_flag'] = 'a'\n item['create_date'] = time.strftime('%Y-%m-%d', time.localtime())\n item['case_no'] = response.xpath('//h4[@class=\"ggwh_class\"]/text()').extract_first()\n item['reg_no'] = ''\n item['report_year'] = ''\n item['notice_id'] = ''\n yield item\n\n","sub_path":"scrapy_migrate_project/spiders/tag_oe/province_guangxi/crawler114_19.py","file_name":"crawler114_19.py","file_ext":"py","file_size_in_byte":2871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"191215984","text":"\"\"\"Salus iT600 gateway API.\"\"\"\n\nimport asyncio\nimport json\nimport logging\nfrom typing import Any, Dict, List, Optional, Callable, Awaitable\n\nimport aiohttp\nimport async_timeout\n\nfrom aiohttp import client_exceptions\n\nfrom .const import (\n CURRENT_HVAC_HEAT,\n CURRENT_HVAC_HEAT_IDLE,\n CURRENT_HVAC_COOL,\n CURRENT_HVAC_COOL_IDLE,\n CURRENT_HVAC_IDLE,\n CURRENT_HVAC_OFF,\n HVAC_MODE_HEAT,\n HVAC_MODE_COOL,\n HVAC_MODE_OFF,\n HVAC_MODE_AUTO,\n PRESET_FOLLOW_SCHEDULE,\n PRESET_OFF,\n PRESET_PERMANENT_HOLD,\n PRESET_TEMPORARY_HOLD,\n PRESET_ECO,\n SUPPORT_FAN_MODE,\n SUPPORT_PRESET_MODE,\n SUPPORT_TARGET_TEMPERATURE,\n TEMP_CELSIUS,\n SUPPORT_OPEN,\n SUPPORT_CLOSE,\n SUPPORT_SET_POSITION,\n FAN_MODE_AUTO,\n FAN_MODE_HIGH,\n FAN_MODE_MEDIUM,\n FAN_MODE_LOW,\n FAN_MODE_OFF\n)\nfrom .encryptor import IT600Encryptor\nfrom .exceptions import (\n IT600AuthenticationError,\n IT600CommandError,\n IT600ConnectionError,\n)\nfrom .models import GatewayDevice, ClimateDevice, BinarySensorDevice, SwitchDevice, CoverDevice, SensorDevice\n\n_LOGGER = logging.getLogger(\"pyit600\")\n\nclass IT600Gateway:\n def __init__(\n self,\n euid: str,\n host: str,\n port: int = 80,\n request_timeout: int = 5,\n session: aiohttp.client.ClientSession = None,\n debug: bool = False,\n ):\n self._encryptor = IT600Encryptor(euid)\n self._host = host\n self._port = port\n self._request_timeout = request_timeout\n self._debug = debug\n self._lock = asyncio.Lock() # Gateway supports very few concurrent requests\n\n \"\"\"Initialize connection with the iT600 gateway.\"\"\"\n self._session = session\n self._close_session = False\n\n self._gateway_device: Optional[GatewayDevice] = None\n\n self._climate_devices: Dict[str, ClimateDevice] = {}\n self._climate_update_callbacks: List[Callable[[Any], Awaitable[None]]] = []\n\n self._binary_sensor_devices: Dict[str, BinarySensorDevice] = {}\n self._binary_sensor_update_callbacks: List[Callable[[Any], Awaitable[None]]] = []\n\n self._switch_devices: Dict[str, SwitchDevice] = {}\n self._switch_update_callbacks: List[Callable[[Any], Awaitable[None]]] = []\n\n self._cover_devices: Dict[str, CoverDevice] = {}\n self._cover_update_callbacks: List[Callable[[Any], Awaitable[None]]] = []\n\n self._sensor_devices: Dict[str, SensorDevice] = {}\n self._sensor_update_callbacks: List[Callable[[Any], Awaitable[None]]] = []\n\n async def connect(self) -> str:\n \"\"\"Public method for connecting to Salus universal gateway.\n On successful connection, returns gateway's mac address\"\"\"\n\n _LOGGER.debug(\"Trying to connect to gateway at %s\", self._host)\n\n if self._session is None:\n self._session = aiohttp.ClientSession()\n self._close_session = True\n\n try:\n all_devices = await self._make_encrypted_request(\n \"read\",\n {\n \"requestAttr\": \"readall\"\n }\n )\n\n gateway = next(\n filter(lambda x: len(x.get(\"sGateway\", {}).get(\"NetworkLANMAC\", \"\")) > 0, all_devices[\"id\"]),\n None\n )\n\n if gateway is None:\n raise IT600CommandError(\n \"Error occurred while communicating with iT600 gateway: \"\n \"response did not contain gateway information\"\n )\n\n return gateway[\"sGateway\"][\"NetworkLANMAC\"]\n except IT600ConnectionError as ae:\n try:\n with async_timeout.timeout(self._request_timeout):\n await self._session.get(f\"http://{self._host}:{self._port}/\")\n except Exception:\n raise IT600ConnectionError(\n \"Error occurred while communicating with iT600 gateway: \"\n \"check if you have specified host/IP address correctly\"\n ) from ae\n\n raise IT600AuthenticationError(\n \"Error occurred while communicating with iT600 gateway: \"\n \"check if you have specified EUID correctly\"\n ) from ae\n\n async def poll_status(self, send_callback=False) -> None:\n \"\"\"Public method for polling the state of Salus iT600 devices.\"\"\"\n\n all_devices = await self._make_encrypted_request(\n \"read\",\n {\n \"requestAttr\": \"readall\"\n }\n )\n\n try:\n gateway_devices = list(\n filter(lambda x: \"sGateway\" in x, all_devices[\"id\"])\n )\n\n await self._refresh_gateway_device(gateway_devices, send_callback)\n except BaseException as e:\n _LOGGER.error(\"Failed to poll gateway device\", exc_info=e)\n\n try:\n climate_devices = list(\n filter(lambda x: (\"sIT600TH\" in x) or (\"sTherS\" in x), all_devices[\"id\"])\n )\n\n await self._refresh_climate_devices(climate_devices, send_callback)\n except BaseException as e:\n _LOGGER.error(\"Failed to poll climate devices\", exc_info=e)\n\n try:\n binary_sensors = list(\n filter(lambda x: \"sIASZS\" in x or\n (\"sBasicS\" in x and\n \"ModelIdentifier\" in x[\"sBasicS\"] and\n x[\"sBasicS\"][\"ModelIdentifier\"] in [\"it600MINITRV\", \"it600Receiver\"]), all_devices[\"id\"])\n )\n\n await self._refresh_binary_sensor_devices(binary_sensors, send_callback)\n except BaseException as e:\n _LOGGER.error(\"Failed to poll binary sensors\", exc_info=e)\n\n try:\n sensors = list(\n filter(lambda x: \"sTempS\" in x, all_devices[\"id\"])\n )\n\n await self._refresh_sensor_devices(sensors, send_callback)\n except BaseException as e:\n _LOGGER.error(\"Failed to poll sensors\", exc_info=e)\n\n try:\n switches = list(\n filter(lambda x: \"sOnOffS\" in x, all_devices[\"id\"])\n )\n\n await self._refresh_switch_devices(switches, send_callback)\n except BaseException as e:\n _LOGGER.error(\"Failed to poll switches\", exc_info=e)\n\n try:\n covers = list(\n filter(lambda x: \"sLevelS\" in x, all_devices[\"id\"])\n )\n\n await self._refresh_cover_devices(covers, send_callback)\n except BaseException as e:\n _LOGGER.error(\"Failed to poll covers\", exc_info=e)\n\n async def _refresh_gateway_device(self, devices: List[Any], send_callback=False):\n local_device: Optional[GatewayDevice] = None\n\n if devices:\n status = await self._make_encrypted_request(\n \"read\",\n {\n \"requestAttr\": \"deviceid\",\n \"id\": [{\"data\": device[\"data\"]} for device in devices]\n }\n )\n\n for device_status in status[\"id\"]:\n unique_id = device_status.get(\"sGateway\", {}).get(\"NetworkLANMAC\", None)\n\n if unique_id is None:\n continue\n\n model: Optional[str] = device_status.get(\"sGateway\", {}).get(\"ModelIdentifier\", None)\n\n try:\n local_device = GatewayDevice(\n name=model,\n unique_id=unique_id,\n data=device_status[\"data\"],\n manufacturer=device_status.get(\"sBasicS\", {}).get(\"ManufactureName\", \"SALUS\"),\n model=model,\n sw_version=device_status.get(\"sOTA\", {}).get(\"OTAFirmwareVersion_d\", None)\n )\n except BaseException as e:\n _LOGGER.error(f\"Failed to poll gateway {unique_id}\", exc_info=e)\n\n self._gateway_device = local_device\n _LOGGER.debug(\"Refreshed gateway device\")\n\n async def _refresh_cover_devices(self, devices: List[Any], send_callback=False):\n local_devices = {}\n\n if devices:\n status = await self._make_encrypted_request(\n \"read\",\n {\n \"requestAttr\": \"deviceid\",\n \"id\": [{\"data\": device[\"data\"]} for device in devices]\n }\n )\n\n for device_status in status[\"id\"]:\n unique_id = device_status.get(\"data\", {}).get(\"UniID\", None)\n\n if unique_id is None:\n continue\n\n try:\n if device_status.get(\"sButtonS\", {}).get(\"Mode\", None) == 0:\n continue # Skip endpoints which are disabled\n\n model: Optional[str] = device_status.get(\"DeviceL\", {}).get(\"ModelIdentifier_i\", None)\n\n current_position = device_status.get(\"sLevelS\", {}).get(\"CurrentLevel\", None)\n\n move_to_level_f = device_status.get(\"sLevelS\", {}).get(\"MoveToLevel_f\", None)\n\n if move_to_level_f is not None and len(move_to_level_f) >= 2:\n set_position = int(move_to_level_f[:2], 16)\n else:\n set_position = None\n\n device = CoverDevice(\n available=True if device_status.get(\"sZDOInfo\", {}).get(\"OnlineStatus_i\", 1) == 1 else False,\n name=json.loads(device_status.get(\"sZDO\", {}).get(\"DeviceName\", '{\"deviceName\": \"Unknown\"}'))[\"deviceName\"],\n unique_id=unique_id,\n current_cover_position=current_position,\n is_opening=None if set_position is None else current_position < set_position,\n is_closing=None if set_position is None else current_position > set_position,\n is_closed=True if current_position == 0 else False,\n supported_features=SUPPORT_OPEN | SUPPORT_CLOSE | SUPPORT_SET_POSITION,\n device_class=None,\n data=device_status[\"data\"],\n manufacturer=device_status.get(\"sBasicS\", {}).get(\"ManufactureName\", \"SALUS\"),\n model=model,\n sw_version=device_status.get(\"sZDO\", {}).get(\"FirmwareVersion\", None)\n )\n\n local_devices[device.unique_id] = device\n\n if send_callback:\n self._cover_devices[device.unique_id] = device\n await self._send_cover_update_callback(device_id=device.unique_id)\n except BaseException as e:\n _LOGGER.error(f\"Failed to poll device {unique_id}\", exc_info=e)\n\n self._cover_devices = local_devices\n _LOGGER.debug(\"Refreshed %s cover devices\", len(self._cover_devices))\n\n async def _refresh_switch_devices(self, devices: List[Any], send_callback=False):\n local_devices = {}\n\n if devices:\n status = await self._make_encrypted_request(\n \"read\",\n {\n \"requestAttr\": \"deviceid\",\n \"id\": [{\"data\": device[\"data\"]} for device in devices]\n }\n )\n\n for device_status in status[\"id\"]:\n unique_id = device_status.get(\"data\", {}).get(\"UniID\", None)\n\n if unique_id is None:\n continue\n else:\n unique_id = unique_id + \"_\" + str(device_status[\"data\"][\"Endpoint\"]) # Double switches have a different endpoint id, but the same device id\n\n try:\n if device_status.get(\"sLevelS\", None) is not None:\n continue # Skip roller shutter endpoint in combined roller shutter/relay device\n\n is_on: Optional[bool] = device_status.get(\"sOnOffS\", {}).get(\"OnOff\", None)\n\n if is_on is None:\n continue\n\n model: Optional[str] = device_status.get(\"DeviceL\", {}).get(\"ModelIdentifier_i\", None)\n\n device = SwitchDevice(\n available=True if device_status.get(\"sZDOInfo\", {}).get(\"OnlineStatus_i\", 1) == 1 else False,\n name=json.loads(device_status.get(\"sZDO\", {}).get(\"DeviceName\", '{\"deviceName\": ' + json.dumps(unique_id) + '}'))[\"deviceName\"],\n unique_id=unique_id,\n is_on=True if is_on == 1 else False,\n device_class=\"outlet\" if (model == \"SP600\" or model == \"SPE600\") else \"switch\",\n data=device_status[\"data\"],\n manufacturer=device_status.get(\"sBasicS\", {}).get(\"ManufactureName\", \"SALUS\"),\n model=model,\n sw_version=device_status.get(\"sZDO\", {}).get(\"FirmwareVersion\", None)\n )\n\n local_devices[device.unique_id] = device\n\n if send_callback:\n self._switch_devices[device.unique_id] = device\n await self._send_switch_update_callback(device_id=device.unique_id)\n except BaseException as e:\n _LOGGER.error(f\"Failed to poll device {unique_id}\", exc_info=e)\n\n self._switch_devices = local_devices\n _LOGGER.debug(\"Refreshed %s sensor devices\", len(self._switch_devices))\n\n async def _refresh_sensor_devices(self, devices: List[Any], send_callback=False):\n local_devices = {}\n\n if devices:\n status = await self._make_encrypted_request(\n \"read\",\n {\n \"requestAttr\": \"deviceid\",\n \"id\": [{\"data\": device[\"data\"]} for device in devices]\n }\n )\n\n for device_status in status[\"id\"]:\n unique_id = device_status.get(\"data\", {}).get(\"UniID\", None)\n\n if unique_id is None:\n continue\n\n try:\n temperature: Optional[int] = device_status.get(\"sTempS\", {}).get(\"MeasuredValue_x100\", None)\n\n if temperature is None:\n continue\n\n unique_id = unique_id + \"_temp\" # Some sensors also measure temperature besides their primary function (eg. SW600)\n\n model: Optional[str] = device_status.get(\"DeviceL\", {}).get(\"ModelIdentifier_i\", None)\n\n device = SensorDevice(\n available=True if device_status.get(\"sZDOInfo\", {}).get(\"OnlineStatus_i\", 1) == 1 else False,\n name=json.loads(device_status.get(\"sZDO\", {}).get(\"DeviceName\", '{\"deviceName\": \"Unknown\"}'))[\"deviceName\"],\n unique_id=unique_id,\n state=(temperature / 100),\n unit_of_measurement=TEMP_CELSIUS,\n device_class=\"temperature\",\n data=device_status[\"data\"],\n manufacturer=device_status.get(\"sBasicS\", {}).get(\"ManufactureName\", \"SALUS\"),\n model=model,\n sw_version=device_status.get(\"sZDO\", {}).get(\"FirmwareVersion\", None)\n )\n\n local_devices[device.unique_id] = device\n\n if send_callback:\n self._sensor_devices[device.unique_id] = device\n await self._send_sensor_update_callback(device_id=device.unique_id)\n except BaseException as e:\n _LOGGER.error(f\"Failed to poll device {unique_id}\", exc_info=e)\n\n self._sensor_devices = local_devices\n _LOGGER.debug(\"Refreshed %s sensor devices\", len(self._sensor_devices))\n\n async def _refresh_binary_sensor_devices(self, devices: List[Any], send_callback=False):\n local_devices = {}\n\n if devices:\n status = await self._make_encrypted_request(\n \"read\",\n {\n \"requestAttr\": \"deviceid\",\n \"id\": [{\"data\": device[\"data\"]} for device in devices]\n }\n )\n\n for device_status in status[\"id\"]:\n unique_id = device_status.get(\"data\", {}).get(\"UniID\", None)\n\n if unique_id is None:\n continue\n\n try:\n model: Optional[str] = device_status.get(\"DeviceL\", {}).get(\"ModelIdentifier_i\", None)\n if model in [\"it600MINITRV\", \"it600Receiver\"]:\n is_on: Optional[bool] = device_status.get(\"sIT600I\", {}).get(\"RelayStatus\", None)\n else:\n is_on: Optional[bool] = device_status.get(\"sIASZS\", {}).get(\"ErrorIASZSAlarmed1\", None)\n\n if is_on is None:\n continue\n\n if model == \"SB600\":\n continue # Skip button\n\n device = BinarySensorDevice(\n available=True if device_status.get(\"sZDOInfo\", {}).get(\"OnlineStatus_i\", 1) == 1 else False,\n name=json.loads(device_status.get(\"sZDO\", {}).get(\"DeviceName\", '{\"deviceName\": \"Unknown\"}'))[\"deviceName\"],\n unique_id=device_status[\"data\"][\"UniID\"],\n is_on=True if is_on == 1 else False,\n device_class=\"window\" if (model == \"SW600\" or model == \"OS600\") else\n \"moisture\" if model == \"WLS600\" else\n \"smoke\" if model == \"SmokeSensor-EM\" else\n \"valve\" if model == \"it600MINITRV\" else\n \"receiver\" if model == \"it600Receiver\" else\n None,\n data=device_status[\"data\"],\n manufacturer=device_status.get(\"sBasicS\", {}).get(\"ManufactureName\", \"SALUS\"),\n model=model,\n sw_version=device_status.get(\"sZDO\", {}).get(\"FirmwareVersion\", None)\n )\n\n local_devices[device.unique_id] = device\n\n if send_callback:\n self._binary_sensor_devices[device.unique_id] = device\n await self._send_binary_sensor_update_callback(device_id=device.unique_id)\n except BaseException as e:\n _LOGGER.error(f\"Failed to poll device {unique_id}\", exc_info=e)\n\n self._binary_sensor_devices = local_devices\n _LOGGER.debug(\"Refreshed %s binary sensor devices\", len(self._binary_sensor_devices))\n\n async def _refresh_climate_devices(self, devices: List[Any], send_callback=False):\n local_devices = {}\n\n if devices:\n status = await self._make_encrypted_request(\n \"read\",\n {\n \"requestAttr\": \"deviceid\",\n \"id\": [{\"data\": device[\"data\"]} for device in devices]\n }\n )\n\n for device_status in status[\"id\"]:\n unique_id = device_status.get(\"data\", {}).get(\"UniID\", None)\n\n if unique_id is None:\n continue\n\n try:\n model: Optional[str] = device_status.get(\"DeviceL\", {}).get(\"ModelIdentifier_i\", None)\n\n th = device_status.get(\"sIT600TH\", None)\n ther = device_status.get(\"sTherS\", None)\n scomm = device_status.get(\"sComm\", None)\n sfans = device_status.get(\"sFanS\", None)\n\n global_args = {\n \"available\": True if device_status.get(\"sZDOInfo\", {}).get(\"OnlineStatus_i\", 1) == 1 else False,\n \"name\": json.loads(device_status.get(\"sZDO\", {}).get(\"DeviceName\", '{\"deviceName\": \"Unknown\"}'))[\"deviceName\"],\n \"unique_id\": unique_id,\n \"temperature_unit\": TEMP_CELSIUS, # API always reports temperature as celsius\n \"precision\": 0.1,\n \"device_class\": \"temperature\",\n \"data\": device_status[\"data\"],\n \"manufacturer\": device_status.get(\"sBasicS\", {}).get(\"ManufactureName\", \"SALUS\"),\n \"model\": model,\n \"sw_version\": device_status.get(\"sZDO\", {}).get(\"FirmwareVersion\", None),\n }\n\n if th is not None:\n current_humidity: Optional[float] = None\n\n if model is not None and \"SQ610\" in model:\n current_humidity = th.get(\"SunnySetpoint_x100\", None) # Quantum thermostats store humidity there, other thermostats store there one of the setpoint temperatures\n\n device = ClimateDevice(\n **global_args,\n current_humidity=current_humidity,\n current_temperature=th[\"LocalTemperature_x100\"] / 100,\n target_temperature=th[\"HeatingSetpoint_x100\"] / 100,\n max_temp=th.get(\"MaxHeatSetpoint_x100\", 3500) / 100,\n min_temp=th.get(\"MinHeatSetpoint_x100\", 500) / 100,\n hvac_mode=HVAC_MODE_OFF if th[\"HoldType\"] == 7 else HVAC_MODE_HEAT if th[\"HoldType\"] == 2 else HVAC_MODE_AUTO,\n hvac_action=CURRENT_HVAC_OFF if th[\"HoldType\"] == 7 else CURRENT_HVAC_IDLE if th[\"RunningState\"] % 2 == 0 else CURRENT_HVAC_HEAT, # RunningState 0 or 128 => idle, 1 or 129 => heating\n hvac_modes=[HVAC_MODE_OFF, HVAC_MODE_HEAT, HVAC_MODE_AUTO],\n preset_mode=PRESET_OFF if th[\"HoldType\"] == 7 else PRESET_PERMANENT_HOLD if th[\"HoldType\"] == 2 else PRESET_FOLLOW_SCHEDULE,\n preset_modes=[PRESET_FOLLOW_SCHEDULE, PRESET_PERMANENT_HOLD, PRESET_OFF],\n fan_mode=None,\n fan_modes=None,\n locked=None,\n supported_features=SUPPORT_TARGET_TEMPERATURE | SUPPORT_PRESET_MODE,\n )\n elif ther is not None and scomm is not None and sfans is not None:\n is_heating: bool = (ther[\"SystemMode\"] == 4)\n fan_mode: int = sfans.get(\"FanMode\", 5)\n\n device = ClimateDevice(\n **global_args,\n current_humidity=None,\n current_temperature=ther[\"LocalTemperature_x100\"] / 100,\n target_temperature=(ther[\"HeatingSetpoint_x100\"] / 100) if is_heating else (ther[\"CoolingSetpoint_x100\"] / 100),\n max_temp=(ther.get(\"MaxHeatSetpoint_x100\", 4000) / 100) if is_heating else (ther.get(\"MaxCoolSetpoint_x100\", 4000) / 100),\n min_temp=(ther.get(\"MinHeatSetpoint_x100\", 500) / 100) if is_heating else (ther.get(\"MinCoolSetpoint_x100\", 500) / 100),\n hvac_mode=HVAC_MODE_HEAT if ther[\"SystemMode\"] == 4 else HVAC_MODE_COOL if ther[\"SystemMode\"] == 3 else HVAC_MODE_AUTO,\n hvac_action=CURRENT_HVAC_OFF if scomm[\"HoldType\"] == 7 else CURRENT_HVAC_IDLE if ther[\"RunningState\"] == 0 else CURRENT_HVAC_HEAT if is_heating and ther[\"RunningState\"] == 33 else CURRENT_HVAC_HEAT_IDLE if is_heating else CURRENT_HVAC_COOL if ther[\"RunningState\"] == 66 else CURRENT_HVAC_COOL_IDLE,\n hvac_modes=[HVAC_MODE_HEAT, HVAC_MODE_COOL, HVAC_MODE_AUTO],\n preset_mode=PRESET_OFF if scomm[\"HoldType\"] == 7 else PRESET_PERMANENT_HOLD if scomm[\"HoldType\"] == 2 else PRESET_ECO if scomm[\"HoldType\"] == 10 else PRESET_TEMPORARY_HOLD if scomm[\"HoldType\"] == 1 else PRESET_FOLLOW_SCHEDULE,\n preset_modes=[PRESET_OFF, PRESET_PERMANENT_HOLD, PRESET_ECO, PRESET_TEMPORARY_HOLD, PRESET_FOLLOW_SCHEDULE],\n fan_mode=FAN_MODE_OFF if fan_mode == 0 else FAN_MODE_HIGH if fan_mode == 3 else FAN_MODE_MEDIUM if fan_mode == 2 else FAN_MODE_LOW if fan_mode == 1 else FAN_MODE_AUTO, # fan_mode == 5 => FAN_MODE_AUTO\n fan_modes=[FAN_MODE_AUTO, FAN_MODE_HIGH, FAN_MODE_MEDIUM, FAN_MODE_LOW, FAN_MODE_OFF],\n locked=True if device_status.get(\"sTherUIS\", {}).get(\"LockKey\", 0) == 1 else False,\n supported_features=SUPPORT_TARGET_TEMPERATURE | SUPPORT_PRESET_MODE | SUPPORT_FAN_MODE,\n )\n else:\n continue\n\n local_devices[device.unique_id] = device\n\n if send_callback:\n self._climate_devices[device.unique_id] = device\n await self._send_climate_update_callback(device_id=device.unique_id)\n except BaseException as e:\n _LOGGER.error(f\"Failed to poll device {unique_id}\", exc_info=e)\n\n self._climate_devices = local_devices\n _LOGGER.debug(\"Refreshed %s climate devices\", len(self._climate_devices))\n\n async def _send_climate_update_callback(self, device_id: str) -> None:\n \"\"\"Internal method to notify all update callback subscribers.\"\"\"\n\n if self._climate_update_callbacks:\n for update_callback in self._climate_update_callbacks:\n await update_callback(device_id=device_id)\n else:\n _LOGGER.error(\"Callback for climate updates has not been set\")\n\n async def _send_binary_sensor_update_callback(self, device_id: str) -> None:\n \"\"\"Internal method to notify all update callback subscribers.\"\"\"\n\n if self._binary_sensor_update_callbacks:\n for update_callback in self._binary_sensor_update_callbacks:\n await update_callback(device_id=device_id)\n else:\n _LOGGER.error(\"Callback for binary sensor updates has not been set\")\n\n async def _send_switch_update_callback(self, device_id: str) -> None:\n \"\"\"Internal method to notify all update callback subscribers.\"\"\"\n\n if self._switch_update_callbacks:\n for update_callback in self._switch_update_callbacks:\n await update_callback(device_id=device_id)\n else:\n _LOGGER.error(\"Callback for switch updates has not been set\")\n\n async def _send_cover_update_callback(self, device_id: str) -> None:\n \"\"\"Internal method to notify all update callback subscribers.\"\"\"\n\n if self._cover_update_callbacks:\n for update_callback in self._cover_update_callbacks:\n await update_callback(device_id=device_id)\n else:\n _LOGGER.error(\"Callback for cover updates has not been set\")\n\n async def _send_sensor_update_callback(self, device_id: str) -> None:\n \"\"\"Internal method to notify all update callback subscribers.\"\"\"\n\n if self._sensor_update_callbacks:\n for update_callback in self._sensor_update_callbacks:\n await update_callback(device_id=device_id)\n else:\n _LOGGER.error(\"Callback for sensor updates has not been set\")\n\n def get_gateway_device(self) -> Optional[GatewayDevice]:\n \"\"\"Public method to return gateway device.\"\"\"\n\n return self._gateway_device\n\n def get_climate_devices(self) -> Dict[str, ClimateDevice]:\n \"\"\"Public method to return the state of all Salus IT600 climate devices.\"\"\"\n\n return self._climate_devices\n\n def get_climate_device(self, device_id: str) -> Optional[ClimateDevice]:\n \"\"\"Public method to return the state of the specified climate device.\"\"\"\n\n return self._climate_devices.get(device_id)\n\n def get_binary_sensor_devices(self) -> Dict[str, BinarySensorDevice]:\n \"\"\"Public method to return the state of all Salus IT600 binary sensor devices.\"\"\"\n\n return self._binary_sensor_devices\n\n def get_binary_sensor_device(self, device_id: str) -> Optional[BinarySensorDevice]:\n \"\"\"Public method to return the state of the specified binary sensor device.\"\"\"\n\n return self._binary_sensor_devices.get(device_id)\n\n def get_switch_devices(self) -> Dict[str, SwitchDevice]:\n \"\"\"Public method to return the state of all Salus IT600 switch devices.\"\"\"\n\n return self._switch_devices\n\n def get_switch_device(self, device_id: str) -> Optional[SwitchDevice]:\n \"\"\"Public method to return the state of the specified switch device.\"\"\"\n\n return self._switch_devices.get(device_id)\n\n def get_cover_devices(self) -> Dict[str, CoverDevice]:\n \"\"\"Public method to return the state of all Salus IT600 cover devices.\"\"\"\n\n return self._cover_devices\n\n def get_cover_device(self, device_id: str) -> Optional[CoverDevice]:\n \"\"\"Public method to return the state of the specified cover device.\"\"\"\n\n return self._cover_devices.get(device_id)\n\n def get_sensor_devices(self) -> Dict[str, SensorDevice]:\n \"\"\"Public method to return the state of all Salus IT600 sensor devices.\"\"\"\n\n return self._sensor_devices\n\n def get_sensor_device(self, device_id: str) -> Optional[SensorDevice]:\n \"\"\"Public method to return the state of the specified sensor device.\"\"\"\n\n return self._sensor_devices.get(device_id)\n\n async def set_cover_position(self, device_id: str, position: int) -> None:\n \"\"\"Public method to set position/level (where 0 means closed and 100 is fully open) on the specified cover device.\"\"\"\n\n if position < 0 or position > 100:\n raise ValueError(\"position must be between 0 and 100 (both bounds inclusive)\")\n\n device = self.get_cover_device(device_id)\n\n if device is None:\n _LOGGER.error(\"Cannot set cover position: cover device not found with the specified id: %s\", device_id)\n return\n\n await self._make_encrypted_request(\n \"write\",\n {\n \"requestAttr\": \"write\",\n \"id\": [\n {\n \"data\": device.data,\n \"sLevelS\": {\n \"SetMoveToLevel\": f\"{format(position, '02x')}FFFF\"\n },\n }\n ],\n },\n )\n\n async def open_cover(self, device_id: str) -> None:\n \"\"\"Public method to open the specified cover device.\"\"\"\n\n await self.set_cover_position(device_id, 100)\n\n async def close_cover(self, device_id: str) -> None:\n \"\"\"Public method to close the specified cover device.\"\"\"\n\n await self.set_cover_position(device_id, 0)\n\n async def turn_on_switch_device(self, device_id: str) -> None:\n \"\"\"Public method to turn on the specified switch device.\"\"\"\n\n device = self.get_switch_device(device_id)\n\n if device is None:\n _LOGGER.error(\"Cannot turn on: switch device not found with the specified id: %s\", device_id)\n return\n\n await self._make_encrypted_request(\n \"write\",\n {\n \"requestAttr\": \"write\",\n \"id\": [\n {\n \"data\": device.data,\n \"sOnOffS\": {\n \"SetOnOff\": 1\n },\n }\n ],\n },\n )\n\n async def turn_off_switch_device(self, device_id: str) -> None:\n \"\"\"Public method to turn off the specified switch device.\"\"\"\n\n device = self.get_switch_device(device_id)\n\n if device is None:\n _LOGGER.error(\"Cannot turn off: switch device not found with the specified id: %s\", device_id)\n return\n\n await self._make_encrypted_request(\n \"write\",\n {\n \"requestAttr\": \"write\",\n \"id\": [\n {\n \"data\": device.data,\n \"sOnOffS\": {\n \"SetOnOff\": 0\n },\n }\n ],\n },\n )\n\n async def set_climate_device_preset(self, device_id: str, preset: str) -> None:\n \"\"\"Public method for setting the hvac preset.\"\"\"\n\n device = self.get_climate_device(device_id)\n\n if device is None:\n _LOGGER.error(\"Cannot set mode: climate device not found with the specified id: %s\", device_id)\n return\n\n if device.model == 'FC600':\n request_data = { \"sComm\": { \"SetHoldType\": 7 if preset == PRESET_OFF else 10 if preset == PRESET_ECO else 2 if preset == PRESET_PERMANENT_HOLD else 1 if preset == PRESET_TEMPORARY_HOLD else 0 } }\n else:\n request_data = { \"sIT600TH\": { \"SetHoldType\": 7 if preset == PRESET_OFF else 2 if preset == PRESET_PERMANENT_HOLD else 0 } }\n\n await self._make_encrypted_request(\n \"write\",\n {\n \"requestAttr\": \"write\",\n \"id\": [\n {\n \"data\": device.data,\n **request_data,\n }\n ],\n },\n )\n\n async def set_climate_device_mode(self, device_id: str, mode: str) -> None:\n \"\"\"Public method for setting the hvac mode.\"\"\"\n\n device = self.get_climate_device(device_id)\n\n if device is None:\n _LOGGER.error(\"Cannot set mode: device not found with the specified id: %s\", device_id)\n return\n\n if device.model == 'FC600':\n request_data = { \"sTherS\": { \"SetSystemMode\": 4 if mode == HVAC_MODE_HEAT else 3 if mode == HVAC_MODE_COOL else HVAC_MODE_AUTO } }\n else:\n request_data = { \"sIT600TH\": { \"SetHoldType\": 7 if mode == HVAC_MODE_OFF else 0 } }\n\n await self._make_encrypted_request(\n \"write\",\n {\n \"requestAttr\": \"write\",\n \"id\": [\n {\n \"data\": device.data,\n **request_data,\n }\n ],\n },\n )\n\n async def set_climate_device_fan_mode(self, device_id: str, mode: str) -> None:\n \"\"\"Public method for setting the hvac fan mode.\"\"\"\n\n device = self.get_climate_device(device_id)\n\n if device is None:\n _LOGGER.error(\"Cannot set fan mode: device not found with the specified id: %s\", device_id)\n return\n\n request_data = { \"sFanS\": { \"FanMode\": 5 if mode == FAN_MODE_AUTO else 3 if mode == FAN_MODE_HIGH else 2 if mode == FAN_MODE_MID else 1 if mode == FAN_MODE_LOW else 0 } }\n\n await self._make_encrypted_request(\n \"write\",\n {\n \"requestAttr\": \"write\",\n \"id\": [\n {\n \"data\": device.data,\n **request_data,\n }\n ],\n },\n )\n\n async def set_climate_device_locked(self, device_id: str, locked: bool) -> None:\n \"\"\"Public method for setting the hvac locked status.\"\"\"\n\n device = self.get_climate_device(device_id)\n\n if device is None:\n _LOGGER.error(\"Cannot set locked status: device not found with the specified id: %s\", device_id)\n return\n\n request_data = { \"sTherUIS\": { \"LockKey\": 1 if locked else 0 } }\n\n await self._make_encrypted_request(\n \"write\",\n {\n \"requestAttr\": \"write\",\n \"id\": [\n {\n \"data\": device.data,\n **request_data,\n }\n ],\n },\n )\n\n async def set_climate_device_temperature(self, device_id: str, setpoint_celsius: float) -> None:\n \"\"\"Public method for setting the temperature.\"\"\"\n\n device = self.get_climate_device(device_id)\n\n if device is None:\n _LOGGER.error(\"Cannot set mode: climate device not found with the specified id: %s\", device_id)\n return\n\n if device.model == 'FC600':\n if device.hvac_mode == HVAC_MODE_COOL:\n request_data = { \"sTherS\": { \"SetCoolingSetpoint_x100\": int(self.round_to_half(setpoint_celsius) * 100) } }\n else:\n request_data = { \"sTherS\": { \"SetHeatingSetpoint_x100\": int(self.round_to_half(setpoint_celsius) * 100) } }\n else:\n request_data = { \"sIT600TH\": { \"SetHeatingSetpoint_x100\": int(self.round_to_half(setpoint_celsius) * 100) } }\n\n await self._make_encrypted_request(\n \"write\",\n {\n \"requestAttr\": \"write\",\n \"id\": [\n {\n \"data\": device.data,\n **request_data,\n }\n ],\n },\n )\n\n @staticmethod\n def round_to_half(number: float) -> float:\n \"\"\"Rounds number to half of the integer (eg. 1.01 -> 1, 1.4 -> 1.5, 1.8 -> 2)\"\"\"\n\n return round(number * 2) / 2\n\n async def add_climate_update_callback(self, method: Callable[[Any], Awaitable[None]]) -> None:\n \"\"\"Public method to add a climate callback subscriber.\"\"\"\n\n self._climate_update_callbacks.append(method)\n\n async def add_binary_sensor_update_callback(self, method: Callable[[Any], Awaitable[None]]) -> None:\n \"\"\"Public method to add a binary sensor callback subscriber.\"\"\"\n\n self._binary_sensor_update_callbacks.append(method)\n\n async def add_switch_update_callback(self, method: Callable[[Any], Awaitable[None]]) -> None:\n \"\"\"Public method to add a switch callback subscriber.\"\"\"\n\n self._switch_update_callbacks.append(method)\n\n async def add_cover_update_callback(self, method: Callable[[Any], Awaitable[None]]) -> None:\n \"\"\"Public method to add a cover callback subscriber.\"\"\"\n\n self._cover_update_callbacks.append(method)\n\n async def add_sensor_update_callback(self, method: Callable[[Any], Awaitable[None]]) -> None:\n \"\"\"Public method to add a sensor callback subscriber.\"\"\"\n\n self._sensor_update_callbacks.append(method)\n\n async def _make_encrypted_request(self, command: str, request_body: dict) -> Any:\n \"\"\"Makes encrypted Salus iT600 json request, decrypts and returns response.\"\"\"\n\n async with self._lock:\n if self._session is None:\n self._session = aiohttp.ClientSession()\n self._close_session = True\n\n try:\n request_url = f\"http://{self._host}:{self._port}/deviceid/{command}\"\n request_body_json = json.dumps(request_body)\n\n if self._debug:\n _LOGGER.debug(\"Gateway request: POST %s\\n%s\\n\", request_url, request_body_json)\n\n with async_timeout.timeout(self._request_timeout):\n resp = await self._session.post(\n request_url,\n data=self._encryptor.encrypt(request_body_json),\n headers={\"content-type\": \"application/json\"},\n )\n response_bytes = await resp.read()\n response_json_string = self._encryptor.decrypt(response_bytes)\n\n if self._debug:\n _LOGGER.debug(\"Gateway response:\\n%s\\n\", response_json_string)\n\n response_json = json.loads(response_json_string)\n\n if not response_json[\"status\"] == \"success\":\n repr_request_body = repr(request_body)\n\n _LOGGER.error(\"%s failed: %s\", command, repr_request_body)\n raise IT600CommandError(\n f\"iT600 gateway rejected '{command}' command with content '{repr_request_body}'\"\n )\n\n return response_json\n except asyncio.TimeoutError as e:\n _LOGGER.error(\"Timeout while connecting to gateway: %s\", e)\n raise IT600ConnectionError(\n \"Error occurred while communicating with iT600 gateway: timeout\"\n ) from e\n except client_exceptions.ClientConnectorError as e:\n raise IT600ConnectionError(\n \"Error occurred while communicating with iT600 gateway: \"\n \"check if you have specified host/IP address correctly\"\n ) from e\n except Exception as e:\n _LOGGER.error(\"Exception. %s / %s\", type(e), repr(e.args), e)\n raise IT600CommandError(\n \"Unknown error occurred while communicating with iT600 gateway\"\n ) from e\n\n async def close(self) -> None:\n \"\"\"Close open client session.\"\"\"\n\n if self._session and self._close_session:\n await self._session.close()\n\n async def __aenter__(self) -> \"IT600Gateway\":\n \"\"\"Async enter.\"\"\"\n\n return self\n\n async def __aexit__(self, *exc_info) -> None:\n \"\"\"Async exit.\"\"\"\n\n await self.close()\n","sub_path":"pyit600/gateway.py","file_name":"gateway.py","file_ext":"py","file_size_in_byte":41505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"376291491","text":"from flask import Flask, request, render_template, redirect, flash\nfrom todo_app.flask_config import Config\nimport os\nimport requests\nimport json\nimport pytest\n#from dotenv import find_dotenv, load_dotenv\nfrom todo_app.list_class import get_starting_list_id, add_card_to_list\nfrom todo_app.item_class import item, get_card_object, get_items_on_a_board,get_list_progress,check_if_task_recently_completed\n\n\nredirectURL = '/'\ntrello_authorisation = {'key': os.environ.get('API_KEY'),'token': os.environ.get('TOKEN')}\n\n\ndef create_app():\n\n app = Flask(__name__)\n\n myConfig = Config() \n app.config.from_object(myConfig) \n \n\n @app.route('/,,,', methods=['GET'])\n def index1(todoJobs,progressingJobs,completedJobs,doneoptions):\n cards_on_a_board_json = get_items_on_a_board()\n #cards_on_a_board_json = cards_on_a_board.json() \n my_card_instance = []\n number_of_filtered_items = 0\n\n for myitem in cards_on_a_board_json:\n item_progress = get_list_progress(myitem[\"idList\"])\n if (todoJobs ==\"showToDoItemsTrue\" and item_progress == \"todo\") or (progressingJobs == \"showProgressingItemsTrue\" and item_progress == \"inprogress\"):\n my_card_instance.append(item(myitem[\"idShort\"],myitem[\"name\"],myitem[\"id\"],myitem[\"idList\"], todoJobs, progressingJobs, completedJobs, doneoptions))\n number_of_filtered_items = number_of_filtered_items + 1\n elif (completedJobs == \"showCompletedJobsTrue\") and (item_progress == \"done\"):\n if (doneoptions == \"all\") or (doneoptions == \"xALL\"):\n my_card_instance.append(item(myitem[\"idShort\"],myitem[\"name\"],myitem[\"id\"],myitem[\"idList\"], todoJobs, progressingJobs, completedJobs, doneoptions))\n number_of_filtered_items = number_of_filtered_items + 1\n else:\n done_card_object = get_card_object(myitem[\"id\"])\n\n check_card = check_if_task_recently_completed(done_card_object)\n\n if (doneoptions == check_card):\n my_card_instance.append(item(myitem[\"idShort\"],myitem[\"name\"],myitem[\"id\"],myitem[\"idList\"], todoJobs, progressingJobs, completedJobs, doneoptions))\n number_of_filtered_items = number_of_filtered_items + 1\n\n if number_of_filtered_items == 0:\n return redirect('/showToDoItemsTrue,showProgressingItemsTrue,showCompletedJobsTrue,xALL')\n else: \n return render_template('index.html', items=my_card_instance)\n \n\n @app.route('/', methods=['GET'])\n def index():\n return redirect('/showToDoItemsTrue,showProgressingItemsTrue,showCompletedJobsTrue,all')\n\n @app.route('/add_todo_item', methods=['POST']) \n def add_todo_item(): \n new_todo_item = request.form.get('newitem', \"\")\n add_card_to_list(new_todo_item)\n todo_checkbox = request.values.get('todo_checkbox')\n progressing_checkbox = request.values.get('progressing_checkbox')\n done_checkbox = request.values.get('done_checkbox')\n done_options = request.values.get('doneitems')\n redirectURL = '/'+ todo_checkbox + ',' + progressing_checkbox + ',' + done_checkbox + ',' + done_options\n return redirect(redirectURL)\n\n @app.route('/filterResults', methods=['POST']) \n def filterResults(): \n todo_checkbox = request.form.get('todoJobs1', \"showToDoItemsFalse\")\n progressing_checkbox = request.form.get('progressingJobs', \"showProgressingJobsFalse\")\n done_checkbox = request.form.get('completedJobs', \"showCompletedJobsFalse\")\n done_options = request.values.get('doneitems',\"all\")\n redirectURL = '/'+ todo_checkbox + ',' + progressing_checkbox + ',' + done_checkbox + ',' + done_options\n return redirect(redirectURL)\n \n\n @app.route('/next_list', methods=['POST']) \n def completed(): \n target_card_id = request.values.get('id')\n todo_checkbox = request.values.get('todo_checkbox')\n progressing_checkbox = request.values.get('progressing_checkbox')\n done_checkbox = request.values.get('done_checkbox')\n done_options = request.values.get('doneitems')\n target_card = get_card_object(target_card_id) \n\n my_item = item(target_card[\"idShort\"],target_card[\"name\"],target_card_id,target_card[\"idList\"],todo_checkbox, progressing_checkbox, done_checkbox,done_options)\n my_item.update_card_list()\n \n redirectURL = '/'+ todo_checkbox + ',' + progressing_checkbox + ',' + done_checkbox + ',' + done_options\n return redirect(redirectURL)\n\n @app.route('/delete', methods=['POST']) \n def delete(): \n target_card_id = request.values.get('id')\n \n todo_checkbox = request.values.get('todo_checkbox')\n progressing_checkbox = request.values.get('progressing_checkbox')\n done_checkbox = request.values.get('done_checkbox')\n done_options = request.values.get('doneitems')\n target_card = get_card_object(target_card_id) \n my_item = item(target_card[\"idShort\"],target_card[\"name\"],target_card_id,target_card[\"idList\"],todo_checkbox, progressing_checkbox, done_checkbox, done_options)\n my_item.delete_card()\n \n redirectURL = '/'+ todo_checkbox + ',' + progressing_checkbox + ',' + done_checkbox + ',' + done_options\n return redirect(redirectURL)\n\n \n\n if __name__ == '__main__':\n app.run(host='0.0.0.0', port=80)\n \n return app\n\napp = create_app()\n","sub_path":"todo_app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"62370529","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport logging\nimport os\nimport os.path as op\nimport pprint\nimport re\nfrom collections import Counter\n\nfrom scipy import signal\nfrom termcolor import colored\n\nfrom dataman.formats import get_valid_formats\nfrom dataman.lib.constants import DEFAULT_MEMORY_LIMIT_MB\n\nansi_escape = re.compile(r'\\x1b[^m]*m')\nlogger = logging.getLogger(__name__)\n\n\ndef butter_bandpass(lowcut, highcut, fs, order=5):\n nyq = 0.5 * fs\n low = lowcut / nyq\n high = highcut / nyq\n b, a = signal.butter(order, [low, high], btype='band')\n return b, a\n\n\ndef get_batch_size(arr, ram_limit=DEFAULT_MEMORY_LIMIT_MB):\n \"\"\"Get batch size for an array given memory limit per batch\"\"\"\n batch_size = int(ram_limit * 1e6 / arr.shape[1] / arr.dtype.itemsize)\n return batch_size\n\n\ndef get_batch_limits(length, batch_size):\n starts = [bc * batch_size for bc in range(length // batch_size + 1)]\n ends = [start + batch_size for start in starts[:-1]]\n ends.append(length)\n # if length - (length // batch_size) * batch_size:\n # batches.append(length - length % batch_size)\n # return batches\n return list(zip(starts, ends))\n\n\ndef detect_format(path, return_singlular=True):\n \"\"\"Check if/what known data formats are present at the given path and return the module needed to interact with it.\n\n Args:\n path: Target path\n return_singlular: bool, indicate whether to allow and return only a single format\n\n Returns:\n Single data format object, or list of formats\n \"\"\"\n\n formats = [fmt for fmt in get_valid_formats() if fmt.detect(path)]\n if return_singlular:\n if len(formats) == 1:\n return formats[0]\n else:\n raise ValueError('More than one format detected at target ({}): {}'.format(path, formats))\n else:\n return formats\n # formats = [f for f in [fmt.detect(path) for fmt in get_valid_formats()] if f is not None]\n # if len(formats) == 1:\n # fmt = formats[0]\n # if 'DAT' in fmt:\n # if fmt == 'DAT-File':\n # return dat\n # else:\n # if 'kwik' in fmt:\n # return kwik\n # else:\n # return open_ephys\n # logger.info('Detected format(s) {} not valid.'.format(formats))\n\n\ndef run_prb(path):\n \"\"\"Execute the .prb probe file and import resulting locals return results as dict.\n Args:\n path: file path to probe file with layout as per klusta probe file specs.\n\n Returns: Dictionary of channel groups with channel list, geometry and connectivity graph.\n \"\"\"\n\n if path is None:\n return\n\n path = op.realpath(op.expanduser(path))\n assert op.exists(path)\n with open(path, 'r') as prb:\n layout = prb.read()\n\n metadata = {}\n exec(layout, {}, metadata)\n metadata = {k.lower(): v for (k, v) in metadata.items()}\n return metadata\n\n\ndef write_prb(prb_path, channel_groups, dead_channels=None):\n \"\"\"Write a .prb file with given channel group dictionary and list of dead channels\n \"\"\"\n dead_channels = [] if dead_channels is None else dead_channels\n with open(prb_path, 'w') as prb_file:\n prb_file.write('dead_channels = {}\\n'.format(pprint.pformat(dead_channels)))\n prb_file.write('channel_groups = {}\\n'.format(pprint.pformat(channel_groups)))\n\n\ndef flat_channel_list(prb):\n \"\"\"Flat lists of all channels and bad channels given a probe dictionary.\n\n Args:\n prb: Path to probe file.\n\n Returns:\n Tuple of lists of (all, bad) channels.\n \"\"\"\n\n channels = sum([prb['channel_groups'][cg]['channels'] for cg in sorted(prb['channel_groups'])], [])\n dead_channels = prb['dead_channels'] if 'dead_channels' in prb else []\n\n return channels, dead_channels\n\n\ndef monotonic_prb(prb):\n \"\"\"Return probe file dict with monotonically increasing channel group and channel numbers.\"\"\"\n\n # FIXME: Should otherwise copy any other fields over (unknown fields warning)\n # FIXME: Correct ref like dc to indices\n chan_n = 0\n groups = prb['channel_groups']\n monotonic = {}\n for n, chg in enumerate(groups.keys()):\n monotonic[n] = {'channels': list(range(chan_n, chan_n + len(groups[chg]['channels'])))}\n chan_n += len(groups[chg]['channels'])\n\n # correct bad channel indices\n if 'dead_channels' in prb.keys():\n fcl, fbc = flat_channel_list(prb)\n dead_channels = sorted([fcl.index(bc) for bc in fbc])\n else:\n dead_channels = []\n return monotonic, dead_channels\n\n\ndef make_prb():\n raise NotImplemented\n\n\ndef make_prm():\n raise NotImplemented\n# def make_prm(dat_path, prb_path, n_channels=4):\n# prm_in = pkgr.resource_string('config', 'default.prm').decode()\n# #\n# # with open('default.prm', 'r') as prm_default:\n# # template = prm_default.read()\n#\n# base_name, _ = op.splitext(dat_path)\n# with open(base_name + '.prm', 'w') as prm_out:\n# prm_out.write(prm_in.format(experiment_name=base_name,\n# probe_file=prb_path,\n# n_channels=4))\n\n\ndef has_prb(filepath):\n \"\"\"Check if file at path has a an accompanying .prb file with the same basename.\n\n Args:\n filepath: Path to file of interest\n\n Returns:\n Path to .prb file if exists, else None\n \"\"\"\n # TODO: Use pathlib\n base_path, _ = op.splitext(op.abspath(op.expanduser(filepath)))\n probe_path = base_path + '.prb'\n if op.exists(probe_path) and op.isfile(probe_path):\n return probe_path\n\n\ndef channel_ranges(channel_list):\n \"\"\"List of channels in to ranges of consecutive channels.\n\n Args:\n channel_list: list of channel numbers (ints)\n\n Returns:\n List of list of channels grouped into consecutive sequences.\n\n Example: channel_ranges([1, 3, 4, 5]) -> [[1], [3, 4, 5]]\n \"\"\"\n\n duplicates = [c for c, n in Counter(channel_list).items() if n > 1]\n if len(duplicates):\n logger.warning(\"Channel(s) {} listed more than once\".format(duplicates))\n\n ranges = [[]]\n for channel in channel_list:\n if len(ranges[-1]) and abs(channel - ranges[-1][-1]) != 1:\n ranges.append([])\n ranges[-1].append(channel)\n return ranges\n\n\ndef fmt_channel_ranges(channels, shorten_seq=5, rs=\"tm\", c_sep=\"_\", zp=2):\n \"\"\"String of channel numbers separated with delimiters with consecutive channels\n are shortened when sequence length above threshold.\n\n Args:\n channels: list of channels\n shorten_seq: number of consecutive channels to be shortened. (default: 5)\n rs: range delimiter (default: 'tm')\n c_sep: channel delimiter (default: '_')\n zp: zero pad channel numbers (default: 2)\n\n Returns: String of channels in order they appeared in the list of channels.\n\n Example: fmt_channel_ranges([[1], [3], [5, 6, 7, 8, 9, 10]]) -> 01_03_05tm10\n \"\"\"\n c_ranges = channel_ranges(channels)\n range_strings = [c_sep.join([\"{c:0{zp}}\".format(c=c, zp=zp) for c in c_seq])\n if len(c_seq) < shorten_seq\n else \"{start:0{zp}}{rs}{end:0{zp}}\".format(start=c_seq[0], end=c_seq[-1], rs=rs, zp=zp)\n for c_seq in c_ranges]\n return c_sep.join(range_strings)\n\n\ndef fmt_size(num, unit='B', si=True, sep=' ', col=False, pad=0):\n colors = {\"k\": \"blue\", \"M\": \"green\", \"G\": \"red\", \"T\": \"cyan\",\n \"Ki\": \"blue\", \"Mi\": \"green\", \"Gi\": \"red\", \"Ti\": \"cyan\"}\n if si:\n prefixes = ['', 'k', 'M', 'G', 'T', 'P', 'E']\n else:\n prefixes = ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei']\n \n divisor = 1000 if si else 1024\n for prefix in prefixes:\n if abs(num) < divisor:\n if prefix:\n prefix = colored(prefix, colors[prefix]) if col else prefix\n return \"{:5.1f}{}{}{}\".format(num, sep, prefix, unit, pad=pad-6)\n else:\n return \"{:5.0f}{}{}{} \".format(num, sep, prefix, unit, pad=pad-6)\n num /= divisor\n\n\ndef get_needed_channels(cli_args=None):\n \"\"\"Gets a list of channels that are needed in order to process a given channel.\n \"\"\"\n if cli_args is None:\n import argparse\n parser = argparse.ArgumentParser(description=get_needed_channels.__doc__)\n parser.add_argument('probe_file', nargs=1,\n help=\"\"\"Phe probe file to be used\"\"\")\n parser.add_argument(\"groups\", nargs='+',\n help=\"\"\"A list of groups\"\"\")\n parser.add_argument(\"-f\", \"--filenames\", action='store_true',\n help=\"\"\"Returns a list of open-ephys continuous filenames, instead of a list of channel\n numbers\"\"\")\n parser.add_argument(\"-n\", \"--node\", type=int,\n help=\"\"\"A node number for the filenames (default 100)\"\"\")\n parser.add_argument(\"--zerobased\", action='store_true',\n help=\"Use klusta zero-based convention instead of open-ephys 1-based one\")\n cli_args = parser.parse_args()\n\n probe_file = cli_args.probe_file[0]\n groups = [int(g) for g in cli_args.groups]\n\n do_filenames = False\n if cli_args.filenames:\n do_filenames = True\n\n if cli_args.node:\n node = cli_args.node\n do_filenames = True\n else:\n node = 100\n\n zero_based = False\n if cli_args.zerobased:\n zero_based = True\n\n layout = run_prb(probe_file)\n\n channels = []\n for g in groups:\n channels.extend(layout['channel_groups'][g]['channels'])\n if 'reference' in layout['channel_groups']:\n channels.extend(layout['channel_groups'][g]['reference'])\n\n if 'ref_a' in layout:\n channels.extend(layout['ref_a'])\n\n if 'ref_b' in layout:\n channels.extend(layout['ref_b'])\n\n if not zero_based:\n channels = [c + 1 for c in channels]\n channels = set(channels)\n\n if do_filenames:\n fnames = [str(node) + '_CH' + str(c) + '.continuous' for c in channels]\n print('\\n'.join(fnames))\n else:\n print(' '.join(map(str, channels)))\n\n\ndef fmt_time(s, minimal=True, millis=True, delim=' '):\n \"\"\"\n Args:\n s: time in seconds (float for fractional)\n minimal: Flag, if true, only return strings for times > 0, leave rest outs\n Returns: String formatted 99h 59min 59.9s, where elements < 1 are left out optionally.\n \"\"\"\n sec_fmt = '{s:02.3f}s' if millis else '{s:02.0f}s'\n minutes_fmt = '{m:02d}min'\n hours_fmt = '{h:02d}h '\n\n ms = s-int(s)\n s = int(s)\n s_str = sec_fmt.format(s=s+ms)\n if s < 60 and minimal:\n return s_str\n\n m, s = divmod(s, 60)\n s_str = sec_fmt.format(s=s + ms)\n m_str = minutes_fmt.format(m=m)\n if m < 60 and minimal:\n return delim.join([m_str, s_str])\n\n h, m = divmod(m, 60)\n m_str = minutes_fmt.format(m=m)\n h_str = hours_fmt.format(h=h)\n return delim.join([h_str, m_str, s_str])\n # return \" {m:02d}min {s:02.3f}s\".format(h=h, m=m, s=s+ms)\n\n\ndef fext(fname):\n \"\"\"Grabs the file extension of a file.\n\n Args:\n fname: File name.\n\n Returns:\n String with file extension. Empty string, if file has no extensions.\n\n Raises:\n IOError if file does not exist or can not be accessed.\n \"\"\"\n return os.path.splitext(fname)[1]\n\n\ndef full_path(path):\n \"\"\"Return full path of a potentially relative path, including ~ expansion.\n\n Args:\n path\n\n Returns:\n Absolute(Expanduser(Path))\n \"\"\"\n return os.path.abspath(os.path.expanduser(path))\n\n\ndef path_content(path):\n \"\"\"Gathers root and first level content of a directory.\n\n Args:\n path: Relative or absolute path to a directory.\n\n Returns:\n A tuple containing the root path, the directories and the files\n contained in the root directory.\n\n (path, dir_names, file_names)\n \"\"\"\n path = full_path(path)\n assert(os.path.exists(path))\n if os.path.isdir(path):\n return next(os.walk(path))\n else:\n return os.path.basename(path), [], [path]\n\n\ndef dir_size(path):\n \"\"\"Calculate size of directory including all subdirectories and files\n\n Args:\n path: Relative or absolute path.\n\n Returns:\n Integer value of size in Bytes.\n \"\"\"\n logger.debug('dir_size path: {}'.format(path))\n assert os.path.exists(path)\n if not os.path.isdir(path):\n return os.path.getsize(path)\n\n total_size = 0\n for root, dirs, files in os.walk(path):\n for f in files:\n fp = os.path.join(root, f)\n try:\n total_size += os.path.getsize(fp)\n except OSError:\n # symbolic links cause issues\n pass\n return total_size\n\n\ndef terminal_size():\n \"\"\"Get size of currently used terminal. In many cases this is inaccurate.\n\n Returns:\n Tuple of width, height.\n\n Raises:\n Unknown error when not run from a terminal.\n \"\"\"\n # return map(int, os.popen('stty size', 'r').read().split())\n # Python 3.3+\n ts = os.get_terminal_size()\n return ts.lines, ts.columns\n\n\ndef find_getch():\n \"\"\"Helper to wait for a single character press, instead of having to use raw_input() requiring Enter\n to be pressed. Should work on all OS.\n\n Returns:\n Function that works as blocking single character input without prompt.\n \"\"\"\n # FIXME: Find where I took this piece of code from... and attribute. SO perhaps?\n try:\n import termios\n except ImportError:\n # Non-POSIX. Return msvcrt's (Windows') getch.\n import msvcrt\n return msvcrt.getch\n\n # POSIX system. Create and return a getch that manipulates the tty.\n import sys\n import tty\n\n def _getch():\n fd = sys.stdin.fileno()\n old_settings = termios.tcgetattr(fd)\n try:\n tty.setraw(fd)\n ch = sys.stdin.read(1)\n finally:\n termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n return ch\n\n return _getch\n\n\ndef strip_ansi(string):\n \"\"\"Remove the ANSI codes (e.g. color and additional formatting) from a string.\n\n Args:\n string: A string potentially containing ANSI escape codes.\n\n Returns:\n String with ANSI escape codes removed.\n \"\"\"\n return ansi_escape.sub('', string)\n\n\nif __name__ == \"__main__\":\n pass\n","sub_path":"dataman/lib/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":14375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"647342198","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport argparse\nimport bz2\nimport json\nimport pickle\nimport re\nimport sys\nfrom importlib.metadata import version\nfrom pathlib import Path\n\nfrom packaging.version import Version\n\n\ndef load_from_json(json_fp):\n '''\n Read JSON file with marker metadata\n\n :param json_fp: Path to JSON file\n '''\n with open(json_fp, 'r') as json_f:\n data = json.load(json_f)\n\n for m in data['markers']:\n data['markers'][m]['ext'] = set(data['markers'][m]['ext'])\n\n for t in data['taxonomy']:\n if isinstance(data['taxonomy'][t], list):\n data['taxonomy'][t] = tuple(data['taxonomy'][t])\n return data\n\n\ndef dump_to_json(data, json_fp):\n '''\n Dump marker metadata to JSON file\n\n :param json_fp: Path to JSON file\n '''\n for m in data['markers']:\n data['markers'][m]['ext'] = list(data['markers'][m]['ext'])\n\n with open(json_fp, 'w') as json_f:\n json.dump(data, json_f)\n\n\ndef transform_pkl_to_json(pkl_fp, json_fp):\n '''\n Read Pickle file and drop it to a JSON file\n\n :param pkl_fp: Path to input Pickle file\n :param json_fp: Path to output JSON file\n '''\n # load metadata from Pickle file\n with bz2.BZ2File(pkl_fp, 'r') as pkl_f:\n in_metadata = pickle.load(pkl_f)\n\n out_metadata = {\n 'markers': in_metadata['markers'],\n 'taxonomy': in_metadata['taxonomy'],\n 'merged_taxon': {}\n }\n\n # transform merged_taxons tuple keys to string\n for k in in_metadata['merged_taxon']:\n n = ' , '.join(k)\n out_metadata[n] = in_metadata['merged_taxon'][k]\n\n # dump metadata to JSON file\n dump_to_json(out_metadata, json_fp)\n\n\ndef validate_map_version(infile, file_type):\n '''\n Check conformity of a user-provided pkl file to Metaphlan SGB (>= v4.0).\n\n :param infile: Path to input Pickle/JSON file\n :param file_type: String definining file type, pkl or JSON. Case-insensitive\n '''\n file_type = file_type.lower()\n if file_type == 'pkl' or file_type == 'pickle':\n # load metadata from Pickle file\n with bz2.BZ2File(infile, 'r') as pkl_f:\n in_metadata = pickle.load(pkl_f)\n elif file_type == 'json':\n in_metadata = load_from_json(infile)\n else:\n raise ValueError(\"Unsupported file type to validate.\")\n\n # Get metaphlan version in $PATH\n metaphlan_version = Version(version('metaphlan'))\n\n # Ensure that there are 8 taxonomy levels separated with \"|\"s.\n # v3 DB release encodes the taxids as: ('2|1224|1236|91347|543|547|354276', 4404432)\n # v4 DB release encodes the taxids as: ('2|1224|1236|91347|543|547|354276|', 4404432)\n for k in in_metadata['taxonomy']:\n if (in_metadata['taxonomy'][k][0].count('|') != 7 and metaphlan_version >= Version('4')) or (in_metadata['taxonomy'][k][0].count('|') != 6 and metaphlan_version < Version('4')):\n # raise ValueError(\"Missing/Extra values in GCA list\")\n print(\"The input taxonomy mapping file %s is incompatible with Metaphlan v.%s in $PATH.\" % (infile, metaphlan_version))\n sys.exit(42)\n\n print(\"%s is compatible with Metaphlan v.%s.\" % (infile, metaphlan_version))\n\n\ndef transform_json_to_pkl(json_fp, pkl_fp):\n '''\n Read JSON file and drop it to a Pickle file\n\n :param json_fp: Path to input JSON file\n :param pkl_fp: Path to output Pickle file\n '''\n # load metadata from JSON file\n in_metadata = load_from_json(json_fp)\n\n out_metadata = {\n 'markers': in_metadata['markers'],\n 'taxonomy': in_metadata['taxonomy'],\n 'merged_taxon': {}\n }\n\n # transform merged_taxons keys to tuple\n for k in in_metadata['merged_taxon']:\n n = ' , '.split(k)\n out_metadata[n] = in_metadata['merged_taxon'][k]\n\n # dump metadata to Pickle file\n with bz2.BZ2File(pkl_fp, 'w') as pkl_f:\n pickle.dump(out_metadata, pkl_f)\n\n\ndef add_marker(in_json_fp, out_json_fp, name, m_length, g_length, gca, k_name, k_id, p_name, p_id, c_name, c_id, o_name, o_id, f_name, f_id, g_name, g_id, s_name, s_id, t_name):\n '''\n Add marker to JSON file\n\n :param in_json_fp: Path to input JSON file\n :param out_json_fp: Path to output JSON file\n :param name: Name of new marker\n :param m_length: Length of new marker\n :param g_length: List with lengths of genomes from which the new marker has been extracted\n :param gca: List with GCA of genomes from which the new marker has been extracted\n :param k_name: List with Name of Kingdom for genomes from which the new marker has been extracted\n :param k_id: List with NCBI id of Kingdom for genomes from which the new marker has been extracted\n :param p_name: List with Name of Phylum for genomes from which the new marker has been extracted\n :param p_id: List with NCBI id of Phylum for genomes from which the new marker has been extracted\n :param c_name: List with Name of Class for genomes from which the new marker has been extracted\n :param c_id: List with NCBI id of Class for genomes from which the new marker has been extracted\n :param o_name: List with Name of Order for genomes from which the new marker has been extracted\n :param o_id: List with NCBI id of Order for genomes from which the new marker has been extracted\n :param f_name: List with Name of Family for genomes from which the new marker has been extracted\n :param f_id: List with NCBI id of Family for genomes from which the new marker has been extracted\n :param g_name: List with Name of Genus for genomes from which the new marker has been extracted\n :param g_id: List with NCBI id of Genus for genomes from which the new marker has been extracted\n :param s_name: List with Name of Species for genomes from which the new marker has been extracted\n :param s_id: List with NCBI id of Species for genomes from which the new marker has been extracted\n :param t_name: List with Name of Strain for genomes from which the new marker has been extracted\n '''\n metadata = load_from_json(in_json_fp)\n\n # check that all lists have same size\n genome_n = len(g_length)\n if len(gca) != genome_n:\n raise ValueError(\"Missing/Extra values in GCA list\")\n if len(k_name) != genome_n:\n raise ValueError(\"Missing/Extra values in Kingdom name list\")\n if len(k_id) != genome_n:\n raise ValueError(\"Missing/Extra values in Kingdom ID list\")\n if len(p_name) != genome_n:\n raise ValueError(\"Missing/Extra values in Phylum name list\")\n if len(p_id) != genome_n:\n raise ValueError(\"Missing/Extra values in Phylum ID list\")\n if len(c_name) != genome_n:\n raise ValueError(\"Missing/Extra values in Class name list\")\n if len(c_id) != genome_n:\n raise ValueError(\"Missing/Extra values in Class ID list\")\n if len(o_name) != genome_n:\n raise ValueError(\"Missing/Extra values in Order name list\")\n if len(o_id) != genome_n:\n raise ValueError(\"Missing/Extra values in Order ID list\")\n if len(f_name) != genome_n:\n raise ValueError(\"Missing/Extra values in Family name list\")\n if len(f_id) != genome_n:\n raise ValueError(\"Missing/Extra values in Family ID list\")\n if len(g_name) != genome_n:\n raise ValueError(\"Missing/Extra values in Genus name list\")\n if len(g_id) != genome_n:\n raise ValueError(\"Missing/Extra values in Genus ID list\")\n if len(s_name) != genome_n:\n raise ValueError(\"Missing/Extra values in Species name list\")\n if len(s_id) != genome_n:\n raise ValueError(\"Missing/Extra values in Species ID list\")\n if len(t_name) != genome_n:\n raise ValueError(\"Missing/Extra values in Strain name list\")\n\n # create dictionary to aggregate genome taxonomies and identify marker taxonomy\n taxonomy = {\n 'k': set(),\n 'p': set(),\n 'c': set(),\n 'o': set(),\n 'f': set(),\n 'g': set(),\n 's': set(),\n 't': set(),\n }\n\n # parse genomes\n for i in range(genome_n):\n # add taxonomy of new genome\n g_taxo_names = \"k__%s|p__%s|c__%s|o__%s|f__%s|g__%s|s__%s|t__%s\" % (\n k_name[i],\n p_name[i],\n c_name[i],\n o_name[i],\n f_name[i],\n g_name[i],\n s_name[i],\n t_name[i]\n )\n g_taxo_ids = \"%s|%s|%s|%s|%s|%s|%s\" % (\n k_id[i],\n p_id[i],\n c_id[i],\n o_id[i],\n f_id[i],\n g_id[i],\n s_id[i]\n )\n metadata['taxonomy'][g_taxo_names] = (g_taxo_ids, g_length[i])\n # aggregate taxon levels using sets\n taxonomy['k'].add(k_name[i])\n taxonomy['p'].add(p_name[i])\n taxonomy['c'].add(c_name[i])\n taxonomy['o'].add(o_name[i])\n taxonomy['f'].add(f_name[i])\n taxonomy['g'].add(g_name[i])\n taxonomy['s'].add(s_name[i])\n taxonomy['t'].add(t_name[i])\n\n # extract clade and taxon of marker\n clade = '' # last level before taxomy of genomes diverge\n taxon = '' # combination of levels before divergence\n for level in ['k', 'p', 'c', 'o', 'f', 'g', 's', 't']:\n taxo = list(taxonomy[level])\n if len(taxo) == 1:\n clade = taxo[0]\n taxon = \"%s|%s__%s\" % (taxon, level, taxo)\n\n # add information about the new marker\n metadata['markers'][name] = {\n 'clade': clade,\n 'ext': set(gca),\n 'len': m_length,\n 'taxon': taxon\n }\n\n dump_to_json(metadata, out_json_fp)\n\n\ndef format_markers(marker_l):\n '''\n Format markers\n\n :param marker_l: list of markers\n '''\n markers = []\n for m in marker_l:\n m = m.rstrip()\n if ' ' in m:\n markers.append(m.split(' ')[0])\n else:\n markers.append(m)\n return markers\n\n\ndef get_markers(marker_fp):\n '''\n Get markers from a file\n\n :param marker_fp: Path to file with markers (1 per line)\n '''\n # load markers\n with open(marker_fp, 'r') as marker_f:\n markers = marker_f.readlines()\n\n # format markers\n markers = format_markers(markers)\n\n return markers\n\n\ndef check_not_found_markers(found_markers, original_markers):\n '''\n Check list of markers\n\n :param found_markers: list of found markers\n :param original_markers: list of original markers\n '''\n if len(found_markers) != len(original_markers):\n print('markers not found:')\n for m in original_markers:\n if m not in found_markers:\n print('- \"%s\"' % m)\n\n\ndef prune_taxonomy(in_taxonomy, taxon_s, gca_s):\n '''\n Prune taxonomy to keep only listed taxonomy\n\n :param in_taxonomy: dictionary with list of taxonomy\n :param taxon_s: set of taxons to keep\n :param gca_s: set of GCA ids to keep\n '''\n out_taxonomy = {}\n kept_taxonomy = set()\n kept_taxons = set()\n kept_gca = set()\n for t, v in in_taxonomy.items():\n # check if t match element in list of taxon_s\n kept_taxon = False\n for t_k in taxon_s:\n if t_k in t:\n kept_taxon = True\n out_taxonomy[t] = v\n kept_taxonomy.add(t)\n kept_taxons.add(t_k)\n break\n # check if GCA in the taxon id\n s = re.search(r'GCA_\\d+$', t)\n if s:\n gca = s[0]\n # check if GCA in taxon id is in the list GCA to keep\n if gca in gca_s:\n kept_gca.add(gca)\n if not kept_taxon:\n out_taxonomy[t] = v\n kept_taxonomy.add(t)\n\n print('%s kept taxonomy' % len(kept_taxonomy))\n print('%s / %s taxons not found' % (len(taxon_s) - len(kept_taxons), len(taxon_s)))\n print('%s / %s GCA taxons not found' % (len(gca_s) - len(kept_gca), len(gca_s)))\n return out_taxonomy\n\n\ndef remove_markers(in_json_fp, marker_fp, out_json_fp, kept_marker_fp):\n '''\n Remove markers from JSON file\n\n :param in_json_fp: Path to input JSON file\n :param marker_fp: Path to file with markers to remove (1 per line)\n :param out_json_fp: Path to output JSON file\n :param kept_marker_fp: Path to file with kept markers\n '''\n in_metadata = load_from_json(in_json_fp)\n\n # load markers\n markers_to_remove = set(get_markers(marker_fp))\n print('%s markers to remove' % len(markers_to_remove))\n\n # keep merged_taxon\n out_metadata = {\n 'markers': {},\n 'taxonomy': {},\n 'merged_taxon': in_metadata['merged_taxon']\n }\n\n # parse markers to keep\n removed_markers = []\n kept_markers = []\n taxons_to_keep = set()\n gca_to_keep = set()\n for m, v in in_metadata['markers'].items():\n if m not in markers_to_remove:\n out_metadata['markers'][m] = v\n kept_markers.append(m)\n taxons_to_keep.add(v['taxon'])\n gca_to_keep.update(v['ext'])\n else:\n removed_markers.append(m)\n print('%s removed markers' % len(removed_markers))\n\n # check markers that are not found\n check_not_found_markers(removed_markers, markers_to_remove)\n\n # keep only taxonomy in taxons_to_keep or with GCA in gca_to_keep\n out_metadata['taxonomy'] = prune_taxonomy(in_metadata['taxonomy'], taxons_to_keep, gca_to_keep)\n\n # save to JSON\n dump_to_json(out_metadata, out_json_fp)\n\n # write list of kept markers\n with open(kept_marker_fp, 'w') as kept_marker_f:\n for m in kept_markers:\n kept_marker_f.write(\"%s\\n\" % m)\n\n\ndef keep_markers(in_json_fp, marker_fp, out_json_fp):\n '''\n Keep markers from JSON file, others will be removed\n\n :param in_json_fp: Path to input JSON file\n :param marker_fp: Path to file with markers to keep (1 per line)\n :param out_json_fp: Path to output JSON file\n '''\n in_metadata = load_from_json(in_json_fp)\n\n # load markers\n markers_to_keep = set(get_markers(marker_fp))\n print('%s markers to keep' % len(markers_to_keep))\n\n # keep merged_taxon\n out_metadata = {\n 'markers': {},\n 'taxonomy': {},\n 'merged_taxon': in_metadata['merged_taxon']\n }\n\n # parse markers to keep\n kept_markers = []\n taxons_to_keep = set()\n gca_to_keep = set()\n for m, v in in_metadata['markers'].items():\n if m in markers_to_keep:\n out_metadata['markers'][m] = v\n kept_markers.append(m)\n taxons_to_keep.add(v['taxon'])\n gca_to_keep.update(v['ext'])\n print('%s kept markers' % len(kept_markers))\n\n # check markers that are not found\n check_not_found_markers(kept_markers, markers_to_keep)\n\n # keep only taxonomy in taxons_to_keep or with GCA in gca_to_keep\n out_metadata['taxonomy'] = prune_taxonomy(in_metadata['taxonomy'], taxons_to_keep, gca_to_keep)\n\n # save to JSON\n dump_to_json(out_metadata, out_json_fp)\n\n\nif __name__ == '__main__':\n # Read command line\n parser = argparse.ArgumentParser(description='Customize MetaPhlan database')\n subparsers = parser.add_subparsers(dest='function')\n # transform_pkl_to_json subcommand\n pkl_to_json_parser = subparsers.add_parser('transform_pkl_to_json', help='Transform Pickle to JSON to get marker metadata')\n pkl_to_json_parser.add_argument('--pkl', help=\"Path to input Pickle file\")\n pkl_to_json_parser.add_argument('--json', help=\"Path to output JSON file\")\n # transform_json_to_pkl subcommand\n json_to_pkl_parser = subparsers.add_parser('transform_json_to_pkl', help='Transform JSON to Pickle to push marker metadata')\n json_to_pkl_parser.add_argument('--json', help=\"Path to input JSON file\")\n json_to_pkl_parser.add_argument('--pkl', help=\"Path to output Pickle file\")\n # add_marker subcommand\n add_marker_parser = subparsers.add_parser('add_marker', help='Add new marker to JSON file')\n add_marker_parser.add_argument('--in_json', help=\"Path to input JSON file\")\n add_marker_parser.add_argument('--out_json', help=\"Path to output JSON file\")\n add_marker_parser.add_argument('--name', help=\"Name of new marker\")\n add_marker_parser.add_argument('--m_length', help=\"Length of new marker\")\n add_marker_parser.add_argument('--g_length', help=\"Length of genome from which the new marker has been extracted\", action=\"append\")\n add_marker_parser.add_argument('--gca', help=\"GCA of genome from which the new marker has been extracted\", action=\"append\")\n add_marker_parser.add_argument('--k_name', help=\"Name of Kingdom for genome from which the new marker has been extracted\", action=\"append\")\n add_marker_parser.add_argument('--k_id', help=\"NCBI id of Kingdom for genome from which the new marker has been extracted\", action=\"append\")\n add_marker_parser.add_argument('--p_name', help=\"Name of Phylum for genome from which the new marker has been extracted\", action=\"append\")\n add_marker_parser.add_argument('--p_id', help=\"NCBI id of Phylum for genome from which the new marker has been extracted\", action=\"append\")\n add_marker_parser.add_argument('--c_name', help=\"Name of Class for genome from which the new marker has been extracted\", action=\"append\")\n add_marker_parser.add_argument('--c_id', help=\"NCBI id of Class for genome from which the new marker has been extracted\", action=\"append\")\n add_marker_parser.add_argument('--o_name', help=\"Name of Order for genome from which the new marker has been extracted\", action=\"append\")\n add_marker_parser.add_argument('--o_id', help=\"NCBI id of Order for genome from which the new marker has been extracted\", action=\"append\")\n add_marker_parser.add_argument('--f_name', help=\"Name of Family for genome from which the new marker has been extracted\", action=\"append\")\n add_marker_parser.add_argument('--f_id', help=\"NCBI id of Family for genome from which the new marker has been extracted\", action=\"append\")\n add_marker_parser.add_argument('--g_name', help=\"Name of Genus for genome from which the new marker has been extracted\", action=\"append\")\n add_marker_parser.add_argument('--g_id', help=\"NCBI id of Genus for genome from which the new marker has been extracted\", action=\"append\")\n add_marker_parser.add_argument('--s_name', help=\"Name of Species for genome from which the new marker has been extracted\", action=\"append\")\n add_marker_parser.add_argument('--s_id', help=\"NCBI id of Species for genome from which the new marker has been extracted\", action=\"append\")\n add_marker_parser.add_argument('--t_name', help=\"Name of Strain for genome from which the new marker has been extracted\", action=\"append\")\n # remove_markers subcommand\n remove_markers_parser = subparsers.add_parser('remove_markers', help='Remove markers from JSON file')\n remove_markers_parser.add_argument('--in_json', help=\"Path to input JSON file\")\n remove_markers_parser.add_argument('--markers', help=\"Path to file with markers to remove (1 per line)\")\n remove_markers_parser.add_argument('--out_json', help=\"Path to output JSON file\")\n remove_markers_parser.add_argument('--kept_markers', help=\"Path to file with kept markers\")\n # keep_markers subcommand\n keep_markers_parser = subparsers.add_parser('keep_markers', help='Keep markers from JSON file, others will be removed')\n keep_markers_parser.add_argument('--in_json', help=\"Path to input JSON file\")\n keep_markers_parser.add_argument('--markers', help=\"Path to file with markers to keep (1 per line)\")\n keep_markers_parser.add_argument('--out_json', help=\"Path to output JSON file\")\n\n args = parser.parse_args()\n\n if args.function == 'transform_pkl_to_json':\n validate_map_version(Path(args.pkl), 'pkl')\n transform_pkl_to_json(Path(args.pkl), Path(args.json))\n elif args.function == 'transform_json_to_pkl':\n validate_map_version(Path(args.json), 'json')\n transform_json_to_pkl(Path(args.json), Path(args.pkl))\n elif args.function == 'add_marker':\n add_marker(\n args.in_json,\n args.out_json,\n args.name,\n args.m_length,\n args.g_length,\n args.gca,\n args.k_name,\n args.k_id,\n args.p_name,\n args.p_id,\n args.c_name,\n args.c_id,\n args.o_name,\n args.o_id,\n args.f_name,\n args.f_id,\n args.g_name,\n args.g_id,\n args.s_name,\n args.s_id,\n args.t_name)\n elif args.function == 'remove_markers':\n remove_markers(args.in_json, args.markers, args.out_json, args.kept_markers)\n elif args.function == 'keep_markers':\n keep_markers(args.in_json, args.markers, args.out_json)\n","sub_path":"tools/humann/customizemetadata.py","file_name":"customizemetadata.py","file_ext":"py","file_size_in_byte":20655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"607839099","text":"import torch, math\nfrom typing import Dict, Tuple\nfrom argparse import Namespace\nfrom transformers import BertConfig, BertModel, BertTokenizer, BertPreTrainedModel\n\nfrom retrieval.dense import BPRetrieval\n\nclass BiEncoderModel(BertPreTrainedModel):\n def __init__(self, config: BertConfig, args: Namespace) -> None:\n super().__init__(config)\n\n self.args = args\n self.bert = BertModel(config)\n self.training = False\n\n if getattr(args, \"projection_dim_size\", None) is not None:\n self.dense = torch.nn.Linear(config.hidden_size, args.retriever.projection_dim_size)\n self.layer_norm = torch.nn.LayerNorm(args.retriever.projection_dim_size, eps=config.layer_norm_eps)\n\n self.init_weights()\n\n def forward(self, *args, **kwargs) -> torch.Tensor:\n sequence_output = self.bert(*args, **kwargs)[0] # NOTE: Need to dim check\n cls_output = sequence_output[:, 0, :].contiguous() # NOTE: look again \n if getattr(self.args, \"projection_dim_size\", None) is not None:\n cls_output = self.layer_norm(self.dense(cls_output))\n\n return cls_output\n\n def convert_to_binary_code(self, input_repr: torch.Tensor, global_step: int=1) -> torch.Tensor:\n if self.training:\n # NOTE : study this difference\n if self.args.retriever.use_ste:\n hard_input_repr = input_repr.new_ones(input_repr.size()).masked_fill_(input_repr < 0, -1.0)\n input_repr = torch.tanh(input_repr)\n return hard_input_repr + input_repr - input_repr.detach()\n else:\n scale = math.pow((1.0 + global_step * self.args.retriever.hashnet_gamma), 0.5)\n return torch.tanh(input_repr * scale)\n else:\n return input_repr.new_ones(input_repr.size()).masked_fill_(input_repr < 0, -1.0)\n\nclass BPBert(BPRetrieval):\n def __init__(self, args) -> None:\n super().__init__(args)\n\n self.args = args\n\n self.backbone = \"bert-base-multilingual-cased\"\n self.tokenizer = BertTokenizer.from_pretrained(self.backbone)\n\n def _load_model(self) -> BiEncoderModel:\n config = BertConfig.from_pretrained(self.backbone)\n p_encoder = BiEncoderModel.from_pretrained(self.backbone, config=config, args=self.args).cuda()\n q_encoder = BiEncoderModel.from_pretrained(self.backbone, config=config, args=self.args).cuda()\n return p_encoder, q_encoder\n\n # Get new encoder to load pretrained encoder\n def _get_encoder(self) -> BiEncoderModel:\n config = BertConfig.from_pretrained(self.backbone)\n q_encoder = BiEncoderModel(config=config, args=self.args).cuda()\n return q_encoder\n","sub_path":"retrieval/dense/bp.py","file_name":"bp.py","file_ext":"py","file_size_in_byte":2706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"266719398","text":"#!/usr/bin/env python\n# Copyright 2020 Google LLC\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\"\"\"\nThis script schedules all the jobs to be dispatched to AppEngine.\n\"\"\"\n\nimport os\nimport sys\nfrom functools import partial\nfrom argparse import ArgumentParser\n\nfrom google.cloud import scheduler_v1\nfrom google.cloud.scheduler_v1.types import Job, AppEngineHttpTarget\n\nsys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), \"..\")))\n\n# pylint: disable=wrong-import-position\nfrom lib.pipeline_tools import get_pipelines\n\n\ndef clear_jobs(\n client: scheduler_v1.CloudSchedulerClient, project_id: str, location_id: str\n) -> None:\n \"\"\" Delete all scheduled jobs \"\"\"\n parent = client.location_path(project_id, location_id)\n for job in client.list_jobs(parent):\n client.delete_job(job.name)\n\n\ndef schedule_job(\n client: scheduler_v1.CloudSchedulerClient,\n project_id: str,\n location_id: str,\n timezone: str,\n schedule: str,\n path: str,\n) -> None:\n \"\"\" Schedules the given job for the specified project and location \"\"\"\n # Create a Job to schedule\n target = AppEngineHttpTarget(relative_uri=path, http_method=\"GET\")\n job = Job(app_engine_http_target=target, schedule=schedule, time_zone=timezone)\n\n # Schedule the Job we just created\n parent = client.location_path(project_id, location_id)\n client.create_job(parent, job)\n\n\ndef schedule_all_jobs(project_id: str, location_id: str, timezone: str) -> None:\n \"\"\"\n Clears all previously scheduled jobs and schedules all necessary jobs for the current\n configuration.\n \"\"\"\n client = scheduler_v1.CloudSchedulerClient()\n\n # Create a custom method with our parameters for ease of use\n _schedule_job = partial(\n schedule_job,\n client=client,\n project_id=project_id,\n location_id=location_id,\n timezone=timezone,\n )\n\n # Clear all pre-existing jobs\n clear_jobs(client=client, project_id=project_id, location_id=location_id)\n\n # Cache pull job runs hourly\n _schedule_job(schedule=\"0 * * * *\", path=\"/cache_pull\")\n\n # The job that publishes data into the prod bucket runs every 4 hours\n _schedule_job(\n path=\"/publish\",\n # Offset by 30 minutes to let other hourly tasks finish\n schedule=\"30 */4 * * *\",\n )\n\n # Converting the outputs to JSON is less critical but also slow so it's run separately\n _schedule_job(\n path=\"/convert_json_1\",\n # Offset by 30 minutes to run after publishing\n schedule=\"0 1-23/4 * * *\",\n )\n\n # The convert to JSON task is split in two because otherwise it takes too long\n _schedule_job(\n path=\"/convert_json_2\",\n # Offset by 30 minutes to run after publishing\n schedule=\"0 1-23/4 * * *\",\n )\n\n # Get new errors once a day at midday.\n _schedule_job(path=\"/report_errors_to_github\", schedule=\"0 12 * * *\")\n\n # Keep track of the different job groups to only output them once\n job_urls_seen = set()\n\n for data_pipeline in get_pipelines():\n # The job that combines data sources into a table runs hourly\n _schedule_job(\n path=f\"/combine_table?table={data_pipeline.table}\",\n # Offset by 15 minutes to let other hourly tasks finish\n schedule=\"15 * * * *\",\n )\n\n for idx, data_source in enumerate(data_pipeline.data_sources):\n # The job to pull each individual data source runs hourly unless specified otherwise\n job_sched = data_source.config.get(\"automation\", {}).get(\"schedule\", \"0 * * * *\")\n\n # Each data source has a job group. All data sources within the same job group are run\n # as part of the same job in series. The default job group is the index of the data\n # source.\n job_group = data_source.config.get(\"automation\", {}).get(\"job_group\", idx)\n job_url = f\"/update_table?table={data_pipeline.table}&job_group={job_group}\"\n\n if job_url not in job_urls_seen:\n job_urls_seen.add(job_url)\n _schedule_job(path=job_url, schedule=job_sched)\n\n\nif __name__ == \"__main__\":\n\n # Get default values from environment\n default_project = os.environ.get(\"GCP_PROJECT\")\n default_location = os.environ.get(\"GCP_LOCATION\", \"us-east1\")\n default_timezone = os.environ.get(\"GCP_TIMEZONE\", \"EST\")\n\n # Parse arguments from the command line\n argparser = ArgumentParser()\n argparser.add_argument(\"--project-id\", type=str, default=default_project)\n argparser.add_argument(\"--location-id\", type=str, default=default_location)\n argparser.add_argument(\"--timezone\", type=str, default=default_timezone)\n args = argparser.parse_args()\n\n # Ensure project ID is not empty, since we don't have a default value for it\n assert args.project_id is not None, 'Argument \"project-id\" must not be empty'\n\n # Clear all preexisting jobs and schedule the new ones, this assumes the current code has\n # already been successfully deployed to GAE in a previous build step\n schedule_all_jobs(args.project_id, args.location_id, args.timezone)\n","sub_path":"src/scripts/schedule_jobs.py","file_name":"schedule_jobs.py","file_ext":"py","file_size_in_byte":5621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"632749801","text":"\n# This function reads a file and returns a list with every line stripped.\ndef load(fname):\n with open(fname) as f:\n lst = []\n for line in f:\n word = line.strip()\n lst.append(word)\n return lst\n\n\ndef filterPattern(lst, pattern):\n ...\n\n\n# matchesPattern should return True iff string s matches the given pattern.\n# Each ? in pattern should match any character in the same position in s.\n# Other characters must match exactly, but case-insensitive.\ndef matchesPattern(s, pattern):\n ...\n\n\n# Uncomment these lines to test the matchesPattern function:\n#assert matchesPattern(\"secret\", \"s?c??t\") == True\n#assert matchesPattern(\"socket\", \"s?c??t\") == True\n#assert matchesPattern(\"soccer\", \"s?c??t\") == False\n#assert matchesPattern(\"SEcrEt\", \"?ecr?t\") == True, \"should be case-insensitive\"\n\n\ndef main():\n englishWords = load(\"/usr/share/dict/words\")\n\n lst = filterPattern(englishWords, \"s?c??t\")\n print(lst)\n\n assert isinstance(lst, list), \"result lst should be a list\"\n assert \"secret\" in lst, \"result should contain 'secret'\"\n\n # Solution to \"?YS???Y\"\n lst = filterPattern(englishWords, \"?ys???y\")\n print(lst)\n\n\n# Call main function:\nmain()\n\n","sub_path":"practical-classes/lab07x/findWords.py","file_name":"findWords.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"458090798","text":"import csv\n\"\"\" Calculates weighted grade from csv file \"\"\"\n\n\ndef main():\n grades = []\n possible_points = []\n with open('grades.csv', 'r', newline='', encoding='utf-8') as csv_file:\n reader = csv.reader(csv_file)\n sheet = list(reader)\n\n for row in sheet[1:]:\n grades.append(float(row[1]))\n possible_points.append(float(row[2]))\n\n score = sum(grades)\n total = sum(possible_points)\n difference = total - score\n percentage = score / total * 100\n weighted_percentage = percentage * 40 / 100\n\n with open('stats.txt', 'w', encoding='utf-8') as outfile:\n print(f'Score: {score}', file=outfile)\n print(f'Total: {total}', file=outfile)\n print(f'Difference: {difference}', file=outfile)\n print(f'Percentage: {percentage}', file=outfile)\n print(f'Weighted percentage: {weighted_percentage}', file=outfile)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"score_calculator.py","file_name":"score_calculator.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"580472661","text":"import os\nimport sqlite3\nfrom flask import Flask\nfrom flask import request, render_template\nfrom flask import jsonify\nimport sys\nfrom wtforms import Form, SelectMultipleField\nfrom flask_jsglue import JSGlue \nimport json\nimport copy\n\nNUM_ELE = 15\n\n# LIVING_INDEX_YEARS = [\"2015\", \"2016\", \"2017\", \"2018\", \"2019\"]\n\ninfo_params = {\"cost\" : [\"cost_living_index\", \"groceries_index\" , \"restaurant_price_index\"] , \"pollution\" : [\"pollution_index\"]\n , \"traffic\": [\"traffic_index\", \"time_index\", \"inefficiency_index\"], \"crime\": [\"crime_index\", \"safety_index\"] }\n\ndef dict_factory(cursor, row):\n d = {}\n for idx, col in enumerate(cursor.description):\n d[col[0]] = row[idx]\n return d\n\ndef query_db(query, num_ele = 20, all_flag = False):\n connection = sqlite3.connect('instance/flaskr.sqlite')\n connection.row_factory = dict_factory\n cursor = connection.cursor()\n cursor.execute(query)\n rows = cursor.fetchall()\n # for row in rows:\n # print(row)\n # break\n # print(rows[0])\n if all_flag:\n return rows\n return rows[:num_ele]\n\ndef get_city_info(city):\n query = \"select *, photos_nus.id as photo_id from photos_nus inner join cost_view on photos_nus.city=cost_view.city where cost_view.city like '%{}%'\" \n query = query.format(city)\n # print(query, file=sys.stderr)\n query_response = query_db(query, 1)\n return query_response\n\ndef create_json(photos_list):\n # pics_json = json.dumps(photos_list)\n # print(pics_json)\n formatted_list = []\n class_tag_overall = set()\n for photos in photos_list:\n a = dict()\n # print(photos)\n a[\"city\"] = photos['city']\n a[\"country\"] = photos['country']\n a[\"latitude\"] = photos['latitude']\n a[\"longitude\"] = photos['longitude']\n # a[\"cost_id\"] = photos['cost_id']\n a[\"popularity\"] = photos['popularity']\n a[\"class_tag_overall\"] = {}\n description_list = []\n url_list = photos['url'].split(',')\n cdn_url_list = photos['cdn_url'].split(',')\n indl_popularity_list = photos['indl_popularity'].split(',')\n # print(photos['url'])\n # print(url_list)\n class_tags_list = photos['class_tag'].split(',')\n for index in range(0,len(url_list)):\n description_dict = dict()\n description_dict[\"url\"] = url_list[index]\n description_dict[\"cdn_url\"] = cdn_url_list[index]\n description_dict[\"class_tag\"] = class_tags_list[index]\n description_dict[\"indl_popularity\"] = indl_popularity_list[index]\n # print(class_tags_list[index].split(\"-\"))\n for class_tag in class_tags_list[index].split(\"-\"):\n # print(class_tag)\n if class_tag in a[\"class_tag_overall\"]:\n a[\"class_tag_overall\"][class_tag] = a[\"class_tag_overall\"][class_tag] + 1\n else:\n a[\"class_tag_overall\"][class_tag] = 1\n class_tag_overall.add(class_tags_list[index])\n description_list.append(description_dict)\n a[\"description\"] = description_list\n for view in info_params:\n view_columns = info_params[view]\n year_list = photos[view + \"_year\"].split(\",\")\n view_columns_list = []\n for column_names in view_columns:\n view_columns_list.append(photos[column_names].split(\",\"))\n view_dict = {}\n for year_index in range(len(year_list)):\n year = year_list[year_index]\n view_dict[year] = {}\n for i in range(len(view_columns_list)):\n view_dict[year][view_columns[i]] = view_columns_list[i][year_index]\n\n a[view] = copy.deepcopy(view_dict)\n\n # cost_year_list = photos[\"year\"].split(\",\")\n # groceries_index_list = photos[\"groceries_index\"].split(\",\")\n # restaurant_price_index_list = photos[\"restaurant_price_index\"].split(\",\")\n # cost_living_index_list = photos[\"cost_living_index\"].split(\",\")\n # cost_dict = {}\n # for year_index in range(len(cost_year_list)):\n # year = year_list[year_index]\n # cost_dict[year] = {}\n # cost_dict[year][\"groceries_index\"] = groceries_index_list[year_index]\n # cost_dict[year][\"restaurant_price_index\"] = restaurant_price_index_list[year_index]\n # cost_dict[year][\"cost_living_index\"] = cost_living_index_list[year_index]\n # a[\"cost\"] = copy.deepcopy(cost_dict)\n\n\n # for year in LIVING_INDEX_YEARS:\n # a[\"cost_living_index_\" + year] = photos['cost_living_index_' + year]\n # a[\"groceries_index_\" + year] = photos['groceries_index_' + year]\n # a[\"restaurant_price_index_\" + year] = photos['restaurant_price_index_' + year]\n formatted_list.append(a)\n # print(\"$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\\n\\n\")\n # print(formatted_list)\n return formatted_list\n\ndef get_cities_of_country(pref, country):\n pref = pref.split(\",\")\n inner_query = \"select * from photos_nus where country like '{}' and (\".format(country)\n inner_query = inner_query + \" or \".join(\"class_tag like '%{}%'\".format(p) for p in pref) + \" )\" \n query = \"select * from ( select city, country, latitude, longitude, sum(popularity) as popularity,group_concat(url) as url, group_concat(cdn_url) as cdn_url, group_concat(class_tag) as class_tag, group_concat(popularity) as indl_popularity from (\" + inner_query + \" ) group by city, country ) as p inner join [cost_view] c on p.city = c.city inner join [pollution_view] po on c.city = po.city inner join [crime_view] cr on cr.city = po.city inner join [traffic_view] t on t.city = cr.city where p.country = c.country and po.country = c.country and cr.country = po.country and t.country = cr.country\" \n # print(query)\n query_resp = query_db(query)\n # print(query_resp)\n return create_json(query_resp)\n\ndef get_country_count():\n query = \"select count, country from [photo_count]\"\n country_list = query_db(query, all_flag = True)\n # print(country_list[:10])\n country_count = {x[\"country\"]:x[\"count\"] for x in country_list}\n return country_count\n \n\ndef get_top_elements_from_db(pref):\n # query = \"select * from photos where class_tag = ? order by popularity desc\"\n # query = \"select *, photos.id as photo_id from photos inner join costs_combined on photos.cost_id=costs_combined.id where class_tag = ? order by popularity desc\"\n pref = pref.split(\",\")\n print(pref)\n total_pref = len(pref)\n ret_ele = []\n inner_query = \"select * from photos_nus where class_tag like '%{}%'\"\n inner_query = inner_query.format(pref[0])\n # print(inner_query)\n if(total_pref == 2 ):\n inner_query = inner_query + \" and class_tag like '%{}%'\"\n inner_query = inner_query.format(pref[1])\n elif(total_pref == 3):\n inner_query = inner_query + \" and class_tag like '%{}%'\" + \" and class_tag like '%{}%'\"\n inner_query = inner_query.format(pref[1], pref[2])\n # for p in pref:\n # inner_query.format()\n query = \"select * from (\" \\\n \"select city, country, latitude, longitude, sum(popularity) as popularity, group_concat(url) as url, \" \\\n \"group_concat(cdn_url) as cdn_url, group_concat(class_tag) as class_tag, group_concat(popularity) as \" \\\n \"indl_popularity from (\" + inner_query + \")\" + \" group by city, country\" \\\n \") as p inner join [cost_view] c on p.city = c.city inner join [pollution_view] po on c.city = po.city \" \\\n \"inner join [crime_view] cr on cr.city = po.city inner join \" \\\n \"[traffic_view] t on t.city = cr.city where \" \\\n \"p.country = c.country and po.country = c.country and cr.country = po.country \" \\\n \"and t.country = cr.country order by p.popularity desc\"\n # print(query)\n # print(tuple(pref))\n and_query_response = query_db(query, NUM_ELE)\n ret_ele.extend(and_query_response)\n ele_remaining = NUM_ELE - len(and_query_response)\n if(ele_remaining > 2 and total_pref > 1):\n print(\"Ele remaining\")\n query = \"select * from (\" \\\n \"select city, country, latitude, longitude, sum(popularity) as popularity, group_concat(url) as \" \\\n \"url, group_concat(cdn_url) as cdn_url, group_concat(class_tag) as class_tag, group_concat(popularity) as \" \\\n \" indl_popularity from (\" + \"select * from photos_nus where class_tag like '%{}%'\" + \\\n \")\" + \" group by city,country) as p inner join [cost_view] c on p.city = c.city inner join [pollution_view] po on c.city = po.city \" \\\n \"inner join [crime_view] cr on cr.city = po.city inner join \" \\\n \"[traffic_view] t on t.city = cr.city where \" \\\n \"p.country = c.country and po.country = c.country and cr.country = po.country \" \\\n \"and t.country = cr.country \" \\\n \"order by p.popularity desc\"\n for ele in pref:\n query_response = query_db(query.format(ele), int(ele_remaining/total_pref))\n # print(query_response)\n ret_ele.extend(query_response)\n # print(ret_ele)\n formatted_list = create_json(ret_ele)\n return formatted_list\n\ndef create_app(test_config=None):\n # create and configure the app\n app = Flask(__name__, instance_relative_config=True)\n app.config.from_mapping(\n SECRET_KEY='dev',\n DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),\n )\n\n jsglue = JSGlue(app)\n\n if test_config is None:\n # load the instance config, if it exists, when not testing\n app.config.from_pyfile('config.py', silent=True)\n else:\n # load the test config if passed in\n app.config.from_mapping(test_config)\n\n # ensure the instance folder exists\n try:\n os.makedirs(app.instance_path)\n except OSError:\n pass\n\n # a simple page that says hello\n @app.route('/')\n def hello():\n title = \"Input Preference\"\n print(os.getcwd(), file=sys.stderr)\n return render_template('user_pref.html', title=title)\n\n @app.route('/attractions', methods=['GET'])\n def user_pref():\n # print(request.args.get('pref'), file=sys.stderr)\n pref = request.args.get('pref')\n # print(pref, file=sys.stderr)\n result = json.dumps(get_top_elements_from_db(pref))\n country_count = get_country_count()\n # print(country_count)\n # print(result, file=sys.stderr)\n return render_template('map.html', result=result, pref=pref, country_count=country_count)\n\n @app.route('/city_info', )\n def city_info():\n query = request.args.get('data')\n query = json.loads(query)\n # data = get_city_info(query)\n # print(data[0], file=sys.stderr)\n # get_country_count()\n html = render_template('city_info.html', data=query, raw=json.dumps(query))\n return jsonify({'results':html})\n\n @app.route('/city_compare', methods=['POST'])\n def city_compare():\n content = request.get_json(silent=True)\n print(content, file=sys.stderr)\n # query = json.loads(query)\n html = render_template('city_comparison.html', data=content)\n return jsonify({'results': html})\n\n @app.route('/country_info')\n def country_info():\n pref = request.args.get('pref')\n country = request.args.get('country')\n print(country, file=sys.stderr)\n print(pref, file=sys.stderr)\n result = json.dumps(get_cities_of_country(pref, country))\n return jsonify({\"result\":result})\n\n from . import db\n db.init_app(app)\n\n return app","sub_path":"flaskr/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":11889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"539081860","text":"import superheroes\n\n\n# Testing Hero class\ndef test_hero_kills_and_deaths():\n batman = superheroes.Hero(\"Batman\")\n batmanAbility = superheroes.Ability(\"Detective\", 100)\n batman.add_ability(batmanAbility)\n superman = superheroes.Hero(\"Superman\")\n batman.fight(superman)\n assert (batman.kills == 1 and batman.deaths == 0) and (superman.kills == 0 and superman.deaths == 1)\n\ndef test_hero_add_ability():\n batman = superheroes.Hero(\"Batman\")\n batmanAbility = superheroes.Ability(\"Detective\", 10)\n batman.add_ability(batmanAbility)\n damage = batman.attack()\n assert (damage > -1 and damage < 11)\n\ndef test_hero_add_armor():\n batman = superheroes.Hero(\"Batman\")\n batsuit = superheroes.Armor(\"Bat Suit\", 1)\n batman.add_armor(batsuit)\n defence = batman.defence\n assert (defence > -1 and defence < 2)\n\ndef test_hero_attack():\n batman = superheroes.Hero(\"Batman\")\n damage = batman.attack()\n assert damage == 0\n\ndef test_hero_take_damage():\n batman = superheroes.Hero(\"Batman\")\n batman.take_damage(50)\n assert batman.current_health == 50\n\ndef test_hero_take_damage_with_armor():\n batman = superheroes.Hero(\"Batman\")\n batsuit = superheroes.Armor(\"Bat Suit\", 1)\n batman.add_armor(batsuit)\n batman.take_damage(50)\n assert (batman.current_health == 51 or batman.current_health == 50)\n\ndef test_hero_death():\n batman = superheroes.Hero(\"Batman\")\n batman.take_damage(100)\n assert batman.is_alive() == False\n\ndef test_hero_fight():\n batman = superheroes.Hero(\"Batman\")\n batmanAbility = superheroes.Ability(\"Detective\", 100)\n batman.add_ability(batmanAbility)\n superman = superheroes.Hero(\"Superman\")\n batman.fight(superman)\n\n catwoman = superheroes.Hero(\"Cat Woman\")\n captainmarvel = superheroes.Hero(\"Captain Marvel\")\n catwomanAbility = superheroes.Ability(\"Meow\", 100)\n catwoman.add_ability(catwomanAbility)\n captainmarvel.fight(catwoman)\n assert (superman.is_alive() == False and captainmarvel.is_alive() == False)\n\n\n# Testing Ability class\ndef test_ability_attack():\n batmanAbility = superheroes.Ability(\"Detective\", 100)\n damage = batmanAbility.attack()\n assert (damage > -1 and damage < 101)\n\n# Testing Weapon class\ndef test_weapon_attack():\n batmanAbility = superheroes.Weapon(\"Detective\", 2)\n damage = batmanAbility.attack()\n assert (damage > 0 and damage < 3)\n\n# Testing Team class\ndef test_team_count():\n batman = superheroes.Hero(\"Batman\")\n superman = superheroes.Hero(\"Superman\")\n justiceLeague = superheroes.Team(\"Justice League\")\n\n justiceLeague.add_hero(batman)\n justiceLeague.add_hero(superman)\n justiceLeague.remove_hero(superman)\n assert len(justiceLeague.heroes) == 1\n\n# TODO: Gonna have to update this attack test.\ndef test_team_attack():\n batman = superheroes.Hero(\"Batman\")\n batAttack= superheroes.Ability(\"batPunch\", attackStrenght=100)\n batman.add_ability(batAttack)\n batsuit = superheroes.Armor(\"Bat Suit\", 1)\n batman.add_armor(batsuit)\n\n superman = superheroes.Hero(\"Superman\")\n justiceLeague = superheroes.Team(\"League\")\n evilLeague = superheroes.Team(\"Evil League\")\n\n justiceLeague.add_hero(batman)\n evilLeague.add_hero(superman)\n justiceLeague.attack(evilLeague)\n assert superman.kills == 0 and superman.deaths == 1 and batman.kills == 1 and batman.deaths == 0\n\ndef test_team_revive_heroes():\n batman = superheroes.Hero(\"Batman\")\n batAttack= superheroes.Ability(\"batPunch\", attackStrenght=100)\n batman.add_ability(batAttack)\n batsuit = superheroes.Armor(\"Bat Suit\", 1)\n batman.add_armor(batsuit)\n superman = superheroes.Hero(\"Superman\")\n justiceLeague = superheroes.Team(\"League\")\n evilLeague = superheroes.Team(\"Evil League\")\n justiceLeague.add_hero(batman)\n evilLeague.add_hero(superman)\n justiceLeague.attack(evilLeague)\n evilLeague.revive_heroes()\n justiceLeague.revive_heroes(300)\n assert superman.current_health == 100 and batman.current_health == 300\n\n# Test Armor class\ndef test_armor_block():\n shield = superheroes.Armor(\"Shield\", 5)\n block = shield.block()\n assert (-1 < block < 6)\n","sub_path":"superheores/hero_test.py","file_name":"hero_test.py","file_ext":"py","file_size_in_byte":4151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"137064832","text":"login_url = \"/np/login\"\nlogout_url = \"/np/logout\"\nexerciser_login = \"/np/exerciser/login\"\nexerciser_login_as_guest = \"/np/exerciser/loginAsGuest\"\nexerciser_sign_up = \"/np/exerciser/signUp\"\ncreate_manual_workout_url= \"/np/workout?clientProcessed=true\"\nbrand_description_url = \"/np/brand/description\"\nexerciser_update_url = \"/np/exerciser/%s\"\nexerciser_profile_url = \"/np/exerciser/%s/profile\"\nexerciser_features_list_url = \"/np/exerciser/features\"\nexerciser_feature_pref_url = \"/np/exerciser/%s/feature-preferences\"\nchain_clubs_url = \"/np/company/children?responseType=detail\"\nfavorite_clubs_url = \"/np/exerciser/company/favorite\"\nsend_users_device_locale_url = \"/np/exerciser/%s/locale\"\nexerciser_password_reset = \"/np/exerciser/password-reset\"\nsend_device_locale_params = {'locale':'fr-FR'}\nexerciser_linking_status = \"/np/exerciser/linkingStatus\"\nexerciser_validate_url = \"/np/exerciser/validate\"\nexerciser_registration_url = \"/np/exerciser\"\nexerciser_registration_params = {'locale':'en-US', 'gender':'M', 'measurementUnit':'M', 'homeClubUuid':'9fbd8609-7f4c-480c-abd6-087899b9bd88'}\nexerciser_statistics_url = \"/np/exerciser/%s/stats\"\nexerciser_notification_url = \"/np/exerciser/%s/notification\"\nexerciser_notification_params = {'platform':'ANDROID','deviceUid':'3295d96260789ec3',\n 'token':'APA91bGRq8E66LiJwjjoDaewqaPmcln7rIdxIdr2wjaVzOi3hqra5L-PmBJMRJ4bg4zBLWSbcuCIsn1c9LcqlNEXWEyXnAX5g8mYO7L1pbN9kB2DAWy_Kqr6lOvv2W2JUo9ecqjgFK6npv73S28CjdPtFymPyuCjRA'}\n\n\"\"\" WORKOUT PARAMETERS \"\"\"\ncreate_workout_url = \"/np/exerciser/%s/workout\"\ncreate_workout_xcapture_url = \"/np/exerciser/%s/workout/xcapture\"\nsingle_workout_url = \"/np/exerciser/%s/workout/%s\"\nview_workouts_url = \"/np/exerciser/%s/workouts\"\ncategories_url = \"/np/workout/categories\"\nmet_values_url = \"/np/workout/met-values\"\nview_workouts_params = {'endDate':20150115, 'interval':\"year\", 'intervalCount':'1', 'filter':'all'}\ncreate_workout_params = {'workoutDateTimeNoTz':'', 'timezone':'Europe/Kiev',\n'category':15, 'duration':45, 'calories':450, 'distance':5, 'comment':'created',\n'equipmentType':'Treadmill'}\nedit_workout_params = {'workoutDateTimeNoTz':'', 'timezone':'Europe/Kiev',\n'category':20, 'duration':20, 'calories':200, 'distance':3, 'comment':'changed',\n'equipmentType':'Treadmill'}\ncreate_workout_with_hrm_url=\"/np/workout\"\ncreate_workout_with_hrm_params= {'workoutDateTime': '', 'duration': 22,\n'heartRateHistory': [0, 0, 1, 2, 3, 4, 10, 23, 4, 46, 78, 96, 21, 35, 6], 'averageHeartRate': 10, 'heartRateIncrement': 2,\n'calories': 205, 'equipmentType': 'Otbeat', 'points': 50, 'hrm': {'targetHeartRate': 180,'redZoneSeconds': 12,\n'orangeZoneSeconds': 13, 'greenZoneSeconds': 14, 'blueZoneSeconds': 35, 'greyZoneSeconds': 34 }}\n\n\"\"\" GOAL PARAMETERS \"\"\"\ngoal_url = \"/np/exerciser/%s/goal\"\ngoal_id_url = \"/np/goal/%s\"\nview_progress_url = \"/np/exerciser/%s/goal/progress\"\ncreate_goal_params = {'deleteActive':False, 'name':'Do it!', 'goalType':'Workout',\n'iterationCount':4, 'targetAmount':20}\nrestart_goal_params = {'restart':True}\nview_progress_params = {'completed':False}\n\n\"\"\" CHALLENGE PARAMETERS \"\"\"\nchallenge_progress_url = \"/np/exerciser/%s/challenge/progress\"\nget_challenges_list = \"/np/exerciser/%s/challenges?pageSize=%s&start=%s\"\nget_challenge_list_with_user_uuid = \"/np/exerciser/%s/challenges?startFrom=%s&endBy=%s\"\nget_challenge_list_with_end_date = \"/np/challenges?startFrom=%s&endBy=%s\"\nget_challenge_details = \"/np/exerciser/%s/challenge/%s\"\nget_challenge_prize = \"/np/challenge/%s/prize\"\ncreate_challenge = \"/np/company/%s/challenge\"\ncreate_global_challenge = \"/np/company/challenge\"\ncreate_global_challenge_params={'name':'', 'shortDescription':'desc','longDescription':'desc', 'goal':'', 'unit':'',\n'startTime':'', 'endTime':'', 'workoutCreditMode':'all', 'challengeLevel':'global', 'dailyMaxCredit':'',\n'includeManualWorkouts':'true', 'includeFitnessMachineWorkouts':'true', 'locale':'en_US'}\nget_prize_image = \"/np/challenge/%s/prize/image\"\nchallenge_start_from_params = '2015-03-03'\nchallenge_end_by_params = '2015-05-03'\n\nget_external_devices = \"/np/externalDevices\"\njoin_challenge_param = {'command':\"join\"}\nleave_challenge_param = {'command':\"leave\"}\n\n\"\"\" REWARDS PARAMETERS \"\"\"\ncompany_available_rewards = \"/np/np-rewards/v1/program/%s/rewards\"\ncompany_rewards_description = \"/np/np-rewards/v1/program/%s/description\"\nexerciser_rewards_program_status = \"/np/np-rewards/v1/programAccount/%s\"\n\n\"\"\" REFERRALS PARAMETERS \"\"\"\nreferral_configs_url = \"/np/referral-configs\"\nget_referral_config_params = {\"offset\" : \"1\", \"country\" : \"US\", \"state\" : \"CA\"}\nNP_Admin_creds = {\"username\" : \"npuser@mailinator.com\", \"password\" : \"123123\", \"club_portal\" : True}\n\n\n\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":4655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"60829543","text":"import networkx as nwx\nimport progressbar\nimport json\nimport os\n\nbar = progressbar.ProgressBar()\n\ndef load_words(filename):\n #Function is loading the data from a JSON Formatted file into the application in the examples case the output will be a dictionary.\n # the format of the output will be given by the input file.\n try:\n with open(filename,\"r\") as english_dictionary:\n valid_words = json.load(english_dictionary)\n return valid_words\n except Exception as e:\n return str(e)\n\ndef map_network(dict_file):\n #this is the function responsible for the whole network, while giving as an attribute the length of each node (important for ex. 1)\n # it is comparing the previous list of neighbors (generated in the gen_possible_neighbors) checking which words are in the same \"neighborhood\" and according to it making all the edges[connections] in the network\n #the output of this function is the completed network.\n network = nwx.Graph()\n used_dict = load_words(dict_file)\n city = {}\n for word in bar(used_dict):\n network.add_node(word, length=len(word))\n for neighbors in gen_possible_neighbors(word):\n if neighbors in city:\n e=[]\n for neighbor in city[neighbors]:\n e.append(tuple((word,neighbor)))\n e.append(tuple((neighbor,word)))\n network.add_edges_from(e)\n city[neighbors].append(word)\n else:\n city[neighbors] = [word]\n print(\"Network created, export to file begins (might take a few minutes...)\")\n return network\n\n\n\ndef gen_possible_neighbors(word):\n #this function generates a list of all possible subwords that could be connected with the entered word (i.E.:\n #input word is test --> [*test, t*est, te*st, tes*t, test*, *est, t*st, te*t, tes*]\n #this function is essential to assign the right \"neighbors\" to a word and add the edges from one node to another correctly\n possible_neighbors = []\n possible_neighbors.append(\"*\"+word)\n for b in range(len(word)):\n possible_neighbors.append(word[:b] + \"*\" + word[b + 1:])\n possible_neighbors.append(word[:b + 1] + \"*\" + word[b + 1:])\n return possible_neighbors\n\n\ndef yes_no(answer):\n #simple yes/no answer function for user with default set to Y\n yes = set(['yes', 'y', 'ye', '','aye'])\n no = set(['no', 'n','nay', 'nah'])\n\n while True:\n selection = input(answer).lower()\n if selection in yes:\n return True\n elif selection in no:\n return False\n else:\n print\n \"Please respond with 'yes' or 'no'\\n\"\n\ndef export_gexf():\n words = input(\"Enter name of dictionary to export (E.g. words_dictionary):\")\n if os.path.isfile(os.getcwd()+\"/\"+words+\".gexf\") == True:\n ovrwrite = yes_no(\"file already exists, overwrite Y/N (Default Y):\")\n if ovrwrite == False:\n return print(\"Existing file will be used\")\n print(\"Wordnetwork is being being created...\")\n nwx.write_gexf(map_network(words+\".json\"), words+\".gexf\")\n\ndef export_pickle():\n words = input(\"Enter filename of dictionary to export (E.g. words_dictionary):\")\n if os.path.isfile(os.getcwd() + \"/\" + words + \".pickle\") == True:\n ovrwrite = yes_no(\"file already exists, overwrite Y/N (Default Y):\")\n if ovrwrite == False:\n return print(\"Existing file will be used\")\n print(\"Wordnetwork is being being created...\")\n nwx.write_gpickle(map_network(words + \".json\"), words + \".pickle\")\n\ndef run_trail(start, end, method=\"ex2\"):\n #Part1: Load the words into the network\n network = None\n use_existing = yes_no(\"Do you want to load an existing network out of a pickle?\")\n if use_existing == True:\n fname = input(\"enter the name of the .pickle file you want to use (whole filename):\")\n try:\n network = nwx.read_gpickle(fname)\n print (\"Network successfully loaded!\")\n except Exception as e:\n print (\"Load of network failed\")\n if network == None:\n fname = input(\"Enter filename of dictionary (E.g. words_dictionary):\")\n network = map_network(fname + \".json\")\n if method == \"ex1\":\n #for exercise one we filter the network for only values that have the same lenght attribute. it is done with a subgraph\n if len(start)==len(end):\n network = network.subgraph([n for n, attrdict in network.node.items() if (\"length\", len(start)) in attrdict.items()])\n else:\n return print(\"Words are not in the same length, please select method 'ex2' for comparing words of unequal length\")\n #Part2: getting the shortest path between the source word and the end word and saving it into a list\n try:\n outlst = nwx.shortest_path(network,source=start,target=end)\n except nwx.NetworkXNoPath :\n return print(\"No path between '\"+start+\"' and '\"+end+\"' found :'-(\")\n except nwx.NodeNotFound:\n return print (\"One of the words selected can not be found in the dictionary, please try something else\")\n #Part3: formatting the output to be as given in the exercise description\n print(\"Transformation from \"+start+\" to \"+end+\" can be made with following path:\")\n print(\" --> \".join(outlst))\n\n\nif __name__ == '__main__':\n run_trail(\"elephant\",\"animalic\")\n # export_gexf()\n # g = nwx.read_gpickle(\"words_dictionary.pickle\")\n # #g = map_network(\"words_dictionary_ger.json\")\n # sg = g.subgraph([n for n, attrdict in g.node.items() if (\"length\", 4) in attrdict.items()])\n # print (nwx.shortest_path(sg,source=\"head\", target=\"tail\"))\n\n\n#\n","sub_path":"1_2.py","file_name":"1_2.py","file_ext":"py","file_size_in_byte":5681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"377648824","text":"import re #导入正则表达式模块\nimport requests #python HTTP客户端 编写爬虫和测试服务器经常用到的模块\nimport random #随机生成一个数,范围[0,1]\nimport string\ndef getpic(keyword):\n word = keyword\n result = requests.get('http://image.baidu.com/search/index?tn=baiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=1&ie=utf-8&word=' + word)\n \n def spiderPic(html,keyword):\n print('正查找 ' + keyword +' 对应的图,下载中...')\n length = len(re.findall('\"objURL\":\"(.*?)\"',html,re.S))\n try:\n ran = random.randint(1, length)\n addr = re.findall('\"objURL\":\"(.*?)\"',html,re.S)[ran]\n except:\n ran = random.randint(1, length)\n addr = re.findall('\"objURL\":\"(.*?)\"',html,re.S)[ran]\n print('正爬取URL地址:'+str(addr)) #爬取的地址长度超过30时,用'...'代替后面的内容\n \n try:\n pics = requests.get(addr,timeout=10)#请求URL时间(最大10秒)\n except requests.exceptions.ConnectionError:\n print('您当前请求的URL地址出现错误')\n \n fq = open('.\\\\pics\\\\' + addr.split('/')[-1],'wb')#下载图片,并保存和命名\n fq.write(pics.content)\n fq.close()\n return addr.split('/')[-1]\n aa = spiderPic(result.text,word)\n while aa.find('.')==-1:\n aa = spiderPic(result.text,word)\n print(\"出现404网页\")\n return aa\n","sub_path":"ui/getpicture.py","file_name":"getpicture.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"485839589","text":"\nimport datetime\n\ndef log(string):\n\tnow = str(datetime.datetime.now())\n\tprint(\"[{0}] {1}\".format(now, string))\n\ndef err_log(string, exception=None):\n\tnow = str(datetime.datetime.now())\t\n\terror_message = \"[{0}] ==== ERROR ==== {1}\".format(now, string)\n\tprint(error_message)\n\n\twith open('err.log', 'a') as errlog:\n\t\t# Write the error message to error log\n\t\t# In the future, also write the traceback (if applicable)\n\t\terrlog.write(error_message)\n\t\terrlog.write(\"\\n\")\n","sub_path":"logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"521081915","text":"from pyspark.sql import SparkSession\nfrom pyspark.sql import functions as F\n\nspark = SparkSession.builder.appName(\"MyApp\").getOrCreate()\ndf = spark.read.option(\"multiline\",\"true\").json(\"file:///home/flavio/Disc10/trabalhoFinal/ans.json\")\n\ndf_mun = df.groupBy('municipio_ibge').sum('valor')\ndf_mun = df_mun.withColumnRenamed('municipio_ibge','municipio').withColumnRenamed('sum(valor)','soma')\ndf_mun.orderBy(df_mun.soma.asc()).show()\n\n#maximo = df_mun.agg({'soma':'max'}).collect()[0][0]\n#print(\"Maximo = \",maximo)\nspark.stop()","sub_path":"Modulo 10 - Streaming de Dados em tempo real/trabalhoFinal/Q4c_spark.py","file_name":"Q4c_spark.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"135851588","text":"#-*- conding:utf-8 -*-\n\"\"\"\nAuthor: Jan Palach\nContact: palach@gmail.com\n\"\"\"\nimport os\nfrom flask import Module, Flask, jsonify, render_template, request, session, redirect, url_for, flash\nfrom werkzeug import secure_filename\n\nfrom utilities.vtk_reader import VTKReader\n\nfrom persistence.database import Base, db_session, engine\nfrom persistence.models import User, VTKModels\n\nfrom helper_functions import allowed_files\n\n\nUPLOAD_FOLDER = \"../model_files\"\n\nfrontend = Module(__name__)\n\n\n@frontend.route('/')\ndef index():\n if not session.get('logged_in'):\n return redirect(url_for('login'))\n elif session[\"logged_in\"] == True:\n return redirect(url_for('main'))\n return redirect(url_for('login'))\n\n\n@frontend.route('/main', methods=['GET'])\ndef main():\n models = VTKModels.query.filter(VTKModels.user_id == session['user_id']).all()\n\n return render_template(\"main.html\", models=models)\n\n\n@frontend.route('/login', methods=['GET', 'POST'])\ndef login():\n error = None\n if request.method == 'POST':\n user = User.get_user(request.form['email'], request.form['password'])\n\n if user is not None:\n session['logged_in'] = True\n session['user_id'] = user.id\n flash('You were logged in')\n return redirect(url_for('index'))\n return render_template('login.html', error=error)\n\n\n@frontend.route('/logout')\ndef logout():\n session.pop('logged_in', False)\n return redirect(url_for('index'))\n\n\n@frontend.route('/register-user', methods=['POST', 'GET'])\ndef register_user():\n if request.method == 'POST':\n user = User(\n request.form['name'],\n request.form['email'],\n request.form['password']\n )\n db_session.add(user)\n db_session.commit()\n return redirect(url_for('login'))\n return render_template('register.html')\n\n\n@frontend.route('/expose-model', methods=['GET', 'POST'])\ndef expose_model():\n if request.method == 'POST':\n model = VTKModels.query.filter(VTKModels.id == int(request.form['model_select'])).first()\n reader = VTKReader()\n reader.read(model.path, model.type)\n \n dataset_geometry = jsonify(\n vertices = [vertice for vertice in reader.vertices],\n indices = [id for id in reader.indices],\n pickable = \"true\"\n )\n \n return render_template('models.html', dataset=dataset_geometry)\n return redirect(url_for('main'))\n\n\n@frontend.route('/register-model', methods=['GET', 'POST'])\ndef register_model():\n \"\"\"\n This funtion allow a user to submit a vtk 3D model.\n \"\"\"\n if request.method == 'POST' and session[\"logged_in\"] == True:\n user_id = session['user_id']\n file = request.files['model_file']\n\n dir_path = os.path.join(UPLOAD_FOLDER, str(session['user_id']))\n if not os.path.isdir(dir_path):\n os.makedirs(dir_path)\n path = os.path.join(dir_path,file.filename)\n\n if file and allowed_files(file.filename):\n filename = secure_filename(file.filename)\n file.save(path)\n\n model = VTKModels(\n user_id,\n request.form['model_title'],\n request.form['model_description'],\n request.form['model_dataset_type'],\n path\n )\n\n db_session.add(model)\n db_session.commit()\n return redirect(url_for('main'))\n\n","sub_path":"vtk2webgl/src/controllers/frontend.py","file_name":"frontend.py","file_ext":"py","file_size_in_byte":3543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"291803396","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport sys\nfrom os import path\nimport json\nimport asyncio\nimport webbrowser\nfrom functools import partial\n\nfrom tornado import web\nfrom tornado import websocket\nfrom tornado.platform.asyncio import AsyncIOMainLoop\n\nimport misaka as m\nfrom pygments import highlight\nfrom pygments.styles import STYLE_MAP\nfrom pygments.formatters import HtmlFormatter\nfrom pygments.lexers import get_lexer_by_name, PythonLexer\n\ncurrent_dir = path.dirname(__file__)\nsys.path.insert(0, path.join(current_dir, 'wdom'))\n\nfrom wdom import options\nfrom wdom.tag import Div, Style, H2, Script, WebElement\nfrom wdom.document import get_document\nfrom wdom.server import get_app, start_server\nfrom wdom.parser import parse_html\n\n\nconnections = []\nCURSOR_TAG = '' \nstatic_dir = path.join(current_dir, 'static')\ntemplate_dir = path.join(current_dir, 'template')\n\noptions.parser.define('browser', default='google-chrome', type=str)\noptions.parser.define('browser-port', default=8089, type=int)\noptions.parser.define('vim-port', default=8090, type=int)\noptions.parser.define('no-default-js', default=False, action='store_const',\n const=True)\noptions.parser.define('no-default-css', default=False, action='store_const',\n const=True)\noptions.parser.define('js-files', default=[], nargs='+')\noptions.parser.define('css-files', default=[], nargs='+')\noptions.parser.define('highlight-theme', default='default', type=str)\n\n\nclass HighlighterRenderer(m.HtmlRenderer):\n def blockcode(self, text, lang):\n if not lang:\n return '\\n
    {}
    \\n'.format(text)\n else:\n lexer = get_lexer_by_name('python', stripall=True)\n lexer = PythonLexer()\n formatter = HtmlFormatter()\n html = highlight(text, lexer, formatter)\n return html\n\n\nconverter = m.Markdown(HighlighterRenderer(), extensions=(\n 'fenced-code',\n 'tables',\n))\n\n\nclass MainHandler(web.RequestHandler):\n def get(self):\n self.render('main.html', css=css, port=options.config.browser_port)\n\n\nclass WSHandler(websocket.WebSocketHandler):\n def open(self):\n connections.append(self)\n\n def on_close(self):\n connections.remove(self)\n\n\nclass VimListener(asyncio.Protocol):\n pass\n\n\nclass Server(object):\n def __init__(self, address='localhost', port=8090, loop=None, doc=None,\n mount_point=None):\n self.address = address\n self.port = port\n if loop is None:\n self.loop = asyncio.get_event_loop()\n else:\n self.loop = loop\n\n self.doc = doc\n self.script = None\n self.mount_point = mount_point\n self.tlist = []\n\n self.listener = VimListener\n self.listener.connection_made = self.connection_made\n self.listener.data_received = self.data_received\n self._tasks = []\n self.transport = None\n\n def start(self):\n self.coro_server = self.loop.create_server(self.listener, self.address,\n self.port)\n self.server_task = self.loop.run_until_complete(self.coro_server)\n return self.server_task\n\n def stop(self):\n self.server_task.close()\n\n def connection_made(self, transport):\n self.transport = transport\n\n def data_received(self, data):\n self.transport.close()\n for task in self._tasks:\n if not task.done() and not task.cancelled():\n task.cancel()\n self._tasks.remove(task)\n\n msg = json.loads(data.decode())[1]\n line = msg['line']\n event = msg['event']\n if event == 'update':\n self.tlist = msg['text']\n _task = self.update_preview\n elif event == 'move':\n _task = self.move_cursor\n else:\n raise ValueError('Get unknown event: {}'.format(event))\n\n try:\n self._tasks.append(asyncio.ensure_future(_task(line)))\n except asyncio.CancelledError:\n pass\n\n @asyncio.coroutine\n def update_preview(self, line):\n html = yield from self.convert_to_html(self.tlist)\n yield from self.mount_html(html)\n yield from self.move_cursor(line)\n\n @asyncio.coroutine\n def convert_to_html(self, tlist):\n md = '\\n'.join(tlist)\n yield from asyncio.sleep(0.0)\n return converter(md)\n\n @asyncio.coroutine\n def mount_html(self, html):\n fragment = parse_html(html)\n if self.mount_point.length < 1:\n self.mount_point.appendChild(fragment)\n else:\n diff = yield from self.find_diff_node(fragment)\n for _i in diff['inserted']:\n self.mount_point.insertBefore(_i[1], _i[0])\n for _d in diff['deleted']:\n self.mount_point.removeChild(_d)\n for _a in diff['appended']:\n self.mount_point.appendChild(_a)\n\n @asyncio.coroutine\n def move_cursor(self, line):\n blank_lines = 0\n i = 1\n while i < len(self.tlist):\n if self.tlist[i] == '' and self.tlist[i - 1] == '':\n blank_lines += 1\n i += 1\n continue\n else:\n i += 1\n cur_line = line - blank_lines\n\n if self.mount_point is not None and self.mount_point.ownerDocument:\n _l = 0\n elm = self.mount_point.firstChild\n while elm is not None:\n yield from asyncio.sleep(0.0)\n _l += elm.textContent.count('\\n')\n if _l >= cur_line:\n break\n elm = elm.nextSibling\n\n if elm is not None:\n if isinstance(elm, WebElement):\n self.move_to(elm.id)\n else:\n while elm is not None:\n elm = elm.previousSibling\n if isinstance(elm, WebElement):\n self.move_to(elm.id)\n break\n\n def move_to(self, id):\n script = 'moveToElement(\"{}\")'.format(id)\n self.mount_point.js_exec('eval', script=script)\n\n def _is_same_node(self, node1, node2):\n if node1.nodeType == node2.nodeType:\n if node1.nodeType == node1.TEXT_NODE:\n return node1.textContent == node2.textContent\n else:\n return node1.html_noid == node2.html_noid\n else:\n return False\n\n @asyncio.coroutine\n def find_diff_node(self, tree):\n _deleted = []\n _inserted = []\n\n node1 = self.mount_point.firstChild\n node2 = tree.firstChild\n last_node2 = node2\n while node1 is not None and node2 is not None: # Loop over old html\n yield from asyncio.sleep(0.0)\n if self._is_same_node(node1, node2):\n node1 = node1.nextSibling\n node2 = node2.nextSibling\n last_node2 = node2\n else:\n _pending = [node2]\n while True: # Loop over new html\n node2 = node2.nextSibling\n if node2 is None:\n _deleted.append(node1)\n node1 = node1.nextSibling\n node2 = last_node2\n break\n elif self._is_same_node(node1, node2):\n for n in _pending:\n _inserted.append((node1, n))\n node1 = node1.nextSibling\n node2 = node2.nextSibling\n last_node2 = node2\n break\n else:\n _pending.append(node2)\n n = last_node2\n _appended = []\n while n is not None:\n _appended.append(n)\n n = n.nextSibling\n\n return {'deleted': _deleted, 'inserted': _inserted,\n 'appended': _appended}\n\ndef main():\n AsyncIOMainLoop().install()\n\n doc = get_document()\n\n if not options.config.no_default_js:\n doc.add_jsfile(\n 'https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js')\n doc.add_jsfile('static/bootstrap.min.js')\n if not options.config.no_default_css:\n doc.add_cssfile('static/bootstrap.min.css')\n\n _user_static_dirs = set()\n for js in options.config.js_files:\n _user_static_dirs.add(path.dirname(js))\n doc.add_jsfile(js)\n for css in options.config.css_files:\n _user_static_dirs.add(path.dirname(css))\n doc.add_cssfile(css)\n\n # choices arg is better, but detecting error is not easy in livemark.vim\n if options.config.highlight_theme in STYLE_MAP:\n pygments_style = HtmlFormatter(\n style=options.config.highlight_theme).get_style_defs()\n else:\n pygments_style = HtmlFormatter('default').get_style_defs()\n doc.head.appendChild(Style(pygments_style))\n\n script = Script(parent=doc.body)\n script.innerHTML = '''\n function moveToElement(id) {\n var elm = document.getElementById(id)\n if (elm) {\n var x = window.scrollX\n var rect = elm.getBoundingClientRect()\n window.scrollTo(x, rect.top + window.scrollY)\n console.log(elm.textContent)\n }\n }\n '''\n mount_point = Div(parent=doc.body, class_='container')\n mount_point.appendChild(H2('LiveMark is running...'))\n app = get_app(doc)\n app.add_static_path('static', static_dir)\n for _d in _user_static_dirs:\n app.add_static_path(_d, _d)\n web_server = start_server(app, port=options.config.browser_port)\n\n loop = asyncio.get_event_loop()\n vim_server = Server(port=options.config.vim_port, loop=loop, doc=doc,\n mount_point=mount_point)\n browser = webbrowser.get(options.config.browser)\n browser.open('http://localhost:{}'.format(options.config.browser_port))\n try:\n vim_server.start()\n loop.run_forever()\n except KeyboardInterrupt:\n vim_server.stop()\n web_server.stop()\n\n\nif __name__ == '__main__':\n options.parse_command_line()\n main()\n","sub_path":"plugin/livemark.py","file_name":"livemark.py","file_ext":"py","file_size_in_byte":10258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"418333908","text":"from com.port8.core.environment import Environment\nfrom com.port8.core.singleton import Singleton\nfrom com.port8.core.loggingP8 import Logging\nfrom com.port8.core.globals import Global\nfrom com.port8.core.utility import Utility\n\nfrom apscheduler.schedulers.background import BackgroundScheduler\nfrom jsonref import JsonRef\n\nimport traceback,sys,os,json, importlib\n\nclass Infra(object, metaclass=Singleton):\n\n def __init__(self):\n\n # setting the Environment\n try:\n '''\n if not infraType or infraType not in ['REST','SCHEDULE','DAEMON']:\n print('expectig valid infra type REST/SCHEDULE/DAMEON got {got}, exiting !!!'.format(got = infraType))\n sys.exit(-1)\n '''\n self.env = Environment()\n self.globals = Global()\n self.util = Utility()\n self.logging = Logging()\n\n self.configLoc = self.env.appCfgLoc\n #print(self.configLoc)\n self.bootStrapFile = self.getBootStrapFile()\n if not self.bootStrapFile:\n raise ValueError('expecting valid bootstrap file, found NONE')\n\n self.dbConfigData = {}\n self.daemonConfifData = {}\n self.schedulerConfigData = {}\n self.restApiConfigData = {}\n self.agentConfigData = {}\n\n #print(self.Env._Env__initData)\n #print(self.Env._Env__EnvDetails)\n\n print(\"Loading bootstrap config....................\".ljust(50),end='')\n self.__loadBootStrapConfig()\n self.__loadSchema()\n\n # ensuring all needed lib is available\n print(\"Checking all required libraries................\".ljust(50),end='')\n self.__validateAllLib()\n\n '''\n self.Logger = \\\n self.logging.buildLoggingInfra(\\\n self.loggingConfigData,\\\n self.globals.LoggerName[infraType]['LogFile'],\n self.globals.LoggerName[infraType]['Name']\n )\n '''\n #self.Logger.debug('this is test from Infrastructure')\n\n # ensure db is up and repository is abvailable\n #print(\"Validating database............................\".ljust(50),end='')\n #self.__validateDb(infraType)\n #self.db = self.__getNewConnection()\n\n # loading DB schema\n # populating json schema for database\n '''\n commenting follwoing line, will revisit later to implement jsonref for db\n self.__loadDbJsonSchema() \n '''\n #print(\"Loading logging config.........................\".ljust(50),end='')\n #self.logger = Logging(self.loggingConfigData)\n #logger \n print(\"[infra started with OS pid {pid}]\".format(pid=self.getMyOsPid()))\n\n #self.db_dyna_sql = self.jsonSchema.get('Main').get('db_dyna_sql_call')\n #self.myModuleLogger.info ('Infrastructure started with os pid [{pid}]'.format(pid=os.getpid()))\n\n except Exception as err:\n\n exc_type, exc_value, exc_traceback = sys.exc_info()\n myErrorMessage = repr(traceback.format_exception(exc_type, exc_value, exc_traceback))\n\n print ('Error [{error}], terminating !!!'.format(error=myErrorMessage))\n sys.exit(-1)\n\n def __loadBootStrapConfig(self):\n\n # read bootstrap cnfig file\n try:\n self.__bootStrapData = json.load(open(self.bootStrapFile))\n\n if not self.__bootStrapData:\n print(\"Empty bootstrap data, terminating !!!\")\n sys.exit(-1) \n\n # validating if all modules config data is available\n myMissingModule = self.util.findMissingKeyInDict(self.__bootStrapData['Main']['Modules'], list(self.__bootStrapData['Main']['Modules'].keys()))\n if myMissingModule:\n print('Missing config information for module {0}'.format(myMissingModule))\n sys.exit(-1)\n\n #extracting module config information\n if self.env.environment not in self.__bootStrapData['Main']['Modules']['DB']['REPOSITORY']:\n print('[Error]\\n unable to find repository information for environment >> {env}'.format(env = self.env.environment))\n sys.exit(-1)\n\n if not self.env.environment in self.__bootStrapData['Main']['Modules']['DB']['REPOSITORY']:\n print('invalid environment >>> {env}'.format(env=self.env.Environment))\n sys.exit(-1)\n\n self.repConfigData = self.__bootStrapData['Main']['Modules']['DB']['REPOSITORY'][self.env.environment]\n self.dbConfigData = {\n 'user' : self.repConfigData['User'], \n 'password' : self.repConfigData['enc'], \n 'host' : self.repConfigData['Host'], \n 'port' : self.repConfigData['Port'],\n 'database' : self.repConfigData['Name']\n }\n\n self.schedulerConfigData = self.__bootStrapData['Main']['Modules']['Scheduler']\n self.loggingConfigData = self.__bootStrapData['Main']['Modules']['Logging']\n self.restApiConfigData = self.__bootStrapData['Main']['Modules']['RestAPI']\n self.daemonConfigData = self.__bootStrapData['Main']['Modules']['Daemon']\n self.jsonSchemaConfigData = self.__bootStrapData['Main']['Modules']['JsonSchema']\n\n if (not self.repConfigData):\n print('Repository DB Configuration is empty')\n sys.exit(-1)\n\n if (not self.schedulerConfigData):\n print('Scheduler Configuration is empty')\n sys.exit(-1)\n\n if (not self.loggingConfigData):\n print('Loggine Configuration is empty')\n sys.exit(-1)\n\n if (not self.restApiConfigData):\n print('RestApi Configuration is empty')\n sys.exit(-1)\n\n if (not self.restApiConfigData):\n print('Daemon Configuration is empty')\n sys.exit(-1)\n\n if (not self.jsonSchemaConfigData):\n print('Json Schema Configuration is empty')\n sys.exit(-1)\n\n print(\"[OK]\")\n\n except Exception as err:\n myErrorMessage = sys.exc_info()[1:],traceback.format_exc(limit=2) \n #myErrorMessage = self.Utility.extractError()\n print(myErrorMessage)\n #print(\"Error [{err}] loading bootstrap config data\".format(err=err))\n sys.exit(-1)\n \n def __loadSchema(self):\n \n # load json schema data and resolve the reference if used, this will be needed to validate user data\n #print(self.configLoc)\n configFile = self.util.buildFileWPath(self.configLoc,self.jsonSchemaConfigData['ConfigFile'])\n if not self.util.isFileExist(configFile):\n print('Json Schema Configuration file {file} is missing !!!'.format(file=os.path.join(self.configLoc,self.jsonSchemaConfigData['ConfigFile'])))\n sys.exit(-1)\n \n #loading json schema file and resolving references if used in schema\n try:\n self.jsonSchema = JsonRef.replace_refs(json.load(open(configFile)))\n #print(self.jsonSchema)\n except Exception as err:\n myErrorMessage = sys.exc_info()[1:],traceback.format_exc(limit=2) \n print (myErrorMessage)\n sys.exit(-1)\n\n def __validateAllLib(self):\n\n # Ensuring all required library as specified in bootStrap.json is installed\n try:\n for lib in self.__bootStrapData['Main']['libraries']:\n if not self.util.isPackageInstalled(lib):\n #self.myModuleLogger.error('Lib {frmtLib} is not installed, Pls install it using '.format(frmtLib=lib))\n print(\"[missing library {frmtLib}]\".format(frmtLib=lib))\n sys.exit(-1)\n\n print(\"[OK]\")\n\n except Exception as err:\n exc_type, exc_value, exc_traceback = sys.exc_info()\n myErrorMessage = repr(traceback.format_exception(exc_type, exc_value, exc_traceback))\n\n print('[Failed {err}]'.format(err=myErrorMessage)) \n sys.exit(-1)\n\n def isValidBootStrapData(self):\n if self.__bootStrapData:\n return True\n else:\n return False\n\n def isValidLogger(self):\n if self.myModuleLogger:\n return True\n else:\n return False\n\n def getBootStrapFile(self):\n \n #print(self.env._Environment__bootStrapFileKey)\n #print (self.env._Environment__initData)\n return self.env._Environment__initData[self.env._Environment__bootStrapFileKey]\n #mybootStrapFile = os.getEnv[self.Env._Environment__bootStrapKey]\n\n def getAppName(self):\n return os.Environ['APP_NAME']\n\n def getMyOsPid(self):\n # returns current OS pid\n return os.getpid()\n\n def getInfraLogger(self, infraArg):\n if infraArg == 'Scheduler':\n return self.SchedLogger\n elif infraArg == 'Daemon':\n return self.DaemonLogger\n elif infraArg == 'Rest':\n return self.RestLogger\n\n def isModuleInstalled(self, argLib):\n\n # returns existence of a library passed as an argument\n\n try:\n __import__('imp').find_module(argLib)\n return True\n except ImportError:\n #print('Missing library {lib}'.format(lib=argLib))\n return False\n\n #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n # method for DB\n #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ \n\n def __validateMySqlDB(self):\n\n self.dbLib = importlib.import_module('mysql.connector')\n\n # validate the db config file\n try:\n # connecting to database to ensure db is up\n db = self.dbLib.connect(host = self.dbConfigData['host'], port = self.dbConfigData['port'], user = self.dbConfigData['user'], password = self.util.decrypt(self.repConfigData['key'], self.dbConfigData['password']), database = self.dbConfigData['database'])\n\n # connection is successful, closing the connection\n db.close()\n # connection is successful\n except self.dbLib.Error as err:\n if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:\n print(\"something is wrong with your user name or password, exiting !!!\")\n sys.exit(-1)\n elif err.errno == errorcode.ER_BAD_DB_ERROR:\n print(\"Database does not exist, exiting !!!\")\n sys.exit(-1)\n else:\n print(err)\n '''\n except Exception as err:\n exc_type, exc_value, exc_traceback = sys.exc_info()\n myErrorMessage = repr(traceback.format_exception(exc_type, exc_value, exc_traceback))\n\n print('[Failed {err}]'.format(err=myErrorMessage)) \n sys.exit(-1)\n '''\n\n def __validateDb(self,infraType):\n #print(self.repConfigData)\n if infraType == 'REST':\n if self.repConfigData['Vendor'] == \"mysql\" :\n self.__validateMySqlDB()\n else:\n print('unsuported database for repository')\n sys.exit(-1)\n else:\n pass\n print(\"[OK]\")\n\n def __loadDbJsonSchema(self):\n #self.dbSchema = self.jsonSchema.get('Main').get('db_schema').get(self.__bootStrapData['Main']['Modules']['DB']['REPOSITORY'])\n \n self.dbSchema = self.jsonSchema.get('Main').get('db_schema').get(self.__bootStrapData['Main']['Modules']['DB']['REPOSITORY'][self.env.environment])\n\n def __getNewConnection(self):\n try:\n #print('db config',self.dbConfigData)\n db = self.dbLib.connect(host = self.dbConfigData['host'], port = self.dbConfigData['port'], user = self.dbConfigData['user'], password = self.util.decrypt(self.repConfigData['key'], self.dbConfigData['password']), database = self.dbConfigData['database'])\n #dbCursor = db.cursor(dictionary=True, buffered=True)\n #dbCursor = db.cursor(buffered=True)\n return db\n except Exception as err:\n self.logger.critical('Error obtaining db connection using {}'.format(self.dbConfigData))\n raise err\n\n def __closeConnection(self, conn):\n if conn:\n conn.close()\n\n def isConnectionOpen(self, conn):\n try:\n dbCur = conn.cursor()\n dbCur.execute('select now()')\n return True\n except Exception as err:\n return False\n\nclass RestInfra(Infra, metaclass=Singleton):\n def __init__(self):\n # calling super (Infra) class init method\n super().__init__()\n\n print(\"Validating database............................\".ljust(50),end='')\n super()._Infra__validateDb(self.globals.RestInfra)\n\n #self.db = self._Infra__getNewConnection()\n\n self.Logger = \\\n self.logging.buildLoggingInfra(\\\n self.loggingConfigData,\\\n self.globals.LoggerName[self.globals.RestInfra]['LogFile'],\n self.globals.LoggerName[self.globals.RestInfra]['Name']\n )\n print(\"Loading factory method metadata\")\n # need to load factory metadata somewhere else. this is callingg mysql and ,mysql is callin infra going in loop\n self.factoryMetadata = self.loadFactoryMetadata()\n #print('Factory metadata ',self.factoryMetadata)\n self.Logger.debug('this is test from Rest Infrastructure')\n\n def loadFactoryMetadata(self):\n #from com.port8.core.mysqlutils import MysqlUtil\n try:\n conn = super()._Infra__getNewConnection()\n dbCur = conn.cursor()\n dbResult = dbCur.execute(self.globals.buildFactoryDataSql)\n myAllColumns = dbCur.column_names\n myRawData = dbCur.fetchall()\n\n #building dict data\n myData = [dict(zip(myAllColumns, row)) for row in myRawData]\n dbCur.close()\n conn = super()._Infra__closeConnection(conn)\n #print('Factory metadata (raw)', myData)\n myFactoryData = list() \n #print('myData count', len(myData))\n for pageAction in myData:\n #print('in loop')\n #checking if this page exists \n pageIdx = [idx for idx, val in enumerate(myFactoryData) if myFactoryData[idx]['PAGE_ID'] == pageAction['PAGE_ID']]\n #print('pageIdx',pageIdx)\n if pageIdx: pageIdx = pageIdx[0]\n #print('index', pageIdx)\n if not pageIdx:\n # page doesnt exist, adding new page and its 1st action\n #print('page not found', pageAction['PAGE_ID'], myFactoryData)\n myFactoryData.append(\n {'PAGE_ID': pageAction['PAGE_ID'], 'PAGE_STATUS' : pageAction['PAGE_STATUS'],\n \"ACTIONS\" : [\n {'ACTION_ID' : pageAction['ACTION_ID'], 'ACTION_STATUS' : pageAction['ACTION_STATUS'],\n 'BPM_CALL_JSON': eval(pageAction['BPM_CALL_JSON']) }\n ] \n }\n )\n else:\n # page exist, adding action\n #print('page found',pageIdx, pageAction['PAGE_ID'], myFactoryData[pageIdx])\n myFactoryData[pageIdx][\"ACTIONS\"].append(\n {'ACTION_ID' : pageAction['ACTION_ID'], \n 'ACTION_STATUS' : pageAction['ACTION_STATUS'],\n 'BPM_CALL_JSON': eval(pageAction['BPM_CALL_JSON']) \n }\n )\n\n #print('Factory metadata', myFactoryData)\n return myFactoryData\n\n except Exception as err:\n raise err\n # we need to build factory metadata which will be used by factotu method to navigate method name\n\nclass SchedInfra(Infra, metaclass=Singleton):\n def __init__(self):\n\n super(SchedInfra, self).__init__()\n\n self.Logger = \\\n self.logging.buildLoggingInfra(\\\n self.loggingConfigData,\\\n self.globals.LoggerName[self.globals.SchedInfra]['LogFile'],\n self.globals.LoggerName[self.globals.SchedInfra]['Name']\n )\n\n self.Logger.info('instantiating scheduler, current os pid [{pid}'.format(pid=os.getpid()))\n self.Logger.info('current os is [{os}]'.format(os=os.uname()))\n self.Logger.info('Scheduler configuration .... \\n')\n self.Logger.info('Config Data ---> {data}'.format(data=self.schedulerConfigData))\n\n self.Logger.debug('this is test from Sched Infrastructure')\n\n # populating json schema for scheduler\n self.scheduleSchema = self.jsonSchema.get('Main').get('schedule_schema')\n self.intervalSchema = self.jsonSchema.get('Main').get('interval_schema')\n self.cronSchema = self.jsonSchema.get('Main').get('cron_schema')\n self.processJobSchema = self.jsonSchema.get('Main').get('process_job_schema')\n\n # Load json schema\n self.db = self.getNewConnection()\n\nclass DaemonInfra(Infra, metaclass=Singleton):\n def __init__(self):\n\n #inheriting Super class variables\n super(DaemonInfra, self).__init__()\n\n # creating logger for Daemon infrastructure\n self.Logger = \\\n self.logging.buildLoggingInfra(\\\n self.loggingConfigData,\\\n self.globals.LoggerName[self.globals.DaemonInfra]['LogFile'],\n self.globals.LoggerName[self.globals.DaemonInfra]['Name']\n )\n\n self.Logger.info('instantiating Daemon, current os pid [{pid}'.format(pid=os.getpid()))\n self.Logger.info('current os is [{os}]'.format(os=os.uname()))\n self.Logger.info('Daemon configuration .... \\n')\n self.DaemonLogger.info('Config Data ---> {data}'.format(data=self.daemonConfigData))\n\n self.Logger.debug('this is test from Daemon Infrastructure')\n\nclass DBInfra(Infra, metaclass=Singleton):\n def __init__(self):\n\n super(DBInfra,self).__init__()\n\n self.Logger = \\\n self.Logging.buildLoggingInfra(\\\n self.loggingConfigData,\\\n self.globals.LoggerName[self.globals.DBLoggerNameKey]['LogFile'],\n self.globals.LoggerName[self.globals.DBLoggerNameKey]['Name']\n )\n\n self.Logger.info('instantiating DB, current os pid [{pid}'.format(pid=os.getpid()))\n self.Logger.info('current os is [{os}]'.format(os=os.uname()))\n self.Logger.info('DB configuration .... \\n')\n self.Logger.info('Config Data ---> {data}'.format(data=self.dbConfigData))\n\n self.Logger.debug('this is test from Sched Infrastructure')\n\nif __name__ == \"__main__\":\n #infra = Infra()\n rest = RestInfra()\n","sub_path":"com_donot_use/port8/core/infrastructure.py","file_name":"infrastructure.py","file_ext":"py","file_size_in_byte":19224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"40323565","text":"from flask import Flask, render_template, session, redirect\nfrom flask import url_for, flash, request\nfrom flask_bootstrap import Bootstrap\nfrom flask_moment import Moment\nfrom flask_wtf import FlaskForm\nfrom wtforms import TextField, IntegerField, TextAreaField\nfrom wtforms import SubmitField, RadioField, SelectField\nfrom wtforms import validators, ValidationError\nfrom wtforms import StringField\nfrom wtforms.validators import DataRequired\nfrom flask_script import Manager\nfrom frame import Frame\nfrom wtforms.fields.html5 import DecimalRangeField\n\nfrom threading import Thread, Lock\n# from hksSer import serThread\nimport time\nimport bslCtrClient\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'hard to guess string'\n\nbootstrap = Bootstrap(app)\nmoment = Moment(app)\nmanager = Manager(app)\n\nclass ControlForm(FlaskForm):\n gid = IntegerField(\"Group Id: \",[validators.Required(\"Please enter your name.\")])\n pid = IntegerField(\"Private Id: \",[])\n # pid = IntegerField(\"Private Id: \",[validators.Required(\"Please enter your name.\")])\n level = IntegerField(\"Level: \",[])\n\n rxtx = RadioField('Destination RxTx', choices=[('1','Rx'),('2','Tx'), ('32','Gateway')])\n\n sub = RadioField('Command', choices=[('103','Control'),('109','Alternative')])\n\n submit = SubmitField(\"Send\")\n\n subDict = dict([('103','Control'),('109','Alternative')])\n\n rxtxDict = dict([('1','Rx'), ('2','Tx'), ('32','Gateway')])\n\ndef FileSave(filename,content):\n import io\n with open(filename, \"a+\") as myfile:\n myfile.write(content)\n\ndef returnSubLabel(sub):\n form = ControlForm()\n return form.subDict[sub]\n\nmyFrame = Frame()\n\nfrom datetime import datetime\n@app.route('/', methods=['GET', 'POST'])\ndef control():\n # startSer()\n form = ControlForm()\n if request.method == 'POST':\n if form.validate() == False:\n flash('All fields are required.')\n print('form.validate() == False:')\n return render_template('control.html', form=form)\n else:\n # myFrame = Frame()\n global myFrame\n gid = request.form['gid']\n pid = request.form['pid']\n level = request.form['level']\n\n rxtx = request.form['rxtx']\n sub = request.form['sub']\n\n dt = datetime.now()\n print(dt.date(), dt.time())\n\n print('gid:{}, pid:{}, level:{}, rxtx:{}, sub:{}'.format(gid, pid, level,\n form.rxtxDict[rxtx], form.subDict[sub]))\n # returnSubLabel(sub)))\n writeStr = 'Send:: ' + str(dt.date()) + ':' + str(dt.time())\n writeStr += '--->gid:{}, pid:{}, level:{}, sub:{}'.format(gid, pid, level, returnSubLabel(sub))\n FileSave('send.txt', writeStr+'\\n')\n\n myFrame.rate[0] = 1; myFrame.status[0] = 0;\n myFrame.Type[0] = 1;\n myFrame.setLevel(int(level));\n\n myFrame.setRxTx(int(rxtx)); myFrame.setSub(int(sub))\n myFrame.setGid(int(gid)); myFrame.setPid(int(pid));\n myFrame.setFrame()\n print('------------ Ctr Start ----------------')\n bslCtrClient.sendSocket(myFrame.getFrame())\n # print('bslCtrClient.sendSocket and wait return')\n timeOutCount = 0\n # while bslCtrClient.receiveFlag == False:\n # time.sleep(0.001)\n # timeOutCount += 1\n # if timeOutCount > 1000:\n # break\n #\n # if bslCtrClient.receiveFlag:\n # # print('I received frame from gateway')\n # flash('Result::'+bslCtrClient.returnPowerOrStatus)\n # flash('Mac Add:'+bslCtrClient.returnMac)\n # bslCtrClient.receiveFlag = False\n # else:\n # print('Time out')\n # flash('Time out')\n # mySer.send(myFrame.getFrame())\n print('------------ Ctr End ----------------')\n return render_template('control.html', form=form)\n\n elif request.method == 'GET':\n print('request.method == GET ')\n return render_template('control.html', form=form)\n\nif __name__ == '__main__':\n print('Now Run')\n # app.run(debug=True)\n manager.run()\n# python3 hello.py runserver --host 0.0.0.0\n# py bsl.py\n","sub_path":"project/rfTech/bslCtr.py","file_name":"bslCtr.py","file_ext":"py","file_size_in_byte":4286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"149092991","text":"ones = [\n \"\", \n \"واحد \", \n \"اثنان \", \n \"ثلاثة \", \n \"اربعة \", \n \"خمسة \", \n \"ستة \", \n \"سبعة \", \n \"ثمانية \", \n \"تسعة \", \n \"عشرة \", \n \"احدي عشرة \",\n \"اثنا عشرة \", \n \"ثلاثة عشرة \", \n \"أربعة عشرة \", \n \"خمسة عشرة \", \n \"ستة عشرة \", \n \"سبعة عشرة \", \n \"ثمانية عشرة \", \n \"تسعة عشرة \"\n]\nones_2 = [\n \"\", \n \"\", \n \"\", \n \"ثلاث\", \n \"اربع\", \n \"خمس\", \n \"ست\", \n \"سبع\", \n \"ثماني\", \n \"تسع\"\n]\ntwenties = [\n \"\", \n \"\", \n \"عشرون \", \n \"ثلاثون \", \n \"اربعون \",\n \"خمسون \", \n \"ستون \", \n \"سبعون \", \n \"ثمانون \", \n \"تسعون \"\n]\nthousands = [\n \"\", \n \"الف \", \n \"مليون \", \n \"بليون \", \n \"تريليون \"\n]\n\ndef num2word(n):\n c = n % 10 # singles digit\n b = ((n % 100) - c) / 10 # tens digit\n a = ((n % 1000) - (b * 10) - c) / 100 # hundreds digit\n t = \"\"\n h = \"\"\n if a != 0 and b == 0 and c == 0:\n if ones[int(a)] == ones[1]:\n t = ones_2[int(a)] + \"مائه \"\n elif ones[int(a)] == ones[2]:\n t = \"مئتان \"\n else:\n t = ones_2[int(a)] + \"مائه \"\n\n elif a != 0:\n if ones[int(a)] == ones[1]:\n t = \"مائه و \"\n elif ones[int(a)] == ones[2]:\n t = \"مئتان و \"\n else:\n t = ones_2[int(a)] + \"مائه و \"\n if b <= 1:\n h = ones[n % 100]\n elif b > 1:\n if ones[int(c)]:\n h = ones[int(c)] + ' و ' + twenties[int(b)]\n else:\n h = twenties[int(b)]\n st = t + h\n return st\n\n\ndef convert(input):\n num = int(input)\n if num == 0: return 'صفر'\n i = 3\n n = str(num)\n word = \"\"\n k = 0\n while(i == 3):\n nw = n[-i:]\n n = n[:-i]\n if int(nw) == 0:\n word = num2word(int(nw)) + thousands[int(nw)] + word\n else:\n first_num = num2word(int(nw))\n if num < 11:\n word = first_num\n elif first_num == ones[1]:\n if word:\n word = ' و ' + word\n word = thousands[int(k)] + word\n elif first_num == ones[2]:\n if word:\n word = ' و ' + word\n word = 'الفان ' + word\n elif first_num in ones[3:11]:\n if word:\n word = ' و ' + word\n word = first_num + 'آلاف ' + word\n else:\n if word:\n word = ' و ' + word\n word = first_num + thousands[int(k)] + word \n if n == '':\n i = i+1\n k += 1\n\n input_fraction = input - num\n input_fraction = round(input_fraction,2)\n input_fraction = str(input_fraction)\n input_fraction = input_fraction[2:]\n word = ' فقط ' + word[:-1] + ' لاغير '\n if input_fraction and int(input_fraction) !=0:\n input_fraction = ' و ' + input_fraction + '\\\\100'\n return word + input_fraction\n else:\n return word","sub_path":"num2word.py","file_name":"num2word.py","file_ext":"py","file_size_in_byte":3193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"184112441","text":"\n\n#calss header\nclass _TROOP():\n\tdef __init__(self,): \n\t\tself.name = \"TROOP\"\n\t\tself.definitions = [u'to walk somewhere in a large group, usually with one person behind another: ', u'to travel somewhere as a group, especially when told to: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_troop.py","file_name":"_troop.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"137194949","text":"from django.shortcuts import render,Http404,redirect,HttpResponse\nfrom django.contrib.auth import authenticate,login\nfrom .forms import LoginForm\nfrom django.contrib.auth.forms import UserCreationForm,AuthenticationForm\n# Create your views here.\ndef index_login(request):\n\tcontext = {}\n\tif request.method == 'GET':\n\t\tform = AuthenticationForm\n\tif request.method == 'POST':\n\t\tprint(request.POST)\n\t\tform = AuthenticationForm(data = request.POST)\n\t\tif form.is_valid():\n\t\t\tlogin(request,form.get_user())\n\t\t\treturn render(request,'index.html')\n\tcontext['form'] = form\n\treturn render(request,'login.html',context)\n\ndef register(request):\n\tcontext = {}\n\tif request.method == 'GET':\n\t\tform = UserCreationForm\n\telse:\n\n\t\tform = UserCreationForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tform.save()\n\t\t\treturn HttpResponse('

    注册成功!

    ')\n\tcontext['form'] = form\n\tprint(\"%%%%\"*30)\n\treturn render(request, 'register.html',context)\n","sub_path":"users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"124948500","text":"#!/usr/bin/env python\n\nimport operator as op\nimport jerrington_tools as jt\n\n_EQUALS = jt.curry2(op.eq)\n\nBASEPAIR = \"MB\"\nCENTIMORGAN = \"cM\"\n\nclass IBDEntry:\n \"\"\" Represents one entry of IDB between two individuals. Represents exactly\n one line of GERMLINE data. This class defines __str__ to produce\n GERMLINE data.\n IBDEntry instances support rich comparison, on the basis of the length\n of the inner interval.\n \"\"\"\n\n @staticmethod\n def from_GERMLINE(path_or_handle):\n \"\"\" Parse a GERMLINE output file (possibly gzipped) into a list of\n IDBEntry objects.\n\n Arguments:\n path_or_handle (string or file handle):\n If the argument is a string, then a handle will be opened\n and closed by this method. Otherwise, the caller is\n expected to manage the resource.\n \"\"\"\n needs_close = False\n if isinstance(path_or_handle, str):\n handle = jt.maybe_gzip_open(path_or_handle)\n needs_close = True\n else:\n handle = path_or_handle\n\n L = map(IBDEntry.from_string, handle)\n\n if needs_close:\n handle.close()\n return L\n\n @staticmethod\n def ifrom_GERMLINE(handle):\n \"\"\" Lazily parse GERMLINE output (possible gzipped) as a generator.\n Since this function is a generator, the caller must handle opening\n and closing the file\"\"\"\n for line in handle:\n yield IBDEntry.from_string(line)\n\n @staticmethod\n def from_string(input_str):\n \"\"\" Parse a string of one line of GERMLINE output as an IBDEntry. \"\"\"\n (fam1, id1hap, fam2, id2hap, chr, start, end,\n a1, a2, a3, a4, type, dat) = input_str.split(None, 12)\n id1, hap1 = id1hap.split('.')\n id2, hap2 = id2hap.split('.')\n\n dat = '\\t'.join([a1, a2, a3, a4, type, dat])\n\n return IBDEntry(\n chr, id1, id2, hap1, hap2, fam1, fam2, start, end, dat, type)\n\n def __init__(self, chr, name1, name2, hap1, hap2, fam1, fam2,\n start, end, dat, type=BASEPAIR):\n numparse = lambda x: (float if type == \"cM\" else int)(x) if isinstance(x, str) else x\n\n self.chromosome = int(chr)\n self.name = (name1, name2)\n self.haplotype = map(int, [hap1, hap2])\n self.family = (fam1, fam2)\n\n # parse as int or float if string, else don't parse.\n self.interval = jt.Interval(numparse(start), numparse(end))\n self.dat = dat\n\n self.type = type\n\n def complement(self):\n \"\"\" Construct an IBD segment ranging over the same region of the\n genome, but with the haplotype identifiers switched for both\n individuals.\n \"\"\"\n return IBDEntry(self.chromosome, self.name[0], self.name[1],\n 1 - self.haplotype[0], 1 - self.haplotype[1],\n self.family[0], self.family[1],\n self.interval.start, self.interval.end, self.dat, self.type)\n\n def is_involved(self, individual_name):\n return any(map(_EQUALS(individual_name), self.name))\n\n def to_string(self):\n \"\"\" Convenience function for readability. \"\"\"\n return self.__str__()\n\n def length(self):\n \"\"\" Return the length of the underlying Interval.\n This method is not subject to casting to int as with the len builtin.\n \"\"\"\n return self.interval.length()\n\n def __str__(self):\n \"\"\" Convert this IBD entry into a valid line of GERMLINE output. \"\"\"\n return \"{}\\t{}.{}\\t{}\\t{}.{}\\t{}\\t{}\\t{}\\t{}\" \\\n .format(self.family[0], self.name[0], self.haplotype[0],\n self.family[1], self.name[1], self.haplotype[1],\n self.chromosome,\n self.interval.start, self.interval.end,\n self.dat)\n\n def __repr__(self):\n return \"IBDEntry({}, '{}', '{}', '{}', '{}', '{}', '{}', {}, {}, '{}')\" \\\n .format(self.chromosome, self.name[0], self.name[1],\n self.haplotype[0], self.haplotype[1], self.family[0],\n self.family[1], self.interval.start, self.interval.end,\n self.dat)\n\n def __lt__(self, other):\n \"\"\" Compare this IBDEntry with another, on the basis of the length of\n the inner interval.\n \"\"\"\n return len(self.interval) < len(other.interval)\n\n def __len__(self):\n return len(self.interval)\n","sub_path":"ibd.py","file_name":"ibd.py","file_ext":"py","file_size_in_byte":4565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"354268774","text":"from django.contrib.postgres.fields import JSONField\n\nfrom auth.models import Permissions\nfrom django.conf import settings\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth.models import Permission\nfrom django.db import models\nfrom django_kala.managers import ActiveManager\nfrom taggit.managers import TaggableManager\nfrom uuid import uuid4\n\nimport datetime\n\nUser = get_user_model()\n\n\nclass Project(models.Model):\n name = models.CharField(max_length=255)\n description = models.TextField()\n tags = TaggableManager(blank=True)\n\n organization = models.ForeignKey('organizations.Organization', on_delete=models.CASCADE)\n clients = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True)\n\n created = models.DateTimeField(auto_now_add=True)\n removed = models.DateField(null=True)\n changed = models.DateTimeField(auto_now=True)\n is_active = models.BooleanField(default=True)\n uuid = models.UUIDField(unique=True, db_index=True, default=uuid4, editable=False)\n\n objects = ActiveManager()\n\n class Meta:\n ordering = ('name',)\n db_table = 'kala_projects'\n\n def set_active(self, active):\n self.is_active = active\n if not self.is_active:\n self.removed = datetime.date.today()\n self.save()\n\n def __str__(self):\n return self.name\n\n def get_documents(self, user):\n if user.is_superuser:\n return self.document_set.filter(project=self)\n if Permissions.has_perms([\n 'change_organization',\n 'add_organization',\n 'delete_organization'\n ], user, self.organization.uuid) or Permissions.has_perms([\n 'change_project',\n 'add_project',\n 'delete_project'\n ], user, self.uuid):\n return self.document_set.all().prefetch_related('documentversion_set', 'documentversion_set__user')\n else:\n document__uuids = self.document_set.all().values_list('uuid', flat=True)\n perm_uuids = Permissions.objects.filter(\n user=user,\n object_uuid__in=document__uuids\n ).values_list('object_uuid', flat=True)\n return self.document_set.filter(uuid__in=perm_uuids).prefetch_related('documentversion_set',\n 'documentversion_set__user')\n\n def get_users(self, user):\n if user.is_superuser:\n return User.objects.all()\n # If you have permissions for the org, or permissions for the\n # project, then you can see everyone in the org.\n if Permissions.has_perms([\n 'change_organization',\n 'add_organization',\n 'delete_organization'\n ], user, self.organization.uuid) or Permissions.has_perms([\n 'change_project',\n 'delete_project'\n ], user, self.uuid):\n return self.organization.user_set.all()\n return None\n\n def add_change(self, user):\n perm = Permission.objects.get(codename='change_project')\n Permissions.add_perm(perm=perm, user=user, uuid=self.uuid)\n\n def has_change(self, user):\n perm = Permission.objects.get(codename='change_project')\n org_perm = Permission.objects.get(codename='change_organization')\n return Permissions.has_perm(\n perm=perm,\n user=user,\n uuid=self.uuid\n ) or Permissions.has_perm(\n perm=org_perm,\n user=user,\n uuid=self.organization.uuid\n )\n\n def add_delete(self, user):\n perm = Permission.objects.get(codename='delete_project')\n Permissions.add_perm(perm=perm, user=user, uuid=self.uuid)\n\n def has_delete(self, user):\n perm = Permission.objects.get(codename='delete_project')\n org_perm = Permission.objects.get(codename='delete_organization')\n return Permissions.has_perm(\n perm=perm,\n user=user,\n uuid=self.uuid\n ) or Permissions.has_perm(\n perm=org_perm,\n user=user,\n uuid=self.organization.uuid\n )\n\n def add_create(self, user):\n perm = Permission.objects.get(codename='add_project')\n Permissions.add_perm(perm=perm, user=user, uuid=self.uuid)\n\n def has_create(self, user):\n perm = Permission.objects.get(codename='add_project')\n org_perm = Permission.objects.get(codename='add_organization')\n return Permissions.has_perm(\n perm=perm,\n user=user,\n uuid=self.uuid\n ) or Permissions.has_perm(\n perm=org_perm,\n user=user,\n uuid=self.organization.uuid\n )\n\n\nclass Category(models.Model):\n name = models.CharField(max_length=255)\n project = models.ForeignKey(Project, on_delete=models.CASCADE)\n type = models.CharField(max_length=20, db_index=True, null=True, blank=True)\n\n def __str__(self):\n return '{0}'.format(self.name)\n\n\nclass Export(models.Model):\n name = models.CharField(max_length=255)\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n key = models.CharField(max_length=255)\n details = JSONField(default={})\n","sub_path":"django_kala/projects/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"277077392","text":"import mimetypes\r\n\r\nimport datetime\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\nimport os\r\nimport xarray as xr\r\nfrom typing import List, Dict, Tuple, Union, Optional\r\n\r\nimport act\r\nfrom tsdat.constants import ATTS\r\n\r\n# Note that we can't use these in the type hints because\r\n# importing them here causes a circular dependency\r\n# from tsdat.config import Config, VariableDefinition\r\n\r\n\r\nmimetypes.init()\r\n\r\n\r\nclass DSUtil: \r\n \"\"\"\r\n Provides helper functions for xarray.Dataset\r\n \"\"\"\r\n\r\n @staticmethod\r\n def record_corrections_applied(ds: xr.Dataset, variable: str, correction: str):\r\n \"\"\"Records a description of a correction made to a variable to the \r\n corrections_applied corresponding attribute.\r\n\r\n :param ds: Dataset containing the corrected variable\r\n :type ds: xr.Dataset\r\n :param variable: The name of the variable that was corrected\r\n :type variable: str\r\n :param correction: A description of the correction\r\n :type correction: str\r\n \"\"\" \r\n corrections = ds[variable].attrs.get(ATTS.CORRECTIONS_APPLIED, [])\r\n corrections.append(correction)\r\n ds[variable].attrs[ATTS.CORRECTIONS_APPLIED] = corrections\r\n\r\n @staticmethod\r\n def datetime64_to_string(datetime64: Union[np.ndarray, np.datetime64]) -> Tuple[str, str]:\r\n \"\"\"Convert a datetime64 object to formated string.\r\n\r\n :param datetime64: The datetime64 object\r\n :type datetime64: Union[np.ndarray, np.datetime64]\r\n :return: A tuple of strings representing the formatted date. The first string is\r\n the day in 'yyyymmdd' format. The second string is the time in 'hhmmss' format.\r\n :rtype: Tuple[str, str]\r\n \"\"\" \r\n datetime = act.utils.datetime64_to_datetime()[0]\r\n return datetime.strftime(\"%Y%m%d\"), datetime.strftime(\"%H%M%S\")\r\n\r\n @staticmethod\r\n def datetime64_to_timestamp(variable_data: np.ndarray) -> np.ndarray:\r\n \"\"\"Converts each datetime64 value to a timestamp in same units as\r\n the variable (eg., seconds, nanoseconds).\r\n\r\n :param variable_data: ndarray of variable data\r\n :type variable_data: np.ndarray\r\n :return: An ndarray of the same shape, with time values converted to \r\n long timestamps (e.g., int64)\r\n :rtype: np.ndarray\r\n \"\"\" \r\n return variable_data.astype(pd.Timestamp).astype(np.int64)\r\n\r\n @staticmethod\r\n def get_datastream_name(ds: xr.Dataset = None, config=None) -> str:\r\n \"\"\"Returns the datastream name defined in the dataset or in the provided\r\n pipeline configuration.\r\n\r\n :param ds: The data as an xarray dataset; defaults to None\r\n :type ds: xr.Dataset, optional.\r\n :param config: The Config object used to assist reading time data from \r\n the raw_dataset; defaults to None.\r\n :type config: Config, optional\r\n :return: The datastream name\r\n :rtype: str\r\n \"\"\" \r\n assert(ds is not None or config is not None)\r\n if ds is not None and \"datastream_name\" in ds.attrs:\r\n return ds.attrs[\"datastream_name\"]\r\n elif config :\r\n return config.dataset_definition.datastream_name\r\n return None\r\n\r\n @staticmethod\r\n def get_end_time(ds: xr.Dataset) -> Tuple[str, str]:\r\n \"\"\"Convenience method to get the end date and time from a xarray\r\n dataset.\r\n\r\n :param ds: The dataset\r\n :type ds: xr.Dataset\r\n :return: A tuple of [day, time] as formatted strings representing\r\n the last time point in the dataset.\r\n :rtype: Tuple[str, str]\r\n \"\"\"\r\n time64 = np.min(ds['time'].data)\r\n return DSUtil.datetime64_to_string(time64)\r\n\r\n @staticmethod\r\n def get_fail_max(ds: xr.Dataset, variable_name: str): \r\n \"\"\"Get the max value from the fail_range attribute\r\n for the given variable.\r\n\r\n :param ds: The dataset\r\n :type ds: xr.Dataset\r\n :param variable_name: A variable in the dataset\r\n :type variable_name: str\r\n :return: The max value of the fail_range attribute or \r\n None if not defined\r\n :rtype: same data type of the variable (int, float, etc.)\r\n or None\r\n \"\"\" \r\n fail_max = None\r\n fail_range = ds[variable_name].attrs.get(ATTS.FAIL_RANGE, None)\r\n if fail_range is not None:\r\n fail_max = fail_range[-1]\r\n return fail_max\r\n\r\n @staticmethod\r\n def get_fail_min(ds: xr.Dataset, variable_name):\r\n \"\"\"Get the min value from the fail_range attribute\r\n for the given variable.\r\n\r\n :param ds: The dataset\r\n :type ds: xr.Dataset\r\n :param variable_name: A variable in the dataset\r\n :type variable_name: str\r\n :return: The min value of the fail_range attribute or \r\n None if not defined\r\n :rtype: same data type of the variable (int, float, etc.)\r\n or None\r\n \"\"\" \r\n fail_min = None\r\n fail_range = ds[variable_name].attrs.get(ATTS.FAIL_RANGE, None)\r\n if fail_range is not None:\r\n fail_min = fail_range[0]\r\n return fail_min\r\n\r\n @staticmethod\r\n def get_valid_max(ds: xr.Dataset, variable_name):\r\n \"\"\"Get the max value from the valid_range attribute\r\n for the given variable.\r\n\r\n :param ds: The dataset\r\n :type ds: xr.Dataset\r\n :param variable_name: A variable in the dataset\r\n :type variable_name: str\r\n :return: The max value of the valid_range attribute or \r\n None if not defined\r\n :rtype: same data type of the variable (int, float, etc.)\r\n or None\r\n \"\"\" \r\n valid_max = None\r\n valid_range = ds[variable_name].attrs.get(ATTS.VALID_RANGE, None)\r\n if valid_range is not None:\r\n valid_max = valid_range[-1]\r\n return valid_max\r\n\r\n @staticmethod\r\n def get_valid_min(ds: xr.Dataset, variable_name):\r\n \"\"\"Get the min value from the valid_range attribute\r\n for the given variable.\r\n\r\n :param ds: The dataset\r\n :type ds: xr.Dataset\r\n :param variable_name: A variable in the dataset\r\n :type variable_name: str\r\n :return: The min value of the valid_range attribute or \r\n None if not defined\r\n :rtype: same data type of the variable (int, float, etc.)\r\n or None\r\n \"\"\" \r\n valid_min = None\r\n valid_range = ds[variable_name].attrs.get(ATTS.VALID_RANGE, None)\r\n if valid_range is not None:\r\n valid_min = valid_range[0]\r\n return valid_min\r\n\r\n @staticmethod\r\n def get_fill_value(ds: xr.Dataset, variable_name: str):\r\n \"\"\"Get the value of the _FillValue attribute\r\n for the given variable.\r\n\r\n :param ds: The dataset\r\n :type ds: xr.Dataset\r\n :param variable_name: A variable in the dataset\r\n :type variable_name: str\r\n :return: The value of the _FillValue attr or None\r\n if it is not defined\r\n :rtype: same data type of the variable (int, float, etc.)\r\n or None\r\n \"\"\" \r\n return ds[variable_name].attrs.get(ATTS.FILL_VALUE, None)\r\n\r\n @staticmethod\r\n def get_non_qc_variable_names(ds: xr.Dataset) -> List[str]:\r\n \"\"\"Get a list of all data variables in the dataset that\r\n are NOT qc variables.\r\n\r\n :param ds: A dataset\r\n :type ds: xr.Dataset\r\n :return: List of non-qc data variable names\r\n :rtype: List[str]\r\n \"\"\" \r\n varnames = []\r\n\r\n def exclude_qc(variable_name):\r\n if variable_name.startswith('qc_'):\r\n return False\r\n else:\r\n return True\r\n\r\n varnames = filter(exclude_qc, list(ds.data_vars.keys()))\r\n\r\n return varnames\r\n\r\n @staticmethod\r\n def get_raw_end_time(raw_ds: xr.Dataset, time_var_definition) -> Tuple[str, str]:\r\n \"\"\"Convenience method to get the end date and time from a raw xarray\r\n dataset. This uses `time_var_definition.get_input_name()` as the\r\n dataset key for the time variable and additionally uses the input's\r\n `Converter` object if applicable.\r\n\r\n :param raw_ds: A raw dataset (not standardized)\r\n :type raw_ds: xr.Dataset\r\n :param time_var_definition: The 'time' variable definition from the \r\n pipeline config\r\n :type time_var_definition: VariableDefinition\r\n :return: A tuple of strings representing the last time data point\r\n in the dataset. The first string is the day in 'yyyymmdd' format. \r\n The second string is the time in 'hhmmss' format.\r\n :rtype: Tuple[str, str]\r\n \"\"\" \r\n time_var_name = time_var_definition.get_input_name()\r\n time_data = raw_ds[time_var_name].values\r\n\r\n time64_data = time_var_definition.run_converter(time_data)\r\n\r\n end_datetime64 = np.max(time64_data)\r\n end: datetime.datetime = act.utils.datetime64_to_datetime(end_datetime64)[0]\r\n return end.strftime(\"%Y%m%d\"), end.strftime(\"%H%M%S\")\r\n\r\n @staticmethod\r\n def get_raw_start_time(raw_ds: xr.Dataset, time_var_definition) -> Tuple[str, str]:\r\n \"\"\"Convenience method to get the start date and time from a raw xarray\r\n dataset. This uses `time_var_definition.get_input_name()` as the\r\n dataset key for the time variable and additionally uses the input's\r\n `Converter` object if applicable.\r\n\r\n :param raw_ds: A raw dataset (not standardized)\r\n :type raw_ds: xr.Dataset\r\n :param time_var_definition: The 'time' variable definition from the \r\n pipeline config\r\n :type time_var_definition: VariableDefinition\r\n :return: A tuple of strings representing the first time data point\r\n in the dataset. The first string is the day in 'yyyymmdd' format. \r\n The second string is the time in 'hhmmss' format.\r\n :rtype: Tuple[str, str]\r\n \"\"\" \r\n time_var_name = time_var_definition.get_input_name()\r\n time_data = raw_ds[time_var_name].values\r\n\r\n time64_data = time_var_definition.run_converter(time_data)\r\n\r\n start_datetime64 = np.min(time64_data)\r\n start: datetime.datetime = act.utils.datetime64_to_datetime(start_datetime64)[0]\r\n return start.strftime(\"%Y%m%d\"), start.strftime(\"%H%M%S\")\r\n\r\n @staticmethod\r\n def get_coordinate_variable_names(ds: xr.Dataset) -> List[str]:\r\n \"\"\"Get a list of all coordinate variables in this dataset.\r\n\r\n :param ds: The dataset\r\n :type ds: xr.Dataset\r\n :return: List of coordinate variable names\r\n :rtype: List[str]\r\n \"\"\" \r\n return list(ds.coords.keys())\r\n\r\n @staticmethod\r\n def get_shape(ds: xr.Dataset, variable_name: str) -> Tuple[List[str], List[int]]:\r\n \"\"\"Get the shape of a variable's data. Convenience \r\n method to provide access to dimension names and their\r\n lengths in one call.\r\n\r\n :param ds: The dataset\r\n :type ds: xr.Dataset\r\n :param variable_name: A variable in the dataset\r\n :type variable_name: str\r\n :return: A tuple where the first value is an array of the dimension\r\n names belonging to this variable and the second value is an array\r\n of the corresponding lengths of those dimensions.\r\n :rtype: Tuple[List[str], List[int]]\r\n \"\"\"\r\n var = ds.get(variable_name)\r\n dims = []\r\n lengths = []\r\n\r\n for dim in var.sizes:\r\n dims.append(dim)\r\n lengths.append(var.sizes[dim])\r\n\r\n return dims, lengths\r\n\r\n @staticmethod\r\n def get_start_time(ds: xr.Dataset) -> Tuple[str, str]:\r\n \"\"\"Convenience method to get the start date and time from a xarray\r\n dataset.\r\n\r\n :param ds: A standardized dataset\r\n :type ds: xr.Dataset\r\n :return: A tuple of strings representing the first time data point\r\n in the dataset. The first string is the day in 'yyyymmdd' format. \r\n The second string is the time in 'hhmmss' format.\r\n :rtype: Tuple[str, str]\r\n \"\"\" \r\n time64 = np.min(ds['time'].data)\r\n start = act.utils.datetime64_to_datetime(time64)[0]\r\n return start.strftime(\"%Y%m%d\"), start.strftime(\"%H%M%S\")\r\n\r\n @staticmethod\r\n def get_timestamp(dt64: np.datetime64):\r\n \"\"\"Convert a datetime64 value into a long integer timestamp\r\n :param dt64: datetime64 object\r\n :return: timestamp in seconds since 1970-01-01T00:00:00Z\r\n :rtype: int\r\n \"\"\"\r\n ts = int((dt64 - np.datetime64('1970-01-01T00:00:00Z')) / np.timedelta64(1, 's'))\r\n return ts\r\n\r\n @staticmethod\r\n def get_variables_with_dimension(ds: xr.Dataset, dim_name: str, include_qc=False) -> List[str]:\r\n \"\"\"Find all variables dimensioned by the given dim.\r\n Note that this method will only get data variables, NOT coordinate\r\n variables.\r\n\r\n :param ds: A dataset\r\n :type ds: xr.Dataset\r\n :param dim_name: Dimension name\r\n :type dim_name: str\r\n :param include_qc: Should qc variables be included, defaults to False\r\n :type include_qc: bool, optional\r\n :return: A list of all variable names that have that dimension\r\n :rtype: List[str]\r\n \"\"\" \r\n variable_names: List[str] = []\r\n for variable_name in ds.data_vars:\r\n if include_qc or not variable_name.startswith('qc_'):\r\n variable = ds.get(variable_name)\r\n for dim in variable.sizes:\r\n if dim == dim_name:\r\n variable_names.append(variable_name)\r\n return variable_names\r\n\r\n @staticmethod\r\n def get_metadata(ds: xr.Dataset) -> Dict:\r\n \"\"\"Get a dictionary of all global and variable\r\n attributes in a dataset. Global atts are found\r\n under the 'attributes' key and variable atts are\r\n found under the 'variables' key.\r\n\r\n :param ds: A dataset\r\n :type ds: xr.Dataset\r\n :return: A dictionary of global & variable attributes\r\n :rtype: Dict\r\n \"\"\" \r\n attributes = ds.attrs\r\n variables = {var_name: ds[var_name].attrs for var_name in ds.variables}\r\n metadata = {\"attributes\": attributes, \"variables\": variables}\r\n return metadata\r\n\r\n @staticmethod\r\n def get_warn_max(ds: xr.Dataset, variable_name):\r\n \"\"\"Get the max value from the warn_range attribute\r\n for the given variable.\r\n\r\n :param ds: The dataset\r\n :type ds: xr.Dataset\r\n :param variable_name: A variable in the dataset\r\n :type variable_name: str\r\n :return: The max value of the warn_range attribute or \r\n None if not defined\r\n :rtype: same data type of the variable (int, float, etc.)\r\n or None\r\n \"\"\" \r\n warn_max = None\r\n warn_range = ds[variable_name].attrs.get(ATTS.WARN_RANGE, None)\r\n if warn_range is not None:\r\n warn_max = warn_range[-1]\r\n return warn_max\r\n\r\n @staticmethod\r\n def get_warn_min(ds: xr.Dataset, variable_name):\r\n \"\"\"Get the min value from the warn_range attribute\r\n for the given variable.\r\n\r\n :param ds: The dataset\r\n :type ds: xr.Dataset\r\n :param variable_name: A variable in the dataset\r\n :type variable_name: str\r\n :return: The min value of the warn_range attribute or \r\n None if not defined\r\n :rtype: same data type of the variable (int, float, etc.)\r\n or None\r\n \"\"\" \r\n warn_min = None\r\n warn_range = ds[variable_name].attrs.get(ATTS.WARN_RANGE, None)\r\n if warn_range is not None:\r\n warn_min = warn_range[0]\r\n return warn_min\r\n\r\n @staticmethod\r\n def is_coord_var(ds: xr.Dataset, variable_name: str) -> bool:\r\n \"\"\"Determine if given variable is a coordinate variable\r\n for a dimension.\r\n\r\n :param ds: A dataset\r\n :type ds: xr.Dataset\r\n :param variable_name: A variable in the dataset\r\n :type variable_name: str\r\n :return: True if the variable is a coordinate variable\r\n :rtype: bool\r\n \"\"\" \r\n for dim in ds.coords.dims.keys():\r\n if variable_name == dim:\r\n return True\r\n\r\n return False\r\n\r\n @staticmethod\r\n def plot_qc(ds: xr.Dataset, variable_name: str, filename: str=None): \r\n \"\"\"Create a QC plot for the given variable. This is based on the ACT library:\r\n https://arm-doe.github.io/ACT/source/auto_examples/plot_qc.html#sphx-glr-source-auto-examples-plot-qc-py\r\n\r\n We provide a convenience wrapper method for basic QC plots of a variable, but\r\n we recommend to use ACT directly and look at their examples for more complex plots\r\n like plotting variables in two different datasets.\r\n\r\n TODO: Depending on use cases, we will likely add more arguments to be able to quickly produce\r\n the most common types of QC plots.\r\n \r\n :param ds: A dataset\r\n :type ds: xr.Dataset\r\n :param variable_name: The variable to plot\r\n :type variable_name: str\r\n :param filename: The filename for the image. Saves the plot as this filename if provided.\r\n :type filename: str, optional\r\n \"\"\"\r\n\r\n display = act.plotting.TimeSeriesDisplay(ds, figsize=(15, 10), subplot_shape=(2,))\r\n\r\n # Plot temperature data in top plot\r\n display.plot(variable_name, subplot_index=(0,))\r\n\r\n # Plot QC data\r\n display.qc_flag_block_plot(variable_name, subplot_index=(1,))\r\n\r\n # Either display or save the plot, depending upon the parameters passed\r\n if filename:\r\n plt.savefig(filename)\r\n else:\r\n plt.show()\r\n\r\n @staticmethod\r\n def get_plot_filename(dataset: xr.Dataset, plot_description: str, extension: str) -> str:\r\n \"\"\"Returns the filename for a plot according to MHKIT-Cloud Data\r\n standards. The dataset is used to determine the datastream_name and\r\n start date/time. The standards dictate that a plot filename should\r\n follow the format: `datastream_name.date.time.description.extension`.\r\n\r\n :param dataset: The dataset from which the plot data is drawn from.\r\n This is used to collect the datastream_name and start date/time.\r\n :type dataset: xr.Dataset\r\n :param plot_description: The description of the plot. Should be as \r\n brief as possible and contain no spaces. Underscores may be used.\r\n :type plot_description: str\r\n :param extension: The file extension for the plot.\r\n :type extension: str\r\n :return: The standardized plot filename.\r\n :rtype: str\r\n \"\"\" \r\n datastream_name = DSUtil.get_datastream_name(dataset)\r\n date, time = DSUtil.get_start_time(dataset)\r\n return f\"{datastream_name}.{date}.{time}.{plot_description}.{extension}\"\r\n\r\n @staticmethod\r\n def get_dataset_filename(dataset: xr.Dataset, file_extension=\".nc\") -> str:\r\n \"\"\"Given an xarray dataset this function will return the base filename of\r\n the dataset according to MHkiT-Cloud data standards. The base filename\r\n does not include the directory structure where the file should be\r\n saved, only the name of the file itself, e.g.\r\n z05.ExampleBuoyDatastream.b1.20201230.000000.nc\r\n\r\n :param dataset: The dataset whose filename should be generated.\r\n :type dataset: xr.Dataset\r\n :param file_extension: The file extension to use. Defaults to \".nc\"\r\n :type file_extension: str, optional\r\n :return: The base filename of the dataset.\r\n :rtype: str\r\n \"\"\" \r\n datastream_name = DSUtil.get_datastream_name(dataset)\r\n start_date, start_time = DSUtil.get_start_time(dataset)\r\n return f\"{datastream_name}.{start_date}.{start_time}{file_extension}\"\r\n\r\n @staticmethod\r\n def get_raw_filename(raw_dataset: xr.Dataset, old_filename: str, config) -> str:\r\n \"\"\"Returns the appropriate raw filename of the raw dataset according to\r\n MHKIT-Cloud naming conventions. Uses the config object to parse the\r\n start date and time from the raw dataset for use in the new filename.\r\n\r\n The new filename will follow the MHKIT-Cloud Data standards for raw\r\n filenames, ie: `datastream_name.date.time.raw.old_filename`, where the\r\n data level used in the datastream_name is `00`.\r\n\r\n :param raw_dataset: The raw data as an xarray dataset.\r\n :type raw_dataset: xr.Dataset\r\n :param old_filename: The name of the original raw file.\r\n :type old_filename: str\r\n :param config: The Config object used to assist reading time data from \r\n the raw_dataset.\r\n :type config: Config\r\n :return: The standardized filename of the raw file.\r\n :rtype: str\r\n \"\"\" \r\n original_filename = os.path.basename(old_filename)\r\n raw_datastream_name = config.pipeline_definition.input_datastream_name\r\n time_var = config.dataset_definition.get_variable('time')\r\n start_date, start_time = DSUtil.get_raw_start_time(raw_dataset, time_var)\r\n return f\"{raw_datastream_name}.{start_date}.{start_time}.raw.{original_filename}\"\r\n\r\n @staticmethod\r\n def get_date_from_filename(filename: str) -> str:\r\n \"\"\"Given a filename that conforms to MHKiT-Cloud Data Standards, return\r\n the date of the first point of data in the file.\r\n\r\n :param filename: The filename or path to the file.\r\n :type filename: str\r\n :return: The date, in \"yyyymmdd.hhmmss\" format.\r\n :rtype: str\r\n \"\"\" \r\n filename = os.path.basename(filename)\r\n date = filename.split(\".\")[3]\r\n time = filename.split(\".\")[4]\r\n return f\"{date}.{time}\"\r\n\r\n @staticmethod\r\n def get_datastream_name_from_filename(filename: str) -> Optional[str]:\r\n \"\"\"Given a filename that conforms to MHKiT-Cloud Data Standards, return\r\n the datastream name. Datastream name is everything to the left of the\r\n third '.' in the filename.\r\n \r\n e.g., humboldt_ca.buoy_data.b1.20210120.000000.nc\r\n\r\n :param filename: The filename or path to the file.\r\n :type filename: str\r\n :return: The datstream name, or None if filename is not in proper format.\r\n :rtype: Optional[str]\r\n \"\"\" \r\n datastream_name = None\r\n\r\n parts = filename.split(\".\")\r\n if len(parts) > 2:\r\n datastream_name = f'{parts[0]}.{parts[1]}.{parts[2]}'\r\n\r\n return datastream_name\r\n\r\n @staticmethod\r\n def get_datastream_directory(datastream_name: str, root: str = \"\") -> str:\r\n \"\"\"Given the datastream_name and an optional root, returns the path to\r\n where the datastream should be located. Does NOT create the directory\r\n where the datastream should be located.\r\n\r\n :param datastream_name: The name of the datastream whose directory path should\r\n be generated.\r\n :type datastream_name: str\r\n :param root: The directory to use as the root of the directory structure.\r\n Defaults to None. Defaults to \"\"\r\n :type root: str, optional\r\n :return: The path to the directory where the datastream should be located.\r\n :rtype: str\r\n \"\"\" \r\n location_id = datastream_name.split(\".\")[0]\r\n return os.path.join(root, location_id, datastream_name)\r\n\r\n @staticmethod\r\n def is_image(filename: str) -> bool:\r\n \"\"\"Detect the mimetype from the file extension and use it to determine\r\n if the file is an image or not\r\n\r\n :param filename: The name of the file to check\r\n :type filename: str\r\n :return: True if the file extension matches an image mimetype\r\n :rtype: bool\r\n \"\"\"\r\n is_an_image = False\r\n mimetype = mimetypes.guess_type(filename)[0]\r\n if mimetype is not None:\r\n mimetype = mimetype.split('/')[0]\r\n if mimetype == 'image':\r\n is_an_image = True\r\n\r\n return is_an_image\r\n\r\n# TODO: Maybe we need a method to be able to quickly dump out a summary of the list of problems with the data.\r\n\r\n\r\n","sub_path":"tsdat/utils/dsutils.py","file_name":"dsutils.py","file_ext":"py","file_size_in_byte":24623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"272550235","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @first_date 20160311\n# @date 20160311\n# @version 0.0\n\"\"\"Init flask app\n\"\"\"\n# level1: native python packages\n# None\n\n# level2: native web framework packages\nfrom flask import Flask\n\n# level3: relative web framework plugins\nfrom flask.ext.mongoengine import MongoEngine\n\n# level4: third-party packages\n# None\n\n# level5: specify-project packages\n# None\n\n\napp = Flask(__name__)\n\n\ndef url(blueprints, version=None):\n # data process: Decide url structure of the application\n prefix = '/%s' % version if version else ''\n\n # data process: set the new url_prefix (create new object and avoid mutable dict)\n bps = []\n for blueprint in blueprints:\n bps.append({\n 'blueprint': blueprint['blueprint'],\n 'url_prefix': prefix + blueprint['url_prefix']\n })\n return bps\n\n\nclass FlaskApplicationFactory(object):\n '''FlaskApplicationFactory'''\n\n def install_extension(self):\n '''install_extension'''\n _ = MongoEngine(app)\n\n def install_blueprint(self):\n '''install_blueprint'''\n # blueprint porcess: import patterns it's ready to be registered\n from .http.blueprints import BLUEPRINT_PATTERNS as http_bp_patterns\n\n # blueprint porcess: Add version for each patterns\n versioning_patterns = (\n url(http_bp_patterns),\n url(http_bp_patterns, version='v1'),\n )\n\n # blueprint porcess: app register blueprint\n for blueprint_patterns in versioning_patterns:\n for blueprint in blueprint_patterns:\n app.register_blueprint(**blueprint)\n\n def install_handlers(self):\n '''install_handlers'''\n from .handlers import (\n status_code_handlers,\n mongoengine_handlers\n )\n\n def install_middlewares(self):\n from .middlewares import process_request\n\n def create_app(self, config_filename):\n '''create_app'''\n app.config.from_object(config_filename)\n self.install_middlewares()\n self.install_extension()\n self.install_blueprint()\n self.install_handlers()\n return app\n","sub_path":"pourer/app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"517173427","text":"\"\"\" Server metrics upload.\n\"\"\"\n# -*- coding: utf-8 -*-\n\nimport os\nimport platform\nimport time\n\nimport psutil\nfrom aleph.sdk import AuthenticatedAlephClient\nfrom aleph.sdk.account import _load_account\n\n\ndef get_sysinfo():\n uptime = int(time.time() - psutil.boot_time())\n sysinfo = {\n \"uptime\": uptime,\n \"os\": platform.platform(),\n \"load_avg\": os.getloadavg(),\n \"num_cpus\": psutil.cpu_count(),\n }\n\n return sysinfo\n\n\ndef get_memory():\n return psutil.virtual_memory()._asdict()\n\n\ndef get_swap_space():\n sm = psutil.swap_memory()\n swap = {\n \"total\": sm.total,\n \"free\": sm.free,\n \"used\": sm.used,\n \"percent\": sm.percent,\n \"swapped_in\": sm.sin,\n \"swapped_out\": sm.sout,\n }\n return swap\n\n\ndef get_cpu():\n return psutil.cpu_times_percent(0)._asdict()\n\n\ndef get_cpu_cores():\n return [c._asdict() for c in psutil.cpu_times_percent(0, percpu=True)]\n\n\ndef send_metrics(account, metrics):\n with AuthenticatedAlephClient(\n account=account, api_server=\"https://api2.aleph.im\"\n ) as client:\n return client.create_aggregate(\"metrics\", metrics, channel=\"SYSINFO\")\n\n\ndef collect_metrics():\n return {\n \"memory\": get_memory(),\n \"swap\": get_swap_space(),\n \"cpu\": get_cpu(),\n \"cpu_cores\": get_cpu_cores(),\n }\n\n\ndef main():\n account = _load_account()\n while True:\n metrics = collect_metrics()\n message, status = send_metrics(account, metrics)\n print(\"sent\", message.item_hash)\n time.sleep(10)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"examples/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"609056772","text":"import sys\nimport subprocess\nfrom pybullet_utils.arg_parser import ArgParser\nfrom pybullet_utils.logger import Logger\n\n\ndef main():\n # Command line arguments\n args = sys.argv[1:]\n arg_parser = ArgParser()\n arg_parser.load_args(args)\n\n num_workers = arg_parser.parse_int('num_workers', 1)\n assert (num_workers > 0)\n\n Logger.print2('Running with {:d} workers'.format(num_workers))\n cmd = 'mpiexec -n {:d} python3 DeepMimic_Optimizer.py '.format(num_workers)\n cmd += ' '.join(args)\n Logger.print2('cmd: ' + cmd)\n subprocess.call(cmd, shell=True)\n return\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Projects/bullet3-2.89/examples/pybullet/gym/pybullet_envs/deep_mimic/mpi_run.py","file_name":"mpi_run.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"14078406","text":"import streamlit as st\nimport sys\nfrom fastai.vision.all import load_learner\nimport torch\nfrom skimage.io import imread\nimport plotly.express as px\nfrom datetime import datetime\n\nsys.path.append(\"fsdl_deforestation_detection/data/\")\nsys.path.append(\"fsdl_deforestation_detection/dashboard/\")\nfrom data_utils import DATA_PATH\nfrom dashboard_utils import (\n set_paths,\n load_image,\n load_image_names,\n load_data,\n run_model,\n show_model_output,\n show_labels,\n get_performance_metrics,\n get_gauge_plot,\n get_number_plot,\n get_hist_plot,\n get_pixel_dist_plot,\n gen_user_id,\n gen_image_id,\n upload_user_data,\n upload_user_comment,\n delete_user_data,\n)\nfrom session_state import session_state\n\n# Get a user ID\nsession_state.user_id = gen_user_id()\n\n\ndef playground():\n st.title(\"Playground\")\n # Initial instructions\n init_info = st.empty()\n init_info.info(\n \"ℹ️ Upload an image on the sidebar to run the model on it!\\n\"\n \"Just be sure that it's satellite imagery, otherwise you're \"\n \"just going to get random outputs 🤷‍♂️\"\n )\n # Set the sidebar inputs\n st.sidebar.title(\"Inputs\")\n # NOTE For the sake of time, we're just going to use the `Land scenes` model\n # model_type = st.sidebar.radio(\"Model\", [\"Deforestation\", \"Land scenes\"])\n model_type = \"Land scenes\"\n input_file = st.sidebar.file_uploader(\n \"Upload an image\",\n type=[\"jpg\", \"jpeg\", \"png\", \"tif\"],\n accept_multiple_files=False,\n help=\"Test our model on an image of your liking! \"\n \"But remember that this should only work for satellite imagery, \"\n \"ideally around 256x256 size.\",\n )\n st.sidebar.markdown(\n \"Made by [André Ferreira](https://andrecnf.com/) and [Karthik Bhaskar](https://www.kbhaskar.com/).\"\n )\n # Set the model\n model = load_learner(\n \"fsdl_deforestation_detection/modeling/resnet50-128.pkl\"\n )\n # Speed up model inference by deactivating gradients\n model.model.eval()\n torch.no_grad()\n if input_file is not None:\n # Load and display the uploaded image\n with st.spinner(\"Loading image...\"):\n img = imread(input_file)\n # Check if it's a different image than the one before\n if input_file.name != session_state.image_name:\n session_state.image_name = input_file.name\n session_state.image_id = gen_image_id()\n session_state.ts = datetime.now()\n session_state.user_data_uploaded = False\n # Reset buttons\n session_state.user_feedback_positive = False\n session_state.user_feedback_negative = False\n fig = px.imshow(img)\n st.plotly_chart(fig)\n init_info.empty()\n # Run the model on the image\n output = run_model(model, img)\n st.subheader(\"Model output:\")\n show_model_output(model_type, output)\n st.info(\n \"ℹ️ Green labels represent categories that we don't associate with deforestation \"\n \"risk (e.g. natural occurences or old structures), while red labels can serve as \"\n \"a potential deforestation signal (e.g. new constructions, empty patches in forests).\"\n )\n # User feedback / data flywheel\n st.write(\"Did the model output match what you expected?\")\n feedback_cols = st.beta_columns(2)\n with feedback_cols[0]:\n positive_btn = st.button(\"✅\")\n with feedback_cols[1]:\n negative_btn = st.button(\"❌\")\n if (\n positive_btn or session_state.user_feedback_positive\n ) and not negative_btn:\n session_state.user_feedback_positive = True\n session_state.user_feedback_negative = False\n st.info(\n \"ℹ️ Thank you for your feedback! This can help us \"\n \"improve our models 🙌\"\n )\n if session_state.user_data_uploaded is False:\n upload_user_data(\n session_state.user_id,\n session_state.ts,\n session_state.image_id,\n img,\n output[1],\n session_state.user_feedback_positive,\n )\n session_state.user_data_uploaded = True\n if st.button(\"Delete my image and feedback data\"):\n st.info(\n \"ℹ️ Alright, we deleted it. Just know that we had \"\n \"high expectations that you could help us improve \"\n \"deforestation detection models. We thought we \"\n \"were friends 🙁\"\n )\n elif (\n negative_btn or session_state.user_feedback_negative\n ) and not positive_btn:\n session_state.user_feedback_positive = False\n session_state.user_feedback_negative = True\n st.info(\n \"ℹ️ Thank you for your feedback! This can help us \"\n \"improve our models 🙌\\n\"\n \"It would be even better if you could tell us \"\n \"what makes you think the model failed. Mind \"\n \"leaving a comment bellow?\"\n )\n if session_state.user_data_uploaded is False:\n upload_user_data(\n session_state.user_id,\n session_state.ts,\n session_state.image_id,\n img,\n output[1],\n session_state.user_feedback_positive,\n )\n session_state.user_data_uploaded = True\n user_comment = st.empty()\n user_comment_txt = user_comment.text_input(\n label=\"Leave a comment on why the model failed.\",\n max_chars=280,\n )\n if len(user_comment_txt) > 0:\n upload_user_comment(\n session_state.user_id,\n session_state.image_id,\n user_comment_txt,\n )\n if st.button(\"Delete my image and feedback data\"):\n st.info(\n \"ℹ️ Alright, we deleted it. Just know that we had \"\n \"high expectations that you could help us improve \"\n \"deforestation detection models. We thought we \"\n \"were friends 🙁\"\n )\n delete_user_data(session_state.user_id, session_state.image_id)\n # Model interpretation\n with st.beta_expander(\"Peek inside the black box\"):\n explain_cols = st.beta_columns(2)\n with explain_cols[0]:\n st.subheader(\"Model structure\")\n st.info(\n \"ℹ️ Our model is largely based on the [ResNet](https://paperswithcode.com/method/resnet) \"\n \"archirtecture, using a ResNet50 from [FastAI](https://docs.fast.ai/). \"\n \"Bellow you can see the model's layer definition.\"\n )\n st.text(model.model)\n with explain_cols[1]:\n st.subheader(\"Output interpretation\")\n # TODO Add the result of applying SHAP to the model in the current sample\n st.info(\n \"ℹ️ Given some difficulties with using [SHAP](https://github.com/slundberg/shap) \"\n \"with [FastAI](https://docs.fast.ai/), we haven't implemented this yet. \"\n \"Would you like to give it a try?\"\n )\n\n\ndef overview():\n st.title(\"Overview\")\n # Initial instructions\n init_info = st.empty()\n # Set the sidebar inputs\n st.sidebar.title(\"Inputs\")\n # NOTE For the sake of time, we're just going to use the `Land scenes` model\n # model_type = st.sidebar.radio(\"Model\", [\"Deforestation\", \"Land scenes\"])\n model_type = \"Land scenes\"\n dataset_name = st.sidebar.radio(\"Dataset\", [\"Amazon\", \"Oil palm\"])\n chosen_set = None\n if dataset_name == \"Amazon\":\n chosen_set = st.sidebar.radio(\"Set\", [\"Train\", \"Validation\"])\n init_info.info(\n \"ℹ️ You've selected the \"\n \"[Amazon dataset](https://www.kaggle.com/c/planet-understanding-the-amazon-from-space/), \"\n \"which is the one in which our models were trained on. As such, you can look at performance \"\n \"on either the train or validation set.\"\n )\n (\n bucket_name,\n img_path,\n labels_table,\n img_name_col,\n label_col,\n ) = set_paths(dataset_name, model_type)\n else:\n init_info.info(\n \"ℹ️ You've selected the \"\n \"[oil palm dataset](https://www.kaggle.com/c/widsdatathon2019/), \"\n \"which can be seen as a test dataset, i.e. it wasn't used during training. \"\n \"While it should be somewhat similar to the Amazon dataset, it can be interesting \"\n \"to compare results on potentially out-of-domain data.\"\n )\n (\n bucket_name,\n img_path,\n labels_table,\n img_name_col,\n label_col,\n ) = set_paths(dataset_name, model_type)\n # Set the model\n model = load_learner(\n \"fsdl_deforestation_detection/modeling/resnet50-128.pkl\"\n )\n # Speed up model inference by deactivating gradients\n model.model.eval()\n torch.no_grad()\n img_names = load_image_names(model, chosen_set, bucket_name, labels_table)\n sample_name = st.sidebar.selectbox(\n \"Sample\",\n img_names,\n )\n st.sidebar.markdown(\n \"Made by [André Ferreira](https://andrecnf.com/) and [Karthik Bhaskar](https://www.kbhaskar.com/).\"\n )\n # Load all the data (or some samples) from the selected database\n n_samples = 250\n imgs, labels = load_data(\n dataset_name,\n model_type,\n bucket_name,\n img_path,\n img_names,\n labels_table,\n img_name_col,\n n_samples=n_samples,\n )\n # Show some performance metrics\n # TODO Use all the set data to get the correct performance metrics\n st.header(\"Performance\")\n metrics_cols = st.beta_columns(2)\n with st.spinner(\"Getting performance results...\"):\n if dataset_name == \"Amazon\":\n # NOTE This are the metrics obtained for the validation set,\n # when training the model in Colab; ideally, this should still\n # be calculated dynamically in here, but it's proving to be\n # slow and impractical in the approach that we were taking\n acc = 0.956407\n fbeta = 0.926633\n # pred, acc, fbeta = get_performance_metrics(\n # model, imgs, labels, dataset_name\n # )\n pred, _, _ = get_performance_metrics(\n model, imgs, labels, dataset_name\n )\n else:\n pred, acc, fbeta = get_performance_metrics(\n model, imgs, labels, dataset_name\n )\n acc, fbeta = 100 * acc, 100 * fbeta\n with metrics_cols[0]:\n fig = get_gauge_plot(acc, title=\"Accuracy\")\n st.plotly_chart(fig, use_container_width=True)\n with metrics_cols[1]:\n fig = get_gauge_plot(fbeta, title=\"F2\")\n st.plotly_chart(fig, use_container_width=True)\n if dataset_name == \"Amazon\":\n st.info(\n \"ℹ️ These are the validation metrics [obtained when training the model](https://colab.research.google.com/github/karthikraja95/fsdl_deforestation_detection/blob/master/fsdl_deforestation_detection/experimental/FSDL_Final_Model.ipynb).\"\n )\n else:\n st.info(\n \"ℹ️ Showing performance metrics here by mapping the original labels to a \"\n \"binary, deforestation label. This should be somewhat relatable to the \"\n \"presence of oil palm plantations, which is the label in this dataset.\"\n )\n # Show number of samples\n fig = get_number_plot(len(img_names), title=\"Samples\")\n st.plotly_chart(fig, use_container_width=True)\n # Show label analysis\n st.header(\"Label analysis\")\n labels_cols = st.beta_columns(2)\n with labels_cols[0]:\n fig = get_hist_plot(\n labels,\n \"labels\",\n dataset_name,\n model_type,\n title=\"Labels distribution\",\n )\n st.plotly_chart(fig, use_container_width=True)\n with labels_cols[1]:\n fig = get_hist_plot(\n pred,\n \"predictions\",\n dataset_name,\n model_type,\n title=\"Predicted labels distribution\",\n )\n st.plotly_chart(fig, use_container_width=True)\n st.info(\n f\"ℹ️ Using only a subset of {n_samples} samples, so as to make this plot practically fast.\"\n )\n # Show imagery analysis\n st.header(\"Imagery analysis\")\n st.subheader(\"Image size\")\n img_size_cols = st.beta_columns(3)\n with img_size_cols[0]:\n fig = get_number_plot(imgs.shape[1], title=\"Height\")\n st.plotly_chart(fig, use_container_width=True)\n with img_size_cols[1]:\n fig = get_number_plot(imgs.shape[2], title=\"Width\")\n st.plotly_chart(fig, use_container_width=True)\n with img_size_cols[2]:\n fig = get_number_plot(imgs.shape[3], title=\"Channels\")\n st.plotly_chart(fig, use_container_width=True)\n fig = get_pixel_dist_plot(imgs)\n st.plotly_chart(fig, use_container_width=True)\n st.info(\n f\"ℹ️ Using only a subset of {n_samples} samples, so as to make this plot practically fast.\"\n )\n # Show sample analysis\n st.header(\"Sample analysis\")\n # Load and display the uploaded image\n with st.spinner(\"Loading image...\"):\n img = load_image(bucket_name, img_path, sample_name)\n fig = px.imshow(img)\n st.plotly_chart(fig)\n # Run the model on the image\n output = run_model(model, img)\n st.subheader(\"Model output:\")\n show_model_output(model_type, output)\n st.subheader(\"Real labels:\")\n show_labels(\n dataset_name, sample_name, labels_table, img_name_col, label_col\n )\n st.info(\n \"ℹ️ Green labels represent categories that we don't associate with deforestation \"\n \"risk (e.g. natural occurences or old structures), while red labels can serve as \"\n \"a potential deforestation signal (e.g. new constructions, empty patches in forests).\"\n )\n # Model interpretation\n with st.beta_expander(\"Peek inside the black box\"):\n explain_cols = st.beta_columns(2)\n with explain_cols[0]:\n st.subheader(\"Model structure\")\n st.info(\n \"ℹ️ Our model is largely based on the [ResNet](https://paperswithcode.com/method/resnet) \"\n \"archirtecture, using a ResNet50 from [FastAI](https://docs.fast.ai/). \"\n \"Bellow you can see the model's layer definition.\"\n )\n st.text(model.model)\n with explain_cols[1]:\n st.subheader(\"Output interpretation\")\n # TODO Add the result of applying SHAP to the model in the current sample\n st.info(\n \"ℹ️ Given some difficulties with using [SHAP](https://github.com/slundberg/shap) \"\n \"with [FastAI](https://docs.fast.ai/), we haven't implemented this yet. \"\n \"Would you like to give it a try?\"\n )\n","sub_path":"fsdl_deforestation_detection/dashboard/layouts.py","file_name":"layouts.py","file_ext":"py","file_size_in_byte":15515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"420048027","text":"#Auhtor:Aninda Kundu\n\ndef main():\n import pandas as pd\n from sklearn.preprocessing import LabelEncoder\n from sklearn.model_selection import train_test_split\n import seaborn as sns\n import matplotlib.pyplot as plt\n from sklearn.preprocessing import StandardScaler\n import keras\n from keras.models import Sequential\n from keras.layers import Dense\n from keras.layers import LeakyReLU, PReLU, ELU\n from keras.layers import Dropout\n from sklearn.metrics import confusion_matrix\n from sklearn.metrics import accuracy_score\n\n #Data preprocessing\n df = pd.read_csv(\"data.csv\")\n df.drop('Unnamed: 32', axis=1, inplace=True)\n df.drop('id', axis=1, inplace=True)\n X = df.drop('diagnosis', axis=1)\n y = df['diagnosis']\n labelencoder_X_1 = LabelEncoder()\n y = labelencoder_X_1.fit_transform(y)\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)\n\n #Check the distributions of all features\n '''\n for feature in X.columns:\n sns.distplot(X[feature])\n plt.ylabel(feature)\n plt.xlabel(feature)\n plt.show()\n '''\n\n sc = StandardScaler()\n X_train = sc.fit_transform(X_train)\n X_test = sc.transform(X_test)\n\n # Initialising the ANN\n classifier = Sequential()\n\n # Adding the input layer and the first hidden layer\n classifier.add(Dense(units=6, kernel_initializer='he_uniform', activation='relu', input_dim=30))\n # classifier.add(Dropout(0.5))\n\n # Adding the second hidden layer\n classifier.add(Dense(units=6, kernel_initializer='he_uniform', activation='relu'))\n # classifier.add(Dropout(0.5))\n # Adding the output layer\n classifier.add(Dense(units=1, kernel_initializer='glorot_uniform', activation='sigmoid'))\n\n # Compiling the ANN\n classifier.compile(optimizer='adam', loss='binary_crossentropy', metrics=['acc'])\n\n model_history = classifier.fit(X_train, y_train, validation_split=0.33, batch_size=10, epochs=150)\n\n # list all data in history\n\n print(model_history.history.keys())\n # summarize history for accuracy\n plt.plot(model_history.history['acc'])\n plt.plot(model_history.history['val_acc'])\n plt.title('model accuracy')\n plt.ylabel('accuracy')\n plt.xlabel('epoch')\n plt.legend(['train', 'test'], loc='upper left')\n plt.show()\n\n # summarize history for loss\n plt.plot(model_history.history['loss'])\n plt.plot(model_history.history['val_loss'])\n plt.title('model loss')\n plt.ylabel('loss')\n plt.xlabel('epoch')\n plt.legend(['train', 'test'], loc='upper left')\n plt.show()\n\n y_pred = classifier.predict(X_test)\n y_pred = (y_pred > 0.5)\n\n # Making the Confusion Matrix\n\n cm = confusion_matrix(y_test, y_pred)\n\n # Calculate the Accuracy\n\n score = accuracy_score(y_pred, y_test)\n print(cm)\n print(score)\n sns.heatmap(cm, annot=True)\n plt.savefig('h.png')\n\n\nif __name__==\"__main__\":\n main()","sub_path":"ANN.py","file_name":"ANN.py","file_ext":"py","file_size_in_byte":2953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"451587050","text":"import logging\n\nclass Logger:\n\n log = logging.getLogger(__name__)\n\n @staticmethod\n def getLogger():\n return Logger.log\n\n @staticmethod\n def init():\n Logger.log.setLevel(logging.DEBUG)\n\n file_handler = logging.FileHandler('/var/www/virginia/logs/virginia.log','w','utf-8')\n file_handler.setLevel(logging.DEBUG)\n file_format = logging.Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d in %(funcName)s]')\n file_handler.setFormatter(file_format)\n Logger.log.addHandler(file_handler)\n\n console_handler = logging.StreamHandler()\n console_handler.setLevel(logging.INFO)\n console_format = logging.Formatter('%(message)s')\n console_handler.setFormatter(console_format)\n Logger.log.addHandler(console_handler)\n","sub_path":"applogging/virginia_logger.py","file_name":"virginia_logger.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"459420533","text":"'''\nCreated on Sep 17, 2016\n\n@author: uid38420\n'''\nimport os\nimport cv2\nimport numpy as np\nfrom glob import glob\nimport algorithm as algo\n\ndatabase = \"D:/Codes/Git/For everything else/AI_Bio_Face_db_YaleB/\"\ngamma = 1.5\n\ndir = os.listdir(database) \nfor item in dir :\n if \".git\" not in item:\n folderName = database + item + \"/*.jpg\"\n \n for fn in glob(folderName):\n img1 = cv2.imread(fn, 0)\n \n cl1 = algo.clahe(img1)\n adjusted = algo.gammaCorrection(cl1, gamma=gamma)\n cv2.putText(adjusted, \"g={}\".format(gamma), (10, 30),\n cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 3)\n \n name = fn.rpartition('\\\\')\n print('processing...' + name[2])\n fileName = name[2].rpartition('.')\n resultPath = os.getcwd() + \"\\\\\" + \"results\" + \"\\\\\" + item + \"\\\\\"\n if not os.path.exists(resultPath):\n os.makedirs(resultPath)\n resultName = resultPath + name[2]\n# cv2.imwrite(resultName, np.hstack([cl1, adjusted]))\n cv2.imwrite(resultName, adjusted)\n","sub_path":"PreProcessing/IlluminationNormalisation/GIC+Clahe.py","file_name":"GIC+Clahe.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"266087285","text":"import pandas as pd\nfrom flaskr.framework.model.request.response import Response\n\nfrom flaskr.database.dataset_models.repository import Repository\nfrom flaskr.model.helpers.covidstats import covid_stats\n\n\nclass Writer:\n def __init__(self,\n excelwriter: pd.ExcelWriter,\n dataset_id: str):\n self.excelwriter = excelwriter\n self.dataset_id = dataset_id\n self.time = []\n self.workbook = None\n\n def writebook(self):\n dataset_repository = Repository()\n dataset = dataset_repository.get_by_id(self.dataset_id)\n df = dataset.get_pd_well_collection()\n\n df = covid_stats(df)\n\n df.to_excel(self.excelwriter, sheet_name='summary', index=False)\n self.excel_formatting('summary', df)\n\n return Response(True, '')\n\n def excel_formatting(self, sheetname, df):\n worksheet = self.excelwriter.sheets[sheetname]\n for idx, column in enumerate(df.columns):\n lengths = [len(x) for x in df.loc[:, column].astype('str')]\n lengths.append(len(column))\n maxlength = max(lengths)\n worksheet.set_column(idx, idx + 1, maxlength + 3)\n","sub_path":"flaskr/filewriter/statswriter.py","file_name":"statswriter.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"153984999","text":"import re\nimport random\nimport string\nfrom datetime import datetime\nfrom pytz import UTC\n\ndef to_utc(dt):\n if not isinstance(dt, datetime):\n dt = datetime(dt.year, dt.month, dt.day)\n if dt.tzinfo is None:\n return UTC.localize(dt)\n else:\n return dt.astimezone(UTC)\n\nsource = string.ascii_lowercase + string.digits\ndef uid():\n vals = [random.choice(source) for i in range(5)]\n return ''.join(vals)\n\n\nidre = lambda name: re.compile(r'\\b%s\\b' % re.escape(name))\n\nclass Replace(object):\n \"\"\"\n Utility for fast updates on table involving most rows in the table.\n Instead of executemany(\"UPDATE ...\"), create and populate\n a new table (which can be done using COPY), then rename.\n\n Can do this only if no other tables in the db depend on the table.\n\n NOTE: With PostgreSQL < 9.3 after the table is dropped attempts to\n query it will fail.\n\n See http://dba.stackexchange.com/a/41111/9941\n \"\"\"\n def __init__(self, connection, table):\n self.cursor = connection.cursor()\n self.uid = uid()\n self.table = table\n self.name_re = idre(table)\n self.temp_name = self.newname()\n self.rename = [('TABLE', self.temp_name, table)]\n self.inspect()\n\n def __enter__(self):\n self.create_temp()\n self.create_defaults()\n return self.temp_name\n\n def __exit__(self, exc_type, exc, tb):\n if exc_type is None:\n self.create_notnull()\n self.create_constraints()\n self.create_indices()\n self.create_triggers()\n self.swap()\n self.create_views()\n self.cursor.close()\n\n def inspect(self):\n defquery = \"\"\"\n SELECT attname, pg_get_expr(adbin, adrelid)\n FROM pg_attribute\n JOIN pg_attrdef ON attrelid = adrelid AND adnum = attnum\n WHERE adnum > 0\n AND attrelid = %s::regclass;\n \"\"\"\n self.cursor.execute(defquery, (self.table,))\n self.defaults = self.cursor.fetchall()\n seqquery = \"\"\"\n SELECT attname, relname FROM pg_class\n JOIN pg_depend ON (objid = pg_class.oid)\n JOIN pg_attribute ON (attnum=refobjsubid AND attrelid=refobjid)\n WHERE relkind = 'S'\n AND refobjid = %s::regclass\n \"\"\"\n self.cursor.execute(seqquery, (self.table,))\n self.sequences = self.cursor.fetchall()\n attquery = \"\"\"\n SELECT attname\n FROM pg_catalog.pg_attribute\n WHERE attrelid = %s::regclass\n AND attnum > 0 AND attnotnull\n \"\"\"\n self.cursor.execute(attquery, (self.table,))\n self.notnull = [an for (an,) in self.cursor]\n # primary key is recreated as a constraint, \n # but all other unique constraints are only\n # recreated as unique index\n conquery = \"\"\"\n SELECT DISTINCT contype, conname, pg_catalog.pg_get_constraintdef(oid)\n FROM pg_catalog.pg_constraint\n WHERE conrelid = %s::regclass AND contype != 'u'\n \"\"\"\n self.cursor.execute(conquery, (self.table,))\n self.constraints = self.cursor.fetchall()\n indquery = \"\"\"\n SELECT c.relname, pg_catalog.pg_get_indexdef(i.indexrelid)\n FROM pg_catalog.pg_index i\n JOIN pg_catalog.pg_class c ON c.oid = i.indexrelid\n WHERE NOT indisprimary\n AND indrelid = %s::regclass\n \"\"\"\n self.cursor.execute(indquery, (self.table,))\n self.indices = self.cursor.fetchall()\n trigquery = \"\"\"\n SELECT tgname, pg_catalog.pg_get_triggerdef(oid)\n FROM pg_catalog.pg_trigger\n WHERE tgconstraint = 0\n AND tgrelid=%s::regclass\n \"\"\"\n self.cursor.execute(trigquery, (self.table,))\n self.triggers = self.cursor.fetchall()\n viewquery = \"\"\"\n SELECT DISTINCT c.relname, pg_get_viewdef(r.ev_class)\n FROM pg_rewrite r\n JOIN pg_depend d ON d.objid = r.oid\n JOIN pg_class c ON c.oid = r.ev_class\n WHERE d.refobjid = %s::regclass;\n \"\"\"\n self.cursor.execute(viewquery, (self.table,))\n self.views = self.cursor.fetchall()\n\n def create_temp(self):\n create = 'CREATE TABLE \"%s\" AS TABLE \"%s\" WITH NO DATA'\n self.cursor.execute(create % (self.temp_name, self.table))\n\n def create_defaults(self):\n defsql = 'ALTER TABLE \"%s\" ALTER COLUMN \"%s\" SET DEFAULT %s'\n for col, default in self.defaults:\n self.cursor.execute(defsql % (self.temp_name, col, default))\n\n def create_notnull(self):\n nnsql = 'ALTER TABLE \"%s\" ALTER COLUMN \"%s\" SET NOT NULL'\n for col in self.notnull:\n self.cursor.execute(nnsql % (self.temp_name, col))\n\n def create_constraints(self):\n consql = 'ALTER TABLE \"%s\" ADD CONSTRAINT \"%s\" %s'\n for i, (contype, conname, condef) in enumerate(self.constraints):\n newname = self.newname('con', i)\n self.cursor.execute(consql % (self.temp_name, newname, condef))\n if 'p' == contype:\n self.rename.append(('INDEX', newname, conname))\n\n def create_indices(self):\n for i, (oldidxname, indexsql) in enumerate(self.indices):\n newidxname = self.newname('idx', i)\n newsql = self.sqlrename(indexsql, oldidxname, newidxname)\n self.cursor.execute(newsql)\n self.rename.append(('INDEX', newidxname, oldidxname))\n\n def create_triggers(self):\n for i, (oldtrigname, trigsql) in enumerate(self.triggers):\n newtrigname = self.newname('tg', i)\n newsql = self.sqlrename(trigsql, oldtrigname, newtrigname)\n self.cursor.execute(newsql)\n self.rename.append(('TRIGGER',\n '%s\" ON \"%s' % (newtrigname, self.table),\n oldtrigname))\n\n def swap(self):\n self.drop_views()\n self.drop_defaults()\n self.move_sequences()\n self.drop_original_table()\n self.rename_temp_table()\n\n def drop_views(self):\n for view, viewdef in self.views:\n self.cursor.execute('DROP VIEW \"%s\"' % view)\n\n def drop_defaults(self):\n dropdefsql = 'ALTER TABLE \"%s\" ALTER COLUMN \"%s\" DROP DEFAULT'\n for col, default in self.defaults:\n self.cursor.execute(dropdefsql % (self.table, col))\n\n def move_sequences(self):\n seqownersql = 'ALTER SEQUENCE \"%s\" OWNED BY \"%s\".\"%s\"'\n for col, seq in self.sequences:\n self.cursor.execute(seqownersql % (seq, self.temp_name, col))\n\n def drop_original_table(self):\n self.cursor.execute('DROP TABLE \"%s\"' % self.table)\n\n def rename_temp_table(self):\n sql = 'ALTER %s \"%s\" RENAME TO \"%s\"'\n for rename in self.rename:\n self.cursor.execute(sql % rename)\n\n def create_views(self):\n viewsql = 'CREATE VIEW \"%s\" AS %s'\n for view in self.views:\n sql = viewsql % view\n self.cursor.execute(sql)\n\n\n unsafe_re = re.compile(r'\\W+')\n def newname(self, pre=None, i=None):\n parts = ['%s']\n vals = [self.table]\n if pre is not None:\n parts.append('%s')\n vals.append(pre)\n if i is not None:\n parts.append('%02d')\n vals.append(i)\n parts.append('%s')\n vals.append(self.uid)\n return self.unsafe_re.sub('', '_'.join(parts) % tuple(vals)).lower()\n\n def sqlrename(self, sql, *args):\n newsql = self.name_re.sub(self.temp_name, sql)\n try:\n old, new = args\n except ValueError:\n return newsql\n else:\n return idre(old).sub(new, newsql)\n\n\nclass RenameReplace(Replace):\n \"Subclass for renaming old table and recreating empty one like it\"\n def __init__(self, connection, table, xform):\n \"\"\"\n xform must be a function which translates old\n names to new ones, used on tables & pk constraints\n \"\"\"\n super(RenameReplace, self).__init__(connection, table)\n self.xform = xform\n\n def drop_original_table(self):\n pass\n\n def rename_temp_table(self):\n sql = 'ALTER %s \"%s\" RENAME TO \"%s\"'\n for objtype, temp, orig in self.rename:\n print(objtype, temp, orig)\n new_name = self.xform(orig)\n self.cursor.execute(sql % (objtype, orig, new_name))\n super(RenameReplace, self).rename_temp_table()\n\n\ndef rename_replace(connection, table, xform):\n with RenameReplace(connection, table, xform):\n pass\n","sub_path":"pgcopy/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":8662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"521183001","text":"from Read_data import Read_GAP_data\nimport copy\nimport cplex\nclass ADMM:\n def __init__(self):\n self.reliability=2\n self.transition=2\n\n mod=Read_GAP_data()\n self.g_number_of_agents,self.g_number_of_jobs,self.agent_list,self.job_list=mod.read_data()\n self.g_iteration_times=40\n self.big_M=500\n #DP\n self.g_machine_state_vector_list=[[] for i in range (self.g_number_of_agents)]\n self.g_ending_state_vector_list=[None]*self.g_number_of_agents\n\n #results\n self.assignment_record=[] #the assignment matrix in each iteration\n self.serving_times=[] # record serving times of each job\n self.repeat_served=[] #repeat served in each iteration\n self.un_served=[] #unserved in each iteration\n self.record_multiplier=[] #multipliers in each iteration\n #LB,UB\n self.max_label_cost=float(\"inf\")\n self.ADMM_local_LB = [0] *self.g_iteration_times\n self.ADMM_local_UB = [0] *self.g_iteration_times\n self.ADMM_global_LB = [-self.max_label_cost] *self.g_iteration_times\n self.ADMM_global_UB = [self.max_label_cost] *self.g_iteration_times\n\n\n def g_solving_the_GAP_by_LR_heuristics(self):\n for i in range(self.g_iteration_times):\n self.assignment_record.append([])\n self.serving_times.append([0]*self.g_number_of_jobs)\n self.repeat_served.append([])\n self.un_served.append([])\n self.record_multiplier.append([])\n\n# step 1:LB generation\n serving_matrix_of_LR=[]\n serve_times=[0]*self.g_number_of_jobs\n for m in range(self.g_number_of_agents):#first term\n served_jobs,global_LB=self.g_solve_reliability_oriented_KS(m)\n self.ADMM_local_LB[i]+=global_LB\n serving_matrix_of_LR.append(served_jobs)\n for j in range(self.g_number_of_jobs):\n if served_jobs[j]==1:\n serve_times[j]+=1\n\n \"\"\"\n self.g_solve_KS(m,1)\n print(m)\n self.ADMM_local_LB[i]+=self.g_ending_state_vector_list[m].state_vector[0].cost_for_LR\n served_jobs=self.g_ending_state_vector_list[m].state_vector[0].served_jobs\n \n for j in served_jobs:\n serve_times[j]+=1\n \"\"\"\n\n for j in range(self.g_number_of_jobs):#multiplier term\n self.ADMM_local_LB[i]-=self.job_list[j].multiplier\n\n# step 2:UB generation (Handly, local search)\n #we should sort the job into three types: 0;1;>1\n #Question: For repeat served jobs, which knapsack should we choose?\n #choose the KS max: (u_j-c_i_j)/a_i_j\n self.assignment_matrix=[]\n for j in range(self.g_number_of_agents):\n self.assignment_matrix.append([0]*self.g_number_of_jobs)\n S_0=[]\n S_1=[]\n S_2=[]\n for j in range(self.g_number_of_jobs):\n if serve_times[j]==0:\n S_0.append(j)\n if serve_times[j]==1:\n S_1.append(j)\n if serve_times[j]>1:\n S_2.append(j)\n\n\n residual_capacity_list = []\n for m in range(self.g_number_of_agents):\n Agent = self.agent_list[m]\n residual_capacity_list.append(Agent.resource)\n\n mean_and_var=[]\n for m in range(self.g_number_of_agents):\n mean_and_var.append([0,0])\n\n # For S1:\n for j in S_1:\n for m in range(self.g_number_of_agents):\n Agent = self.agent_list[m]\n if serving_matrix_of_LR[m][j]==1:\n self.assignment_matrix[m][j]=1 #record\n # self.ADMM_local_UB[i] += Agent.cost_list_each_job[j] #S_0\n mean_and_var[m][0]+=Agent.cost_list_each_job[j]\n mean_and_var[m][1]+=Agent.cost_list_each_job[j]*self.transition\n residual_capacity_list[m]-=Agent.resource_list_each_job[j] #update resource\n\n # For S3: repeat served\n for j in S_2:\n served_KS_list=[]\n for m in range(self.g_number_of_agents):\n if serving_matrix_of_LR[m][j]==1:\n served_KS_list.append(m)\n utility_list=[]\n for m in served_KS_list:\n Agent = self.agent_list[m]\n # utility=Agent.cost_list_each_job[j]\n utility=(Agent.cost_list_each_job[j]+self.job_list[j].multiplier)/Agent.resource_list_each_job[j]\n utility_list.append(utility)\n #Find a KS (min)\n min_utility=min(utility_list)\n index=utility_list.index(min_utility)\n m=served_KS_list[index]\n Agent = self.agent_list[m]\n self.assignment_matrix[m][j] = 1 # record\n # self.ADMM_local_UB[i] += Agent.cost_list_each_job[j] # S_0\n mean_and_var[m][0]+=Agent.cost_list_each_job[j]\n mean_and_var[m][1]+=Agent.cost_list_each_job[j]*self.transition\n residual_capacity_list[m] -= Agent.resource_list_each_job[j] # update resource\n\n\n # For S0: unserved\n for j in S_0:\n served_KS_list=[]\n for m in range(self.g_number_of_agents):\n Agent = self.agent_list[m]\n resouce_of_j=Agent.resource_list_each_job[j]\n if residual_capacity_list[m]-resouce_of_j>=0:\n served_KS_list.append(m)\n\n utility_list = []\n for m in served_KS_list:\n Agent = self.agent_list[m]\n # utility = Agent.cost_list_each_job[j]\n utility =(Agent.cost_list_each_job[j]+self.job_list[j].multiplier) / Agent.resource_list_each_job[j]\n utility_list.append(utility)\n # Find a KS (min)\n if utility_list==[]:\n self.ADMM_local_UB[i]+=self.big_M\n self.un_served[i].append(j)\n else:\n min_utility = min(utility_list)\n index = utility_list.index(min_utility)\n m = served_KS_list[index]\n Agent = self.agent_list[m]\n self.assignment_matrix[m][j] = 1 # record\n # self.ADMM_local_UB[i] += Agent.cost_list_each_job[j] # S_0\n mean_and_var[m][0]+=Agent.cost_list_each_job[j]\n mean_and_var[m][1]+=Agent.cost_list_each_job[j]*self.transition\n residual_capacity_list[m] -= Agent.resource_list_each_job[j] # update resource\n\n self.assignment_record[i]=self.assignment_matrix\n\n #compute the UB\n for m in range(self.g_number_of_agents):\n mean=mean_and_var[m][0]\n var=mean_and_var[m][1]\n self.ADMM_local_UB[i]+=mean+self.reliability*(var)**(0.5)\n\n# step 3:multiplier update\n #step size: Handly\n # step_size=10/(i+1)\n # if step_size<0.1:\n # step_size=0.1\n #step size:\n # step 3.1 update gloabal UB/LB\n if i==0:\n self.ADMM_global_LB[i] = self.ADMM_local_LB[i]\n self.ADMM_global_UB[i] =self.ADMM_local_UB[i]\n else:\n self.ADMM_global_LB[i] = max(self.ADMM_local_LB[i],self.ADMM_global_LB[i-1])\n self.ADMM_global_UB[i] = min(self.ADMM_local_UB[i],self.ADMM_global_UB[i-1])\n\n print(\"iteration_{}_UB:{}\".format(i, self.ADMM_global_UB[i]))\n print(\"iteration_{}_LB:{}\".format(i, self.ADMM_global_LB[i]))\n # step 3.1 step size\n difference=0\n for j in range(self.g_number_of_jobs):\n difference+=(serve_times[j]-1)**2\n if difference==0:\n step_size=0\n else:\n step_size=(self.ADMM_global_UB[i]-self.ADMM_global_LB[i])/difference/4\n\n # step_size = 1\n for j in range(self.g_number_of_jobs):\n #record the multipliers\n self.record_multiplier[i].append(self.job_list[j].multiplier)\n self.job_list[j].multiplier+=step_size*(serve_times[j]-1)\n#Step 4: Terminal condition\n#Note: for min 1, for max -1\n if self.ADMM_global_LB[i]!=0:\n gap=(self.ADMM_global_UB[i]-self.ADMM_global_LB[i])/self.ADMM_global_UB[i]\n else:\n gap=1\n if gap<0.03:\n # self.g_iteration_times_total=i+1\n break\n # self.g_iteration_times_total=self.g_iteration_times\n\n def g_solve_reliability_oriented_KS(self,m):\n #step 1: initilization\n global_LB=-10000\n global_UB= 10000\n k_max=20\n optimal_assignment=[]\n self.multiplier_agent=0.5\n y_=self.g_solve_least_expected_KS(m)\n\n for k in range(k_max):\n LB=0\n UB=0\n #step 2: solve decomposed dual problems\n #Part I: subproblem of x\n self.g_solve_subproblem_of_x(m)\n LB+=self.Knapsack.solution.get_objective_value()\n variance_of_selected_jobs=0\n value_list=self.Knapsack.solution.get_values()\n for j in range(self.g_number_of_jobs):\n if value_list[j]==1:\n variance_of_selected_jobs+=self.agent_list[m].cost_list_each_job[j]*self.transition\n\n #Part II: subprolem of y\n obj_of_y_=self.reliability*(y_)**0.5-self.multiplier_agent*y_\n if obj_of_y_>0:\n y=0\n LB+=0\n else:\n y=y_\n LB+=obj_of_y_\n\n #generate the current UB\n Agent=self.agent_list[m]\n cost_list_each_job=Agent.cost_list_each_job\n for j in range(self.g_number_of_jobs):\n if round(value_list[j])==1:\n job = self.job_list[j]\n multiplier=job.multiplier\n UB+=multiplier+cost_list_each_job[j]\n UB+=self.reliability*(variance_of_selected_jobs)**0.5\n\n #UB and LB update\n if LB>global_LB:\n global_LB=LB\n if UBself.agent_list[m].resource:\n continue\n else:\n new_element.weight+=self.agent_list[m].resource_list_each_job[j]\n new_element.served_jobs.append(j)\n new_element.calculate_cost(self.agent_list[m],self.job_list[j])\n self.g_machine_state_vector_list[m][j+1].update_stage_state(new_element, Flag)\n if j == self.g_number_of_jobs-1:\n self.g_ending_state_vector_list[m].update_stage_state(new_element, Flag)\n continue\n self.g_ending_state_vector_list[m].sort(Flag) #Note: min\n # print()\n\n\nclass State_vector:\n def __init__(self):\n self.state_vector_id=0\n self.state_vector=[] #possible states in stage k\n\n def Reset(self):\n self.state_vector_id=0\n self.state_vector = [] # possible states in stage k\n\n def update_stage_state(self,element,Flag):\n weight=element.weight\n if Flag==1:#LR\n cost=element.cost_for_LR\n #when we cannot find a better state than element, we add the element.\n#Note: add the new element?\n w=0 #1,存在一个比element更优的;0,不存在\n for state in self.state_vector:\n cost0=state.cost_for_LR\n weight0=state.weight\n if cost0cost and weight0>=weight:\n self.state_vector.remove(state)\n #add the element\n if w==0:\n self.state_vector.append(element)\n\n if Flag == 2: # ALR\n cost = element.cost_for_ALR\n # when we cannot find a better state than element, we add the element.\n w = 0 # 1,存在一个比element更优的;0,不存在\n for state in self.state_vector:\n cost0 = state.cost_for_ALR\n weight0 = state.weight\n if cost0 < cost and weight0 <= weight: # exist a state\n w = 1\n # Note: delete an existed state?\n if cost0 > cost and weight0 >= weight:\n self.state_vector.remove(state)\n # add the element\n if w == 0:\n self.state_vector.append(element)\n\n\n def sort(self,Flag):\n if Flag == 1:\n self.state_vector = sorted(self.state_vector, key=lambda x: x.cost_for_LR)\n if Flag == 2:\n self.state_vector = sorted(self.state_vector, key=lambda x: x.cost_for_ALR)\n\nclass State:\n def __init__(self):\n self.weight=0\n self.served_jobs=[]\n self.primal_cost=0\n self.cost_for_LR=0\n self.cost_for_ALR=0\n def copy(self,element):\n self.weight=copy.copy(element.weight)\n self.served_jobs = []\n self.served_jobs = copy.copy(element.served_jobs)\n self.primal_cost = copy.copy(element.primal_cost)\n self.cost_for_LR = copy.copy(element.cost_for_LR)\n self.cost_for_ALR = copy.copy(element.cost_for_ALR)\n\n def calculate_cost(self,agent,job):\n #agent: current machine; job:current job.(class)\n job_id=job.job_id\n self.primal_cost-=agent.cost_list_each_job[job_id]\n self.cost_for_LR=self.cost_for_LR-agent.cost_list_each_job[job_id]+job.multiplier\n self.cost_for_ALR=self.cost_for_ALR-agent.cost_list_each_job[job_id]+job.multiplier_ALR\n#note: \"-\" for max problem; \"+\" min problem","sub_path":"A/Scenario-5 R=2, T=2/LR/a05200~3235/Model.py","file_name":"Model.py","file_ext":"py","file_size_in_byte":20933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"290508317","text":"#run: python3 find_large_clusters.py src_file dest_file img_num\nimport pandas as pd\nimport csv\nimport sys\n\n\nif len(sys.argv) < 4:\n print(\"Usage: python3 find_large_clusters.py src_file large_clusters_file small_clusters_file embedding_file img_num\")\n sys.exit()\n\nsrc_file = sys.argv[1] # read from\nlarge_clusters_file = sys.argv[2] # where to save\nsmall_clusters_file = sys.argv[3] # where to save\nembedding_file = sys.argv[4] # the file that containes the embeddings\nimg_num = int(sys.argv[5]) # the number of images in the cluster\n\ndf = pd.read_csv(src_file, sep=':', names=['path', 'label'])\nemb_df = pd.read_csv(embedding_file, sep='G', names=['path', 'emb'])\n\nlarge_clusters = pd.DataFrame()\nsmall_clusters = pd.DataFrame()\n\n\nlabels = df.label.unique()\nfor l in labels:\n rows = df.loc[df['label'] == l]\n if rows.shape[0] > img_num:\n large_clusters = large_clusters.append(rows, ignore_index = True)\n else:\n for index, row in rows.iterrows():\n line = emb_df.loc[emb_df['path'] + 'G' == row['path'].replace('.icon','')]\n small_clusters = small_clusters.append(line, ignore_index = True)\nlarge_clusters.to_csv(large_clusters_file, index = None, sep= ':', header = False)\nsmall_clusters.to_csv(small_clusters_file, index = None, sep= ':', header = False)\n","sub_path":"separate_small_large_clusters.py","file_name":"separate_small_large_clusters.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"167791570","text":"# Copyright 2017 Intel Corporation\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\nimport json\nimport unittest\n\nimport requests\n\nfrom sawtooth_ias_client.ias_client import IasClient\nimport mock_ias_server\n\nURL = \"http://127.0.0.1:8008\"\n\n\nclass TestIasClient(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.mock_server = mock_ias_server.create(URL)\n cls.mock_server.start(\"up\")\n\n @classmethod\n def tearDownClass(cls):\n cls.mock_server.stop()\n\n def test_up(self):\n \"\"\"Verify that the client behaves as expected when the IAS server is\n functioning properly.\n \"\"\"\n self.mock_server.restart(\"up\")\n client = IasClient(URL, None, 5)\n\n siglist = client.get_signature_revocation_lists(gid=\"gid\")\n received = self.mock_server.get_received()\n\n self.assertEqual(received[\"command\"], \"GET\")\n self.assertEqual(received[\"path\"], \"/attestation/v3/sigrl/gid\")\n self.assertEqual(siglist, \"thisisasignaturelist\")\n\n verification = client.post_verify_attestation(\n \"thisisaquote\", \"thisisamanifest\", 34608138615\n )\n received = self.mock_server.get_received()\n received_data = json.loads(received[\"data\"].decode())\n\n self.assertEqual(received[\"command\"], \"POST\")\n self.assertEqual(received[\"path\"], \"/attestation/v3/report\")\n self.assertEqual(received_data, {\n \"isvEnclaveQuote\": \"thisisaquote\",\n \"pseManifest\": \"thisisamanifest\",\n \"nonce\": 34608138615,\n })\n self.assertEqual(verification, {\n \"verification_report\": '{\"thisisa\":\"verification_report\"}',\n \"signature\": \"signature\",\n })\n\n def test_error(self):\n \"\"\"Verify that the client behaves as expected when the IAS server\n returns an HTTP status code that is an error.\n \"\"\"\n self.mock_server.restart(\"error\")\n client = IasClient(URL, None, 5)\n self.assertRaises(requests.HTTPError,\n client.get_signature_revocation_lists)\n self.assertRaises(requests.HTTPError,\n client.post_verify_attestation, \"\")\n\n def test_slow(self):\n \"\"\"Verify that the client throws a timeout error if the IAS server is\n slow to respond.\n \"\"\"\n self.mock_server.restart(\"slow\")\n client = IasClient(URL, None, 0.1)\n self.assertRaises(requests.exceptions.Timeout,\n client.get_signature_revocation_lists)\n self.assertRaises(requests.exceptions.Timeout,\n client.post_verify_attestation, \"\")\n\n def test_down(self):\n \"\"\"Verify that the client throws a connection error if the IAS server\n doesn't repond correctly.\n \"\"\"\n self.mock_server.restart(\"down\")\n client = IasClient(URL, None, 5)\n self.assertRaises(requests.exceptions.ConnectionError,\n client.get_signature_revocation_lists)\n self.assertRaises(requests.exceptions.ConnectionError,\n client.post_verify_attestation, \"\")\n","sub_path":"ias_client/tests/unit/test_ias_client.py","file_name":"test_ias_client.py","file_ext":"py","file_size_in_byte":3725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"450180534","text":"from pprint import pprint\nfrom time import sleep\nimport logging\nimport requests\nimport json\nimport os\nfrom datetime import timedelta\n\nfrom ..json.processor import GenericJsonProcessor\nfrom ... import Config\nfrom ... import utils\nfrom ...app import get_push_receiver\nfrom ...datestring import date_to_string, string_to_date\n\nfrom bookiesports.normalize import IncidentsNormalizer, NotNormalizableException\n\n\n\"\"\"\n Provider module, actual name obfuscated\n\"\"\"\nNAME = os.path.basename(__file__).split(\".\")[0]\nPLAIN_NAME = Config.get(\"providers\", NAME, \"name\", default=None)\n\nEVENTS_HISTORY = {}\n\n\ndef _get(*args, **kwargs):\n return Config.get(\"providers\", NAME, *args, **kwargs)\n\n\ndef logged_json_get(url):\n logging.getLogger(__name__).info(\"[GET] \" + url)\n json_payload = utils.save_json_loads(\n requests.get(\n url,\n timeout=_get(\"timeout\", 2)\n ).content\n )\n if \"error\" in json_payload:\n raise Exception(url + \": \" + json_payload[\"error\"])\n if \"pager\" in json_payload:\n # fetch all\n _paged_results = [json_payload]\n while _paged_results[len(_paged_results) - 1][\"pager\"][\"per_page\"] == len(_paged_results[len(_paged_results) - 1][\"results\"]):\n _url = url + \"&page=\" + str(_paged_results[len(_paged_results) - 1][\"pager\"][\"page\"] + 1)\n logging.getLogger(__name__).info(\"[GET] \" + _url)\n # we received a full page, query next\n _paged_results.append(\n utils.save_json_loads(\n requests.get(\n _url,\n timeout=_get(\"timeout\", 2)\n ).content\n )\n )\n # merge results\n json_payload = {\n \"success\": _paged_results[0][\"success\"],\n \"pager\": _paged_results[0][\"pager\"],\n \"results\": []\n }\n for _json_payload in _paged_results:\n for _event in _json_payload[\"results\"]:\n json_payload[\"results\"].append(_event)\n return json_payload\n\n\ndef _as_list(result, find_string=None):\n if \"results\" in result:\n result = result[\"results\"]\n return [str(x[\"id\"]) + \" - \" + x[\"name\"] for x in result if find_string is None or find_string.lower() in x[\"name\"].lower()]\n\n\ndef _unify(result, find_string=None):\n if \"results\" in result:\n result = result[\"results\"]\n return [{\n \"id\": x[\"id\"],\n \"name\": x[\"name\"]\n } for x in result if find_string is None or find_string.lower() in x[\"name\"].lower()]\n\n\ndef _parse_id(id_or_name):\n try:\n return int(id_or_name)\n except Exception:\n return None\n\n\ndef resolve_via_api(url):\n # resolve via http API\n seperator = \"&\" if \"?\" in url else \"?\"\n\n url_with_token = (url + seperator +\n \"token=\" + _get(\"token\"))\n return logged_json_get(url_with_token)\n\n\ndef _get_sports_to_track():\n return _unify(_get(\n \"recognize\",\n \"sports\"\n ))\n\n\ndef _id_to_sport(sport_id):\n sports = _get(\n \"recognize\",\n \"sports\"\n )\n return next(item for item in sports if str(item[\"id\"]) == str(sport_id))\n\n\ndef _get_upcoming_events(api, sport_id, league_id, until=None):\n if until is None:\n reponse = resolve_via_api(_get(\"api\", api, \"upcoming\") + \"?sport_id=\" + str(sport_id) + \"&league_id=\" + str(league_id))\n else:\n if type(until) == int:\n until = string_to_date() + timedelta(days=until)\n else:\n until = string_to_date(until)\n now = string_to_date()\n if (now < until):\n results_list = []\n while now < until:\n day = now.strftime(\"%Y%m%d\")\n results_list.append(\n resolve_via_api(\n _get(\"api\", api, \"upcoming\") +\n \"?sport_id=\" + str(sport_id) +\n \"&league_id=\" + str(league_id) +\n \"&day=\" + day\n )\n )\n now = now + timedelta(days=1)\n results = {\n \"success\": results_list[0][\"success\"],\n \"results\": []\n }\n for _results in results_list:\n for _event in _results[\"results\"]:\n results[\"results\"].append(_event)\n reponse = results\n else:\n raise Exception(\"Can only query into the future\")\n reponse[\"api\"] = api\n return reponse\n\n\ndef _get_inplay_events(api, sport_id, league_id):\n return resolve_via_api(_get(\"api\", api, \"inplay\") + \"?sport_id=\" + str(sport_id) + \"&league_id=\" + str(league_id))\n\n\ndef _get_ended_events(api, sport_id, league_id):\n now = date_to_string()\n now = now[0:4] + now[5:7] + now[8:10]\n return resolve_via_api(\n _get(\"api\", api, \"ended\") +\n \"?sport_id=\" + str(sport_id) +\n \"&league_id=\" + str(league_id) +\n \"&day=\" + now\n )\n\n\ndef _get_event(api, event_id):\n json_payload = resolve_via_api(_get(\"api\", api, \"event\") + \"?event_id=\" + str(event_id))\n if json_payload[\"success\"] == 1 and json_payload[\"results\"][0][\"id\"] == event_id:\n return json_payload[\"results\"][0]\n else:\n raise Exception(\"Event not found\")\n\n\nclass Processor(GenericJsonProcessor):\n def __init__(self):\n super(Processor, self).__init__()\n self._sports_to_track = None\n\n def _parse_raw(self, raw_file_content, raw_environ=None):\n return raw_file_content\n\n def _get_provider_info(self, event):\n info = {\n \"name\": PLAIN_NAME,\n \"pushed\": date_to_string(),\n \"api_event_id\": event[\"id\"]\n }\n if event.get(\"our_event_id\", None) is not None:\n info[\"our_event_id\"] = event[\"our_event_id\"]\n return info\n\n def _process_event_json(self, source_json):\n incidents = []\n for _event in source_json[\"results\"]:\n try:\n incident_id = {\n \"sport\": _id_to_sport(_event[\"sport_id\"])[\"name\"],\n \"home\": _event[\"home\"][\"name\"],\n \"away\": _event[\"away\"][\"name\"],\n \"start_time\": date_to_string(_event[\"time\"]),\n \"event_group_name\": _event[\"league\"][\"name\"],\n }\n except KeyError:\n # wrong format?\n pass\n\n call = self._mapStatus(_event[\"time_status\"])\n arguments = self._getArgument(call, incident_id, _event[\"id\"])\n\n incidents.append({\n \"id\": incident_id,\n \"call\": call,\n \"arguments\": arguments,\n \"provider_info\": self._get_provider_info(_event)\n })\n\n if call == \"create\" and \"etfa\" in source_json.get(\"api\", None):\n # resolve dbmgs\n betfair_event = _get_event(\"etfa\", _event[\"id\"])\n print(betfair_event)\n\n elif call == \"finish\":\n call = \"result\"\n arguments = self._getArgument(call, incident_id, _event[\"id\"])\n incidents.append({\n \"id\": incident_id,\n \"call\": call,\n \"arguments\": arguments,\n \"provider_info\": self._get_provider_info(_event)\n })\n\n # it's unfeasible to maintain a list of applicable leagues. We attempt normalization\n # and only forward incidents that can be normalized (witness will still re-normalize as\n # dataproxies normally don't do that\n normalized = []\n normalizer = IncidentsNormalizer(chain=_get(\"bookiesports_chain\"))\n for incident in incidents:\n try:\n normalized.append(normalizer.normalize(incident, True))\n except NotNormalizableException as e:\n logging.getLogger(__name__).debug(str(e.__class__.__name__) + \": \" + str(incident[\"id\"]))\n pass\n return normalized\n\n def _process_source(self, source, source_type):\n if source_type == \"string\":\n source = json.loads(source)\n\n if \"results\" in source and \"home\" in source[\"results\"][0]:\n return self._process_event_json(source)\n\n return []\n\n def source_of_interest(self, source):\n if source:\n return '\"results\": [{\"id\":' in source and \"sport_id\" in source and \"league\" in source and \"home\" in source and \"away\" in source\n else:\n return False\n\n def _mapStatus(self, status):\n status_map = {\n \"0\": \"create\", # Not Started,\n \"1\": \"in_progress\", # InPlay\n \"3\": \"finish\", # Ended\n \"4\": \"canceled\", # Postponed\n \"5\": \"canceled\", # Cancelled\n \"8\": \"canceled\", # Abandoned\n \"9\": \"canceled\", # Retired\n \"99\": \"canceled\" # Removed\n }\n return status_map.get(status, \"canceled\")\n\n def _getArgument(self, call, incident_id, event_id=None):\n resolve_whistle_times = False\n\n if call == \"create\":\n return {\n \"season\": incident_id[\"start_time\"][0:4]\n }\n elif call == \"in_progress\":\n if event_id is not None:\n event_details = _get_event(\"general\", event_id)\n if resolve_whistle_times and \"inplay_created_at\" in event_details:\n return {\n \"whistle_end_time\": date_to_string(int(event_details[\"inplay_created_at\"]))\n }\n return {\n \"whistle_start_time\": None\n }\n elif call == \"finish\":\n if event_id is not None:\n event_details = _get_event(\"general\", event_id)\n if resolve_whistle_times and \"confirmed_at\" in event_details:\n return {\n \"whistle_end_time\": date_to_string(int(event_details[\"confirmed_at\"]))\n }\n return {\n \"whistle_end_time\": None\n }\n elif call == \"result\":\n if event_id is None:\n raise Exception(\"Event id is needed for resolving\")\n event_details = _get_event(\"general\", event_id)\n result = event_details[\"ss\"].split(\"-\")\n return {\n \"home_score\": result[0],\n \"away_score\": result[1]\n }\n raise Exception(\"Result not found\")\n elif call == \"canceled\":\n return {\"reason\": None}\n else:\n raise Exception(\"Unknown call: \" + str(call))\n\n def _incident_of_interest(self, incident):\n # check history, make sure it doesnt explode\n giid = incident[\"unique_string\"] + \"_\" + incident[\"provider_info\"][\"name\"]\n found = giid in EVENTS_HISTORY\n if not found:\n keys = list(EVENTS_HISTORY.keys())\n if len(keys) > 1000:\n EVENTS_HISTORY.pop(keys[0])\n EVENTS_HISTORY[giid] = True\n return not found\n\n\nclass BackgroundThread():\n\n def getName(self):\n return \"BackgroundPoller_\" + PLAIN_NAME\n\n def _send(self, results):\n try:\n response = requests.post(\n \"http://localhost:\" + str(Config.get(\"wsgi\", \"port\")) + \"/push/\" + NAME,\n files={\"json\": json.dumps(results)}\n )\n if response and response.content == _get(\"processor\", \"response\").encode() and response.status_code == 200:\n pass\n else:\n raise Exception(\"Pull could not be pushed, response \" + str(response.status_code))\n except Exception as e:\n logging.getLogger(self.getName()).warning(\"Fetching events failed ... error below ... continueing with next\")\n logging.getLogger(self.getName()).exception(e)\n\n def execute(self):\n api = \"general\"\n leagues = _get(\n \"recognize\",\n \"leagues\"\n )\n for league in leagues:\n self._send(_get_upcoming_events(api, league[\"sport_id\"], league[\"id\"], 3))\n self._send(_get_inplay_events(api, league[\"sport_id\"], league[\"id\"]))\n self._send(_get_ended_events(api, league[\"sport_id\"], league[\"id\"]))\n\n def run(self):\n sleep(2)\n while True:\n try:\n logging.getLogger(self.getName()).info(\"Fetching events ...\")\n self.execute()\n sleep(\n _get(\n \"polling_in_seconds\",\n 5\n )\n )\n except Exception as e:\n logging.getLogger(self.getName()).info(\"Exception while fetching events.\")\n logging.getLogger(self.getName()).exception(e)\n # sleep additionally\n sleep(\n _get(\n \"polling_in_seconds\",\n 5\n )\n )\n\n\nclass TooManyFoundException(Exception):\n pass\n\n\nclass NoneFoundException(Exception):\n pass\n\n\nclass CommandLineInterface():\n\n def _get_leagues(self, sport_id, country_id=None):\n _url = _get(\"api\", \"leagues\") + \"?sport_id=\" + str(sport_id)\n if country_id is not None:\n _url = _url + \"&cc=\" + country_id\n return resolve_via_api(_url)\n\n def pull(self, sport_id, league_id, date_from, date_to, matches=None, details=None):\n _pulled = _get_upcoming_events(sport_id, league_id)\n _processor = Processor()\n if matches is not None:\n _processor.debug_games(matches)\n incidents = []\n receiver = get_push_receiver(\n PLAIN_NAME,\n _processor\n )\n result = receiver.process_content(\n json.dumps(_pulled),\n \".json\",\n target=\"skip\",\n async_queue=False\n )\n for incident in result[\"incidents\"]:\n incidents.append(incident)\n return incidents\n\n def find(self, sport, country, eventgroup, season, date_from, date_to, details):\n if sport is not None:\n\n if _parse_id(eventgroup) is None:\n return _as_list(self._get_leagues(sport, country), eventgroup)\n else:\n return resolve_via_api(_get(\"api\", \"general\", \"upcoming\") + \"?sport_id=\" + sport)\n else:\n return _as_list(_get_sports_to_track())\n","sub_path":"dataproxy/provider/modules/radish.py","file_name":"radish.py","file_ext":"py","file_size_in_byte":14418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"346289772","text":"from MLEstimator import MLEstimator\n\n# Parse the data file.\ndef parse_no_title(lines, seperator):\n words= list()\n for i in range(2, len(lines), 4):\n parsed_line = lines[i].split(seperator)\n parsed_line.remove(\"\")\n for word in parsed_line:\n words.append(word)\n return words\n\n# Read the data file.\ndef read_file(file_name, parse_func, separator=None):\n file = open(file_name, 'r')\n lines = file.read().splitlines()\n file.close()\n return parse_func(lines, separator)\n\n\n# Write the output file.\ndef write_file(file_name, content):\n file = open(file_name, 'w')\n file.write(content)\n file.close()","sub_path":"Utils.py","file_name":"Utils.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"189298007","text":"from Grano import Grano\nfrom Fileaudio import Fileaudio\n\nclass Granulatore:\n\tdef __init__(self, fileaudio, grain_dur, olap, window):\n\t\tself.fileaudio = fileaudio\n\t\tself.grain_dur = grain_dur\n\t\tself.overlap = olap\n\t\tself.window = window\n\t\tself.grani = self.granula()\n\n\tdef granula(self):\n\t\tstep = self.grain_dur/self.overlap\n\t\tcur = 0\n\t\tres = [];\n\t\twhile (cur < self.fileaudio.dur):\n\t\t\tres.append(Grano(self.fileaudio, cur, self.grain_dur, self.window, self.overlap))\n\t\t\tcur += step\n\t\treturn res\n\n\tdef to_csound(self):\n\t\tself.header()\n\t\tfor g in self.grani:\n\t\t\tg.to_csound()\n\n\tdef header(self):\n\t\tprint('f%-2d 0 4096 20 2' % (self.window))\n","sub_path":"CAE-2/20190619/Rivelatore/Granulatore.py","file_name":"Granulatore.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"531036471","text":"from functools import reduce\nfrom operator import and_\n\nfrom litex.gen import *\nfrom litex.gen.genlib.cdc import MultiReg, ElasticBuffer\nfrom litex.gen.genlib.misc import WaitTimer\nfrom litex.gen.genlib.io import DifferentialInput\n\nfrom litex.soc.interconnect.csr import *\n\nfrom litejesd204b.transport import (LiteJESD204BTransportTX,\n LiteJESD204BSTPLGenerator)\nfrom litejesd204b.link import LiteJESD204BLinkTX\n\n\nclass LiteJESD204BCoreTX(Module, AutoCSR):\n def __init__(self, phys, jesd_settings, converter_data_width):\n self.enable = Signal()\n self.jsync = Signal()\n self.ready = Signal()\n self.restart = Signal()\n\n self.prbs_config = Signal(4)\n self.stpl_enable = Signal()\n\n self.sink = Record([(\"converter\"+str(i), converter_data_width)\n for i in range(jesd_settings.nconverters)])\n\n # # #\n\n # restart when disabled or on re-synchronization request\n self.comb += self.restart.eq(~self.enable | self.ready & ~self.jsync)\n\n # transport layer\n transport = LiteJESD204BTransportTX(jesd_settings,\n converter_data_width)\n self.submodules.transport = transport\n\n # stpl\n stpl = LiteJESD204BSTPLGenerator(jesd_settings,\n converter_data_width)\n self.submodules += stpl\n stpl_enable = Signal()\n self.specials += \\\n MultiReg(self.stpl_enable, stpl_enable)\n self.comb += \\\n If(stpl_enable,\n transport.sink.eq(stpl.source)\n ).Else(\n transport.sink.eq(self.sink)\n )\n\n links = []\n for n, (phy, lane) in enumerate(zip(phys, transport.source.flatten())):\n phy_name = \"phy{}\".format(n)\n phy_cd = phy_name + \"_tx\"\n\n # claim the phy\n setattr(self.submodules, phy_name, phy)\n\n ebuf = ElasticBuffer(len(phy.data), 4, \"sys\", phy_cd)\n setattr(self.submodules, \"ebuf{}\".format(n), ebuf)\n\n link = LiteJESD204BLinkTX(len(phy.data), jesd_settings, n)\n link = ClockDomainsRenamer(phy_cd)(link)\n links.append(link)\n self.comb += link.jsync.eq(self.jsync)\n self.submodules += link\n\n # connect data\n self.comb += [\n ebuf.din.eq(lane),\n link.sink.data.eq(ebuf.dout),\n phy.data.eq(link.source.data),\n phy.ctrl.eq(link.source.ctrl)\n ]\n\n # connect control\n self.comb += phy.transmitter.init.restart.eq(self.restart &\n \t (self.prbs_config == 0))\n\n self.specials += MultiReg(self.prbs_config,\n phy.transmitter.prbs_config,\n phy_cd)\n ready = Signal()\n self.comb += ready.eq(reduce(and_, [link.ready for link in links]))\n self.specials += MultiReg(ready, self.ready)\n\n def register_jsync(self, jsync):\n if isinstance(jsync, Signal):\n self.comb += self.jsync.eq(jsync)\n elif isinstance(jsync, Record):\n self.specials += DifferentialInput(jsync.p, jsync.n, self.jsync)\n else:\n raise ValueError\n\n\nclass LiteJESD204BCoreTXControl(Module, AutoCSR):\n def __init__(self, core):\n self.enable = CSRStorage()\n self.ready = CSRStatus()\n\n self.prbs_config = CSRStorage(4)\n self.stpl_enable = CSRStorage()\n\n self.jsync = CSRStatus()\n\n self.restart_count_clear = CSR()\n self.restart_count = CSRStatus(8)\n\n # # #\n\n # core control/status\n self.comb += [\n core.enable.eq(self.enable.storage),\n core.prbs_config.eq(self.prbs_config.storage),\n core.stpl_enable.eq(self.stpl_enable.storage),\n\n self.ready.status.eq(core.ready)\n ]\n self.specials += MultiReg(core.jsync, self.jsync.status)\n\n # restart monitoring\n\n # restart is a slow signal so we simply pass it to sys_clk and\n # count rising edges\n restart = Signal()\n restart_d = Signal()\n restart_count = Signal(8)\n self.specials += MultiReg(core.restart, restart)\n self.sync += \\\n If(self.restart_count_clear.re,\n restart_count.eq(0)\n ).Elif(restart & ~restart_d,\n # don't overflow when max is reached\n If(restart_count != (2**8-1),\n restart_count.eq(restart_count + 1)\n )\n )\n self.comb += self.restart_count.status.eq(restart_count)\n\n\n","sub_path":"litejesd204b/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":4742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"423079883","text":"#!/usr/bin/env python3\n\"\"\"\n Hyperparameter Tuning project\n\"\"\"\nimport numpy as np\n\n\nclass GaussianProcess():\n \"\"\" represents a noiseless 1D Gaussian process \"\"\"\n\n def __init__(self, X_init, Y_init, l=1, sigma_f=1):\n \"\"\"\n X_init ndarray (t, 1) inputs already sampled with black-box function\n Y_init ndarray (t, 1) outputs of black-box function for\n each input in X_init\n t is the number of initial samples\n l is the length parameter for the kernel\n sigma_f is the standard deviation given to the output of\n the black-box function\n Sets the public instance attributes X, Y, l, and sigma_f corresponding\n to the respective constructor inputs\n Sets the public instance attribute K, representing the current\n covariance kernel matrix for the Gaussian process\n \"\"\"\n self.X = X_init\n self.Y = Y_init\n self.l = l\n self.sigma_f = sigma_f\n self.K = self.kernel(X_init, X_init)\n\n def kernel(self, X1, X2):\n \"\"\" calculates the covariance kernel matrix between two matrices\n X1 ndarray (m, 1)\n X2 ndarray (n, 1)\n the kernel should use the Radial Basis Function (RBF)\n Returns: the covariance kernel matrix as ndarray (m, n)\n \"\"\"\n sqdist = np.sum(X1 ** 2, 1).reshape(-1, 1) +\\\n np.sum(X2 ** 2, 1) - 2 * np.dot(X1, X2.T)\n return self.sigma_f**2 * np.exp(-0.5 / self.l**2 * sqdist)\n\n def predict(self, X_s):\n \"\"\" predicts the mean and standard deviation of\n points in a Gaussian process\n X_s ndarray (s, 1) containing all of the points whose mean and\n standard deviation should be calculated\n s is the number of sample points\n Returns: mu, sigma\n mu ndarray (s,) containing the mean for each point\n in X_s, respectively\n sigma ndarray (s,) containing the variance for each point\n in X_s, respectively\n \"\"\"\n # print(X_s.shape)\n # print(X_s)\n K = self.K\n K_s = self.kernel(self.X, X_s)\n K_ss = self.kernel(X_s, X_s)\n K_inv = np.linalg.inv(K)\n # mu = np.mean(X_s, axis=1)\n sigma = np.var(X_s)\n # x_inv = np.linalg.inv(X_s)\n mu = K_s.T.dot(K_inv).dot(self.Y)\n sigma = K_ss - K_s.T.dot(K_inv).dot(K_s)\n return mu.flatten(), np.diag(sigma)\n\n def update(self, X_new, Y_new):\n \"\"\" updates a Gaussian Process\n X_new ndarray (1,) represents the new sample point\n Y_new ndarray (1,) represents the new sample function value\n Updates the public instance attributes X, Y, and K\n \"\"\"\n self.X = np.append(self.X, X_new[:, np.newaxis], axis=0)\n # print(self.X.shape)\n self.Y = np.append(self.Y, Y_new[:, np.newaxis], axis=0)\n # print('yshape',self.Y.shape)\n self.K = self.kernel(self.X, self.X)\n","sub_path":"unsupervised_learning/0x03-hyperparameter_tuning/2-gp.py","file_name":"2-gp.py","file_ext":"py","file_size_in_byte":3000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"171447327","text":"import os\nimport argparse\nimport numpy as np\nimport random\nfrom tqdm import tqdm\nfrom PIL import Image\nimport cv2\n\n# TensorFlow ライブラリ\nimport tensorflow as tf\nfrom tensorflow.python.client import device_lib\n\n# 自作モジュール\nfrom data.dataset import load_dataset\nfrom models.networks import TempleteNetworks\nfrom utils.utils import set_random_seed, numerical_sort\nfrom utils.utils import sava_image_tsr\nfrom utils.utils import board_add_image, board_add_images\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--exper_name\", default=\"debug\", help=\"実験名\")\n parser.add_argument(\"--dataset_dir\", type=str, default=\"datasets/templete_dataset\")\n parser.add_argument(\"--results_dir\", type=str, default=\"results\")\n parser.add_argument('--save_checkpoints_dir', type=str, default=\"checkpoints/\", help=\"モデルの保存ディレクトリ\")\n parser.add_argument('--load_checkpoints_dir', type=str, default=\"\", help=\"モデルの読み込みファイルのディレクトリ\")\n parser.add_argument('--tensorboard_dir', type=str, default=\"tensorboard\", help=\"TensorBoard のディレクトリ\")\n parser.add_argument(\"--n_epoches\", type=int, default=100, help=\"エポック数\") \n parser.add_argument('--batch_size', type=int, default=4, help=\"バッチサイズ\")\n parser.add_argument('--image_height', type=int, default=128, help=\"入力画像の高さ(pixel単位)\")\n parser.add_argument('--image_width', type=int, default=128, help=\"入力画像の幅(pixel単位)\")\n parser.add_argument('--lr', type=float, default=0.0002, help=\"学習率\")\n parser.add_argument('--beta1', type=float, default=0.5, help=\"学習率の減衰率\")\n parser.add_argument('--beta2', type=float, default=0.999, help=\"学習率の減衰率\")\n parser.add_argument(\"--n_diaplay_step\", type=int, default=100,)\n parser.add_argument('--n_display_valid_step', type=int, default=500, help=\"valid データの tensorboard への表示間隔\")\n parser.add_argument(\"--n_save_epoches\", type=int, default=10,)\n parser.add_argument(\"--val_rate\", type=float, default=0.01)\n parser.add_argument('--n_display_valid', type=int, default=8, help=\"valid データの tensorboard への表示数\")\n parser.add_argument('--data_augument', action='store_true')\n parser.add_argument('--use_tfrecord', action='store_true')\n parser.add_argument(\"--seed\", type=int, default=71)\n #parser.add_argument('--device', choices=['cpu', 'gpu'], default=\"gpu\", help=\"使用デバイス (CPU or GPU)\")\n parser.add_argument('--n_workers', type=int, default=4, help=\"CPUの並列化数(0 で並列化なし)\")\n parser.add_argument('--gpu_ids', type=str, default=\"0\", help=\"使用GPU (例 : 0,1,2,3)\")\n parser.add_argument('--use_amp', action='store_true')\n #parser.add_argument('--use_tfdbg', choices=['not_use', 'cli', 'gui'], default=\"not_use\", help=\"tfdbg使用フラグ\")\n #parser.add_argument('--detect_inf_or_nan', action='store_true')\n parser.add_argument('--use_tensorboard_debugger', action='store_true', help=\"TensorBoard Debugger V2 有効化フラグ()\")\n parser.add_argument('--debug', action='store_true')\n args = parser.parse_args()\n if( args.debug ):\n str_gpu_ids = args.gpu_ids.split(',')\n args.gpu_ids = []\n for str_gpu_id in str_gpu_ids:\n id = int(str_gpu_id)\n if id >= 0:\n args.gpu_ids.append(id)\n\n for key, value in vars(args).items():\n print('%s: %s' % (str(key), str(value)))\n\n print( \"tensoflow version : \", tf.__version__ )\n print( \"device_lib.list_local_devices() : \", device_lib.list_local_devices() )\n\n if( int(tf.__version__.split(\".\")[0]) < 2 and int(tf.__version__.split(\".\")[1]) < 3 and args.use_tensorboard_debugger ):\n print( \"TensorBoard Debugger V2 is not supported in tensoflow version {}\".format(tf.__version__) )\n\n # 出力フォルダの作成\n if not os.path.isdir(args.results_dir):\n os.mkdir(args.results_dir)\n if not os.path.isdir( os.path.join(args.results_dir, args.exper_name) ):\n os.mkdir(os.path.join(args.results_dir, args.exper_name))\n if not( os.path.exists(args.save_checkpoints_dir) ):\n os.mkdir(args.save_checkpoints_dir)\n if not( os.path.exists(os.path.join(args.save_checkpoints_dir, args.exper_name)) ):\n os.mkdir( os.path.join(args.save_checkpoints_dir, args.exper_name) )\n if not os.path.isdir(\"_debug\"):\n os.mkdir(\"_debug\")\n\n #================================\n # tensorflow 設定\n #================================\n # Eager execution mode / tensorflow 2.x では明示不要\n #tf.enable_eager_execution() \n \n # デバイスの配置ログを有効化\n \"\"\"\n if( args.debug ):\n tf.debugging.set_log_device_placement(True)\n \"\"\"\n\n # TensorBoard Debugger V2 有効化\n if( args.use_tensorboard_debugger ):\n tf.debugging.experimental.enable_dump_debug_info(\n dump_root = os.path.join(args.tensorboard_dir, args.exper_name + \"_debug\"),\n tensor_debug_mode = \"FULL_HEALTH\",\n circular_buffer_size = -1\n )\n\n # AMP 有効化\n if( args.use_amp ):\n os.environ['TF_ENABLE_AUTO_MIXED_PRECISION'] = '1'\n\n # seed 値の固定\n set_random_seed(args.seed)\n\n # tensorboard 出力\n board_train = tf.summary.create_file_writer( logdir = os.path.join(args.tensorboard_dir, args.exper_name) )\n board_valid = tf.summary.create_file_writer( logdir = os.path.join(args.tensorboard_dir, args.exper_name + \"_valid\") )\n board_train.set_as_default()\n #board_valid.set_as_default()\n\n # multi gpu\n mirrored_strategy = tf.distribute.MirroredStrategy()\n #mirrored_strategy = tf.distribute.MirroredStrategy(tf.config.experimental.list_physical_devices(\"GPU\"))\n\n #================================\n # データセットの読み込み\n #================================ \n # 学習用データセットとテスト用データセットの設定\n ds_train, ds_valid, n_trains, n_valids = load_dataset( args.dataset_dir, image_height = args.image_height, image_width = args.image_width, n_channels = 3, batch_size = args.batch_size, use_tfrecord = args.use_tfrecord, seed = args.seed )\n with mirrored_strategy.scope():\n ds_train = mirrored_strategy.experimental_distribute_dataset(ds_train)\n ds_valid = mirrored_strategy.experimental_distribute_dataset(ds_valid)\n\n if( args.debug ):\n print( \"n_trains : \", n_trains )\n print( \"n_valids : \", n_valids )\n print( \"ds_train : \", ds_train )\n print( \"ds_valid : \", ds_valid )\n\n #================================\n # モデルの構造を定義する。\n #================================\n with mirrored_strategy.scope():\n model_G = TempleteNetworks(out_dim=3)\n model_G( tf.zeros([args.batch_size, args.image_height, args.image_width, 3], dtype=tf.float32) )\n if( args.debug ):\n model_G.summary()\n\n #================================\n # モデルの読み込み\n #================================\n if( args.load_checkpoints_dir ):\n ckpt_state = tf.train.get_checkpoint_state(args.load_checkpoints_dir)\n model_G.load_weights(ckpt_state.model_checkpoint_path)\n print( \"load checkpoints in `{}`.\".format(ckpt_state.model_checkpoint_path) )\n init_epoch = int(ckpt_state.model_checkpoint_path.split(\"-\")[-1])\n step = init_epoch # @\n iters = step * args.batch_size # @\n else:\n init_epoch = 0\n step = 0\n iters = 0\n\n #================================\n # optimizer の設定\n #================================\n with mirrored_strategy.scope():\n optimizer_G = tf.keras.optimizers.Adam( learning_rate=args.lr, beta_1=args.beta1, beta_2=args.beta2 )\n\n #================================\n # AMP 有効化\n #================================\n if( args.use_amp ):\n with mirrored_strategy.scope():\n policy = tf.keras.mixed_precision.experimental.Policy('mixed_float16')\n tf.keras.mixed_precision.experimental.set_policy(policy)\n optimizer_G = tf.keras.mixed_precision.experimental.LossScaleOptimizer(optimizer_G, loss_scale='dynamic')\n\n #================================\n # loss 関数の設定\n #================================\n with mirrored_strategy.scope():\n # tf.keras.losses.Reduction.NONE : loss の reduction をなくす\n # reduction をなくした分は、カスタムトレーニング処理の mirrored_strategy.reduce() で reduction する\n loss_fn = tf.keras.losses.MeanSquaredError(reduction=tf.keras.losses.Reduction.NONE)\n\n def calc_loss_multi_gpus(target, output, batch_size):\n losse_gpus = loss_fn(target, output)\n # GPU 度の loss 値の合計を global_batch_size で除算\n loss = tf.nn.compute_average_loss(losse_gpus, global_batch_size=batch_size)\n #loss = tf.reduce_sum(losse_gpus, keepdims=True) * (1. / 128.0)\n return loss\n\n #================================\n # tfdbg でのデバッグ処理有効化\n #================================\n \"\"\"\n if( args.use_tfdbg == \"cli\" ):\n from tensorflow.python import debug as tf_debug\n #import tensorflow.python.keras.backend as K\n import tensorflow.keras.backend as K\n sess = K.get_session()\n #sess.run( tf.global_variables_initializer() )\n sess = tf_debug.LocalCLIDebugWrapperSession(sess)\n if( args.detect_inf_or_nan ):\n from tensorflow.python.debug.lib.debug_data import has_inf_or_nan\n sess.add_tensor_filter('has_inf_or_nan', has_inf_or_nan)\n elif( args.use_tfdbg == \"gui\" ):\n # [ToDo] AttributeError: module 'tensorflow.python.debug' has no attribute 'TensorBoardDebugWrapperSession' のエラー解消\n from tensorflow.python import debug as tf_debug\n from tensorflow.python import debug as tf_debug\n #import tensorflow.python.keras.backend as K\n import tensorflow.keras.backend as K\n sess = K.get_session()\n tf_debug.TensorBoardDebugWrapperSession(sess, \"localhost:6007\")\n if( args.detect_inf_or_nan ):\n from tensorflow.python.debug.lib.debug_data import has_inf_or_nan\n sess.add_tensor_filter('has_inf_or_nan', has_inf_or_nan)\n \"\"\"\n\n #================================\n # モデルの学習\n #================================ \n print(\"Starting Training Loop...\")\n n_prints = 1\n for epoch in tqdm( range(args.n_epoches+init_epoch), desc = \"epoches\", initial=init_epoch ):\n # ミニバッチデータの取り出し\n for image_s, image_t in ds_train:\n image_s_gpus = image_s.values\n image_t_gpus = image_t.values\n if( args.debug and n_prints > 0 ):\n for gpu_id in range(len(args.gpu_ids)):\n print(\"[image_s_gpus[{}]] shape={}, dtype={}, min={}, max={}\".format(gpu_id, image_s_gpus[gpu_id].shape, image_s_gpus[gpu_id].dtype, np.min(image_s_gpus[gpu_id].numpy()), np.max(image_s_gpus[gpu_id].numpy())))\n print(\"[image_t_gpus[{}]] shape={}, dtype={}, min={}, max={}\".format(gpu_id, image_t_gpus[gpu_id].shape, image_t_gpus[gpu_id].dtype, np.min(image_t_gpus[gpu_id].numpy()), np.max(image_t_gpus[gpu_id].numpy())))\n sava_image_tsr( image_s_gpus[gpu_id][0], \"_debug/image_s_gpu{}.png\".format(gpu_id) )\n sava_image_tsr( image_t_gpus[gpu_id][0], \"_debug/image_t_gpu{}.png\".format(gpu_id) )\n\n #====================================================\n # 学習処理\n #====================================================\n #@tf.function # 高速化のためのデコレーター\n def train_on_batch(input, target, batch_size):\n # スコープ以下を自動微分計算\n with tf.GradientTape() as tape:\n # モデルの forward 処理\n output = model_G(input, training=True)\n\n # 損失関数の計算\n loss_G = calc_loss_multi_gpus(target, output, batch_size)\n\n # モデルの更新処理\n grads = tape.gradient(loss_G, model_G.trainable_weights)\n optimizer_G.apply_gradients(zip(grads, model_G.trainable_weights))\n return output, loss_G\n\n #@tf.function # 高速化のためのデコレーター\n def train_on_batch_multi_gpus(input, target, batch_size):\n output_gpus, loss_gpus = mirrored_strategy.run(train_on_batch, args=(input, target, batch_size))\n output = tf.concat(output_gpus.values, axis=0)\n # loss_fn の reduction をなくした分は、mirrored_strategy.reduce で reduction する\n loss_G = mirrored_strategy.reduce(tf.distribute.ReduceOp.SUM, loss_gpus, axis=None)\n #loss_G = mirrored_strategy.reduce(tf.distribute.ReduceOp.MEAN, loss_gpus, axis=None)\n return output,loss_G\n\n output, loss_G = train_on_batch_multi_gpus( image_s, image_t, args.batch_size )\n if( args.debug and n_prints > 0 ):\n print(\"[output] shape={}, dtype={}, min={}, max={}\".format(output.shape, output.dtype, np.min(output), np.max(output)))\n\n #====================================================\n # 学習過程の表示\n #====================================================\n if( step == 0 or ( step % args.n_diaplay_step == 0 ) ):\n # lr\n pass\n\n # loss\n print( \"epoch={}, step={}, loss_G={:.5f}\".format(epoch, step, loss_G) )\n with board_train.as_default():\n tf.summary.scalar(\"G/loss_G\", loss_G, step=step+1, description=\"生成器の全loss\")\n\n # visual images\n with board_train.as_default():\n visuals = [\n [ tf.concat(image_s_gpus, axis=0), tf.concat(image_t_gpus, axis=0), output ],\n ]\n board_add_images(board_train, 'train', visuals, step+1 )\n\n #====================================================\n # valid データでの処理\n #====================================================\n if( step != 0 and ( step % args.n_display_valid_step == 0 ) ):\n loss_G_total = 0\n n_valid_loop = 0 \n for i, (image_s, image_t) in enumerate(ds_valid):\n image_s_gpus = image_s.values\n image_t_gpus = image_t.values\n\n #---------------------------------\n # 推論処理\n #---------------------------------\n #@tf.function\n def eval_on_batch(input, target, batch_size=1):\n # スコープ以下を自動微分計算\n with tf.GradientTape() as tape:\n # モデルの forward 処理\n output = model_G(input, training=False)\n\n # 損失関数の計算\n loss_G = calc_loss_multi_gpus(target, output, batch_size)\n\n return output, loss_G\n\n #@tf.function\n def eval_on_batch_multi_gpus(input, target, batch_size=1):\n output_gpus, loss_gpus = mirrored_strategy.run(eval_on_batch, args=(input, target, batch_size))\n output = tf.concat(output_gpus.values, axis=0)\n loss_G = mirrored_strategy.reduce(tf.distribute.ReduceOp.SUM, loss_gpus, axis=None) \n #loss_G = mirrored_strategy.reduce(tf.distribute.ReduceOp.MEAN, loss_gpus, axis=None) \n return output, loss_G\n\n output, loss_G = eval_on_batch_multi_gpus( image_s, image_t, 1 )\n loss_G_total += loss_G\n\n #---------------------------------\n # 生成画像表示\n #---------------------------------\n if( i <= args.n_display_valid ):\n with board_valid.as_default():\n visuals = [\n [ tf.concat(image_s_gpus, axis=0), tf.concat(image_t_gpus, axis=0), output ],\n ]\n board_add_images(board_train, 'valid/{}'.format(i), visuals, step+1 )\n\n n_valid_loop += 1\n\n # loss 値表示\n with board_valid.as_default():\n tf.summary.scalar(\"G/loss_G\", loss_G_total/n_valid_loop, step=step+1, description=\"生成器の全loss\")\n\n step += 1\n iters += args.batch_size\n n_prints -= 1\n\n #====================================================\n # モデルの保存\n #====================================================\n if( epoch % args.n_save_epoches == 0 ):\n model_G.save_weights( os.path.join(args.save_checkpoints_dir, args.exper_name, \"model_G-{}\".format(epoch)) )\n\n print(\"Finished Training Loop.\")\n","sub_path":"templetes_tf2.x/train_multi_gpu.py","file_name":"train_multi_gpu.py","file_ext":"py","file_size_in_byte":17487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"457175145","text":"from django.contrib.auth.models import User\n\nfrom game.models import Game, GamePlayed, PaymentDetail\nfrom accounts.models import Profile\n\nfrom rest_framework import serializers\n\nclass ProfileSerializer(serializers.ModelSerializer):\n \"\"\"Serializes profiles\n \"\"\"\n class Meta:\n model = Profile\n fields = ('nickname', 'description', 'image')\n ordering_fields = ('nickname', 'description')\n\nclass UserSerializer(serializers.ModelSerializer):\n \"\"\"Serializes users.\n \n This serializer includes a profile field for the user, serialized with\n ProfileSerializer-\n \"\"\"\n class Meta:\n model = User\n fields = ('username', 'profile')\n ordering_fields = ('username',)\n \n profile = ProfileSerializer(many=False, read_only=True)\n\nclass GameSerializer(serializers.ModelSerializer):\n \"\"\"Serializes game instances. Used by the games view of the rest api.\n \n Includes pretty much all information about a game, including statistics.\n \"\"\"\n \n class Meta:\n model = Game\n fields = (\n 'title',\n 'developer',\n 'url',\n 'price',\n 'description',\n 'gameimage',\n 'gamethumb',\n 'viewcount',\n 'sellcount',\n 'upload_date',\n 'popularity',\n 'average_rating',\n 'revenue',\n )\n ordering_fields=(\n 'title',\n 'price',\n 'description',\n 'viewcount',\n 'sellcount',\n 'upload_date',\n 'popularity',\n 'revenue'\n )\n \n developer = serializers.SlugRelatedField(\n slug_field='username',\n many=False,\n read_only=True\n )\n average_rating = serializers.FloatField(source='get_rating', read_only=True)\n\nclass GamePlayedSerializer(serializers.ModelSerializer):\n \"\"\"Serializes GamePlayed instances for the user-games view. Includes the title of\n the game.\n \"\"\"\n class Meta:\n model = GamePlayed\n fields = ('game', 'gameScore', 'rating')\n ordering_fields = ('gameScore', 'rating')\n \n game = serializers.SlugRelatedField(\n slug_field='title',\n many=False,\n read_only=True\n )\n\nclass UserGamePlayedSerializer(serializers.ModelSerializer):\n \"\"\"Serializes GamePlayed instances for the game-buyers view. Includes the username\n of the buyer.\n \"\"\"\n class Meta:\n model = GamePlayed\n fields = ('user', 'gameScore', 'rating')\n ordering_fields = ('gameScore', 'rating')\n \n user = serializers.SlugRelatedField(\n slug_field='username',\n many=False,\n read_only=True\n )\n","sub_path":"api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"27057831","text":"# Copyright 2018 NOKIA\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# 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, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom neutron._i18n import _\nfrom neutron.db import securitygroups_db as sg_db\nfrom neutron.extensions import securitygroup as ext_sg\nfrom neutron_lib.callbacks import events\nfrom neutron_lib.callbacks import registry\nfrom neutron_lib.callbacks import resources\nfrom neutron_lib import exceptions as n_exc\nfrom neutron_lib.plugins import directory\nfrom oslo_log import helpers as log_helpers\nfrom oslo_log import log as logging\nfrom oslo_utils import excutils\nfrom oslo_utils import uuidutils\n\nfrom nuage_neutron.plugins.common import base_plugin\nfrom nuage_neutron.plugins.common import constants\nfrom nuage_neutron.plugins.common import nuagedb\nfrom nuage_neutron.plugins.common import utils as nuage_utils\nfrom nuage_neutron.vsdclient.common import cms_id_helper\nfrom nuage_neutron.vsdclient.common import constants as nuage_constants\nfrom nuage_neutron.vsdclient import restproxy\n\nLOG = logging.getLogger(__name__)\n\n\nclass NuageSecurityGroup(base_plugin.BaseNuagePlugin,\n sg_db.SecurityGroupDbMixin):\n def __init__(self):\n super(NuageSecurityGroup, self).__init__()\n self._l2_plugin = None\n self.stateful = None\n self.sg_name_before_update = None\n\n @property\n def core_plugin(self):\n if self._l2_plugin is None:\n self._l2_plugin = directory.get_plugin()\n return self._l2_plugin\n\n def register(self):\n self.nuage_callbacks.subscribe(self.post_port_create,\n resources.PORT, constants.AFTER_CREATE)\n self.nuage_callbacks.subscribe(self.post_port_update,\n resources.PORT, constants.AFTER_UPDATE)\n self.nuage_callbacks.subscribe(self.post_port_delete,\n resources.PORT, constants.AFTER_DELETE)\n\n @registry.receives(resources.SECURITY_GROUP, [events.BEFORE_CREATE])\n @nuage_utils.handle_nuage_api_errorcode\n @log_helpers.log_method_call\n def pre_create_security_group(self, resource, event, trigger, payload):\n session = payload.context.session\n sg = payload.desired_state\n stateful = sg.get('stateful', True)\n payload.request_body['security_group']['id'] = sg_id = \\\n sg.get('id') or uuidutils.generate_uuid()\n if not stateful:\n nuagedb.set_nuage_sg_parameter(session, sg_id, 'STATEFUL', '0')\n\n @registry.receives(resources.SECURITY_GROUP, [events.BEFORE_DELETE])\n @nuage_utils.handle_nuage_api_errorcode\n @log_helpers.log_method_call\n def pre_delete_security_group(self, resource, event, trigger, payload):\n self.vsdclient.delete_nuage_secgroup(payload.resource_id)\n\n @registry.receives(resources.SECURITY_GROUP, [events.PRECOMMIT_DELETE])\n @nuage_utils.handle_nuage_api_errorcode\n @log_helpers.log_method_call\n def delete_security_group_precommit(self, resource, event, trigger,\n **kwargs):\n session = kwargs['context'].session\n sg_id = kwargs['security_group_id']\n nuagedb.delete_nuage_sg_parameter(session, sg_id, 'STATEFUL')\n\n @registry.receives(resources.SECURITY_GROUP, [events.BEFORE_UPDATE])\n @nuage_utils.handle_nuage_api_errorcode\n @log_helpers.log_method_call\n def pre_update_security_group(self, resource, event, trigger, **kwargs):\n context = kwargs['context']\n sg_id = kwargs['security_group_id']\n current = self.get_security_group(context, sg_id)\n self.sg_name_before_update = current['name']\n sg = kwargs['security_group']\n if 'stateful' in sg and sg['stateful'] != current['stateful']:\n self._check_for_security_group_in_use(context, sg_id)\n self.stateful = kwargs['security_group']['stateful']\n\n @registry.receives(resources.SECURITY_GROUP, [events.PRECOMMIT_UPDATE])\n @nuage_utils.handle_nuage_api_errorcode\n @log_helpers.log_method_call\n def update_security_group_precommit(self, resource, event, trigger,\n payload):\n session = payload.context.session\n sg_id = payload.resource_id\n sg = payload.desired_state\n if self.stateful is not None:\n self._update_stateful_parameter(session, sg_id, self.stateful)\n sg['stateful'] = self.stateful\n self.stateful = None\n\n @registry.receives(resources.SECURITY_GROUP, [events.AFTER_UPDATE])\n @nuage_utils.handle_nuage_api_errorcode\n @log_helpers.log_method_call\n def update_security_group_postcommit(self, resource, event, trigger,\n **kwargs):\n sg_id = kwargs['security_group_id']\n if ('name' in kwargs['security_group'] and\n kwargs['security_group']['name'] !=\n kwargs['original_security_group']['name']):\n data = {\n 'description': kwargs['security_group']['name']\n }\n nuage_policygroups = (\n self.vsdclient.get_sg_policygroup_by_external_id(sg_id))\n for nuage_policy in nuage_policygroups:\n self.vsdclient.update_policygroup(nuage_policy['ID'],\n data)\n nuage_hw_policygroups = (\n self.vsdclient.get_sg_policygroup_by_external_id(\n sg_id,\n sg_type=constants.HARDWARE))\n for nuage_policy in nuage_hw_policygroups:\n self.vsdclient.update_policy_group(nuage_policy['ID'],\n data)\n\n @registry.receives(resources.SECURITY_GROUP_RULE, [events.BEFORE_CREATE])\n @nuage_utils.handle_nuage_api_errorcode\n @log_helpers.log_method_call\n def pre_create_security_group_rule(self, resource, event, trigger,\n **kwargs):\n self.vsdclient.validate_nuage_sg_rule_definition(\n kwargs['security_group_rule'])\n\n @registry.receives(resources.SECURITY_GROUP_RULE, [events.AFTER_CREATE])\n @nuage_utils.handle_nuage_api_errorcode\n @log_helpers.log_method_call\n def post_create_security_group_rule(self, resource, event, trigger,\n **kwargs):\n remote_sg = None\n context = kwargs['context']\n sg_rule = kwargs['security_group_rule']\n sg_id = sg_rule['security_group_id']\n\n if sg_rule.get('remote_group_id'):\n remote_sg = self.core_plugin.get_security_group(\n context, sg_rule.get('remote_group_id'))\n try:\n nuage_policygroup = self.vsdclient.get_sg_policygroup_mapping(\n sg_id)\n if nuage_policygroup:\n sg_params = {\n 'sg_id': sg_id,\n 'neutron_sg_rule': sg_rule,\n 'policygroup': nuage_policygroup,\n }\n if remote_sg:\n sg_params['remote_group_name'] = remote_sg['name']\n self.vsdclient.create_nuage_sgrule(sg_params)\n except Exception:\n with excutils.save_and_reraise_exception():\n self.core_plugin.delete_security_group_rule(context,\n sg_rule['id'])\n\n @registry.receives(resources.SECURITY_GROUP_RULE, [events.BEFORE_DELETE])\n @nuage_utils.handle_nuage_api_errorcode\n @log_helpers.log_method_call\n def pre_delete_security_group_rule(self, resource, event, trigger,\n **kwargs):\n context = kwargs['context']\n id = kwargs['security_group_rule_id']\n local_sg_rule = self.core_plugin.get_security_group_rule(context, id)\n self.vsdclient.delete_nuage_sgrule([local_sg_rule])\n\n def post_port_create(self, resource, event, trigger, context, port, vport,\n subnet_mapping, **kwargs):\n if self._is_vsd_mgd(subnet_mapping):\n return\n\n if port[ext_sg.SECURITYGROUPS]:\n vsd_subnet = self._find_vsd_subnet(context, subnet_mapping)\n if vsd_subnet:\n self._process_port_security_group(context,\n port,\n vport,\n port[ext_sg.SECURITYGROUPS],\n vsd_subnet,\n subnet_mapping)\n\n def post_port_update(self, resource, event, trigger, context, port,\n original_port, vport, rollbacks, subnet_mapping,\n **kwargs):\n if self._is_vsd_mgd(subnet_mapping):\n return\n new_sg = (set(port.get(ext_sg.SECURITYGROUPS)) if\n port.get(ext_sg.SECURITYGROUPS) else set())\n if (port.get(ext_sg.SECURITYGROUPS) !=\n original_port.get(ext_sg.SECURITYGROUPS)):\n vsd_subnet = self.vsdclient.get_nuage_subnet_by_mapping(\n subnet_mapping)\n self._process_port_security_group(context,\n port,\n vport,\n new_sg,\n vsd_subnet,\n subnet_mapping)\n rollbacks.append((self._process_port_security_group,\n [context, port, vport,\n original_port[ext_sg.SECURITYGROUPS],\n vsd_subnet, subnet_mapping],\n {}))\n deleted_sg_ids = (set(original_port[ext_sg.SECURITYGROUPS]) -\n set(port[ext_sg.SECURITYGROUPS]))\n self.vsdclient.check_unused_policygroups(deleted_sg_ids)\n\n def post_port_delete(self, resource, event, trigger, **kwargs):\n port = kwargs['port']\n subnet_mapping = kwargs['subnet_mapping']\n if self._is_vsd_mgd(subnet_mapping):\n return\n\n securitygroups = port.get(ext_sg.SECURITYGROUPS, [])\n successful = False\n attempt = 1\n while not successful:\n try:\n self.vsdclient.check_unused_policygroups(securitygroups)\n successful = True\n except restproxy.RESTProxyError as e:\n msg = str(e).lower()\n if (e.code not in (404, 409) and 'policygroup' not in msg and\n 'policy group' not in msg):\n raise\n elif attempt < 3:\n attempt += 1\n else:\n raise\n\n @log_helpers.log_method_call\n def _process_port_security_group(self, context, port, vport, sg_ids,\n vsd_subnet, subnet_mapping):\n if not port.get('fixed_ips'):\n return\n\n self._check_security_groups_per_port_limit(sg_ids)\n\n successful = False\n attempt = 1\n max_attempts = 4\n while not successful:\n try:\n policygroup_ids = []\n for sg_id in sg_ids:\n vsd_policygroup = self._find_or_create_policygroup(\n context, sg_id, vsd_subnet)\n policygroup_ids.append(vsd_policygroup['ID'])\n\n self.vsdclient.update_vport_policygroups(vport['ID'],\n policygroup_ids)\n successful = True\n except restproxy.RESTProxyError as e:\n LOG.debug(\"Policy group retry %s times.\", attempt)\n msg = str(e).lower()\n if (e.code not in (404, 409) and 'policygroup' not in msg and\n 'policy group' not in msg):\n raise\n elif e.vsd_code in constants.NOT_SUPPORTED_NW_MACRO:\n msg = str(e).split(': ', 1)\n if len(msg) > 1:\n e.msg = ('{}: Non supported remote CIDR in security'\n ' rule: {}'.format(msg[0], msg[1]))\n raise\n elif attempt < max_attempts:\n attempt += 1\n if e.vsd_code == nuage_constants.PG_VPORT_DOMAIN_CONFLICT:\n vsd_subnet = self._find_vsd_subnet(context,\n subnet_mapping)\n if not vsd_subnet:\n return\n else:\n LOG.debug(\"Retry failed %s times.\", max_attempts)\n raise\n\n def _find_or_create_policygroup(self, context, security_group_id,\n vsd_subnet):\n external_id = cms_id_helper.get_vsd_external_id(security_group_id)\n policygroups = self.get_policygroups(external_id, vsd_subnet)\n if len(policygroups) > 1:\n msg = _(\"Found multiple policygroups with externalID %s\")\n raise n_exc.Conflict(msg=msg % external_id)\n elif len(policygroups) == 1:\n return policygroups[0]\n else:\n return self._create_policygroup(context, security_group_id,\n vsd_subnet)\n\n def get_policygroups(self, external_id, vsd_subnet):\n if vsd_subnet['type'] == constants.L2DOMAIN:\n policygroups = self.vsdclient.get_nuage_l2domain_policy_groups(\n vsd_subnet['ID'],\n externalID=external_id)\n else:\n domain_id = self.vsdclient.get_router_by_domain_subnet_id(\n vsd_subnet['ID'])\n policygroups = self.vsdclient.get_nuage_domain_policy_groups(\n domain_id,\n externalID=external_id)\n return policygroups\n\n def _create_policygroup(self, context, security_group_id, vsd_subnet):\n security_group = self.core_plugin.get_security_group(context,\n security_group_id)\n # pop rules, make empty policygroup first\n security_group_rules = security_group.pop('security_group_rules')\n try:\n policy_group = self.vsdclient.create_security_group(vsd_subnet,\n security_group)\n except restproxy.RESTProxyError as e:\n if e.vsd_code == restproxy.REST_PG_EXISTS_ERR_CODE:\n # PG is being concurrently created\n external_id = cms_id_helper.get_vsd_external_id(\n security_group_id)\n policygroups = self.get_policygroups(external_id, vsd_subnet)\n return policygroups[0]\n else:\n raise\n # Before creating rules, we might have to make other policygroups first\n # if the rule uses remote_group_id to have rule related to other PG.\n with nuage_utils.rollback() as on_exc:\n on_exc(self.vsdclient.delete_nuage_policy_group,\n policy_group['ID'])\n remote_sg_ids = []\n for rule in security_group_rules:\n remote_sg_id = rule.get('remote_group_id')\n if remote_sg_id and remote_sg_id not in remote_sg_ids:\n remote_sg_ids.append(remote_sg_id)\n self._find_or_create_policygroup(context,\n remote_sg_id,\n vsd_subnet)\n\n self.vsdclient.create_security_group_rules(policy_group,\n security_group_rules)\n return policy_group\n\n def _check_for_security_group_in_use(self, context, sg_id):\n filters = {'security_group_id': [sg_id]}\n bound_ports = self._get_port_security_group_bindings(context, filters)\n if bound_ports:\n raise ext_sg.SecurityGroupInUse(id=sg_id)\n\n @staticmethod\n def _update_stateful_parameter(session, sg_id, stateful):\n if stateful:\n nuagedb.delete_nuage_sg_parameter(session, sg_id, 'STATEFUL')\n else:\n nuagedb.set_nuage_sg_parameter(session, sg_id, 'STATEFUL', '0')\n","sub_path":"nuage_neutron/plugins/nuage_ml2/securitygroup.py","file_name":"securitygroup.py","file_ext":"py","file_size_in_byte":16897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"156426579","text":"import argparse\nimport ipaddress\nimport os\nimport requests\nimport sys\n\n\nPROVIDER_URL = 'https://api.ipify.org'\nIP_FILE = 'ip.db'\n\n\ndef fetch_ip():\n return requests.get(PROVIDER_URL).text\n\n\ndef check_ip(ip):\n save_ip(ip)\n print('oko')\n\n\ndef load_ip():\n with open(IP_FILE) as f:\n return f.read()\n\n\ndef save_ip(ip):\n with open(IP_FILE, 'w') as f:\n f.write(ip)\n\n\ndef is_new_ip(new, old):\n return new == old\n\n\ndef print_ip(ip):\n print(ip)\n\n\ndef create_argument_parser():\n parser = argparse.ArgumentParser()\n p_or_c = parser.add_mutually_exclusive_group()\n p_or_c.add_argument('-p', '--print', action='store_true',\n help='Fetch ip and print to stdout')\n p_or_c.add_argument('-c', '--check', action='store_true',\n help='Check if ip has changed since last check')\n return parser\n\n\ndef main(args=None):\n parser = create_argument_parser()\n ip = None\n if args is None:\n args = sys.argv[1:]\n args = parser.parse_args(args)\n if args.print:\n ip = fetch_ip()\n print_ip(ip)\n elif args.check:\n ip = fetch_ip()\n check_ip(ip)\n else:\n parser.print_help()\n\nif __name__ == '__main__':\n main()\n","sub_path":"trackmyip.py","file_name":"trackmyip.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"125012440","text":"\"\"\"\nCopyright © Prof. Anurag Srivastava, Gowtham Kandaperumal, Linli Jia, and Dr. Sanjeev Pannala.\nNo image or information should be reproduced, transmitted, or copied without the prior agreement with Prof. Srivastava.\n\"\"\"\n\nimport csv\nimport numpy as np\nfrom collections import defaultdict\nfrom AWR_py_function import *\nimport networkx as nx\nfrom networkx import linalg\nfrom networkx import algorithms\nfrom networkx import *\nimport scipy as sp\nimport statistics as stat\nimport math\nimport matplotlib.pyplot as plt\n\nfilename = r'resiliency_withstand_jan13\\LAslice_2019.csv'\nmy_dict = defaultdict(list)\n\nwith open(filename, 'r') as csv_file:\n csv_reader = csv.DictReader(csv_file)\n for line in csv_reader:\n for key, value in line.items():\n my_dict[key].append(value)\n\ndata = list(my_dict.items())\neventdata = np.array(data)\n# convert read file to Lists\n\nnodefile = r\"C:\\Users\\rocki\\Documents\\ASWork\\Visual Studio Workspace\\Radiance-CEC\\RadianceProject\\cec-extra-files\\Radiance_RTRMT\\resiliency_withstand_jan13\\Scenario Files\\Case0\\node-file-case0.csv\"\nedgefile = r\"C:\\Users\\rocki\\Documents\\ASWork\\Visual Studio Workspace\\Radiance-CEC\\RadianceProject\\cec-extra-files\\Radiance_RTRMT\\resiliency_withstand_jan13\\Scenario Files\\Case0\\edge-file-case0.csv\"\n\n\nload_LA = eventdata.tolist()[1][1]\nload_MT = eventdata.tolist()[2][1]\nload_NT = eventdata.tolist()[3][1]\nload_13m = eventdata.tolist()[4][1]\nOrca_Dlevel = eventdata.tolist()[5][1]\nOrca_DSL = eventdata.tolist()[6][1]\nnum_crit = eventdata.tolist()[7][1]\nscenario_selector = 0\nresilience_withstand = []\nCaseName = 'Case' + str(scenario_selector)\n\n# case 0\nSOC = 1\nORCA_load_level = 1\nWL_HBC = 70\nWL_PC = 70\n\nA, nodename, nodedata, edgedata, prioritynodes, G = loadbasecase_func(\n nodefile, edgefile)\n\nG2 = G.copy()\nadj2 = A\nnodes2 = nodename\nnodedata2 = nodedata\nload_LA_max = str(max(list(map(float, load_LA))))\nload_MT_max = str(max(list(map(float, load_MT))))\nload_NT_max = str(max(list(map(float, load_NT))))\nload_13m_max = str(max(list(map(float, load_13m))))\n\nfor i in range(19, 27):\n nodedata[2][1][i] = '0'\n nodedata2[2][1][i] = '0'\n\nfor i in range(30, 38):\n nodedata[2][1][i] = '0'\n nodedata2[2][1][i] = '0'\n\nfor i in range(39, 46):\n nodedata[2][1][i] = '0'\n nodedata2[2][1][i] = '0'\n# make max load\n\nnodedata[2][1][18] = load_LA_max\nnodedata[2][1][28] = load_MT_max\nnodedata[2][1][30] = load_NT_max\nnodedata[2][1][47] = load_13m_max\n# replace load data\n\nfor n in range(0, 15):\n nodedata[2][1][18] = load_LA[n]\n nodedata[2][1][28] = load_MT[n]\n nodedata[2][1][30] = load_NT[n]\n nodedata[2][1][47] = load_13m[n]\n\nif SOC == 0:\n print('Case run without Batteryu at Eyak')\nelse:\n print(\"Case {} run with Battery at Eyak with SOC = {}\".format(n, SOC*100))\n\n# change nodetable for each area load = max\n# Linli - comment\n# compute topolical factors\n\n\n# NO AHP FOR NOW\nRunAHP = 1\n\nG, Topovec = topo_extract(G, nodename)\nG2, Topovec2 = topo_extract(G2, nodes2)\n\nif Topovec == Topovec2:\n Alt1Top = 1\n Alt2Top = 1\nelse:\n Alt1 = RunAHP\n Alt1 = RunAHP\n\nP = nx.draw(G)\nplt.show()","sub_path":"RadianceProject/cec-extra-files/Radiance_RTRMT/main (2021_02_21 03_19_50 UTC).py","file_name":"main (2021_02_21 03_19_50 UTC).py","file_ext":"py","file_size_in_byte":3097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"395247743","text":"from django.utils import timezone\n\nfrom .characters.models import Character\n\n\ndef spotlight_main():\n date = timezone.now().date()\n return Character.objects.order_by(\n 'spotlight_on'\n ).filter(\n spotlight_on__lte=date\n )[:3]\n","sub_path":"charred/spotlight.py","file_name":"spotlight.py","file_ext":"py","file_size_in_byte":250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"634674519","text":"# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0\n# For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt\n\n\"\"\"Determine contexts for coverage.py\"\"\"\n\ndef should_start_context_test_function(frame):\n \"\"\"Is this frame calling a test_* function?\"\"\"\n if frame.f_code.co_name.startswith(\"test\"):\n return qualname_from_frame(frame)\n return None\n\n\ndef qualname_from_frame(frame):\n \"\"\"Get a qualified name for the code running in `frame`.\"\"\"\n co = frame.f_code\n fname = co.co_name\n if not co.co_varnames:\n return fname\n\n first_arg = co.co_varnames[0]\n if co.co_argcount and first_arg == \"self\":\n self = frame.f_locals[\"self\"]\n else:\n return fname\n\n method = getattr(self, fname, None)\n if method is None:\n return fname\n\n func = getattr(method, '__func__', None)\n if func is None:\n return fname\n\n if hasattr(func, '__qualname__'):\n qname = func.__qualname__\n else:\n for cls in self.__class__.__mro__:\n f = cls.__dict__.get(fname, None)\n if f is None:\n continue\n if f is func:\n qname = cls.__name__ + \".\" + fname\n break\n else:\n qname = fname\n return qname\n","sub_path":"coverage/context.py","file_name":"context.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"384998097","text":"import pandas as pd\nimport math\nimport matplotlib\nimport numpy as np\nimport time\nimport functions as fn\nimport scipy\nimport scipy.special as scispec\nimport scipy.optimize as scopt\n\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\nfrom mpl_toolkits.mplot3d import Axes3D\n\n\ndef laplace_approx(approx_func, approx_args, initial_param, approx_method):\n \"\"\"Finding an approximation to the integral of the function using Laplace's Approximation\"\"\"\n # Takes in a function and imposes a gaussian function over it\n # Measure uncertainty from actual value. As M increases, the approximation of the function by\n # a gaussian function gets better. Note that an unscaled gaussian function is used.\n \"\"\"Tabulate the global maximum of the function - within certain boundaries - using latin hypercube\"\"\"\n solution = scopt.minimize(fun=approx_func, arg=approx_args, x0=initial_param, method=approx_method)\n optimal_param_vect = solution.x\n optimal_func_val = solution.fun\n\n \"\"\"Generate matrix of second derivatives - The Hessian Matrix of the function\"\"\"\n return optimal_param_vect, optimal_func_val\n\n\ndef poisson_cont(k, landa): # to allow for non-integer k values\n numerator_p = np.power(landa, k) * np.exp(-1 * landa)\n denominator_p = scispec.gamma(k + 1) # Generalised factorial function for non-integer k values\n # if argument into gamma function is 0, the output is a zero as well, but 0! = 1\n p = numerator_p / denominator_p\n return p\n\n\ndef poisson_product(k_array, landa_array):\n \"\"\"Takes in 2 arrays of equal size, and takes product of poisson distributions\"\"\"\n quadrats = len(k_array) # define the number of quadrats in total\n prob_array = np.zeros(quadrats)\n\n if landa_array.size == 1:\n for i in range(len(k_array)):\n prob_array[i] = poisson_cont(k_array[i], landa_array)\n else:\n if len(k_array) == len(landa_array):\n for i in range(len(prob_array)):\n prob_array[i] = poisson_cont(k_array[i], landa_array[i])\n else:\n print('Length Mismatch')\n p_likelihood = np.prod(prob_array) # Taking combined product of distributions\n # Note output is a scalar (singular value)\n return p_likelihood # Returns the non logarithmic version.\n\n\n# Testing for kernel function matrix\ndef squared_exp_2d(sigma_exp, length_exp, x1, x2): # Only for 2-D\n # Define horizontal and vertical dimensions of covariance matrix c\n if np.array([x1.shape]).size == 1 and np.array([x2.shape]).size != 1 and x1.size == x2.shape[0]:\n rows = 1\n columns = x2.shape[1]\n elif np.array([x2.shape]).size == 1 and np.array([x1.shape]).size != 1 and x2.size == x1.shape[0]:\n rows = x1.shape[1]\n columns = 1\n elif np.array([x1.shape]).size == 1 and np.array([x2.shape]).size == 1 and x1.size == x2.size:\n rows = 1\n columns = 1\n else:\n rows = x1.shape[1]\n columns = x2.shape[1]\n\n c = np.zeros((rows, columns))\n\n for i in range(c.shape[0]):\n for j in range(c.shape[1]):\n if np.array([x1.shape]).size == 1 and np.array([x2.shape]).size != 1:\n diff = x1 - x2[:, j]\n elif np.array([x1.shape]).size != 1 and np.array([x2.shape]).size == 1:\n diff = x1[:, i] - x2\n elif np.array([x1.shape]).size == 1 and np.array([x2.shape]).size == 1:\n diff = x1 - x2\n else:\n diff = x1[:, i] - x2[:, j]\n\n euclidean = np.sqrt(np.matmul(diff, np.transpose(diff)))\n exp_power = np.exp(-1 * (euclidean ** 2) * (length_exp ** -2))\n c[i, j] = (sigma_exp ** 2) * exp_power\n\n return c # Note that this creates the covariance matrix directly\n\n\n# Try obtaining a covariance matrix - which can be used to evaluate the posterior\n# First obtain a data set\n\n\"\"\"Extract Data from csv\"\"\" # Arbitrary Point Process Data\nA = np.genfromtxt('PP_Data_2D.csv', delimiter=',') # Extract from csv using numpy\ndf = pd.read_csv('PP_Data_2D.csv') # Generates a DataFrame from csv - coal data\nx = np.ravel(df.values[0])\ny = np.ravel(df.values[1])\n\n\nfig = plt.figure()\nfig.canvas.set_window_title('Incidences and Quads')\nspacing = 1\nminorLocator = ticker.MultipleLocator(spacing)\nincidence = fig.add_subplot(111)\nincidence.scatter(x, y, color='black', marker='.', s=1)\nincidence.yaxis.set_minor_locator(minorLocator)\nincidence.xaxis.set_minor_locator(minorLocator)\nincidence.grid(which='minor')\n\nplt.show()\n\n\n\n\n\n\n","sub_path":"testbed.py","file_name":"testbed.py","file_ext":"py","file_size_in_byte":4523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"304040882","text":"from Dzien10.game import Character, Barbarian, Dice\n\nplayer = Character(20) # domyslne wartosci: (self, health = 10, strength = 5, damage = 2, armor = 5) - podwyzszamy health do 20\nenemy = Character() # domyslne wartosci: (self, health = 10, strength = 5, damage = 2, armor = 5)\nbarbarian = Barbarian()\n\nhow_many_attacks = 5\n\nprint(player)\n\nfor number_of_attacks in range(how_many_attacks):\n if player.character_state == 'Dead':\n break\n enemy.attack(player)\n\nbarbarian.attack(player)\n\n\nprint(f\"Player has armor: {player.armor} and health: {player.health}\")\n\n\n##################################################################################################################\ngame=Dice()\n\nprint(f\"Rolled with number: {game.roll()}\")","sub_path":"Dzien10/play_a_game.py","file_name":"play_a_game.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"21938364","text":"class Solution:\n def singleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n seen = {}\n for n in nums:\n try:\n seen.pop(n)\n except:\n seen[n]=1\n return seen.popitem()[0]\n\n def singleNumber1(self, nums):\n i =0\n for n in nums:\n i^=n\n return i\n\n\ns =Solution()\nprint(s.singleNumber([1,2,2]))\n","sub_path":"algorithms/136. Single Number/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"337904642","text":"from geth import DevGethProcess\nfrom populus.utils.filesystem import get_blockchains_dir\nfrom web3 import IPCProvider\nfrom web3 import Web3\n\n__all__ = ('FlaskWeb3')\n__version__ = '0.1.0'\n\ntry:\n from flask import _app_ctx_stack as stack\nexcept ImportError:\n from flask import _request_ctx_stack as stack\n\n\nclass FlaskWeb3(object):\n def __init__(self, app=None, chain_name=None, config_prefix='FLASKWEB3'):\n self.chain_name = chain_name\n self.config_prefix = config_prefix\n if app is not None:\n self.init_app(app)\n\n def init_app(self, app):\n self.chain_name = app.config.get(\n '{0}_CHAIN_NAME'.format(self.config_prefix), 'temp'\n )\n self.project_dir = app.config.get(\n '{0}_PROJECTDIR'.format(self.config_prefix), '.'\n )\n self._geth = DevGethProcess(\n chain_name=self.chain_name,\n base_dir=get_blockchains_dir(self.project_dir))\n self._geth.start()\n\n if not hasattr(app, 'extensions'):\n app.extensions = {}\n app.extensions[self.config_prefix.lower()] = self\n\n @property\n def web3(self):\n ctx = stack.top\n if ctx is not None:\n if not hasattr(ctx, 'web3'):\n ctx.web3 = Web3(IPCProvider(self._geth.ipc_path))\n return ctx.web3\n","sub_path":"flask_web3/flask_web3.py","file_name":"flask_web3.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"99133589","text":"from __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport six\nfrom docker.errors import APIError\n\nfrom compose.parallel import parallel_execute\nfrom compose.parallel import parallel_execute_iter\nfrom compose.parallel import UpstreamError\n\n\nweb = 'web'\ndb = 'db'\ndata_volume = 'data_volume'\ncache = 'cache'\n\nobjects = [web, db, data_volume, cache]\n\ndeps = {\n web: [db, cache],\n db: [data_volume],\n data_volume: [],\n cache: [],\n}\n\n\ndef get_deps(obj):\n return [(dep, None) for dep in deps[obj]]\n\n\ndef test_parallel_execute():\n results, errors = parallel_execute(\n objects=[1, 2, 3, 4, 5],\n func=lambda x: x * 2,\n get_name=six.text_type,\n msg=\"Doubling\",\n )\n\n assert sorted(results) == [2, 4, 6, 8, 10]\n assert errors == {}\n\n\ndef test_parallel_execute_with_deps():\n log = []\n\n def process(x):\n log.append(x)\n\n parallel_execute(\n objects=objects,\n func=process,\n get_name=lambda obj: obj,\n msg=\"Processing\",\n get_deps=get_deps,\n )\n\n assert sorted(log) == sorted(objects)\n\n assert log.index(data_volume) < log.index(db)\n assert log.index(db) < log.index(web)\n assert log.index(cache) < log.index(web)\n\n\ndef test_parallel_execute_with_upstream_errors():\n log = []\n\n def process(x):\n if x is data_volume:\n raise APIError(None, None, \"Something went wrong\")\n log.append(x)\n\n parallel_execute(\n objects=objects,\n func=process,\n get_name=lambda obj: obj,\n msg=\"Processing\",\n get_deps=get_deps,\n )\n\n assert log == [cache]\n\n events = [\n (obj, result, type(exception))\n for obj, result, exception\n in parallel_execute_iter(objects, process, get_deps)\n ]\n\n assert (cache, None, type(None)) in events\n assert (data_volume, None, APIError) in events\n assert (db, None, UpstreamError) in events\n assert (web, None, UpstreamError) in events\n","sub_path":"tests/unit/parallel_test.py","file_name":"parallel_test.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"226714480","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport csv\nimport numpy as np\nfrom torch.utils.data import TensorDataset, DataLoader\n\n\nwith open('testfile.csv','r') as file:\n csv_reader = csv.DictReader(file)\n data ={}\n for row in csv_reader:\n for key, value in row.items():\n data.setdefault(key, list()).append(value)\n\nfeatures = ['price','sma','rsi','macd','macdSignal','adx','Middle bband','Lower bband','Upper bband','Parabolic sar','ema']\nfeaturesList =[]\n\nfor feature in features:\n featuresList.append(data[feature])\n\n\nprices = data['price']\ntY = np.array(prices).astype(np.float)\n#print(Y.shape)\ntX = np.array(featuresList).astype(np.float)\ntX = tX.transpose()\n\ntrainExs =[]\ntrainYs = []\n\ni =0\nwhile i < 2047-21:\n tempEx = tX[i:i+12]\n tempEx = tempEx.flatten()\n tempEx = tempEx.tolist()\n trainExs.append(tempEx)\n\n i+=1\n\nj =0\nwhile j < 2047-21:\n tempY = tY[j+15:j+21]\n tempY = tempY.flatten()\n tempY = tempY.tolist()\n trainYs.append(tempY)\n j+=1\n\nprint(len(trainYs))\ntargets = torch.FloatTensor(trainYs)\ninputs = torch.FloatTensor(trainExs)\n\nclass Net(nn.Module):\n def __init__(self):\n super().__init__()\n '''\n self.l1 = nn.Linear(132,20)\n self.l2 = nn.Linear(20,15)\n self.l3 = nn.Linear(15,10)\n self.l4 = nn.Linear(10,6)\n '''\n self.l1 = nn.Linear(132,20)\n self.l2 = nn.Linear(20,6)\n\n\n def forward(self,x):\n '''\n x = F.relu(self.l1(x))\n x = F.relu(self.l2(x))\n x = F.relu(self.l3(x))\n x = F.relu(self.l4(x))\n '''\n x = F.relu(self.l1(x))\n x = F.relu(self.l2(x))\n\n return x\n\n\n#print(inputs.shape)\n\ninputMin = inputs.min(0,keepdim=True)[0]\ninputMax = inputs.max(0,keepdim=True)[0]\n#print(inputs.narrow(0,2000,2))\n\ncopyInputs= inputs\n'''\nmin max normalization\ncopyInputs -= inputMin\ncopyInputs /= inputMax - inputMin\ninputs = copyInputs\n'''\n\ncopyInputs -= torch.mean(copyInputs,dim=0)\ncopyInputs /= torch.std(copyInputs,dim=0)\ninputs = copyInputs\n\n\nnet = Net()\ntrainDS = TensorDataset(inputs,targets)\n\nbatch_size = 10\n\ntrain_dl = DataLoader(trainDS,batch_size,shuffle = False)\n\n\n\noptimizer = optim.SGD(net.parameters(), lr = 1e-5)\n\nepochs = 200\n\nlossFn = F.mse_loss\n\n\nfor epoch in range(epochs):\n for data in train_dl:\n X,y = data\n out = net(X)\n\n loss = lossFn(out,y)\n loss.backward()\n optimizer.step()\n optimizer.zero_grad()\n print('Training loss: ', lossFn(net(inputs), targets))\n\n\n\nwith open('actualtestfile.csv', 'r') as file:\n csv_reader = csv.DictReader(file)\n testdata ={}\n for row in csv_reader:\n for key, value in row.items():\n testdata.setdefault(key, list()).append(value)\n\ntestfeatures = ['price','sma','rsi','macd','macdSignal','adx','Middle bband','Lower bband','Upper bband','Parabolic sar','ema']\ntestfeaturesList =[]\n\nfor feature in testfeatures:\n testfeaturesList.append(testdata[feature])\n\n\ntestprices = testdata['price']\ntestY = np.array(testprices).astype(np.float)\n#print(Y.shape)\ntestX = np.array(testfeaturesList).astype(np.float)\ntestX = testX.transpose()\n\n\ntestXs = []\ntestYs = []\n#print(testX.shape)\nk = 20\n\nwhile k < 3127 -21:\n temp = testX[k:k+12]\n temp = temp.flatten()\n temp = temp.tolist()\n testXs.append(temp)\n k+=1\n\n\nl = 20\n\nwhile l< 3127-21:\n tempTY = testY[l+15:l+21]\n tempTY = tempTY.flatten()\n tempTY = tempTY.tolist()\n testYs.append(tempTY)\n l+=1\n\n\n\n\ntestInputs = torch.FloatTensor(testXs)\ntestTargets = torch.FloatTensor(testYs)\n\n#print(testTargets)\n\ncopyTestInputs = testInputs\n\ncopyTestInputs -= torch.mean(copyTestInputs,dim=0)\ncopyTestInputs /= torch.std(copyTestInputs,dim=0)\ntestInputs = copyTestInputs\n\n\n\ntestOutputs = net(testInputs)\n\n\n#3086 guesses\n\n\n\nprint(testOutputs)\n","sub_path":"finhubDataAndModels/linearRegression3.py","file_name":"linearRegression3.py","file_ext":"py","file_size_in_byte":3869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"243175241","text":"# python3\n# coding=\n\nimport re\nimport csv\n\n\nclass Result:\n def __init__(self, language, query_params):\n \"\"\"\n language: str: language\n query_params: dict: __dict__ of used parser\n \"\"\"\n self.results = list()\n self.N = 0\n self.lang = language\n self.query = query_params['query']\n self.params = {k: query_params[k] \\\n for k in query_params \\\n if k[0] != '_' and k not in ['page', 'query']\n }\n \n self.__header = ('index', 'text')\n self.__kwic_header = ('index', 'left', 'center', 'right')\n self.__not_allowed = '/\\\\?%*:|\"<>'\n \n def add(self, x):\n self.results.append(x)\n self.N += 1\n \n def __str__(self):\n return 'Result(query=%s, N=%s, params=%s)' \\\n % (self.query,\n self.N,\n self.params\n )\n \n __repr__ = __str__\n \n def __iter__(self):\n return iter(self.results)\n \n def __getitem__(self,key):\n return self.results[key]\n \n def __setitem__(self,key,val):\n self.results[key] = val\n\n def __delitem__(self, key):\n del self.results[key]\n \n def export_csv(self, filename=None, header=True, sep=';'):\n if filename is None:\n filename = '%s_%s_results.csv' \\\n % (self.lang,\n re.sub(self.__not_allowed, '', self.query)\n )\n \n with open(filename,'w',encoding='utf-8-sig') as f:\n writer = csv.writer(f, delimiter=sep, quotechar='\"',\n quoting=csv.QUOTE_MINIMAL, lineterminator='\\n'\n )\n \n if self.params['kwic']:\n if header:\n writer.writerow(self.__kwic_header)\n \n nLeft = self.params['nLeft'] \n nRight = self.params['nRight']\n \n if nLeft is None:\n nLeft = 10\n \n if nRight is None:\n nRight = 10\n \n for i, t in enumerate(self.results):\n writer.writerow((i + 1, *t.kwic(nLeft, nRight)))\n \n else:\n if header:\n writer.writerow(self.__header)\n \n for i, t in enumerate(self.results):\n writer.writerow((i + 1, t.text))\n \n def clear(self):\n self.results = list()\n","sub_path":"lingcorpora/result.py","file_name":"result.py","file_ext":"py","file_size_in_byte":2650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"537298970","text":"import pytest\nimport requests_mock\n\nfrom tinkoff.credit import TinkoffCredit\n\npytestmark = [pytest.mark.django_db]\n\n\n@pytest.fixture(autouse=True)\ndef _tinkoff_credentials(settings):\n settings.TINKOFF_CREDIT_SHOP_ID = '1234'\n settings.TINKOFF_CREDIT_SHOWCASE_ID = '123-45'\n settings.TINKOFF_CREDIT_DEMO_MDOE = False\n\n\n@pytest.fixture(autouse=True)\ndef _absolute_host(settings):\n settings.ABSOLUTE_HOST = 'https://tst.hst'\n settings.FRONTEND_URL = 'https://front.tst.hst'\n\n\n@pytest.fixture\ndef record(mixer):\n return mixer.blend(\n 'products.Record',\n name='Пентакли и тентакли',\n name_receipt='Предоставление доступа к записи курса «Пентакли и Тентакли»',\n )\n\n\n@pytest.fixture\ndef order(factory, user, record):\n return factory.order(user=user, item=record, price='100500')\n\n\n@pytest.fixture\ndef tinkoff(order):\n with requests_mock.Mocker() as m:\n client = TinkoffCredit(order)\n\n client.m = m\n\n yield client\n\n\n@pytest.fixture\ndef user(mixer):\n return mixer.blend('users.User', first_name='Авраам Соломонович', last_name='Пейзенгольц')\n","sub_path":"src/tinkoff/tests/credit_client/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"645123990","text":"\"\"\"Tests for database report nodes table.\"\"\"\n\nfrom datetime import datetime\n\nfrom autostorage.database.model.scenario.parse_state import ScenarioParseState\n\n\ndef test_parse_state_representation():\n \"\"\"Check parse state representation.\n\n 1. Create parse state object.\n 2. Check representation of the parse state.\n \"\"\"\n scenario_id = 1\n scenario_node_id = 1\n parse_rule_id = 1\n enabled = False\n now = datetime.utcnow()\n\n state = ScenarioParseState(\n scenario_id=scenario_id,\n scenario_node_id=scenario_node_id,\n parse_rule_id=parse_rule_id,\n enabled=enabled,\n changed=now\n )\n\n attrs = \", \".join((\n \"id={}\".format(None),\n \"scenario_id={}\".format(scenario_id),\n \"scenario_node_id={}\".format(scenario_node_id),\n \"parse_rule_id={}\".format(parse_rule_id),\n \"enabled={})\".format(enabled),\n \"changed={})\".format(now),\n ))\n assert repr(state) == \"\".format(attrs), \"Wrong representation string\"\n","sub_path":"src/tests/database/model/tables/test_scenario_parse_state.py","file_name":"test_scenario_parse_state.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"444588822","text":"import fonctions\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndonnee = pd.read_csv(\"post-32566-EIVP_KM.csv\", sep=';')\r\n\r\ntemperature=donnee['temp']\r\nhum=donnee['humidity']\r\ncarbone=donnee['co2']\r\n\r\ndate=donnee['sent_at']\r\n\r\n\r\n# print(donnee)\r\n\r\n\r\n\r\n#_______________________________________________________________________________\r\n\r\n\r\n# Date :\r\n\r\ndef separer_date_heure(date_elementaire):\r\n if len(date_elementaire)>=19:\r\n d=date_elementaire[0:10]\r\n h=date_elementaire[11:19]\r\n else:\r\n d=date_elementaire[0:10]\r\n h=[]\r\n return d,h\r\n\r\n\r\ndef separer_date(date_elementaire): # a-b-c ...\r\n d,h=separer_date_heure(date_elementaire)\r\n a=''\r\n b=''\r\n for x in d:\r\n if x!='-':\r\n a+=x\r\n if h==[]:\r\n b=0\r\n else:\r\n for y in h:\r\n if y!=':':\r\n b+=y\r\n return int(a),int(b) # [abc]\r\n\r\n\r\ndef separer_date2(date_elementaire): # a-b-c ...\r\n D=[]\r\n H=[]\r\n d,h=separer_date_heure(date_elementaire)\r\n a=''\r\n b=''\r\n for x in d:\r\n if x=='-':\r\n D.append(int(a))\r\n a=''\r\n if x!='-':\r\n a+=x\r\n D.append(int(a))\r\n for y in h:\r\n if y==':':\r\n H.append(int(b))\r\n b=''\r\n if y!=':':\r\n b+=y\r\n H.append(int(b))\r\n return D,H # [a,b,c]\r\n\r\n\r\ndef separer_date_liste(date_liste):\r\n L=[]\r\n H=[]\r\n n=len(date_liste)\r\n for k in range(n):\r\n l,h=separer_date(date_liste[k])\r\n L.append(l)\r\n H.append(h)\r\n return L,H\r\n\r\n\r\ndef separer_date_liste_num(date_liste):\r\n L=[]\r\n n=len(date_liste)\r\n for k in range(n):\r\n l,h=separer_date(date_liste[k])\r\n num=[k]\r\n num.append(l)\r\n L.append(num)\r\n return L\r\n\r\n\r\n# Agrandi donnee\r\n\r\ndate2,heure2=separer_date_liste(date)\r\ndate2\r\ndonnee['date2']=date2\r\ndonnee['heure2']=heure2\r\ndonnee.sort_values(by=['date2','heure2'],ascending=[True,True])\r\n\r\n# print(donnee)\r\n\r\n\r\ndef trier_date(L):\r\n return L\r\n\r\n\r\ndef trouver_first_date(date_elementaire):\r\n d,h=separer_date(date_elementaire)\r\n index=0\r\n while d>date2[index]:\r\n index+=1\r\n if index==len(date2):\r\n break\r\n return index\r\n\r\n\r\ndef trouver_last_date(date_elementaire):\r\n d,h=separer_date(date_elementaire)\r\n index=0\r\n while d>=date2[index]:\r\n index+=1\r\n if index==len(date2):\r\n break\r\n return index\r\n\r\n\r\n\r\n#_______________________________________________________________________________\r\n\r\n\r\n# Courbe :\r\n\r\ndef Afficher_carbone(start_date='2019-01-01',end_date='2019-02-01'):\r\n i=trouver_first_date(start_date)\r\n j=trouver_last_date(end_date)\r\n x = date[i:j]\r\n y = carbone[i:j]\r\n\r\n #plt.subplot(2, 1, 2)\r\n\r\n plt.plot(x, y, '.-')\r\n plt.xlabel('Temps')\r\n plt.ylabel('Carbone')\r\n plt.title('Evolution carbone')\r\n \r\n plt.show()\r\n return None\r\n\r\n\r\ndef Afficher_temperature(start_date='2019-01-01',end_date='2019-02-01'):\r\n x = date\r\n y = temperature\r\n\r\n #plt.subplot(2, 1, 2)\r\n\r\n plt.plot(x, y, '.-')\r\n plt.xlabel('Temps')\r\n plt.ylabel('Température')\r\n plt.title('Evolution température')\r\n \r\n plt.show()\r\n return None\r\n\r\n\r\ndef Afficher_humidite(start_date='2019-01-01',end_date='2019-02-01'):\r\n x = date\r\n y = hum\r\n\r\n #plt.subplot(2, 1, 2)\r\n\r\n plt.plot(x, y, '.-')\r\n plt.xlabel('Temps')\r\n plt.ylabel('Humidité')\r\n plt.title('Evolution humidité')\r\n \r\n plt.show()\r\n return None\r\n\r\n\r\ndef Afficher_courbe(col,start_date='2019-01-01',end_date='2019-02-01'):\r\n x = date\r\n y = col\r\n\r\n #plt.subplot(2, 1, 2)\r\n\r\n plt.plot(x, y, '.-')\r\n plt.xlabel('Temps')\r\n plt.ylabel('col')\r\n plt.title('Evolution ')\r\n \r\n plt.show()\r\n return None\r\n\r\n\r\n#____________________________________________________________\r\n\r\n\r\n# Statistique : Moyenne, mediane, variance :\r\n\r\ndef moyenne(l):\r\n moyen=0\r\n n=len(l)\r\n for x in l:\r\n moyen+=x\r\n moyen=moyen/n\r\n return moyen\r\n\r\ndef mediane(l):\r\n l=quickSort(l)\r\n mediane=0\r\n n=len(l)\r\n if n%2==0:\r\n a=l[n//2]\r\n b=l[(n//2)+1]\r\n madiane=moyenne((a,b))\r\n else:\r\n mediane=l[n//2]\r\n return mediane\r\n \r\n\r\ndef variance(l): # E(x**2)-E(x)**2\r\n Lcarree=[]\r\n var=0\r\n moyen=moyenne(l)\r\n for x in l:\r\n Lcarree.append(x**2)\r\n moyen_carree=moyenne(Lcarree)\r\n var=moyen_carree-moyen**2\r\n return var\r\n\r\n\r\ndef covariance(X,Y):\r\n n=len(X)\r\n m=len(Y)\r\n if n!=m:\r\n return None\r\n S=0\r\n x=moyenne(X)\r\n y=moyenne(Y)\r\n for i in range(n):\r\n S+=X[i]*Y[i]\r\n S=S/n\r\n covar=S-x*y\r\n return covar\r\n\r\n\r\ndef ecart_type(l):\r\n var=variance(l)\r\n return var**(1/2)\r\n\r\n\r\n#_______________________________________________________________________________\r\n\r\n# Moyenne des journée : Transformer la tableau de donnée en tableau moyenné par jour/Avec un filtre\r\n\r\n # Avec list_une_journee, on selectionne toutes les données d'une journée, \r\n # puis on en fait la moyenne sur une ligne, et on les ajoute à un nouveau tableau \r\n\r\n\r\ndef list_jour_moyen(L, first='2019-08-11', last='2019-08-25'): #L est la liste de donnée\r\n first,h=separer_date(first)\r\n last,h=separer_date(last)\r\n donnee_tous_jours=[]\r\n \r\n carbone_tous_jours,temperature_tous_jours,hum_tous_jours,bruit_tous_jours,lum_tous_jours,date_tous_jours=[],[],[],[],[],[]\r\n \r\n n=last-first\r\n \r\n for i in range(n+1):\r\n jour=first+i\r\n jour2=jour-20190800\r\n donnee_une_journee=list_une_journee(donnee,jour)\r\n \r\n carbone_tous_jours.append(moyenne(donnee_une_journee.co2))\r\n temperature_tous_jours.append(moyenne(donnee_une_journee.temp))\r\n hum_tous_jours.append(moyenne(donnee_une_journee.humidity))\r\n bruit_tous_jours.append(moyenne(donnee_une_journee.noise))\r\n lum_tous_jours.append(moyenne(donnee_une_journee.lum))\r\n date_tous_jours.append(jour2)\r\n \r\n return carbone_tous_jours, temperature_tous_jours, hum_tous_jours, bruit_tous_jours, lum_tous_jours, date_tous_jours\r\n \r\n\r\ndef Afficher_jours_moyen(first='2019-08-11', last='2019-08-25'):\r\n carbone_tous_jours, temperature_tous_jours, hum_tous_jours, bruit_tous_jours, lum_tous_jours, date_tous_jours=list_jour_moyen(donnee)\r\n \r\n x = date_tous_jours\r\n y = carbone_tous_jours\r\n y2 = temperature_tous_jours\r\n y3 = bruit_tous_jours\r\n y4 = hum_tous_jours\r\n y5 = lum_tous_jours\r\n\r\n plt.plot(x, y,color='black',label=\"carbone\")\r\n plt.plot(x, y2,color='red',label=\"température\")\r\n plt.plot(x, y3,color='green',label=\"bruit\")\r\n plt.plot(x, y4,color='cyan',label=\"humidité\")\r\n plt.plot(x, y5,color='yellow',label=\"luminosité\")\r\n \r\n plt.xlabel('Jours')\r\n plt.title('Donnée entre le '+str(date_tous_jours[0])+' et le '+str(date_tous_jours[-1])+' août 2019')\r\n plt.legend(bbox_to_anchor=(0.8, 1), loc='upper left', borderaxespad=0.)\r\n \r\n plt.show()\r\n return None\r\n\r\n\r\ndef Afficher_moyen(col,first='2019-08-11', last='2019-08-25'):\r\n carbone_tous_jours, temperature_tous_jours, hum_tous_jours, bruit_tous_jours, lum_tous_jours, date_tous_jours=list_jour_moyen(donnee)\r\n x = date_tous_jours\r\n \r\n if col=='co2':\r\n y = carbone_tous_jours\r\n plt.title('Evolution de carbone entre le '+str(date_tous_jours[0])+' et le '+str(date_tous_jours[-1])+' août 2019')\r\n elif col=='temp':\r\n y = temperature_tous_jours\r\n plt.title('Evolution de la température entre le '+str(date_tous_jours[0])+' et le '+str(date_tous_jours[-1])+' août 2019')\r\n elif col=='noise':\r\n y = bruit_tous_jours\r\n plt.title('Evolution du bruit entre le '+str(date_tous_jours[0])+' et le '+str(date_tous_jours[-1])+' août 2019')\r\n elif col=='hum':\r\n y = hum_tous_jours\r\n plt.title(\"Evolution de l'humidité entre le \"+str(date_tous_jours[0])+' et le '+str(date_tous_jours[-1])+' août 2019')\r\n elif col=='lum':\r\n y = lum_tous_jours\r\n plt.title('Evolution de la luminosité entre le '+str(date_tous_jours[0])+' et le '+str(date_tous_jours[-1])+' août 2019')\r\n else:\r\n return \"Cette colonne n'existe pas\"\r\n\r\n plt.plot(x, y)\r\n plt.xlabel('Jours')\r\n plt.show()\r\n return None\r\n\r\n\r\ndef Afficher_moyen2(*col,first='2019-08-11', last='2019-08-25'):\r\n carbone_tous_jours, temperature_tous_jours, hum_tous_jours, bruit_tous_jours, lum_tous_jours, date_tous_jours=list_jour_moyen(donnee)\r\n x = date_tous_jours\r\n \r\n for k in col:\r\n k=str(k)\r\n if k=='co2':\r\n y = carbone_tous_jours\r\n plt.plot(x, y,color='black',label=\"carbone\")\r\n elif k=='temp':\r\n y2 = temperature_tous_jours\r\n plt.plot(x, y2,color='red',label=\"température\")\r\n elif k=='noise':\r\n y3 = bruit_tous_jours\r\n plt.plot(x, y3,color='green',label=\"bruit\")\r\n elif k=='hum':\r\n y4 = hum_tous_jours\r\n plt.plot(x, y4,color='cyan',label=\"humidité\")\r\n elif k=='lum':\r\n y5 = lum_tous_jours\r\n plt.plot(x, y5,color='yellow',label=\"luminosité\")\r\n \r\n else:\r\n print(\"La colonne \"+k+\" n'existe pas\")\r\n \r\n plt.xlabel('Jours')\r\n plt.title('Donnée entre le '+str(date_tous_jours[0])+' et le '+str(date_tous_jours[-1])+' août 2019')\r\n plt.legend(bbox_to_anchor=(0.8, 1), loc='upper left', borderaxespad=0.)\r\n\r\n plt.show()\r\n return None\r\n\r\n\r\n#_______________________________________________________________________________\r\n\r\n# Une journée :\r\n\r\ndef list_une_journee(L,jour): #L est la liste de donnée\r\n donnee_une_journee=donnee[donnee.date2==jour]\r\n donnee_une_journee.sort_values(by='heure2')\r\n return donnee_une_journee\r\n\r\n\r\ndef separer_une_journee(jour):\r\n donnee_une_journee=list_une_journee(donnee,jour)\r\n \r\n carbone_journee=donnee_une_journee.co2.tolist()\r\n temperature_journee=donnee_une_journee.temp.tolist()\r\n hum_journee=donnee_une_journee.humidity.tolist()\r\n bruit_journee=donnee_une_journee.noise.tolist()\r\n lum_journee=donnee_une_journee.lum.tolist()\r\n date_journee=donnee_une_journee.date2\r\n heure_journee=donnee_une_journee.heure2\r\n \r\n return carbone_journee,temperature_journee,hum_journee,bruit_journee,lum_journee,date_journee,heure_journee\r\n\r\n \r\ndef Afficher_une_journee(jour):\r\n donnee_une_journee=list_une_journee(donnee,jour)\r\n donnee_une_journee.sort_values(by='heure2')\r\n x = donnee_une_journee.heure2\r\n y = donnee_une_journee.co2\r\n y2 = donnee_une_journee.temp\r\n y3 = donnee_une_journee.noise\r\n y4 = donnee_une_journee.humidity\r\n y5 = donnee_une_journee.lum\r\n\r\n plt.plot(x, y,color='black')\r\n plt.plot(x, y2,color='red')\r\n plt.plot(x, y3,color='green')\r\n plt.plot(x, y4,color='cyan')\r\n plt.plot(x, y5,color='yellow')\r\n \r\n plt.xlabel('Temps')\r\n plt.title('Donnée sur une journée')\r\n \r\n plt.show()\r\n return None\r\n\r\n\r\ndef Afficher_journee(jour,col=None):\r\n if col==None:\r\n return Afficher_une_journee(jour)\r\n \r\n donnee_une_journee=list_une_journee(donnee,jour)\r\n donnee_une_journee.sort_values(by='heure2')\r\n x = donnee_une_journee.heure2\r\n y = donnee_une_journee.col\r\n\r\n plt.plot(x, y)\r\n \r\n plt.xlabel('Temps')\r\n plt.title('Donnée sur une journée')\r\n \r\n plt.show()\r\n return None\r\n\r\n\r\ndef Afficher_une_journee2(jour):\r\n if len(str(jour))>8:\r\n jour,h=separer_date(str(jour))\r\n jour=int(jour)\r\n carbone_journee,temperature_journee,hum_journee,bruit_journee,lum_journee,date_journee,heure_journee=separer_une_journee(jour)\r\n jour2=jour-20190800\r\n\r\n x = [x/10000 for x in heure_journee]\r\n y = carbone_journee\r\n y2 = temperature_journee\r\n y3 = bruit_journee\r\n y4 = hum_journee\r\n y5 = lum_journee\r\n \r\n plt.plot(x, y,color='black',label=\"carbone\")\r\n plt.plot(x, y2,color='red',label=\"température\")\r\n plt.plot(x, y3,color='green',label=\"bruit\")\r\n plt.plot(x, y4,color='cyan',label=\"humidité\")\r\n plt.plot(x, y5,color='yellow',label=\"luminosité\")\r\n \r\n plt.xlabel('Temps')\r\n plt.title('Donnée de la journee du '+str(jour2)+' août 2019')\r\n plt.legend(bbox_to_anchor=(0.8, 1), loc='upper left', borderaxespad=0.)\r\n plt.show()\r\n return None\r\n\r\n\r\n\r\n#_______________________________________________________________________________\r\n\r\n# Anomalie :\r\n\r\ndef is_anomalie(col,id):\r\n C=col\r\n m=moyenne(col)\r\n if abs(col[id]-m)>ecart_type(col):\r\n return True\r\n return False\r\n\r\n\r\ndef find_anomalie_id_value(col,first,last):\r\n C=col[first:last]\r\n l=[]\r\n L=[]\r\n n=len(C)\r\n for i in range(n):\r\n if is_anomalie(col,i):\r\n l.append(i)\r\n L.append(col[i])\r\n return l,L\r\n\r\n\r\ndef Afficher_anomalie(col,start_date='2019-08-11',end_date='2019-08-25'):\r\n x = date\r\n y = col\r\n first=0\r\n last=10\r\n id,value=find_anomalie_id_value(col,first,last)\r\n plt.plot(x, y, '.-')\r\n plt.xlabel('Temps')\r\n plt.ylabel(col)\r\n plt.title('Anomalie')\r\n \r\n plt.show()\r\n return None\r\n\r\n\r\n\r\n# Dérive :\r\n\r\ndef derive(L,T): # Il faut que len(T)=len(L)>0\r\n l=[]\r\n n=len(L)\r\n for k in range(n-1):\r\n x=(float(L[k+1])-float(L[k])) # divise par T[k+1]-T[k]\r\n l.append(x)\r\n return l\r\n\r\n\r\ndef vitesse(L,T):\r\n return derive(L,T)\r\n \r\n \r\ndef acceleration(L,T):\r\n n=len(T)-1\r\n return vitesse(vitesse(L,T),T[0:n])\r\n\r\n\r\n# Définition de \"e\", la plus grande variatiion de l'acceleration possible (sans anomalie)\r\n\r\ne=100\r\n\r\n\r\ndef is_anomalie2(acc,id): # acc=acceleration(col,date2)\r\n if abs(acc[id])>e:\r\n return True\r\n return False\r\n\r\n\r\ndef anomalie_list(col,T):\r\n index=[]\r\n acc=acceleration(col,T)\r\n for i in range(len(col)-2):\r\n if is_anomalie2(acc,i):\r\n index.append(i)\r\n return index\r\n\r\n\r\ndef drop_anomalie(col,T):\r\n index=anomalie_list(col,T)\r\n donnee.drop(index)\r\n return None\r\n\r\n\r\ndef drop_anomalie_donnee(L): # L = donnee\r\n D=donnee.date2\r\n drop_anomalie(donnee.co2,D)\r\n drop_anomalie(donnee.temp,D)\r\n drop_anomalie(donnee.humidity,D)\r\n drop_anomalie(donnee.noise,D)\r\n drop_anomalie(donnee.lum,D)\r\n return None\r\n\r\n\r\ndrop_anomalie_donnee(donnee)\r\n\r\n\r\ndef Afficher_un_jour_sans_anomalie(jour):\r\n if len(str(jour))>8:\r\n jour,h=separer_date(str(jour))\r\n jour=int(jour)\r\n carbone_journee,temperature_journee,hum_journee,bruit_journee,lum_journee,date_journee,heure_journee=separer_une_journee(jour)\r\n carbone_journee=drop_anomalie(carbone_journee,date_journee)\r\n temperature_journee=drop_anomalie(temperature_journee,date_journee)\r\n hum_journee=drop_anomalie(hum_journee,date_journee)\r\n bruit_journee=drop_anomalie(bruit_journee,date_journee)\r\n lum_journee=drop_anomalie(lum_journee,date_journee)\r\n jour2=jour-20190800\r\n\r\n x = [x/10000 for x in heure_journee]\r\n y = carbone_journee\r\n y2 = temperature_journee\r\n y3 = bruit_journee\r\n y4 = hum_journee\r\n y5 = lum_journee\r\n \r\n plt.plot(x, y,color='black',label=\"carbone\")\r\n plt.plot(x, y2,color='red',label=\"température\")\r\n plt.plot(x, y3,color='green',label=\"bruit\")\r\n plt.plot(x, y4,color='cyan',label=\"humidité\")\r\n plt.plot(x, y5,color='yellow',label=\"luminosité\")\r\n \r\n plt.xlabel('Temps')\r\n plt.title('Donnée de la journee du '+str(jour2)+' août 2019')\r\n plt.legend(bbox_to_anchor=(0.8, 1), loc='upper left', borderaxespad=0.)\r\n plt.show()\r\n return None\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\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\r\n\r\n","sub_path":"projet1.py","file_name":"projet1.py","file_ext":"py","file_size_in_byte":15790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"29249579","text":"from sequana.scripts import mapping\nfrom sequana import sequana_data\nimport os\nimport pytest\nimport shutil\n\nprog = \"sequana_mapping\"\n\n\ndef test_analysis():\n file1 = sequana_data(\"Hm2_GTGAAA_L005_R1_001.fastq.gz\")\n file2 = sequana_data(\"Hm2_GTGAAA_L005_R2_001.fastq.gz\")\n reference = sequana_data(\"measles.fa\")\n\n from tempfile import TemporaryDirectory\n directory = TemporaryDirectory()\n shutil.copy(file1, directory.name)\n shutil.copy(file2, directory.name)\n shutil.copy(reference, directory.name)\n\n df = mapping.main([prog, \n '--file1', file1,\n \"--file2\", file2, \n \"--reference\", reference])\n\n\ndef test_help():\n try:\n mapping.main([prog, '--help', '1>/tmp/out', '2>/tmp/err'])\n assert False\n except SystemExit:\n pass\n else:\n raise Exception\n","sub_path":"test/scripts/test_mapping.py","file_name":"test_mapping.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"202584082","text":"file = 'a.txt'\ndata = [_.strip() for _ in open(file).readlines()]\n\n\ndef clean(input: str):\n output = []\n for index in range(len(input)):\n if input[index] == input[index-1]:\n output.append(int(input[index]))\n\n return sum(output)\n\n\nprint([clean(x) for x in data])\n","sub_path":"01/a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"527199259","text":"import os\n\nimport pandas as pd\nimport sys\nsys.path.append(\"../../../benchmarks/adult/\")\nimport load_adult_income\n\nfrom aif360.datasets import StandardDataset\n\n\ndefault_mappings = {\n 'label_maps': [{1.0: '>50K', 0.0: '<=50K'}],\n 'protected_attribute_maps': [{1.0: 'White', 0.0: 'Non-white'},\n {1.0: 'Male', 0.0: 'Female'}]\n}\n\nclass MyAdultDataset(StandardDataset):\n \"\"\"Adult Census Income Dataset.\n\n See :file:`aif360/data/raw/adult/README.md`.\n \"\"\"\n # features_to_drop=['fnlwgt']\n # categorical_features=['workclass', 'education',\n # 'marital-status', 'occupation', 'relationship',\n # 'native-country']\n # privileged_classes=[['White'], ['Male']] # Male is 1 \n # favorable_classes=['>50K', '>50K.'],\n def __init__(self, label_name='target',\n favorable_classes=[1],\n protected_attribute_names=['race', 'sex'],\n privileged_classes=[['White'], [1]], \n instance_weights_name=None,\n categorical_features=[],\n features_to_keep=[], features_to_drop=[],\n na_values=[], custom_preprocessing=None,\n metadata=default_mappings, normalized=False, permute=-1):\n \"\"\"See :obj:`StandardDataset` for a description of the arguments.\n\n Examples:\n The following will instantiate a dataset which uses the `fnlwgt`\n feature:\n\n >>> from aif360.datasets import AdultDataset\n >>> ad = AdultDataset(instance_weights_name='fnlwgt',\n ... features_to_drop=[])\n WARNING:root:Missing Data: 3620 rows removed from dataset.\n >>> not np.all(ad.instance_weights == 1.)\n True\n\n To instantiate a dataset which utilizes only numerical features and\n a single protected attribute, run:\n\n >>> single_protected = ['sex']\n >>> single_privileged = [['Male']]\n >>> ad = AdultDataset(protected_attribute_names=single_protected,\n ... privileged_classes=single_privileged,\n ... categorical_features=[],\n ... features_to_keep=['age', 'education-num'])\n >>> print(ad.feature_names)\n ['education-num', 'age', 'sex']\n >>> print(ad.label_names)\n ['income-per-year']\n\n Note: the `protected_attribute_names` and `label_name` are kept even\n if they are not explicitly given in `features_to_keep`.\n\n In some cases, it may be useful to keep track of a mapping from\n `float -> str` for protected attributes and/or labels. If our use\n case differs from the default, we can modify the mapping stored in\n `metadata`:\n\n >>> label_map = {1.0: '>50K', 0.0: '<=50K'}\n >>> protected_attribute_maps = [{1.0: 'Male', 0.0: 'Female'}]\n >>> ad = AdultDataset(protected_attribute_names=['sex'],\n ... privileged_classes=[['Male']], metadata={'label_map': label_map,\n ... 'protected_attribute_maps': protected_attribute_maps})\n\n Now this information will stay attached to the dataset and can be\n used for more descriptive visualizations.\n \"\"\"\n if normalized:\n features_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', '..', '..', 'adult-dataset', 'normalized_adult_features.csv')\n labels_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', '..', '..', 'adult-dataset', 'adult_labels.csv')\n df = pd.read_csv(features_path)\n df2 = pd.read_csv(labels_path)\n df['target'] = df2\n else:\n train_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', '..', '..', 'adult-dataset', 'adult_no_missing.csv')\n df = pd.read_csv(train_path)\n assert len(df.columns[df.isnull().any()]) == 0\n \n if permute == -1:\n df_ordered = df\n else:\n assert(permute < 20)\n ordering = load_adult_income.permutations(permute)\n x = df.to_numpy()\n x = x[ordering]\n df_ordered = pd.DataFrame(x, columns=df.columns.tolist())\n if not normalized:\n new1 = df_ordered.sort_values(by=['fnlwgt']).reset_index(drop=True)\n new2 = df.sort_values(by=['fnlwgt']).reset_index(drop=True)\n z = new1 == new2\n assert(sum([z[i].unique()[0] for i in z.columns.tolist()]) == len(z.columns.tolist())) # just a sanity check\n\n column_names = ['age','workclass','fnlwgt','education','marital-status','occupation','race','sex','capitalgain','capitalloss','hoursperweek','native-country','target']\n\n # except IOError as err:\n # print(\"IOError: {}\".format(err))\n # print(\"To use this class, please download the following files:\")\n # print(\"\\n\\thttps://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data\")\n # print(\"\\thttps://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.test\")\n # print(\"\\thttps://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.names\")\n # print(\"\\nand place them, as-is, in the folder:\")\n # print(\"\\n\\t{}\\n\".format(os.path.abspath(os.path.join(\n # os.path.abspath(__file__), '..', '..', 'data', 'raw', 'adult'))))\n # import sys\n # sys.exit(1)\n\n # df = pd.concat([test, train], ignore_index=True)\n # df = train\n\n super(MyAdultDataset, self).__init__(df=df_ordered, label_name=label_name,\n favorable_classes=favorable_classes,\n protected_attribute_names=protected_attribute_names,\n privileged_classes=privileged_classes,\n instance_weights_name=instance_weights_name,\n categorical_features=categorical_features,\n features_to_keep=features_to_keep,\n features_to_drop=features_to_drop, na_values=na_values,\n custom_preprocessing=custom_preprocessing, metadata=metadata)\n","sub_path":"aif360/datasets/my_adult.py","file_name":"my_adult.py","file_ext":"py","file_size_in_byte":6214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"128712370","text":"import tensorflow.contrib.layers as layers\nimport tensorflow as tf\n\ndef build_model(inputs, labels, num_classes, config):\n with tf.contrib.framework.arg_scope([layers.convolution2d],\n padding='SAME', activation_fn=tf.nn.relu, \n weights_initializer=layers.xavier_initializer_conv2d(),\n weights_regularizer=layers.l2_regularizer(config['weight_decay'])):\n net = layers.convolution2d(inputs=inputs, num_outputs=config['conv1_output'], kernel_size=config['conv1_kernel'], stride=config['conv1_stride'], variables_collections=['weights'], scope='conv1')\n net = layers.max_pool2d(inputs=net, kernel_size=config['pool1_kernel'], stride=config['pool1_stride'], scope='pool1')\n net = layers.convolution2d(inputs=net, num_outputs=config['conv2_output'], kernel_size=config['conv2_kernel'], stride=config['conv2_stride'], variables_collections=['weights'], scope='conv2')\n net = layers.max_pool2d(inputs=net, kernel_size=config['pool2_kernel'], stride=config['pool2_stride'], scope='pool2')\n\n with tf.contrib.framework.arg_scope([layers.fully_connected], activation_fn=tf.nn.relu,\n weights_initializer=layers.xavier_initializer(),\n weights_regularizer=layers.l2_regularizer(config['weight_decay'])):\n net = layers.flatten(net)\n fc_outputs = config['fc_outputs']\n for i in range(len(fc_outputs)):\n net = layers.fully_connected(net, fc_outputs[i], scope='fc{}'.format(i+1), variables_collections=['weights'])\n\n logits = layers.fully_connected(net, config['num_classes'], activation_fn=None, scope='logits', variables_collections=['weights'])\n per_example_loss = tf.nn.softmax_cross_entropy_with_logits(logits, labels)\n loss = tf.reduce_mean(per_example_loss) + tf.reduce_sum(tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES))\n return logits, per_example_loss, loss, tf.get_collection('weights')","sub_path":"lab2/tf_model.py","file_name":"tf_model.py","file_ext":"py","file_size_in_byte":1914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"55968506","text":"import os\n# import pymongo\nimport json\nimport random\nimport django\nfrom flask import jsonify\n\n\n\n\ndef connector():\n # cockroachstring = \"dbname='wet-dingo-838.defaultdb' user='muntaser' password='geturownpassword' host='free-tier.gcp-us-central1.cockroachlabs.cloud' port='26257'\"\n cockroachstring = os.environ.get('COCKROACHSTR')\n conn=django.connect(cockroachstring)\n return conn\n\n\n\ndef initialize(conn):\n with conn.cursor() as cur:\n cur.execute(\n \"CREATE TABLE IF NOT EXISTS users (id INT PRIMARY KEY, username STRING, email STRING, userpassword STRING, useraddress STRING, lat STRING, lon STRING, usertype STRING)\"\n )\n cur.execute(\n \"CREATE TABLE IF NOT EXISTS questions (id INT PRIMARY KEY, name STRING, text STRING, alt1 STRING, alt2 STRING, type STRING, img STRING)\"\n )\n cur.execute(\n \"CREATE TABLE IF NOT EXISTS answers (id INT PRIMARY KEY, name STRING, questionid INT, text STRING, status STRING)\"\n )\n cur.execute(\n \"CREATE TABLE IF NOT EXISTS alternates (id INT PRIMARY KEY, name STRING, questionid INT, text STRING, status STRING)\"\n )\n # cur.execute(\"UPSERT INTO users (id, email, userpassword, usertype, name) VALUES (1, 'jon@fisherman.com', 'password1', 'fisherman', 'jon stewart'), (2, 'joe@gmail.com', 'password1', 'customer', 'joe someone')\")\n # logging.debug(\"create_accounts(): status message: %s\", cur.statusmessage)\n conn.commit()\n\n\n\ndef add_questions(conn, name, text, alt1, alt2, type, img):\n with conn.cursor() as cur:\n cur.execute(\"SELECT id FROM questions\")\n # logging.debug(\"print_balances(): status message: %s\", cur.statusmessage)\n rows = cur.fetchall()\n conn.commit()\n # print(f\"Balances at {time.asctime()}:\")\n i = 1\n for row in rows:\n i = i + 1\n i = str(i)\n questionid = \"-1\"\n status = \"created\"\n cur.execute(\"UPSERT INTO questions (id, name, text, alt1, alt2, type, img) VALUES (\" + i +\", '\" + name +\"', '\" + alt1 + \"', '\" + alt2 + \"', '\" + type +\"', '\" + img +\"')\")\n # logging.debug(\"create_accounts(): status message: %s\", cur.statusmessage)\n conn.commit()\n return i\n # print (\"question added\")\n\n\t\ndef add_answers(conn, name, questionid, text, status):\n with conn.cursor() as cur:\n cur.execute(\"SELECT id FROM answers\")\n # logging.debug(\"print_balances(): status message: %s\", cur.statusmessage)\n rows = cur.fetchall()\n conn.commit()\n # print(f\"Balances at {time.asctime()}:\")\n i = 1\n for row in rows:\n i = i + 1\n i = str(i)\n questionid = \"-1\"\n status = \"created\"\n cur.execute(\"UPSERT INTO answers (id, name, questionid, text, status) VALUES (\" + i +\", '\" + name +\"', '\" + questionid + \"', '\" + text + \"', '\" + status +\"')\")\n # logging.debug(\"create_accounts(): status message: %s\", cur.statusmessage)\n conn.commit()\n return i\n # print (\"question added\")\n\t\n\n\t\ndef add_alternates(conn, name, questionid, text, status):\n with conn.cursor() as cur:\n cur.execute(\"SELECT id FROM alternates\")\n # logging.debug(\"print_balances(): status message: %s\", cur.statusmessage)\n rows = cur.fetchall()\n conn.commit()\n # print(f\"Balances at {time.asctime()}:\")\n i = 1\n for row in rows:\n i = i + 1\n i = str(i)\n questionid = \"-1\"\n status = \"created\"\n cur.execute(\"UPSERT INTO alternates (id, name, questionid, text, status) VALUES (\" + i +\", '\" + name +\"', '\" + questionid + \"', '\" + text + \"', '\" + status +\"')\")\n # logging.debug(\"create_accounts(): status message: %s\", cur.statusmessage)\n conn.commit()\n return i\n # print (\"question added\")\t\n\t\n\t\n\n\n\n\n\n\ndef add_users(conn, uname, pw, utype, uemail, lat, lon, uaddress):\n with conn.cursor() as cur:\n cur.execute(\"SELECT id FROM users\")\n # logging.debug(\"print_balances(): status message: %s\", cur.statusmessage)\n rows = cur.fetchall()\n conn.commit()\n # print(f\"Balances at {time.asctime()}:\")\n i = 1\n for row in rows:\n i = i + 1\n i = str(i)\n \n cur.execute(\"UPSERT INTO users (id, email, userpassword, usertype, username, lat, lon, useraddress) VALUES (\" + i +\", '\" + uemail + \"', '\" + pw + \"', '\" + utype +\"', '\" + uname + \"', '\" + lat +\"', '\" + lon +\"', '\" + uaddress +\"')\")\n # logging.debug(\"create_accounts(): status message: %s\", cur.statusmessage)\n conn.commit()\n return i\n # print (\"user added\")\n\n\ndef login(conn, uemail, pw):\n with conn.cursor() as cur:\n cur.execute(\"SELECT id, email, userpassword, usertype, username, lat, lon, useraddress FROM users\")\n # logging.debug(\"print_balances(): status message: %s\", cur.statusmessage)\n rows = cur.fetchall()\n conn.commit()\n # print(f\"Balances at {time.asctime()}:\")\n for row in rows:\n # print(row)\n # print (type(row))\n if row[1] == uemail and row[2] == pw:\n # print (\"found\")\n return True, row[0], row[3], row[4], row[5], row[6], row[7]\n return False, 'none', 'none', '-1', '-1', '-1', '-1', '-1', '-1' \n\n\ndef getuserbyid(conn, uid):\n with conn.cursor() as cur:\n cur.execute(\"SELECT id, email, userpassword, usertype, username, lat, lon, useraddress FROM users\")\n # logging.debug(\"print_balances(): status message: %s\", cur.statusmessage)\n rows = cur.fetchall()\n conn.commit()\n # print(f\"Balances at {time.asctime()}:\")\n for row in rows:\n # print(row)\n # print (type(row))\n if row[0] == int(uid):\n # print (\"found\")\n return True, row[0], row[1], row[3], row[4], row[5], row[6], row[7]\n return False, 'none', 'none', '-1', '-1', '-1', '-1', '-1', '-1' , '-1'\n\n\n\n\n\ndef delete_users(conn):\n with conn.cursor() as cur:\n cur.execute(\"DELETE FROM defaultdb.users\")\n # logging.debug(\"delete_accounts(): status message: %s\", cur.statusmessage)\n conn.commit()\n with conn.cursor() as cur:\n cur.execute(\"DROP TABLE users\")\n # logging.debug(\"delete_accounts(): status message: %s\", cur.statusmessage)\n conn.commit()\n\n print (\"users table deleted\")\n\n\ndef purgedb(conn):\n with conn.cursor() as cur:\n cur.execute(\"DELETE FROM defaultdb.users\")\n # logging.debug(\"delete_accounts(): status message: %s\", cur.statusmessage)\n conn.commit()\n with conn.cursor() as cur:\n cur.execute(\"DROP TABLE users\")\n # logging.debug(\"delete_accounts(): status message: %s\", cur.statusmessage)\n conn.commit()\n\n print (\"users table deleted\")\n\n\n\ndef dummy(request):\n\n\n summarytext = \"Kinetic energy is the energy an object has because of its motion. To accelerate an object, we must apply a force. Applying a force requires us to do work. After work has been done, energy has been transferred to the object, and the object will be moving with a new constant speed. The energy transferred is known as kinetic energy, and it depends on the mass and speed achieved.Kinetic energy can be transferred between objects and transformed into other kinds of energy.\"\n\n\n \"\"\"Responds to any HTTP request.\n Args:\n request (flask.Request): HTTP request object.\n Returns:\n The response text or any set of values that can be turned into a\n Response object using\n `make_response `.\n \"\"\"\n if request.method == 'OPTIONS':\n # Allows GET requests from origin https://mydomain.com with\n # Authorization header\n headers = {\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'POST',\n 'Access-Control-Allow-Headers': '*',\n 'Access-Control-Max-Age': '3600',\n 'Access-Control-Allow-Credentials': 'true'\n }\n return ('', 204, headers)\n\n # Set CORS headers for main requests\n headers = {\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Credentials': 'true'\n }\n\n request_json = request.get_json()\n conn = connector()\n initialize(conn)\n\n retjson = {}\n\n action = request_json['action']\n\n if action == 'getallquestions':\n qna = {}\n questions = ['here is a sample question, how are you?', 'here is another sample question, what are you?', 'Why is the Principle of the Conservation of Momentum useful?', \"Energy isn't always conserved in the form of what?\"]\n answers = ['here is the first sample answer, good', 'here is the second sample answer, i am groot', 'it means that you can tell what is going to happen after a collision before it has taken place', 'kinetic energy' ]\n alternatives = [[],[],[],['renewable', 'solar', 'hydrogen']]\n\n# [{'answer': 'it means that you can tell what is going to happen after a collision before it has taken place',\n# 'question': 'Why is the Principle of the Conservation of Momentum useful?'},\n# {'alternatives': ['renewable', 'solar', 'hydrogen'],\n# 'answer': 'kinetic energy',\n# 'question': \"Energy isn't always conserved in the form of what?\"}]\n\n qna['questions'] = questions\n qna['answers'] = answers\n qna['alternatives'] = alternatives\n\n return jsonify(qna)\n \n\n if action == 'getsummary':\n summ = {}\n\n summ['summary'] = summarytext\n\n\n return jsonify(summ)\n\n\n\n\n if action == \"createuser\" :\n uname = request_json['name']\n pw = request_json['password']\n utype = request_json['type']\n uaddress = request_json['address']\n lat = request_json['lat']\n lon = request_json['lon']\n uemail = request_json['email']\n\n pid = add_users(conn, uname, pw, utype, uemail, lat, lon, uaddress)\n\n retjson['status'] = \"successfully added\"\n retjson['id'] = pid\n\n return json.dumps(retjson)\n\n if action == \"createquestion\" :\n name = request_json['name']\n text = request_json['text']\n alt1 = request_json['alt1']\n alt2 = request_json['alt2']\n type = request_json['type']\n img = request_json['img']\n\n tid = add_tasks(conn, name, text, alt1, alt2, type, img)\n \n \n\n retjson['status'] = \"successfully added\"\n retjson['id'] = tid\n\n return json.dumps(retjson)\n\n\t\t\n if action == \"createanswer\" :\n name = request_json['name']\n text = request_json['text']\n questionid = request_json['qid']\n status = request_json['status']\n\n tid = add_answers(conn, name, qid, text, status)\n \n \n\n retjson['status'] = \"successfully added\"\n retjson['id'] = tid\n\n return json.dumps(retjson)\n\n\n if action == \"createalternate\" :\n name = request_json['name']\n text = request_json['text']\n questionid = request_json['qid']\n status = request_json['status']\n\n tid = add_answers(conn, name, qid, text, status)\n \n \n\n retjson['status'] = \"successfully added\"\n retjson['id'] = tid\n\n return json.dumps(retjson)\n\n\n \n\n if action == 'login':\n uemail = request_json['email']\n pw = request_json['password']\n\n res = login(conn, uemail, pw)\n\n retjson['status'] = str(res[0])\n retjson['id'] = str(res[1])\n retjson['type'] = str(res[2])\n retjson['name'] = str(res[3])\n retjson['lat'] = str(res[4])\n retjson['lon'] = str(res[5])\n retjson['address'] = str(res[6])\n \n\n return json.dumps(retjson)\n\n\n\n if action == 'getuserbyid':\n uid = request_json['uid']\n\n res = getuserbyid(conn, uid)\n\n retjson['status'] = str(res[0])\n retjson['id'] = str(res[1])\n retjson['email'] = str(res[2])\n retjson['type'] = str(res[3])\n retjson['name'] = str(res[4])\n retjson['lat'] = str(res[5])\n retjson['lon'] = str(res[6])\n retjson['address'] = str(res[7])\n \n\n return json.dumps(retjson)\n\n\n retstr = \"action not done\"\n\n if request.args and 'message' in request.args:\n return request.args.get('message')\n elif request_json and 'message' in request_json:\n return request_json['message']\n else:\n return retstr\n","sub_path":"databackend.py","file_name":"databackend.py","file_ext":"py","file_size_in_byte":12459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"412108913","text":"import matplotlib.pyplot as plt\n\napplePrice=[10,20,30,40]\nprint(type(applePrice))\ngooglePrice=[60,70,80,90]\nYear=[2015,2016,2017,2018]\nplt.plot(Year,applePrice,'k',\n Year,googlePrice,'g')\n# plt.plot(Year,googlePrice)\nplt.xlabel='Year'\nplt.ylabel='Price'\n# plt.axis([(min(Year)-10), max(Year),( min(applePrice)-10), max(googlePrice)])\nplt.grid(True)\nplt.plot();\nplt.show()\n","sub_path":"Module-5/SamplePlot.py","file_name":"SamplePlot.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"106067764","text":"import filecmp\nimport pathlib\nfrom typing import Union\nimport pandas as pd\n\n\ndef concat_data(\n path: Union[str, pathlib.Path],\n):\n if not isinstance(path, pathlib.Path):\n path = pathlib.Path(path)\n\n full_data = []\n\n for file in path.iterdir():\n data = pd.read_csv(file)\n same_day = pd.to_datetime(data['created']).dt.date == pd.to_datetime(data['applicable_date']).dt.date\n full_data.append(data[same_day])\n\n full_data = pd.concat(full_data)\n\n data_to_save = pd.DataFrame(full_data, columns=['created', 'min_temp', 'the_temp', 'max_temp', 'air_pressure', 'humidity', 'visibility', 'wind_direction_compass', 'wind_direction', 'wind_speed'])\n data_to_save.rename({'the_temp': 'temp'}, inplace=True, axis='columns')\n data_to_save['created'] = data_to_save['created'].apply(lambda x: x[0:16])\n data_to_save.sort_values('created', inplace=True)\n data_to_save.to_csv(f'{path}.csv', index=False)\n\n\nif __name__ == '__main__':\n concat_data('weather_data/523920_2017_03')\n assert filecmp.cmp(\n 'expected_523920_2017_03.csv',\n 'weather_data/523920_2017_03.csv'\n )\n","sub_path":"lab_10/tasks/task_3.py","file_name":"task_3.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"370953605","text":"from sklearn.grid_search import GridSearchCV\nfrom sklearn.svm import SVC\nfrom sklearn.tree import DecisionTreeClassifier\nimport matplotlib.pyplot as plt\nfrom sklearn.learning_curve import learning_curve, validation_curve\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import MinMaxScaler, StandardScaler\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.decomposition import PCA\nimport Machine_Learning.CommonFunctions.commonvariables as common\nfrom sklearn.cross_validation import train_test_split,StratifiedKFold,cross_val_score\nimport numpy as np\nfrom scipy import interp\nfrom sklearn.metrics import roc_curve, auc , roc_auc_score, accuracy_score\n\nx=common.x_breast\ny=common.y_breast\n\n\n\n## create a pipiline to exuete the Data Preporocessing and classification model\npipeline_lr = Pipeline([('scl',StandardScaler()),('pca',PCA(n_components=2)),(('clf',LogisticRegression(penalty='l2', random_state=0,C=10))) ])\n\n\n## partiion the data into traning and test\nx_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=1)\n\nx_train_2=x_train[:,[4,14]]\n\n## Cross Validation\ncv=StratifiedKFold(y_train,n_folds=3,random_state=1)\n\n## Create a figure\nfig = plt.figure(figsize=(7,5))\n\n\nmean_tpr=0\nmean_fpr=np.linspace(0,1,100)\nall_tpr=[]\n\nfor i, (train,test) in enumerate(cv):\n print (\"i= {} max_train= {} max_test {}\".format(i,max(train),max(test)))\n #print (\"train {} test{}\".format(train,test))\n print (x_train[train])\n import sys; sys.exit()\n\n## for each fold excute the train and test and calculate true positive, false postive rate.\nfor i, (train,test) in enumerate(cv):\n probas = pipeline_lr.fit(x_train_2[train],y_train[train]).predict_proba(x_train_2[test])\n try:\n fpr,tpr,threshold = roc_curve(y_train[test],probas[:,1],pos_label=1)\n except Exception:\n pass\n mean_tpr+=interp(mean_fpr,fpr,tpr)\n mean_tpr[0]=0.0\n roc_auc=auc(fpr,tpr)\n plt.plot(fpr, tpr,lw=1,label='ROC fold %d (area = %0.2f)' % (i+1,roc_auc))\n\nplt.plot([0,1],[0,1],linestyle='--',color=(0.6,0.6,0.6,0.6),label='Random Guessing')\nmean_tpr /= len(cv)\nmean_tpr[-1]=1.0\nmean_auc = auc(mean_fpr,mean_tpr)\nplt.plot(mean_fpr,mean_tpr,'k--',label='mean ROC (area =%0.2f)' % mean_auc, lw=2 )\nplt.plot([0,0,1],[0,1,1],lw=2,linestyle=':',color='black',label='perfect performance')\nplt.xlim([-0.05,1.05])\nplt.ylim([-0.05,1.05])\nplt.xlabel('false postive rate')\nplt.ylabel('true postive rate')\nplt.title('Receiver Operating Characteristic')\nplt.legend(loc=\"lower right\")\nplt.show()\n\n\npipeline_lr =pipeline_lr.fit(x_train_2,y_train)\n\ny_pred2 = pipeline_lr.predict(x_test[:,[4,14]])\n\nprint('ROC AUC : %.3f' % roc_auc_score(y_true=y_test,y_score=y_pred2))\nprint ('Accuracy : %0.3f' % accuracy_score(y_true=y_test,y_pred=y_pred2))\n","sub_path":"Machine_Learning/6 - Model Evaluation(Best Practices)/Plot Receiver Operating Characteristics (ROC).py","file_name":"Plot Receiver Operating Characteristics (ROC).py","file_ext":"py","file_size_in_byte":2799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"547807221","text":"#/Users/leclercq/miniconda/bin/python\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as mpl\n\nimport aplpy\n\nfig = mpl.figure(figsize=(14,7))\n\nf1 = aplpy.FITSFigure('N4_polarised_intensity.fits', figure=fig)\n\nf1.tick_labels.set_font(size='x-small')\nf1.axis_labels.set_font(size='small')\nf1.show_colorscale(cmap='afmhot')\nf1.add_colorbar()\nf1.colorbar.set_axis_label_text('brightness [K]')\nf1.show_rectangles(0,32,1000,1000)\nf1.show_rectangles(1000,32,1000,1000)\nf1.show_rectangles(2000,32,1000,1000)\nf1.show_rectangles(3000,32,1000,1000)\nf1.show_rectangles(4000,32,1000,1000)\n\n## f2 = aplpy.FITSFigure('S2rm0.fits', figure=fig,\n## subplot=[0.1, 0.4, 0.9, 0.3])\n\n## f2.tick_labels.set_font(size='x-small')\n## f2.axis_labels.set_font(size='small')\n## f2.show_colorscale(cmap='seismic',vmin=-150,vmax=150)\n## f2.add_colorbar()\n## f2.colorbar.set_axis_label_text('RM [rad/m^2]')\n\n## f3 = aplpy.FITSFigure('N4rm0.fits', figure=fig,\n## subplot=[0.1, 0.1, 0.9, 0.3])\n\n## f3.tick_labels.set_font(size='x-small')\n## f3.axis_labels.set_font(size='small')\n## f3.show_colorscale(cmap='seismic',vmin=-150,vmax=150)\n## f3.add_colorbar()\n## f3.colorbar.set_axis_label_text('RM [rad/m^2]')\n\n## f1.axis_labels.hide_x()\n## f1.tick_labels.hide_x()\n\n## f2.axis_labels.hide_x()\n## f2.tick_labels.hide_x()\n\nfig.savefig('n4pol_withchunks.pdf', bbox_inches='tight')\n","sub_path":"rm/aplpypol.py","file_name":"aplpypol.py","file_ext":"py","file_size_in_byte":1403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"285799056","text":"import pygame\nfrom Constants import *\n\ndef between(a, mn, mx):\n if a >= mn and a <= mx:\n return True\n else: return False\n\ndef intersects(one, two):\n\n if one.bottom <= two.bottom and one.bottom > two.top and one.right > two.left and one.right <= two.right:\n return True \n elif one.bottom <= two.bottom and one.bottom > two.top and one.left >= two.left and one.left < two.right:\n return True\n elif one.top < two.bottom and one.top >= two.top and one.left >= two.left and one.left < two.right:\n return True\n elif one.top < two.bottom and one.top >= two.top and one.right > two.left and one.right <= two.right:\n return True\n else: return False\n\nclass Camera():\n def __init__(self, screen, win_width, win_height):\n self.width = win_width // SCALE\n self.height = win_height // SCALE\n self.x = 0\n self.y = 0\n self.screen = screen\n self.surface = pygame.Surface((self.width, self.height))\n\n self.top = self.y\n self.bottom = self.y + self.height - 1\n self.left = self.x\n self.right = self.x + self.width - 1\n\n def update(self, hero_x, hero_y, width, height):\n\n self.width = width // SCALE\n self.height = height // SCALE\n\n self.x = hero_x - self.width / 2\n self.y = hero_y - self.height / 2\n\n self.top = self.y\n self.bottom = self.y + self.height - 1\n self.left = self.x\n self.right = self.x + self.width - 1\n\n if self.bottom > TOTAL_LEVEL_HEIGHT: \n self.y = TOTAL_LEVEL_HEIGHT - self.height\n\n self.surface.fill((170, 252, 249))\n\n def apply(self, element):\n if intersects(element, self):\n x = element.x - self.x\n y = element.y - self.y\n self.surface.blit(element.img, (x, y))\n\n def render(self):\n srf = pygame.transform.scale(self.surface, (SCREEN_WIDTH, SCREEN_HEIGHT))\n self.screen.blit(srf, (0, 0))\n\nclass Hero():\n\n def __init__(self, camera, game):\n self.camera = camera\n self.game = game\n\n self.img = HERO\n self.x = 150\n self.y = 70\n\n self.height = self.img.get_height()\n self.width = self.img.get_width()\n\n self.top = self.y\n self.bottom = self.y + self.height - 1\n self.left = self.x\n self.right = self.x + self.width - 1\n\n self.bottom_blocks = []\n self.top_blocks = []\n self.right_blocks = []\n self.left_blocks = []\n\n self.onGround = False\n\n self.yvel = 0\n self.xvel = 0\n\n self.jump_power = 0.8\n self.speed = 0.25\n self.gravity_force = 0.035\n\n def handle_event(self, event_type, key):\n if event_type == pygame.KEYDOWN:\n if key == pygame.K_RIGHT:\n self.xvel = self.speed\n elif key == pygame.K_LEFT:\n self.xvel = -self.speed\n elif key == pygame.K_UP:\n if self.onGround:\n self.onGround = False\n self.yvel = -self.jump_power\n\n elif event_type == pygame.KEYUP:\n if key == pygame.K_RIGHT and self.xvel > 0:\n self.xvel = 0\n elif key == pygame.K_LEFT and self.xvel < 0:\n self.xvel = 0\n\n def select_blocks(self, platforms):\n self.bottom_blocks = []\n self.top_blocks = []\n self.right_blocks = []\n self.left_blocks = []\n\n\n for p in platforms:\n\n if between(p.top, self.top, self.bottom) or between(p.bottom, self.top, self.bottom):\n if p.right <= self.left + 5 and p.right > self.left - self.width // 2:\n self.left_blocks.append(p)\n elif p.left >= self.right - 5 and p.left < self.right + self.width // 2:\n self.right_blocks.append(p)\n\n for p in platforms:\n denied = False\n\n for b in self.left_blocks:\n if b.x == p.x:\n denied = True\n break\n\n for b in self.right_blocks:\n if b.x == p.x:\n denied = True\n break \n\n if between(p.left, self.left, self.right) or between(p.right, self.left, self.right):\n if p.bottom <= self.top and p.bottom > self.top - self.height // 3:\n if not denied:\n self.top_blocks.append(p)\n elif p.top >= self.bottom and p.top < self.bottom + self.height // 3:\n if not denied:\n self.bottom_blocks.append(p)\n\n\n def check_collision(self, xvel, yvel, platforms):\n\n if self.bottom_blocks == []:\n self.onGround = False\n\n if self.bottom_blocks != [] and yvel > 0:\n \n self.y = self.bottom_blocks[0].top - self.height\n self.onGround = True\n self.yvel = 0\n\n if self.top_blocks != [] and yvel < 0:\n \n self.y = self.top_blocks[0].bottom\n self.yvel = 0\n\n if self.right_blocks != [] and xvel > 0:\n \n self.x = self.right_blocks[0].left - self.width + 1\n\n if self.left_blocks != [] and xvel < 0:\n \n self.x = self.left_blocks[0].right\n\n\n def update(self, platforms, dt):\n\n if self.y > 800:\n self.y = 50\n\n if not self.onGround:\n self.yvel += self.gravity_force\n\n\n self.x += self.xvel * dt\n\n self.left = self.x\n self.right = self.x + self.width - 1\n\n self.select_blocks(platforms)\n self.check_collision(self.xvel, 0, platforms)\n\n self.y += self.yvel * dt\n\n self.top = self.y\n self.bottom = self.y + self.height - 1\n\n self.check_collision(0, self.yvel, platforms)\n\n if COLOR_BORDER_BLOCKS:\n for block in self.bottom_blocks:\n block.img = RED\n\n for block in self.right_blocks:\n block.img = RED\n\n for block in self.left_blocks:\n block.img = RED\n\n for block in self.top_blocks:\n block.img = RED\n \n\n def render(self):\n self.camera.apply(self)","sub_path":"Objects.py","file_name":"Objects.py","file_ext":"py","file_size_in_byte":6222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"92920866","text":"import xml.etree.ElementTree as ET\n\nfrom pydantic import BaseModel\n\n\nclass Vocabularies:\n \"This is a Vocabularies class\"\n def __init__(self, path):\n self.root = ET.parse(path).getroot()\n\n def get_ontologies(self):\n ontologies = []\n for i, atype in enumerate(self.root.findall('.//ontology')):\n ontology = Ontology(i, atype)\n ontologies.append(ontology)\n\n return ontologies\n\nclass Ontology:\n def __init__(self, i, element):\n self.i = i\n self.element = element\n def get_index(self):\n return self.i\n\n def get_name(self):\n return self.element.attrib['name']\n\n def get_type(self):\n return self.element.find('type').text\n\n def get_vocabulary(self):\n v = self.element.find('vocabulary')\n if v is not None:\n return self.element.find('vocabulary').text\n return ''\n\n def get_base_url(self):\n return self.element.find('api').text\n\n def get_uri(self):\n u = self.element.find('parameters/uri')\n if u is not None:\n return u.text\n return ''\n\n def get_vocab(self):\n u = self.element.find('parameters/vocab')\n if u is not None:\n return u.text\n return ''\n\n def get_query(self):\n u = self.element.find('parameters/query')\n if u is not None:\n return u.text\n return ''\n\n def get_lang(self):\n u = self.element.find('parameters/lang')\n if u is not None:\n return u.text\n return ''\n\n\nclass WriteXML:\n root = ET.Element('vocabularies');\n def __init__(self, el):\n #Remove all vocabularies children\n for child in self.root.findall('.//ontology'):\n self.root.remove(child)\n for key, value in el:\n if str(value).strip() != '':\n if str(key).startswith('inputName_'):\n ontology = ET.SubElement(self.root, 'ontology')\n ontology.set('name',str(value))\n if str(key).startswith('inputType_'):\n type = ET.SubElement(ontology, 'type')\n type.text = str(value)\n if str(key).startswith('inputVocabulary_'):\n voc = ET.SubElement(ontology, 'vocabulary')\n voc.text = str(value)\n if str(key).startswith('inputBaseUrl_'):\n api = ET.SubElement(ontology, 'api')\n api.text = str(value)\n parameters = ET.SubElement(ontology, 'parameters')\n\n if str(key).startswith('inputUri_'):\n uri = ET.SubElement(parameters, 'uri')\n uri.text = str(value)\n\n if str(key).startswith('inputVocab_'):\n vocab = ET.SubElement(parameters, 'vocab')\n vocab.text = str(value)\n\n if str(key).startswith('inputQuery_'):\n query = ET.SubElement(parameters, 'query')\n query.text = str(value)\n\n if str(key).startswith('inputLang_'):\n lang = ET.SubElement(parameters, 'lang')\n lang.text = str(value)\n\n # create a new XML file with the results\n def save(self, path):\n mydata = ET.tostring(self.root, encoding='UTF8', method='xml')\n myfile = open(path, 'wb')\n myfile.seek(0)\n myfile.truncate()\n myfile.seek(0)\n myfile.write(mydata)\n myfile.close()","sub_path":"app/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"367111443","text":"def initialize():\n global workers\n global distributed_parameters\n\n digest = digest = hashlib.sha256(\"cane\".encode(\"utf-8\")).hexdigest()\n\n file_path = \"/home/simone/Scrivania/Mythic/Payload_Types/kayn/shared/dictionary.txt\"\n f = open(file_path)\n dictionary = f.readlines()\n\n distributed_parameters = []\n\n words_per_worker = math.ceil(len(dictionary)/workers)\n for i in range(workers):\n param = {\n 'digest': digest,\n 'dictionary': []\n }\n if i == workers - 1:\n for j in range(len(dictionary) - i * words_per_worker):\n param[\"dictionary\"].append(dictionary[i * words_per_worker + j].strip())\n else:\n for j in range(words_per_worker):\n param[\"dictionary\"].append(dictionary[i * words_per_worker + j].strip())\n distributed_parameters.append(param)\n\n return distributed_parameters\n\n\n\ndef worker(param):\n\n global worker_output\n\n param = ast.literal_eval(param)\n\n dictionary = param[\"dictionary\"]\n\n print(dictionary)\n\n found = False\n\n for word in dictionary:\n print(word)\n if \"parallel\" in stopping_functions:\n print(colored(\"\\t - Stopped\", \"red\"))\n stopping_functions.remove('parallel')\n return\n\n word = word.strip()\n digest = hashlib.sha256(word.encode(\"utf-8\")).hexdigest()\n if digest == param[\"digest\"]:\n worker_output = \"Password found: \" + word\n print(worker_output)\n found = True\n return\n\n if found == False:\n worker_output = \"Password not found\"\n print(worker_output)\n return\n","sub_path":"Payload_Types/kayn/shared/DC.py","file_name":"DC.py","file_ext":"py","file_size_in_byte":1668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"580268124","text":"import sys\nimport os\nimport time\nimport mysql.connector\n\nimport projectConstants as constants\nfrom terminalColor import color as tc\n\npath = constants.PROJECT_PATH\n\n# Database connector\ncnx = mysql.connector.connect(user='lam', password='lam', database='bitcoin')\ncursor = cnx.cursor()\n\nfileCount = 0\n# loop all files\nfor fn in sorted(os.listdir(path + 'data/')):\n\n # Skip imported files\n if fn.endswith('.done'):\n continue\n\n fileCount = fileCount + 1\n print(\"Processing file {}\".format(fn))\n #sys.stdout.write(\"\\033[F\")\n #sys.stdout.write(\"\\033[K\")\n\n noError = True\n\n for line in open(path + 'data/' + fn):\n columns = line.split()\n\n try:\n # Write to database\n\n # Create appropriate database\n databaseName = time.strftime('%Y%m', time.localtime(int(columns[0])))\n query = (\"CREATE TABLE IF NOT EXISTS `{}` (`sysid` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, \"\n \"`unixdate` INT, `buy` FLOAT, `high` FLOAT, `last` FLOAT, \"\n \"`low` FLOAT, `sell` FLOAT, `vol` FLOAT, PRIMARY KEY(`sysid`))\".format(databaseName))\n cursor.execute(query)\n\n # Insert into database\n query = (\"INSERT INTO `{}`(unixdate, buy, high, last, low, sell, vol) \"\n \"VALUES(%s,%s,%s,%s,%s,%s,%s) \".format(databaseName))\n cursor.execute(query, (columns[0], columns[1], columns[2], columns[3], columns[4],\n columns[5], columns[6]))\n\n print(\"Inserting into table {}: {} {}\".format(databaseName, columns[0],\n time.strftime('%Y%m%d %H:%M:%S', time.localtime(int(columns[0]))) ))\n sys.stdout.write(\"\\033[F\")\n sys.stdout.write(\"\\033[K\")\n\n except mysql.connector.Error as err:\n print(\"Error: {}\".format(err))\n noError = False\n\n cnx.commit()\n\n if noError:\n os.rename(path + 'data/' + fn, path + 'data/' + fn + '.done')\n\n\n# Close database connection\ncursor.close()\ncnx.close()\n\n\nprint(\"Imported all {} files\".format(fileCount))\n","sub_path":"sys-import-data.py","file_name":"sys-import-data.py","file_ext":"py","file_size_in_byte":2138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"257801002","text":"# %% libraries\nimport cv2 as cv\nfrom mtcnn import MTCNN\n\n# %% setups\n# detector - default mtcnn\ndetector = MTCNN()\n\n# start capturing video\nvid_cam = cv.VideoCapture(0)\n\n# while looping video frame\nwhile True:\n # capture frame-by-frame\n _, frame = vid_cam.read()\n # detect faces\n faces = detector.detect_faces(frame)\n # check faces are detected\n # if not faces:\n # # loop faces if detected\n for face in faces:\n # get coordinates\n x1, y1, w, h = face['box']\n # plot in frame\n cv.rectangle(frame, (x1, y1), (x1+w, y1+h), (0, 0, 255), 2)\n # display video frame, with bounded rectangle on face\n cvshow = cv.imshow(\"TITLE\", frame)\n # stop taking video\n if cv.waitKey(100) & 0xFF == ord('q'):\n break\n\n# Stop video\nvid_cam.release()\n\n# Close all started windows\ncv.destroyAllWindows()\n","sub_path":"past_testing/mtcnn_video.py","file_name":"mtcnn_video.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"219247401","text":"#! C:\\Python36\\python.exe\n# coding:utf-8\n'''\n匹配、检索、替换\n'''\nimport re\n\nif __name__ == \"__main__\":\n mPattern = \"1[35789][0-9]{9}\"#模拟电话号码\n mstr = \"我的电话是13912345678\"\n # mstr = \"13912345678我的电话\"\n mstr = \"fuck13912345678,shit18612345678,damn188666\"\n ret = re.match(mPattern,mstr)#判断大串是否以子串开头\n ret = re.search(mPattern,mstr)#判断大串中有无子串,并返回第一个子串的信息\n ret = re.findall(mPattern,mstr)#从大串中搜索全部子串,以列表返回\n ret = re.sub(mPattern,\"【我的亲生儿子】\",mstr)#替换大串中的全部子串为【我的亲生儿子】,并返回新的大串\n print(ret)\n\n print(\"main over\")","sub_path":"day1/1025/demos/W5/day5/02MatchSearchFindallSub.py","file_name":"02MatchSearchFindallSub.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"586517829","text":"\"\"\"empty message\n\nRevision ID: bfb5d8811922\nRevises: 9d1b12c9d3b0\nCreate Date: 2020-03-13 18:28:44.636715\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'bfb5d8811922'\ndown_revision = '9d1b12c9d3b0'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('tag',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('created', sa.DateTime(), nullable=True),\n sa.Column('modified', sa.DateTime(), nullable=True),\n sa.Column('label', sa.String(), nullable=False),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('event_tag',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('created', sa.DateTime(), nullable=True),\n sa.Column('modified', sa.DateTime(), nullable=True),\n sa.Column('event_fk', sa.Integer(), nullable=True),\n sa.Column('tag_fk', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['event_fk'], ['event.id'], ),\n sa.ForeignKeyConstraint(['tag_fk'], ['tag.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('person_tag',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('created', sa.DateTime(), nullable=True),\n sa.Column('modified', sa.DateTime(), nullable=True),\n sa.Column('person_fk', sa.Integer(), nullable=True),\n sa.Column('tag_fk', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['person_fk'], ['person.id'], ),\n sa.ForeignKeyConstraint(['tag_fk'], ['tag.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('person_tag')\n op.drop_table('event_tag')\n op.drop_table('tag')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/bfb5d8811922_.py","file_name":"bfb5d8811922_.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"15803541","text":"import tkinter as tk\nfrom tkinter import messagebox\nimport requests\nfrom abstract_player import AbstractPlayer\n\n\nclass AddCenterPopup(tk.Frame):\n \"\"\" Popup fram to add a Center \"\"\"\n\n def __init__(self, parent, close_callback):\n \"\"\" Constructor \"\"\"\n\n tk.Frame.__init__(self, parent)\n self._close_cb = close_callback\n self.grid(rowspan=2, columnspan=2)\n\n tk.Label(self, text=\"Player ID:\").grid(row=1, column=1)\n self._player_id = tk.Entry(self)\n self._player_id.grid(row=1, column=2)\n tk.Label(self, text=\"First Name:\").grid(row=2, column=1)\n self._first_name = tk.Entry(self)\n self._first_name.grid(row=2, column=2)\n tk.Label(self, text=\"Last Name\").grid(row=3, column=1)\n self._last_name = tk.Entry(self)\n self._last_name.grid(row=3, column=2)\n tk.Label(self, text=\"Height:\").grid(row=4, column=1)\n self._height = tk.Entry(self)\n self._height.grid(row=4, column=2)\n tk.Label(self, text=\"Weight:\").grid(row=5, column=1)\n self._weight = tk.Entry(self)\n self._weight.grid(row=5, column=2)\n tk.Label(self, text=\"Year Drafted:\").grid(row=6, column=1)\n self._year_drafted = tk.Entry(self)\n self._year_drafted.grid(row=6, column=2)\n tk.Label(self, text=\"Number of Rebounds:\").grid(row=7, column=1)\n self._num_rebounds = tk.Entry(self)\n self._num_rebounds.grid(row=7, column=2)\n tk.Label(self, text=\"Play Style:\").grid(row=8, column=1)\n self._play_type = tk.Entry(self)\n self._play_type.grid(row=8, column=2)\n tk.Button(self, text=\"Submit\", command=self._submit_cb).grid(row=11, column=1)\n tk.Button(self, text=\"Close\", command=self._close_cb).grid(row=11, column=2)\n\n def _submit_cb(self):\n\n data = {}\n data['player_id'] = int(self._player_id.get())\n data['first_name'] = str(self._first_name.get())\n data['last_name'] = str(self._last_name.get())\n data['height'] = int(self._height.get())\n data['weight'] = int(self._weight.get())\n data['year_drafted'] = int(self._year_drafted.get())\n data['player_type'] = str(\"center\")\n data['num_rebounds'] = int(self._num_rebounds.get())\n data['play_type'] = str(self._play_type.get())\n\n url = 'http://localhost:5000/playermanager/players'\n response = requests.post(url, json=data)\n if response.status_code == 200:\n self._close_cb()\n else:\n messagebox.showwarning(\"Error\", \"Add Player Request Failed\")\n","sub_path":"add_center_popup.py","file_name":"add_center_popup.py","file_ext":"py","file_size_in_byte":2573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"189150177","text":"import jwt\nfrom time import time\nfrom bson import ObjectId\nfrom jwt.exceptions import ExpiredSignatureError, DecodeError\n\nfrom clink.type import AuthConf\nfrom clink.com import stamp\nfrom clink.type.com import Service\nfrom clink.error.http import Http400Error, Http401Error\nfrom clink.dflow import verify, NonExistError, ExpiredError, FormatError\n\nfrom .authdb_sv import AuthDbSv\nfrom .acc_sv import AccSv\nfrom clink.model.std import acc_name as acc_name_model, acc_pwd as pwd_model\n\n\n@stamp(AuthDbSv, AccSv, AuthConf)\nclass OAuthSv(Service):\n '''\n Limited OAuth2 implementation\n '''\n\n _TOKEN_ALG = 'HS512'\n\n def __init__(self, authdb_sv, acc_sv, auth_conf):\n '''\n :param AuthDbSv authdb_sv:\n :param AccSv acc_sv:\n :param AuthConf auth_conf:\n '''\n\n self._authdb_sv = authdb_sv\n self._acc_sv = acc_sv\n\n self._jwt_key = auth_conf.jwt_key\n self._token_time = auth_conf.token_time\n self._rtoken_time = auth_conf.rtoken_time\n\n @verify(None, acc_name_model, pwd_model)\n def mktoken_pwd(self, name, password):\n '''\n Create an token from account name and password\n\n :param str name:\n :param str password:\n :rtype: dict\n :raise NonExistError:\n '''\n\n acc = self._acc_sv.find_pwd(name, password)\n if acc is None:\n raise NonExistError({'name': name, 'password': '***'})\n\n return self._mk_token(acc['_id'])\n\n def mktoken_rtoken(self, rtoken):\n '''\n Create an token from refresh token\n\n :param str rtoken:\n :rtype: dict\n :raise TypeError:\n :raise ExpiredError:\n '''\n\n try:\n rtoken_raw = jwt.decode(\n rtoken, self._jwt_key, algorithm=self._TOKEN_ALG\n )\n return self._mk_token(rtoken_raw['sub'])\n except ExpiredSignatureError:\n raise ExpiredError({'refresh_token': None})\n except DecodeError:\n raise FormatError('refresh_token', None, None)\n\n def authen(self, access_token):\n '''\n Authenticate access token\n\n :param str access_token:\n :rtype: bson.objectid.ObjectId\n :raise FormatError:\n :raise ExpiredError:\n '''\n\n try:\n atoken_raw = jwt.decode(\n access_token, self._jwt_key, algorithm=self._TOKEN_ALG\n )\n return ObjectId(atoken_raw['sub'])\n except ExpiredSignatureError:\n raise ExpiredError({'access_token': None})\n except DecodeError:\n raise FormatError('access_token', None, None)\n\n def authen_req(self, req):\n '''\n Authenticate HTTP request\n\n :param Request req:\n :rtype mongo.objectid.ObjectId:\n :raise Http400Error:\n '''\n\n if 'AUTHORIZATION' not in req.header:\n raise Http401Error(req)\n auth_header = req.header['AUTHORIZATION']\n auth_type = auth_header[:7]\n if auth_type != 'Bearer ':\n raise Http400Error(req)\n atoken = auth_header[7:]\n\n return self.authen(atoken)\n\n def _mk_token(self, acc_id):\n '''\n Create token\n\n :param bson.objectid.ObjectId:\n :rtype: dict\n '''\n\n return {\n 'token_type': 'Bearer',\n 'expires_in': time() + self._token_time,\n 'access_token': self._mk_atoken(acc_id),\n 'refresh_token': self._mk_rtoken(acc_id)\n }\n\n def _mk_atoken(self, acc_id):\n '''\n Create access token\n\n :param bson.object.ObjectId:\n :rtype: str\n '''\n\n token_raw = {\n 'sub': str(acc_id),\n 'exp': time() + self._token_time\n }\n token = jwt.encode(\n token_raw, self._jwt_key, algorithm=self._TOKEN_ALG\n )\n return token.decode()\n\n def _mk_rtoken(self, acc_id):\n '''\n Create refresh token\n\n :param bson.object.ObjectId:\n :rtype: str\n '''\n\n token_raw = {\n 'sub': str(acc_id),\n 'exp': time() + self._rtoken_time\n }\n token = jwt.encode(\n token_raw, self._jwt_key, algorithm=self._TOKEN_ALG\n )\n return token.decode()\n","sub_path":"clink/service/auth/oauth_sv.py","file_name":"oauth_sv.py","file_ext":"py","file_size_in_byte":4262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"21885854","text":"from django.shortcuts import render_to_response, render\nfrom django.template import RequestContext\n\nfrom openpyxl import load_workbook\nimport openpyxl\nfrom Main.models import ProtectedCountry\nfrom Main.Logic.SearchCountryYear import draw_chart\nfrom Main.Logic.SearchCountryYear import draw_estimation\n\n\ndef get_year_country_from_work_book(wb, year, country):\n ws = wb['ESTIMATES']\n year_column = int(year) - 1950 + 5\n # i = 0\n # for row in ws.rows:\n # if row[0].value == 'Index':\n # for cell in row:\n # if cell.value == year:\n # year_column = i\n # i += 1\n count = -1\n for row in ws.rows:\n if row[2].value == country:\n print(\"found!\")\n print(row[year_column].value)\n count = row[year_column].value\n return count\n\n\ndef get_year_country(request, year, country):\n wb = load_workbook(filename='../../Data/WPP2015_POP_F01_2_TOTAL_POPULATION_MALE.xlsx', read_only=True)\n maleCount = get_year_country_from_work_book(wb, year, country)\n if maleCount == -1:\n maleCount = 'not found!'\n wb = load_workbook(filename='../../Data/WPP2015_POP_F01_3_TOTAL_POPULATION_FEMALE.xlsx', read_only=True)\n femaleCount = get_year_country_from_work_book(wb, year, country)\n if femaleCount == -1:\n femaleCount = 'not found!'\n return render_to_response('get_year_country.html',\n {'male_count': maleCount,\n 'female_count': femaleCount},\n context_instance=RequestContext(request))\n\n\ndef update_information(request):\n if request.method == 'POST':\n if request.POST.get('country', None) and request.POST.get('year', None):\n country = request.POST.get('country', None)\n year = request.POST.get('year', None)\n men = request.POST.get('men', None)\n women = request.POST.get('women', None)\n\n if ProtectedCountry.objects.filter(name_country=country).count() == 0:\n message_action = 'Please enter number for edit Men Or Women'\n if men:\n wb = openpyxl.load_workbook('..\\..\\Data\\WPP2015_POP_F01_2_TOTAL_POPULATION_MALE.xlsx')\n message_action = update_information_popularity_on_year(wb['ESTIMATES'], country, year, men) + '-> Men \\n'\n wb.save('..\\..\\Data\\WPP2015_POP_F01_2_TOTAL_POPULATION_MALE.xlsx')\n if women:\n wb = openpyxl.load_workbook('..\\..\\Data\\WPP2015_POP_F01_3_TOTAL_POPULATION_FEMALE.xlsx')\n message_action += update_information_popularity_on_year(wb['ESTIMATES'], country, year, women) + '-> Women'\n wb.save('..\\..\\Data\\WPP2015_POP_F01_3_TOTAL_POPULATION_FEMALE.xlsx')\n return render_to_response('update_information.html', {'message_action': message_action},\n context_instance=RequestContext(request))\n\n else:\n message_action = country + \"'s data is lock! you can't update information\"\n return render_to_response('update_information.html', {'message_action': message_action},\n context_instance=RequestContext(request))\n return render_to_response('update_information.html', {}, context_instance=RequestContext(request))\n\n\ndef update_information_popularity_on_year(ws, name_country, year, num):\n name_city_col = 3\n year_start_col = 6\n year_row = 17\n\n i = 18\n while True:\n if ws.cell(row=i, column=name_city_col).value == name_country:\n j = 0\n while True:\n if ws.cell(row=year_row, column=year_start_col + j).value == year:\n ws.cell(row=i, column=year_start_col + j).value = num\n return 'update data'\n\n elif not ws.cell(row=i, column=year_start_col + j).value:\n break\n\n j += 1\n\n return 'this year not exist -> year = ' + year\n\n elif not ws.cell(row=i, column=name_city_col).value:\n break\n\n i += 1\n return 'this country not exist -> country = ' + name_country\n\n\ndef update_protected_cell_of_country(request):\n if request.method == 'POST':\n message = 'Please enter name of country '\n\n if request.POST.get('country', None):\n country = request.POST.get('country', None)\n if ProtectedCountry.objects.all().filter(name_country=country).count() > 0:\n message = 'the country exist for action!'\n else:\n p = ProtectedCountry(name_country=country)\n p.save()\n message = 'add country!'\n return render_to_response('protectedCountry.html', {'message': message},\n context_instance=RequestContext(request))\n\n return render_to_response('protectedCountry.html', {}, context_instance=RequestContext(request))\n\n\ndef show_list_population(request):\n if request.method == 'POST' and request.POST.get('year', None):\n\n year = request.POST.get('year')\n\n wb = openpyxl.load_workbook('..\\..\\Data\\WPP2015_POP_F01_2_TOTAL_POPULATION_MALE.xlsx')\n m = get_list_population(wb['ESTIMATES'], year)\n\n wb = openpyxl.load_workbook('..\\..\\Data\\WPP2015_POP_F01_3_TOTAL_POPULATION_FEMALE.xlsx')\n w = get_list_population(wb['ESTIMATES'], year)\n\n if m and w:\n list_pop = []\n for x in w.keys():\n list_pop.append([x, w[x], m[x], w[x] + m[x]])\n\n list_pop.sort(key=lambda y: y[3])\n\n return render_to_response('showListOfPopularity.html', {'year': year, 'list_of_popularity': list_pop},\n context_instance=RequestContext(request))\n\n return render_to_response('showListOfPopularity.html', {'year': year}, context_instance=RequestContext(request))\n\n return render_to_response('showListOfPopularity.html', {}, context_instance=RequestContext(request))\n\n\ndef get_list_population(ws, year):\n name_city_col = 3\n name_city_row = 29\n year_start_col = 6\n year_row = 17\n list_pop = {}\n\n i = 0\n while True:\n if ws.cell(row=year_row, column=year_start_col + i).value == year:\n j = 0\n while True:\n if not ws.cell(row=name_city_row + j, column=name_city_col).value:\n break\n\n else:\n print(ws.cell(row=name_city_row + j, column=year_start_col + i).value)\n list_pop[ws.cell(row=name_city_row + j, column=name_city_col).value] = \\\n int(ws.cell(row=name_city_row + j, column=year_start_col + i).value)\n\n j += 1\n\n return list_pop\n\n elif not ws.cell(row=year_row, column=year_start_col + i).value:\n break\n\n i += 1\n\n return None\n\n\ndef show_list_prop(request):\n if request.method == 'POST' and request.POST.get('year', None) and request.POST.get('prop', None):\n\n year = request.POST.get('year')\n prop = request.POST.get('prop')\n\n try:\n wb = openpyxl.load_workbook('..\\..\\Data\\WPP2015_POP_F01_2_TOTAL_POPULATION_MALE.xlsx')\n m = get_list_population(wb[prop], year)\n\n wb = openpyxl.load_workbook('..\\..\\Data\\WPP2015_POP_F01_3_TOTAL_POPULATION_FEMALE.xlsx')\n w = get_list_population(wb[prop], year)\n\n if m and w:\n list_pop = []\n for x in w.keys():\n list_pop.append([x, w[x], m[x], w[x] + m[x]])\n\n list_pop.sort(key=lambda y: y[3])\n\n return render_to_response('showListOfPopularityWithProp.html',\n {'year': year, 'prop': prop, 'list_of_popularity': list_pop},\n context_instance=RequestContext(request))\n\n return render_to_response('showListOfPopularityWithProp.html', {'year': year},\n context_instance=RequestContext(request))\n except KeyError:\n print('bad prop!')\n return render_to_response('showListOfPopularityWithProp.html', {'error': 'bad property :|'},\n context_instance=RequestContext(request))\n\n return render_to_response('showListOfPopularityWithProp.html', {}, context_instance=RequestContext(request))\n\n\ndef countryshowchart(request, countryname):\n print(countryname)\n return render_to_response('year_chart.html',{\"url\":draw_chart(countryname)},context_instance=RequestContext(request))\n\ndef estimatechart(request, countryname,kind):\n print(countryname)\n return render_to_response('year_chart.html',{\"url\":draw_estimation(countryname,kind)},context_instance=RequestContext(request))\n\n","sub_path":"APP/SoftWareProject/Main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"363738549","text":"from datetime import datetime, timedelta\n\nfrom django.conf import settings\nfrom django.db.models import Q, Prefetch, F\nfrom django.db.models.functions import Now\nfrom django.utils import timezone\nfrom django.utils.translation import gettext_lazy as _\nfrom django_filters.rest_framework import DjangoFilterBackend\nfrom rest_framework import viewsets, mixins, permissions, status\nfrom rest_framework import serializers\nfrom rest_framework.decorators import action\nfrom rest_framework.exceptions import ValidationError\nfrom rest_framework.pagination import LimitOffsetPagination\nfrom rest_framework.response import Response\nfrom rest_framework.serializers import Serializer\n\nfrom account.permissions import HasAvailableAccessCodeOrReadOnly\nfrom account.serializers import SubjectSerializer\nfrom scheduling import filters, util\nfrom scheduling.models import TimeSlot, Appointment\nfrom scheduling.serializers import AppointmentAlternativeSerializer, AppointmentRejectionSerializer, AvailableSlotSerializer, FullAppointmentSerializer, TimeSlotSerializer\n\n\nclass IsOwnerOrReadOnly(permissions.BasePermission):\n def has_object_permission(self, request, view, obj):\n if request.method in permissions.SAFE_METHODS:\n return True\n return obj.owner == request.user\n\n\nclass IsSlotOwner(permissions.BasePermission):\n def has_object_permission(self, request, view, obj):\n return request.user == obj.timeslot.owner\n\n\nclass BelongsToAppointment(permissions.BasePermission):\n def has_object_permission(self, request, view, obj):\n return request.user == obj.invitee or request.user == obj.owner\n\n\nclass AvailableSlotViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):\n queryset = TimeSlot.objects.prefetch_related(\n Prefetch('appointment_set', queryset=Appointment.objects.filter(\n start_time__gte=Now()))\n ).select_related(\n 'owner',\n 'owner__tutordata'\n ).prefetch_related(\n 'owner__tutordata__subjects'\n ).filter(Q(weekly=True) | Q(start_time__gte=Now()), owner__tutordata__verified=True)\n serializer_class = AvailableSlotSerializer\n permission_classes = [permissions.IsAuthenticated]\n filter_backends = [DjangoFilterBackend]\n filterset_class = filters.AvailableSlotFilter\n pagination_class = LimitOffsetPagination\n\n def get_queryset(self):\n qs = self.queryset.all()\n if self.request.user.studentdata and settings.NAKLAR_SCHEDULING_SCHOOLDATA:\n qs = qs.filter(\n owner__tutordata__schooldata=self.request.user.studentdata.school_data)\n return qs\n\n @action(['GET'], detail=False, serializer_class=SubjectSerializer, filterset_class=None)\n def subjects(self, request, *args, **kwargs):\n qs = self.filter_queryset(self.get_queryset())\n subjects = set()\n for timeslot in qs:\n if len(timeslot.available_slots()) > 0:\n subjects = subjects.union(\n timeslot.owner.tutordata.subjects.all())\n serializer = SubjectSerializer(subjects, many=True)\n return Response(serializer.data)\n\n def list(self, request, *args, **kwargs):\n queryset = self.filter_queryset(self.get_queryset())\n slots = []\n for timeslot in queryset:\n slots.extend(timeslot.available_slots(\n earliest_start=timezone.now() + timedelta(minutes=settings.NAKLAR_SCHEDULING_APPOINTMENT_DISTANCE)))\n slots.sort(key=lambda x: x.start_time)\n\n page = self.paginate_queryset(slots)\n if page is not None:\n serializer = self.get_serializer(page, many=True)\n return self.get_paginated_response(serializer.data)\n\n serializer = self.get_serializer(slots, many=True)\n return Response(serializer.data)\n\n\nclass AppointmentViewSet(viewsets.ModelViewSet):\n queryset = Appointment.objects.select_related('owner').filter(\n Q(start_time__gte=Now() - F('duration')) | Q(start_time__gte=timezone.now() - timedelta(hours=2),\n meeting__ended=False))\n serializer_class = FullAppointmentSerializer\n permission_classes = [permissions.IsAuthenticated,\n IsOwnerOrReadOnly, HasAvailableAccessCodeOrReadOnly]\n\n @action(detail=True, methods=['post'], permission_classes=[IsSlotOwner])\n def accept(self, request, pk=None):\n appointment = self.get_object()\n if appointment.status == Appointment.Status.REQUESTED:\n appointment.status = Appointment.Status.CONFIRMED\n appointment.save()\n appointment.send_confirmed()\n return Response(data=self.get_serializer(instance=appointment).data)\n\n @action(detail=True, methods=['delete', 'post'], permission_classes=[BelongsToAppointment], serializer_class=AppointmentRejectionSerializer)\n def reject(self, request, pk=None):\n appointment = self.get_object()\n serializer = self.get_serializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n\n appointment.handle_rejection(\n self.request.user, reason=serializer.data[\"reason\"] if \"reason\" in serializer.data else \"\")\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n @action(detail=True, methods=['get'], permission_classes=[BelongsToAppointment], serializer_class=AppointmentAlternativeSerializer\n )\n def has_alternative(self, request, pk=None):\n appointment: Appointment = self.get_object()\n new_timeslot = appointment.get_alternative()\n serializer = AppointmentAlternativeSerializer(\n data={'has_alternative': True if new_timeslot else False})\n serializer.is_valid(raise_exception=True)\n return Response(data=serializer.data)\n\n @action(detail=True, methods=['post'], permission_classes=[BelongsToAppointment],\n queryset=Appointment.objects.filter(start_time__lte=Now() + timedelta(minutes=15),\n start_time__gte=Now() - F('duration'), status__in=[\n Appointment.Status.BOTH_STARTED,\n Appointment.Status.INVITEE_STARTED,\n Appointment.Status.OWNER_STARTED,\n Appointment.Status.CONFIRMED]))\n def start_meeting(self, request, pk=None):\n from roulette.models import Meeting\n appointment = self.get_object()\n if appointment.meeting:\n meeting = appointment.meeting\n else:\n meeting = Meeting.objects.create(\n tutor=appointment.invitee, student=appointment.owner)\n meeting.users.add(appointment.owner, appointment.invitee)\n appointment.meeting = meeting\n if self.request.user == appointment.owner:\n appointment.status = Appointment.Status.BOTH_STARTED \\\n if appointment.status == Appointment.Status.INVITEE_STARTED else Appointment.Status.OWNER_STARTED\n elif self.request.user == appointment.invitee:\n appointment.status = Appointment.Status.BOTH_STARTED \\\n if appointment.status == Appointment.Status.OWNER_STARTED else Appointment.Status.INVITEE_STARTED\n appointment.save()\n url = meeting.create_join_link(self.request.user, True)\n return Response(data={'join_url': url, 'meeting_id': meeting.meeting_id})\n\n def perform_create(self, serializer: Serializer):\n is_direct = True\n if not serializer.validated_data['timeslot']:\n is_direct = False\n qs = TimeSlot.objects.all()\n if 'direct_invitee' in serializer.validated_data:\n qs = qs.filter(\n owner=serializer.validated_data.pop('direct_invitee'))\n is_direct = True\n start_time: datetime = serializer.validated_data['start_time']\n duration = serializer.validated_data['duration']\n subject = serializer.validated_data['subject']\n timeslot = util.find_matching_timeslot(\n start_time, duration, subject, self.request.user, qs\n )\n if timeslot:\n serializer.initial_data['timeslot'] = timeslot.id\n serializer.run_validation(serializer.initial_data)\n serializer.validated_data['timeslot'] = timeslot\n else:\n raise ValidationError({\n 'timeslot': _(\"Couldn't find matching timeslot!\")}\n )\n serializer.save(is_direct=is_direct)\n\n def get_queryset(self):\n queryset = super(AppointmentViewSet, self).get_queryset()\n return queryset.filter(Q(owner=self.request.user) | Q(timeslot__owner=self.request.user))\n\n\nclass TimeSlotViewSet(viewsets.ModelViewSet):\n queryset = TimeSlot.objects.select_related('owner').filter(\n Q(start_time__gte=Now()) | Q(weekly=True))\n serializer_class = TimeSlotSerializer\n permission_classes = [permissions.IsAuthenticated, IsOwnerOrReadOnly]\n\n def get_queryset(self):\n queryset = super(TimeSlotViewSet, self).get_queryset()\n return queryset.filter(owner=self.request.user)\n","sub_path":"backend/naklar-io/scheduling/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"358434610","text":"# Adapted from mdtraj/devtools/travis-ci/update_versions_json.py,\n# by Robert T McGibbon, under the LGPLv2.1 license\n# Similarly by the terms of LGPL this is also in the public domain\n# Lily Wang, 2020\n#\n# This script is called by deploy_docs_via_travis.sh to:\n# 1. update versions.json\n# 2. Write some redirect stubs\n# 3. Write a sitemap.xml file for the root directory\n#\n\nimport json\nimport os\nimport errno\nimport glob\nimport shutil\nimport textwrap\nimport xml.etree.ElementTree as ET\n\ntry:\n from urllib.request import Request, urlopen\nexcept ImportError:\n from urllib2 import Request, urlopen\n\nURL = os.environ['URL']\nVERSION = os.environ['VERSION']\n\n\ndef get_web_file(filename, callback, default):\n url = os.path.join(URL, filename)\n try:\n page = Request(url, headers={'User-Agent': 'Mozilla/5.0'})\n data = urlopen(page).read().decode()\n except Exception as e:\n print(e)\n try:\n with open(filename, 'r') as f:\n return callback(f)\n except IOError as e:\n print(e)\n return default\n else:\n return callback(data)\n\n\n# ========= WRITE HTML STUBS =========\n# Add HTML files to redirect:\n# index.html -> latest release\n# latest/index.html -> latest release\n# dev/index.html -> dev docs\n\n\ndef write_redirect(file, version='', outfile=None):\n if outfile is None:\n outfile = file\n url = os.path.join(URL, version, file)\n REDIRECT = textwrap.dedent(f\"\"\"\n \n \n Redirecting to {url}\n \n \n \"\"\")\n with open(outfile, 'w') as f:\n f.write(REDIRECT)\n\n\n# ========= WRITE JSON =========\n# Update $root/versions.json with links to the right version\nversions = get_web_file('versions.json', json.loads, [])\nexisting = [item['version'] for item in versions]\nalready_exists = VERSION in existing\n\nif not already_exists:\n latest = 'dev' not in VERSION\n if latest:\n for ver in versions:\n ver['latest'] = False\n\n versions.append({\n 'version': VERSION,\n 'display': VERSION,\n 'url': os.path.join(URL, VERSION),\n 'latest': latest\n })\n\nwith open(\"versions.json\", 'w') as f:\n json.dump(versions, f, indent=2)\n\nfor ver in versions[::-1]:\n if ver['latest']:\n latest_version = ver['version']\n break\nelse:\n try:\n latest_version = versions[-1]['version']\n except IndexError:\n latest_version = None\n\nfor ver in versions[::-1]:\n if 'dev' in ver['version']:\n dev_version = ver['version']\n break\nelse:\n try:\n dev_version = versions[-1]['version']\n except IndexError:\n dev_version = None\n\nif latest_version:\n html_files = glob.glob(f'{latest_version}/**/*.html', recursive=True)\n for file in html_files:\n outfile = file.strip(f'{latest_version}/')\n dirname = os.path.dirname(outfile)\n if dirname and not os.path.exists(dirname):\n try:\n os.makedirs(dirname)\n except OSError as exc:\n if exc.errno != errno.EEXIST:\n raise\n\n write_redirect(file, '', outfile)\n write_redirect('index.html', latest_version, 'latest/index.html')\n\nif dev_version:\n write_redirect('index.html', dev_version, 'dev/index.html')\n\n# ========= WRITE SUPER SITEMAP.XML =========\n# make one big sitemap.xml\nET.register_namespace('xhtml', \"http://www.w3.org/1999/xhtml\")\n\n# so we could make 1 big sitemap as commented\n# below, but they must be max 50 MB / 50k URL.\n# Yes, this is 100+ releases, but who knows when\n# that'll happen and who'll look at this then?\n# bigroot = ET.Element(\"urlset\")\n# bigroot.set(\"xmlns\", \"http://www.sitemaps.org/schemas/sitemap/0.9\")\n# for ver in versions:\n# tree = get_web_file(ver['version']+'/sitemap.xml', ET.fromstring,\n# ET.fromstring(''))\n# root = tree.getroot()\n# bigroot.extend(root.getchildren())\n# ET.ElementTree(bigroot).write('sitemap.xml',\n# xml_declaration=True,\n# encoding='utf-8',\n# method=\"xml\")\n\n# so instead we make a sitemap of sitemaps.\nbigroot = ET.Element(\"sitemapindex\")\nbigroot.set(\"xmlns\", \"http://www.sitemaps.org/schemas/sitemap/0.9\")\nfor ver in versions:\n path = os.path.join(URL, '{}/sitemap.xml'.format(ver['version']))\n sitemap = ET.SubElement(bigroot, 'sitemap')\n ET.SubElement(sitemap, 'loc').text = path\n\nET.ElementTree(bigroot).write('sitemap_index.xml',\n xml_declaration=True,\n encoding='utf-8',\n method=\"xml\")\n","sub_path":"maintainer/update_json_stubs_sitemap.py","file_name":"update_json_stubs_sitemap.py","file_ext":"py","file_size_in_byte":4760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"361530586","text":"import numpy as np\n\n# method is complete - DO NOT MODIFY\ndef forcing_heat1d(f, x, t):\n u = 0.\n if f == 1:\n u = 0.\n return u\n\n# method is complete - DO NOT MODIFY\ndef boundary_heat1d(x1d, nx, nt, base, scale, mu, sigma):\n bc = np.zeros((nx,nt))\n gauss_tmp1 = (1./(np.sqrt(2*np.pi*sigma*sigma)))\n gauss_tmp2 = np.exp(-1.*(x1d-mu)*(x1d-mu)/(2.*sigma*sigma))\n gauss = gauss_tmp1*gauss_tmp2\n bc[:,0] = base+scale*gauss\n bc[0,:] = base\n bc[-1,:] = base\n return bc\n\n\n# method is incomplete - TODO\ndef heat1d(scheme, f, a, dx, dt, x1d, t1d, bc):\n # Solves the parabolic differential equation given in Tasks 3 and 4\n # Inputs\n # scheme : string denoting which scheme to use\n # f : integer describing which forcing option to use in forcing_heat1d\n # a : thermal diffusivity constant\n # dx : horizontal grid spacing\n # dt : temporal grid spacing\n # x1d : physical distance along the beam (1d array, length nx)\n # t1d : times at which state of beam is solved (1d array, length nt)\n # bc : boundary conditions (2d array, length nx by nt)\n # Outputs\n # u : numerical solution (2d array, length nx by nt)\n\n # Transpose so each row is a time period (as ndenumerate will loop across rows)\n u = np.transpose(bc);\n\n # Iterate over all elements row by row, calculating temperature with explicit scheme\n for (t_idx,x_idx), val in np.ndenumerate(u):\n # Only calculate for internal points\n if t_idx > 0 and x_idx > 0 and x_idx < len(x1d) -1:\n u[t_idx, x_idx] = u[t_idx - 1, x_idx] + (dt/a) * ((u[t_idx - 1, x_idx - 1] - 2*u[t_idx - 1, x_idx] + u[t_idx - 1, x_idx + 1])/dx**2 - forcing_heat1d(f ,x1d[x_idx], t1d[t_idx]))\n return u;\n\n\ndef heat1d_v2(scheme, f, a, dx, dt, x1d, t1d, bc):\n # Solves the parabolic differential equation given in Tasks 3 and 4\n # Inputs\n # scheme : string denoting which scheme to use\n # f : integer describing which forcing option to use in forcing_heat1d\n # a : thermal diffusivity constant\n # dx : horizontal grid spacing\n # dt : temporal grid spacing\n # x1d : physical distance along the beam (1d array, length nx)\n # t1d : times at which state of beam is solved (1d array, length nt)\n # bc : boundary conditions (2d array, length nx by nt)\n # Outputs\n # u : numerical solution (2d array, length nx by nt)\n\n # Transpose so each row is a time period\n u = np.transpose(bc);\n\n nt = len(t1d)\n nx = len(x1d)\n\n # Get scheme parameters and matrix\n options = {\n 'explicit' : 0.0,\n 'crank-nicolson' : 1/2,\n 'galerkin' : 2/3,\n 'backward-euler' : 1.0\n }\n theta = options[scheme]\n r = dt/(a*dx**2)\n matrix = generateMatrix(r, theta, nx)\n\n # Solve implicit scheme one time period at a time\n for n in range(1,nt):\n b = u[[n-1,n], :].reshape((2*nx,1))\n A = matrix\n x = np.linalg.solve(A,b)\n u[n, :] = x[nx:].T\n\n return u;\n\ndef generateMatrix(r, theta, nx):\n# This function will generate a matrix that solves one time period of an implicit\n# finite difference scheme for the 1D heat equation\n# Inputs:\n# r - as defined by the notes (dt/(a*dx**2)) float\n# theta - the theta associated with the specific scheme to be generated float\n# nx - the number of x values in the model grid int\n\n # Start with the identity matrix \n A = np.eye(2*nx)\n # Generate matrix based off stencil for unknown points\n for i in range(1,nx-1):\n row = mat2arr(i, 1, nx=nx)\n A[row, mat2arr(i-1, 0, nx=nx)] = (1-theta)*r;\n A[row, mat2arr(i , 0, nx=nx)] = 1 - 2*(1-theta)*r;\n A[row, mat2arr(i+1, 0, nx=nx)] = (1-theta)*r;\n A[row, mat2arr(i-1, 1, nx=nx)] = theta*r;\n A[row, mat2arr(i , 1, nx=nx)] = -1 - 2*theta*r;\n A[row, mat2arr(i+1, 1, nx=nx)] = theta*r;\n return A\n\ndef mat2arr(i, n, nx):\n# Helper funtion to convert x and t indices in to their corresponding array index\n# i - an index corresponding to a x value in the model grid\n# n - an index corresponding to a t value in the model grid\n# nx - the number of x values in the model grid \n return n*nx + i","sub_path":"src/fd_functions_part2.py","file_name":"fd_functions_part2.py","file_ext":"py","file_size_in_byte":4307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"13476216","text":"import collections\nimport corenlp\nimport json\nimport openreview\nimport random\nimport sys\n\nimport openreview_lib as orl\n\nrandom.seed(47)\n\nCORENLP_ANNOTATORS = \"ssplit tokenize\"\ndef get_pair_text_from_forums(forums, guest_client):\n print(\"Getting pair text from \", len(forums), \" forums\")\n sid_map, pairs = orl.get_review_rebuttal_pairs(\n forums, guest_client)\n with corenlp.CoreNLPClient(\n annotators=CORENLP_ANNOTATORS, output_format='conll') as corenlp_client:\n return orl.get_pair_text(pairs, sid_map, corenlp_client)\n\ndef get_abstracts_from_forums(forums, guest_client):\n print(\"Getting abstracts\")\n with corenlp.CoreNLPClient(\n annotators=CORENLP_ANNOTATORS, output_format='conll') as corenlp_client:\n return orl.get_abstract_texts(forums, guest_client, corenlp_client)\n\ndef get_unstructured(conference, guest_client, output_dir):\n forums = get_sampled_forums(conference, guest_client, 1).forums\n pair_texts = get_pair_text_from_forums(forums, guest_client)\n unstructured_text = []\n for pair in pair_texts:\n unstructured_text.append(pair[\"review_text\"])\n unstructured_text.append(pair[\"rebuttal_text\"])\n abstracts = get_abstracts_from_forums(forums, guest_client)\n with open(output_dir + \"/\" + orl.Split.UNSTRUCTURED + \".json\", 'w') as f:\n json.dump({\n \"conference\": conference,\n \"split\": orl.Split.UNSTRUCTURED,\n \"subsplit\": orl.SubSplit.TRAIN,\n \"review_rebuttal_text\": unstructured_text,\n \"abstracts\": abstracts,\n }, f)\n\ndef get_traindev(conference, guest_client, output_dir):\n forums = get_sampled_forums(conference, guest_client, 1).forums\n random.shuffle(forums)\n offsets = {\n orl.SubSplit.DEV :(0, int(0.2*len(forums))),\n orl.SubSplit.TRAIN : (int(0.2*len(forums)), int(0.8*len(forums))),\n orl.SubSplit.TEST : (int(0.8*len(forums)), int(1.1*len(forums)))\n }\n sub_split_forum_map = {\n sub_split: forums[start:end]\n for sub_split, (start, end) in offsets.items()\n }\n for sub_split, sub_split_forums in sub_split_forum_map.items():\n pair_texts = get_pair_text_from_forums(sub_split_forums, guest_client)\n with open(\n \"\".join([output_dir, \"/\", orl.Split.TRAINDEV, \"_\",\n sub_split, \".json\"]), 'w') as f:\n json.dump({\n \"conference\": conference,\n \"split\": orl.Split.TRAINDEV,\n \"subsplit\": sub_split,\n \"review_rebuttal_pairs\": pair_texts,\n \"abstracts\": None\n }, f)\n\ndef get_truetest(conference, guest_client, output_dir):\n forums = get_sampled_forums(conference, guest_client, 0.2).forums\n pair_texts = get_pair_text_from_forums(forums, guest_client)\n with open(output_dir + \"/\" + orl.Split.TRUETEST + \".json\", 'w') as f:\n json.dump({\n \"conference\": conference,\n \"split\": orl.Split.TRUETEST,\n \"subsplit\": orl.SubSplit.TEST,\n \"review_rebuttal_pairs\": pair_texts,\n \"abstracts\": None\n }, f)\n\n\ndef main():\n guest_client = openreview.Client(baseurl='https://api.openreview.net')\n\n SPLIT_TO_CONFERENCE = {\n orl.Split.UNSTRUCTURED: orl.Conference.iclr18,\n orl.Split.TRAINDEV: orl.Conference.iclr19,\n orl.Split.TRUETEST: orl.Conference.iclr20\n }\n\n output_dir = \"unlabeled/\"\n\n get_unstructured(\n SPLIT_TO_CONFERENCE[orl.Split.UNSTRUCTURED], guest_client, output_dir)\n get_traindev(\n SPLIT_TO_CONFERENCE[orl.Split.TRAINDEV], guest_client, output_dir)\n get_truetest(\n SPLIT_TO_CONFERENCE[orl.Split.TRUETEST], guest_client, output_dir)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"build_database.py","file_name":"build_database.py","file_ext":"py","file_size_in_byte":3503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"128861456","text":"import json\nimport re\nimport time\nfrom datetime import datetime\n\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom tqdm import tqdm\n\nfrom webdriver_manager.chrome import ChromeDriverManager\n\nprint(\"\\nScrapping Athletes\")\nprint(\n \"---------------------------------------------------------------------------------\"\n)\n\ndriver = webdriver.Chrome(ChromeDriverManager().install())\n\ndriver.get(\"https://www.forbes.com/athletes/list\")\ndriver.set_page_load_timeout(20)\nwait = WebDriverWait(driver, 10)\n\n# wait until table loaded\nelem = wait.until(lambda x: x.find_element_by_tag_name(\"table\"))\n\n# scroll the page to the bottom to load all records (which are loaded on scroll)\nlast_height = driver.execute_script(\"return document.body.scrollHeight\")\nwhile True:\n # Scroll down to bottom\n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n\n # Wait to load page\n time.sleep(3)\n\n # Calculate new scroll height and compare with last scroll height\n new_height = driver.execute_script(\"return document.body.scrollHeight\")\n if new_height == last_height:\n break\n last_height = new_height\n\n# reload the table since new elements are added to it after scroll\n\nelem = wait.until(lambda x: x.find_element_by_tag_name(\"table\"))\n\nh = driver.execute_script(\"return arguments[0].innerHTML;\", elem)\ndriver.close()\nsoup = BeautifulSoup(h, \"html.parser\")\n\n# create data\ndata = []\nfor idx, record in enumerate(tqdm(soup.find_all(\"tr\"))):\n if idx == 0:\n continue\n elif idx == 3:\n worth = float(104)\n else:\n try:\n worth = float(re.findall(r\"\\d+.?\\d+\", record.find_all(\"td\")[3].text)[0])\n except:\n continue\n\n image = f'https:{record.find(\"img\")[\"src\"]}'\n name = record.find_all(\"td\")[2].text\n sport = record.find_all(\"td\")[6].text\n\n data.append(\n {\n \"worth\": worth * 1000000,\n \"data\": {\n \"image\": image,\n \"name\": name,\n \"sports\": sport,\n },\n }\n )\n\n\n# save\nwith open(\"../src/assets/jsons/athlete.json\", \"w\") as file:\n file.write(json.dumps({\"date\": datetime.now().strftime(\"%d %B, %Y\"), \"data\": data}))\n","sub_path":"scrapers/athlete_scrapper.py","file_name":"athlete_scrapper.py","file_ext":"py","file_size_in_byte":2425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"415631816","text":"import cattr\nimport requests_mock\nfrom unittest import TestCase\n\nfrom tests.utils import FixtureLoader\nfrom truework.base import TrueworkHTTPError\nfrom truework.verification_request import VerificationRequest\n\n\nclass TestVerificationRequestsCreate(TestCase, FixtureLoader):\n @requests_mock.mock()\n def test_create_success(self, mock):\n verification_request_response = self.load_fixture(\n \"verification_requests/verification_request_response.json\"\n )\n mock.post(\n VerificationRequest.url(),\n status_code=200,\n json=verification_request_response,\n )\n\n data = {\n \"type\": \"employment\",\n \"permissible_purpose\": \"risk-assessment\",\n \"target\": {\n \"first_name\": \"Joe\",\n \"last_name\": \"Smith\",\n \"social_security_number\": \"000-00-0000\",\n \"contact_email\": \"joesmith@example.org\",\n \"company\": {\"id\": \"1234\"},\n },\n \"documents\": [\n {\n \"filename\": \"signed_auth_form.pdf\",\n \"content\": \"iVBORw0KGgoAAAANSUhEUg......IhAAAAABJRU5ErkJggg==\",\n },\n {\n \"filename\": \"verifier_notes.pdf\",\n \"content\": \"iVBORw0KGgoAAAANSUhEUg......IhAAAAABJRU5FRSJghg==\",\n },\n ],\n }\n\n response = VerificationRequest.create(**data)\n self.assertEqual(\n response,\n cattr.structure(verification_request_response, VerificationRequest),\n )\n\n @requests_mock.mock()\n def test_create_missing_data(self, mock):\n mock.post(\n VerificationRequest.url(),\n status_code=400,\n json={\"error\": {\"message\": \"missing type field\"}},\n )\n\n data = {\n \"permissible_purpose\": \"risk-assessment\",\n \"target\": {\n \"first_name\": \"Joe\",\n \"last_name\": \"Smith\",\n \"social_security_number\": \"000-00-0000\",\n \"contact_email\": \"joesmith@example.org\",\n \"company\": {\"id\": \"1234\"},\n },\n \"documents\": [\n {\n \"filename\": \"signed_auth_form.pdf\",\n \"content\": \"iVBORw0KGgoAAAANSUhEUg......IhAAAAABJRU5ErkJggg==\",\n },\n {\n \"filename\": \"verifier_notes.pdf\",\n \"content\": \"iVBORw0KGgoAAAANSUhEUg......IhAAAAABJRU5FRSJghg==\",\n },\n ],\n }\n\n with self.assertRaises(TrueworkHTTPError) as context:\n VerificationRequest.create(**data)\n\n self.assertEqual(context.exception.status_code, 400)\n","sub_path":"tests/verification_requests/test_create.py","file_name":"test_create.py","file_ext":"py","file_size_in_byte":2753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"2885550","text":"'''\nCreated on Oct 31, 2018\n\n@author: Lizhen Shi\n'''\n\nimport numpy as np\nimport pandas as pd \nfrom gct.alg.clustering import Result\nimport sys\nfrom gct.dataset import convert\nfrom gct.dataset.dataset import Clustering\nfrom gct import utils, config\nimport os\n\nfrom .graph_metrics import GraphMetrics, SNAPGraphMetrics\n\nclass GraphClusterMetrics(object):\n '''\n metrics for a clustering of a graph. e.g. modularity.\n \n '''\n\n def __init__(self, data, clusteringobj):\n '''\n :param data: a :class:`gct.Dataset` object \n :param clusteringobj: a :class:`gct.Clustering` object or refer to the *groundtruth* parameter of :meth:`gct.from_edgelist`\n '''\n if data.is_directed() or data.is_weighted():\n print (\"Warning! Graph will be taken as undirected and unweighted.\")\n if isinstance(clusteringobj, Clustering):\n self.clusterobj = clusteringobj\n elif isinstance(clusteringobj, Result):\n ##self.clusterobj = Clustering(clusteringobj.clusters(as_dataframe=True))\n self.clusterobj = Clustering(clusteringobj.clustering(as_dataframe=True))\n elif isinstance(clusteringobj, pd.DataFrame) or isinstance(clusteringobj, list) \\\n or isinstance(clusteringobj, np.ndarray) or isinstance(clusteringobj, str) or isinstance(clusteringobj, dict):\n self.clusterobj = Clustering(clusteringobj)\n else:\n raise Exception(\"Unsupported \" + str(type(clusteringobj)))\n self.data = data \n self.clusters = self.clusterobj.value()\n\n def set_if_not_exists(self, name, fun):\n if hasattr(self, name):\n return getattr(self, name)\n else:\n # print (\"call fun for \" + name)\n value = fun()\n setattr(self, name, value)\n return value \n \n @property\n def edges(self):\n\n def f():\n df = self.data.get_edges()\n if not self.data.is_weighted():\n df['weight'] = float(1)\n return df \n\n prop_name = \"_\" + sys._getframe().f_code.co_name \n return self.set_if_not_exists(prop_name, f)\n \n @property \n def num_edges(self):\n '''\n number of edges of the graph\n '''\n return self.edges.shape[0]\n \n @property \n def num_vertices(self):\n '''\n number of vertices (nodes) of the graph\n '''\n prop_name = \"_\" + sys._getframe().f_code.co_name \n return self.set_if_not_exists(prop_name, lambda: len(set(np.unique(self.edges[['src', 'dest']].values))))\n\n @property\n def node_degrees(self):\n '''\n degrees for all the nodes\n ''' \n return self.unweighted_degrees\n\n @property\n def node_weights(self):\n '''\n weight sum for each node\n '''\n return self.weighted_degrees\n\n @property\n def sum_weight(self):\n return np.sum(list(self.node_weights.values()))\n \n @property\n def unweighted_degrees(self):\n '''\n unweighted degrees of nodes\n '''\n\n def f():\n arr = self.edges[['src', 'dest']].values.ravel() \n unique, counts = np.unique(arr, return_counts=True)\n return dict(zip(unique, counts))\n\n prop_name = \"_\" + sys._getframe().f_code.co_name \n return self.set_if_not_exists(prop_name, f)\n\n @property\n def weighted_degrees(self):\n '''\n weighted degrees of nodes\n '''\n\n def f():\n df1 = self.edges[['src', 'weight']]\n df2 = self.edges[['dest', 'weight']]\n df2.columns = df1.columns\n df = pd.concat([df1, df2])\n return df.groupby('src')['weight'].sum().to_dict()\n\n prop_name = \"_\" + sys._getframe().f_code.co_name \n return self.set_if_not_exists(prop_name, f)\n\n @property \n def num_clusters(self):\n '''\n number of partitions\n '''\n return len(self.cluster_indexes)\n \n @property \n def cluster_indexes(self):\n '''\n cluster identifiers\n '''\n return self.cluster_sizes.keys() \n \n @property \n def cluster_sizes(self):\n \"\"\"\n return cluster size for each cluster\n \"\"\"\n prop_name = \"_\" + sys._getframe().f_code.co_name \n return self.set_if_not_exists(prop_name, lambda: self.clusters[['node', 'cluster']].groupby('cluster')['node'].count().to_dict())\n \n @property \n def cluster_sum_intra_weights(self):\n\n def f():\n df = self.edges[['src', 'dest', 'weight']]\n c_df = self.clusters[['node', 'cluster']].set_index('node')['cluster'].to_dict()\n df['src_c'] = df['src'].map(c_df) \n df['dest_c'] = df['dest'].map(c_df)\n df = df [(df['src_c'] == df['dest_c'])]\n\n a = df[['src_c', 'weight']].groupby('src_c')['weight'].sum() * 2\n return a.to_dict()\n \n prop_name = \"_\" + sys._getframe().f_code.co_name\n \n return self.set_if_not_exists(prop_name, f) \n\n @property \n def cluster_sum_weighted_degrees(self):\n\n def f():\n df = self.clusters[['node', 'cluster']]\n d = self.weighted_degrees\n df['wd'] = df['node'].map(d)\n return df.groupby(\"cluster\")['wd'].sum().to_dict()\n \n prop_name = \"_\" + sys._getframe().f_code.co_name\n \n return self.set_if_not_exists(prop_name, f) \n \n @property\n def cluster_edge_sizes(self):\n\n def f():\n df = self.edges[['src', 'dest']]\n c_df = self.clusters[['node', 'cluster']].set_index('node')['cluster'].to_dict()\n df['src_c'] = df['src'].map(c_df) \n df['dest_c'] = df['dest'].map(c_df)\n df['is_intra'] = (df['src_c'] == df['dest_c']).astype(np.float)\n\n a = df[['src_c', 'is_intra']].groupby('src_c')['is_intra'].sum().to_dict()\n return a \n \n prop_name = \"_\" + sys._getframe().f_code.co_name\n \n return self.set_if_not_exists(prop_name, f) \n \n @property\n def cluster_out_sum_weights(self):\n\n def f():\n df = self.edges[['src', 'dest', 'weight']]\n c_df = self.clusters[['node', 'cluster']].set_index('node')['cluster'].to_dict()\n df['src_c'] = df['src'].map(c_df) \n df['dest_c'] = df['dest'].map(c_df)\n df = df[(df['src_c'] != df['dest_c'])]\n \n a = df.groupby('src_c')[['weight']].sum().reset_index()\n b = df.groupby('dest_c')[['weight']].sum().reset_index() \n b.columns = a.columns\n a = pd.concat([a, b]).groupby('src_c').sum()\n return a['weight'].to_dict()\n \n prop_name = \"_\" + sys._getframe().f_code.co_name\n \n return self.set_if_not_exists(prop_name, f)\n \n @property\n def cluster_expansions(self):\n \"\"\"\n return expansions for each cluster where expansions is \n \n .. math::\n \\\\frac{c_s}{n_s}\n \n where :math:`c_s` is the cluster size of cluster :math:`s` and :math:`n_s` is the number of vertices for the cluster.\n \n \"\"\"\n \n if self.data.is_weighted():\n raise Exception(\"only support unweighted graph\")\n\n def f():\n ow = self.cluster_out_sum_weights\n cs = self.cluster_sizes\n return {u:v / cs[u] for u, v in ow.items()}\n \n prop_name = \"_\" + sys._getframe().f_code.co_name\n \n return self.set_if_not_exists(prop_name, f) \n\n @property\n def cluster_cut_ratios(self):\n \"\"\"\n return cut ratio for each cluster which is \n \n .. math::\n \\\\frac{c_s}{n_s(n-n_s)}\n \n where :math:`c_s` is the cluster size of cluster :math:`s`, n is the number of node of graph and :math:`n_s` is the number of vertices for the cluster.\n \n \"\"\"\n \n d = self.cluster_sizes\n n = self.num_vertices\n return {u:v / float(n - d[u]) for u, v in self.cluster_expansions.items()}\n \n @property\n def intra_cluster_densities(self):\n '''\n return internal cluster density for each cluster which is \n \n .. math::\n \\\\frac{m_s}{n_s(n-n_s)/2}\n \n where :math:`m_s` is number of edges of cluster :math:`s`, n is the number of node of graph and :math:`n_s` is the number of vertices for the cluster.\n \n '''\n if self.data.is_weighted():\n raise Exception(\"only support unweighted graph\")\n return self.unweighted_intra_cluster_densities\n \n @property\n def unweighted_intra_cluster_densities(self):\n \n def f():\n r = {}\n d = self.cluster_edge_sizes\n for cluster, n_node in self.cluster_sizes.items():\n if cluster in d:\n n_edge = d[cluster]\n else: \n n_edge = 0\n a = float(n_edge) * 2 / n_node / (n_node - 1) if n_node > 1 else 0.0\n r[cluster] = a\n return r \n\n prop_name = \"_\" + sys._getframe().f_code.co_name\n \n return self.set_if_not_exists(prop_name, f) \n \n @property\n def intra_cluster_density(self):\n return np.mean(list(self.intra_cluster_densities.values())) \n\n @property\n def inter_cluster_density(self):\n '''\n return internal cluster density for the clustring which is \n\n .. math::\n \\\\frac{|\\{ (u,v) | u \\in C_i, v \\in C_j, i \\\\neq j \\}|}{n(n-1)/2 + \\sum_{s=1}^{k} n_s(n-n_s)/2}\n\n \n where :math:`m_s` is number of edges of cluster :math:`s`, n is the number of node of graph, :math:`n_s` is the number of vertices for the cluster, :math:`C_i` is the set of nodes in i-th cluster\n \n ''' \n if self.data.is_weighted():\n raise Exception(\"only support unweighted graph\") \n return self.inter_unweighted_cluster_density\n \n @property\n def inter_unweighted_cluster_density(self):\n n_intra_edges = np.sum(list(self.cluster_edge_sizes.values()))\n n_edge = self.num_edges\n n = self.num_vertices\n d = n * (n - 1) - np.sum([u * (u - 1) for u in self.cluster_sizes.values()])\n if np.isnan(d):\n raise \"invalid number: \" +str(d)\n \n if n_edge==n_intra_edges:\n return 0.0\n else:\n return float(n_edge - n_intra_edges) * 2 / d\n\n @property\n def relative_cluster_densities(self):\n '''\n return relative cluster density for each cluster which is \n\n .. math::\n \\\\frac{deg_{intra}}{deg_{intra}+deg_{out}}\n\n where the degree is weighted degree.\n '''\n\n def f():\n df = self.edges[['src', 'dest', 'weight']]\n c_df = self.clusters[['node', 'cluster']].set_index('node')['cluster'].to_dict()\n df['src_c'] = df['src'].map(c_df) \n df['dest_c'] = df['dest'].map(c_df)\n df['is_intra'] = (df['src_c'] == df['dest_c'])\n df['is_inter'] = (df['src_c'] != df['dest_c'])\n\n a = df[df['is_intra']].groupby('src_c')['weight'].sum()\n b = df[df['is_inter']].groupby('src_c')['weight'].sum()\n c = df[df['is_inter']].groupby('dest_c')['weight'].sum()\n\n newdf = pd.concat([a, b, c], axis=1).fillna(0)\n newdf.columns = ['intra', 'inter1', 'inter2']\n newdf['density'] = newdf['intra'] / (newdf['inter1'] + newdf['inter2'] + newdf['intra'])\n \n return newdf['density'].to_dict()\n \n prop_name = \"_\" + sys._getframe().f_code.co_name\n \n return self.set_if_not_exists(prop_name, f) \n\n def snap_modularities(self, frac=1):\n import snap\n\n def f():\n G = convert.to_snap(self.data)\n m = self.num_edges\n ret = {}\n for k, v in self.clusters.groupby('cluster')['node'].apply(lambda u: list(u)).to_dict().items():\n if np.random.random() < frac:\n Nodes = snap.TInt64V()\n for nodeId in v:\n Nodes.Add(nodeId)\n mod = snap.GetModularity(G, Nodes, m)\n ret[k] = mod \n return ret \n\n prop_name = \"_\" + sys._getframe().f_code.co_name\n \n return self.set_if_not_exists(prop_name, f) \n\n @property\n def modularity(self):\n '''\n return modularity of the clustering for weighted or unweighted graph. For unweighted graph it is \n\n .. math::\n Q=1/(2m) \\sum_{i,j} (A_{ij}- \\\\frac{k_i k_j}{2m}) 1_{(i=j)}\n\n where m is the number of edges, A is the adjacency matrix, 1 is indicator function, :math:`k_i k_j` is the expected number of random edges between the two nodes. \n ''' \n return self.modularity2\n\n @property\n def modularity2(self): # another formula\n\n def f():\n c = self.sum_weight\n d = 1.0 / (c * c)\n a = np.sum(list(self.cluster_sum_intra_weights.values())) / c\n b = np.sum([u * u * d for u in self.cluster_sum_weighted_degrees.values()])\n return a - b\n \n prop_name = \"_\" + sys._getframe().f_code.co_name\n \n return self.set_if_not_exists(prop_name, f)\n \n @property\n def conductance(self): # another formula\n '''\n return conductance of a cluster S, for unweighted graph which is \n\n .. math::\n \\\\frac{Cut_S}{\\\\min (deg_S, deg_{(V \\setminus S}))}\n\n where S is a cluster \n ''' \n\n def f():\n a = self.cluster_out_sum_weights\n d = self.cluster_sum_intra_weights\n keys=set(a.keys()).union(d.keys())\n ret={}\n for u in keys:\n if u in a:\n v=a[u]\n if u in d:\n ret[u] = v / (v + d[u]) \n else:\n ret[u] = v / (v + 0) \n else:\n ret[u]=0\n return ret\n \n prop_name = \"_\" + sys._getframe().f_code.co_name\n \n return self.set_if_not_exists(prop_name, f) \n \n @property\n def normalized_cut(self): # another formula\n '''\n normalized cut\n '''\n\n def f():\n m = self.sum_weight\n a = self.cluster_out_sum_weights\n d = self.cluster_sum_intra_weights\n keys=set(a.keys()).union(d.keys())\n ret={}\n for u in keys:\n if u in a:\n v=a[u]\n if u in d:\n ret[u] = v / (v + d[u]) + v / (v + m - d[u])\n else:\n ret[u] = v / (v + 0) + v / (v + m - 0)\n else:\n ret[u]=0\n return ret\n \n prop_name = \"_\" + sys._getframe().f_code.co_name\n \n return self.set_if_not_exists(prop_name, f) \n \n @property\n def cluster_max_out_degree_fraction(self):\n '''\n max out degree fraction\n '''\n return self.cluster_out_degree_fraction[0]\n\n @property\n def cluster_avg_out_degree_fraction(self):\n '''\n average out degree fraction\n '''\n return self.cluster_out_degree_fraction[1]\n\n @property\n def cluster_flake_out_degree_fraction(self):\n '''\n Flake out degree fraction\n '''\n return self.cluster_out_degree_fraction[2] \n \n @property\n def cluster_out_degree_fraction(self):\n\n def f1():\n df = self.edges[['src', 'dest', 'weight']]\n df2 = self.edges[['dest', 'src', 'weight']]\n df2.columns = df.columns \n df = pd.concat([df, df2]);del df2 \n c_df = self.clusters[['node', 'cluster']].set_index('node')['cluster'].to_dict()\n df['src_c'] = df['src'].map(c_df) \n df['dest_c'] = df['dest'].map(c_df)\n df1 = df[(df['src_c'] != df['dest_c'])].drop(['dest_c', 'dest'], axis=1)\n df1 = df1.groupby(['src_c', 'src'])[\"weight\"].sum().reset_index()\n df1.columns = ['cluster', 'node', 'inter_weight']\n df2 = df[(df['src_c'] == df['dest_c'])].drop(['dest_c', 'dest'], axis=1)\n df2 = df.groupby(['src_c', 'src'])[\"weight\"].sum().reset_index()\n df2.columns = ['cluster', 'node', 'intra_weight']\n df = pd.merge(df1, df2, on=['cluster', 'node'], how='outer')\n return df.fillna(0)\n\n def f2():\n df = f1()\n df['odf'] = df['inter_weight'] / (df['inter_weight'] + df['intra_weight'])\n df['flake'] = (df['inter_weight'] > df['intra_weight']).astype(np.float)\n max_odf = df.groupby('cluster')['odf'].max().to_dict()\n avg_odf = df.groupby('cluster')['odf'].mean().to_dict()\n flake_odf = df.groupby('cluster')[['flake']].sum()\n d = self.cluster_sizes\n flake_odf['cluster_size'] = flake_odf.index.map(d)\n flake_odf = (flake_odf['flake'] / flake_odf['cluster_size']).to_dict()\n return max_odf, avg_odf, flake_odf\n\n prop_name = \"_\" + sys._getframe().f_code.co_name\n \n return self.set_if_not_exists(prop_name, f2)\n \n @property\n def separability(self):\n '''\n separability :math:`m_s/c_s`\n '''\n \n a = self.cluster_out_sum_weights\n b = self.cluster_sum_intra_weights\n keys=set(a.keys()).union(b.keys())\n ret={}\n for u in keys:\n if u in b:\n if u in a:\n ret[u] = b[u] / float(a[u]) \n else:\n ret[u] = b[u]\n else:\n ret[u]=0\n return ret\n \n @property\n def cluster_clustering_coefficient(self):\n '''\n (global) clustering coefficient\n '''\n\n def f1(edges):\n import igraph \n g = igraph.Graph(edges=edges[['src', 'dest']].values.tolist(), directed=False) \n return g.transitivity_undirected()\n\n def f2():\n df = self.edges[['src', 'dest']]\n c_df = self.clusters[['node', 'cluster']].set_index('node')['cluster'].to_dict()\n df['src_c'] = df['src'].map(c_df) \n df['dest_c'] = df['dest'].map(c_df)\n df = df[(df['src_c'] == df['dest_c'])]\n \n ret = {}\n for i in self.cluster_indexes:\n edges = df[df['src_c'] == i]\n ret[i] = f1(edges)\n if np.isnan(ret[i]):\n ret[i]=0.0\n return ret \n \n prop_name = \"_\" + sys._getframe().f_code.co_name\n \n return self.set_if_not_exists(prop_name, f2)\n\n @property\n def cluster_local_clustering_coefficient(self):\n '''\n local clustering coefficient\n '''\n\n def f1(edges):\n import igraph \n g = igraph.Graph(edges=edges[['src', 'dest']].values.tolist(), directed=False) \n return g.transitivity_local_undirected()\n\n def f2():\n df = self.edges[['src', 'dest']]\n c_df = self.clusters[['node', 'cluster']].set_index('node')['cluster'].to_dict()\n df['src_c'] = df['src'].map(c_df) \n df['dest_c'] = df['dest'].map(c_df)\n df = df[(df['src_c'] == df['dest_c'])]\n \n ret = {}\n for i in self.cluster_indexes:\n edges = df[df['src_c'] == i]\n ret[i] = f1(edges)\n return ret \n \n prop_name = \"_\" + sys._getframe().f_code.co_name\n \n return self.set_if_not_exists(prop_name, f2)\n\n def graph_tool_draw(self, node_size=6, output_size=(1000, 500), edge_pen_width=1,\n edge_color=[0.0, 0, 0, 0.05], cmap='nipy_spectral', vertex_shape='circle', layout=None):\n layouts = 'sfdp_layout fruchterman_reingold_layout arf_layout planar_layout random_layout'.split(\" \")\n assert layout is None or layout in layouts\n \n import graph_tool.stats\n import graph_tool.draw \n import matplotlib.pyplot as plt \n g_gtool = self.data.to_graph_tool_graph()\n graph_tool.stats.remove_self_loops(g_gtool)\n \n node_size = g_gtool.new_vertex_property(\"double\", np.zeros(g_gtool.num_vertices()) + node_size)\n c_map = plt.get_cmap(cmap)\n n_cluster = self.clusterobj.num_cluster\n d = self.clusterobj.value(erase_overlap=self.clusterobj.is_overlap).set_index('node')['cluster'].to_dict()\n if layout is None: layout = 'sfdp_layout'\n \n # pos = gall.draw.sfdp_layout(g_gtool)\n pos = getattr(graph_tool.draw, layout)(g_gtool)\n cluster_colors = np.zeros((g_gtool.num_vertices()))\n v = 255.0 / (1 + n_cluster)\n for i in range(len(cluster_colors)):\n cluster_colors[i] = d[i] * v if i in d else (n_cluster + 1) * v\n \n node_colours = g_gtool.new_vertex_property(\"double\", cluster_colors)\n graph_tool.draw.graph_draw(g_gtool, pos, output_size=output_size,\n vertex_size=node_size,\n vertex_fill_color=node_colours,\n vorder=node_size,\n edge_pen_width=edge_pen_width,\n edge_color=edge_color,\n vprops={\"shape\":vertex_shape},\n vcmap=c_map)\n\n\nclass ClusterComparator(object):\n '''\n metrics for two clustering. e.g. nmi, overlap nmi etc.\n In case that some metrics requires ground truth, make ground truth as the first parameter.\n \n When calculating a metric that does not support overlapping, the overlapped nodes are removed or retrun None\n '''\n\n def __init__(self, clusteringobj1, clusteringobj2):\n '''\n clusteringobj1 will be taken as ground truth if necessary.\n \n :param clusteringobj1: a :class:`gct.Clustering` object or refer to the *groundtruth* parameter of :meth:`gct.from_edgelist`\n :param clusteringobj2: a :class:`gct.Clustering` object or refer to the *groundtruth* parameter of :meth:`gct.from_edgelist` \n '''\n \n self.logger = utils.get_logger(\"{}\".format(type(self).__name__))\n\n def to_obj(clusterobj):\n if isinstance(clusterobj, Clustering):\n return clusterobj\n elif isinstance(clusterobj, Result):\n return Clustering(clusterobj.clustering(as_dataframe=True))\n elif isinstance(clusterobj, pd.DataFrame) or isinstance(clusterobj, list) \\\n or isinstance(clusterobj, np.ndarray) or isinstance(clusterobj, str) or isinstance(clusterobj, dict):\n return Clustering(clusterobj)\n else:\n raise Exception(\"Unsupported \" + str(type(clusterobj)))\n \n self.clusterobj1 = to_obj(clusteringobj1) \n self.clusterobj2 = to_obj(clusteringobj2)\n \n if self.clusterobj1.is_overlap or self.clusterobj2.is_overlap: \n self.overlap = True \n else:\n self.overlap = False \n \n def clean():\n df1 = self.clusterobj1.value(self.clusterobj1.is_overlap)\n df2 = self.clusterobj2.value(self.clusterobj2.is_overlap)\n nodes = set(df1['node']).union(set(df2['node']))\n \n for n in nodes.difference(set(df1['node'])):\n df1=df1.append({'node':n, \"cluster\": -9999}, ignore_index=True)\n for n in nodes.difference(set(df2['node'])):\n df2=df2.append({'node':n, \"cluster\": -9999}, ignore_index=True)\n self.logger.info (\"resulting {} nodes out of {},{}\".format(len(nodes), len(df1), len(df2)))\n df1 = df1[df1['node'].isin(nodes)].set_index('node')\n df2 = df2[df2['node'].isin(nodes)].set_index('node').loc[df1.index]\n df1.index.name = 'node'\n df2.index.name = 'node'\n return df1, df2 \n\n clean_clusterobj1, clean_clusterobj2 = clean()\n self.clean_clusterobj1, self.clean_clusterobj2 =clean_clusterobj1, clean_clusterobj2 \n \n @property \n def ground_truth(self): # assume the first one is ground truth\n '''\n Alias for for the first Clustering of constructor\n '''\n return self.clusterobj1\n \n @property \n def clean_ground_truth(self): # assume the first one is ground truth\n return self.clean_clusterobj1\n\n @property \n def predition(self):\n '''\n Alias for for the second Clustering of constructor\n ''' \n return self.clusterobj2\n\n @property \n def clean_prediction(self): \n return self.clean_clusterobj2\n \n def sklean_nmi(self):\n '''\n sklearn `normalized_mutual_info_score `_\n '''\n if False and self.overlap:\n return None \n else:\n prop_name = \"_\" + sys._getframe().f_code.co_name \n\n def f():\n from sklearn.metrics.cluster import normalized_mutual_info_score\n return normalized_mutual_info_score(self.clean_clusterobj1['cluster'].values, self.clean_clusterobj2['cluster'].values)\n\n return utils.set_if_not_exists(self, prop_name, f)\n \n def sklean_ami(self):\n '''\n sklearn `adjusted_mutual_info_score `_\n '''\n if False and self.overlap:\n return None \n else:\n prop_name = \"_\" + sys._getframe().f_code.co_name \n\n def f():\n from sklearn.metrics.cluster import adjusted_mutual_info_score \n return adjusted_mutual_info_score(self.clean_clusterobj1['cluster'].values, self.clean_clusterobj2['cluster'].values)\n\n return utils.set_if_not_exists(self, prop_name, f)\n\n def sklean_ars(self):\n '''\n sklearn `adjusted_rand_score `_\n '''\n if False and self.overlap:\n return None \n else:\n prop_name = \"_\" + sys._getframe().f_code.co_name \n\n def f():\n from sklearn.metrics.cluster import adjusted_rand_score \n return adjusted_rand_score(self.clean_clusterobj1['cluster'].values, self.clean_clusterobj2['cluster'].values)\n\n return utils.set_if_not_exists(self, prop_name, f)\n\n def sklean_completeness(self):\n '''\n sklearn `completeness_score `_\n ''' \n if self.overlap:\n print(\"warning! completeness for overlap graph \")\n if True:\n prop_name = \"_\" + sys._getframe().f_code.co_name \n\n def f():\n from sklearn.metrics.cluster import completeness_score \n return completeness_score(self.clean_ground_truth['cluster'].values, self.clean_prediction['cluster'].values)\n\n return utils.set_if_not_exists(self, prop_name, f)\n\n def GenConvNMI(self, sync=None, id_remap=None, nmis=None, fnmi=True, risk=None, error=None, fast=None, membership=None, retain_dups=None):\n '''\n A wrapper for https://github.com/eXascaleInfolab/GenConvNMI\n \n Arguments\n\n Usage: ./gecmi [options] \n clusters - clusters file in the `CNL format `_, where each line lists space separated ids of the cluster members\n\n ============================= ========================================================\n -h [ --help ] produce help message\n --input arg name of the input files\n -s [ --sync ] synchronize the node base omitting the \n non-matching nodes for the fair evaluation. The \n node base is selected automatically as a \n clustering having the least number of nodes.\n -i [ --id-remap ] remap ids allowing arbitrary input ids \n (non-contiguous ranges), otherwise ids should \n form a solid range and start from 0 or 1\n -n [ --nmis ] output both NMI [max] and NMI_sqrt\n -f [ --fnmi ] evaluate also FNMI, includes '-n'\n -r [ --risk ] arg (=0.01) probability of value being outside\n -e [ --error ] arg (=0.01) admissible error\n -a [ --fast ] apply fast approximate evaluations that are less\n accurate, but much faster on large networks\n -m [--membership] arg (=1) average expected membership of nodes in the \n clusters, > 0, typically >= 1\n -d [ --retain-dups ] retain duplicated clusters if any instead of filtering them out (not recommended)\n ============================= ========================================================\n \n Reference\n \n =============== =============================================================================================================================================================================================================================================================================================\n overlap nmi Esquivel, Alcides Viamontes, and Martin Rosvall. \"Comparing network covers using mutual information.\" arXiv preprint arXiv:1202.0425 (2012).\n fair nmi Amelio, Alessia, and Clara Pizzuti. \"Is normalized mutual information a fair measure for comparing community detection methods?.\" Proceedings of the 2015 IEEE/ACM International Conference on Advances in Social Networks Analysis and Mining 2015. ACM, 2015.\n =============== =============================================================================================================================================================================================================================================================================================\n \n '''\n \n params = locals(); del params['self'];del params['sync']\n params = {u.replace('_', '-'):v for u, v in params.items() if v}\n nonbools = ['risk', 'error', 'membership']\n cmd = [config.GECMI_PROG]\n for u, v in params.items():\n if u in nonbools:\n cmd.append(\"--{} {}\".format(u, v))\n else:\n if v:\n cmd.append (\"--{}\".format(u))\n\n if sync:\n cmd.append(\"--sync -\")\n with utils.TempDir() as tmp_dir:\n cnl1 = self.clusterobj1.make_cnl_file(filepath=os.path.join(tmp_dir, 'cluster1.cnl'))\n cnl2 = self.clusterobj2.make_cnl_file(filepath=os.path.join(tmp_dir, 'cluster2.cnl'))\n cmd.append(cnl1)\n cmd.append(cnl2)\n cmd.append(\"> nmioutput\")\n cmd = \" \".join(cmd) \n self.logger.info(\"Running \" + cmd)\n with open(os.path.join(tmp_dir, \"tmpcmd\"), 'wt') as f: f.write(cmd) \n timecost, status = utils.timeit(lambda: utils.shell_run_and_wait(\"bash tmpcmd\", tmp_dir))\n if status != 0: \n raise Exception(\"Run command with error status code {}\".format(status))\n \n with open (os.path.join(tmp_dir, \"nmioutput\"), \"r\") as output:\n line = [u.strip() for u in output.readlines() if not u.startswith('#')][0]\n line = line.split(\";\")[0]\n if not nmis and not fnmi: \n res = {'NMI_max':float(line)}\n else:\n lst = [u.split(\":\") for u in line.split(\",\")]\n res = dict([ (k.strip(), float(v.strip())) for k, v in lst])\n return res \n\n def OvpNMI(self, sync=None, allnmi=None, omega=None, membership=None, verbose=None):\n '''\n A wrapper for https://github.com/eXascaleInfolab/OvpNMI\n\n Compare sets of clusters by their members (nodes) using various measures (NMI,\n Omega) and considering overlaps\n \n Arguments\n \n Usage: onmi [OPTIONS] clsfile1 clsfile2\n \n ========================= =========================================================\n -a, --allnmis output all NMIs (sqrt and sum-denominators, LFK besides the max-denominator) (default=off)\n -m, --membership=FLOAT average expected membership of nodes in the clusters, > 0, typically >= 1 (default=`1')\n -o, --omega print the Omega measure (can be slow) (default=off)\n -v, --verbose detailed debugging (default=off)\n ========================= =========================================================\n \n Reference\n \n =============== =============================================================================================================================================================================================================================================================================================\n overlap nmi McDaid, Aaron F., Derek Greene, and Neil Hurley. \"Normalized mutual information to evaluate overlapping community finding algorithms.\" arXiv preprint arXiv:1110.2515 (2011).\n overlap nmi Lancichinetti, Andrea, Santo Fortunato, and János Kertész. \"Detecting the overlapping and hierarchical community structure in complex networks.\" New Journal of Physics 11.3 (2009): 033015.\n Omega Collins, Linda M., and Clyde W. Dent. \"Omega: A general formulation of the rand index of cluster recovery suitable for non-disjoint solutions.\" Multivariate Behavioral Research 23.2 (1988): 231-242.\n =============== =============================================================================================================================================================================================================================================================================================\n \n ''' \n if self.clusterobj1.num_cluster < 2 or self.clusterobj2.num_cluster < 2:\n return {\"NMImax\":None}\n params = locals(); del params['self'];del params['sync']\n params = {u.replace('_', '-'):v for u, v in params.items() if v}\n nonbools = [ 'membership']\n cmd = [config.ONMI_PROG]\n for u, v in params.items():\n if u in nonbools:\n cmd.append(\"--{} {}\".format(u, v))\n else:\n if v:\n cmd.append (\"--{}\".format(u))\n\n if sync:\n cmd.append(\"--sync\")\n\n with utils.TempDir() as tmp_dir:\n # tmp_dir=\"/tmp/abc\"\n cnl1 = self.clusterobj1.make_cnl_file(filepath=os.path.join(tmp_dir, 'cluster1.cnl'))\n cnl2 = self.clusterobj2.make_cnl_file(filepath=os.path.join(tmp_dir, 'cluster2.cnl'))\n cmd.append(cnl1)\n cmd.append(cnl2)\n cmd.append(\"> ovpnmioutput\")\n cmd = \" \".join(cmd) \n self.logger.info(\"Running \" + cmd)\n with open(os.path.join(tmp_dir, \"tmpcmd\"), 'wt') as f: f.write(cmd) \n timecost, status = utils.timeit(lambda: utils.shell_run_and_wait(\"bash tmpcmd\", tmp_dir))\n if status != 0: \n self.logger.error(Exception(\"Run command with error status code {}\".format(status)))\n return {\"NMImax\":None} \n \n with open (os.path.join(tmp_dir, \"ovpnmioutput\"), \"r\") as output:\n line = [u.strip() for u in output.readlines() if not u.startswith('#')][0]\n line = line.split(\";\")[0]\n if not allnmi and not omega: \n res = {'NMImax':float(line)}\n else:\n lst = [u.split(\":\")[:2] for u in line.split(\",\")]\n lst = [ (k.strip(), v.strip().split(\" \")[0]) for k, v in lst]\n res = dict([ (k.strip(), float(v.strip())) for k, v in lst])\n return res \n\n def xmeasure_nmi(self, sync=None, all=False, membership=None, detailed=None):\n '''\n A wrapper for https://github.com/eXascaleInfolab/xmeasures.\n \n Normalized Mutual Information, normalized by either max or also\n sqrt, avg and min information content denominators.\n \n ATTENTION: This is a standard NMI, which should be used ONLY for the HARD\n partitioning evaluation (non-overlapping clustering on a single resolution).\n It penalizes overlapping and multi-resolution structures.\n \n Arguments\n\n Usage: onmi [OPTIONS] clsfile1 clsfile2\n \n ========================= =========================================================\n -m, --membership=FLOAT average expected membership of the nodes in the\n clusters, > 0, typically >= 1. Used only to\n facilitate estimation of the nodes number on\n the containers preallocation if this number\n is not specified in the file header.\n (default=`1')\n\n -n, --nmi evaluate NMI (Normalized Mutual Information),\n applicable only to the non-overlapping\n clusters (default=off)\n -a, --all evaluate all NMIs using sqrt, avg and min\n denominators besides the max one\n (default=off)\n -d, --detailed detailed (verbose) results output\n (default=off)\n ========================= =========================================================\n \n \n ''' \n \n params = locals(); del params['self'];del params['sync']\n params = {u.replace('_', '-'):v for u, v in params.items() if v}\n nonbools = [ 'membership']\n cmd = [config.XMEASURES_PROG]\n for u, v in params.items():\n if u in nonbools:\n cmd.append(\"--{} {}\".format(u, v))\n else:\n if v:\n cmd.append (\"--{}\".format(u))\n \n cmd.append(\"--nmi\") \n if sync:\n cmd.append(\"--sync\")\n\n with utils.TempDir() as tmp_dir:\n cnl1 = Clustering(self.clean_ground_truth.reset_index()).make_cnl_file(filepath=os.path.join(tmp_dir, 'cluster1.cnl'))\n cnl2 = Clustering(self.clean_prediction.reset_index()).make_cnl_file(filepath=os.path.join(tmp_dir, 'cluster2.cnl'))\n cmd.append(cnl1)\n cmd.append(cnl2)\n cmd.append(\"> xmeasurenmioutput\")\n cmd = \" \".join(cmd) \n self.logger.info(\"Running \" + cmd)\n with open(os.path.join(tmp_dir, \"tmpcmd\"), 'wt') as f: f.write(cmd) \n timecost, status = utils.timeit(lambda: utils.shell_run_and_wait(\"bash tmpcmd\", tmp_dir))\n if status != 0: \n raise Exception(\"Run command with error status code {}\".format(status))\n \n with open (os.path.join(tmp_dir, \"xmeasurenmioutput\"), \"r\") as output:\n line = [u.strip() for u in output.readlines() if not u.startswith('=')][-1]\n line = line.split(\";\")[0]\n if not all: \n res = {'NMI_max':float(line)}\n else:\n lst = [u.split(\":\")[:2] for u in line.split(\",\")]\n lst = [ (k.strip(), v.strip().split(\" \")[0]) for k, v in lst]\n res = dict([ (k.strip(), float(v.strip())) for k, v in lst])\n return res \n\n def xmeasure(self, sync=None, ovp=None, unique=None, omega=None, extended=None, f1=None, kind=False, membership=None, detailed=None):\n '''\n Evaluating measures are:\n \n - OI: Omega Index (a fuzzy version of the Adjusted Rand Index, identical to the Fuzzy Rand Index), which yields the same value as Adjusted Rand Index when applied to the non-overlapping clusterings.\n - [M]F1: various [mean] F1 measures of the Greatest (Max) Match including the Average F1-Score (suggested by J. Leskovec) with optional weighting. NOTE: There are 3 matching policies available for each kind of F1. The most representative evaluation is performed by the F1p with combined matching policy (considers both micro and macro weighting).\n \n \n Arguments\n \n ========================== ==========================================================\n -O, --ovp evaluate overlapping instead of the\n multi-resolution clusters, where max matching\n for any shared member between R overlapping\n clusters is 1/R (the member is shared)\n instead of 1 (the member fully belongs to\n each [hierarchical sub]group) for the member\n belonging to R distinct clusters on R\n resolutions.\n NOTE: It has no effect for the Omega Index\n evaluation. (default=off)\n -q, --unique ensure on loading that all cluster members are\n unique by removing all duplicates.\n (default=off)\n -m, --membership=FLOAT average expected membership of the nodes in the\n clusters, > 0, typically >= 1. Used only to\n facilitate estimation of the nodes number on\n the containers preallocation if this number\n is not specified in the file header.\n (default=`1')\n -d, --detailed detailed (verbose) results output\n (default=off)\n \n ========================== ========================================================== \n \n Omega Index options :\n \n ========================== ========================================================== \n -o, --omega evaluate Omega Index (a fuzzy version of the\n Adjusted Rand Index, identical to the Fuzzy\n Rand Index and on the non-overlapping\n clusterings equals to ARI). (default=off)\n -x, --extended evaluate extended (Soft) Omega Index, which\n does not excessively penalize distinctly\n shared nodes. (default=off)\n \n ========================== ========================================================== \n \n Mean F1 options:\n \n ========================== ========================================================== \n -f, --f1[=ENUM] evaluate mean F1 of the [weighted] average of\n the greatest (maximal) match by F1 or partial\n probability.\n NOTE: F1p <= F1h <= F1a, where:\n \n - p (F1p or Ph): Harmonic mean (F1) of two [weighted] averages of the Partial Probabilities, the most indicative as satisfies the largest number of the Formal Constraints (homogeneity, completeness and size/quantity except the rag bag in some cases);\n - h (F1h): Harmonic mean (F1) of two [weighted] averages of all local F1 (harmonic means of the Precision and Recall of the best matches of the clusters);\n - a (F1a): Arithmetic mean (average) of two [weighted] averages of all local F1, the least discriminative and satisfies the lowest number of the Formal Constraints.\n \n (possible values=\"partprob\",\"harmonic\", \"average\" default=`partprob')\n \n -k, --kind[=ENUM] kind of the matching policy:\n \n - w - Weighted by the number of nodes in each cluster\n - u - Unweighed, where each cluster is treated equally\n - c - Combined(w, u) using geometric mean (drops the value not so much as harmonic mean)\n \n (possible values=\"weighted\", \"unweighed\", \"combined\" default=`weighted')\n ========================== ==========================================================\n\n Reference\n \n ======================= =============================================================================================================================================================================================================================================================================================\n F1a (Average F1-Score) Yang, Jaewon, and Jure Leskovec. \"Overlapping community detection at scale: a nonnegative matrix factorization approach.\" Proceedings of the sixth ACM international conference on Web search and data mining. ACM, 2013.\n Omega Collins, Linda M., and Clyde W. Dent. \"Omega: A general formulation of the rand index of cluster recovery suitable for non-disjoint solutions.\" Multivariate Behavioral Research 23.2 (1988): 231-242.\n ======================= =============================================================================================================================================================================================================================================================================================\n\n \n ''' \n \n assert not(omega is None and f1 is None)\n params = locals(); del params['self'];del params['sync']\n params = {u.replace('_', '-'):v for u, v in params.items() if v}\n if f1 is not None: assert f1 in ['p', 'h', 'a']\n nonbools = [ 'membership', 'f1', 'kind']\n cmd = [config.XMEASURES_PROG]\n for u, v in params.items():\n if u in nonbools:\n cmd.append(\"--{}={}\".format(u, v))\n else:\n if v:\n cmd.append (\"--{}\".format(u))\n \n if sync:\n cmd.append(\"--sync\")\n\n with utils.TempDir() as tmp_dir:\n cnl1 = Clustering(self.clean_ground_truth.reset_index()).make_cnl_file(filepath=os.path.join(tmp_dir, 'cluster1.cnl'))\n cnl2 = Clustering(self.clean_prediction.reset_index()).make_cnl_file(filepath=os.path.join(tmp_dir, 'cluster2.cnl'))\n cmd.append(cnl1)\n cmd.append(cnl2)\n cmd.append(\"> xmeasureoutput\")\n cmd = \" \".join(cmd) \n self.logger.info(\"Running \" + cmd)\n with open(os.path.join(tmp_dir, \"tmpcmd\"), 'wt') as f: f.write(cmd) \n timecost, status = utils.timeit(lambda: utils.shell_run_and_wait(\"bash tmpcmd\", tmp_dir))\n if status != 0: \n raise Exception(\"Run command with error status code {}\".format(status))\n \n with open (os.path.join(tmp_dir, \"xmeasureoutput\"), \"r\") as output:\n lines = [u.strip() for u in output.readlines() if not u.startswith('=') and not \";\" in u]\n ret = {}\n assert len(lines) in [2, 4]\n ret [lines[0].split(\" \")[0].strip()] = float(lines[1])\n if len(lines) == 4:\n ret [lines[2].split(\" \")[0].strip()] = float(lines[3])\n return ret, params \n","sub_path":"python/src/gct/metrics/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":50068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"78379508","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom pygame import *\nimport os\nimport pyganim\nfrom pygame.locals import *\n\nPLATFORM_WIDTH = 32\nPLATFORM_HEIGHT = 32\nPLATFORM_COLOR = \"black\"\nICON_DIR = os.path.dirname(__file__)\n\nANIMATION_MONSTERHORYSONTAL = [('%s/monsters/mushroom1.png' % ICON_DIR),\n ('%s/monsters/fire2.png' % ICON_DIR )]\n\nANIMATION_BLOCKTELEPORT = [\n ('%s/blocks/portal2.png' % ICON_DIR),\n ('%s/blocks/portal1.png' % ICON_DIR)]\n \nANIMATION_PRINCESS = [\n ('%s/blocks/princess_l.png' % ICON_DIR),\n ('%s/blocks/princess_r.png' % ICON_DIR)]\n\nANIMATION_INBLOCKTELEPORT = [\n ('%s/blocks/invisiblePortal.png' % ICON_DIR),\n ('%s/blocks/invisiblePortal2.png' % ICON_DIR)]\n\n \nclass Platform(sprite.Sprite):\n def __init__(self, x, y):\n sprite.Sprite.__init__(self)\n self.image = Surface((PLATFORM_WIDTH, PLATFORM_HEIGHT))\n self.image.fill(Color(PLATFORM_COLOR))\n self.image = image.load(\"%s/blocks/platform.png\" % ICON_DIR)\n self.image.set_colorkey(Color(PLATFORM_COLOR))\n self.rect = Rect(x, y, PLATFORM_WIDTH, PLATFORM_HEIGHT)\n \n\nclass BlockDie(Platform):\n def __init__(self, x, y):\n Platform.__init__(self, x, y)\n self.image = image.load(\"%s/blocks/dieBlock.png\" % ICON_DIR)\n\n\nclass BlockTeleport(Platform):\n def __init__(self, x, y, goX, goY):\n Platform.__init__(self, x, y)\n self.goX = goX # координаты назначения перемещения\n self.goY = goY # координаты назначения перемещения\n boltAnim = []\n for anim in ANIMATION_BLOCKTELEPORT:\n boltAnim.append((anim, 0.5))\n self.boltAnim = pyganim.PygAnimation(boltAnim)\n self.boltAnim.play()\n\n\n def update(self):\n self.image.fill(Color(PLATFORM_COLOR))\n self.boltAnim.blit(self.image, (0, 0))\n\n\nclass InvisibleBlockTeleport(Platform):\n def __init__(self, x, y, goX, goY):\n Platform.__init__(self, x, y)\n self.goX = goX # координаты назначения перемещения\n self.goY = goY # координаты назначения перемещения\n self.image = image.load(\"%s/blocks/invisiblePortal.png\" % ICON_DIR)\n\n def update(self):\n self.image.fill(Color(PLATFORM_COLOR))\n\n\nclass Princess(Platform):\n def __init__(self, x, y):\n Platform.__init__(self, x, y)\n boltAnim = []\n for anim in ANIMATION_PRINCESS:\n boltAnim.append((anim, 0.8))\n self.boltAnim = pyganim.PygAnimation(boltAnim)\n self.boltAnim.play()\n \n def update(self):\n self.image.fill(Color(PLATFORM_COLOR))\n self.boltAnim.blit(self.image, (0, 0))\n\n\nclass Saw(Platform):\n def __init__(self, x, y):\n Platform.__init__(self, x, y)\n self.original = image.load(\"%s/blocks/saw.png\" % ICON_DIR)\n self.image = self.original\n self.angle = 0\n\n def update(self):\n rotated_image = pygame.transform.rotate(self.original, self.angle)\n rotated_image.fill(Color(PLATFORM_COLOR))\n self.angle += 3\n pygame.display.update()\n","sub_path":"blocks.py","file_name":"blocks.py","file_ext":"py","file_size_in_byte":3229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"16979946","text":"import numpy as np\nimport pandas as pd\nimport torch\n\nfrom push_task_utils.extrapolation import extrapolate, make_infer_callback_for_forward_model\nfrom cross_entropy.cross_entropy_planner import CrossEntropyPlanner\nfrom experiments.push_model_learning import *\n\n# PATHS\nFORWARD_MODEL_PATH = f\"{RESULTS_PATH}/forward_model\"\n\n# CE METHOD PARAMS\nCE_BATCH_SIZE = 2048\nNUM_ITERATIONS = 150\nSIGMA = 1e-2 # exploration param (sigma = 1 -> 1 std = valid sampling range)\nALPHA = 1.0 # update smoothing param (alpha = 1 -> no smoothing)\nNUM_EXAMPLES = 10\n\nif __name__ == \"__main__\":\n\n forward_model = ForwardModel(\n num_state_dims=NUM_STATE_DIMS,\n num_action_dims=NUM_ACTION_DIMS,\n hidden_layer_sizes=HIDDEN_LAYER_SIZES\n )\n forward_model.load_state_dict(torch.load(f\"{FORWARD_MODEL_PATH}/forward_model_params.pt\"))\n ce_planner = CrossEntropyPlanner(\n forward_model=forward_model,\n batch_size=CE_BATCH_SIZE,\n num_iterations=NUM_ITERATIONS,\n sigma=SIGMA,\n alpha=ALPHA\n )\n infer = make_infer_callback_for_forward_model(ce_planner)\n\n errors = []\n ground_truth_pushes = []\n predicted_pushes = []\n for i in range(NUM_EXAMPLES):\n\n # Sample push\n state, goal_state, (action_1, action_2) = ce_planner.sampler.environment.sample_multi_step_push(seed=i)\n\n final_state, (predicted_action_1, predicted_action_2) = extrapolate(\n state=state,\n goal_state=goal_state,\n infer=infer,\n env=ce_planner.sampler.environment\n )\n\n # Record push data for videos\n ground_truth_pushes.append(\n dict(\n obj_x=state[0],\n obj_y=state[1],\n start_push_x_1=action_1[0],\n start_push_y_1=action_1[1],\n end_push_x_1=action_1[2],\n end_push_y_1=action_1[3],\n start_push_x_2=action_2[0],\n start_push_y_2=action_2[1],\n end_push_x_2=action_2[2],\n end_push_y_2=action_2[3]\n )\n )\n predicted_pushes.append(\n dict(\n obj_x=state[0],\n obj_y=state[1],\n start_push_x_1=predicted_action_1[0],\n start_push_y_1=predicted_action_1[1],\n end_push_x_1=predicted_action_1[2],\n end_push_y_1=predicted_action_1[3],\n start_push_x_2=predicted_action_2[0],\n start_push_y_2=predicted_action_2[1],\n end_push_x_2=predicted_action_2[2],\n end_push_y_2=predicted_action_2[3]\n )\n )\n\n # Calculate errors\n errors.append(\n dict(\n action_1_error=np.linalg.norm(action_1 - predicted_action_1, 2),\n action_2_error=np.linalg.norm(action_2 - predicted_action_2, 2),\n state_error=np.linalg.norm(goal_state - final_state, 2)\n )\n )\n\n pd.DataFrame(errors).to_csv(f\"{FORWARD_MODEL_PATH}/forward_model_extrapolation_errors.csv\")\n pd.DataFrame(ground_truth_pushes).to_csv(f\"{FORWARD_MODEL_PATH}/ground_truth_two_step_pushes.csv\")\n pd.DataFrame(ground_truth_pushes).to_csv(f\"{FORWARD_MODEL_PATH}/predicted_two_step_pushes.csv\")\n","sub_path":"src/experiments/push_forward_model_extrapolation.py","file_name":"push_forward_model_extrapolation.py","file_ext":"py","file_size_in_byte":3279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"33702586","text":"# -*- coding: utf-8 -*-\nfrom model.contact import Contact\nimport random\nimport string\nimport os.path\nimport jsonpickle\nimport getopt\nimport sys\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=6\nf=\"data/contacts.json\"\n\nfor o, a in opts:\n if o==\"-n\":\n n=int(a)\n elif o==\"-f\":\n f=a\n\ndef random_string(prefix, maxlen):\n symbols = string.ascii_letters+string.digits\n return prefix+\"\".join([random.choice(symbols) for i in range(random.randrange(1, maxlen))])\n\ntestdata=[Contact(firstname=\"\", lastname=\"\", address=\"\", nickname=\"\", company=\"\", title=\"\", fax=\"\", home=\"\", mobile=\"\",\n work=\"\", email=\"\")] + [\n Contact(firstname=random_string(\"firstname\", 10), lastname=random_string(\"lastname\", 10), nickname=random_string(\"nikname\", 10), title=\"title\",\n company=\"company\", address=\"address\", home=\"home\", mobile=\"111111\", work=\"222222\",\n fax=\"333333\", email=\"yeroshchenko@gmail.com\", bday=\"17\", bmonth=\"July\", byear=\"2000\")\n for i in range(n)\n]\n\n\nfile = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"..\", f)\n\nwith open(file, \"w\") as fw:\n jsonpickle.set_encoder_options(\"json\", indent=2)\n fw.write(jsonpickle.encode(testdata))\n","sub_path":"generator/contact.py","file_name":"contact.py","file_ext":"py","file_size_in_byte":1354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"56522301","text":"import os\nimport logging\nimport datetime\nfrom sqlalchemy import create_engine\nfrom sqlalchemy import Column, Integer, Boolean, DateTime, MetaData, Table, String, UniqueConstraint\nfrom sqlalchemy import Index, select, update, insert\nfrom sqlalchemy.sql import func\nfrom sqlalchemy.dialects import postgresql\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.exc import IntegrityError\n\nlogging.basicConfig(format='%(asctime)s %(name)s %(levelname)s %(message)s')\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\n\ndef get_db_engine():\n engine = create_engine(os.getenv('FCHAN_DB'))\n return engine\n\n\ndef get_status_table(board):\n db = os.getenv('FCHAN_DB')\n engine = create_engine(db)\n metadata = MetaData(engine)\n table_name = '{}_state'.format(board)\n poll_status = Table(\n table_name,\n metadata,\n Column('id', Integer, primary_key=True),\n Column('thread', Integer, unique=True, index=True),\n Column('archived', Boolean),\n Column('replies', postgresql.JSONB),\n Column('created_at', DateTime(timezone=True), server_default=func.now()),\n Column('modified_at', DateTime(timezone=True), onupdate=func.now())\n )\n if not engine.dialect.has_table(engine, table_name):\n poll_status.create()\n\n return poll_status\n\n\ndef get_board_staging_table(board):\n db = os.getenv('FCHAN_DB')\n engine = create_engine(db)\n metadata = MetaData(db)\n table_name = '{}_stage'.format(board)\n data_table = Table(\n table_name,\n metadata,\n Column('id', Integer, primary_key=True),\n Column('parent', Integer),\n Column('chan_id', Integer, unique=True),\n Column('created_at', postgresql.TIMESTAMP),\n Column('clean_text', String),\n Column('raw', postgresql.JSONB),\n\n Index('ix_pol_ts', 'created_at')\n )\n if not engine.dialect.has_table(engine, table_name):\n data_table.create()\n\n return data_table\n\n\ndef get_bigram_table(daily):\n db = os.getenv('FCHAN_DB')\n engine = create_engine(db)\n metadata = MetaData(engine)\n table_name = 'bigram_daily'\n poll_status = Table(\n table_name,\n metadata,\n Column('id', Integer, primary_key=True),\n Column('thread', Integer, unique=True, index=True),\n Column('archived', Boolean),\n Column('replies', postgresql.JSONB),\n Column('created_at', DateTime(timezone=True), server_default=func.now()),\n Column('modified_at', DateTime(timezone=True), onupdate=func.now())\n )\n if not engine.dialect.has_table(engine, table_name):\n poll_status.create()\n\n return poll_status\n\n\ndef get_url_table():\n db = os.getenv('FCHAN_DB')\n engine = create_engine(db)\n metadata = MetaData(db)\n table_name = 'url_stage'\n data_table = Table(\n table_name,\n metadata,\n Column('id', Integer, primary_key=True),\n Column('url', String),\n Column('chan_id', Integer),\n Column('reply_to', Integer),\n Column('created_at', postgresql.TIMESTAMP),\n Column('subject', String),\n Column('country', String),\n\n UniqueConstraint('url', 'chan_id', name='uix_1'),\n Index('ix_url_ts', 'created_at')\n )\n if not engine.dialect.has_table(engine, table_name):\n data_table.create()\n return data_table\n\n\ndef mark_thread_archived(thread, engine, table):\n Session = sessionmaker(engine)\n session = Session()\n u = update(table)\n u = u.values({\"archived\": True})\n u = u.where(table.c.thread == thread)\n session.execute(u)\n session.commit()\n\n\ndef get_last_active(engine, table):\n q = select([table]).where(table.c.archived == False)\n with engine.connect() as conn:\n last_active = conn.execute(q)\n return last_active\n\n\ndef get_or_create(session, table, thread):\n instance = session.query(table).filter_by(thread=thread, archived=False).first()\n if instance:\n return instance\n else:\n try:\n i = insert(table)\n i = i.values({\"thread\": thread, \"archived\": False})\n session.execute(i)\n session.commit()\n except IntegrityError as e:\n logger.info(e)\n\n\ndef write_state(ids, engine, table):\n Session = sessionmaker(engine)\n session = Session()\n for id_ in ids:\n get_or_create(session, table, id_)\n\n\ndef load_thread(thread, engine, data_table, thread_id):\n with engine.connect() as conn:\n try:\n for post in thread['posts']:\n conn.execute(\n data_table.insert(),\n parent=int(thread_id),\n chan_id=post['no'],\n created_at=datetime.datetime.fromtimestamp(post['time']),\n clean_text=post.get('clean_text', None),\n raw=post\n )\n # logger.info(\"Loaded {} to db\".format(thread_id))\n except IntegrityError as e:\n logger.info(\"{} previously saved\".format(post['no']))\n except Exception as e:\n logger.warning(\"LOAD THREAD: {} \\n{}\".format(thread, e))\n\n\ndef load_post(post, engine, data_table, thread_id):\n with engine.connect() as conn:\n try:\n conn.execute(\n data_table.insert(),\n parent=int(thread_id),\n chan_id=post['no'],\n created_at=datetime.datetime.fromtimestamp(post['time']),\n clean_text=post['clean_text'],\n raw=post\n )\n except IntegrityError as e:\n logger.info(\"{} previously saved\".format(post['no']))\n except Exception as e:\n logger.warning(\"LOAD POST: {} \\n{}\".format(post, e))\n\n\ndef load_link(link, engine, data_table):\n with engine.connect() as conn:\n try:\n conn.execute(\n data_table.insert(),\n url=link['url'],\n chan_id=link['post_no'],\n reply_to=link['reply_to'],\n created_at=link['created_at'],\n subject=link['subject'],\n country=link['country']\n )\n # logger.info(\"Link saved {}\".format(link))\n except IntegrityError as e:\n logger.info(\"LINK {} previously saved {}\".format(link['post_no'], link['url']))\n except Exception as e:\n logger.warning(\"Could not write {} to db \\n{}\".format(link, e))\n print(e)\n\n","sub_path":"streamchan/db_utils.py","file_name":"db_utils.py","file_ext":"py","file_size_in_byte":6588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"577305767","text":"# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\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\"\"\"Example / benchmark for building a PTB LSTM model.\n\nTrains the model described in:\n(Zaremba, et. al.) Recurrent Neural Network Regularization\nhttp://arxiv.org/abs/1409.2329\n\nThere are 3 supported model configurations:\n===========================================\n| config | epochs | train | valid | test\n===========================================\n| small | 13 | 37.99 | 121.39 | 115.91\n| medium | 39 | 48.45 | 86.16 | 82.07\n| large | 55 | 37.87 | 82.62 | 78.29\nThe exact results may vary depending on the random initialization.\n\nThe hyperparameters used in the model:\n- init_scale - the initial scale of the weights\n- learning_rate - the initial value of the learning rate\n- max_grad_norm - the maximum permissible norm of the gradient\n- num_layers - the number of LSTM layers\n- num_steps - the number of unrolled steps of LSTM\n- hidden_size - the number of LSTM units\n- max_epoch - the number of epochs trained with the initial learning rate\n- max_max_epoch - the total number of epochs for training\n- keep_prob - the probability of keeping weights in the dropout layer\n- lr_decay - the decay of the learning rate for each epoch after \"max_epoch\"\n- batch_size - the batch size\n- rnn_mode - the low level implementation of lstm cell: one of\n BASIC, or BLOCK, representing basic_lstm, and\n lstm_block_cell classes.\n\nThe data required for this example is in the data/ dir of the\nPTB dataset from Tomas Mikolov's webpage:\n\n$ wget http://www.fit.vutbr.cz/~imikolov/rnnlm/simple-examples.tgz\n$ tar xvf simple-examples.tgz\n\nTo run:\n\n$ python evolve_model.py --data_path=simple-examples/data/\n\n\"\"\"\n# from __future__ import absolute_import\n# from __future__ import division\n# from __future__ import print_function\n\nimport time\n\nimport numpy as np\nimport tensorflow as tf\n\nimport reader\nimport util\n\nclass PTBInput(object):\n \"\"\"The input data.\"\"\"\n\n def __init__(self, config, data, name=None):\n self.batch_size = batch_size = config.batch_size\n self.num_steps = num_steps = config.num_steps\n self.epoch_size = ((len(data) // batch_size) - 1) // num_steps\n self.input_data, self.targets = reader.ptb_producer(\n data, batch_size, num_steps, name=name)\n\n\nclass PTBModel(object):\n \"\"\"The PTB model.\"\"\"\n\n def __init__(self, name, is_training, config, input_):\n self.is_training = is_training\n self.input = input_\n self._cell = None\n self.name = name\n self.batch_size = input_.batch_size\n self.num_steps = input_.num_steps\n size = config.hidden_size\n vocab_size = config.vocab_size\n\n self.initial_state_name = util.with_prefix(self.name, \"initial\")\n self.final_state_name = util.with_prefix(self.name, \"final\")\n\n print(input_.input_data)\n with tf.device(\"/cpu:0\"):\n embedding = tf.get_variable(\n \"embedding\", [vocab_size, size], dtype=util.data_type())\n inputs = tf.nn.embedding_lookup(embedding, input_.input_data)\n\n if is_training and config.keep_prob < 1:\n inputs = tf.nn.dropout(inputs, config.keep_prob)\n\n output, state = self._build_rnn_graph_lstm(inputs, config, is_training)\n\n softmax_w = tf.get_variable(\"softmax_w\", [size, vocab_size], dtype=util.data_type())\n softmax_b = tf.get_variable(\"softmax_b\", [vocab_size] , dtype=util.data_type())\n logits = tf.nn.xw_plus_b(output, softmax_w, softmax_b)\n logits_3d = tf.reshape(logits, [self.batch_size, self.num_steps, vocab_size])\n\n # Use the contrib sequence loss and average over the batches\n loss = tf.contrib.seq2seq.sequence_loss(\n logits_3d,\n input_.targets,\n tf.ones([self.batch_size, self.num_steps], dtype=util.data_type()),\n average_across_timesteps=False,\n average_across_batch=True)\n\n # Update the cost\n self.cost = tf.reduce_sum(loss)\n self.final_state = state\n\n if not is_training:\n return\n\n self.lr = tf.Variable(0.0, trainable=False)\n tvars = tf.trainable_variables()\n\n # https://stackoverflow.com/a/435619771\n grads, _ = tf.clip_by_global_norm(tf.gradients(self.cost, tvars),\n config.max_grad_norm)\n\n tf.train.GradientDescentOptimizer(self.lr).apply_gradients(\n zip(grads, tvars),\n global_step=tf.train.get_or_create_global_step())\n\n self.new_lr = tf.placeholder(tf.float32, shape=[], name=\"new_learning_rate\")\n self.lr_update = tf.assign(self.lr, self.new_lr)\n\n def _build_rnn_graph_lstm(self, inputs, config, is_training):\n \"\"\"Build the inference graph using canonical LSTM cells.\"\"\"\n cell = util.create_lstm_cell(is_training, config)\n state = util.get_zero_state_for_the_cell(cell, config)\n\n self.initial_state = state\n with tf.variable_scope(\"RNN\"):\n inputs = tf.unstack(inputs, num=self.num_steps, axis=1)\n outputs, state = tf.contrib.rnn.static_rnn(cell, inputs,\n initial_state=self.initial_state)\n output = tf.reshape(tf.concat(outputs, 1), [-1, config.hidden_size])\n return output, state\n\n def assign_lr(self, session, lr_value):\n session.run(self.lr_update, feed_dict={self.new_lr: lr_value})\n\n def import_ops(self):\n \"\"\"Imports ops from collections.\"\"\"\n if self.is_training:\n self.lr = tf.get_collection_ref(\"lr\")[0]\n self.new_lr = tf.get_collection_ref(\"new_lr\")[0]\n self.lr_update = tf.get_collection_ref(\"lr_update\")[0]\n\n self.cost = tf.get_collection_ref(util.with_prefix(self.name, \"cost\"))[0]\n self.initial_state = util.import_state_tuples(\n self.initial_state, self.initial_state_name, self.name)\n self.final_state = util.import_state_tuples(\n self.final_state, self.final_state_name, self.name)\n\n\ndef run_epoch(session, model, verbose=False):\n \"\"\"Runs the model on the given data.\"\"\"\n start_time = time.time()\n costs = 0.0\n iters = 0\n state = session.run(model.initial_state)\n\n fetches = {\n \"cost\" : model.cost,\n \"final_state\": util.final_state_tuples(model.final_state, model.name),\n }\n\n for step in range(model.input.epoch_size):\n feed_dict = {}\n for i, (c, h) in enumerate(util.initial_state_tuples(model.initial_state, model.name)):\n feed_dict[c] = state[i].c\n feed_dict[h] = state[i].h\n\n vals = session.run(fetches, feed_dict)\n cost = vals[\"cost\"]\n state = vals[\"final_state\"]\n\n costs += cost\n iters += model.input.num_steps\n\n if verbose and step % (model.input.epoch_size // 10) == 10:\n print(\"%.3f perplexity: %.3f speed: %.0f wps\" %\n (step * 1.0 / model.input.epoch_size, np.exp(costs / iters),\n iters * model.input.batch_size * max(1, util.FLAGS.num_gpus) /\n (time.time() - start_time)))\n\n return np.exp(costs / iters)\n\n\ndef main(_):\n if not util.FLAGS.data_path:\n raise ValueError(\"Must set --data_path to PTB data directory\")\n gpus = util.list_gpus()\n if util.FLAGS.num_gpus > len(gpus):\n raise ValueError(\n \"Your machine has only %d gpus \"\n \"which is less than the requested --num_gpus=%d.\"\n % (len(gpus), util.FLAGS.num_gpus))\n\n train_data, valid_data, test_data, _ = reader.ptb_raw_data(util.FLAGS.data_path)\n\n config = util.get_config()\n eval_config = util.get_config()\n eval_config.batch_size = 1\n eval_config.num_steps = 1\n\n with tf.Graph().as_default():\n initializer = tf.random_uniform_initializer(-config.init_scale,\n config.init_scale)\n\n with tf.name_scope(\"Train\"):\n train_input = PTBInput(config=config, data=train_data, name=\"TrainInput\")\n with tf.variable_scope(\"Model\", reuse=None, initializer=initializer):\n mtrain = PTBModel(name=\"Train\", is_training=True, config=config, input_=train_input)\n tf.summary.scalar(\"Training Loss\", mtrain.cost)\n tf.summary.scalar(\"Learning Rate\", mtrain.lr)\n\n with tf.name_scope(\"Valid\"):\n valid_input = PTBInput(config=config, data=valid_data, name=\"ValidInput\")\n with tf.variable_scope(\"Model\", reuse=True, initializer=initializer):\n mvalid = PTBModel(name=\"Valid\", is_training=False, config=config, input_=valid_input)\n tf.summary.scalar(\"Validation Loss\", mvalid.cost)\n\n with tf.name_scope(\"Test\"):\n test_input = PTBInput(\n config=eval_config, data=test_data, name=\"TestInput\")\n with tf.variable_scope(\"Model\", reuse=True, initializer=initializer):\n mtest = PTBModel(name=\"Test\", is_training=False, config=eval_config,\n input_=test_input)\n\n models = [mtrain, mvalid, mtest]\n [(util.export_ops(model, config)) for model in models]\n metagraph = tf.train.export_meta_graph()\n\n with tf.Graph().as_default():\n\n tf.train.import_meta_graph(metagraph)\n [(model.import_ops()) for model in models]\n\n sv = tf.train.Supervisor(logdir=util.FLAGS.save_path)\n config_proto = tf.ConfigProto(allow_soft_placement=False)\n with sv.managed_session(config=config_proto) as session:\n for i in range(config.max_max_epoch):\n lr_decay = config.lr_decay ** max(i + 1 - config.max_epoch, 0.0)\n mtrain.assign_lr(session, config.learning_rate * lr_decay)\n\n print(\"Epoch: %d Learning rate: %.3f\" % (i + 1, session.run(mtrain.lr)))\n train_perplexity = run_epoch(session, mtrain,\n verbose=True)\n print(\"Epoch: %d Train Perplexity: %.3f\" % (i + 1, train_perplexity))\n valid_perplexity = run_epoch(session, mvalid)\n print(\"Epoch: %d Valid Perplexity: %.3f\" % (i + 1, valid_perplexity))\n\n test_perplexity = run_epoch(session, mtest)\n print(\"Test Perplexity: %.3f\" % test_perplexity)\n\n if util.FLAGS.save_path:\n print(\"Saving model to %s.\" % util.FLAGS.save_path)\n sv.saver.save(session, util.FLAGS.save_path, global_step=sv.global_step)\n\n\nif __name__ == \"__main__\":\n tf.app.run()\n","sub_path":"tutorials/rnn/time-series/evolve_model.py","file_name":"evolve_model.py","file_ext":"py","file_size_in_byte":10655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"596038884","text":"#-*-coding:utf-8-*-\n\nfrom __future__ import division\nimport numpy as np\nimport cv2\nfrom PIL import Image\nimport piexif\nimport warnings\n\nwarnings.filterwarnings(\"error\", category=UserWarning)\n\ndef read_image_bgr(path):\n \"\"\"\n 读取图片为BGR的格式\n :param path:\n :return:\n \"\"\"\n # warnings.filterwarnings(\"error\")\n try:\n image = np.asarray(Image.open(path).convert(\"RGB\"))\n except UserWarning:\n print(\"rewrite exif warning file: {}\".format(path))\n piexif.remove(path)\n image = np.asarray(Image.open(path).convert(\"RGB\"))\n # warnings.filterwarnings(\"default\")\n return image[:, :, ::-1].copy()\n\nclass TransformParameters:\n\n def __init__(self,\n fill_mode='nearest',\n interpolation=\"linear\",\n cval=0,\n relative_translation=True):\n # 边界填充模式\n self.fill_mode = fill_mode\n\n self.cval = cval\n # 插值模式\n self.interpolation = interpolation\n self.relative_translation = relative_translation\n\n def cvBorderMode(self):\n if self.fill_mode == \"constant\":\n return cv2.BORDER_CONSTANT\n elif self.fill_mode == \"nearest\":\n return cv2.BORDER_REPLICATE\n elif self.fill_mode == \"reflect\":\n return cv2.BORDER_REFLECT_101\n elif self.fill_mode == \"wrap\":\n return cv2.BORDER_WRAP\n\n def cvInterpolation(self):\n # 最邻近插值\n if self.interpolation == \"nearest\":\n return cv2.INTER_NEAREST\n # 线性插值\n elif self.interpolation == \"linear\":\n return cv2.INTER_LINEAR\n # 三次样条插值\n elif self.interpolation == \"cubic\":\n return cv2.INTER_CUBIC\n # 区域插值\n elif self.interpolation == \"area\":\n return cv2.INTER_AREA\n # lanczos插值\n elif self.interpolation == \"lanczos4\":\n return cv2.INTER_LANCZOS4\n\ndef apply_transform(matrix, image, params=TransformParameters()):\n # matrix, _, _ = matrix\n res = cv2.warpAffine(image, matrix[:2, :],\n dsize=(image.shape[1], image.shape[0]),\n flags=params.cvInterpolation(),\n borderMode=params.cvBorderMode(),\n borderValue=params.cval)\n return res\n\ndef preprocess_image(x, mode=\"caffe\"):\n x = x.astype(np.float32)\n\n if mode == \"tf\":\n x /= 127.5\n x -= 1.0\n elif mode == \"caffe\":\n x[..., 0] -= 103.939\n x[..., 1] -= 116.779\n x[..., 2] -= 123.68\n\n return x\n\ndef compute_resize_scales(image_shape, min_side=800, max_side=1333):\n width, height, _ = image_shape\n small_side = min(width, height)\n\n scale = min_side/small_side\n\n large_side = max(width, height)\n\n if large_side*scale > max_side:\n scale = max_side/large_side\n\n return scale\n\ndef resize_image(img, min_side=800, max_side=1333):\n\n scale = compute_resize_scales(img.shape, min_side=min_side, max_side=max_side)\n\n img = cv2.resize(img, None, fx=scale, fy=scale)\n\n return img, scale\n\ndef clip(image):\n\n return np.clip(image, 0, 255).astype(np.uint8)\n\ndef adjust_constrast(image, factor):\n \"\"\"\n 调整图像的明暗对比\n :param image:\n :param factor:\n :return:\n \"\"\"\n mean = image.mean(axis=0).mean(axis=0)\n return clip((image-mean)*factor + mean)\n\ndef adjust_brightness(image, delta):\n \"\"\"\n 调整图像的亮度\n :param image:\n :param delta:\n :return:\n \"\"\"\n return clip(image+delta*255)\n\ndef adjust_hue(image, delta):\n \"\"\"\n 调整图像的颜色,delta在-1和1之间\n :param image:\n :param delta:\n :return:\n \"\"\"\n image[..., 0] = np.mod(image[..., 0]+delta*180, 180)\n return image\n\ndef adjust_saturation(image, factor):\n \"\"\"\n 调整色彩饱和度\n :param image:\n :param factor:\n :return:\n \"\"\"\n image[..., 1] = np.clip(image[..., 1]*factor, 0, 255)\n return image\n\nclass VisualEffect:\n\n def __init__(self,\n constrast_factor,\n brightness_delta,\n hue_delta,\n saturation_factor):\n self.constrast_factor = constrast_factor\n self.brightness_delta = brightness_delta\n self.hue_delta = hue_delta\n self.saturation_factor = saturation_factor\n\n def __call__(self, image):\n\n if self.constrast_factor:\n image = adjust_constrast(image, self.constrast_factor)\n if self.brightness_delta:\n image = adjust_brightness(image, self.brightness_delta)\n\n if self.hue_delta or self.saturation_factor:\n\n image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n\n if self.hue_delta:\n image = adjust_hue(image, self.hue_delta)\n if self.saturation_factor:\n image = adjust_saturation(image, self.saturation_factor)\n\n image = cv2.cvtColor(image, cv2.COLOR_HSV2BGR)\n\n return image\n\ndef uniform(val_range):\n return np.random.uniform(val_range[0], val_range[1])\n\ndef random_visual_effect_generator(\n contrast_range=(0.9, 1.1),\n brightness_range=(-0.1, 0.1),\n hue_range=(-0.05, 0.05),\n saturation_range=(0.95, 1.05)\n):\n def _generate():\n while True:\n yield VisualEffect(\n constrast_factor=uniform(contrast_range),\n brightness_delta=uniform(brightness_range),\n hue_delta=uniform(hue_range),\n saturation_factor=uniform(saturation_range),\n )\n\n return _generate()\n\nif __name__ == \"__main__\":\n read_image_bgr(\"/media/user/disk2/delusion/oid/train/train_0/0a0a00b2fbe89a47.jpg\")","sub_path":"utils/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":5727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"138899351","text":"#!/usr/bin/env python3\n# coding: utf-8\n\n# @Author: Alexandre Biguet \n# @Date: 11 - Jul - 2018\n# @Last modified by: alexandrebiguet\n# @Last modified time: 11 - Jul - 2018\n\nimport sys\nimport os\nimport docopt\nimport subprocess as sub\n\nSCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))\nBUILD_DIR = SCRIPT_DIR + '/build-cmake'\nBUILD_DIR_A = BUILD_DIR + '/build-projA'\nBUILD_DIR_B = BUILD_DIR + '/build-projB'\nRELEASE_DIR = BUILD_DIR + '/release'\nSRC_DIR_A = SCRIPT_DIR + '/projA'\nSRC_DIR_B = SCRIPT_DIR + '/projB'\n\nusage = \"\"\"\nbuild.py\n\nUsage:\n build.py projA\n build.py projB\n build.py clean\n\nOptions:\n --help Show this screen\n --version Show version\n\"\"\"\n\nclass BuildInfo:\n\n def __init__(self,\n src_dir, build_dir, release_dir, generator, cmake_options):\n\n self._release_dir = release_dir\n self._src_dir = src_dir\n self._build_dir = build_dir\n self._generator = generator\n self._cmake_options = cmake_options\n\n def src_dir(self):\n return self._src_dir\n\n def build_dir(self):\n return self._build_dir\n\n def release_dir(self):\n return self._release_dir\n\n def generator(self):\n return self._generator\n\n def cmake_options(self):\n return self._cmake_options\n\n\ndef build(build_info):\n src_dir = '-H' + build_info.src_dir()\n build_dir = '-B' + build_info.build_dir()\n rel_dir = '-DCMAKE_INSTALL_PREFIX=' + build_info.release_dir()\n # gen = '\"' + build_info.generator() + '\" '\n gen = build_info.generator()\n options = build_info.cmake_options()\n if options:\n print('options : ', options)\n sub.run(['cmake', src_dir, build_dir, rel_dir, '-G', gen] + options,\n check=True)\n else:\n sub.run(['cmake', src_dir, build_dir, '-G', gen, rel_dir], check=True)\n sub.run(['cmake', '--build', build_info.build_dir()], check=True)\n sub.run(['cmake', '--build', build_info.build_dir(), '--target', 'install'],\n check=True)\n\n\n\ndef main():\n\n arglist = []\n cmake_options = []\n for arg in sys.argv[1:]:\n if arg.startswith('-D'):\n cmake_options.append(arg)\n else:\n arglist.append(arg)\n\n arguments = docopt.docopt(usage, argv=arglist, version='build.py 1.0')\n\n if arguments['projA']:\n info = BuildInfo(SRC_DIR_A, BUILD_DIR_A, RELEASE_DIR, 'Unix Makefiles',\n cmake_options)\n build(info)\n\n if arguments['projB']:\n info = BuildInfo(SRC_DIR_B, BUILD_DIR_B, RELEASE_DIR, 'Unix Makefiles',\n cmake_options)\n build(info)\n\n if arguments['clean']:\n sub.run(['rm', '-rf', BUILD_DIR])\n\n\nif __name__ == '__main__':\n try:\n main()\n except KeyboardInterrupt:\n print('Interrupted by user')\n","sub_path":"cmake/components/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":2823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"392856390","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport sys\nimport click\nfrom pprint import pprint\n\nfrom .VERSION import *\n\nfrom .core.auth import USER_DIR, USER_CONFIG_FILE_PATH, USER_HISTORY_FILE\nfrom .core.api import *\nfrom .core.utils import open_multi_platform, init_config_folder, print_warning_prompt_version, preview_contents\nfrom .core.version_utils import print_dimcli_report, is_dimcli_outdated\n\ntry:\n from prompt_toolkit.formatted_text import HTML\n from prompt_toolkit.shortcuts import CompleteStyle\n from prompt_toolkit import PromptSession\n from prompt_toolkit.styles import Style\n PROMPT_TOOLKIT_VERSION_OK = True\nexcept:\n PROMPT_TOOLKIT_VERSION_OK = False # => repl disabled\n\n\n@click.command()\n@click.argument(\"instance_name\", nargs=1, default=\"live\")\n@click.option(\n \"--init\", \"-i\",\n is_flag=True,\n help=\"Initialize the configuration file with your Dimensions account details.\")\n@click.option(\n \"--config\", \"-c\",\n is_flag=True,\n help=\"Show configuration file.\")\n@click.option(\n \"--versioncheck\", \"-v\",\n is_flag=True,\n help=\"Check online if your dimcli version is the latest.\")\n@click.option(\n \"--history\", \"-h\", is_flag=True, help=\"Open history file with default editor.\")\n@click.pass_context\ndef main_cli(ctx, instance_name=None, init=False, config=False, versioncheck=False, history=False):\n \"\"\"\n Python client for the Dimensions DSL.\n More info: https://github.com/digital-science/dimcli\n \"\"\"\n click.secho(\"Dimcli - Dimensions API Console (\" + VERSION + \")\", dim=True)\n\n if init:\n init_config_folder(USER_DIR, USER_CONFIG_FILE_PATH)\n return\n\n if versioncheck:\n print_dimcli_report()\n return\n\n if not os.path.exists(USER_CONFIG_FILE_PATH):\n click.secho(\n \"Credentials file not found - you can create one by typing: `dimcli --init`\",\n fg=\"red\",\n )\n click.secho(\n \"More info: https://github.com/digital-science/dimcli#credentials-file\",\n dim=True,\n )\n return\n\n if config:\n preview_contents(USER_CONFIG_FILE_PATH)\n return\n\n if history:\n if os.path.exists(USER_HISTORY_FILE):\n open_multi_platform(USER_HISTORY_FILE)\n return\n\n if PROMPT_TOOLKIT_VERSION_OK:\n from .repl import repl\n # try online version check\n test = is_dimcli_outdated()\n if test:\n click.secho(\"====\\nHeads up: there is a newer version of Dimcli available at https://pypi.org/project/dimcli/.\\n====\", bold=True)\n # launch REPL\n repl.run(instance_name)\n else:\n print_warning_prompt_version()\n\n\n\nif __name__ == \"__main__\":\n main_cli()\n","sub_path":"dimcli/main_cli.py","file_name":"main_cli.py","file_ext":"py","file_size_in_byte":2701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"56906804","text":"def solution(Y, A, B, W):\r\n days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']\r\n months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']\r\n month_lengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\r\n leap_year = Y % 4 == 0\r\n weeks = 0\r\n start_month_index = months.index(A)\r\n end_month_index = months.index(B)\r\n current_month_index = months.index(A)\r\n start_month_first_day = days.index(W)\r\n for x in range(0, start_month_index):\r\n if leap_year: start_month_first_day += (month_lengths[x] - 27)\r\n else: start_month_first_day += (month_lengths[x] - 28)\r\n start_month_first_day %= 7\r\n if start_month_first_day == 0: current_date = 0\r\n else: current_date = 1 + (7 - start_month_first_day)\r\n current_day = 0\r\n while current_month_index < end_month_index:\r\n while current_date + 7 < month_lengths[current_month_index]:\r\n weeks += 1\r\n current_date += 7\r\n if current_month_index + 1 <= end_month_index:\r\n current_month_index += 1\r\n current_date = (current_date + 7) % month_lengths[current_month_index - 1]\r\n weeks += 1\r\n return weeks\r\n\r\nprint(solution(2014, \"April\", \"May\", \"Wednesday\"))\r\n","sub_path":"CodeWars/sandbox 2.py","file_name":"sandbox 2.py","file_ext":"py","file_size_in_byte":1334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"239116709","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 28 12:31:56 2021\n\n@author: mark\n\"\"\"\n\nimport json\nimport datetime\nfrom pyserum.connection import conn\nfrom pyserum.enums import OrderType, Side\nfrom pyserum.market import Market\nfrom solana.account import Account\nfrom solana.publickey import PublicKey\nfrom solana.rpc.types import TxOpts\nfrom spl.token.client import Token\nfrom spl.token.constants import TOKEN_PROGRAM_ID\n\n# %%\n# For a given ccy pair, get the market and the token mint\nfrom pyserum.connection import get_live_markets, get_token_mints\npair = \"SOL/USDC\"\nside = Side.SELL\n\npair_mkt = {}\nfor mkt in get_live_markets():\n pair_mkt.update({mkt.name:mkt.address})\nprint(\"Market Address is: {}\".format(pair_mkt[pair]))\n\nquote_ccy = pair.split(\"/\")[0]\nquote_ccy_mint = {}\nfor mkt in get_token_mints():\n quote_ccy_mint.update({mkt.name:mkt.address})\nprint(\"Token Mint is: {}\".format(quote_ccy_mint[quote_ccy]))\n\n# %%\n\n# Get private key and use that the create a new account\n#pubkey = \"GKksmU6hSJ2X7zz1mcE3Qhr7DDEpvxqbygzb17SxygUD\"\nf = open('./my-solana-wallet/my-keypair.json')\nprivate_key = json.load(f)\nmid = len(private_key)//2\nprivate_key = private_key[:mid] # to 32 bytes \npayer = Account(private_key) # Your account to pay fees\nprint(\"Public Key is: {}\".format(payer.public_key()))\n\n# %%\n\ncc = conn(\"https://api.mainnet-beta.solana.com/\")\n\nquote_token = Token(\n cc,\n pubkey=PublicKey(quote_ccy_mint[quote_ccy]), # mint address of token\n program_id=TOKEN_PROGRAM_ID,\n payer=payer,\n)\n\nquote_wallet = quote_token.create_account(\n payer.public_key(),\n skip_confirmation=False) # Make sure you send tokens to this address\nprint(\"quote wallet: \", str(quote_wallet))\n\nmarket_address = PublicKey(pair_mkt[pair]) \nmarket = Market.load(cc, market_address)\n\ntx_sig = market.place_order(\n payer=quote_wallet, #PublicKey(pubkey), # My public key\n owner=payer,\n side=side,\n order_type=OrderType.LIMIT,\n limit_price=100,\n max_quantity=0.1,\n opts = TxOpts(skip_preflight=False)\n)\nprint(tx_sig)\n\nsummary = {\"mkt_add\": pair_mkt[pair],\n \"token_mint\": quote_ccy_mint[quote_ccy],\n \"public_key\": str(payer.public_key()),\n \"quote_wallet\":str(quote_wallet),\n \"tx_sig\":tx_sig}\nwith open('tx_{}'.format(datetime.datetime.today().strftime(\"%Y-%m-%d %H:%M:%S\")), 'w') as f:\n json.dump(summary, f, indent=4)\n ","sub_path":"place_order.py","file_name":"place_order.py","file_ext":"py","file_size_in_byte":2399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"284185473","text":"class Agenda:\n def __init__(self):\n self.lista = []\n\n def menu(self):\n while True:\n opcion = int(input('*********** MENU DE OPCIONES **************\\n\\n1. Agregar Contacto\\n2. Lista de Contactos\\n3. Buscar Contacto\\n4. Editar Contacto\\n5. Cerrar Agenda\\n\\nElija una opcion: '))\n\n if opcion == 1:\n self.agregar_contacto()\n break\n elif opcion == 2:\n self.imprimir_contactos()\n break\n elif opcion == 3:\n break\n elif opcion == 4:\n break\n elif opcion == 5:\n break\n else:\n print('Elija solo las opciones que se muestran')\n\n def agregar_contacto(self):\n self.nombre = str(input('Ingrese nombre: '))\n self.telefono = int(input('Ingrese telefono: '))\n self.email = str(input('Ingrese email: '))\n\n self.lista.append({'nombre':self.nombre,'telefono':self.telefono,'email':self.email})\n print(self.lista[0]['nombre'])\n\n def imprimir_contactos(self):\n print(self.lista[0]['nombre'])\n \n\nobj1 = Agenda()\nobj1.menu()\n\n\n\n\n","sub_path":"objetos/ejercicio5.py","file_name":"ejercicio5.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"519967088","text":"from __future__ import absolute_import\n\nfrom rest_framework import serializers, status\nfrom rest_framework.response import Response\n\nimport logging\nimport petname\n\nfrom sentry.api.bases.user import UserEndpoint\nfrom sentry.api.decorators import sudo_required\nfrom sentry.api.serializers import serialize\nfrom sentry.models import Authenticator, OrganizationMember\nfrom sentry.security import capture_security_activity\nfrom sentry.web.frontend.accept_organization_invite import ApiInviteHelper\n\nlogger = logging.getLogger(__name__)\n\nALREADY_ENROLLED_ERR = {'details': 'Already enrolled'}\nINVALID_OTP_ERR = {'details': 'Invalid OTP'},\nSEND_SMS_ERR = {'details': 'Error sending SMS'}\n\n\nclass BaseRestSerializer(serializers.Serializer):\n # Fields needed to accept an org invite\n # pending 2FA enrollment\n memberId = serializers.CharField(\n required=False\n )\n token = serializers.CharField(\n required=False,\n )\n\n\nclass TotpRestSerializer(BaseRestSerializer):\n otp = serializers.CharField(\n label='Authenticator code',\n help_text='Code from authenticator',\n required=True,\n max_length=20\n )\n\n\nclass SmsRestSerializer(BaseRestSerializer):\n phone = serializers.CharField(\n label=\"Phone number\",\n help_text=\"Phone number to send SMS code\",\n required=True,\n max_length=20,\n )\n otp = serializers.CharField(\n label='Authenticator code',\n help_text='Code from authenticator',\n required=False,\n max_length=20\n )\n\n\nclass U2fRestSerializer(BaseRestSerializer):\n deviceName = serializers.CharField(\n label='Device name',\n required=False,\n max_length=60,\n default=lambda: petname.Generate(2, ' ', letters=10).title(),\n )\n challenge = serializers.CharField(\n required=True,\n )\n response = serializers.CharField(\n required=True,\n )\n\n\nhidden_fields = ['memberId', 'token']\n\nserializer_map = {\n 'totp': TotpRestSerializer,\n 'sms': SmsRestSerializer,\n 'u2f': U2fRestSerializer,\n}\n\n\ndef get_serializer_field_metadata(serializer, fields=None):\n \"\"\"Returns field metadata for serializer\"\"\"\n meta = []\n for field in serializer.base_fields:\n if (fields is None or field in fields) and field not in hidden_fields:\n serialized_field = dict(serializer.base_fields[field].metadata())\n serialized_field['name'] = field\n serialized_field['defaultValue'] = serializer.base_fields[field].get_default_value()\n meta.append(serialized_field)\n\n return meta\n\n\nclass UserAuthenticatorEnrollEndpoint(UserEndpoint):\n @sudo_required\n def get(self, request, user, interface_id):\n \"\"\"\n Get Authenticator Interface\n ```````````````````````````\n\n Retrieves authenticator interface details for user depending on user enrollment status\n\n :pparam string user_id: user id or \"me\" for current user\n :pparam string interface_id: interface id\n\n :auth: required\n \"\"\"\n\n interface = Authenticator.objects.get_interface(user, interface_id)\n\n # Not all interfaces allow multi enrollment\n if interface.is_enrolled and not interface.allow_multi_enrollment:\n return Response(ALREADY_ENROLLED_ERR, status=status.HTTP_400_BAD_REQUEST)\n\n # User is not enrolled in auth interface:\n # - display configuration form\n response = serialize(interface)\n response['form'] = get_serializer_field_metadata(\n serializer_map[interface_id]\n )\n\n # U2fInterface has no 'secret' attribute\n try:\n response['secret'] = interface.secret\n except AttributeError:\n pass\n\n if interface_id == 'totp':\n response['qrcode'] = interface.get_provision_qrcode(user.email)\n\n if interface_id == 'u2f':\n response['challenge'] = interface.start_enrollment()\n\n return Response(response)\n\n @sudo_required\n def post(self, request, user, interface_id):\n \"\"\"\n Enroll in authenticator interface\n `````````````````````````````````\n\n :pparam string user_id: user id or \"me\" for current user\n :pparam string interface_id: interface id\n\n :auth: required\n \"\"\"\n\n # Using `request.user` here because superuser should not be able to set a user's 2fa\n\n # start activation\n serializer_cls = serializer_map.get(interface_id, None)\n\n if serializer_cls is None:\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n serializer = serializer_cls(data=request.data)\n\n if not serializer.is_valid():\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n interface = Authenticator.objects.get_interface(request.user, interface_id)\n\n # Not all interfaces allow multi enrollment\n #\n # This is probably un-needed because we catch\n # `Authenticator.AlreadyEnrolled` when attempting to enroll\n if interface.is_enrolled and not interface.allow_multi_enrollment:\n return Response(ALREADY_ENROLLED_ERR, status=status.HTTP_400_BAD_REQUEST)\n\n try:\n interface.secret = request.data['secret']\n except KeyError:\n pass\n\n context = {}\n # Need to update interface with phone number before validating OTP\n if 'phone' in request.data:\n interface.phone_number = serializer.validated_data['phone']\n\n # Disregarding value of 'otp', if no OTP was provided,\n # send text message to phone number with OTP\n if 'otp' not in request.data:\n if interface.send_text(for_enrollment=True, request=request._request):\n return Response(status=status.HTTP_204_NO_CONTENT)\n else:\n # Error sending text message\n return Response(SEND_SMS_ERR, status=status.HTTP_500_INTERNAL_SERVER_ERROR)\n\n # Attempt to validate OTP\n if 'otp' in request.data and not interface.validate_otp(serializer.validated_data['otp']):\n return Response(INVALID_OTP_ERR, status=status.HTTP_400_BAD_REQUEST)\n\n # Try u2f enrollment\n if interface_id == 'u2f':\n # What happens when this fails?\n interface.try_enroll(\n serializer.validated_data['challenge'],\n serializer.validated_data['response'],\n serializer.validated_data['deviceName']\n )\n context.update({\n 'device_name': serializer.validated_data['deviceName']\n })\n\n try:\n interface.enroll(request.user)\n except Authenticator.AlreadyEnrolled:\n return Response(ALREADY_ENROLLED_ERR, status=status.HTTP_400_BAD_REQUEST)\n else:\n context.update({\n 'authenticator': interface.authenticator\n })\n capture_security_activity(\n account=request.user,\n type='mfa-added',\n actor=request.user,\n ip_address=request.META['REMOTE_ADDR'],\n context=context,\n send_email=True,\n )\n request.user.clear_lost_passwords()\n request.user.refresh_session_nonce(self.request)\n request.user.save()\n Authenticator.objects.auto_add_recovery_codes(request.user)\n\n # Try to accept an org invite pending 2FA enrollment\n member_id = serializer.validated_data.get('memberId')\n token = serializer.validated_data.get('token')\n\n if member_id and token:\n try:\n helper = ApiInviteHelper(\n instance=self,\n request=request,\n member_id=member_id,\n token=token,\n logger=logger,\n )\n except OrganizationMember.DoesNotExist:\n logger.error('Failed to accept pending org invite', exc_info=True)\n else:\n if helper.valid_request():\n helper.accept_invite()\n\n response = Response(status=status.HTTP_204_NO_CONTENT)\n helper.remove_invite_cookie(response)\n return response\n\n return Response(status=status.HTTP_204_NO_CONTENT)\n","sub_path":"src/sentry/api/endpoints/user_authenticator_enroll.py","file_name":"user_authenticator_enroll.py","file_ext":"py","file_size_in_byte":8470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"303933852","text":"import os\nimport sys\nimport json\nfrom py_mini_racer import py_mini_racer\n\nclass Fusor(object):\n \"\"\"An object for rendering React code into an html string with the following propertie(s):\n\n Attributes:\n ctx: A MiniRacer object for evaluating javascript code.\n \"\"\"\n def __init__(self):\n \"\"\"Return a Fusor object with a MiniRacer context.\"\"\"\n path_to_react = os.path.join(os.path.dirname(__file__), './js/react.min.js')\n path_to_react_dom = os.path.join(os.path.dirname(__file__), './js/react-dom.min.js')\n path_to_react_dom_server = os.path.join(os.path.dirname(__file__), './js/react-dom-server.min.js')\n \n # Initialize V8 instance\n self.ctx = py_mini_racer.MiniRacer()\n \n # Read and evaluate React source code\n with open(path_to_react, \"r\") as react_file, \\\n open(path_to_react_dom, \"r\") as react_dom_file, \\\n open(path_to_react_dom_server, \"r\") as react_dom_server_file: \n self.ctx.eval(react_file.read())\n self.ctx.eval(react_dom_file.read())\n self.ctx.eval(react_dom_server_file.read())\n\n\n\n def fuse(self, name, component, props=None, children=None, static=False):\n \"\"\"Returns an html string of the evaluated string of React component (component).\"\"\"\n jsProps = json.dumps(props)\n jsChildren = json.dumps(children)\n react_code = f\"(() => {{ {component} ; return React.createElement({name}, {jsProps}, {jsChildren}); }})()\" \n if static:\n return self.ctx.eval(f\"ReactDOMServer.renderToStaticMarkup({react_code})\")\n else:\n return self.ctx.eval(f\"ReactDOMServer.renderToString({react_code})\")\n","sub_path":"farnsworth/fusor.py","file_name":"fusor.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"580708904","text":"# -*- coding: utf-8 -*-\nfrom fuzzymatcher.record import RecordToMatch\nimport pandas as pd\n\nclass Matcher:\n \"\"\"The Matcher coordinates data matching\"\"\"\n\n def __init__(self,\n data_preprocessor,\n data_getter,\n scorer,\n top_n_matches = 5):\n self.data_preprocessor = data_preprocessor\n self.data_getter = data_getter\n self.scorer = scorer\n self.top_n_matches = top_n_matches\n\n def add_data(self, df_left,\n df_right,\n left_on,\n right_on,\n left_id_col = None,\n right_id_col = None):\n\n # Copy to prevent modifying the dataframes the user provides\n self.df_left = df_left.copy()\n self.df_right = df_right.copy()\n self.left_on = left_on\n self.right_on = right_on\n self.left_id_col = left_id_col\n self.right_id_col = right_id_col\n\n self.data_preprocessor.add_data(self)\n\n\n def match_all(self):\n\n # Get a dataset with id, record only for left and right\n self.data_preprocessor.preprocess()\n\n # Data preprocessor returns list of dicts, not pd.DataFrame\n self.data_getter.add_data(self)\n self.scorer.add_data(self)\n\n # Get a table that contains only the matches, scores and ids\n self.link_table = self._match_processed_data()\n\n def get_formatted_link_table(self):\n return self._add_original_cols_to_link_table(self.link_table)\n\n def get_left_join_table(self):\n df = self.df_left.merge(self.link_table, left_on = self.left_id_col, right_on = \"__id_left\", how=\"left\")\n df.drop(\"_concat_all\", axis=1, inplace=True)\n\n df = df.merge(self.df_right, left_on = \"__id_right\", right_on=self.right_id_col, how=\"left\", suffixes = (\"_left\", \"_right\"))\n df.drop([\"_concat_all\", \"__id_left\", \"__id_right\"], axis=1, inplace=True)\n\n # Keep records where rank = 1 or there's no rang\n filter1 = df[\"__rank\"] == 1\n filter2 = pd.isnull(df[\"__rank\"])\n df = df[filter1 | filter2]\n df.drop(\"__rank\", axis=1, inplace=True)\n\n cols = [\"__score\"]\n cols.extend([c for c in df.columns if c != \"__score\"])\n\n df = df[cols].rename(columns={\"__score\": \"best_match_score\"})\n return df\n\n def _match_processed_data(self):\n\n # This will store all the regords for the link table\n\n link_table_list = []\n\n for r in self.df_left_processed.iterrows():\n row = r[1]\n record_id = row[self.left_id_col]\n\n record_to_match = RecordToMatch(record_id, row[\"_concat_all\"], self)\n\n record_to_match.find_and_score_potential_matches()\n link_table_list.extend(record_to_match.get_link_table_rows())\n\n return pd.DataFrame(link_table_list)\n\n def _add_original_cols_to_link_table(self, link_table):\n\n df = link_table.merge(self.df_left, left_on = \"__id_left\", right_on = self.left_id_col, how = \"left\", suffixes=('_link', '_left'))\n df.drop(\"_concat_all\", axis=1, inplace=True)\n\n df = df.merge(self.df_right, left_on = \"__id_right\", right_on = self.right_id_col, how=\"left\", suffixes=('_left', \"_right\"))\n df.drop(\"_concat_all\", axis=1, inplace=True)\n\n match_cols_left = self.left_on[::-1].copy()\n match_cols_right = self.right_on[::-1].copy()\n col_order = [\"__id_left\", \"__id_right\", \"__score\", \"__rank\"]\n while len(match_cols_left) > 0 and len(match_cols_right) > 0:\n\n # Check whether suffixes have been added\n left_col = match_cols_left.pop()\n left_col = self._add_suffix_if_needed(left_col, df, \"left\")\n col_order.append(left_col)\n\n right_col = match_cols_right.pop()\n right_col = self._add_suffix_if_needed(right_col, df, \"right\")\n col_order.append(right_col)\n\n col_order.extend(match_cols_left)\n col_order.extend(match_cols_right)\n\n df = df[col_order]\n\n # Finally rename the id columns back to their original and improve names of score and rank\n if self.left_id_col != self.right_id_col:\n rename_dict = {\"__id_left\": self.left_id_col,\n \"__id_right\": self.right_id_col}\n else:\n rename_dict = {\"__id_left\": self.left_id_col + \"_left\",\n \"__id_right\": self.right_id_col + \"_right\"}\n\n if \"match_rank\" not in df.columns:\n rename_dict[\"__rank\"] = \"match_rank\"\n\n if \"match_score\" not in df.columns:\n rename_dict[\"__score\"] = \"match_score\"\n df = df.rename(columns = rename_dict)\n return df\n\n def _add_suffix_if_needed(self, col_name, df, left_or_right):\n\n all_cols = df.columns\n if left_or_right == \"left\":\n left_cols = self.df_left.columns\n\n if col_name in left_cols and col_name not in all_cols:\n return col_name + \"_left\"\n else:\n return col_name\n\n if left_or_right == \"right\":\n right_cols = self.df_right.columns\n if col_name in right_cols and col_name not in all_cols:\n return col_name + \"_right\"\n else:\n return col_name\n\n\n\n\n\n\n\n\n\n\n","sub_path":"fuzzymatcher/matcher.py","file_name":"matcher.py","file_ext":"py","file_size_in_byte":5275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"462256312","text":"import joblib as joblib\nimport pandas as pd\nimport nltk\nfrom nltk.tokenize import TweetTokenizer as TweetTokenizer\nfrom nltk.chunk import tree2conlltags\nfrom preprocessor.preprocess import *\nfrom ekphrasis.classes.preprocessor import TextPreProcessor\nfrom ekphrasis.dicts.emoticons import emoticons\nfrom textblob import TextBlob\nimport corenlp\nimport collections\nimport spacy\nimport re\nimport emoji\n\nfrom gensim.scripts.glove2word2vec import glove2word2vec\nimport regex\nfrom spacy.tokenizer import Tokenizer\nimport gensim\nimport random as rn\nimport numpy as np\nimport pprint\nfrom gensim.test.utils import datapath, get_tmpfile\nfrom gensim.models.wrappers import FastText\n\n#Load Dataset\ndataset = pd.read_csv( 'test_emocontext.txt',delimiter='\\t')\ntweets1 = dataset['turn1']+dataset['turn2']+dataset['turn3']\n\n#dataset = pd.read_csv( 'dev_emocontext.txt',delimiter='\\t')\n#tweets2 = dataset['turn1']+dataset['turn2']+dataset['turn3']\n#tw =pd.concat([tweets1,tweets2],ignore_index=True, axis=1)\ntweets = tweets1\ntweets1\n\n\ngoogle_300 = gensim.models.KeyedVectors.load_word2vec_format(\"crawl-300d-2M.vec\")\n#gensim.models.KeyedVectors.load_word2vec_format(\"crawl-300d-2M.vec\")\n#gensim.models.KeyedVectors.load_word2vec_format( \"../word2vec/embeddings/google_w2v_300.bin\" , binary=True )\n\n#gensim.models.KeyedVectors.load_word2vec_format(\"crawl-300d-2M.vec\")\n\n#gensim.models.KeyedVectors.load_word2vec_format( \"../word2vec/embeddings/glove_word2vec.txt\" , binary=False )\n#senti_pos_500 = gensim.models.KeyedVectors.load_word2vec_format( \"../word2vec/embedings/senti140_w2v_pos_100.bin\", binary=True , unicode_errors='ignore')\n#senti_neg_500 = gensim.models.KeyedVectors.load_word2vec_format( \"../word2vec/embedings/senti140_w2v_neg_100.bin\" , binary=True , unicode_errors='ignore')\n#generics_500 = gensim.models.KeyedVectors.load_word2vec_format( \"../word2vec/embeddings/generics_w2v_neutral_300.bin\" , binary=True , unicode_errors='ignore')\n\n\n\n#classes = dataset['label']\nprint(tweets)\ntw_ = tweets\ntok = list()\n\n#Final 3Dvec\n#train EmoCOntext 20463\n#2761\nmatrix2D = np.zeros((5509,300))\n\n\n\npp = {\n 'CC':1,\n 'CD' :2,\n 'DT' : 3,\n 'EX' : 4,\n 'FW' : 5,\n 'IN' : 6,\n 'JJ' : 7,\n 'JJR' : 8,\n 'JJS' : 9,\n 'LS' : 10,\n 'MD' : 11,\n 'NN' : 12,\n 'NNS' : 13,\n 'NNP' : 14,\n 'NNPS' : 15,\n 'PDT' : 16,\n 'POS' : 17,\n 'PRP' : 18,\n 'PRP$' : 19,\n 'RB' : 20,\n 'RBR' : 21,\n 'RBS' : 22,\n 'RP' : 23,\n 'TO' : 24,\n 'UH' : 25,\n 'VB' : 26,\n 'VBD' : 27,\n 'VBG' : 28,\n 'VBN' : 29,\n 'VBP' : 30,\n 'VBZ' : 31,\n 'WDT' : 32,\n 'WP' : 33,\n 'WP$' : 34,\n 'WRB' : 35,\n '.': 36,\n ',' : 37,\n ':' : 38}\n\niob = {\n 'B-NP':1,\n 'I-NP':2,\n 'O':0\n}\n\nner = {\n 'PERSON':1,\n 'NORP':2,\n 'FAC':3,\n 'ORG':4,\n 'GPE':5,\n 'LOC':6,\n 'PRODUCT':7,\n 'EVENT':8,\n 'WORK_OF_ART':9,\n 'LAW':10,\n 'LANGUAGE':11,\n 'DATE':12,\n 'TIME':13,\n 'PERCENT':14,\n 'MONEY':15,\n 'QUANTITY':16,\n 'ORDINAL':17,\n 'CARDINAL':18,\n '':19\n}\n\ndef countSent(tokens):\n countVPos = 0\n countPos = 0\n countNeutral = 0\n countNeg = 0\n countVNeg = 0\n for core_tok in tokens:\n # Sentiment\n core_w_sent = core_tok.sentiment\n # print(core_w_sent)\n polw = 0\n if core_w_sent == 'Very negative':\n polw = -2\n countVNeg += 1\n if core_w_sent == 'Negative':\n polw = -1\n countNeg += 1\n if core_w_sent == 'Positive':\n polw = 1\n countPos += 1\n if core_w_sent == 'Very positive':\n polw = 2\n countVPos += 1\n if core_w_sent == 'Neutral':\n polw = 0\n countNeutral += 1\n return countVPos, countPos, countNeutral, countNeg, countVNeg\n\n\ndef countEsclamation(tw):\n esclamation = 0\n for token in tw.split():\n if (token == '!' or token == '!!' or token == '!!!' or token == '!!!!'):\n esclamation += 1\n return esclamation\n\ndef countQMark(tw):\n esclamation = 0\n for token in tw.split():\n if (token == '!' or token == '!!' or token == '!!!' or token == '!!!!'):\n esclamation += 1\n return esclamation\n\ndef countStopWord(tw):\n f = pd.read_fwf ( 'stopword_en' )\n stopList = f[ : ]\n isStop = 0\n for token in tw.split():\n if token in stopList:\n isStop += 1\n return isStop\n\ndef countInDictionary(tw):\n f = pd.read_fwf ( 'dict_basic_en' )\n stopList = f[ : ]\n isStop = 0\n for token in tw.split():\n if token in stopList:\n isStop += 1\n return isStop\n\n\nprefix_re = re.compile(r'''^[\\[\\(\"']''')\nsuffix_re = re.compile(r'''[\\]\\)\"']$''')\ninfix_re = re.compile(r'''[-~]''')\nsimple_url_re = re.compile(r'''^https?://''')\ndef custom_tokenizer(nlp):\n return Tokenizer(nlp.vocab, prefix_search=prefix_re.search,\n suffix_search=suffix_re.search,\n infix_finditer=infix_re.finditer,\n token_match=simple_url_re.match)\n\ndef countNouns(tw):\n count = 0\n for tupla in tw:\n if tupla[1] == 'NN' or tupla[1] == 'NNP' or tupla[1] == 'NNS' or tupla[1] == 'NNPS':\n count+=1\n return count\n\ndef countVerbs( tw ):\n count = 0\n for tupla in tw:\n if tupla[ 1 ] == 'VB' or tupla[ 1 ] == 'VBD' or tupla[ 1 ] == 'VBG' or tupla[ 1 ] == 'VBN' or tupla[ 1 ] == 'VBN' or tupla[ 1 ] == 'VBP' or tupla[ 1 ] == 'VBZ ':\n count += 1\n return count\n\ndef countAdjectivies ( tw ):\n count = 0\n for tupla in tw:\n if tupla[ 1 ] == 'JJ' or tupla[ 1 ] == 'JJR' or tupla[ 1 ] == 'JJS':\n count += 1\n return count\n\ndef countPronoun ( tw ):\n count = 0\n for tupla in tw:\n if tupla[ 1 ] == 'PRP' or tupla[ 1 ] == 'PRP$':\n count += 1\n return count\n\ndef countAdverb ( tw ):\n count = 0\n for tupla in tw:\n if tupla[ 1 ] == 'RB' or tupla[ 1 ] == 'RBR' or tupla[ 1 ] == 'RBS':\n count += 1\n return count\n\ndef countEmoji(text):\n emoji_counter = 0\n data = regex.findall(r'\\X', text)\n for word in data:\n if any(char in emoji.UNICODE_EMOJI for char in word):\n emoji_counter += 1\n # Remove from the given text the emojis\n text = text.replace(word, '')\n\n words_counter = len(text.split())\n\n return emoji_counter, words_counter\n\ndef countHashtags(tw):\n pat = re.compile ( r\"#(\\w+)\" )\n l = pat.findall (tw)\n return len(l)\n\ndef numSpecial_meta(tw):\n countMention = 0\n countReserved = 0\n countUrls = 0\n countNumbers= 0\n countPercents = 0\n countEmails = 0\n countMoney = 0\n countPhone = 0\n countTime = 0\n countDate = 0\n\n for c in tw:\n if c == '':\n countMention+=1\n if c == '':\n countReserved+=1\n if c == '' or c == '':\n countUrls+=1\n if c == '':\n countNumbers+=1\n if c == '':\n countPercents+=1\n if c == '':\n countEmails+=1\n if c == '':\n countMoney+=1\n if c == '':\n countPhone+=1\n if c == '
    sflkj\"\nthe_html = BeautifulSoup(text,features='lxml')\nprint(the_html.find('a').attrs['href'])\n'''\n\ndef factorial(n):\n x = 1\n for i in range(1, n+1):\n x = x * i\n # return x\n print(x)\nfactorial(20)","sub_path":"ads.py","file_name":"ads.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"296910726","text":"# -*- coding: utf-8 -*-\nfrom pyalgotrade import strategy\nfrom pyalgotrade.broker import Order\nimport abc\nimport logging\n\nclass TradingSystem(strategy.BaseStrategy):\n def __init__(self, feed, broker, debugMode=True, tradingAlgorithm=None):\n super(TradingSystem, self).__init__(feed, broker)\n self.setUseEventDateTimeInLogs(True)\n self.__setDebugMode(debugMode)\n\n self.__tradingAlgorithm = tradingAlgorithm\n\n def setAlgorithm(self, tradingAlgorithm):\n self.__tradingAlgorithm = tradingAlgorithm\n\n def getAlgorithm(self):\n return self.__tradingAlgorithm\n\n def __setDebugMode(self, debugOn):\n \"\"\"Enable/disable debug level messages in the strategy and backtesting broker.\n This is enabled by default.\"\"\"\n level = logging.DEBUG if debugOn else logging.INFO\n self.getLogger().setLevel(level)\n self.getBroker().getLogger().setLevel(level)\n\n def onOrderUpdated(self, order):\n assert order.getType() == Order.Type.MARKET or order.getType() == Order.Type.STOP\n\n if order.getType() == Order.Type.STOP:\n return\n\n assert order.getAction() == Order.Action.BUY or order.getAction() == Order.Action.SELL\n\n instrument = order.getInstrument()\n if order.getAction() == Order.Action.BUY and (order.getState() == Order.State.FILLED or order.getState() == Order.State.PARTIALLY_FILLED):\n shares = self.getBroker().getShares(instrument)\n self.stopOrder(instrument=instrument, stopPrice=order.stopLossValue, quantity=(-1*shares), goodTillCanceled=True, allOrNone=True)\n elif order.getAction() == Order.Action.SELL and order.getState() == Order.State.ACCEPTED:\n #verify if there was a colision between an sell order and a stop order;\n activeOrders = self.getBroker().getActiveOrders(instrument=instrument)\n if len(activeOrders) == 1 and activeOrders[0].getId() == order.getId():\n self.warning(\"Collision between stop loss and sell condition submitted at %s\" % (order.getSubmitDateTime())) #I could solve that if, before explicitly exiting a position, I verified that the trade was proffitable. That way, the only way to exit a proffitable trade would be via stop loss, so no collisions would happen.\n self.getBroker().cancelOrder(order)\n elif order.getAction() == Order.Action.SELL and order.getState() == Order.State.FILLED:\n stopOrder = [ o for o in self.getBroker().getActiveOrders(instrument=instrument) if o.getType()==Order.Type.STOP][0]\n assert stopOrder.getType() == Order.Type.STOP\n self.getBroker().cancelOrder(stopOrder)\n\n def isOpenPosition(self, instrument):\n return instrument in self.getBroker().getActiveInstruments()\n\n def enterPosition(self, instrument, quantity, stopLossValue):\n assert quantity > 0;\n assert not self.isOpenPosition(instrument)\n\n self.debug(\"Order to buy %s shares of %s at %s\" % (quantity, instrument, self.getBroker().getCurrentDateTime()))\n order = self.marketOrder(instrument=instrument, quantity=quantity, goodTillCanceled=False, allOrNone=True)\n order.stopLossValue = stopLossValue #o ideal seria um ter um novo tipo de ordem pra preencher esse valor.\n\n def exitPosition(self, instrument):\n assert instrument in self.getBroker().getActiveInstruments()\n qty = self.getBroker().getShares(instrument)\n assert qty>0\n\n self.debug(\"Order to sell %s shares of %s at %s\" % (qty, instrument, self.getBroker().getCurrentDateTime()))\n self.marketOrder(instrument=instrument, quantity=(-1*qty))\n\n def onBarsImpl(self, bars, instrument):\n self.__tradingAlgorithm.onBars(bars, instrument)\n\n if (not self.__tradingAlgorithm.shouldAnalyze(bars, instrument)):\n self.debug(\"Skipping stock %s at date %s\" % (len(bars.getInstruments()), bars.getDateTime()))\n return\n\n bar = bars.getBar(instrument)\n if self.isOpenPosition(instrument): # open position\n if self.__tradingAlgorithm.shouldSellStock(bar, instrument):\n self.exitPosition(instrument)\n elif self.__tradingAlgorithm.shouldBuyStock(bar, instrument):\n size = self.__tradingAlgorithm.calculateEntrySize(bar, instrument)\n stopLoss = self.__tradingAlgorithm.calculateStopLoss(bar, instrument)\n self.enterPosition(instrument, size, stopLoss)\n\n def onBars(self, bars):\n assert self.__tradingAlgorithm is not None, \"Algorithm not attached.\"\n self.info(\"Processing date %s\" % (bars.getDateTime()))\n for instrument in bars.getInstruments():\n self.onBarsImpl(bars, instrument)\n\n\nclass TradingAlgorithm(object):\n __metaclass__ = abc.ABCMeta\n\n def __init__(self, feed, broker, technicalIndicators=None):\n self._feed = feed\n self._broker = broker\n self._technicalIndicators = technicalIndicators\n\n def onBars(self, bars, instrument):\n if self._technicalIndicators is None:\n return\n for ti in self._technicalIndicators.values():\n ti.onBars(bars, instrument)\n\n def getBroker(self):\n return self._broker\n\n def getTechnicalIndicators(self):\n return self._technicalIndicators if self._technicalIndicators is not None else {}\n\n @abc.abstractmethod\n def shouldAnalyze(self, bar, instrument):\n \"\"\"\n :param dateTime: datetime of the event.\n :type dateTime: dateTime.datetime.\n \"\"\"\n raise NotImplementedError()\n\n @abc.abstractmethod\n def shouldSellStock(self, bar, instrument):\n raise NotImplementedError()\n\n @abc.abstractmethod\n def shouldBuyStock(self, bar, instrument):\n raise NotImplementedError()\n\n @abc.abstractmethod\n def calculateEntrySize(self, bar, instrument):\n raise NotImplementedError()\n\n @abc.abstractmethod\n def calculateStopLoss(self, bar, instrument):\n raise NotImplementedError()","sub_path":"pytrade/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":6022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"495477288","text":"import sys, os\n\ncwd = os.getcwd()\nsys.path.append(cwd)\nsys.path.append(\"%s/../\" % cwd)\nimport config\nimport numpy as np\n\nNSE = 1472\nK = 50\nIFOLD = config.IFOLD\n\n\ndef loadMapPathway2Des():\n fin = open(config.KEGG_PATHWAY_FILE)\n d = dict()\n while True:\n l = fin.readline()\n if l == \"\":\n break\n l = l.strip().split(\"\\t\")\n d[l[0]] = l[1]\n fin.close()\n return d\n\n\ndef loadMapUnipro2Path():\n fin = open(config.KEGG_UNIPROT_PATHWAY_MAPPING_PATH)\n d = dict()\n while True:\n line = fin.readline()\n if line == \"\":\n break\n line = line.strip().split(\"|\")\n uniprot = line[0]\n pathws = line[1].split(\",\")\n pathSets = set()\n for pw in pathws:\n pathSets.add(pw)\n d[uniprot] = pathSets\n fin.close()\n return d\n\n\ndef loadFPDescription():\n fin = open(config.PUBCHEM_FINGERPRINT_FILE)\n dfp2Des = dict()\n while True:\n line = fin.readline()\n if line == \"\":\n break\n line = line.strip()\n try:\n v = int(line[0])\n sp = line.index(\"\\t\")\n id = int(line[:sp])\n des = line[sp + 1:]\n dfp2Des[id] = des\n except:\n continue\n fin.close()\n return dfp2Des\n\n\ndef export(patternPath, chemInchikey):\n from dataFactory.dataset import Dataset\n dataset = Dataset()\n fout = open(\"%s/matching_fp2.txt\" % config.OUTPUT_DIR, \"a\")\n fout.write(\"%s : %s\\n\" % (chemInchikey, patternPath))\n fin = open(patternPath)\n data = fin.readline().strip()\n fin.close()\n parts = data.split(\"\\t\")\n dfp2Des = loadFPDescription()\n fpList = set()\n\n for part in parts:\n sp = part.index(\":\")\n p1, p2 = part[:sp], part[sp + 1:]\n v = float(p1)\n if v < 0.1:\n break\n if p2.startswith(\"FP\"):\n fp = int(p2[2:])\n fpList.add(fp)\n chemId = dataset.chemInchiKey2Id[chemInchikey]\n chemFp = dataset.chemId2Features[chemId]\n nonZeros = np.nonzero(chemFp)[0]\n for idx in nonZeros:\n if idx in fpList:\n fout.write(\"%s\\t%s\\n\" % (idx, dfp2Des[idx]))\n fout.close()\n\n\ndef export_top_fp(patternPath):\n import utils.utils\n pathOut = \"%s%s.txt\" % (config.TOP_DESCRIPTORS_PATH_PREFIX, IFOLD)\n #utils.utils.ensure_dir(pathOut)\n fout = open(pathOut, \"w\")\n fout.write(\"%s : \\n\" % patternPath)\n fin = open(patternPath)\n\n dfp2Des = loadFPDescription()\n dpw2Des = loadMapPathway2Des()\n duni2Pws = loadMapUnipro2Path()\n\n def getfpDesFromInd(idx):\n try:\n des = dfp2Des[idx]\n except:\n des = idx\n return des\n\n cT = 0\n while True:\n data = fin.readline().strip()\n if data == \"\":\n break\n cT += 1\n\n fout.write(\"Latent group: %s\\n\" % cT)\n fpList = []\n proteinList = []\n pathwayList = []\n parts = data.split(\"\\t\")\n mx = -1\n nc = 0\n\n for part in parts:\n sp = part.index(\":\")\n p1, p2 = part[:sp], part[sp + 1:]\n v = float(p1)\n if mx == -1:\n mx = v\n if (v < 0.1 or mx / v > 10) and nc > 20:\n break\n nc += 1\n if p2.startswith(\"FPT\"):\n fp = int(p2[4:])\n fpList.append(fp)\n elif p2.startswith(\"PWY\"):\n pathwayList.append(p2[4:])\n else:\n proteinList.append(p2[4:])\n\n fout.write(u\"Substructures\\n\")\n for idx in fpList:\n fout.write(\"%s\\t%s\\n\" % (idx, getfpDesFromInd(idx)))\n fout.write(u\"Protein\\n\")\n for p in proteinList:\n # fout.write(\"%s\\n\"%p)\n fout.write(\"%s :\" % p)\n dPW = utils.utils.get_dict(duni2Pws, p, set())\n\n for pw in pathwayList:\n if pw in dPW:\n fout.write(\" %s\" % pw)\n fout.write(\"\\n\")\n\n fout.write(u\"Pathway\\n\")\n for pw in pathwayList:\n fout.write(u\"%s\\t%s\\n\" % (pw, dpw2Des[pw]))\n fout.write(\"\\n\\n===========================\\n\\n\")\n\n if cT == 46:\n fpList = []\n proteinList = []\n pathwayList = []\n fout.write(\"Full G46\\n\")\n for part in parts:\n sp = part.index(\":\")\n p1, p2 = part[:sp], part[sp + 1:]\n v = float(p1)\n if mx == -1:\n mx = v\n if v < 0.001:\n break\n nc += 1\n if p2.startswith(\"FP\"):\n fp = int(p2[4:])\n fpList.append(fp)\n elif p2.startswith(\"PWY\"):\n pathwayList.append(p2[4:])\n else:\n proteinList.append(p2[4:])\n\n fout.write(u\"Substructures\\n\")\n for idx in fpList:\n fout.write(\"%s\\t%s\\n\" % (idx, getfpDesFromInd(idx)))\n fout.write(u\"Protein\\n\")\n for p in proteinList:\n # fout.write(\"%s\\n\"%p)\n fout.write(\"%s :\" % p)\n dPW = utils.utils.get_dict(duni2Pws, p, set())\n\n for pw in pathwayList:\n if pw in dPW:\n fout.write(\" %s\" % pw)\n fout.write(\"\\n\")\n\n fout.write(u\"Pathway\\n\")\n for pw in pathwayList:\n fout.write(u\"%s\\t%s\\n\" % (pw, dpw2Des[pw]))\n fout.write(\"\\n\\n===========================\\n\\n\")\n\n fin.close()\n fout.close()\n\n\nif __name__ == \"__main__\":\n # path = \"../out/dynamic/P0/P_0_X\"\n # inchi = \"CZFFBEXEKNGXKS-UHFFFAOYSA-N\"\n # export(path,inchi)\n # config.IFOLD = \"X\"\n IFOLD = config.IFOLD\n path = \"%s%s\" % (config.LATENT_GROUP_PATTERN_PATH_PREFIX, IFOLD)\n export_top_fp(path)\n","sub_path":"postprocessing/export_fp_matching.py","file_name":"export_fp_matching.py","file_ext":"py","file_size_in_byte":5870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"181136100","text":"from bot import dp, types\nfrom defs import normalize_fund_title, choose_default_fund, fund_sum, fund_string, get_fund_image\n\n\nasync def send_fund(message, fund_total, fund_title, fund_goal):\n fund_title = fund_title[1:]\n\n if fund_goal == 0:\n await message.reply(fund_string(fund_total, fund_title, fund_goal), parse_mode='HTML', disable_web_page_preview=True)\n else:\n image_path = get_fund_image(fund_total, fund_title, fund_goal)\n await message.reply_photo(types.InputFile(image_path), parse_mode='HTML')\n\n\n@dp.message_handler(commands=['fund'])\nasync def fund(message: types.Message):\n text_parts = message.text.split()\n\n if len(text_parts) == 1:\n fund_title = await choose_default_fund()\n _fund = await fund_sum(fund_title.lower())\n else:\n fund_title = normalize_fund_title(text_parts[1])\n _fund = await fund_sum(fund_title)\n\n if _fund:\n fund_total, fund_goal = _fund\n await send_fund(message, fund_total, fund_title, fund_goal)\n else:\n await message.reply('Фонд не найден', parse_mode='HTML')\n","sub_path":"tgbot/bot/modules/fund/Fund.py","file_name":"Fund.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"51105846","text":"#!/usr/bin/env python\n\nfrom gimpfu import *\nimport glob\nimport os\n\npdb = gimp.pdb\n\ndef createplanet_batch(athmospherecolor, postprocessing, bumplayeropacity, distance, gasopacity, groupundo, prefixdetection, planettype, loadfolder, fileextension, savexcf):\n\n# correct loadfolder: add (back-)slash if needed\n if not loadfolder.endswith((\"/\", \"\\\\\")):\n if os.name == \"nt\": # we need backslashes on windows, but slashes on linux/mac\n loadfolder = loadfolder + \"\\\\\"\n else:\n loadfolder = loadfolder + \"/\"\n\n# prepare the file pattern\n filepattern = loadfolder + fileextension\n filelist = glob.glob(filepattern)\n filelist.sort()\n #gimp.message(\" \".join(filelist)\n\n# loop once for every file\n for filepath in filelist:\n # load and set up the image\n if filepath.endswith((\".jpeg,\", \".jpg\")):\n image = pdb.file_jpeg_load(filepath, filepath)\n elif filepath.endswith(\".png\"):\n image = pdb.file_png_load(filepath, filepath)\n layer = image.active_layer\n # prepare filename\n if os.name == \"nt\": # we need backslashes on windows, but slashes on linux/mac\n outputfolder = \"%splanets\\\\\" % loadfolder # add the name of a new folder\n else:\n outputfolder = \"%splanets//\" % loadfolder # add the name of a new folder\n gimp.message(outputfolder)\n if not os.path.exists(outputfolder):\n os.makedirs(outputfolder) # create the new folder if it doesn't exist yet\n filenameext = os.path.basename(filepath) # remove the path and only keep the actual filename with extension\n filename, dummy = os.path.splitext(filenameext) # remove file extension. createplanet will add the correct extension, and we don't want to save an xcf as jpeg.\n outputpath = outputfolder + filename\n # set planettype and postprocessing via prefixdetection, if enabled\n if prefixdetection: # set post processing based on the file prefix, if prefix detection is enabled\n if filename.startswith((\"hp_\", \"otp_\", \"m\")):\n postprocessing = 1\n elif filename.startswith(\"gg_\"):\n postprocessing = 2\n \n if filename.startswith(\"hp_\"):\n planettype = 0\n elif filename.startswith(\"otp_\"):\n planettype = 1\n elif filename.startswith(\"m_\"):\n planettype = 2\n elif filename.startswith(\"ig_\"):\n planettype = 3\n elif filename.startswith(\"gg_\"):\n planettype = 4\n # let createplanet do the rest\n pdb.python_fu_createplanet(image, athmospherecolor, postprocessing, bumplayeropacity, distance, gasopacity, layer, groupundo, planettype, outputpath, savexcf)\n\n\n\nregister(\n \"createplanet_batch\",\n\tN_(\"Apply CreatePlanet to several files at once. CreatePlanet must be installed.\"),\n\t\"Use CreatePlanet with batch processing\",\n\t\"MCOfficer\",\n\t\"@Copyright 2017\",\n\t\"2017\",\n\tN_(\"_Batch Create Planet...\"),\n\t\"\",\n\t[\n\t(PF_COLOR, \"athmospherecolor\", \"Athmosphere Color. Default is white, only use a slight off-white tint for gas giants.\", (255,255,255)),\n\t(PF_RADIO, \"postprocessing\", \"Determines what post-processing will be used. Useless with Prefix Detection enabled.\", 0 , ((\"None\", 0),(\"Terrestrial Planet\", 1),(\"Gas Giant\", 2))),\n\t(PF_SLIDER, \"bumplayeropacity\", \"The opacity of the bumpmap layer. Only effective for terrestrial planets.\", 80, (0, 100, 1)),\n\t(PF_SLIDER, \"distance\", \"The motion blur distance. Only effective for gas giants.\", 150, (100, 200, 1)),\n\t(PF_SLIDER, \"gasopacity\", \"The gas layer opacity. Only effective for gas giants.\", 70, (0, 100, 1)),\n\t(PF_BOOL, \"groupundo\", \"Group undo steps? If this is true, you can undo the entire script at once.\", False ),\n\t(PF_BOOL, \"prefixdetection\", \"Prefix Detection sets planet type and post processing depending on the file's prefix. Possible prefixes are: 'hp', 'otp', 'm', 'ig', 'gg' plus and underscore. Example filename: 'hp[underscore]texture00303423.jpg'.\", True),\n\t(PF_OPTION, \"planettype\", \"Planettype, determines the width of the output image. Useless with Prefix Detection enabled.\", 1 , (\"Habitable Planet (150-210px)\", \"Other Terrestrial Planet (100-250px)\", \"Moon (60-110px)\", \"Ice Giant (280-360px)\", \"Gas Giant (360-450px)\")),\n (PF_STRING, \"loadfolder\", \"The location of your textures.\", \"\"),\n\t(PF_FILE, \"fileextension\", \"Files that should be loaded. Use * to load all files in this folder.\", \"*.jpg\"),\n\t(PF_BOOL, \"savexcf\", \"Do you want to save the .xcf source file? This is useless when Group Undo is enabled.\", True)\n\t],\n\t[],\n\tcreateplanet_batch,\n\tmenu=\"/Scripts/\",\n\tdomain=(\"gimp20-python\", gimp.locale_directory)\n)\n\nmain()\n","sub_path":"endless-sky/CreatePlanet Script/CreatePlanet_Batch v1.4.py","file_name":"CreatePlanet_Batch v1.4.py","file_ext":"py","file_size_in_byte":4729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"91055834","text":"import logging\n\nimport telegram\nfrom telegram.ext import Updater\nfrom telegram.ext import CommandHandler, MessageHandler\nfrom telegram.ext import Filters\n\nimport commands\nimport messages\nimport customFilters\n\nfrom settings import TOKEN\n\n\ndef error(bot, update, error):\n logger.warning('Update \"%s\" caused error \"%s\"', update, error)\n\n# logs for LaBot\n# Enable logging to handle uncaught exceptions\n\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n\t\t\t\t\tlevel=logging.INFO,\n\t\t\t\t\tfilename='LaBot.log')\n\nlogger = logging.getLogger(__name__)\n\ndef main():\n\tlogger.info(\"Initializing bot\")\n\tupdater = Updater(token=TOKEN)\n\tdp = updater.dispatcher\n\n\tdp.add_handler(CommandHandler('start', \t\t\tcommands.start), 1)\n\tdp.add_handler(CommandHandler('help', \t\t\tcommands.help ), 1)\n\tdp.add_handler(CommandHandler('showdeadlines', commands.show_deadlines), 1)\n\n\tdp.add_handler(MessageHandler(customFilters.unknown_files, \tmessages.unknown))\n\tdp.add_handler(MessageHandler( customFilters.LaBot_files, \tmessages.save))\n\n\tdp.add_error_handler(error)\n\n\tprint(\"\\nrunning...\\n\")\n\tlogger.info(\"The bot is enabled\")\n\n\tupdater.start_polling()\n\tupdater.idle()\n\tlogger.info(\"The bot is disabled\")\n\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"LaBot/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"487873304","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 29 18:45:44 2018\n\nAuthor: VigneshSP\n\nQuestion\nThe sum of the squares of the first ten natural numbers is,\n\n12 + 22 + ... + 102 = 385\nThe square of the sum of the first ten natural numbers is,\n\n(1 + 2 + ... + 10)2 = 552 = 3025\nHence the difference between the sum of the squares of the first ten natural\nnumbers and the square of the sum is 3025 − 385 = 2640.\n\nFind the difference between the sum of the squares of the first one hundred\nnatural numbers and the square of the sum.\n\"\"\"\nsquareSum=0\nSum=0\nfor x in range(1,101):\n squareSum+=x**2\n Sum += x\n\ndifference = (Sum**2)-squareSum\nprint(difference)\n","sub_path":"P06-Sum square difference.py","file_name":"P06-Sum square difference.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"153666276","text":"import pandas as pd\n\ndef movies_genres():\n genre_cols = [\"Animation\", \"Children's\", \n 'Comedy', 'Adventure', 'Fantasy', 'Romance', 'Drama',\n 'Action', 'Crime', 'Thriller', 'Horror', 'Sci-Fi', 'Documentary', 'War',\n 'Musical', 'Mystery', 'Film-Noir', 'Western']\n\n genre_and_title_cols = ['title'] + genre_cols \n return genre_and_title_cols \n\n\ndef get_movie_id(movies :pd.DataFrame, title, year=None):\n #print((movies['title'] == title))\n res = movies[(movies['title'] == title)]\n if year:\n res = res[(res['year'] == year)]\n\n if len(res) > 1:\n print(\"Ambiguous: found\")\n print(f\"{res['title']} {res['year']}\")\n elif len(res) == 0:\n print('not found')\n else:\n return res.index[0]\n\ndef get_movie_name(movies, index):\n return movies.iloc[index].title\n\ndef get_movie_year(movies, index):\n return movies.iloc[index].year\n\n","sub_path":"src/movies.py","file_name":"movies.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"14370112","text":"from tempfile import NamedTemporaryFile\nfrom celery.exceptions import Ignore\nfrom celery import Celery, states\nfrom bs4 import BeautifulSoup\nfrom zipfile import ZipFile\nimport requests\nimport imghdr\nimport os\n\nTIMEOUT = 5\nFORBIDDEN_TAGS = [\"script\", \"style\", \"table\", \"a\", \"img\", \"button\", \"header\", \"footer\", \"nav\"]\n\nCELERY_BROKER = os.environ.get('CELERY_BROKER_URL', 'redis://redis:6379')\nCELERY_BACKEND = os.environ.get('CELERY_RESULT_BACKEND', 'redis://redis:6379')\ncelery_app = Celery('tasks', backend=CELERY_BACKEND, broker=CELERY_BROKER)\n\n\n@celery_app.task(bind=True)\ndef get_url_text(self, url):\n try:\n html = requests.get(url, timeout=TIMEOUT).text\n soup = BeautifulSoup(html, features=\"html.parser\")\n\n if not soup.find('html'):\n raise TypeError\n\n for tag in soup.findAll(FORBIDDEN_TAGS):\n tag.extract()\n\n text = ' '.join(soup.get_text().split())\n text_file = NamedTemporaryFile(delete=False, suffix='.txt')\n text_file.write(str.encode(text))\n text_file.close()\n\n return text_file.name\n\n except Exception as e:\n raise TaskFailure(self, e)\n\n\n@celery_app.task(bind=True)\ndef get_url_images(self, url):\n try:\n html = requests.get(url, timeout=TIMEOUT).text\n urls = get_url_img_hrefs(html, url)\n\n zip_file = NamedTemporaryFile(delete=False, suffix='.zip')\n with ZipFile(zip_file.name, 'w') as zip_object:\n for i, url in enumerate(urls):\n img_bytes = requests.get(url, stream=True, timeout=TIMEOUT).content\n add_image_to_zip_object(img_bytes, i, zip_object)\n\n return zip_file.name\n\n except Exception as e:\n raise TaskFailure(self, e)\n\n\ndef get_url_img_hrefs(html, url):\n soup = BeautifulSoup(html, features=\"html.parser\")\n\n img_urls = [tag.get('src') for tag in soup.findAll('img', src=True)]\n domain = get_url_domain(url)\n return fix_relative_urls(img_urls, domain)\n\n\ndef get_url_domain(url):\n return '/'.join(url.split('/')[:3])\n\n\ndef fix_relative_urls(urls, domain):\n return [*map(lambda url: domain + url if url[0] == '/' else url, urls)]\n\n\ndef add_image_to_zip_object(img_bytes, filename, zip_object,):\n with NamedTemporaryFile() as img_file:\n img_file.write(img_bytes)\n img_type = imghdr.what(img_file.name)\n if img_type:\n zip_object.write(img_file.name, f'{filename}.{img_type}')\n\n\nclass TaskFailure(Exception):\n def __init__(self, task, exception):\n task.update_state(\n state=states.FAILURE,\n meta={\n 'exc_message': (type(exception).__name__, ),\n 'custom': '', 'exc_type': '',\n })\n raise Ignore()\n","sub_path":"celery_queue/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":2730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"174996861","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\n\nfrom article.views import ArticleListView, ArticleFullListView, ArticleDetailView\n\nurlpatterns = patterns('',\n\n url(r'^$', ArticleListView.as_view(), name='article-list'),\n url(r'^comments/', include('fluent_comments.urls')),\n url(r'^articles/', include('article.urls')),\n url(r'^admin/', include(admin.site.urls)),\n url(r'^register/$', 'registers.views.register'),\n url(r'^user/home/$', ArticleListView.as_view(), name='article-list'),\n\n url(r\"^delete_comment/(?P\\d+)/$\", \"recipes.views.delete_own_comment\", name='delete_own_comment'),\n url(r\"^comment_deleted\", \"recipes.views.comment_deleted\"),\n\n\n)\n\n\nurlpatterns += patterns(\n 'django.contrib.auth.views',\n\n url(r'^login/$', 'login',\n {'template_name': 'login.html'},\n name='my_login'),\n url(r'^logout/$', 'logout',\n {'next_page': '/'},\n name='my_logout'),\n)\n","sub_path":"simple_web/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"491003760","text":"import re #created by Abhishek Muthe\r\nimport scrapy\r\nimport details\r\nfrom selenium import webdriver \r\nfrom selenium.common.exceptions import NoSuchElementException\r\nfrom scrapy.selector import Selector\r\nfrom time import sleep\r\nfrom selenium.webdriver import ChromeOptions\r\n#driver.get('chrome://settings/')\r\n#driver.execute_script('chrome.settingsPrivate.setDefaultZoom(0.5);')\r\n\r\nclass User():\r\n\t\r\n\tdef __init__(self, driver, url):\r\n\t\tself.driver = driver\r\n\t\tself.url = url\r\n\r\n\r\n\tdef login(self):\r\n\t\tself.driver.maximize_window()\r\n\t\tself.driver.get(self.url)\r\n\t\ttypeusername = self.driver.find_element_by_id('myusername')\r\n\t\ttypepassword = self.driver.find_element_by_name('mypassword')\r\n\t\ttypeusername.send_keys(details.username)\r\n\t\ttypepassword.send_keys(details.password)\r\n\t\tlogin_acc = self.driver.find_element_by_id(\"submit\")\r\n\t\tlogin_acc.click()\r\n\t\r\ndef battlesearch(driver):\r\n\tglobal i\r\n\ti = 0\r\n\tbattle_url = 'https://www.pokemon-vortex.com/battle-search/'\r\n\tdriver.get(battle_url)\r\n\ttrain = driver.find_element_by_xpath('//*[@name=\"buser\"]')\r\n\ttrain.send_keys(details.training_acc)\r\n\tbattle = driver.find_element_by_xpath('//*[@name=\"submitb\"]')\r\n\tbattle.click()\r\n\twhile i < 6:\r\n\t\ttry:\r\n\t\t\tsleep(0.2)\r\n\t\t\tbacktoteam(driver)\r\n\t\t\tattack(driver)\r\n\t\t\tcontinuos(driver)\r\n\t\t\ti = i + 1\r\n\t\texcept:\r\n\t\t\treturn battlesearch(driver)\r\ndef backtoteam(driver):\r\n\twhile True:\r\n\t\ttry:\r\n\t\t\tsleep(0.2)\r\n\t\t\tsel = Selector(text=driver.page_source)\r\n\t\t\ta = sel.xpath('//*[@class=\"button-maroon button-small\"]/@value').extract()\r\n\t\t\tr = re.compile(\".*ntinu*.\")\r\n\t\t\tb = list(filter(r.match, a))\r\n\t\t\tb = \"\".join(map(str, b))\r\n\t\t\td = '//*[@value=\"foo\"]'\r\n\t\t\td = d.replace(\"foo\", b)\r\n\t\t\tdriver.execute_script(\"window.scrollTo(0, 1000)\")\r\n\t\t\tnum1 = sel.xpath('//*[@id=\"nojs-solve-a\"]/@value').extract()\r\n\t\t\tnum2 = sel.xpath('//*[@id=\"nojs-solve-b\"]/@value').extract()\r\n\t\t\tnum1 = int(\"\".join(map(str, num1)))\r\n\t\t\tnum2 = int(\"\".join(map(str, num2)))\r\n\t\t\tnum = num1 + num2\r\n\t\t\tv = driver.find_element_by_xpath('//*[@id=\"nojs-solve-v\"]')\r\n\t\t\tv.send_keys(num)\r\n\t\t\tc = driver.find_element_by_xpath(d)\r\n\t\t\tsleep(0.2)\r\n\t\t\tc.click()\r\n\t\texcept:\r\n\t\t\tbreak\r\n\t\r\ndef attack(driver):\r\n\twhile True:\r\n\t\ttry:\r\n\t\t\tsels = Selector(text=driver.page_source)\r\n\t\t\tat = sels.xpath('//*[@class=\"button-maroon button-small\"]/@value').extract()\r\n\t\t\tr = re.compile(\".*ttac*.\")\r\n\t\t\tb = list(filter(r.match, at))\r\n\t\t\tb = \"\".join(map(str, b))\r\n\t\t\td = '//*[@value=\"fooo\"]'\r\n\t\t\td = d.replace(\"fooo\", b)\r\n\t\t\t#driver.execute_script('window.scrollTo(0, 200)')\r\n\t\t\tsleep(0.2)\r\n\t\t\tattack = driver.find_element_by_xpath(d)\r\n\t\t\tattack.click()\r\n\t\texcept:\r\n\t\t\tbreak\r\n\t\r\ndef continuos(driver):\r\n\twhile True:\r\n\t\ttry:\r\n\t\t\tsleep(0.2)\r\n\t\t\tseli = Selector(text=driver.page_source)\r\n\t\t\tat = seli.xpath('//*[@class=\"button-maroon button-small\"]/@value').extract()\r\n\t\t\t#r = re.compile(\".*ntinu*.\")\r\n\t\t\t#e = list(filter(r.match, at))\r\n\t\t\tf = at[1:2]\r\n\t\t\tf = \"\".join(map(str, f))\r\n\t\t\tg = '//*[@value=\"foooo\"]'\r\n\t\t\tg = g.replace(\"foooo\", f)\r\n\t\t\tt = driver.find_element_by_xpath(g)\r\n\t\t\t#driver.execute_script('window.scrollTo(0, 250)')\r\n\t\t\tsleep(0.2)\r\n\t\t\tt.click()\r\n\t\texcept:\r\n\t\t\tbreak\r\ndef rebattle(driver, l):\r\n\tsleep(0.2)\r\n\t# l = driver.find_element_by_xpath('//*[@class=\"menu-tab\"]/a')\r\n\t# l = l.get_attribute('href')\r\n\tdriver.get(l)\r\n\ti = 0\r\n\twhile i < 6:\r\n\t\ttry:\r\n\t\t\tsleep(0.2)\r\n\t\t\tbacktoteam(driver)\r\n\t\t\tattack(driver)\r\n\t\t\tcontinuos(driver)\r\n\t\t\ti = i + 1\r\n\t\texcept:\r\n\t\t\treturn rebattle(driver, l)\r\n\treturn rebattle(driver, l)\r\n\t\r\ndef getlink(driver):\r\n\tglobal l\r\n\tl = driver.find_element_by_xpath('//*[@class=\"menu-tab\"]/a')\r\n\tl = l.get_attribute('href')\r\n\r\n\r\ndef main():\r\n\toptions = ChromeOptions()\r\n\tprefs = {'profile.managed_default_content_settings.javascript': 2}\r\n\toptions.add_experimental_option('prefs', prefs)\r\n\turl = 'https://www.pokemon-vortex.com/login/'\r\n\tdriver = webdriver.Chrome('Add your path here/chromedriver.exe', options=options) #Add path here with '/' slash\r\n\tuser = User(driver, url)\r\n\tuser.login()\r\n\tbattlesearch(driver)\r\n\tgetlink(driver)\r\n\trebattle(driver ,l)\r\n\r\nif __name__ == '__main__':\r\n\tmain()\r\n\t\t\r\n\t\t\t\r\n\t\r\n\t\r\n\t","sub_path":"Exp Bot/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":4075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"234390231","text":"#!/usr/bin/\n\n# Date created : 09-20-2016\n# File name : VignetteAutomation_v1.py\n# Author : Dixant Rai, IT, Turn5 Inc\n# Python Version : 2.7\n# Description : This python script creates vignette files (.vnt) using the Scene7 Image Authoring - Vignette Authoring Tool\n# Prerequisites : 1. Folder \"InputFiles\" should exist in the same folder as this python file\n# 2. The InputFiles folder should contain two types of files - for example:\n# a) J104707_alt4.psd : This is the base image file in *.psd format.\n# b) J104707_alt4-mask.png : This is the mask file in *.png format, to be applied to the base file.\n# This file must have the same filename as the base file in (a) appended with the \"-mask\" suffix.\n# Output : The \"OutputFiles\" folder is re-created on every run. For each qualifying pair of the input files, an output file\n# with the same filename with .vnt extension is created. (eg. J104707_alt4.vnt).\n# Log.txt file will contain logs for each file in the \"InputFiles\" folder.\n#\n# History \n# Version Date Modifer Comment\n# 1.0 09-20-2016 Dixant Rai Created\n# 1.1 10-14-2016 Dixant Rai Adjusted script so that main image file without \"_alt\" are also be processed.\n\nimport datetime\nimport time\nimport os\nimport shutil\nimport fnmatch\nfrom os.path import splitext\nfrom s7vampy import *\n\n# set working dir to the location of this python file\ndir_path = os.path.dirname(os.path.realpath('__file__'))\nlog_path = os.path.join(dir_path,'log.txt')\n\ndef writetolog(textfile,text):\n f = open(textfile,'a')\n ts = time.time()\n timestamp = str(datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))\n f.write(timestamp + '\\t' + text + '\\n')\n f.close()\n\ndef ignore_patterns(*patterns):\n \"\"\"Function that can be used as copytree() ignore parameter.\n Patterns is a sequence of glob-style patterns\n that are used to exclude files\"\"\"\n def _ignore_patterns(path, names):\n ignored_names = []\n for pattern in patterns:\n ignored_names.extend(fnmatch.filter(names, pattern))\n return set(ignored_names)\n return _ignore_patterns\n\ndef copyDirectory(src, dest):\n # delete destination path if it exist\n if os.path.exists(dest):\n shutil.rmtree(dest)\n \n try:\n shutil.copytree(src, dest,ignore=ignore_patterns('*.*'))\n # Directories are the same\n except shutil.Error as e:\n writetolog(log_path,'Directory not copied. Error: %s' % e)\n # Any error saying that the directory doesn't exist\n except OSError as e:\n writetolog(log_path,'Directory not copied. Error: %s' % e)\n\ndef createVignette(parent_file,mask_file,group_name,nontexturable_obj_name,log_path):\n vignette_file = parent_file.replace('.psd','.vnt')\n vignette_file = vignette_file.replace('InputFiles','OutputFiles')\n v = create_vignette(open_image(parent_file))\n v.view.illum[0] = open_image(parent_file)\n group = v.objects.add_group(group_name)\n obj = group.add_nontexturable_object(nontexturable_obj_name, open_image(mask_file)) \n try:\n v.save(vignette_file)\n except OSError as e:\n writetolog(log_path,'\\t Error: %s' % e)\n\ndef main(): \n # set working dir to the location of this python file\n dir_path = os.path.dirname(os.path.realpath('__file__'))\n\n # set source, destination and log file paths\n source_path = os.path.join(dir_path, 'InputFiles')\n dest_path = os.path.join(dir_path, 'OutputFiles')\n log_path = os.path.join(dir_path,'log.txt')\n\n # replicated directory structure from source to destination\n copyDirectory(source_path, dest_path)\n\n writetolog(log_path,'****Begin Process***')\n\n # traverse source_path to find base *.psd images\n for dirName, subdirList, fileList in os.walk(source_path):\n subdir = subdirList or '*Root*'\n writetolog(log_path,'Directory: %s' % subdir)\n for fname in fileList:\n # only process *.psd files\n if (splitext(fname)[1].lower() == '.psd'):\n # only process images for which a corresponding '*-mask.png' file exists\n if os.path.exists(os.path.join(dirName, fname.replace('.psd','-mask.png'))):\n parent = os.path.join(dirName, fname)\n mask = os.path.join(dirName, fname.replace('.psd','-mask.png'))\n createVignette(parent,mask,'car','color',log_path)\n writetolog(log_path,'\\t{0:50} : Successfully processed'.format(fname))\n else:\n # writetolog(log_path,'\\t%s' % fname + ' : Not Processed - corresponding file %s does not exist' % fname.replace('.psd','-mask.png'))\n writetolog(log_path,'\\t{0:50} : Not Processed - corresponding file [%s] does not exist'.format(fname) % fname.replace('.psd','-mask.png'))\n\n writetolog(log_path,'****End Process***' + '\\n')\n\nif __name__ == '__main__':\n main()\n","sub_path":"VignetteAutomation_v2 - backup.py","file_name":"VignetteAutomation_v2 - backup.py","file_ext":"py","file_size_in_byte":5162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"115033895","text":"import tkinter as tk\r\nimport tkinter.ttk as ttk\r\n\r\nNAME = 0\r\nROOM = 1\r\nDOB = 2\r\n\r\n\r\nclass TextScrollCombo(tk.Frame):\r\n def __init__(self, *args, **kwargs):\r\n\r\n super().__init__(*args, **kwargs)\r\n\r\n # ensure a consistent GUI size\r\n self.grid_propagate(False)\r\n # implement stretchability\r\n self.grid_rowconfigure(0, weight=1)\r\n self.grid_columnconfigure(0, weight=1)\r\n\r\n # create a Text widget\r\n self.txt = tk.Text(self, wrap=tk.WORD)\r\n self.txt.grid(row=0, column=0, sticky=\"nsew\", padx=2, pady=2)\r\n\r\n # create a Scrollbar and associate it with txt\r\n scrollb = ttk.Scrollbar(self, command=self.txt.yview)\r\n scrollb.grid(row=0, column=1, sticky='nsew')\r\n self.txt['yscrollcommand'] = scrollb.set\r\n\r\n def gettext(self):\r\n # I seem to always get an extra '\\n' this is how I'm correcting this\r\n temp=self.txt.get(\"1.0\", tk.END)\r\n return temp[:len(temp)-1]\r\n\r\n def gettextaslines(self):\r\n return self.txt.get('1.0',tk.END).splitlines()\r\n\r\n def cleartext(self):\r\n self.txt.delete(1.0, tk.END)\r\n\r\n def settext(self, thistext):\r\n self.cleartext()\r\n self.txt.insert(tk.END, thistext)\r\n\r\n def setstate(self, newstate):\r\n self.txt.config(state=newstate)\r\n\r\n def appendtext(self, thistext):\r\n self.txt.insert(tk.END, thistext + \"\\n\")\r\n\r\n\r\nclass MyListBox(tk.Frame):\r\n def __init__(self, boxfont, *args, **kwargs):\r\n super().__init__(*args, **kwargs)\r\n\r\n self.grid_rowconfigure(0, weight=1)\r\n self.grid_columnconfigure(0, weight=1)\r\n\r\n self.grid_columnconfigure(5, weight=1)\r\n thisrow = 1\r\n\r\n self.listbox = tk.Listbox(self, font=boxfont, exportselection=False, height=5)\r\n self.scrollbar = tk.Scrollbar(self)\r\n self.scrollbar.config(command=self.yview)\r\n\r\n self.listbox.grid(row=thisrow, column=1, sticky='news')\r\n self.scrollbar.grid(row=thisrow, column=2, sticky='ns')\r\n\r\n self.listbox.config(yscrollcommand=self.scrollbar.set)\r\n\r\n thisrow = thisrow + 1\r\n self.grid_rowconfigure(thisrow, weight=1)\r\n\r\n def yview(self, *args):\r\n self.listbox.yview(*args)\r\n\r\n def addpatient(self, thistext, index):\r\n self.listbox.insert(index, thistext)\r\n\r\n def clearlistboxes(self):\r\n self.listbox.delete(0, 'end')\r\n\r\n def populatelistbox(self, textarray):\r\n self.clearlistboxes()\r\n for index, element in enumerate(textarray):\r\n self.addpatient(element, index)\r\n\r\n def whichchosen(self):\r\n\r\n if len(self.listbox.curselection()) == 0:\r\n return -1\r\n else:\r\n return self.listbox.get(self.listbox.curselection()[0])\r\n\r\n\r\nclass MyMultiListBox(tk.Frame):\r\n def __init__(self, patient_obj, buttonfont, *args, **kwargs):\r\n\r\n super().__init__(*args, **kwargs)\r\n\r\n self.patient_obj = patient_obj\r\n\r\n self.grid_rowconfigure(0, weight=1)\r\n self.grid_columnconfigure(0, weight=1)\r\n\r\n self.grid_columnconfigure(5, weight=1)\r\n thisrow = 1\r\n\r\n button_forwardjump = tk.Button(self, font=buttonfont, text=\"Scroll forward 10\")\r\n button_forwardjump.config(command=lambda: self.scrolljump(1))\r\n button_forwardjump.grid(row=thisrow, column=1, sticky='news')\r\n\r\n button_backjump = tk.Button(self, font=buttonfont, text=\"Scroll backward 10\")\r\n button_backjump.config(command=lambda: self.scrolljump(-1))\r\n button_backjump.grid(row=thisrow, column=3, sticky='news')\r\n\r\n thisrow = thisrow + 1\r\n\r\n button_sortbyname = tk.Button(self, text=\"Name\", font=buttonfont, width=20)\r\n button_sortbyname.config(command=lambda: self.sortlist(NAME))\r\n button_sortbyname.grid(row=thisrow, column=1, sticky='news')\r\n\r\n button_sortbydob = tk.Button(self, text=\"Date of Birth\", font=buttonfont, width=20)\r\n button_sortbydob.config(command=lambda: self.sortlist(DOB))\r\n button_sortbydob.grid(row=thisrow, column=2, sticky='news')\r\n\r\n button_sortbyroom = tk.Button(self, text=\"Room\", width=20, font=buttonfont)\r\n button_sortbyroom.config(command=lambda: self.sortlist(ROOM))\r\n button_sortbyroom.grid(row=thisrow, column=3, sticky='news')\r\n\r\n thisrow = thisrow + 1\r\n self.listbox_name = tk.Listbox(self, exportselection=False, yscrollcommand = self.namescroll)\r\n self.listbox_dob = tk.Listbox(self, exportselection=False, yscrollcommand = self.dobscroll)\r\n self.listbox_room = tk.Listbox(self, exportselection=False, yscrollcommand = self.roomscroll)\r\n self.scrollbar = tk.Scrollbar(self)\r\n self.scrollbar.config(command=self.yview)\r\n\r\n self.listbox_name.grid(row=thisrow, column=1, sticky='news')\r\n self.listbox_dob.grid(row=thisrow, column=2, sticky='news')\r\n self.listbox_room.grid(row=thisrow, column=3, sticky='news')\r\n self.scrollbar.grid(row=thisrow, column=4, sticky='ns')\r\n\r\n self.listbox_name.bind(\"<>\", self.listboxclicked)\r\n self.listbox_dob.bind(\"<>\", self.listboxclicked)\r\n self.listbox_room.bind(\"<>\", self.listboxclicked)\r\n\r\n #self.listbox_name.config(yscrollcommand=self.scrollbar.set)\r\n\r\n thisrow = thisrow + 1\r\n self.grid_rowconfigure(thisrow, weight=1)\r\n\r\n def namescroll(self, *args):\r\n if self.listbox_name.yview() != self.listbox_dob.yview():\r\n self.listbox_dob.yview_moveto(args[0])\r\n\r\n if self.listbox_name.yview() != self.listbox_room.yview():\r\n self.listbox_room.yview_moveto(args[0])\r\n\r\n self.scrollbar.set(*args)\r\n\r\n def dobscroll(self, *args):\r\n if self.listbox_dob.yview() != self.listbox_name.yview():\r\n self.listbox_name.yview_moveto(args[0])\r\n\r\n if self.listbox_dob.yview() != self.listbox_room.yview():\r\n self.listbox_room.yview_moveto(args[0])\r\n\r\n self.scrollbar.set(*args)\r\n\r\n def roomscroll(self, *args):\r\n if self.listbox_room.yview() != self.listbox_name.yview():\r\n self.listbox_name.yview_moveto(args[0])\r\n\r\n if self.listbox_room.yview() != self.listbox_dob.yview():\r\n self.listbox_dob.yview_moveto(args[0])\r\n\r\n self.scrollbar.set(*args)\r\n\r\n def whichchosen(self):\r\n if len(self.listbox_name.curselection()) == 0:\r\n return -1\r\n else:\r\n return self.listbox_name.curselection()[0]\r\n\r\n def listboxclicked(self, event=None):\r\n which = event.widget.curselection()[0]\r\n self.listbox_name.select_clear(0, tk.END)\r\n self.listbox_dob.select_clear(0, tk.END)\r\n self.listbox_room.select_clear(0, tk.END)\r\n\r\n self.listbox_name.select_set(which)\r\n self.listbox_dob.select_set(which)\r\n self.listbox_room.select_set(which)\r\n\r\n def yview(self, *args):\r\n self.listbox_name.yview(*args)\r\n self.listbox_dob.yview(*args)\r\n self.listbox_room.yview(*args)\r\n\r\n def scrolljump(self, direction):\r\n self.listbox_name.yview_scroll(direction, \"pages\")\r\n self.listbox_dob.yview_scroll(direction, \"pages\")\r\n self.listbox_room.yview_scroll(direction, \"pages\")\r\n\r\n def sortlist(self, which):\r\n self.patient_obj.sortpatients(which)\r\n self.clearlistboxes()\r\n\r\n for index, this_patient in enumerate(self.patient_obj.ThePatients):\r\n self.addpatient(this_patient, index)\r\n\r\n def addpatient(self, this_patient, index):\r\n self.listbox_name.insert(index, this_patient.name)\r\n self.listbox_dob.insert(index, this_patient.dobstr)\r\n self.listbox_room.insert(index, this_patient.roomnumber)\r\n\r\n def clearlistboxes(self):\r\n self.listbox_dob.delete(0, 'end')\r\n self.listbox_room.delete(0, 'end')\r\n self.listbox_name.delete(0, 'end')\r\n\r\n def populatelistbox(self):\r\n self.clearlistboxes()\r\n for index, this_patient in enumerate(self.patient_obj.ThePatients):\r\n self.addpatient(this_patient, index)\r\n","sub_path":"Misc.py","file_name":"Misc.py","file_ext":"py","file_size_in_byte":8073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"127370734","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n'''\nGiven an array S of n integers, find three integers in S such that the sum is closest to a given number, target.\nReturn the sum of the three integers. You may assume that each input would have exactly one solution.\n\n For example, given array S = {-1 2 1 -4}, and target = 1.\n\n The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).\n'''\n\n# time: O(n^2)\nclass Solution(object):\n def threeSumClosest(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n nums.sort()\n l = len(nums)\n minDiff = sys.maxint\n for pivot in xrange(l - 2):\n i = pivot + 1\n j = l - 1\n while i < j:\n diff = target - (nums[pivot] + nums[i] + nums[j])\n if abs(diff) < abs(minDiff):\n minDiff = diff\n if diff > 0:\n i += 1\n elif diff < 0:\n j -= 1\n else:\n return target\n return target - minDiff\n","sub_path":"Python/16-3SumClosest/3sum_closest.py","file_name":"3sum_closest.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"465192512","text":"#신수민\ndef func_a(arr,num):\n ret=[]\n for i in arr:\n if i!=num:\n ret.append(i)\n return ret\ndef func_b(a,b):\n if a>b:\n return a-b\n else:\n return b-a\n\ndef func_c(arr):\n ret=-1\n for i in arr:\n if ret tkYEnd.get():\n tkYEnd.set(tkYStart.get())\n\n def changeYEnd(*args):\n if tkYStart.get() > tkYEnd.get():\n tkYStart.set(tkYEnd.get())\n \n tkYStart.trace('w', changeYStart)\n tkYEnd.trace('w', changeYEnd)\n\n def run():\n if tkPolu.get() == \"ALL\":\n for polu in POLLUTANTS:\n saveCSV(tkYStart.get(), tkYEnd.get(), polu)\n else:\n saveCSV(tkYStart.get(), tkYEnd.get(), tkPolu.get())\n\n btn = Button(root, text=\"RUN\", command = run)\n btn.pack()\n root.mainloop()","sub_path":"DataReadInPython/dataSetCreation.py","file_name":"dataSetCreation.py","file_ext":"py","file_size_in_byte":4756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"237311943","text":"from django.conf import settings\nfrom django.db import connection\n\nfrom ffcsa.core.utils import get_next_day\n\n_DROPSITE_DICT = {}\nDROPSITE_CHOICES = []\nPRIVATE_DROPSITES = []\n\nfor dropsite in settings.DROPSITES:\n name = dropsite['name']\n DROPSITE_CHOICES.append((name, dropsite['description']))\n if dropsite.get('private', False):\n PRIVATE_DROPSITES.append(name)\n _DROPSITE_DICT[name] = dropsite\n\n\ndef is_valid_dropsite(user):\n return user.profile.home_delivery or user.profile.drop_site in _DROPSITE_DICT\n\n\ndef get_pickup_date(user):\n from ffcsa.shop.orders import get_order_period_for_user\n week_start, week_end = get_order_period_for_user(user)\n\n if user.profile.home_delivery:\n zip = user.profile.delivery_address.zip\n day = settings.HOME_DELIVERY_DAY[zip] if zip in settings.HOME_DELIVERY_DAY else settings.HOME_DELIVERY_DAY[\n 'default']\n else:\n day = _DROPSITE_DICT[user.profile.drop_site]['pickupDay']\n\n return get_next_day(day, week_start)\n\n\ndef get_full_drop_locations():\n \"\"\"\n get a list of full locations. A Location is considered to be full\n if the limit has been reached for that specific location, or if\n the limit has been reached for a group of locations that contain\n the location.\n\n A location is either a dropsite, or a zip code for home delivery\n\n :return: list of locations that are full\n \"\"\"\n cursor = connection.cursor()\n cursor.execute('''\n select p.drop_site, count(*)\n from ffcsa_core_profile p \n where home_delivery = false and (\n (`stripe_subscription_id` is not null and `stripe_subscription_id` <> '') \n or user_id in (select distinct(user_id) from shop_order where time >= date_sub(now(), interval 1 month))\n ) \n group by p.drop_site\n union\n select a.zip, count(*)\n from ffcsa_core_profile p \n join ffcsa_core_address a on p.delivery_address_id = a.id \n where home_delivery = true and (\n (`stripe_subscription_id` is not null and `stripe_subscription_id` <> '')\n or user_id in (select distinct(user_id) from shop_order where time >= date_sub(now(), interval 1 month))\n ) \n group by a.zip\n ''')\n\n location_counts = {}\n full_locations = set()\n for l, count in cursor:\n location_counts[l] = count\n # check if a given dropsite is full\n if l in _DROPSITE_DICT:\n limit = _DROPSITE_DICT[l]['memberLimit']\n if limit is not None and limit <= count:\n full_locations.add(l)\n elif l in settings.HOME_DELIVERY_ZIP_LIMITS:\n if settings.HOME_DELIVERY_ZIP_LIMITS[l] <= count:\n full_locations.add(l)\n\n # check if a location group is full\n for group in settings.DROP_LOCATION_GROUP_LIMITS:\n total = 0\n for l in group['locations']:\n if l in location_counts:\n total = total + location_counts[l]\n\n if total >= group['limit']:\n full_locations.update(group['locations'])\n break\n\n return list(full_locations)\n\n\ndef get_color(dropsite_name):\n if dropsite_name.startswith('Home Delivery'):\n return 'purple', 'black'\n\n in_dict = dropsite_name in _DROPSITE_DICT\n color = _DROPSITE_DICT[dropsite_name]['color'] if in_dict else 'white'\n if not in_dict:\n strokeColor = 'white'\n else:\n strokeColor = color if color is not 'white' else 'black'\n\n return color, strokeColor\n","sub_path":"ffcsa/core/dropsites.py","file_name":"dropsites.py","file_ext":"py","file_size_in_byte":3479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"42011319","text":"import matplotlib.pyplot as plt\r\nimport csv\r\n\r\n# the data set folder is in the folder where the .py file is.\r\nwith open(\"User Identification From Walking Activity/1.csv\", \"r\") as dataSheet:\r\n dataSheetReader = csv.reader(dataSheet)\r\n dataList = []\r\n for row in dataSheetReader:\r\n if len(row) != 0:\r\n dataList = dataList+[row]\r\n\r\ndataSheet.close()\r\n# print(dataList)\r\nlength = len(dataList)\r\n# print(length)\r\n\r\nx_acceleration = []\r\ny_acceleration = []\r\nz_acceleration = []\r\n\r\n# Extracting individual column data. And also converting the string data to float.\r\nfor i in range(0, length):\r\n x_acceleration.append(float(dataList[i][1]))\r\n y_acceleration.append(float(dataList[i][2]))\r\n z_acceleration.append(float(dataList[i][3]))\r\n\r\n# Making a 2d list to plot all data in a single graph instead of three different box plot\r\ndata = [x_acceleration, y_acceleration, z_acceleration]\r\n\r\n# plotting box-plot\r\nplt.boxplot(data)\r\n# label for y axis\r\nplt.ylabel('acceleration value')\r\n# label for x axis\r\nplt.xlabel('Different axes')\r\n# customised name for the x-axis\r\nx_axis = [1, 2, 3]\r\nmy_xticks = ['x axis', 'y axis', 'z axis']\r\nplt.xticks(x_axis, my_xticks)\r\n\r\n# title for the graph\r\nplt.title('BoxPlot for user 1')\r\nplt.show()","sub_path":"box plot for data set/boxplot_script.py","file_name":"boxplot_script.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"566252889","text":"#!/usr/bin/env python\n# Copyright (c) 2016, Yahoo Inc.\n# Copyrights licensed under the BSD License\n# See the accompanying LICENSE.txt file for terms.\n\nimport os\nimport json\nfrom setuptools import setup\n\n# Default version number\nBASE_VERSION = '19.1.1'\nMETADATA_FILENAME = 'invirtualenv/package_metadata.json'\nBASEPATH = os.path.dirname(os.path.abspath(__file__))\nMETADATA_FILE = os.path.join(BASEPATH, METADATA_FILENAME)\n\n\ndef readme():\n \"\"\"\n Get the contents of the README file\n :return:\n \"\"\"\n possible_filenames = ['README.rst', 'README.md', 'README.txt']\n filename = None\n data = ''\n for filename in possible_filenames:\n if os.path.exists(filename):\n break\n if filename:\n with open(filename) as file_handle:\n data = file_handle.read()\n return data\n\n\ndef scripts():\n \"\"\"\n Get a list of the scripts in the scripts directory\n\n Returns\n -------\n list\n A list of strings containing the scripts in the scripts directory\n \"\"\"\n script_list = []\n\n if os.path.isdir('scripts'):\n script_list += [\n os.path.join('scripts', f) for f in os.listdir('scripts')\n ]\n return script_list\n\n\ndef get_version(version_file):\n \"\"\"\n Get the version number based on the BUILD_NUMBER\n\n Parameters\n ----------\n version_file : str\n The python file to store the version metadata in\n\n Returns\n -------\n str\n Version string\n \"\"\"\n for env_variable in ['BUILD_NUMBER', 'TRAVIS_BUILD_NUMBER']:\n build_number = int(os.environ.get(env_variable, '0'))\n if build_number:\n break\n\n version = BASE_VERSION.split('.')\n version[-1] = str(build_number)\n version = '.'.join(version)\n if build_number != 0:\n with open(version_file, 'w') as version_handle:\n json.dump({'version': version}, version_handle)\n\n elif os.path.exists(version_file):\n with open(version_file) as version_handle:\n version = json.load(version_handle)['version']\n\n return version\n\n\nif __name__ == '__main__':\n version = '1.0.0'\n setup(\n name='invirtualenv',\n version=get_version(METADATA_FILENAME),\n author='Dwight Hubbard',\n author_email='dhubbard@oath.com',\n license='LICENSE.txt',\n packages=['invirtualenv', 'invirtualenv_plugins', 'invirtualenv_plugins.rpm_scripts'],\n long_description=readme(),\n description='A utility to generate installation packages for python packaged apps',\n entry_points={\n 'console_scripts': [\"invirtualenv=invirtualenv.cli:main\"],\n 'invirtualenv.plugin': [\n 'docker=invirtualenv_plugins.docker:InvirtualenvDocker',\n 'rpm=invirtualenv_plugins.rpm:InvirtualenvRPM',\n 'parsedconfig=invirtualenv_plugins.parsedconfig:InvirtualenvParsedConfig',\n ],\n },\n install_requires=[\n 'jinja2',\n 'requests',\n 'six>=1.5',\n 'virtualenv',\n 'wheel',\n 'configparser',\n ],\n package_data= {\n 'invirtualenv': [\n 'package_metadata.json',\n ],\n 'invirtualenv_plugins': [\n 'docker_scripts/*'\n ]\n },\n scripts= scripts(),\n url = 'http://github.com/yahoo/invirtualenv',\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"621685141","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html\n\nfrom pymongo import *\n\nfrom joox_search_and_detail.items import *\nfrom joox_search_and_detail.utils import *\n\n\nclass JooxSearchAndDetailPipeline(object):\n\n def __init__(self):\n self.mongo_dao = MongoDao().get_instance()\n self.mongo_dao['JooxSearchItem'].create_index([(\"search_input\", ASCENDING)], unique=True)\n self.mongo_dao['JooxSongDetailsItem'].create_index([(\"songid\", ASCENDING)], unique=True)\n self.mongo_dao['JooxSongLyricItem'].create_index([(\"songid\", ASCENDING)], unique=True)\n\n def process_item(self, item, spider):\n\n if isinstance(item, JooxSearchItem):\n self.mongo_dao['JooxSearchItem'].replace_one({'search_input': item['search_input']}, dict(item), upsert=True)\n elif isinstance(item, JooxSongDetailsItem):\n self.mongo_dao['JooxSongDetailsItem'].replace_one({'songid': item['songid']}, dict(item), upsert=True)\n elif isinstance(item, JooxSongLyricItem):\n self.mongo_dao['JooxSongLyricItem'].replace_one({'songid': item['songid']}, dict(item), upsert=True)\n else:\n raise KeyError\n","sub_path":"joox_search_and_detail/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"4899454","text":"import os \nimport librosa \nimport argparse\nimport numpy as np \nimport sys\nimport joblib\nimport json\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn import svm\nfrom sklearn import preprocessing\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import classification_report\n\nimport tensorflow.keras\nfrom tensorflow.keras.preprocessing import sequence\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Embedding\nfrom tensorflow.keras.layers import LSTM\nfrom tensorflow.keras.preprocessing.text import Tokenizer\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.layers import Input, Flatten, Dropout, Activation\nfrom tensorflow.keras.layers import Conv1D, MaxPooling1D, AveragePooling1D\nfrom tensorflow.keras.layers import BatchNormalization\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.callbacks import ModelCheckpoint\nfrom sklearn.metrics import confusion_matrix\nfrom tensorflow.keras.models import model_from_json\n\n\nimport warnings\nsys.path.append(\"./\")\nfrom utils.loading import load_features_labels\nfrom utils.config_parse import get_config\nfrom utils.write_log import write_config_args_2_log\nfrom utils.setup_log import setup_logging\nimport logging\n\nclass MINI_VGG:\n\n def __init__(self, cfgs):\n self.log_train = None\n self.resume = False\n print(\"Called init function\")\n self.model = None\n self.input_size = cfgs.MINI_VGG.MODEL.INPUT_SIZE\n self.output_size = cfgs.MINI_VGG.MODEL.OUTPUT_SIZE\n self.epochs = cfgs.MINI_VGG.MODEL.EPOCHS\n self.batch_size = cfgs.MINI_VGG.MODEL.BATCH_SIZE\n self.define_model()\n\n def define_model(self):\n\n # Define model\n model = Sequential()\n # inputShape = (height, width, depth)\n # chanDim = -1\n # if using \"channels first\", update the input shape\n # and channels dimension\n # if K.image_data_format() == \"channels_first\":\n # inputShape = (depth, height, width)\n # chanDim = 1\n\n # first CONV => RELU => BN => CONV \n # => RELU => BN => POOL => DO\n model.add(Conv1D(32, 3,padding='same',\n input_shape=(self.input_size,1)))\n\n model.add(Activation(\"relu\"))\n model.add(BatchNormalization())\n model.add(Conv1D(32, 3,padding='same'))\n model.add(Activation(\"relu\"))\n model.add(BatchNormalization())\n model.add(MaxPooling1D(pool_size=(2)))\n model.add(Dropout(0.25))\n\n # second CONV => RELU => BN => CONV \n # => RELU => BN => POOL => DO\n model.add(Conv1D(64, 3,padding='same'))\n model.add(Activation(\"relu\"))\n model.add(BatchNormalization())\n model.add(Conv1D(64, 3,padding='same'))\n model.add(Activation(\"relu\"))\n model.add(BatchNormalization())\n model.add(MaxPooling1D(pool_size=(2)))\n model.add(Dropout(0.25))\n\n # first (only) FC => RELU => BN => DO\n model.add(Flatten())\n model.add(Dense(512))\n model.add(Activation(\"relu\"))\n model.add(BatchNormalization())\n model.add(Dropout(0.5))\n\n # softmax classifier\n model.add(Dense(self.output_size))\n model.add(Activation(\"softmax\"))\n self.model = model\n\n def print_architecture_model(self):\n self.model.summary()\n\n def train(self,x_traincnn, x_testcnn, y_train, y_test):\n assert(len(x_traincnn.shape) == 3 ), \"x_traincnn must be tensor (dimenson = 3)\"\n assert(len(x_testcnn.shape) == 3 ), \"x_testcnn must be tensor (dimenson = 3)\"\n \n # set optimize \n opt = tensorflow.keras.optimizers.RMSprop(learning_rate=0.00001, decay=1e-6)\n self.model.compile(loss='categorical_crossentropy', optimizer=opt,metrics=['accuracy'])\n self.log_train = self.model.fit(x_traincnn, y_train, batch_size=self.batch_size, epochs=self.epochs, validation_data=(x_testcnn, y_test))\n \n def predict(self, x_tess):\n preds = self.model.predict(x_tess, \n batch_size=self.batch_size, \n verbose=1)\n preds = preds.argmax(axis=1) \n return preds\n \n def plot_loss(self, plot_file):\n plt.plot(self.log_train.history['loss'])\n plt.plot(self.log_train.history['val_loss'])\n plt.title('MINI_VGG model loss')\n plt.ylabel('loss')\n plt.xlabel('epoch')\n plt.legend(['train', 'test'], loc='upper left')\n plt.savefig(plot_file)\n \n def save_architecture_model(self, json_path):\n model_json = self.model.to_json()\n with open(json_path, \"w\") as json_file:\n json_file.write(model_json)\n\n def save_weight_model(self, model_path):\n model_name = 'Emotion_Voice_Detection_Model.h5'\n if model_path == \"\":\n save_dir = os.path.join(os.getcwd(), 'saved_models')\n else:\n save_dir = model_path\n # Save model and weights\n if not os.path.isdir(save_dir):\n os.makedirs(save_dir)\n model_path = os.path.join(save_dir, model_name)\n self.model.save(model_path)\n print('Saved trained model at %s ' % model_path)\n\n def load_architecture_model(self, input_path):\n '''\n input_path: json file\n '''\n assert(os.path.isfile(input_path)),\"Model architecture path not exist or wrong!!!\"\n json_file = open(input_path, 'r')\n loaded_model_json = json_file.read()\n loaded_model = model_from_json(loaded_model_json)\n self.model = model \n json_file.close()\n\n def load_weight_model(self, model_path):\n assert(os.path.isfile(model_path)),\"Model weight path not exist or wrong!!!\"\n self.model.load_weights(model_path)\n","sub_path":"libs/MINI_VGG/mini_vgg_class.py","file_name":"mini_vgg_class.py","file_ext":"py","file_size_in_byte":6310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"583256281","text":"# ----------------------------------------------------------------------------\n# Copyright 2015 Nervana Systems Inc.\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# pylint: skip-file\n\nimport itertools\nimport numpy as np\n\nfrom neon.backends.nervanagpu import NervanaGPU\nfrom neon.backends.nervanacpu import NervanaCPU\nfrom neon.backends.autodiff import Autodiff\n\nfrom neon.backends.tests.utils import call_func, gen_backend_tensors\nfrom neon.backends.tests.utils import assert_tensors_allclose\n\n\ndef get_audiff_gradient(f, be, tensors):\n \"\"\"\n get autodiff gradient w.r.t the tensors\n \"\"\"\n op_tree = f(be, *tensors)\n ad = Autodiff(op_tree, be)\n return ad.get_grad_asnumpyarray(tensors)\n\n\ndef get_numerical_gradient(f, tensors, delta=1e-5):\n \"\"\"\n sum all of f's elements to make the last layer error as one\n \"\"\"\n # buffer for gradients\n gradients = []\n for i in range(len(tensors)):\n tensors[i] = tensors[i].astype(np.float64)\n gradients.append(np.zeros(tensors[i].shape))\n\n # iterate throuth each tensor\n for tensor, gradient in zip(tensors, gradients):\n\n tensor_flat = tensor.reshape((-1, ))\n gradient_flat = gradient.reshape((-1, ))\n\n # iterate throuth each element\n for idx in range(len(tensor_flat)):\n # backup\n backup = tensor_flat[idx]\n # increment\n tensor_flat[idx] = tensor_flat[idx] + delta\n f_inc = np.sum(f(np, *tensors))\n # decrement\n tensor_flat[idx] = backup - delta\n f_dec = np.sum(f(np, *tensors))\n # recover\n tensor_flat[idx] = backup\n # gradient\n gradient_flat[idx] = (f_inc - f_dec) / (2.0 * delta)\n\n return gradients\n\n\ndef func_basic_ops(be, x0, x1, x2, x3, x4):\n return (x0 + x2) + x0 * x4 + x1 * x3\n\n\ndef func_real(be, x0, x1, x2, x3, x4):\n return x1 + be.absolute(x2 + x3) + x4 - (x1 + be.square(x2 + x3) + x4)\n\n\ndef func_dot(be, x0, x1, x2, x3, x4):\n return (x0 + x3) + be.dot(x1, x2) - (x1 - x2) - be.dot(x3, x4)\n\n\ndef func_dot_reduction_mix(be, x0, x1, x2, x3, x4):\n f1 = be.std(be.var(x0, axis=0, keepdims=True), axis=1, keepdims=True)\n f2 = (be.max(x1, axis=0, keepdims=True) +\n be.min(x1, axis=0, keepdims=True))\n f3 = be.std(x2, keepdims=True)\n f4 = be.dot(1.0 / x3, x4 / x2)\n f5 = be.dot(x3, x4 - x0)\n f6 = be.dot(x2 / f4, f5 + x3)\n return f1 + f2 + f3 + f4 + 1.0 / (be.dot(f5, f6))\n\n\ndef func_scalar_broadcast(be, x0, x1, x2, x3, x4):\n return (0.2 * x0 - x1 * x2 / 3 * 4 * x1 + x0 * x0 / x0 / x3\n - x0 * x1 ** (x0 + x1 - 2) / (x3 - 0.5) / (x2 * 0.2)\n + x2 / be.sqrt(x0 * x1 * x0 * 0.1 * 0.8 * 0.9) / x0\n + 0.9 ** x0 + x0 ** 0.9)\n\n\ndef pytest_generate_tests(metafunc):\n # number of test to repeat\n test_indices = range(1)\n\n # test params\n test_funcs = [\n func_basic_ops,\n func_real,\n func_dot\n ]\n test_tensor_flags = ['pos_rand', 'neg_rand', 'rand']\n test_tensor_dims = [(2, 2)]\n test_dtypes = [np.float16, np.float32]\n test_backends = [NervanaGPU, NervanaCPU]\n\n # generate params for testing\n if 'custom_args' in metafunc.fixturenames:\n fargs = itertools.product(test_indices, test_funcs, test_tensor_flags,\n test_tensor_dims, test_dtypes, test_backends)\n # parameterize test call\n metafunc.parametrize(\"custom_args\", fargs)\n\n\ndef test_gradients(custom_args):\n test_idx, f, flag, dim, dtype, backend_type = custom_args\n\n be = backend_type(default_dtype=dtype)\n\n # tensors\n tensors = gen_backend_tensors(\n [np, be], 5, [dim] * 5, [flag] * 5, dtype=dtype)\n\n # compare function value and gradient\n numpy_func_val = call_func(f, np, tensors[0])\n backend_func_val = call_func(f, be, tensors[1])\n numerical_gradient = get_numerical_gradient(f, tensors[0])\n autodiff_gradient = get_audiff_gradient(f, be, tensors[1])\n\n # TODO: stricter test to fix numerical issues\n assert_tensors_allclose(\n numpy_func_val, backend_func_val, rtol=0., atol=1e-2)\n assert_tensors_allclose(numerical_gradient, autodiff_gradient, rtol=1e-02,\n atol=1e-3)\n\n if backend_type is NervanaGPU:\n be.ctx.detach()\n del(be)\n","sub_path":"neon/backends/tests/test_autodiff.py","file_name":"test_autodiff.py","file_ext":"py","file_size_in_byte":4886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"443141301","text":"import RPi.GPIO as GPIO\nimport time\nimport random\n\ncorrect_pin = 14\nincorrect_pin = 15\n\ndef clear_pins():\n GPIO.output(correct_pin, GPIO.LOW)\n GPIO.output(incorrect_pin, GPIO.LOW)\n\ndef light_pin(pin):\n GPIO.output(pin, GPIO.HIGH)\n\ndef getquiz():\n done = False\n while not(done):\n choice = input(\"Which quiz would you like (1=addition, 2=subtraction, 3=multiplication) ? \")\n if choice in ['1','2','3']:\n done = True\n else:\n print(\"select 1, 2 or 3\")\n return choice\n\ndef getquestion(a,b,whichquiz):\n question = \"What is \" + str(a)\n if whichquiz == '1':\n question = question + \" + \"\n if whichquiz == '2':\n question = question + ' - '\n if whichquiz == '3':\n question = question + ' x '\n question = question + str(b) + ' ? '\n return question\n\ndef checkresponse(a,b,response, whichquiz):\n if whichquiz == '1':\n correct = (a+b == response)\n elif whichquiz =='2':\n correct = (a-b == response)\n elif whichquiz == '3':\n correct = (a*b == response)\n if correct:\n return correct_pin\n else:\n return incorrect_pin\n\ndef main():\n GPIO.setmode(GPIO.BCM)\n GPIO.setwarnings(False)\n GPIO.setup(correct_pin, GPIO.OUT)\n GPIO.setup(incorrect_pin, GPIO.OUT)\n\n whichquiz = getquiz()\n\n while True:\n clear_pins()\n\n a = random.randint(0,12)\n b = random.randint(0,12)\n question = getquestion(a,b,whichquiz)\n response = input(question)\n try:\n response = int(response)\n except:\n response = None\n\n pin = checkresponse(a,b,response,whichquiz)\n\n light_pin(pin)\n time.sleep(2)\n\n\nif __name__ == '__main__':\n main()","sub_path":"quiz.py","file_name":"quiz.py","file_ext":"py","file_size_in_byte":1742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"50263253","text":"from OWDTestToolkit.global_imports import *\n\t\nclass main(GaiaTestCase):\n\n def checkThumbDuration(self, p_thumb_num, p_length_str_MMSS, p_errorMargin_SS):\n #\n # Check the duration of a video thumbnail.\n #\n durations = self.UTILS.getElements(DOM.Video.thumb_durations,\n \"Thumbnail durations\", True, 20, False)\n \n if not durations:\n \treturn False\n \n myDur = durations[p_thumb_num].text.strip()\n \n #\n # Video length didn't match exactly, but is it within the acceptable error margin?\n #\n from datetime import datetime, timedelta\n \n actual_time = datetime.strptime(myDur, '%M:%S')\n expect_time = datetime.strptime(p_length_str_MMSS, '%M:%S')\n margin_time = timedelta(seconds=p_errorMargin_SS)\n \n diff_time = actual_time - expect_time\n \n in_errorMargin = False\n \n # Less than expected, but within the error margin?\n if margin_time >= diff_time:\n in_errorMargin = True\n \n self.UTILS.TEST(in_errorMargin, \n \"Expected video length on thumbnail to be %s, +- %s seconds (it was %s seconds).\" % \n (p_length_str_MMSS, p_errorMargin_SS, myDur))\n\n","sub_path":"OWDTestToolkit/apps/Video/checkThumbDuration.py","file_name":"checkThumbDuration.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"123675488","text":"# _*_coding:utf-8_*_\n# Created by #Suyghur, on 2019-03-05.\n# Copyright (c) 2019 3KWan.\n# Description :\n\n\nclass GlobalStaticVars:\n # 渠道标识\n CHANNEL_NAME = ''\n # ChannelLibrary路径\n CHANNEL_LIBRARY_PROJECT_PATH = ''\n # 融合SDK路径\n COMMONSDK_PROJECT_PATH = ''\n\n CHANNEL_LIBRARY_PROJECT_SETTINGS_GRADLE_PATH = ''\n CHANNEL_LIBRARY_PROJECT_SETTINGS_GRADLE_CHANNEL_NAME = ''\n CHANNEL_LIBRARY_PROJECT_CHANNEL_PATH = ''\n CHANNEL_LIBRARY_PROJECT_AAR_OUTPUT_PATH = ''\n # 融合SDKDemo依赖库\n COMMONSDK_PROJECT_DEMO_LIBRARY_PATH = ''\n # 融合SDK渠道依赖库\n COMMONSDK_PROJECT_CHANNEL_LIBRARY_PATH = ''\n # 融合SDK渠道依赖库的build.gradle\n COMMONSDK_PROJECT_CHANNEL_LIBRARY_GRADLE_PATH = ''\n # 融合渠道实现类路径\n COMMONSDK_PROJECT_CHANNEL_IMPL_CLZ_PATH = ''\n COMMONSDK_PROJECT_CHANNEL_IMPL_CLZ_CHANNEL_VERSION = 'private static final String CHANNEL_VERSION = '\n # 渠道版本Json路径\n TOOLS_CHANNEL_VERSION_JSON_PATH = ''\n # 渠道新资源路径\n TOOLS_CHANNEL_RES_PATH = ''\n TOOLS_CHANNEL_RES_ASSETS_PATH = ''\n TOOLS_CHANNEL_RES_LIBS_PATH = ''\n TOOLS_CHANNEL_RES_JAR_PATH = ''\n TOOLS_CHANNEL_RES_RES_PATH = ''\n TOOLS_CHANNEL_RES_JNILIBS_PATH = ''\n\n def __init__(self, channelName, channelLibraryPath, commonsdkPath):\n self.CHANNEL_NAME = channelName\n self.CHANNEL_LIBRARY_PROJECT_PATH = channelLibraryPath\n self.COMMONSDK_PROJECT_PATH = commonsdkPath\n # channel_library工程目录下的路径\n self.CHANNEL_LIBRARY_PROJECT_SETTINGS_GRADLE_PATH = channelLibraryPath + '/settings.gradle'\n self.CHANNEL_LIBRARY_PROJECT_SETTINGS_GRADLE_CHANNEL_NAME = 'def channelName = \\\"' + channelName + '\\\"'\n self.CHANNEL_LIBRARY_PROJECT_CHANNEL_PATH = channelLibraryPath + '/library_' + channelName\n self.CHANNEL_LIBRARY_PROJECT_AAR_OUTPUT_PATH = self.CHANNEL_LIBRARY_PROJECT_CHANNEL_PATH + '/build/outputs/aar'\n # CommonSDK工程目录下的路径\n self.COMMONSDK_PROJECT_DEMO_LIBRARY_PATH = commonsdkPath + '/example_common/libs'\n self.COMMONSDK_PROJECT_CHANNEL_LIBRARY_PATH = commonsdkPath + '/library_commons/libs'\n self.COMMONSDK_PROJECT_CHANNEL_LIBRARY_GRADLE_PATH = commonsdkPath + '/library_commons/build.gradle'\n self.COMMONSDK_PROJECT_CHANNEL_IMPL_CLZ_PATH = commonsdkPath + '/library_commonsdk/src/main/java/cn/impl/common/impl/' + self.getImplClz()\n self.TOOLS_CHANNEL_VERSION_JSON_PATH = commonsdkPath + '/tools/commonsdk_python/config/channel_version.json'\n self.TOOLS_CHANNEL_RES_PATH = commonsdkPath + '/tools/channel_update_res'\n self.TOOLS_CHANNEL_RES_ASSETS_PATH = self.TOOLS_CHANNEL_RES_PATH + '/assets'\n self.TOOLS_CHANNEL_RES_LIBS_PATH = self.TOOLS_CHANNEL_RES_PATH + '/libs'\n self.TOOLS_CHANNEL_RES_RES_PATH = self.TOOLS_CHANNEL_RES_PATH + '/res'\n self.TOOLS_CHANNEL_RES_JNILIBS_PATH = self.TOOLS_CHANNEL_RES_PATH + '/jniLibs'\n\n # 获取渠道实现类\n def getImplClz(self):\n switcher = {\n '3k': 'CommonSdkImpl3k.java',\n 'wandou': 'CommonSdkImplWdj.java',\n '360': 'CommonSdkImpl360.java',\n 'anfan': \"CommonSdkImplAnFan.java\",\n 'dangle': 'CommonSdkImplDangle.java',\n 'huawei': 'CommonSdkImplHuaWeiHMS.java',\n 'jinli': 'CommonSdkImplJinli.java',\n 'mi': 'CommonSdkImplMi.java',\n 'oppo': 'CommonSdkImplOppo.java',\n 'uc': 'CommonSdkImplUc.java',\n 'duoku': 'CommonSdkImplBaidu.java',\n 'lenovo': 'CommonSdkImplLenovo.java',\n 'jolo': 'CommonSdkImplHtc.java',\n 'anzhi': 'CommonSdkImplAnZhi.java',\n 'qq': 'CommonSdkImplTengXun.java',\n 'vivo': 'CommonSdkImplVivo',\n 'qq3k': 'CommonSdkImplYSDK.java',\n 'fanyue': 'CommonSdkImplFanYue.java',\n 'coolpad': 'CommonSdkImplCoolpad',\n 'gfan': 'CommonSdkImplJiFeng.java',\n 'lewan': 'CommonSdkImplLeWan.java',\n 'momo': 'CommonSdkImplMoMo.java',\n '4399': 'CommonSdkImpl4399.java',\n 'xmwan': 'CommonSdkImplXMW.java',\n 'yl': 'CommonSdkImplYouLong.java',\n 'pps': 'CommonSdkImplPPS.java',\n 'ch': 'CommonSdkImplCaoHua.java',\n 'jdkj': 'CommonSdkImplJDKJ.java',\n 'linyou': 'CommonSdkImplLinYou.java',\n 'sogou': 'CommonSdkImplSoGou.java',\n 'zhangyue': 'CommonSdkImplZhangYue.java',\n 'sina': 'CommonSdkImplSina.java',\n '37': 'CommonSdkImpl37.java',\n 'ewan': 'CommonSdkImplEWan.java',\n 'zysc': 'CommonSdkImplZhuoYi.java',\n 'muzhi': 'CommonSdkImplMZYW.java',\n 'chmsdk': '',\n 'lb': 'CommonSdkImplLieBao.java',\n 'kuaiyong1': 'CommonSdkImplKuaiYong.java',\n 'dw': 'CommonSdkImplDuWan.java',\n 'kaopu': 'CommonSdkImplKaoPu.java',\n 'shoumeng': 'CommonSdkImplShouMeng.java',\n 'letv': 'CommonSdkImplLeShi.java',\n 'cm': 'CommonSdkImplChangMeng.java',\n 'muzhiwan': 'CommonSdkImplMzw.java',\n 'samsung': 'CommonSdkImplSamSung.java',\n 'pptv': 'CommonSdkImplPPTV.java',\n 'mango': 'CommonSdkImplMGou.java',\n 'nubia': 'CommonSdkImplNubiya.java',\n 'bdcps': 'CommonSdkImplBaidu3kcps.java',\n 'szmy': 'CommonSdkImplSZMY.java',\n 'fish': 'CommonSdkImpl3kFish.java',\n 'maya': 'CommonSdkImplMaYa.java',\n 'jc': 'CommonSdkImpl3kJCPlay.java',\n '11wan': 'CommonSdkImpl11wan.java',\n 'ss': 'CommonSdkImplSongShu.java',\n 'keyi': 'CommonSdkImplKeYi.java',\n 'feimiao': 'CommonSdkImplFeiMiao',\n 'x7': 'CommonSdkImplXiaoQi.java',\n 'douyu': 'CommonSdkImplDouyu.java',\n 'bilibili': 'CommonSdkImplBiliBili.java',\n 'liebao': 'CommonSdkImplLieBaoYiDong.java',\n 'shiyue': 'CommonSdkImplShiYue.java',\n 'tt': 'CommonSdkImplTT.java',\n 'ldmnq': 'CommonSdkImplLeiDian.java',\n 'yxf': 'CommonSdkImplYXFan.java',\n '921game': 'CommonSdkImplShenHai.java',\n 'quxuan': 'CommonSdkImplQuXuan.java',\n 'leyou': 'CommonSdkImpLeYou.java',\n 'lehihi': 'CommonSdkImplLeHiHi.java',\n 'douyin': 'CommonSdkImplDouyin.java',\n 'bluestacks': 'CommonSdkImplBlueStacks.java',\n 'ywgame': 'CommonSdkImplYuewen.java',\n '163game': 'CommonSdkImplNetEaseCloud.java',\n 'yeshen': 'CommonSdkImplYeShen.java',\n 'kuyou': 'CommonSdkImplKuYou.java'\n }\n return switcher.get(self.CHANNEL_NAME)\n","sub_path":"commonsdk_python/tl_global_static_vars.py","file_name":"tl_global_static_vars.py","file_ext":"py","file_size_in_byte":6746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"390945350","text":"class GUMIAndSongsDiv1:\n def maxSongs(self, duration, tone, T):\n dt = zip(tone, duration)\n dt.sort()\n ldt = len(dt)\n max_kinds = 0\n for i in range(ldt):\n for j in range(i, ldt):\n tt = [dt[t][1] for t in range(i, j+1)]\n tt.sort()\n cost = dt[j][0] - dt[i][0]\n left_time = T - cost\n kinds = 0\n for t in range(len(tt)):\n if left_time >= tt[t]:\n left_time -= tt[t]\n kinds += 1\n else:\n break\n max_kinds = kinds if kinds > max_kinds else max_kinds\n return max_kinds\n","sub_path":"algorithm/topcoder/contest/SRM588_DIV1/GUMIAndSongsDiv1.py","file_name":"GUMIAndSongsDiv1.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"363832437","text":"import argparse\nimport curses\nparser = argparse.ArgumentParser()\nparser.add_argument('-lvl', action='store', dest='version_arg', type=int)\nparsed_args = parser.parse_args()\nLEVEL = parsed_args.version_arg or 1\nimport random\nimport time\n'''\nAbove argparse and curses are imported and set up.#and numpy\nBelow I will establish the Classes before getting into the different LEVELs.\n'''\n\nclass Sprite():\n def __init__(self, y, x, uni):\n self.y = y\n self.x = x\n self.uni = uni\n def __str__(self):\n return self.uni\n\nclass Item(Sprite):\n def __init__(self, y, x, uni, id):\n super().__init__(y, x, uni)\n self.id = id\n def __repr__(self):\n return self.uni\n\nclass Character(Sprite):\n def __init__(self, y, x, uni):\n super().__init__(y, x, uni)\n self.inv = []\n\n def __str__(self):\n return self.uni\n \n def move(self, direction, steps):\n # change the y/x position of the character\n pass\n\n def attack(self, direction, weapon):\n #attack and everything\n pass\n\nhero = Character(10, 15, '😶')\n\nenemies = [\n Character(7, 7, '👿'),\n Character(7, 23, '😈'),\n Character(13, 7, '😈'),\n Character(13, 23, '👿'),\n]\n\nitems = [\n Item(11, 16, '🏹', 'bow'),\n Item(19, 5, '🔫', 'gun')\n]\n\nunicode_storage_list = ['🗡', '⚔', '🔫', '🏹', '🛡', '🔑', '🗝', '❤', '☠', '☠', '⬆', '➡', '⬇', '⬅']\n\nmoves = [[0, 1], [0, -1], [1, 0], [-1, 0]]\n\nkey_list = ['KEY_UP', 'KEY_DOWN', 'KEY_RIGHT', 'KEY_LEFT']\n\ndef fix_pos(sprite):\n if sprite.y < 0:\n sprite.y = 0\n if sprite.y > 20:\n sprite.y = 20\n if sprite.x < 0:\n sprite.x = 0\n if sprite.x > 30:\n sprite.x = 30\n\ndef aim(hero, wasd):\n if wasd == 'w':\n game_screen.addstr(hero.y - 1, hero.x, '⬆')\n elif wasd == 'a':\n game_screen.addstr(hero.y, hero.x - 1, '⬅')\n elif wasd == 's':\n game_screen.addstr(hero.y + 1, hero.x, '⬇')\n elif wasd == 'd':\n game_screen.addstr(hero.y, hero.x + 2, '➡')\n # draw_screen(draw_screen(hero, enemies, items, game_screen)\n\ndef shoot(hero, enemies, aim_dir, game_screen):\n if hero.inv:\n for enemy in enemies:\n if (aim_dir == 'w' and hero.x == enemy.x and hero.y > enemy.y) or (aim_dir == 'a' and hero.y == enemy.y and hero.x > enemy.x) or (aim_dir == 's' and hero.x == enemy.x and hero.y < enemy.y) or (aim_dir == 'd' and hero.y == enemy.y and hero.x < enemy.x):\n enemy.uni = '☠'\n draw_screen(hero, enemies, items, game_screen)\n time.sleep(1)\n enemies.remove(enemy)\n\n\n\n\ndef draw_screen(hero, enemies, items, game_screen):\n game_screen.clear()\n [game_screen.addstr(item.y, item.x, str(item)) for item in items]\n [game_screen.addstr(enemy.y, enemy.x, str(enemy)) for enemy in enemies]\n game_screen.addstr(hero.y, hero.x, str(hero))\n game_screen.addstr(21, 5, f\"Inventory: {hero.inv}\")\n\ngame_screen = curses.initscr()\ncurses.curs_set(0)\n\ngame_screen.keypad(True)\ngame_screen.clear()\n\ngame_screen.addstr(hero.y, hero.x, str(hero))\n[game_screen.addstr(item.y, item.x, str(item)) for item in items]\n[game_screen.addstr(enemy.y, enemy.x, str(enemy)) for enemy in enemies]\ngame_screen.addstr(21, 5, f\"Inventory: {hero.inv}\")\n\n# for enemy in enemies:\n# game_screen.addstr(enemy.y, enemy.x, str(enemy))\nprint(game_screen.getmaxyx())\nwhile True:\n in_key = game_screen.getkey()\n if in_key == 'q':\n curses.endwin()\n break\n \n\n if in_key in ['KEY_UP', 'KEY_DOWN', 'KEY_RIGHT', 'KEY_LEFT']:\n for enemy in enemies:\n y_or_x = random.choice(['y', 'x'])\n if y_or_x == 'y':\n enemy.y += random.randrange(-1, 2, 2)\n else:\n y_or_x == 'x'\n enemy.x += random.randrange(-1, 2, 2)\n fix_pos(enemy)\n if in_key == key_list[0]:\n hero.y -= 1\n elif in_key == key_list[1]:\n hero.y += 1\n elif in_key == key_list[2]:\n hero.x += 1\n elif in_key == key_list[3]:\n hero.x -= 1\n fix_pos(hero)\n for item in items:\n if item.y == hero.y and item.x == hero.x:\n hero.inv.append(item)\n items.remove(item)\n # if hero \n # if in_key \n if in_key in ['w', 'a', 's', 'd']:\n aim(hero, in_key)\n aim_dir = in_key\n draw_screen(hero, enemies, items, game_screen)\n if in_key == ' ':\n shoot(hero, enemies, aim_dir, game_screen)\n\n draw_screen(hero, enemies, items, game_screen)\n # game_screen.addstr(21, 31, '')","sub_path":"Assignments/pete/python/curses/curses5/curses5.py","file_name":"curses5.py","file_ext":"py","file_size_in_byte":4659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"26348091","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n@Time : 2021/2/24 8:19 下午\n@Author : mc\n@File : solution.py\n@Software: PyCharm\n\"\"\"\n\n\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution:\n def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':\n if not root:\n return None\n if p.val < root.val and q.val < q.val:\n return self.lowestCommonAncestor(root.left, p, q)\n elif p.val > root.val and q.val > root.val:\n return self.lowestCommonAncestor(root.right, p, q)\n else:\n return root\n","sub_path":"68-2-二叉搜索树的最近公共祖先 /solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"84670059","text":"import json\r\nimport hashlib\r\nimport urllib.request, urllib.error, urllib.parse\r\n\r\nserviceurl = 'http://api.map.baidu.com'\r\nak = 'your ak' #replace\r\nsk = 'your sk' #replace\r\n\r\nwhile True:\r\n address = input('Enter location(Only in China): ')\r\n\r\n if (len(address) < 1) or (address == 'Done'):\r\n break\r\n \r\n queryStr = '/geocoder/v2/?address=%s&output=json&ak=%s' % (address, ak)\r\n encodedStr = urllib.parse.quote(queryStr, safe=\"/:=&?#+!$,;'@()*[]\") #百度地图官网提供的方法,只对输入的中文进行编码\r\n rawStr = encodedStr + sk\r\n sn = (hashlib.md5(urllib.parse.quote_plus(rawStr).encode(\"utf8\")).hexdigest()) #采用sn验证,用IP白名单时不需要\r\n url = urllib.parse.quote(\"http://api.map.baidu.com\"+queryStr+\"&sn=\"+sn, safe=\"/:=&?#+!$,;'@()*[]\")\r\n #print('url:', url)\r\n\r\n uh = urllib.request.urlopen(url)\r\n data = uh.read().decode('UTF-8')\r\n try:\r\n js = json.loads(data)\r\n except:\r\n js = None\r\n\r\n if not js or 'status' not in js or js['status'] != 0:\r\n print('===Failure To Retrieve===')\r\n print(data)\r\n continue\r\n\r\n #print(json.dumps(js, indent = 4))\r\n\r\n lng = js['result']['location']['lng']\r\n lat = js['result']['location']['lat']\r\n print('lng:', lng, 'lat:', lat)\r\n","sub_path":"baidumap.py","file_name":"baidumap.py","file_ext":"py","file_size_in_byte":1299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"419822373","text":"import cv2\r\nimport mediapipe as mp\r\nimport streamlit as st\r\nfrom PIL import Image\r\nimport numpy as np\r\n\r\n# streamlit run face_detection.py\r\nmp_drawing = mp.solutions.drawing_utils\r\nmp_selfie_segmentation = mp.solutions.selfie_segmentation\r\n\r\n\r\ndef main(image_file):\r\n with mp_selfie_segmentation.SelfieSegmentation(\r\n model_selection=0) as selfie_segmentation:\r\n image = image_file\r\n BG_COLOR = (192, 192, 192) # gray\r\n MASK_COLOR = (255, 255, 255) # white\r\n image_height, image_width, _ = image.shape\r\n # Convert the BGR image to RGB before processing.\r\n results = selfie_segmentation.process(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))\r\n\r\n # Draw selfie segmentation on the background image.\r\n # To improve segmentation around boundaries, consider applying a joint\r\n # bilateral filter to \"results.segmentation_mask\" with \"image\".\r\n condition = np.stack((results.segmentation_mask,) * 3, axis=-1) > 0.1\r\n # Generate solid color images for showing the output selfie segmentation mask.\r\n fg_image = np.zeros(image.shape, dtype=np.uint8)\r\n fg_image[:] = MASK_COLOR\r\n bg_image = np.zeros(image.shape, dtype=np.uint8)\r\n bg_image[:] = BG_COLOR\r\n output_image = np.where(condition, fg_image, bg_image)\r\n \r\n return output_image\r\n\r\ndef app():\r\n html_temp = \"\"\"\r\n \r\n
    \r\n

    Selfie Segementation

    \r\n
    \r\n \r\n \"\"\"\r\n st.markdown(html_temp, unsafe_allow_html=True)\r\n\r\n\r\n image_file = st.file_uploader(\"Upload Image\", type=['jpg'])\r\n if image_file is not None:\r\n our_image = np.array(Image.open(image_file))\r\n st.text(\"DONE\")\r\n if st.button(\"Find\"): \r\n output = main(our_image)\r\n st.image(output)\r\n","sub_path":"pages/selfie_segmentation.py","file_name":"selfie_segmentation.py","file_ext":"py","file_size_in_byte":1996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"77094788","text":"from pathlib import Path\n\nimport mlflow\nimport pandas as pd\nimport pytest\nfrom kedro.extras.datasets.pandas import CSVDataSet\nfrom kedro.extras.datasets.pickle import PickleDataSet\nfrom mlflow.tracking import MlflowClient\nfrom pytest_lazyfixture import lazy_fixture\n\nfrom kedro_mlflow.io.artifacts import MlflowArtifactDataSet\n\n\n@pytest.fixture\ndef tracking_uri(tmp_path):\n return tmp_path / \"mlruns\"\n\n\n@pytest.fixture\ndef df1():\n return pd.DataFrame({\"col1\": [1, 2, 3], \"col2\": [4, 5, 6]})\n\n\n@pytest.fixture\ndef df2():\n return pd.DataFrame({\"col3\": [7, 8, 9], \"col4\": [\"a\", \"b\", \"c\"]})\n\n\n@pytest.mark.parametrize(\n \"dataset,extension,data,artifact_path\",\n [\n (CSVDataSet, \".csv\", lazy_fixture(\"df1\"), None),\n (\"pandas.CSVDataSet\", \".csv\", lazy_fixture(\"df1\"), None),\n (PickleDataSet, \".pkl\", lazy_fixture(\"df1\"), None),\n (\"pickle.PickleDataSet\", \".pkl\", lazy_fixture(\"df1\"), None),\n (CSVDataSet, \".csv\", lazy_fixture(\"df1\"), \"artifact_dir\"),\n (\"pandas.CSVDataSet\", \".csv\", lazy_fixture(\"df1\"), \"artifact_dir\"),\n (PickleDataSet, \".pkl\", lazy_fixture(\"df1\"), \"artifact_dir\"),\n (\n \"pickle.PickleDataSet\",\n \".pkl\",\n lazy_fixture(\"df1\"),\n \"artifact_dir\",\n ),\n ],\n)\ndef test_mlflow_csv_dataset_save_reload(\n tmp_path, tracking_uri, dataset, extension, data, artifact_path\n):\n mlflow.set_tracking_uri(tracking_uri.as_uri())\n mlflow_client = MlflowClient(tracking_uri=tracking_uri.as_uri())\n filepath = (tmp_path / \"data\").with_suffix(extension)\n\n mlflow_dataset = MlflowArtifactDataSet(\n artifact_path=artifact_path,\n data_set=dict(type=dataset, filepath=filepath.as_posix()),\n )\n\n with mlflow.start_run():\n mlflow_dataset.save(data)\n run_id = mlflow.active_run().info.run_id\n\n # the artifact must be properly uploaded to \"mlruns\" and reloadable\n run_artifacts = [\n fileinfo.path\n for fileinfo in mlflow_client.list_artifacts(run_id=run_id, path=artifact_path)\n ]\n remote_path = (\n filepath.name\n if artifact_path is None\n else (Path(artifact_path) / filepath.name).as_posix()\n )\n assert remote_path in run_artifacts\n assert data.equals(mlflow_dataset.load())\n\n\n@pytest.mark.parametrize(\n \"exists_active_run\",\n [(False), (True)],\n)\ndef test_artifact_dataset_save_with_run_id(\n tmp_path, tracking_uri, df1, exists_active_run\n):\n mlflow.set_tracking_uri(tracking_uri.as_uri())\n mlflow_client = MlflowClient(tracking_uri=tracking_uri.as_uri())\n nb_runs = 0\n # create a first run and get its id\n with mlflow.start_run():\n mlflow.log_param(\"fake\", 2)\n run_id = mlflow.active_run().info.run_id\n nb_runs += 1\n\n # check behaviour when logging with an already opened run\n if exists_active_run:\n mlflow.start_run()\n active_run_id = mlflow.active_run().info.run_id\n nb_runs += 1\n\n # then same scenario but the run_id where data is saved is specified\n mlflow_csv_dataset = MlflowArtifactDataSet(\n data_set=dict(type=CSVDataSet, filepath=(tmp_path / \"df1.csv\").as_posix()),\n run_id=run_id,\n )\n mlflow_csv_dataset.save(df1)\n\n # same tests as previously, bu no new experiments must have been created\n runs_list = mlflow_client.list_run_infos(experiment_id=\"0\")\n run_artifacts = [\n fileinfo.path for fileinfo in mlflow_client.list_artifacts(run_id=run_id)\n ]\n\n assert len(runs_list) == nb_runs # no new run must have been created when saving\n assert (\n mlflow.active_run().info.run_id == active_run_id\n if mlflow.active_run()\n else True\n ) # if a run was opened before saving, it must be reopened\n assert \"df1.csv\" in run_artifacts # the file must exists\n assert df1.equals(mlflow_csv_dataset.load()) # and must loadable\n\n if exists_active_run:\n mlflow.end_run()\n\n\ndef test_is_versioned_dataset_logged_correctly_in_mlflow(tmp_path, tracking_uri, df1):\n \"\"\"Check if versioned dataset is logged correctly in MLflow as artifact.\n\n For versioned datasets just artifacts from current run should be logged.\n \"\"\"\n mlflow.set_tracking_uri(tracking_uri.as_uri())\n mlflow_client = MlflowClient(tracking_uri=tracking_uri.as_uri())\n\n with mlflow.start_run():\n\n run_id = mlflow.active_run().info.run_id\n\n mlflow_csv_dataset = MlflowArtifactDataSet(\n data_set=dict(\n type=CSVDataSet,\n filepath=(tmp_path / \"df1.csv\").as_posix(),\n versioned=True,\n ),\n # run_id=run_id,\n )\n mlflow_csv_dataset.save(df1)\n\n run_artifacts = [\n fileinfo.path for fileinfo in mlflow_client.list_artifacts(run_id=run_id)\n ]\n\n # Check if just one artifact was created in given run.\n assert len(run_artifacts) == 1\n\n artifact_path = mlflow_client.download_artifacts(\n run_id=run_id, path=run_artifacts[0]\n )\n\n # Check if saved artifact is file and not folder where versioned datasets are stored.\n assert Path(artifact_path).is_file()\n\n assert df1.equals(mlflow_csv_dataset.load()) # and must loadable\n\n\ndef test_artifact_dataset_logging_deactivation(tmp_path, tracking_uri):\n mlflow_pkl_dataset = MlflowArtifactDataSet(\n data_set=dict(type=PickleDataSet, filepath=(tmp_path / \"df1.csv\").as_posix())\n )\n\n mlflow.set_tracking_uri(tracking_uri.as_uri())\n mlflow_client = MlflowClient(tracking_uri=tracking_uri.as_uri())\n\n mlflow_pkl_dataset._logging_activated = False\n\n all_runs_id_beginning = set(\n [\n run.run_id\n for k in range(len(mlflow_client.list_experiments()))\n for run in mlflow_client.list_run_infos(experiment_id=f\"{k}\")\n ]\n )\n\n mlflow_pkl_dataset.save(2)\n\n all_runs_id_end = set(\n [\n run.run_id\n for k in range(len(mlflow_client.list_experiments()))\n for run in mlflow_client.list_run_infos(experiment_id=f\"{k}\")\n ]\n )\n\n assert all_runs_id_beginning == all_runs_id_end\n\n\ndef test_mlflow_artifact_logging_deactivation_is_bool(tmp_path):\n mlflow_csv_dataset = MlflowArtifactDataSet(\n data_set=dict(type=CSVDataSet, filepath=(tmp_path / \"df1.csv\").as_posix())\n )\n\n with pytest.raises(ValueError, match=\"_logging_activated must be a boolean\"):\n mlflow_csv_dataset._logging_activated = \"hello\"\n\n\ndef test_artifact_dataset_load_with_run_id(tmp_path, tracking_uri, df1, df2):\n\n mlflow.set_tracking_uri(tracking_uri.as_uri())\n\n # define the logger\n mlflow_csv_dataset = MlflowArtifactDataSet(\n data_set=dict(type=CSVDataSet, filepath=(tmp_path / \"df.csv\").as_posix())\n )\n\n # create a first run, save a first dataset\n with mlflow.start_run():\n run_id1 = mlflow.active_run().info.run_id\n mlflow_csv_dataset.save(df1)\n\n # saving a second time will erase local dataset\n with mlflow.start_run():\n mlflow_csv_dataset.save(df2)\n\n # if we load the dataset, it will be equal to the seond one, using the local filepath\n assert df2.equals(mlflow_csv_dataset.load())\n\n # update the logger and reload outside of an mlflow run : it should load the dataset if the first run id\n mlflow_csv_dataset.run_id = run_id1\n assert df1.equals(mlflow_csv_dataset.load())\n","sub_path":"tests/io/artifacts/test_mlflow_artifact_dataset.py","file_name":"test_mlflow_artifact_dataset.py","file_ext":"py","file_size_in_byte":7414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"526011379","text":"\"\"\"\nWhat is this?\nThis is a python script that adds the header and footer parts to each page.\n\"\"\"\n\nimport re\nimport os\n\n\ndef check_page(directory, file_name):\n title = None\n in_content = False\n has_start = False\n has_end = False\n content = \"\"\n\n path = os.path.join(directory, file_name)\n\n js_files = ['js/vendor/modernizr-2.8.3.min.js',\n 'https://code.jquery.com/jquery-1.12.0.min.js',\n 'js/vendor/jquery-1.12.0.min.js',\n 'js/plugins.js',\n 'js/main.js',\n 'https://www.google-analytics.com/analytics.js',\n 'js/vendor/jquery.jrumble.1.3.min.js']\n\n extra_js = ''\n\n with open(path, 'r') as f:\n for ix, line in enumerate(f):\n # print(line, end='')\n if '' in line:\n title = re.search('<title>(.*)', line).group(1)\n if '' in line:\n in_content = True\n has_start = True\n\n if '.js' in line:\n js_file = re.search('[^\\'\"]*\\.js', line).group(0)\n if js_file not in js_files:\n extra_js += line\n\n if in_content:\n content += line\n\n if '' in line:\n in_content = False\n has_end = True\n\n if title is None or not has_start or not has_end:\n print(\"{} is invalid\".format(file_name))\n return\n # print('{}: title = {}, content = {} lines long'.format(file_name, title, content.count('\\n')))\n print('- {}:'.format(file_name))\n # print(extra_js, end=\"\")\n\n header_path = os.path.join(directory, 'header.html')\n footer_path = os.path.join(directory, 'footer.html')\n header = None\n footer = None\n with open(header_path, 'r') as f:\n header = f.read()\n with open(footer_path, 'r') as f:\n footer = f.read()\n if header is None or footer is None:\n return\n header = header.replace('Page Title', title)\n footer = footer.replace('', extra_js)\n new_file = header + '\\n' + content + '\\n' + footer\n return new_file\n\n\ndef main():\n directory = \".\"\n for file in os.listdir(directory):\n if file.lower().endswith(\".html\"):\n formatted_page = check_page(directory, file)\n\n if formatted_page is None:\n continue\n\n path = os.path.join(directory, file)\n with open(path, 'w') as f:\n f.write(formatted_page)\n\nif __name__ == '__main__':\n main()\n","sub_path":"info1003 website/html_adderer.py","file_name":"html_adderer.py","file_ext":"py","file_size_in_byte":2577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"425540558","text":"import datetime\nimport json\nimport os\nimport time\nfrom google.cloud import bigquery\nimport pytz\nimport re\nimport pandas as pd\n\nos.environ['GOOGLE_APPLICATION_CREDENTIALS'] = '/mnt/esun-crawler-code/ga_etl/.ga_key/GA360-dfc33d0beb96.json'\n\ndef DataEncoder(obj):\n if isinstance(obj, datetime.datetime):\n return obj.strftime('%Y-%m-%d %H:%M:%S')\n elif isinstance(obj, datetime.date):\n return obj.strftime('%Y-%m-%d')\n elif isinstance(obj, str):\n return '\"'+re.sub('\"','',obj)+'\"'\n else:\n return str(obj) \n\nstart_time = time.time()\n \netl_dt = datetime.datetime.strftime(datetime.datetime.now(pytz.timezone('Asia/Taipei')),'%Y-%m-%d')\nprint(etl_dt)\noutput_dir = '/mnt/esun-crawler-ga/'\n#output_dir = '/mnt/esun-crawler-data/ga_data/test/'\n\ntry: \n print('start process query web_event...')\n\n\n client = bigquery.Client()\n query_job = client.query(\"\"\"SELECT max(visitDate) as max_date, min(visitDate) as min_date FROM `neat-motif-123006.ga_etl.web_event`\"\"\")\n\n res = query_job.result()\n for row in res:\n max_date = datetime.datetime.strftime(row['max_date'],'%Y%m%d')\n min_date = datetime.datetime.strftime(row['min_date'],'%Y%m%d')\n\n client = bigquery.Client()\n num_of_rows = 0\n num_of_process = 0\n d_dir = '{}web_event_{}.D'.format(output_dir, max_date)\n h_dir = '{}web_event_{}.H'.format(output_dir, max_date) \n with open(d_dir, 'w') as f, open(h_dir, 'w') as f1:\n print('start query')\n query_job = client.query(\"\"\"SELECT * FROM `neat-motif-123006.ga_etl.web_event`\"\"\")\n\n res = query_job.result()\n\n num_of_rows += res.total_rows\n\n print('start parsing data...')\n for row in res:\n num_of_process += 1\n columns = ['{}_{}'.format(row['visitDate'],num_of_process),\n row['etl_dt'],row['eventDateTime'],row['visitDateTime'],row['visitDate'],\n row['fullVisitorId'],row['clientId'],row['deviceCategory'],row['deviceBrowser'],\n row['hits_eventInfo_eventCategory'],row['hits_eventInfo_eventAction'],row['hits_eventInfo_eventLabel'],\n row['hits_eventInfo_eventValue']]\n\n f.write(','.join([DataEncoder(col) for col in columns]))\n f.write('\\n')\n f1.write(min_date+\n max_date+\n datetime.datetime.strftime(datetime.datetime.now(pytz.timezone('Asia/Taipei')),\n '%Y%m%d%H%M%S')+\n '{:010d}'.format(num_of_rows)+\n 'web_event_{}.D'.format(max_date))\n print('finish query web_event')\n\n\n # 寫入檢查表\n table_name = 'web_event'\n df = pd.read_csv('/mnt/esun-crawler-ga/ga_checklist/ga_checklist_{}_{}.csv'.format(table_name, max_date))\n df.set_index('table_name', inplace=True)\n df.loc[['{}_{}'.format(table_name, max_date)],['status']] = 'finish'\n df.loc[['{}_{}'.format(table_name, max_date)],['file_D']] = 'Y'\n df.loc[['{}_{}'.format(table_name, max_date)],['file_H']] = 'Y'\n df.reset_index(inplace=True) \n df.to_csv('/mnt/esun-crawler-ga/ga_checklist/ga_checklist_{}_{}.csv'.format(table_name, max_date), index=False)\n\n\n\n print('--------------------------------------')\n print('number of row need processed: {}'.format(num_of_rows))\n print('number of row actually processed: {}'.format(num_of_process))\n print('process time: {:.2f} mins'.format((time.time()-start_time)/60))\n print('--------------------------------------') \n\nexcept:\n max_date = datetime.datetime.now(pytz.timezone('Asia/Taipei')) - datetime.timedelta(days=1)\n max_date = max_date.strftime('%Y%m%d')\n d_dir = '{}web_event_{}.D'.format(output_dir, max_date)\n h_dir = '{}web_event_{}.H'.format(output_dir, max_date) \n with open(d_dir, 'w') as f, open(h_dir, 'w') as f1: \n f1.write(max_date+\n max_date+\n datetime.datetime.strftime(datetime.datetime.now(pytz.timezone('Asia/Taipei')),\n '%Y%m%d%H%M%S')+\n '{:010d}'.format(0)+\n 'web_event_{}.D'.format(max_date))\n # 寫入檢查表\n table_name = 'web_event'\n df = pd.read_csv('/mnt/esun-crawler-ga/ga_checklist/ga_checklist_{}_{}.csv'.format(table_name, max_date))\n df.set_index('table_name', inplace=True)\n df.loc[['{}_{}'.format(table_name, max_date)],['status']] = 'finish'\n df.loc[['{}_{}'.format(table_name, max_date)],['file_D']] = 'Y'\n df.loc[['{}_{}'.format(table_name, max_date)],['file_H']] = 'Y'\n df.reset_index(inplace=True) \n df.to_csv('/mnt/esun-crawler-ga/ga_checklist/ga_checklist_{}_{}.csv'.format(table_name, max_date), index=False)","sub_path":"src/web_event_etl.py","file_name":"web_event_etl.py","file_ext":"py","file_size_in_byte":4737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"526917990","text":"#\n# Copyright (c) 2017 Joy Diamond. All rights reserved.\n#\nif 0:\n import Gem, sys as PythonSystem\n\n\n none = Gem.BuiltIn.none\n flush_standard_output = PythonSystem.stdout.flush\n write_standard_output = PythonSystem.stdout.write\n\n\n def line(format = none, *arguments):\n if format is none:\n assert length(arguments) is 0\n\n write_standard_output('\\n')\n else:\n write_standard_output((format % arguments if arguments else format) + '\\n')\n\n flush_standard_output()\n\n\n\n Gem_keys = sorted(Gem.__dict__.keys())\n BuiltIn_keys = sorted(Gem.BuiltIn.__dict__.keys())\n\n line('Gem: %s', Gem_keys)\n line('BuiltIn: %s', BuiltIn_keys)\n\n line('Shared: [- exported]: %s',\n sorted(k for k in Gem.Shared.__dict__.keys() if k not in Gem_keys))\n\n line('Privileged: %s', sorted(Gem.Shared.Privileged.__dict__.keys()))\n","sub_path":"Junk/Boot.py","file_name":"Boot.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"443100600","text":"from tkinter import*\nfrom pyDatalog import pyDatalog, pyEngine\nimport menu\nimport base_conocimiento_2\nimport ui\nimport sys\n\n\ndef main():\n estado = True\n while estado:\n opcion = ui.menu_principal()\n if opcion == 1:\n ui.ingresar_datos_usuario()\n genero = ui.ingresar_genero()\n edad = ui.ingresar_edad()\n peso = ui.ingresar_peso()\n estatura = ui.ingresar_estatura()\n sedentarismo = ui.sedentarismo()\n print(\"\")\n total = ui.calcular_IMC(genero, peso, estatura, edad, sedentarismo)\n print(\"\")\n t1 = total *(3/8)\n t2 = total *(3/8)\n t3 = total *(2/8)\n \n base_conocimiento_2.busqueda1(t1)\n \n base_conocimiento_2.busqueda2(t2)\n \n base_conocimiento_2.busqueda3(t3)\n \n\n\n one= Label(root, text=base_conocimiento_2.busqueda1(t1))\n one.pack()\n\n two= Label(root, text=base_conocimiento_2.busqueda2(t2))\n two.pack()\n\n tree= Label(root, text=base_conocimiento_2.busqueda3(t3))\n tree.pack()\n\n root.mainloop()\n\n elif opcion == 2:\n ui.instrucciones()\n elif opcion == 0:\n ui.mensaje_salida()\n sys.exit(1)\n break\n else:\n print(\"opcion no encontrada\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Programacion 3/Nomem_app/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"155475010","text":"# 作用域\n# python L(local局部)E(embed嵌套)G(global全局)B(bulitin)\n\ndef func():\n num=10\n print('in func num is %d'%num)\nfunc()\n# print(num) 局部变量不可以在外面调用,不造成全局污染\n\ncount=0\ndef modifyCount():\n # 注意 可读 但如果在py内部方法修改全局变量的值,通过global来告诉这是一个全局\n global count\n count=2\n count+=1\n print('in modifyCount: count is %d'%count)\nmodifyCount()\nprint('after modify count is %d'%count)\n\n\n","sub_path":"DEMO/demo20_scope.py","file_name":"demo20_scope.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"325092122","text":"import discord\nfrom discord import Message, Reaction, User\nfrom discord.abc import PrivateChannel\nfrom discord.ext.commands import Bot, Context\nfrom discord.utils import oauth_url\n\nfrom bashbot.command.about import AboutCommand\nfrom bashbot.command.close import CloseCommand\nfrom bashbot.command.controls import ControlsCommand\nfrom bashbot.command.freeze import FreezeCommand\nfrom bashbot.command.here import HereCommand\nfrom bashbot.command.interactive import InteractiveCommand\nfrom bashbot.command.macro import MacroCommand\nfrom bashbot.command.open import OpenCommand\nfrom bashbot.command.rename import RenameCommand\nfrom bashbot.command.repeat import RepeatCommand\nfrom bashbot.command.select import SelectCommand\nfrom bashbot.command.submit import SubmitCommand\nfrom bashbot.exceptions import SessionDontExistException, ArgumentFormatException, TerminalNotFoundException, \\\n MacroNotFoundException\nfrom bashbot.settings import settings\nfrom bashbot.terminal.control import TerminalControl\nfrom bashbot.terminal.sessions import sessions\nfrom bashbot.terminal.terminal import TerminalState\nfrom bashbot.utils import get_logger, parse_template, extract_prefix, is_command, remove_prefix\n\n\nclass BashBot(Bot):\n logger = get_logger('BashBot')\n cmd_logger = get_logger('Command')\n\n def __init__(self, command_prefix, **options):\n super().__init__(command_prefix, **options)\n self.add_cog(OpenCommand())\n self.add_cog(CloseCommand())\n self.add_cog(HereCommand())\n self.add_cog(FreezeCommand())\n self.add_cog(RenameCommand())\n self.add_cog(ControlsCommand())\n self.add_cog(AboutCommand())\n self.add_cog(RepeatCommand())\n self.add_cog(MacroCommand())\n self.add_cog(SelectCommand())\n self.add_cog(InteractiveCommand())\n self.add_cog(SubmitCommand())\n\n async def on_ready(self):\n self.logger.info(f'Logged in as {self.user.name} ({self.user.id})')\n self.logger.info(f'You can add bot to your server via {oauth_url(self.user.id)}')\n\n presence = parse_template(\n settings().get(\"discord.presence\"),\n prefix=self.command_prefix\n )\n await self.change_presence(\n status=discord.Status.online,\n activity=discord.Game(presence)\n )\n\n async def on_message(self, message: Message):\n if message.author.bot:\n return\n\n terminal = sessions().get_by_channel(message.channel)\n\n if self.is_invoke(message):\n await self.process_commands(message)\n elif terminal and terminal.state == TerminalState.OPEN:\n prefix = extract_prefix(message.content)\n if not terminal.interactive and not prefix:\n return\n\n # We don't remove prefix when in interactive mode\n content = message.content\n if not terminal.interactive:\n content = remove_prefix(content)\n\n if terminal.auto_submit:\n content += '\\n'\n\n terminal.input(content)\n\n # Log message\n guild_name = message.channel.guild.name\n channel_name = message.channel.name\n author_name = message.author.name\n self.cmd_logger.info(f\"[{guild_name}/#{channel_name}/{terminal.name}] {author_name} typed: {content}\")\n\n async def on_command(self, ctx: Context):\n guild_name = ctx.message.channel.guild.name\n channel_name = ctx.message.channel.name\n author_name = ctx.message.author.name\n content = ctx.message.content\n\n self.cmd_logger.info(f\"[{guild_name}/#{channel_name}] {author_name} invoked command: {content}\")\n\n async def on_reaction_add(self, reaction: Reaction, user: User):\n if user.bot:\n return\n\n terminal = sessions().get_by_message(reaction.message)\n if reaction.emoji not in terminal.controls:\n return\n\n control: TerminalControl = terminal.controls[reaction.emoji]\n terminal.input(control.text)\n\n async def on_reaction_remove(self, reaction: Reaction, user: User):\n await self.on_reaction_add(reaction, user)\n\n def is_invoke(self, message: Message):\n if isinstance(message.channel, PrivateChannel):\n return True\n\n has_mention = self.user in message.mentions\n return is_command(message.content) or has_mention\n\n async def on_command_error(self, ctx: Context, error):\n message = None\n\n if isinstance(error, ArgumentFormatException):\n message = error.message\n\n if isinstance(error, SessionDontExistException):\n message = error.message\n\n if isinstance(error, TerminalNotFoundException):\n message = error.message\n\n if isinstance(error, MacroNotFoundException):\n message = error.message\n\n if message:\n await ctx.send(f'`{message}`')\n","sub_path":"bashbot/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":4910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"54378727","text":"# Graph Theory Project 2021\n# Author: Emmanuel Osabuehien\n# Module: Graph Theory\n# 30/04/2021\n\n# Imports\nimport argparse\n\n\"\"\"Creating a program that helps you search text files\"\"\"\n\"\"\"I will be using regular expression wihtin this code\"\"\"\n\ndef shunt(infix):\n \"\"\"Convert infix expressions to postfix.\"\"\"\n # The eventual output.\n postfix = \"\"\n # The shunting yard operator stack.\n stack = \"\"\n # Operator precedence.\n prec = {'*': 100, '.': 90, '|': 80}\n # Loop through the input a character at a time.\n for c in infix:\n # c is an operator.\n if c in {'*', '.', '|'}:\n # Check what is on the stack.\n while len(stack) > 0 and stack[-1] != '(' and prec[stack[-1]] >= prec[c]:\n # Append operator at top of stack to output.\n postfix = postfix + stack[-1]\n # Remove operator from stack.\n stack = stack[:-1]\n # Push c to stack.\n stack = stack + c\n elif c == '(':\n # Push c to stack.\n stack = stack + c\n elif c == ')':\n while stack[-1] != \"(\":\n # Append operator at top of stack to output.\n postfix = postfix + stack[-1]\n # Remove operator from stack.\n stack = stack[:-1]\n # Remove open bracket from stack.\n stack = stack[:-1]\n # c is a non-special.\n else:\n # Push it to the output.\n postfix = postfix + c\n\n # Empty the operator stack.\n while len(stack) != 0:\n # Append operator at top of stack to output.\n postfix = postfix + stack[-1]\n # Remove operator from stack.\n stack = stack[:-1]\n # Return the postfix version of infix.\n return postfix\n\nclass State:\n \"\"\"A state and its arrows in Thompson's construction.\"\"\"\n def __init__(self, label, arrows, accept):\n \"\"\"label is the arrow labels, arrows is a list of states to\n point to, accept is a boolean as to whether this is an accept\n state.\n \"\"\"\n self.label = label\n self.arrows = arrows\n self.accept = accept\n \n def followes(self):\n \"\"\"The set of states that are gotten from following this state\n and all its e arrows.\"\"\"\n # Include this state in the returned set.\n states = {self}\n # If this state has e arrows, i.e. label is None.\n if self.label is None:\n # Loop through this state's arrows.\n for state in self.arrows:\n # Incorporate that state's earrow states in states.\n states = (states | state.followes())\n # Returns the set of states. \n return states\n\nclass NFA:\n \"\"\"A non-deterministic finite automaton.\"\"\"\n def __init__(self, start, end):\n self.start = start\n self.end = end\n\n def match(self, s):\n \"\"\"Return True if this NFA (instance) matches the string s.\"\"\"\n # A list of previous states that we are still in.\n previous = self.start.followes()\n # Loop through the string, a character at a time.\n for c in s:\n # Start with an empty set of current states.\n current = set()\n # Loop throuth the previous states.\n for state in previous:\n # Check if there is a c arrow from state.\n if state.label == c:\n # Add followes for next state.\n current = (current | state.arrows[0].followes())\n # Replace previous with current.\n previous = current\n # If the final state is in previous, then return True. False otherwise. \n return (self.end in previous)\n\n def match2():\n \"\"\"Returns True or false after a file is read and infix and string have been matched\"\"\"\n words = []\n infixes = []\n #Searches and opens text files in directory\n textfile = open(\"infix.txt\", \"rt\")\n textfile2 = open(\"infix2.txt\", \"rt\")\n #The strip will remove any unneccessary spacing in the string that is return\n for txt in textfile:\n infixes.append(txt.strip())\n\n for txt2 in textfile2:\n words.append(txt2.strip())\n \n for infix in infixes:\n for word in words:\n #Function is then printed to screen\n print(\"Match: \" + str(match(infix, word)), \"Infix: \" + infix, \"String: \" + word)\n #Close files after function is complete\n textfile.close()\n textfile2.close()\n\n def match3(infixes, words):\n \"\"\"Return True or False after a string has been input and matched to infix, it will also print out results in a text file\"\"\"\n #Searches and opens text files in directory\n textfile = open(\"output.txt\", \"a+\")\n textfile2 = open(\"infix.txt\", \"a+\")\n textfile3 = open(\"infix2.txt\", \"a+\")\n\n for infix in infixes:\n for word in words:\n print(\"Match: \" + str(match(infix, word)), \"Infix: \" + infix, \"String: \" + word)\n #The string that is return is then output into a text file and stored\n textfile.write(\"{} {} {}\".format(\"Match: %s\" % str(match(infix, word)), \"Infix: %s\" % infix, \"String: %s\\n\" % word))\n textfile2.write(\"%s\\n\" % infix)\n textfile3.write(\"%s\\n\" % word)\n\n file.close()\n\ndef re_to_nfa(postfix):\n # A stack for NFAs.\n stack = []\n # Loop through the postfix r.e. left to right.\n for c in postfix:\n # Concatenation.\n if c == '.':\n # Pop top NFA off stack.\n nfa2 = stack[-1]\n stack = stack[:-1]\n # Pop the next NFA off stack.\n nfa1 = stack[-1]\n stack = stack[:-1]\n # Make accept state of NFA1 non-accept.\n nfa1.end.accept = False\n # Make it point at start state of nfa2.\n nfa1.end.arrows.append(nfa2.start)\n # Make a new NFA with nfa1's start state and nfa2's end state.\n nfa = NFA(nfa1.start, nfa2.end)\n # Push to the stack.\n stack.append(nfa)\n elif c == '|':\n # Pop top NFA off stack.\n nfa2 = stack[-1]\n stack = stack[:-1]\n # Pop the next NFA off stack.\n nfa1 = stack[-1]\n stack = stack[:-1]\n # Create new start and end states.\n start = State(None, [], False)\n end = State(None, [], True)\n # Make new start state point at old start states.\n start.arrows.append(nfa1.start)\n start.arrows.append(nfa2.start)\n # Make old end states non-accept.\n nfa1.end.accept = False\n nfa2.end.accept = False\n # Point old end states to new one.\n nfa1.end.arrows.append(end)\n nfa2.end.arrows.append(end)\n # Make a new NFA.\n nfa = NFA(start, end)\n # Push to the stack.\n stack.append(nfa)\n elif c == '*':\n # Pop one NFA off stack.\n nfa1 = stack[-1]\n stack = stack[:-1]\n # Create new start and end states.\n start = State(None, [], False)\n end = State(None, [], True)\n # Make new start state point at old start state.\n start.arrows.append(nfa1.start)\n # And at the new end state.\n start.arrows.append(end)\n # Make old end state non-accept.\n nfa1.end.accept = False\n # Make old end state point to new end state.\n nfa1.end.arrows.append(end)\n # Make old end state point to old start state.\n nfa1.end.arrows.append(nfa1.start)\n # Make a new NFA.\n nfa = NFA(start, end)\n # Push to the stack.\n stack.append(nfa)\n else:\n # Create an NFA for the non-special character c.\n # Create the end state.\n end = State(None, [], True)\n # Create the start state.\n start = State(c, [], False)\n # Point new start state at new end state.\n start.arrows.append(end)\n # Create the NFA with the start and end state.\n nfa = NFA(start, end)\n # Append the NFA to the NFA stack.\n stack.append(nfa)\n \n # There should only be one NFA on the stack.\n if len(stack) != 1:\n return None\n else:\n return stack[0]\n\nif __name__ == \"__main__\":\n automatons =[ [\"a.(b.b)*.a\", [\"abba\", \"ab\", \"acc\", \"abbc\", \"accb\", \"caba\", \"abbbc\", \"abcb\", \"bac\", \"cab\"]],\n [\"a.b\", [\"abba\", \"ab\", \"acc\", \"abbc\", \"accb\", \"caba\", \"abbbc\", \"abcb\", \"bac\", \"cab\"]],\n [\"(a.(b|c))*\", [\"abba\", \"ab\", \"acc\", \"abbc\", \"accb\", \"caba\", \"abbbc\", \"abcb\", \"bac\", \"cab\"]],\n [\"a+b.c\", [\"abba\", \"ab\", \"acc\", \"abbc\", \"accb\", \"caba\", \"abbbc\", \"abcb\", \"bac\", \"cab\"]],\n [\"a.(b|c).a*\", [\"abba\", \"ab\", \"acc\", \"abbc\", \"accb\", \"caba\", \"abbbc\", \"abcb\", \"bac\", \"cab\"]],\n [\"a.(b.b)*.c\", [\"abba\", \"ab\", \"acc\", \"abbc\", \"accb\", \"caba\", \"abbbc\", \"abcb\", \"bac\", \"cab\"]],\n [\"aa.*\", [\"abba\", \"ab\", \"acc\", \"abbc\", \"accb\", \"caba\", \"abbbc\", \"abcb\", \"bac\", \"cab\"]]\n ]\n print(\"Test\")\n for automata in automatons:\n infix = automata[0]\n postfix = shunt(infix)\n nfa = re_to_nfa(postfix)\n print(\"infix: %s\"% infix)\n print(\"postfix: %s\" % shunt(infix))\n print(\"nfa: %s\" %{re_to_nfa(postfix)})\n for s in automata[1]:\n match = nfa.match(s)\n print(\"The String Passes True Or False: %s\"%nfa.match(s))\n\n#Menu to display 2 of my aforementioned functions\n#Menu is kinda messy so it may print out or it may not, it prints out locally on my end\ndef choices():\n select = True\n while select:\n option = input(\"\\n1: Reads in a text files to compare infixes and string\" +\n \"\\n2: Prints out results to associated file\" + \"\\n3: QUIT!\\n\")\n if option == 1:\n match2()\n elif option == 2:\n match3()\n elif option == 3:\n select = False\n\nchoices()","sub_path":"regex.py","file_name":"regex.py","file_ext":"py","file_size_in_byte":10238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"159521525","text":"import dash\nfrom dash.dependencies import Output, Input\nimport dash_bootstrap_components as dbc\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport plotly\nimport plotly.graph_objs as go\nfrom collections import deque\nimport pandas as pd\nimport mysql.connector\n\n\nname_title = 'Stats from SQL Server'\nBS = \"https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css\"\n\napp = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP, BS])\n\n\ndatabase = mysql.connector.connect(host=\"localhost\", user=\"root\", password=\"root\", port=8889, db=\"financial_data\")\ncursor = database.cursor() #Read the database \n\n@app.callback(Output('example-graph', 'figure'), \n [Input('graph-update', 'interval')])\n\n\n\ndef update_graph_scatter(input_data):\n\n cursor.execute(\"SELECT * from Profit_Loss\")\n rows = cursor.fetchall()\n data_sql = []\n\n data_sql.append(rows[0])\n \n df = pd.DataFrame.from_records(data_sql)\n new_df = df.transpose()\n\n x = [\"Year_2005\", \"Year_2006\", \"Year_2007\", \"Year_2008\", \"Year_2009\", \"Year_2010\", \"Year_2011\", \"Year_2012\", \"Year_2013\", \"Year_2014\", \"Year_2015\", \"Year_2016\", \"Year_2017\", \"Year_2018\", \"Year_2019\"]\n y = new_df[0]\n\n data = plotly.graph_objs.Scatter(\n x=list(x),\n y=list(y),\n name='Scatter',\n mode= 'lines+markers'\n )\n\n return {'data': [data],'layout' : go.Layout(\n xaxis=dict(range=[min(x),max(x)]),\n yaxis=dict(range=[min(y),max(y)]),)}\n\ndef get_num_rows_all_data():\n cursor.execute(\"SELECT * from Profit_Loss\")\n profit_loss = cursor.fetchall()\n no_of_profit_loss = len(profit_loss)\n\n cursor.execute(\"SELECT * from Balance_Sheet\")\n balance_sheet = cursor.fetchall()\n no_of_balance_sheet = len(balance_sheet)\n\n cursor.execute(\"SELECT * from Cash_Flow\")\n cash_flow = cursor.fetchall()\n no_of_cash_flow = len(cash_flow)\n\n cursor.execute(\"SELECT * from Financial_Ratio\")\n Financial_Ratio = cursor.fetchall()\n no_of_financial_ratio = len(Financial_Ratio)\n\n total_data = no_of_financial_ratio + no_of_cash_flow + no_of_balance_sheet + no_of_profit_loss\n return [total_data, no_of_profit_loss, no_of_balance_sheet, no_of_cash_flow, no_of_financial_ratio]\n\ndef get_num_cols_data():\n cursor.execute(\"SELECT * from Profit_Loss\")\n profit_loss = cursor.fetchall()\n col_count = len(profit_loss[0][0])\n\n return col_count\n\ndef retrieve_empty_data():\n cursor.execute(\"SELECT * from Profit_Loss\")\n profit_loss = cursor.fetchall()\n counter_pl = 0\n for row in profit_loss:\n for col in row:\n if col == \"-\":\n counter_pl += 1\n\n cursor.execute(\"SELECT * from Balance_Sheet\")\n balance_sheet = cursor.fetchall()\n counter_bs = 0\n for row in balance_sheet:\n for col in row:\n if col == \"-\":\n counter_bs += 1\n \n cursor.execute(\"SELECT * from Cash_Flow\")\n cash_flow = cursor.fetchall()\n counter_cf = 0\n for row in cash_flow:\n for col in row:\n if col == \"-\":\n counter_cf += 1\n\n cursor.execute(\"SELECT * from Financial_Ratio\")\n Financial_Ratio = cursor.fetchall()\n counter_fr = 0\n for row in Financial_Ratio:\n for col in row:\n if col == \"-\":\n counter_fr += 1\n\n total_empty = counter_pl + counter_fr + counter_cf + counter_bs\n\n return [total_empty,counter_pl,counter_bs, counter_cf, counter_fr]\n\nrow_count = get_num_rows_all_data()\ncol_count = get_num_cols_data()\nempty_count = retrieve_empty_data()\ntotal_data = col_count * row_count[0]\n\nPLOTLY_LOGO = \"https://images.plot.ly/logo/new-branding/plotly-logomark.png\"\napp.layout = dbc.Container(html.Div(children=[\n dbc.Navbar(\n [\n html.A(\n # Use row and col to control vertical alignment of logo / brand\n dbc.Row(\n [\n dbc.Col(html.Img(src=PLOTLY_LOGO, height=\"30px\")),\n dbc.Col(dbc.NavbarBrand(\"Dashboard\", className=\"ml-2\")),\n ],\n align=\"center\",\n no_gutters=True,\n ),\n href=\"#\",\n ),\n dbc.NavbarToggler(id=\"navbar-toggler\"),\n ],\n color=\"dark\",\n dark=True,\n ),\n html.H1(\"\"),\n html.H1(children=\"Revenue Data Breakdown\"),\n dcc.Graph(\n id='example-graph',\n animate=True),\n dcc.Interval(\n id='graph-update',\n interval=1*500),\n dbc.Row(dbc.Col(html.H1(children=\"Metadata Breakdown\"))),\n dbc.Row(\n [\n dbc.Col(html.Div(\"Total Data Row Count: \")),\n dbc.Col(html.Div(\"Total Data Column Count\")),\n dbc.Col(html.Div(\"Total No of Empty Data\")),\n ]\n ),\n dbc.Row(\n [\n dbc.Col(html.H3(row_count[0])),\n dbc.Col(html.H3(col_count)),\n dbc.Col(html.H3(empty_count[0])),\n ]\n ),\n html.Br(),\n html.Br(),\n\n html.H2(\"Empty Data vs Total Number of Data\"),\n html.Div(\n [\n dbc.Progress(value=(empty_count[0]/total_data * 100), style={\"height\": \"1px\"}, className=\"mb-3\"),\n dbc.Progress(value=(empty_count[0]/total_data * 100), style={\"height\": \"30px\"}),\n ]\n ), \n html.Br(),\n html.Br(),\n html.H2(\"Total Data Row Count Breakdown\"),\n dbc.Row(\n [\n dbc.Col(html.Div(\"Row Count Profit & Loss: \")),\n dbc.Col(html.Div(\"Row Count Balance Sheet\")),\n dbc.Col(html.Div(\"Row Count Cash Flow\")),\n dbc.Col(html.Div(\"Row Count Financial Ratio\")),\n ]\n ),\n dbc.Row(\n [\n dbc.Col(html.H3(row_count[1])),\n dbc.Col(html.H3(row_count[2])),\n dbc.Col(html.H3(row_count[3])),\n dbc.Col(html.H3(row_count[4])),\n ]\n ),\n html.Br(),\n html.Br(),\n]))\n\nif __name__ == \"__main__\":\n app.run_server(debug=True)\n","sub_path":"create_metadata.py","file_name":"create_metadata.py","file_ext":"py","file_size_in_byte":6000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"194154614","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nfrom PyQt5.QtCore import QAbstractTableModel, Qt, QVariant, QModelIndex\nfrom collections import namedtuple\nimport util\n\nclass OrderTableModel(QAbstractTableModel):\n HeaderLabels = ['Line', 'StartTime', 'Mile', 'OnStation','OffStation', 'Price', 'Status', 'OrderTime', 'DayNum']\n\n OrderInfo = namedtuple('OrderInfo', 'lineNo startTime mileage onStationName offStationName originalPrice status'\n ' orderTime dayNum payType vehTime id')\n\n def __init__(self, parent = None):\n super(OrderTableModel, self).__init__(parent)\n self.orderDataList = []\n\n def headerData(self, p_int, Qt_Orientation, role=None):\n if role != Qt.DisplayRole:\n return None\n if Qt_Orientation == Qt.Horizontal:\n return OrderTableModel.HeaderLabels[p_int]\n elif Qt_Orientation == Qt.Vertical:\n return p_int + 1\n return None\n\n def columnCount(self, parent=None, *args, **kwargs):\n return len(OrderTableModel.HeaderLabels)\n\n def rowCount(self, parent=None, *args, **kwargs):\n return len(self.orderDataList)\n\n def data(self, index : QModelIndex, role=None):\n if not index.isValid() or role != Qt.DisplayRole:\n return QVariant()\n row = index.row()\n column = index.column()\n if row >= len(self.orderDataList):\n return QVariant()\n return self.orderDataList[row][column]\n\n\n def setOrderData(self, orderDataList : list):\n if len(orderDataList) == 0:\n return\n self.beginResetModel()\n self.orderDataList.clear()\n for orderObj in orderDataList:\n statusStr = ''\n if orderObj.status == 0:\n statusStr = '未完成'\n elif orderObj.status == 1:\n statusStr = '已取消'\n elif orderObj.status == 2:\n statusStr = '已完成'\n orderInfo = OrderTableModel.OrderInfo(orderObj.lineNo, util.formatTime(orderObj.startTime), orderObj.mileage,\n orderObj.onStationName, orderObj.offStationName, orderObj.originalPrice,\n statusStr, orderObj.orderTime, orderObj.dayNum, orderObj.payType,\n orderObj.vehTime, orderObj.id)\n self.orderDataList.append(orderInfo)\n self.endResetModel()\n\n def getOrderId(self, row : int):\n if row < 0 or row >= len(self.orderDataList):\n return -1\n return self.orderDataList[row].id\n\nclass DetailInfoModel(QAbstractTableModel):\n HeaderLabels = ['Date', 'Status']\n DetailInfo = namedtuple('DetailInfo', 'runDate status')\n\n def __init__(self, parent = None):\n super(DetailInfoModel, self).__init__(parent)\n self.detailInfoList = []\n\n def headerData(self, p_int, Qt_Orientation, role=None):\n if role != Qt.DisplayRole:\n return None\n if Qt_Orientation == Qt.Horizontal:\n return DetailInfoModel.HeaderLabels[p_int]\n elif Qt_Orientation == Qt.Vertical:\n return p_int + 1\n return None\n\n def columnCount(self, parent=None, *args, **kwargs):\n return len(DetailInfoModel.HeaderLabels)\n\n def rowCount(self, parent=None, *args, **kwargs):\n return len(self.detailInfoList)\n\n def data(self, index : QModelIndex, role=None):\n if not index.isValid() or role != Qt.DisplayRole:\n return QVariant()\n row = index.row()\n column = index.column()\n if row >= len(self.detailInfoList):\n return QVariant()\n return self.detailInfoList[row][column]\n\n\n def setDetailInfoList(self, detailInfoList : list):\n if len(detailInfoList) == 0:\n return\n self.beginResetModel()\n self.detailInfoList.clear()\n for detailInfoObj in detailInfoList:\n statusStr = ''\n if detailInfoObj.status == 0:\n statusStr = '未完成'\n elif detailInfoObj.status == 1:\n statusStr = '已取消'\n elif detailInfoObj.status == 2:\n statusStr = '已完成'\n orderInfo = DetailInfoModel.DetailInfo(detailInfoObj.runDate, statusStr)\n self.detailInfoList.append(orderInfo)\n self.endResetModel()\n\n def getRunDate(self, row : int):\n if row < 0 or row >= len(self.detailInfoList):\n return ''\n return self.detailInfoList[row].runDate\n\nif __name__ == '__main__':\n pass\n","sub_path":"gui/OrderTableModel.py","file_name":"OrderTableModel.py","file_ext":"py","file_size_in_byte":4604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"185047103","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 13 13:45:27 2021\n\n:copyright: \n Jared Peacock (jpeacock@usgs.gov)\n\n:license: MIT\n\n\"\"\"\n# =============================================================================\n# Imports\n# =============================================================================\n\nimport unittest\nfrom pathlib import Path\nimport numpy as np\n\nfrom mth5 import CHANNEL_DTYPE\nfrom mth5 import helpers\nfrom mth5.mth5 import MTH5\nfrom mt_metadata.timeseries import Experiment\nfrom mt_metadata import MT_EXPERIMENT_SINGLE_STATION\n\nfn_path = Path(__file__).parent\n# =============================================================================\n#\n# =============================================================================\nhelpers.close_open_files()\n\n\nclass TestMTH5(unittest.TestCase):\n @classmethod\n def setUpClass(self):\n self.maxDiff = None\n self.fn = fn_path.joinpath(\"test.h5\")\n self.mth5_obj = MTH5(file_version=\"0.1.0\")\n self.mth5_obj.open_mth5(self.fn, mode=\"w\")\n self.experiment = Experiment()\n self.experiment.from_xml(fn=MT_EXPERIMENT_SINGLE_STATION)\n self.mth5_obj.from_experiment(self.experiment)\n\n def test_surveys(self):\n survey = self.experiment.surveys[0]\n self.assertEqual(survey, self.mth5_obj.survey_group.metadata)\n\n def test_stations(self):\n stations = self.experiment.surveys[0].stations\n for station in stations:\n with self.subTest(station.id):\n h5_station = self.mth5_obj.get_station(station.id)\n sd = station.to_dict(single=True)\n sd.pop(\"hdf5_reference\")\n sd.pop(\"mth5_type\")\n\n h5_sd = h5_station.metadata.to_dict(single=True)\n h5_sd.pop(\"hdf5_reference\")\n h5_sd.pop(\"mth5_type\")\n\n self.assertDictEqual(h5_sd, sd)\n\n def test_runs(self):\n runs = self.experiment.surveys[0].stations[0].runs\n for run in runs:\n with self.subTest(run.id):\n h5_run = self.mth5_obj.get_run(\n self.experiment.surveys[0].stations[0].id, run.id\n )\n sd = run.to_dict(single=True)\n sd.pop(\"hdf5_reference\")\n sd.pop(\"mth5_type\")\n\n h5_sd = h5_run.metadata.to_dict(single=True)\n h5_sd.pop(\"hdf5_reference\")\n h5_sd.pop(\"mth5_type\")\n\n self.assertDictEqual(h5_sd, sd)\n\n def test_to_run_ts(self):\n run_group = self.mth5_obj.get_run(\n self.experiment.surveys[0].stations[0].id,\n self.experiment.surveys[0].stations[0].runs[0].id,\n )\n run_ts = run_group.to_runts()\n\n for key in self.experiment.surveys[0].to_dict(single=True).keys():\n with self.subTest(f\"survey.{key}\"):\n self.assertEqual(\n self.experiment.surveys[0].get_attr_from_name(key),\n run_ts.survey_metadata.get_attr_from_name(key),\n )\n\n for key in (\n self.experiment.surveys[0].stations[0].to_dict(single=True).keys()\n ):\n if key in [\"hdf5_reference\", \"mth5_type\"]:\n continue\n\n with self.subTest(f\"station.{key}\"):\n if key in [\"run_list\"]:\n self.assertListEqual(\n [\"a\", \"b\", \"c\", \"d\", \"e\"],\n run_ts.station_metadata.run_list,\n )\n\n else:\n self.assertEqual(\n self.experiment.surveys[0]\n .stations[0]\n .get_attr_from_name(key),\n run_ts.station_metadata.get_attr_from_name(key),\n )\n\n for key in (\n self.experiment.surveys[0]\n .stations[0]\n .runs[0]\n .to_dict(single=True)\n .keys()\n ):\n if key in [\"hdf5_reference\", \"mth5_type\"]:\n continue\n with self.subTest(f\"run.{key}\"):\n if key in [\"time_period.end\"]:\n self.assertNotEqual(\n self.experiment.surveys[0]\n .stations[0]\n .runs[0]\n .get_attr_from_name(key),\n run_ts.run_metadata.get_attr_from_name(key),\n )\n else:\n self.assertEqual(\n self.experiment.surveys[0]\n .stations[0]\n .runs[0]\n .get_attr_from_name(key),\n run_ts.run_metadata.get_attr_from_name(key),\n )\n\n def test_channels(self):\n runs = self.experiment.surveys[0].stations[0].runs\n for run in runs:\n h5_run = self.mth5_obj.get_run(\n self.experiment.surveys[0].stations[0].id, run.id\n )\n for channel in run.channels:\n with self.subTest(f\"{run.id}/ch.component\"):\n h5_channel = h5_run.get_channel(channel.component)\n\n sd = channel.to_dict(single=True)\n sd.pop(\"hdf5_reference\")\n sd.pop(\"mth5_type\")\n\n h5_sd = h5_channel.metadata.to_dict(single=True)\n h5_sd.pop(\"hdf5_reference\")\n h5_sd.pop(\"mth5_type\")\n\n self.assertDictEqual(h5_sd, sd)\n\n def test_to_channel_ts(self):\n channel_group = self.mth5_obj.get_channel(\n self.experiment.surveys[0].stations[0].id,\n self.experiment.surveys[0].stations[0].runs[0].id,\n self.experiment.surveys[0]\n .stations[0]\n .runs[0]\n .channels[0]\n .component,\n )\n ch_ts = channel_group.to_channel_ts()\n\n for key in self.experiment.surveys[0].to_dict(single=True).keys():\n with self.subTest(f\"survey.{key}\"):\n self.assertEqual(\n self.experiment.surveys[0].get_attr_from_name(key),\n ch_ts.survey_metadata.get_attr_from_name(key),\n )\n\n for key in (\n self.experiment.surveys[0].stations[0].to_dict(single=True).keys()\n ):\n if key in [\"hdf5_reference\", \"mth5_type\"]:\n continue\n\n with self.subTest(f\"station.{key}\"):\n if key in [\"run_list\", \"channels_recorded\"]:\n self.assertListEqual(\n [\"a\", \"b\", \"c\", \"d\", \"e\"],\n ch_ts.station_metadata.run_list,\n )\n else:\n self.assertEqual(\n self.experiment.surveys[0]\n .stations[0]\n .get_attr_from_name(key),\n ch_ts.station_metadata.get_attr_from_name(key),\n )\n\n for key in (\n self.experiment.surveys[0]\n .stations[0]\n .runs[0]\n .to_dict(single=True)\n .keys()\n ):\n if key in [\n \"hdf5_reference\",\n \"mth5_type\",\n \"channels_recorded_magnetic\",\n \"channels_recorded_electric\",\n \"channels_recorded_auxiliary\",\n ]:\n continue\n with self.subTest(f\"run.{key}\"):\n self.assertEqual(\n self.experiment.surveys[0]\n .stations[0]\n .runs[0]\n .get_attr_from_name(key),\n ch_ts.run_metadata.get_attr_from_name(key),\n )\n\n for key in (\n self.experiment.surveys[0]\n .stations[0]\n .runs[0]\n .channels[0]\n .to_dict(single=True)\n .keys()\n ):\n if key in [\n \"hdf5_reference\",\n \"mth5_type\",\n \"filter.name\",\n \"filter.applied\",\n ]:\n continue\n with self.subTest(f\"channel.{key}\"):\n # end time is off by one second (bug?)\n if key in [\"time_period.end\"]:\n self.assertNotEqual(\n self.experiment.surveys[0]\n .stations[0]\n .runs[0]\n .channels[0]\n .get_attr_from_name(key),\n ch_ts.station_metadata.get_attr_from_name(key),\n )\n else:\n self.assertEqual(\n self.experiment.surveys[0]\n .stations[0]\n .runs[0]\n .channels[0]\n .get_attr_from_name(key),\n ch_ts.channel_metadata.get_attr_from_name(key),\n )\n\n def test_filters(self):\n exp_filters = self.experiment.surveys[0].filters\n\n for key, value in exp_filters.items():\n key = key.replace(\"/\", \" per \").lower()\n sd = value.to_dict(single=True, required=False)\n h5_sd = self.mth5_obj.filters_group.to_filter_object(key)\n h5_sd = h5_sd.to_dict(single=True, required=False)\n for k in sd.keys():\n with self.subTest(f\"{key}_{k}\"):\n v1 = sd[k]\n v2 = h5_sd[k]\n if isinstance(v1, (float, int)):\n self.assertAlmostEqual(v1, float(v2), 5)\n elif isinstance(v1, np.ndarray):\n self.assertEqual(v1.dtype, v2.dtype)\n self.assertTrue((v1 == v2).all())\n else:\n self.assertEqual(v1, v2)\n\n def test_channel_summary(self):\n self.mth5_obj.channel_summary.summarize()\n\n with self.subTest(\"test shape\"):\n self.assertEqual(self.mth5_obj.channel_summary.shape, (25,))\n with self.subTest(\"test nrows\"):\n self.assertEqual(self.mth5_obj.channel_summary.nrows, 25)\n with self.subTest((\"test dtype\")):\n self.assertEqual(\n self.mth5_obj.channel_summary.dtype, CHANNEL_DTYPE\n )\n with self.subTest(\"test station\"):\n self.assertTrue(\n (\n self.mth5_obj.channel_summary.array[\"station\"] == b\"REW09\"\n ).all()\n )\n\n @classmethod\n def tearDownClass(self):\n self.mth5_obj.close_mth5()\n self.fn.unlink()\n\n\nclass TestUpdateFromExperiment(unittest.TestCase):\n @classmethod\n def setUpClass(self):\n self.maxDiff = None\n self.fn = fn_path.joinpath(\"test.h5\")\n self.mth5_obj = MTH5(file_version=\"0.1.0\")\n self.mth5_obj.open_mth5(self.fn, mode=\"w\")\n self.experiment = Experiment()\n self.experiment.from_xml(fn=MT_EXPERIMENT_SINGLE_STATION)\n self.mth5_obj.from_experiment(self.experiment)\n\n self.experiment_02 = Experiment()\n self.experiment_02.from_xml(fn=MT_EXPERIMENT_SINGLE_STATION)\n self.experiment_02.surveys[0].id = \"different_survey_name\"\n self.experiment_02.surveys[0].stations[0].location.latitude = 10\n\n def test_update_from_new_experiment(self):\n\n self.mth5_obj.from_experiment(self.experiment_02, update=True)\n\n with self.subTest(\"new_survey\"):\n self.assertEqual(\n self.mth5_obj.survey_group.metadata.id,\n self.experiment_02.surveys[0].id,\n )\n with self.subTest(\"new_location\"):\n st = self.mth5_obj.get_station(\"REW09\")\n self.assertEqual(\n st.metadata.location.latitude,\n self.experiment_02.surveys[0].stations[0].location.latitude,\n )\n\n @classmethod\n def tearDownClass(self):\n self.mth5_obj.close_mth5()\n self.fn.unlink()\n\n\n# =============================================================================\n# Run\n# =============================================================================\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/version_1/test_build_from_experiment.py","file_name":"test_build_from_experiment.py","file_ext":"py","file_size_in_byte":12252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"51252103","text":"#!/usr/bin/env python-2.4.3\n#\n# October 29 2009, Ripon Bhattacharjee\n#\n# Copyright (c) 2009-2011 by cisco Systems, Inc.\n# All rights reserved.\n#\nimport pdb\nimport sys, os, time\nimport xrut, ip, pre, re, results, ut\n\n\n#\n#Oct 29 11:21:35.279 PDT\n#Neighbor VRF Spk AS InQ OutQ NBRState NSRState\n#10.0.0.100 default 0 100 0 0 Established -\n\nclass neighbor_brief_result_t (results.simple_column_table_result_t):\n '''An object containing the results form \"show bgp sessions.'''\n def __init__ (self, router):\n results.simple_column_table_result_t.__init__(\n self, router, \"show bgp sessions\",\n [\"Neighbor\", \"VRF\", \"Spk\", \"AS\", \"InQ\", \"OutQ\", \"NBRState\", \"NSRState\"])\n\n def has_neighbor (self, nbrid):\n nbrid = str(nbrid)\n return (self.entries.has_key(nbrid) and\n (self.entries[nbrid]['NBRState'] == \"Established\" ))\n\n def has_neighbors (self, neighbor_list):\n for nbr in neighbor_list:\n if not self.has_neighbor(nbr):\n return False\n return True\n\n def does_not_have_neighbor (self, nbrid):\n return not self.neighbors.has_key(nbrid)\n\n def does_not_have_neighbors (self, neighbor_list):\n for nbr in neighbor_list:\n if self.has_neighbor(nbr):\n return False\n return True\n\n def match_results (self, reach_list, not_reach_list = []):\n return (self.has_neighbors(reach_list) and\n self.does_not_have_neighbors(not_reach_list))\n\n\ndef has_neighbor_test(test, uut, rtr_if_list):\n '''has_neighbor_test\n\n Using neighbor_brief_result_t check that the router UUT\n is neighbors with all routers in ROUTER_LIST.'''\n\n if not isinstance(rtr_if_list, list):\n rtr_if_list = [ rtr_if_list ]\n\n name_list = \"\"\n id_list = []\n for rtr, ifname in rtr_if_list:\n id_list.append(str(rtr.interfaces[ifname].ipv4_prefix.address))\n if name_list == \"\":\n name_list = rtr.name\n else:\n name_list += \", \" + rtr.name\n\n ut.log_test_start(test,\n \"BGP: Verify \" + uut.name + \" is neighbors with \" + name_list)\n nres = neighbor_brief_result_t(uut)\n assert nres\n if nres.has_neighbors(id_list):\n ut.log_test_pass(test)\n return True\n else:\n ut.log_test_fail(test)\n return False\n\nclass bgp_neighbor_pred_t (pre.simple_pred_t):\n def __init__ (self, rtr, nbr_or_list):\n self.router = rtr\n if hasattr(nbr_or_list, '__iter__'):\n self.nbr_or_list = nbr_or_list\n else:\n self.nbr_or_list = [ nbr_or_list ]\n self.last_state = \"unset\"\n\n def test (self):\n self.last_state = True\n for nbr in self.nbr_or_list:\n output = self.router.send_command(\"show bgp neighbor \" + str(nbr))\n m = re.search(r\"BGP state = (\\w+)\", output)\n if not m or not m.group(1) == \"Established\":\n self.last_state = False\n break\n return self.last_state\n\n def __str__ (self):\n return \"Predicate(router \" + self.router.name + \": has BGP neighbors \" + str(self.nbr_or_list) + \" last: \" + str(self.last_state) + \")\"\n\nclass bgp_converged_pred_t (pre.simple_pred_t):\n \"\"\"Verify that BGP has converged.\"\"\"\n\n def __init__ (self, rtr, topo = \"ipv4 unicast\"):\n self.router = rtr\n self.topo = topo\n self.last_state = \"unuset\"\n\n def test (self):\n output = self.router.send_command(\"show bgp \" + self.topo + \" convergence\")\n m = re.search(\"\\r\\nConverged.\", output)\n if m:\n self.last_state = \"Converged\"\n return True\n else:\n self.last_state = \"Not converged\"\n return False\n\n def __str__ (self):\n return \"Predicate(router \" + self.router.name + \": BGP is converged. last: \" + self.last_state + \")\"\n\n","sub_path":"X-COPY/infra/test/xrut/modules/bgp.py","file_name":"bgp.py","file_ext":"py","file_size_in_byte":3940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"618588846","text":"from PyQt4.QtCore import Qt\r\nfrom PyQt4.QtGui import QGraphicsEllipseItem, QGraphicsItem, QBrush\r\n\r\nfrom info import Info\r\nfrom arrow import Arrow\r\n\r\n\r\nclass Particle(QGraphicsEllipseItem):\r\n def __init__(self, scene, m, v, *args, **kwargs):\r\n # Creates the particle of given size, fills with colour,\r\n # initializes variables to be used later\r\n\r\n super().__init__(*args, **kwargs)\r\n self.scene = scene\r\n self.initialX = args[0]\r\n self.velocity = v\r\n self.update_dx()\r\n self.mass = m\r\n self.r = args[2] / 2\r\n self.info = Info(scene)\r\n self.info.update(self)\r\n self.arrow = Arrow(self, scene)\r\n self.arrow.show()\r\n self.setFlag(QGraphicsItem.ItemIsMovable, True)\r\n self.setBrush(QBrush(Qt.blue))\r\n self.isPressed = False\r\n self.dragged = False\r\n self.doubleClicked = False\r\n\r\n def momentum(self):\r\n # Returns momentum of the particle\r\n\r\n return self.mass * self.velocity\r\n\r\n def x(self):\r\n # Returns the x-ordinate of left edge of the particle.\r\n\r\n return self.scenePos().x() + self.initialX\r\n\r\n def update_dx(self):\r\n # Calculates speed at which particle will be moving in the window.\r\n # Time is discrete, dx represents change in position per unit time.\r\n\r\n if abs(self.velocity) < 0.03:\r\n self.velocity = 0\r\n self.dx = round(self.velocity * self.scene.velocity_k, 2)\r\n\r\n def move(self):\r\n # Moves particle by it's dx.\r\n\r\n self.moveBy(self.dx, 0)\r\n self.info.update(self)\r\n\r\n def set_pos(self, x):\r\n # Changes particle's position,\r\n # so that x-ordinate of particle's left edge is at x.\r\n # Information about particle is moved with it.\r\n\r\n dx = x - self.x()\r\n self.moveBy(dx, 0)\r\n self.info.update(self)\r\n self.arrow.upd_pos()\r\n\r\n def update(self, m, v, r):\r\n # Sets new properties to particle and resizes it.\r\n\r\n self.arrow.hide()\r\n x0 = self.rect().x()\r\n y0 = self.rect().y()\r\n dr = r - self.r\r\n self.setRect(x0, y0, r+r, r+r)\r\n self.moveBy(-dr, -dr)\r\n\r\n self.r = r\r\n self.mass = m\r\n self.velocity = v\r\n self.info.update(self)\r\n self.arrow.show()\r\n\r\n def mousePressEvent(self, event):\r\n # Overriden method from QGraphicsEllipseItem class.\r\n # The purpose is to get click location and pause the system.\r\n\r\n super().mousePressEvent(event)\r\n if not allow_event(event):\r\n return\r\n self.isPressed = True\r\n self.scenePaused = self.scene.paused\r\n if self.scenePaused is False:\r\n self.scene.stop_timer()\r\n self.pressPos = event.pos().x()\r\n self.posWhenPressed = self.x()\r\n\r\n def mouseDoubleClickEvent(self, event):\r\n # Overriden method from QGraphicsEllipseItem class.\r\n # Method is used to indicate that particle was double-clicked.\r\n # This fact is then used in mouseReleaseEvent.\r\n\r\n super().mouseDoubleClickEvent(event)\r\n if allow_event(event):\r\n self.doubleClicked = True\r\n\r\n def mouseReleaseEvent(self, event):\r\n # Overriden method from QGraphicsEllipseItem class.\r\n # This method takes into account what events happened before.\r\n # If particle was double-clicked 'Edit particle' dialog is called.\r\n # It particle was dragged then it determines,\r\n # whether it can stay in current position.\r\n\r\n super().mouseReleaseEvent(event)\r\n if not allow_event(event):\r\n return\r\n if self.doubleClicked:\r\n self.scene.update_particle(self)\r\n self.doubleClicked = False\r\n if self.scenePaused is False:\r\n self.scene.start_timer()\r\n\r\n self.isPressed = False\r\n if self.dragged:\r\n if not self.scene.has_allowed_position(self):\r\n self.set_pos(self.posWhenPressed)\r\n self.scene.correct_order()\r\n if self.scenePaused is False:\r\n self.scene.start_timer()\r\n\r\n def mouseMoveEvent(self, event):\r\n # Overriden method from QGraphicsEllipseItem class.\r\n # The purpose is to restrict dragging to only one dimension.\r\n\r\n if self.isPressed:\r\n self.dragged = True\r\n mouseX = event.pos().x()\r\n # Mouse position from window\r\n dx = self.pressPos - self.x()\r\n self.set_pos(mouseX - dx)\r\n self.info.update(self)\r\n self.arrow.upd_pos()\r\n\r\n\r\ndef allow_event(event):\r\n # Tells whether event should be used.\r\n # Want to work only with left-clicks\r\n\r\n return event.button() == Qt.LeftButton\r\n","sub_path":"particle.py","file_name":"particle.py","file_ext":"py","file_size_in_byte":4748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"132876267","text":"import unittest\nimport json\n\nfrom campersheaven.engine import Engine\nfrom campersheaven.datastore import DictionaryStore\nfrom campersheaven.models import Camper\n\n\nclass TestEngine(unittest.TestCase):\n\n datadir = \"tests/data\"\n with open(f\"{datadir}/empty_camper.json\") as f:\n empty_data = f.read()\n with open(f\"{datadir}/correct_camper.json\") as f:\n correct_camper_data = f.read()\n with open(f\"{datadir}/correct_campers.json\") as f:\n correct_campers_data = f.read()\n\n def setUp(self):\n \"\"\"Setup Engine with an associated DictionaryStore\"\"\"\n self.ds = DictionaryStore(Camper)\n self.engine = Engine(self.ds)\n\n def test_insert_empty_data(self):\n \"\"\"Test insertion results of empty data\"\"\"\n self.engine.insert_data(self.empty_data)\n self.assertDictEqual(self.ds.store, {})\n\n def test_insert_data(self):\n \"\"\"Test insertion results of correct data\"\"\"\n self.engine.insert_data(self.correct_camper_data)\n self.assertDictEqual(\n self.ds.store,\n {\n 3: Camper(**{\n \"id\": 3,\n \"latitude\": 38.7436883,\n \"longitude\": -9.1952226,\n \"price_per_day\": 85.5,\n \"weekly_discount\": 0.25\n })\n })\n\n with open(f\"{datadir}/search_one.json\") as f:\n search_one = f.read()\n with open(f\"{datadir}/search_many.json\") as f:\n search_many = f.read()\n\n def test_search_emptystore(self):\n \"\"\"Test search results in an empty store\"\"\"\n results = self.engine.search(self.search_one)\n with open(f\"{self.datadir}/empty_results.json\") as f:\n self.assertDictEqual(\n json.loads(results),\n json.loads(f.read())\n )\n\n def test_search_one(self):\n \"\"\"Test search results giving only one result\"\"\"\n self.engine.insert_data(self.correct_camper_data)\n results = self.engine.search(self.search_one)\n with open(f\"{self.datadir}/results_one.json\") as f:\n self.assertDictEqual(\n json.loads(results),\n json.loads(f.read())\n )\n\n def test_search_many(self):\n \"\"\"Test search results giving many results\"\"\"\n self.engine.insert_data(self.correct_campers_data)\n results = self.engine.search(self.search_many)\n with open(f\"{self.datadir}/results_many.json\") as f:\n self.assertDictEqual(\n json.loads(results),\n json.loads(f.read())\n )\n","sub_path":"level2/tests/test_engine.py","file_name":"test_engine.py","file_ext":"py","file_size_in_byte":2592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"117213944","text":"\"\"\"\n# Harmonics\nExtract and analyze harmonic frequencies from power spectra.\n\n## Harmonic group extraction\n- `harmonic_groups()`: detect peaks in power spectrum and group them\n according to their harmonic structure.\n- `expand_group()`: add more harmonics to harmonic group. \n- `extract_fundamentals()`: collect harmonic groups from\n lists of power spectrum peaks.\n- `build_harmonic_group()`: Find all the harmonics belonging to the largest peak in the power spectrum.\n- `retrieve_harmonic_group()`: Find all the harmonics belonging to a given fundamental..\n- `threshold_estimate()`: estimates thresholds for peak detection\n in a power spectrum.\n\n## Handling of lists of harmonic groups\n- `fundamental_freqs()`: extract fundamental frequencies from\n lists of harmonic groups.\n- `fundamental_freqs_and_power()`: extract fundamental frequencies and their\n power in dB from lists of harmonic groups.\n\n## Handling of lists of fundamental frequencies\n- `add_relative_power()`: add a column with relative power.\n- `add_power_ranks()`: add a column with power ranks.\n- `similar_indices()`: indices of similar frequencies.\n- `unique_mask()`: mark similar frequencies from different recordings as dublicate.\n- `unique()`: remove similar frequencies from different recordings.\n\n## Visualization\n- `colors_markers()`: Generate a list of colors and markers for plotting.\n- `plot_harmonic_groups()`: Mark decibel power of fundamentals and their\n harmonics.\n- `plot_psd_harmonic_groups()`: Plot decibel power-spectrum with detected peaks,\n harmonic groups, and mains frequencies.\n\n## Configuration parameter\n- `add_psd_peak_detection_config()`: add parameters for the detection of\n peaks in power spectra to configuration.\n- `psd_peak_detection_args()`: retrieve parameters for the detection of peaks\n in power spectra from configuration.\n- `add_harmonic_groups_config()`: add parameters for the detection of\n harmonic groups to configuration.\n- `harmonic_groups_args()`: retrieve parameters for the detection of\n harmonic groups from configuration.\n\"\"\"\n\nfrom __future__ import print_function\nimport math as m\nimport numpy as np\nimport scipy.signal as sig\nfrom .eventdetection import detect_peaks, trim, hist_threshold\nfrom .powerspectrum import decibel, power, plot_decibel_psd\ntry:\n import matplotlib.cm as cm\n import matplotlib.colors as mc\nexcept ImportError:\n pass\n\n\ndef build_harmonic_group(good_freqs, all_freqs, freq_tol, verbose=0,\n min_group_size=4, max_divisor=4, max_rel_power_weight=2.0):\n \"\"\"Find all the harmonics belonging to the largest peak in a list of frequency peaks.\n\n Parameters\n ----------\n good_freqs: 2-D array\n List of frequency, power, and count of strong peaks\n in a power spectrum.\n all_freqs:\n List of frequency, power, and count of all peaks\n in a power spectrum.\n freq_tol: float\n Harmonics need to fall within this frequency tolerance.\n This should be in the range of the frequency resolution\n and not be smaller than half of the frequency resolution.\n verbose: int\n Verbosity level.\n min_group_size: int\n Within min_group_size no harmonics are allowed to be filled in.\n max_divisor: int\n Maximum divisor used for checking for sub-harmonics.\n max_rel_power_weight: float\n Harmonic groups with larger overall power are preferred. If min_group_size\n is larger than two, the overall power is divided by the relative power of\n the `min_group_size`-th harmonics relative to the power of the fundamental.\n This way, harmonic groups with strong harmonics are punished. The relative power\n can be limited to range from `1/max_rel_power_weight` to `max_rel_power_weight`.\n Set `max_rel_power_weight` to one to disable this.\n \n Returns\n -------\n good_freqs: 2-D array\n List of strong frequencies with frequencies of\n the returned group removed.\n all_freqs: 2-D array\n List of all frequencies with updated double-use counts.\n group: 2-D array\n The detected harmonic group. Might be empty.\n best_fzero_harmonics: int\n The highest harmonics that was used to recompute\n the fundamental frequency.\n fmax: float\n The frequency of the largest peak in good_freqs\n for which the harmonic group was detected.\n \"\"\"\n # check:\n if max_divisor > min_group_size:\n print('max_divisor=%d must not be larger than min_group_size=%d!'\n % (max_divisor, min_group_size))\n max_divisor = min_group_size\n # select strongest frequency for building the harmonic group:\n fmaxinx = np.argmax(good_freqs[:,1])\n fmax = good_freqs[fmaxinx,0]\n if verbose > 0:\n print('')\n print('%s build harmonic group %s' % (10*'#', 38*'#'))\n print('%s fmax=%7.2fHz, power=%9.3g %s'\n % (10*'#', fmax, good_freqs[fmaxinx,1], 27*'#'))\n print('good_freqs: ', '[',\n ', '.join(['%.2f' % f for f in good_freqs[:,0]]), ']')\n\n # container for harmonic groups\n best_group = []\n best_value = 0.0\n best_divisor = 0\n best_fzero = 0.0\n best_fzero_harmonics = 0\n\n # check for integer fractions of the frequency:\n for divisor in range(1, max_divisor + 1):\n # 1. hypothesized fundamental:\n fzero = fmax / divisor\n fzero_harmonics = 1\n \n # 2. find harmonics in good_freqs and adjust fzero accordingly:\n prev_freq = fmax\n for h in range(divisor+1, 2*min_group_size+1):\n ff = good_freqs[np.abs(good_freqs[:,0]/h - fzero)0) == 0:\n if h > min_group_size:\n break\n continue\n ff = ff[dh>0]\n dh = dh[dh>0]\n df = ff - prev_freq\n fe = np.abs(df/dh - fzero)\n idx = np.argmin(fe)\n if fe[idx] > 2.0*freq_tol:\n if h > min_group_size:\n break\n continue\n # update fzero:\n prev_freq = ff[idx]\n fzero_harmonics = h\n fzero = prev_freq/fzero_harmonics\n if verbose > 1:\n print('adjusted fzero to %.2fHz' % fzero)\n \n ## # this is not faster:\n ## freqs = [fmax]\n ## prev_h = divisor\n ## prev_fe = 0.0\n ## for f in good_freqs[good_freqs[:,0] > fmax + 0.6*fzero,0]:\n ## h = m.floor(f/fzero + 0.5) # round\n ## #if h < 1:\n ## # continue\n ## if h > min_group_size:\n ## if h - prev_h > 1 or h > 2*min_group_size:\n ## break\n ## if m.fabs(f/h - fzero) > freq_tol:\n ## continue\n ## df = f - freqs[-1]\n ## if df < 0.5*fzero and len(freqs)>1:\n ## df = f - freqs[-2]\n ## dh = m.floor(df/fzero + 0.5)\n ## fe = m.fabs(df/dh - fzero)\n ## if fe > 2.0*freq_tol:\n ## continue\n ## if h > prev_h or fe < prev_fe:\n ## prev_freq = f\n ## prev_h = h\n ## prev_fe = fe\n ## freqs.append(f)\n ## # update fzero:\n ## fzero_harmonics = prev_h\n ## fzero = prev_freq/fzero_harmonics\n ## if verbose > 1:\n ## print('adjusted fzero to %.2fHz' % fzero)\n \n if verbose > 0:\n print('# divisor: %d, fzero=%7.2fHz adjusted from harmonics %d'\n % (divisor, fzero, fzero_harmonics))\n # fmax might not be in our group anymore, because fzero was adjusted:\n if np.abs(fmax/divisor - fzero) > freq_tol:\n if verbose > 0:\n print(' discarded: lost frequency')\n continue\n\n # 3. collect harmonics from all_freqs:\n new_group = -np.ones(min_group_size, dtype=np.int)\n ## # slower:\n ## prev_freq = 0.0\n ## freqs = all_freqs[all_freqs[:,0]<(min_group_size+0.5)*fzero,0]\n ## for h in range(1, min_group_size+1):\n ## fac = 1.0 if h >= divisor else 2.0 \n ## sel = np.abs(freqs/h - fzero) < fac*freq_tol\n ## if sum(sel) == 0:\n ## if verbose > 1:\n ## print('no candidates at %d harmonics' % h)\n ## break\n ## ff = freqs[sel]\n ## df = np.abs(ff - prev_freq)\n ## fe = np.abs(df/np.round(df/fzero) - fzero)\n ## idx = np.argmin(fe)\n ## fac = 1.0 if h > divisor else 2.0 \n ## if fe[idx] > 2.0*fac*freq_tol:\n ## if verbose > 1:\n ## print('%d. harmonics is off %.2fHz' % (h, ff[idx]))\n ## break\n ## prev_freq = ff[idx]\n ## new_group[h-1] = np.where(sel)[0][idx]\n\n # a little bit faster:\n freqs = []\n prev_h = 0\n prev_fe = 0.0\n fupper = (min_group_size+0.5)*fzero\n for i, f in enumerate(all_freqs[all_freqs[:,0] < fupper,0]):\n h = m.floor(f/fzero + 0.5) # round\n if h < 1:\n continue\n if h > min_group_size:\n break\n fac = 1.0 if h >= divisor else 2.0\n if m.fabs(f/h - fzero) > fac*freq_tol:\n if verbose > 1 and m.fabs(f/h - fzero) < 20.0*fac*freq_tol:\n print(' %d. harmonics at %7.2fHz is off by %7.2fHz (max %5.2fHz) from %7.2fHz'\n % (h, f, f-h*fzero, fac*freq_tol, h*fzero))\n continue\n if len(freqs) > 0:\n pf = freqs[-1]\n df = f - pf\n if df < 0.5*fzero:\n if len(freqs)>1:\n pf = freqs[-2]\n df = f - pf\n else:\n pf = 0.0\n df = h*fzero\n dh = m.floor(df/fzero + 0.5)\n fe = m.fabs(df/dh - fzero)\n fac = 1.0 if h > divisor else 2.0 \n if fe > 2.0*fac*freq_tol:\n if verbose > 1:\n print(' %d. harmonics at %7.2fHz is off by %7.2fHz (max %5.2fHz) from previous harmonics at %7.2fHz'\n % (h, f, fe, 2.0*fac*freq_tol, pf))\n continue\n else:\n fe = 0.0\n if h > prev_h or fe < prev_fe:\n if h - prev_h > 1:\n break\n if h == prev_h and len(freqs) > 0:\n freqs.pop()\n freqs.append(f)\n new_group[int(h)-1] = i\n prev_h = h\n prev_fe = fe\n \n # 4. check new group:\n \n # all harmonics in min_group_size required:\n if np.any(new_group<0):\n if verbose > 0:\n print(' discarded group because %d smaller than min_group_size %d!' %\n (np.sum(new_group>=0), min_group_size), new_group)\n continue\n # check double use of frequencies:\n double_use = np.sum(all_freqs[new_group, 2]>0)\n if double_use > divisor:\n if verbose > 0:\n print(' discarded group because of double use = %d' % double_use)\n continue\n\n # 5. compare new group to best group:\n peaksum = np.sum(all_freqs[new_group, 1])\n rel_power = all_freqs[new_group[-1], 1]/all_freqs[new_group[0], 1]\n new_group_value = peaksum\n if min_group_size >= 3:\n fac = rel_power\n if fac < 1.0/max_rel_power_weight:\n fac = 1.0/max_rel_power_weight\n elif fac > max_rel_power_weight:\n fac = max_rel_power_weight\n new_group_value = peaksum/fac\n if verbose > 0:\n print(' new group: fzero=%7.2fHz, value=%9.3g, peaksum=%9.3g, relpower=%.3f'\n % (fzero, new_group_value, peaksum, rel_power), new_group)\n if verbose > 1:\n print(' best group: divisor=%d, fzero=%7.2fHz, value=%9.3g'\n % (best_divisor, best_fzero, best_value), best_group)\n # select new group if sum of peak power is larger and\n # relative power is smaller:\n if new_group_value >= best_value:\n best_value = new_group_value\n best_group = new_group\n best_divisor = divisor\n best_fzero = fzero\n best_fzero_harmonics = fzero_harmonics\n if verbose > 1:\n print(' new best group: divisor=%d, fzero=%7.2fHz, value=%9.3g'\n % (best_divisor, best_fzero, best_value), best_group)\n elif verbose > 0:\n print(' took as new best group')\n \n # no group found:\n if len(best_group) == 0:\n # erase freq:\n good_freqs = np.delete(good_freqs, fmaxinx, axis=0)\n group = np.zeros((0, 3))\n return good_freqs, all_freqs, group, 1, fmax\n\n # increment double use count:\n all_freqs[best_group, 2] += 1.0\n \n # fill up group:\n group = all_freqs[best_group,:]\n group[:,0] = np.arange(1,len(group)+1)*best_fzero\n\n # indices of group in good_freqs:\n ## indices = np.where(np.abs(good_freqs[:,0] - np.round(good_freqs[:,0]/best_fzero)*best_fzero) < 2.0*freq_tol)[0]\n ## \n indices = []\n freqs = []\n prev_h = 0\n prev_fe = 0.0\n for i, f in enumerate(good_freqs[:,0]):\n h = m.floor(f/best_fzero + 0.5) # round\n if h < 1:\n continue\n fac = 1.0 if h >= divisor else 2.0\n if m.fabs(f/h - best_fzero) > fac*freq_tol:\n continue\n if len(freqs) > 0:\n df = f - freqs[-1]\n if df <= 0.5*best_fzero:\n if len(freqs)>1:\n df = f - freqs[-2]\n else:\n df = h*best_fzero\n dh = m.floor(df/best_fzero + 0.5)\n fe = m.fabs(df/dh - best_fzero)\n fac = 1.0 if h > divisor else 2.0 \n if fe > 2.0*fac*freq_tol:\n continue\n else:\n fe = 0.0\n if h > prev_h or fe < prev_fe:\n if h == prev_h and len(freqs) > 0:\n freqs.pop()\n indices.pop()\n freqs.append(f)\n indices.append(i)\n prev_h = h\n prev_fe = fe\n ##\n ## # very slow:\n ## indices = []\n ## prev_freq = 0.0\n ## freqs = all_freqs[:,0]\n ## for h in range(1, int(m.floor(freqs[-1]/best_fzero+0.5))+1):\n ## fac = 1.0 if h >= divisor else 2.0 \n ## sel = np.abs(freqs/h - best_fzero) < fac*freq_tol\n ## if sum(sel) == 0:\n ## continue\n ## ff = freqs[sel]\n ## df = np.abs(ff - prev_freq)\n ## fe = np.abs(df/np.round(df/best_fzero) - best_fzero)\n ## idx = np.argmin(fe)\n ## fac = 1.0 if h > divisor else 2.0 \n ## if fe[idx] > 2.0*fac*freq_tol:\n ## continue\n ## prev_freq = ff[idx]\n ## indices.append(np.where(sel)[0][idx])\n\n # report:\n if verbose > 1:\n print('')\n print('# best group found for fmax=%.2fHz, fzero=%.2fHz, divisor=%d:'\n % (fmax, best_fzero, best_divisor))\n print('# best good freqs: ', indices,\n '[', ', '.join(['%.2f' % f for f in good_freqs[indices,0]]), ']')\n print('# best all freqs : ', best_group,\n '[', ', '.join(['%.2f' % f for f in all_freqs[best_group,0]]), ']')\n if verbose > 0:\n refi = np.argmax(group[:,1] > 0.0)\n print('')\n print('#### resulting harmonic group for fmax=%.2fHz' % fmax)\n for i in range(len(group)):\n print('f=%8.2fHz n=%5.2f: power=%9.3g power/p0=%6.4f'\n % (group[i,0], group[i,0]/group[0,0],\n group[i,1], group[i,1]/group[refi,1]))\n print('')\n \n # erase group from good_freqs:\n good_freqs = np.delete(good_freqs, indices, axis=0)\n\n # good_freqs: removed all frequencies of bestgroup\n # all_freqs: updated double use count\n return good_freqs, all_freqs, group, best_fzero_harmonics, fmax\n\n\ndef retrieve_harmonic_group(freq, good_freqs, all_freqs, freq_tol, verbose=0,\n min_group_size=4):\n \"\"\"Find all the harmonics belonging to a given fundamental.\n\n Parameters\n ----------\n freq: float\n Fundamental frequency for which harmonics are retrieved.\n good_freqs: 2-D array\n List of frequency, power, and count of strong peaks\n in a power spectrum.\n all_freqs:\n List of frequency, power, and count of all peaks\n in a power spectrum.\n freq_tol: float\n Harmonics need to fall within this frequency tolerance.\n This should be in the range of the frequency resolution\n and not be smaller than half of the frequency resolution.\n verbose: int\n Verbosity level.\n min_group_size: int\n Within min_group_size no harmonics are allowed to be filled in.\n \n Returns\n -------\n good_freqs: 2-D array\n List of strong frequencies with frequencies of\n the returned group removed.\n all_freqs: 2-D array\n List of all frequencies with updated double-use counts.\n group: 2-D array\n The detected harmonic group. Might be empty.\n fzero_harmonics: int\n The highest harmonics that was used to recompute\n the fundamental frequency.\n \"\"\"\n if verbose > 0:\n print('')\n print('%s retrieve harmonic group %s' % (10*'#', 35*'#'))\n print('%s freq=%7.2fHz %s' % (10*'#', freq, 44*'#'))\n print('good_freqs: ', '[',\n ', '.join(['%.2f' % f for f in good_freqs[:,0]]), ']')\n\n # 1. find harmonics in good_freqs and adjust fzero accordingly:\n fzero = freq\n fzero_harmonics = 1\n prev_freq = fzero\n for h in range(2, 2*min_group_size+1):\n ff = good_freqs[np.abs(good_freqs[:,0]/h - fzero)0) == 0:\n if h > min_group_size:\n break\n continue\n ff = ff[dh>0]\n dh = dh[dh>0]\n df = ff - prev_freq\n fe = np.abs(df/dh - fzero)\n idx = np.argmin(fe)\n if fe[idx] > 2.0*freq_tol:\n if h > min_group_size:\n break\n continue\n # update fzero:\n prev_freq = ff[idx]\n fzero_harmonics = h\n fzero = prev_freq/fzero_harmonics\n if verbose > 1:\n print('adjusted fzero to %.2fHz' % fzero)\n if verbose > 0:\n print('# fzero=%7.2fHz adjusted from harmonics %d'\n % (fzero, fzero_harmonics))\n # freq might not be in our group anymore, because fzero was adjusted:\n if np.abs(freq - fzero) > freq_tol:\n if verbose > 0:\n print(' discarded: lost frequency')\n return good_freqs, all_freqs, np.zeros((0, 2)), fzero_harmonics\n\n # 2. collect harmonics from all_freqs:\n new_group = -np.ones(min_group_size, dtype=np.int)\n freqs = []\n prev_h = 0\n prev_fe = 0.0\n fupper = (min_group_size+0.5)*fzero\n for i, f in enumerate(all_freqs[all_freqs[:,0] < fupper,0]):\n h = m.floor(f/fzero + 0.5) # round\n if h < 1:\n continue\n if h > min_group_size:\n break\n fac = 1.0 if h >= 1 else 2.0\n if m.fabs(f/h - fzero) > fac*freq_tol:\n if verbose > 1 and m.fabs(f/h - fzero) < 20.0*fac*freq_tol:\n print(' %d. harmonics at %7.2fHz is off by %7.2fHz (max %5.2fHz) from %7.2fHz'\n % (h, f, f-h*fzero, fac*freq_tol, h*fzero))\n continue\n if len(freqs) > 0:\n pf = freqs[-1]\n df = f - pf\n if df < 0.5*fzero:\n if len(freqs)>1:\n pf = freqs[-2]\n df = f - pf\n else:\n pf = 0.0\n df = h*fzero\n dh = m.floor(df/fzero + 0.5)\n fe = m.fabs(df/dh - fzero)\n fac = 1.0 if h > 1 else 2.0 \n if fe > 2.0*fac*freq_tol:\n if verbose > 1:\n print(' %d. harmonics at %7.2fHz is off by %7.2fHz (max %5.2fHz) from previous harmonics at %7.2fHz'\n % (h, f, fe, 2.0*fac*freq_tol, pf))\n continue\n else:\n fe = 0.0\n if h > prev_h or fe < prev_fe:\n if h - prev_h > 1:\n break\n if h == prev_h and len(freqs) > 0:\n freqs.pop()\n freqs.append(f)\n new_group[int(h)-1] = i\n prev_h = h\n prev_fe = fe\n\n # 3. check new group:\n\n # all harmonics in min_group_size required:\n if np.any(new_group<0):\n if verbose > 0:\n print(' discarded group because %d smaller than min_group_size %d!' %\n (np.sum(new_group>=0), min_group_size), new_group)\n return good_freqs, all_freqs, np.zeros((0, 2)), fzero_harmonics\n # check double use of frequencies:\n double_use = np.sum(all_freqs[new_group, 2]>0)\n if double_use > 1:\n if verbose > 0:\n print(' discarded group because of double use = %d' % double_use)\n return good_freqs, all_freqs, np.zeros((0, 2)), fzero_harmonics\n\n # increment double use count:\n all_freqs[new_group, 2] += 1.0\n \n # fill up group:\n group = all_freqs[new_group,:]\n group[:,0] = np.arange(1,len(group)+1)*fzero\n\n # indices of group in good_freqs:\n indices = []\n freqs = []\n prev_h = 0\n prev_fe = 0.0\n for i, f in enumerate(good_freqs[:,0]):\n h = m.floor(f/fzero + 0.5) # round\n if h < 1:\n continue\n fac = 1.0 if h >= 1 else 2.0\n if m.fabs(f/h - fzero) > fac*freq_tol:\n continue\n if len(freqs) > 0:\n df = f - freqs[-1]\n if df <= 0.5*fzero:\n if len(freqs)>1:\n df = f - freqs[-2]\n else:\n df = h*fzero\n dh = m.floor(df/fzero + 0.5)\n fe = m.fabs(df/dh - fzero)\n fac = 1.0 if h > 1 else 2.0 \n if fe > 2.0*fac*freq_tol:\n continue\n else:\n fe = 0.0\n if h > prev_h or fe < prev_fe:\n if h == prev_h and len(freqs) > 0:\n freqs.pop()\n indices.pop()\n freqs.append(f)\n indices.append(i)\n prev_h = h\n prev_fe = fe\n\n # report:\n if verbose > 1:\n print('')\n print('# group found for freq=%.2fHz, fzero=%.2fHz:'\n % (freq, fzero))\n print('# good freqs: ', indices,\n '[', ', '.join(['%.2f' % f for f in good_freqs[indices,0]]), ']')\n print('# all freqs : ', new_group,\n '[', ', '.join(['%.2f' % f for f in all_freqs[new_group,0]]), ']')\n if verbose > 0:\n refi = np.argmax(group[:,1] > 0.0)\n print('')\n print('#### resulting harmonic group for freq=%.2fHz' % freq)\n for i in range(len(group)):\n print('f=%8.2fHz n=%5.2f: power=%9.3g power/p0=%6.4f'\n % (group[i,0], group[i,0]/group[0,0],\n group[i,1], group[i,1]/group[refi,1]))\n print('')\n \n # erase group from good_freqs:\n good_freqs = np.delete(good_freqs, indices, axis=0)\n\n # good_freqs: removed all frequencies of bestgroup\n # all_freqs: updated double use count\n return good_freqs, all_freqs, group, fzero_harmonics\n\n\ndef expand_group(group, freqs, freq_tol, max_harmonics=0):\n \"\"\" Add more harmonics to harmonic group. \n\n Parameters\n ----------\n group: ndarray\n Group of fundamental frequency and harmonics\n as returned by build_harmonic_group.\n freqs: 2D array\n List of frequency, power, and count of all peaks\n in a power spectrum.\n freq_tol: float\n Harmonics need to fall within this frequency tolerance.\n This should be in the range of the frequency resolution\n and not be smaller than half of the frequency resolution.\n max_harmonics: int\n Maximum number of harmonics to be returned for each group.\n \"\"\"\n if len(group) == 0:\n return group\n if max_harmonics <= 0:\n max_harmonics = 10000\n if max_harmonics <= len(group):\n return group\n fzero = group[0,0]\n ## indices = np.where(np.abs(freqs[:,0] - np.round(freqs[:,0]/fzero)*fzero) < 2.0*freq_tol)[0]\n ## \n indices = []\n group_freqs = list(group[:,0])\n prev_h = len(group_freqs)\n prev_fe = 0.0\n for i, f in enumerate(freqs[:,0]):\n if f <= group[-1,0] + 0.5*fzero:\n continue\n h = m.floor(f/fzero + 0.5) # round\n if h > max_harmonics:\n break\n if m.fabs(f/h - fzero) > freq_tol:\n continue\n df = f - group_freqs[-1]\n if df <= 0.5*fzero:\n if len(group_freqs)>1:\n df = f - group_freqs[-2]\n else:\n df = h*fzero\n dh = m.floor(df/fzero + 0.5)\n fe = m.fabs(df/dh - fzero)\n if fe > 2.0*freq_tol:\n continue\n if h > prev_h or fe < prev_fe:\n if h == prev_h and len(group_freqs) > 0:\n group_freqs.pop()\n indices.pop()\n ## do we realy need fill ins? It is not working anyways!\n ## else:\n ## while prev_h < h-2:\n ## indices.append(-1)\n ## prev_h += 1\n group_freqs.append(f)\n indices.append(i)\n prev_h = h\n prev_fe = fe\n # assemble group:\n new_group = freqs[indices,:group.shape[1]]\n ## indices = np.array(indices)\n ## new_group = np.zeros((len(indices),group.shape[1]))\n ## new_group[indices>=0,:] = freqs[indices[indices>=0],:group.shape[1]]\n ## fill_in = np.where(indices<0)[0]\n ## new_group[indices<0,0] = fzero*(fill_in+1)\n #group[:,0] = np.arange(1,len(group)+1)*fzero\n return np.vstack((group, new_group))\n \n\ndef extract_fundamentals(good_freqs, all_freqs, freq_tol, verbose=0,\n check_freqs=[], mains_freq=60.0, mains_freq_tol=1.0,\n min_freq=0.0, max_freq=2000.0,\n max_divisor=4, min_group_size=4,\n max_rel_power_weight=2.0, max_rel_power=0.0,\n max_harmonics=0, max_groups=0, **kwargs):\n \"\"\"Extract fundamental frequencies from power-spectrum peaks.\n \n Parameters\n ----------\n good_freqs: 2-D array\n List of frequency, power, and count of strong peaks\n in a power spectrum.\n all_freqs: 2-D array\n List of frequency, power, and count of all peaks\n in a power spectrum.\n freq_tol: float\n Harmonics need to fall within this frequency tolerance.\n This should be in the range of the frequency resolution\n and not be smaller than half of the frequency resolution.\n verbose: int\n Verbosity level.\n check_freqs: list of float\n List of fundamental frequencies that will be checked\n first for being present and valid harmonic groups in the peak frequencies\n of a power spectrum.\n mains_freq: float\n Frequency of the mains power supply.\n mains_freq_tol: float\n Tolarerance around harmonics of the mains frequency,\n within which peaks are removed.\n min_freq: float\n Minimum frequency accepted as a fundamental frequency.\n max_freq: float\n Maximum frequency accepted as a fundamental frequency.\n max_divisor: int\n Maximum divisor used for checking for sub-harmonics.\n min_group_size: int\n Within min_group_size no harmonics are allowed to be filled in.\n max_rel_power_weight: float\n Harmonic groups with larger overall power are preferred. If min_group_size\n is larger than two, the overall power is divided by the relative power of\n the `min_group_size`-th harmonics relative to the power of the fundamental.\n This way, harmonic groups with strong harmonics are punished. The relative power\n can be limited to range from `1/max_rel_power_weight` to `max_rel_power_weight`.\n Set `max_rel_power_weight` to one to disable this.\n max_rel_power: float\n Maximum allowed power of the `min_group_size`-th harmonics\n relative to fundamental. If zero do not check for relative power.\n max_harmonics: int\n Maximum number of harmonics to be returned for each group.\n max_groups: int\n If not zero the maximum number of most powerful harmonic groups.\n\n Returns\n -------\n group_list: list of 2-D arrays\n List of all harmonic groups found sorted by fundamental frequency.\n Each harmonic group is a 2-D array with the first dimension the harmonics\n and the second dimension containing frequency and power of each harmonic.\n If the power is zero, there was no corresponding peak in the power spectrum.\n fzero_harmonics_list: list of int\n The harmonics from which the fundamental frequencies were computed.\n mains_freqs: 2-d array\n Array of mains peaks found in all_freqs (frequency, power).\n \"\"\"\n if verbose > 0:\n print('')\n\n # set double use count to zero:\n all_freqs[:,2] = 0.0\n\n # remove power line harmonics from good_freqs:\n if mains_freq > 0.0:\n indices = np.where(np.abs(good_freqs[:,0] - np.round(good_freqs[:,0]/mains_freq)*mains_freq) < mains_freq_tol)[0]\n if len(indices)>0:\n if verbose > 1:\n print('remove power line frequencies',\n ', '.join(['%.1f' % f for f in good_freqs[indices,0]]))\n good_freqs = np.delete(good_freqs, indices, axis=0)\n\n if verbose > 1:\n print('all_freqs: ', '[',\n ', '.join(['%.2f' % f for f in all_freqs[:,0] if f < 3000.0]), ']')\n\n group_list = []\n fzero_harmonics_list = []\n first = True\n # as long as there are frequencies left in good_freqs:\n fi = 0\n while len(good_freqs) > 0:\n if fi < len(check_freqs):\n # check for harmonic group of a given fundamental frequency:\n fmax = check_freqs[fi]\n f0s = 'freq'\n good_freqs, all_freqs, harm_group, fzero_harmonics = \\\n retrieve_harmonic_group(fmax, good_freqs, all_freqs, freq_tol,\n verbose-1, min_group_size)\n fi += 1\n else:\n # check for harmonic groups:\n f0s = 'fmax'\n good_freqs, all_freqs, harm_group, fzero_harmonics, fmax = \\\n build_harmonic_group(good_freqs, all_freqs, freq_tol,\n verbose-1, min_group_size, max_divisor)\n\n # nothing found:\n if len(harm_group) == 0:\n if verbose > 1 or first:\n s = 'largest' if first else ''\n print('No %-7s harmonic group %7.2fHz' % (s, fmax))\n first = False\n continue\n first = False\n\n # check frequency range of fundamental:\n fundamental_ok = (harm_group[0, 0] >= min_freq and\n harm_group[0, 0] <= max_freq)\n # check power hum:\n mains_ok = ((mains_freq <= 0.0) or\n (m.fabs(harm_group[0,0] - mains_freq) > freq_tol))\n # check relative power of highest harmonic:\n rpower = harm_group[-1,1]/harm_group[0,1]\n amplitude_ok = ((max_rel_power <= 0.0) or (rpower < max_rel_power))\n # check:\n if fundamental_ok and mains_ok and amplitude_ok:\n if verbose > 0:\n print('Accepting harmonic group from %s=%7.2fHz: %7.2fHz power=%9.3g'\n % (f0s, fmax, harm_group[0,0], np.sum(harm_group[:,1])))\n group_list.append(harm_group[:,0:2])\n fzero_harmonics_list.append(fzero_harmonics)\n else:\n if verbose > 0:\n fs = 'is ' if fundamental_ok else 'not'\n ms = 'not ' if mains_ok else 'is'\n ps = 'smaller' if amplitude_ok else 'larger '\n print('Discarded harmonic group from %s=%7.2fHz: %7.2fHz power=%9.3g: %s in frequency range, %s mains frequency, relpower=%5.3f %s than %5.3f'\n % (f0s, fmax, harm_group[0,0], np.sum(harm_group[:,1]),\n fs, ms, rpower, ps, max_rel_power))\n \n # select most powerful harmonic groups:\n if max_groups > 0:\n powers = [np.sum(group[:,1]) for group in group_list]\n powers_inx = np.argsort(powers)\n group_list = [group_list[pi] for pi in powers_inx[-max_groups:]]\n fzero_harmonics_list = [fzero_harmonics_list[pi] for pi in powers_inx[-max_groups:]]\n if verbose > 0:\n print('Selected the %d most powerful groups.' % max_groups)\n \n # sort groups by fundamental frequency:\n freqs = [group[0,0] for group in group_list]\n freq_inx = np.argsort(freqs)\n group_list = [expand_group(group_list[fi], all_freqs, freq_tol, max_harmonics) for fi in freq_inx]\n fzero_harmonics_list = [fzero_harmonics_list[fi] for fi in freq_inx]\n\n if verbose > 1:\n print('')\n if len(group_list) > 0:\n print('## FUNDAMENTALS FOUND: ##')\n for group, fzero_h in zip(group_list, fzero_harmonics_list):\n print('%7.2fHz: power=%9.3g fzero-h=%2d'\n % (group[0,0], np.sum(group[:,1]), fzero_h))\n else:\n print('## NO FUNDAMENTALS FOUND ##')\n\n # assemble mains frequencies from all_freqs:\n if mains_freq > 0.0:\n mains_freqs = all_freqs[np.abs(all_freqs[:,0] - np.round(all_freqs[:,0]/mains_freq)*mains_freq) < mains_freq_tol,:2]\n else:\n mains_freqs = np.zeros((0, 2))\n \n return group_list, fzero_harmonics_list, mains_freqs\n\n \ndef threshold_estimate(psd_data, low_thresh_factor=6.0, high_thresh_factor=10.0,\n nbins=100, hist_height=1.0/ np.sqrt(np.e)):\n \"\"\"Estimate thresholds for peak detection from histogram of power spectrum.\n\n The standard deviation of the noise floor without peaks is estimated from\n the width of the histogram of the power spectrum at `hist_height` relative height.\n The histogram is computed in the third quarter of the linearly detrended power spectrum.\n\n Parameters\n ----------\n psd_data: array\n The power spectrum from which to estimate the thresholds.\n low_thresh_factor: float\n Factor by which the estimated standard deviation of the noise floor\n is multiplied to set the `low_threshold`.\n high_thresh_factor: float\n Factor by which the estimated standard deviation of the noise floor\n is multiplied to set the `high_threshold`.\n nbins: int or list of floats\n Number of bins or the bins for computing the histogram.\n hist_height: float\n Height between 0 and 1 at which the standard deviation of the histogram is estimated.\n\n Returns\n -------\n low_threshold: float\n The threshold for peaks just above the noise floor.\n high_threshold: float\n The threshold for distinct peaks.\n center: float\n The baseline level of the power spectrum.\n \"\"\"\n n = len(psd_data)\n psd_data_seg = psd_data[n//2:n*3//4]\n psd_data_seg = psd_data_seg[~np.isinf(psd_data_seg)]\n psd_data_seg = np.mean(psd_data_seg) + \\\n sig.detrend(psd_data_seg, type='linear')\n noise_std, center = hist_threshold(psd_data_seg, thresh_fac=1.0, nbins=nbins)\n low_threshold = noise_std * low_thresh_factor\n high_threshold = noise_std * high_thresh_factor\n return low_threshold, high_threshold, center\n\n\ndef harmonic_groups(psd_freqs, psd, verbose=0, check_freqs=[],\n low_threshold=0.0, high_threshold=0.0, thresh_bins=100,\n low_thresh_factor=6.0, high_thresh_factor=10.0,\n freq_tol_fac=1.0, mains_freq=60.0, mains_freq_tol=1.0,\n min_freq=0.0, max_freq=2000.0, max_divisor=4,\n min_group_size=4, max_rel_power_weight=2.0, max_rel_power=0.0,\n max_harmonics=0, max_groups=0, **kwargs):\n \"\"\"Detect peaks in power spectrum and group them according to their harmonic structure.\n\n Parameters\n ----------\n psd_freqs: array\n Frequencies of the power spectrum.\n psd: array\n Power spectrum (linear, not decible).\n verbose: int\n Verbosity level.\n check_freqs: list of float\n List of fundamental frequencies that will be checked\n first for being present and valid harmonic groups in the peak frequencies\n of the power spectrum.\n low_threshold: float\n The relative threshold for detecting all peaks in the decibel spectrum.\n high_threshold: float\n The relative threshold for detecting good peaks in the decibel spectrum.\n thresh_bins: int or list of floats\n Number of bins or the bins for computing the histogram from\n which the standard deviation of the noise level in the `psd` is estimated.\n low_thresh_factor: float\n Factor by which the estimated standard deviation of the noise floor\n is multiplied to set the `low_threshold`.\n high_thresh_factor: float\n Factor by which the estimated standard deviation of the noise floor\n is multiplied to set the `high_threshold`.\n freq_tol_fac: float\n Harmonics need to fall within `deltaf*freq_tol_fac`.\n mains_freq: float\n Frequency of the mains power supply.\n mains_freq_tol: float\n Tolarerance around harmonics of the mains frequency,\n within which peaks are removed.\n min_freq: float\n Minimum frequency accepted as a fundamental frequency.\n max_freq: float\n Maximum frequency accepted as a fundamental frequency.\n max_divisor: int\n Maximum divisor used for checking for sub-harmonics.\n min_group_size: int\n Within min_group_size no harmonics are allowed to be filled in.\n max_rel_power_weight: float\n Harmonic groups with larger overall power are preferred. If min_group_size\n is larger than two, the overall power is divided by the relative power of\n the `min_group_size`-th harmonics relative to the power of the fundamental.\n This way, harmonic groups with strong harmonics are punished. The relative power\n can be limited to range from `1/max_rel_power_weight` to `max_rel_power_weight`.\n Set `max_rel_power_weight` to one to disable this.\n max_rel_power: float\n Maximum allowed power of the min_group_size harmonics\n relative to fundamental. If zero do not check for relative power.\n max_harmonics: int\n Maximum number of harmonics to be returned for each group.\n max_groups: int\n If not zero the maximum number of most powerful harmonic groups.\n\n Returns\n -------\n group_list: list of 2-D arrays\n List of all extracted harmonic groups, sorted by fundamental frequency.\n Each harmonic group is a 2-D array with the first dimension the harmonics\n and the second dimension containing frequency and power of each harmonic.\n If the power is zero, there was no corresponding peak in the power spectrum.\n fzero_harmonics: list of ints\n The harmonics from which the fundamental frequencies were computed.\n mains: 2-d array\n Frequencies and power of multiples of the mains frequency found in the power spectrum.\n all_freqs: 2-d array\n Peaks in the power spectrum detected with low threshold\n [frequency, power, double use count].\n good_freqs: 1-d array\n Frequencies of peaks detected with high threshold.\n low_threshold: float\n The relative threshold for detecting all peaks in the decibel spectrum.\n high_threshold: float\n The relative threshold for detecting good peaks in the decibel spectrum.\n center: float\n The baseline level of the power spectrum.\n \"\"\"\n if verbose > 0:\n print('')\n print(70*'#')\n print('##### harmonic_groups', 48*'#')\n\n # decibel power spectrum:\n log_psd = decibel(psd)\n delta_f = psd_freqs[1] - psd_freqs[0]\n\n # thresholds:\n center = np.NaN\n if low_threshold <= 0.0 or high_threshold <= 0.0:\n low_th, high_th, center = threshold_estimate(log_psd, low_thresh_factor,\n high_thresh_factor,\n thresh_bins)\n if low_threshold <= 0.0:\n low_threshold = low_th\n if high_threshold <= 0.0:\n high_threshold = high_th\n if verbose > 1:\n print('')\n print('low_threshold =%g center+low_threshold =%g' % (low_threshold, center + low_threshold))\n print('high_threshold=%g center+high_threshold=%g' % (high_threshold, center + high_threshold))\n print('center=%g' % center)\n\n # detect peaks in decibel power spectrum:\n peaks, troughs = detect_peaks(log_psd, low_threshold)\n peaks, troughs = trim(peaks, troughs)\n all_freqs = np.zeros((len(peaks), 3))\n all_freqs[:,0] = psd_freqs[peaks]\n all_freqs[:,1] = psd[peaks]\n\n if len(all_freqs) == 0:\n return [], [], [], np.zeros((0, 3)), [], low_threshold, high_threshold, center\n \n # select good peaks:\n good_freqs = all_freqs[(log_psd[peaks] - log_psd[troughs] > high_threshold) &\n (all_freqs[:,0] >= min_freq) &\n (all_freqs[:,0] < max_freq*max_divisor),:]\n\n # detect harmonic groups:\n groups, fzero_harmonics, mains = \\\n extract_fundamentals(good_freqs, all_freqs, delta_f*freq_tol_fac,\n verbose, check_freqs, mains_freq, mains_freq_tol,\n min_freq, max_freq, max_divisor, min_group_size,\n max_rel_power_weight, max_rel_power, max_harmonics, max_groups)\n\n return (groups, fzero_harmonics, mains, all_freqs, good_freqs[:,0],\n low_threshold, high_threshold, center)\n\n\ndef fundamental_freqs(group_list):\n \"\"\"\n Extract fundamental frequencies from lists of harmonic groups.\n\n The inner list of 2-D arrays of the input argument is transformed into\n a 1-D array containig the fundamental frequencies extracted from\n the 2-D arrays.\n\n Parameters\n ----------\n group_list: (list of (list of ...)) list of 2-D arrays\n Arbitrarily nested lists of harmonic groups as returned by\n extract_fundamentals() and harmonic_groups() with the element\n [0, 0] being the fundamental frequency.\n\n Returns\n -------\n fundamentals: (list of (list of ...)) 1-D array\n Nested list (corresponding to `group_list`) of 1-D arrays\n with the fundamental frequencies extracted from the harmonic groups.\n \"\"\"\n if len(group_list) == 0:\n return np.array([])\n\n # check whether group_list is list of harmonic groups:\n list_of_groups = True\n for group in group_list:\n if not ( hasattr(group, 'shape') and len(group.shape) == 2 ):\n list_of_groups = False\n break\n\n if list_of_groups:\n fundamentals = np.array([group[0, 0] for group in group_list if len(group) > 0])\n else:\n fundamentals = []\n for groups in group_list:\n f = fundamental_freqs(groups)\n fundamentals.append(f)\n return fundamentals\n\n\ndef fundamental_freqs_and_power(group_list, power=False,\n ref_power=1.0, min_power=1e-20):\n \"\"\"\n Extract fundamental frequencies and their power in dB from lists of harmonic groups.\n\n The inner list of 2-D arrays of the input argument is transformed\n into a 2-D array containig for each fish (1st dimension) the\n fundamental frequencies and powers (summed over all harmonics)\n extracted from the 2-D arrays.\n \n Parameters\n ----------\n group_list: (list of (list of ...)) list of 2-D arrays\n Arbitrarily nested lists of harmonic groups as returned by\n extract_fundamentals() and harmonic_groups() with the element\n [0, 0] being the fundamental frequency and the elements [:,1] being\n the powers of each harmonics.\n power: boolean\n If `False` convert the power into decibel using the\n powerspectrum.decibel() function.\n ref_power: float\n Reference power for computing decibel.\n If set to `None` the maximum power is used.\n min_power: float\n Power values smaller than `min_power` are set to `-np.inf`.\n\n Returns\n -------\n fundamentals: (list of (list of ...)) 2-D array\n Nested list (corresponding to `group_list`) of 2-D arrays\n with fundamental frequencies in first column and\n corresponding power in second column.\n \"\"\"\n\n if len(group_list) == 0:\n return np.array([])\n\n # check whether group_list is list of harmonic groups:\n list_of_groups = True\n for group in group_list:\n if not ( hasattr(group, 'shape') and len(group.shape) == 2 ):\n list_of_groups = False\n break\n \n if list_of_groups:\n fundamentals = np.array([[group[0, 0], np.sum(group[:, 1])]\n for group in group_list if len(group) > 0])\n if not power:\n fundamentals[:, 1] = decibel(fundamentals[:, 1],\n ref_power, min_power)\n else:\n fundamentals = []\n for groups in group_list:\n f = fundamental_freqs_and_power(groups, power,\n ref_power, min_power)\n fundamentals.append(f)\n return fundamentals\n\n\ndef add_relative_power(freqs):\n \"\"\" Add a column with relative power.\n\n For each element in `freqs`, its maximum power is subtracted\n from all powers.\n\n Parameters\n ----------\n freqs: list of 2D ndarrays\n First column in the ndarrays is fundamental frequency and\n second column the corresponding power.\n Further columns are optional and kept in the returned list.\n fundamental_freqs_and_power() returns such a list.\n\n Returns\n -------\n power_freqs: list of 2D ndarrays\n Same as freqs, but with an added column containing the relative power.\n \"\"\"\n return [np.column_stack((f, f[:,1] - np.max(f[:,1]))) for f in freqs]\n\n\ndef add_power_ranks(freqs):\n \"\"\" Add a column with power ranks.\n\n Parameters\n ----------\n freqs: list of 2D ndarrays\n First column in the ndarrays is fundamental frequency and\n second column the corresponding power.\n Further columns are optional and kept in the returned list.\n fundamental_freqs_and_power() returns such a list.\n\n Returns\n -------\n rank_freqs: list of 2D ndarrays\n Same as freqs, but with an added column containing the ranks.\n The highest power is assinged to zero,\n lower powers are assigned negative integers.\n \"\"\"\n rank_freqs = []\n for f in freqs:\n i = np.argsort(f[:,1])[::-1]\n ranks = np.empty_like(i)\n ranks[i] = -np.arange(len(i))\n rank_freqs.append(np.column_stack((f, ranks)))\n return rank_freqs\n\n\ndef similar_indices(freqs, df_thresh, nextfs=0):\n \"\"\" Indices of similar frequencies.\n\n If two frequencies from different elements in the inner lists of `freqs` are\n reciprocally the closest to each other and closer than `df_thresh`,\n then two indices (element, frequency) of the respective other frequency\n are appended.\n\n Parameters\n ----------\n freqs: (list of (list of ...)) list of 2D ndarrays\n First column in the ndarrays is fundamental frequency.\n df_thresh: float\n Fundamental frequencies closer than this threshold are considered\n equal.\n nextfs: int\n If zero, compare all elements in freqs with each other. Otherwise,\n only compare with the `nextfs` next elements in freqs.\n\n Returns\n -------\n indices: (list of (list of ...)) list of list of two-tuples of int\n For each frequency of each element in `freqs` a list of two tuples containing\n the indices of elements and frequencies that are similar.\n \"\"\"\n if len(freqs) == 0:\n return []\n \n # check whether freqs is list of fundamental frequencies and powers:\n list_of_freq_power = True\n for group in freqs:\n if not (hasattr(group, 'shape') and len(group.shape) == 2):\n list_of_freq_power = False\n break\n\n if list_of_freq_power:\n indices = [ [[] for j in range(len(freqs[i]))] for i in range(len(freqs))]\n for j in range(len(freqs)-1):\n freqsj = np.asarray(freqs[j])\n for m in range(len(freqsj)):\n freq1 = freqsj[m]\n nn = len(freqs) if nextfs == 0 else j+1+nextfs\n if nn > len(freqs):\n nn = len(freqs)\n for k in range(j+1, nn):\n freqsk = np.asarray(freqs[k])\n if len(freqsk) == 0:\n continue\n n = np.argmin(np.abs(freqsk[:,0] - freq1[0]))\n freq2 = freqsk[n]\n if np.argmin(np.abs(freqsj[:,0] - freq2[0])) != m:\n continue\n if np.abs(freq1[0] - freq2[0]) < df_thresh:\n indices[k][n].append((j, m))\n indices[j][m].append((k, n))\n else:\n indices = []\n for groups in freqs:\n indices.append(similar_indices(groups, df_thresh, nextfs))\n return indices\n\n\ndef unique_mask(freqs, df_thresh, nextfs=0):\n \"\"\" Mark similar frequencies from different recordings as dublicate.\n\n If two frequencies from different elements in `freqs` are\n reciprocally the closest to each other and closer than `df_thresh`,\n then the one with the smaller power is marked for removal.\n\n Parameters\n ----------\n freqs: list of 2D ndarrays\n First column in the ndarrays is fundamental frequency and\n second column the corresponding power or equivalent.\n If values in the second column are equal (e.g. they are the same ranks),\n and there is a third column (e.g. power),\n the third column is used to decide, which element should be removed.\n df_thresh: float\n Fundamental frequencies closer than this threshold are considered\n equal.\n nextfs: int\n If zero, compare all elements in freqs with each other. Otherwise,\n only compare with the `nextfs` next elements in freqs.\n\n Returns\n -------\n mask: list of boolean arrays\n For each element in `freqs` True if that frequency should be kept.\n \"\"\"\n mask = [np.ones(len(freqs[i]), dtype=bool) for i in range(len(freqs))]\n for j in range(len(freqs)-1):\n freqsj = np.asarray(freqs[j])\n for m in range(len(freqsj)):\n freq1 = freqsj[m]\n nn = len(freqs) if nextfs == 0 else j+1+nextfs\n if nn > len(freqs):\n nn = len(freqs)\n for k in range(j+1, nn):\n freqsk = np.asarray(freqs[k])\n if len(freqsk) == 0:\n continue\n n = np.argmin(np.abs(freqsk[:,0] - freq1[0]))\n freq2 = freqsk[n]\n if np.argmin(np.abs(freqsj[:,0] - freq2[0])) != m:\n continue\n if np.abs(freq1[0] - freq2[0]) < df_thresh:\n if freq1[1] > freq2[1]:\n mask[k][n] = False\n elif freq1[1] < freq2[1]:\n mask[j][m] = False\n elif len(freq1) > 2:\n if freq1[2] > freq2[2]:\n mask[k][n] = False\n else:\n mask[j][m] = False\n else:\n mask[j][m] = False\n return mask\n\n\ndef unique(freqs, df_thresh, mode='power', nextfs=0):\n \"\"\" Remove similar frequencies from different recordings.\n\n If two frequencies from different elements in the inner lists of `freqs`\n are reciprocally the closest to each other and closer than `df_thresh`,\n then the one with the smaller power is removed. As power, either the\n absolute power as provided in the second column of the data elements\n in `freqs` is taken (mode=='power'), or the relative power\n (mode='relpower'), or the power rank (mode='rank').\n\n Parameters\n ----------\n freqs: (list of (list of ...)) list of 2D ndarrays\n First column in the ndarrays is fundamental frequency and\n second column the corresponding power, as returned by\n fundamental_freqs_and_power().\n df_thresh: float\n Fundamental frequencies closer than this threshold are considered\n equal.\n mode: string\n - 'power': use second column of freqs elements as power.\n - 'relpower': use relative power computed from the second column\n of freqs elements for deciding which frequency to delete.\n - 'rank': use rank of second column of freqs elements\n for deciding which frequency to delete.\n nextfs: int\n If zero, compare all elements in freqs with each other. Otherwise,\n only compare with the `nextfs` next elements in freqs.\n\n Returns\n -------\n uniqe_freqs: (list of (list of ...)) list of 2D ndarrays\n Same as `freqs` but elements with similar fundamental frequencies\n removed.\n \"\"\"\n if len(freqs) == 0:\n return []\n \n # check whether freqs is list of fundamental frequencies and powers:\n list_of_freq_power = True\n for group in freqs:\n if not (hasattr(group, 'shape') and len(group.shape) == 2):\n list_of_freq_power = False\n break\n\n if list_of_freq_power:\n if mode == 'power':\n mask = unique_mask(freqs, df_thresh, nextfs)\n elif mode == 'relpower':\n power_freqs = [f[:,[0, 2, 1]] for f in add_relative_power(freqs)]\n mask = unique_mask(power_freqs, df_thresh, nextfs)\n elif mode == 'rank':\n rank_freqs = [f[:,[0, 2, 1]] for f in add_power_ranks(freqs)]\n mask = unique_mask(rank_freqs, df_thresh, nextfs)\n else:\n raise ValueError('%s is not a valid mode for unique(). Choose one of \"power\" or \"rank\"')\n unique_freqs = []\n for f, m in zip(freqs, mask):\n unique_freqs.append(f[m])\n else:\n unique_freqs = []\n for groups in freqs:\n unique_freqs.append(unique(groups, df_thresh, mode, nextfs))\n return unique_freqs\n\n\ndef colors_markers():\n \"\"\"\n Generate a list of colors and markers for plotting.\n\n Returns\n -------\n colors: list\n list of colors\n markers: list\n list of markers\n \"\"\"\n # color and marker range:\n colors = []\n markers = []\n mr2 = []\n # first color range:\n cc0 = cm.gist_rainbow(np.linspace(0.0, 1.0, 8.0))\n # shuffle it:\n for k in range((len(cc0) + 1) // 2):\n colors.extend(cc0[k::(len(cc0) + 1) // 2])\n markers.extend(len(cc0) * 'o')\n mr2.extend(len(cc0) * 'v')\n # second darker color range:\n cc1 = cm.gist_rainbow(np.linspace(0.33 / 7.0, 1.0, 7.0))\n cc1 = mc.hsv_to_rgb(mc.rgb_to_hsv(np.array([cc1[:, :3]])) * np.array([1.0, 0.9, 0.7]))[0]\n cc1 = np.hstack((cc1, np.ones((len(cc1),1))))\n # shuffle it:\n for k in range((len(cc1) + 1) // 2):\n colors.extend(cc1[k::(len(cc1) + 1) // 2])\n markers.extend(len(cc1) * '^')\n mr2.extend(len(cc1) * '*')\n # third lighter color range:\n cc2 = cm.gist_rainbow(np.linspace(0.67 / 6.0, 1.0, 6.0))\n cc2 = mc.hsv_to_rgb(mc.rgb_to_hsv(np.array([cc1[:, :3]])) * np.array([1.0, 0.5, 1.0]))[0]\n cc2 = np.hstack((cc2, np.ones((len(cc2),1))))\n # shuffle it:\n for k in range((len(cc2) + 1) // 2):\n colors.extend(cc2[k::(len(cc2) + 1) // 2])\n markers.extend(len(cc2) * 'D')\n mr2.extend(len(cc2) * 'x')\n markers.extend(mr2)\n return colors, markers\n\n\ndef plot_harmonic_groups(ax, group_list, max_freq=2000.0, max_groups=0,\n sort_by_freq=True, label_power=False,\n colors=None, markers=None, legend_rows=8, **kwargs):\n \"\"\"\n Mark decibel power of fundamentals and their harmonics in a plot.\n\n Parameters\n ----------\n ax: axis for plot\n Axis used for plotting.\n group_list: list of 2-D arrays\n Lists of harmonic groups as returned by extract_fundamentals() and\n harmonic_groups() with the element [0, 0] of the harmonic groups being the fundamental frequency,\n and element[0, 1] being the corresponding power.\n max_freq: float\n If greater than zero only mark peaks below this frequency.\n max_groups: int\n If not zero plot only the max_groups most powerful groups.\n sort_by_freq: boolean\n If True sort legend by frequency, otherwise by power.\n label_power: boolean\n If `True` put the power in decibel in addition to the frequency into the legend.\n colors: list of colors or None\n If not None list of colors for plotting each group\n markers: list of markers or None\n If not None list of markers for plotting each group\n legend_rows: int\n Maximum number of rows to be used for the legend.\n kwargs: \n Key word arguments for the legend of the plot.\n \"\"\"\n\n if len(group_list) == 0:\n return\n \n # sort by power:\n powers = np.array([np.sum(group[:,1]) for group in group_list])\n max_power = np.max(powers)\n power_idx = np.argsort(powers)\n if max_groups > 0 and len(power_idx > max_groups):\n power_idx = power_idx[-max_groups:]\n idx = np.array(list(reversed(power_idx)))\n\n # sort by frequency:\n if sort_by_freq:\n freqs = [group_list[group][0, 0] for group in idx]\n if legend_rows > 0 and legend_rows < len(freqs):\n idx[:legend_rows] = idx[np.argsort(freqs[:legend_rows])]\n else:\n idx = idx[np.argsort(freqs)]\n\n # plot:\n for k, i in enumerate(idx):\n group = group_list[i]\n x = np.array([harmonic[0] for harmonic in group])\n y = np.array([harmonic[1] for harmonic in group])\n if max_freq > 0.0:\n y = y[x<=max_freq]\n x = x[x<=max_freq]\n msize = 7.0 + 10.0*(powers[i]/max_power)**0.25\n color_kwargs = {}\n if colors is not None:\n color_kwargs = {'color': colors[k%len(colors)]}\n label = '%6.1f Hz' % group[0, 0]\n if label_power:\n label += ' %6.1f dB' % decibel(np.array([np.sum(group[:,1])]))[0]\n if legend_rows > 5 and k >= legend_rows:\n label = None\n if markers is None:\n ax.plot(x, decibel(y), 'o', ms=msize, label=label,\n clip_on=False, **color_kwargs)\n else:\n if k >= len(markers):\n break\n ax.plot(x, decibel(y), linestyle='None', marker=markers[k],\n mec=None, mew=0.0, ms=msize, label=label,\n clip_on=False, **color_kwargs)\n\n # legend:\n if legend_rows > 0:\n if legend_rows > 5:\n ncol = 1\n else:\n ncol = (len(idx)-1) // legend_rows + 1\n leg = ax.legend(numpoints=1, ncol=ncol, **kwargs)\n else:\n leg = ax.legend(numpoints=1, **kwargs)\n\n\ndef plot_psd_harmonic_groups(ax, psd_freqs, psd, group_list, mains=None, all_freqs=None, good_freqs=None,\n max_freq=2000.0):\n \"\"\"\n Plot decibel power-spectrum with detected peaks, harmonic groups, and mains frequencies.\n \n Parameters:\n -----------\n psd_freqs: array\n Frequencies of the power spectrum.\n psd: array\n Power spectrum (linear, not decible).\n group_list: list of 2-D arrays\n Lists of harmonic groups as returned by extract_fundamentals() and\n harmonic_groups() with the element [0, 0] of the harmonic groups being the fundamental frequency,\n and element[0, 1] being the corresponding power.\n mains: 2-D array\n Frequencies and power of multiples of the mains frequency found in the power spectrum.\n all_freqs: 2-D array\n Peaks in the power spectrum detected with low threshold.\n good_freqs: 1-D array\n Frequencies of peaks detected with high threshold.\n max_freq: float\n Limits of frequency axis are set to (0, max_freq) if max_freq is greater than zero.\n \"\"\"\n \n # mark all and good psd peaks:\n pmin, pmax = ax.get_ylim()\n doty = pmax - 5.0\n if all_freqs is not None:\n ax.plot(all_freqs[:, 0], np.zeros(len(all_freqs[:, 0])) + doty, 'o', color='#ffffff')\n if good_freqs is not None:\n ax.plot(good_freqs, np.zeros(len(good_freqs)) + doty, 'o', color='#888888')\n # mark mains frequencies:\n if mains is not None and len(mains) > 0:\n fpeaks = mains[:, 0]\n fpeakinx = [int(np.round(fp/(psd_freqs[1]-psd_freqs[0]))) for fp in fpeaks if fp < psd_freqs[-1]]\n ax.plot(fpeaks[:len(fpeakinx)], decibel(psd[fpeakinx]), linestyle='None',\n marker='.', color='k', ms=10, mec=None, mew=0.0,\n label='%3.0f Hz mains' % mains[0, 0])\n # mark harmonic groups:\n colors, markers = colors_markers()\n plot_harmonic_groups(ax, group_list, max_freq=max_freq, max_groups=0, sort_by_freq=True,\n colors=colors, markers=markers, legend_rows=8,\n loc='upper right')\n # plot power spectrum:\n plot_decibel_psd(ax, psd_freqs, psd, max_freq=max_freq, color='blue')\n\n \ndef add_psd_peak_detection_config(cfg, low_threshold=0.0, high_threshold=0.0,\n thresh_bins=100,\n low_thresh_factor=6.0, high_thresh_factor=10.0):\n \"\"\" Add parameter needed for detection of peaks in power spectrum used by\n harmonic_groups() as a new section to a configuration.\n\n Parameters\n ----------\n cfg: ConfigFile\n The configuration.\n \"\"\"\n\n cfg.add_section('Thresholds for peak detection in power spectra:')\n cfg.add('lowThreshold', low_threshold, 'dB', 'Threshold for all peaks.\\n If 0.0 estimate threshold from histogram.')\n cfg.add('highThreshold', high_threshold, 'dB', 'Threshold for good peaks. If 0.0 estimate threshold from histogram.')\n \n cfg.add_section('Threshold estimation:\\nIf no thresholds are specified they are estimated from the histogram of the decibel power spectrum.')\n cfg.add('thresholdBins', thresh_bins, '', 'Number of bins used to compute the histogram used for threshold estimation.')\n cfg.add('lowThresholdFactor', low_thresh_factor, '', 'Factor for multiplying standard deviation of noise floor for lower threshold.')\n cfg.add('highThresholdFactor', high_thresh_factor, '', 'Factor for multiplying standard deviation of noise floor for higher threshold.')\n\n\ndef psd_peak_detection_args(cfg):\n \"\"\" Translates a configuration to the respective parameter names for the\n detection of peaks in power spectrum used by harmonic_groups().\n The return value can then be passed as key-word arguments to this function.\n\n Parameters\n ----------\n cfg: ConfigFile\n The configuration.\n\n Returns\n -------\n a: dict\n Dictionary with names of arguments of the `harmonic-group()` function\n and their values as supplied by `cfg`.\n \"\"\"\n return cfg.map({'low_threshold': 'lowThreshold',\n 'high_threshold': 'highThreshold',\n 'thresh_bins': 'thresholdBins',\n 'low_thresh_factor': 'lowThresholdFactor',\n 'high_thresh_factor': 'highThresholdFactor'})\n\n\ndef add_harmonic_groups_config(cfg, mains_freq=60.0, mains_freq_tol=1.0,\n max_divisor=4, freq_tol_fac=1.0,\n min_group_size=4, min_freq=20.0, max_freq=2000.0,\n max_rel_power_weight=2.0, max_rel_power=0.0,\n max_harmonics=0, max_groups=0):\n \"\"\" Add parameter needed for detection of harmonic groups as\n a new section to a configuration.\n\n Parameters\n ----------\n cfg: ConfigFile\n The configuration.\n \"\"\"\n \n cfg.add_section('Harmonic groups:')\n cfg.add('mainsFreq', mains_freq, 'Hz', 'Mains frequency to be excluded.')\n cfg.add('mainsFreqTolerance', mains_freq_tol, 'Hz', 'Exclude peaks within this tolerance around multiples of the mains frequency.')\n cfg.add('minimumGroupSize', min_group_size, '',\n'The number of harmonics (inclusively fundamental) that are allowed do be filled in.')\n cfg.add('maxDivisor', max_divisor, '', 'Maximum ratio between the frequency of the largest peak and its fundamental')\n cfg.add('freqTolerance', freq_tol_fac, '',\n 'Harmonics need be within this factor times the frequency resolution of the power spectrum. Needs to be higher than 0.5!')\n \n cfg.add_section('Acceptance of best harmonic groups:')\n cfg.add('minimumFrequency', min_freq, 'Hz', 'Minimum frequency allowed for the fundamental.')\n cfg.add('maximumFrequency', max_freq, 'Hz', 'Maximum frequency allowed for the fundamental.')\n cfg.add('maxRelativePowerWeight', max_rel_power_weight, '', 'Maximum value of the power of the minimumGroupSize harmonics relative to fundamental used for punishing overall power of a harmonic group.')\n cfg.add('maxRelativePower', max_rel_power, '', 'Maximum allowed power of the minimumGroupSize harmonics relative to fundamental. If zero do not check for relative power.')\n cfg.add('maxHarmonics', max_harmonics, '', '0: keep all, >0 only keep the first # harmonics.')\n cfg.add('maxGroups', max_groups, '', 'Maximum number of harmonic groups. If 0 process all.')\n\n\ndef harmonic_groups_args(cfg):\n \"\"\" Translates a configuration to the\n respective parameter names of the harmonic-group detection functions.\n The return value can then be passed as key-word arguments to this function.\n\n Parameters\n ----------\n cfg: ConfigFile\n The configuration.\n\n Returns\n -------\n a: dict\n Dictionary with names of arguments of the harmonic-group detection functions\n and their values as supplied by `cfg`.\n \"\"\"\n return cfg.map({'mains_freq': 'mainsFreq',\n 'mains_freq_tol': 'mainsFreqTolerance',\n 'freq_tol_fac': 'freqTolerance',\n 'max_divisor': 'maxDivisor',\n 'min_group_size': 'minimumGroupSize',\n 'min_freq': 'minimumFrequency',\n 'max_freq': 'maximumFrequency',\n 'max_rel_power_weight': 'maxRelativePowerWeight',\n 'max_rel_power': 'maxRelativePower',\n 'max_harmonics': 'maxHarmonics',\n 'max_groups': 'maxGroups'})\n\n\nif __name__ == \"__main__\":\n import sys\n import matplotlib.pyplot as plt\n from .fakefish import generate_wavefish\n from .powerspectrum import psd\n\n if len(sys.argv) < 2:\n # generate data:\n title = 'simulation'\n samplerate = 44100.0\n eodfs = [123.0, 333.0, 666.0, 666.5]\n fish1 = generate_wavefish(eodfs[0], samplerate, duration=8.0, noise_std=0.01,\n amplitudes=[0.5, 0.7, 0.3, 0.1, 0.05], phases=[0.0, 0.0, 0.0, 0.0, 0.0])\n fish2 = generate_wavefish(eodfs[1], samplerate, duration=8.0, noise_std=0.01,\n amplitudes=[1.0, 0.5, 0.2, 0.1], phases=[0.0, 0.0, 0.0, 0.0])\n fish3 = generate_wavefish(eodfs[2], samplerate, duration=8.0, noise_std=0.01,\n amplitudes=[10.0, 5.0, 2.0, 0.2], phases=[0.0, 0.0, 0.0, 0.0])\n fish4 = generate_wavefish(eodfs[3], samplerate, duration=8.0, noise_std=0.01,\n amplitudes=[6.0, 3.0, 1.2, 0.3], phases=[0.0, 0.0, 0.0, 0.0])\n data = fish1 + fish2 + fish3 + fish4\n else:\n from .dataloader import load_data\n print(\"load %s ...\" % sys.argv[1])\n data, samplerate, unit = load_data(sys.argv[1], 0)\n title = sys.argv[1]\n\n # retrieve fundamentals from power spectrum:\n psd_data = psd(data, samplerate, freq_resolution=0.5)\n def call_harm():\n harmonic_groups(psd_data[0], psd_data[1], max_divisor=4)\n import timeit\n n = 50\n #print(timeit.timeit(call_harm, number=n)/n)\n groups, _, mains, all_freqs, good_freqs, _, _, _ = harmonic_groups(psd_data[0], psd_data[1], verbose=0, check_freqs=[123.0, 666.0])\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1)\n plot_psd_harmonic_groups(ax, psd_data[0], psd_data[1], groups, mains, all_freqs, good_freqs,\n max_freq=3000.0)\n ax.set_title(title)\n plt.show()\n #exit()\n # unify fundamental frequencies:\n fundamentals = fundamental_freqs(groups)\n np.set_printoptions(formatter={'float': lambda x: '%5.1f' % x})\n print('fundamental frequencies extracted from power spectrum:')\n print(fundamentals)\n print('')\n freqs = fundamental_freqs_and_power([groups])\n freqs.append(np.array([[44.0, -20.0], [44.2, -10.0], [320.5, 2.5], [665.5, 5.0], [666.2, 10.0]]))\n freqs.append(np.array([[123.3, 1.0], [320.2, -2.0], [668.4, 2.0]]))\n rank_freqs = add_relative_power(freqs)\n rank_freqs = add_power_ranks(rank_freqs)\n print('all frequencies (frequency, power, relpower, rank):')\n print('\\n'.join(( str(f) for f in rank_freqs)))\n print('')\n indices = similar_indices(freqs, 1.0)\n print('similar indices:')\n print('\\n'.join(( ('\\n '.join((str(f) for f in g)) for g in indices))))\n print('')\n unique_freqs = unique(freqs, 1.0, 'power')\n print('unique power:')\n print('\\n'.join(( str(f) for f in unique_freqs)))\n print('')\n unique_freqs = unique(freqs, 1.0, 'relpower')\n print('unique relative power:')\n print('\\n'.join(( str(f) for f in unique_freqs)))\n print('')\n unique_freqs = unique(freqs, 1.0, 'rank')\n print('unique rank:')\n print('\\n'.join(( str(f) for f in unique_freqs)))\n print('')\n unique_freqs = unique(freqs, 1.0, 'rank', 1)\n print('unique rank for next neighor only:')\n print('\\n'.join(( str(f) for f in unique_freqs)))\n print('')\n","sub_path":"thunderfish/harmonics.py","file_name":"harmonics.py","file_ext":"py","file_size_in_byte":71028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"348469242","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.figure import Figure\n\n\nx = np.linspace(0,5,100)\n\nplt.xlabel('X')\nplt.ylabel('Y')\nplt.xlim(0, 5)\nplt.ylim(-.2, .5)\n\nplt.plot(x, x**4 * np.exp(-2*x), color='red', label='first')\nplt.plot(x, (x**2 * np.exp(-x) * np.sin(x**2))**2, color='black', label='second')\nplt.legend(loc='upper right')\n\nfigure = Figure(figsize=(6, 5))\nplt.show()\n","sub_path":"0-0.py","file_name":"0-0.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"5822024","text":"import re\nimport torch\nimport logging\nimport numpy as np\nfrom collections import defaultdict\nimport numpy as np\nfrom torch.utils.data import Dataset\n\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')\n\n\nclass smallDataSet(Dataset):\n def __init__(self, inDir):\n self.inDir = inDir\n self.headRelation2Tail = defaultdict(lambda: defaultdict(set))\n self.tailRelation2Head = defaultdict(lambda: defaultdict(set))\n \n self.readTrainTriples()\n self.readEntityNumber()\n self.readRelationNumber()\n \n def __len__(self):\n return self.numOfTriple\n\n def __getitem__(self, item):\n return self.trainTriples[item]\n \n def readTrainTriples(self):\n logging.info (\"-----Reading train tiples from \" + self.inDir + \"/-----\")\n inputData = np.load(self.inDir + \"/train_triples.npy\")\n logging.info(inputData.shape)\n logging.info(\"Data loading complete\")\n \n for count, (head, tail, rel) in enumerate(inputData):\n self.headRelation2Tail[head][rel].add(tail)\n self.tailRelation2Head[tail][rel].add(head)\n logging.info(\"Making count dict complete\")\n \n self.numOfTriple = len(inputData)\n self.trainTriples = torch.LongTensor(inputData)\n\n \n\n def readEntityNumber(self):\n logging.info (\"-----Reading entity2id.txt from \" + self.inDir + \"/-----\")\n inputData = open(self.inDir + \"/entity2id.txt\")\n line = inputData.readline()\n self.numOfEntity = int(re.findall(r\"\\d+\", line)[0])\n \n return\n \n def readRelationNumber(self):\n logging.info (\"-----Reading relation2id.txt from \" + self.inDir + \"/-----\")\n inputData = open(self.inDir + \"/relation2id.txt\")\n line = inputData.readline()\n self.numOfRelation = int(re.findall(r\"\\d+\", line)[0])\n inputData.close()\n \n return \n \n def generateCorruptedBatch(self, batch):\n corruptedBatch = []\n for head, tail, rel in batch:\n head = head.item()\n rel = rel.item()\n tail = tail.item()\n \n if torch.rand(1).item() >= 0.5:\n not_list = self.tailRelation2Head[tail][rel].union(set([head]))\n while True:\n CorruptedHead = torch.FloatTensor(1).uniform_(0, self.numOfEntity).long().item()\n if CorruptedHead not in not_list:\n head = CorruptedHead\n break\n else:\n not_list = self.headRelation2Tail[head][rel].union(set([tail]))\n while True:\n CorruptedTail = torch.FloatTensor(1).uniform_(0, self.numOfEntity).long().item()\n if CorruptedTail not in not_list:\n tail = CorruptedTail\n break\n \n corruptedBatch.append([head, tail, rel])\n \n\n corruptedBatch = torch.LongTensor(corruptedBatch)\n \n return corruptedBatch\n \n \n \n \n ","sub_path":"readTrainingData.py","file_name":"readTrainingData.py","file_ext":"py","file_size_in_byte":3131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"486965345","text":"# -*- coding: utf-8 -*-\nimport logging\nlog = logging.getLogger('payments.sagepay.forms')\nfrom django import forms\nfrom django.conf import settings\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.sites.models import Site\nfrom livesettings import config_value\nfrom unicode2ascii import latin1_to_ascii as hammer\nfrom payment import ProtxPaymentRequest\nfrom cc.shop.models import Order\nfrom cc.conf import coresettings\n\nclass ProtxVSPForm(forms.Form):\n #\n protx = ProtxPaymentRequest()\n url = ProtxPaymentRequest().url()\n #\n VPSProtocol = forms.CharField(initial=\"2.23\", widget=forms.HiddenInput)\n TxType = forms.CharField(initial=coresettings.SAGEPAY_PAYMENT_TYPE, widget=forms.HiddenInput)\n Vendor = forms.CharField(initial=ProtxPaymentRequest().vendorname(), widget=forms.HiddenInput)\n crypt = forms.CharField(widget=forms.HiddenInput)\n \n def __init__(self, customer, address, postage_method, basket_lines, order, *args, **kwargs):\n #\n #\n #\n billing_address = kwargs.pop('billing_address') or address\n #\n # hack the basket into the mix\n basket = kwargs.pop('basket')\n # \n #\n #\n #\n super(ProtxVSPForm, self).__init__(*args, **kwargs)\n # refresh it\n self.protx.__init__()\n # set the urls\n # SSL\n #\n if coresettings.SAGEPAY_SSL:\n protocol = 'https://'\n else:\n protocol = 'http://'\n self.protx.fields['SuccessURL'] = '%s%s%s' % ( protocol, Site.objects.get_current(), reverse('shop_payments_sagepay_success'))\n self.protx.fields['FailureURL'] = '%s%s%s' % ( protocol, Site.objects.get_current(), reverse('shop_payments_sagepay_failure'))\n # about the order\n self.protx.fields['Amount'] = order.total\n self.protx.fields['Description'] = 'Goods purchased online from %s' % config_value('CONTACT', 'COMPANY')\n # basket\n self.protx.basket(basket_lines, postage_method, basket)\n # customer details\n self.protx.fields['CustomerName'] = customer.name\n self.protx.fields['CustomerEmail'] = customer.email\n self.protx.fields['ContactNumber'] = customer.phone\n # split the names\n name = surname = False\n names = customer.name.split(' ')\n if len(names) == 1:\n name = surname = names[0]\n else:\n name = names[0]\n surnames = names\n surnames.reverse()\n surname = surnames[0]\n # delivery & billing\n self.protx.fields['DeliverySurname'] = surname\n self.protx.fields['DeliveryFirstnames'] = name\n self.protx.fields['DeliveryAddress1'] = address.address1\n self.protx.fields['DeliveryAddress2'] = address.address2\n self.protx.fields['DeliveryCity'] = address.region\n self.protx.fields['DeliveryPostCode'] = address.postcode\n self.protx.fields['DeliveryCountry'] = address.country.country.iso\n self.protx.fields['DeliveryPhone'] = customer.phone\n self.protx.fields['BillingSurname'] = surname\n self.protx.fields['BillingFirstnames'] = name\n self.protx.fields['BillingAddress1'] = billing_address.address1\n self.protx.fields['BillingAddress2'] = billing_address.address2\n self.protx.fields['BillingCity'] = billing_address.region\n self.protx.fields['BillingPostCode'] = billing_address.postcode\n self.protx.fields['BillingCountry'] = billing_address.country.country.iso\n self.protx.fields['BillingPhone'] = customer.phone\n # now we can crypt it all\n self.fields[\"crypt\"].initial = self.protx.crypt()\n \n\n\n\n","sub_path":"cc/shop/payments/sagepay/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"376853968","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.2 (3180)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/livedesk/core/impl/icon_content.py\n# Compiled at: 2013-10-02 09:54:57\n\"\"\"\nCreated on August 19, 2013\n\n@package: livedesk-sync\n@copyright: 2013 Sourcefabric o.p.s.\n@license: http://www.gnu.org/licenses/gpl-3.0.txt\n@author: Martin Saturka\n\nContent for icons of collaborators of chained blogs.\n\"\"\"\nimport socket, logging\nfrom urllib.request import urlopen\nfrom ally.api.model import Content\nfrom urllib.error import HTTPError\nfrom ally.exception import InputError, Ref\nfrom ally.internationalization import _\nfrom urllib.request import Request\nfrom urllib.parse import quote, urlsplit, SplitResult, urlunsplit\nlog = logging.getLogger(__name__)\n\nclass ChainedIconContent(Content):\n \"\"\"\n Simple remote icon content taking\n \"\"\"\n __slots__ = ('_url', '_response')\n\n def __init__(self, contentURL, fileName):\n \"\"\"\n Initialize the content.\n\n @param contentURL: string\n The URL of the icon to be downloaded.\n @param fileName: string\n The name of file under that the icon should be saved.\n \"\"\"\n Content.__init__(self, fileName, 'image', 'binary', 0)\n parsed = urlsplit(contentURL if not isinstance(contentURL, Request) else contentURL.full_url)\n parsed = SplitResult(parsed.scheme, parsed.netloc, quote(parsed.path), quote(parsed.query), parsed.fragment)\n if isinstance(contentURL, Request):\n contentURL.full_url = urlunsplit(parsed)\n else:\n contentURL = urlunsplit(parsed)\n self._url = contentURL\n self._response = None\n return\n\n def read(self, nbytes=None):\n \"\"\"\n @see: Content.read\n \"\"\"\n if not self._response:\n try:\n self._response = urlopen(self._url)\n except (HTTPError, socket.error) as e:\n log.error('Can not read icon image data %s' % e)\n raise InputError(Ref(_('Can not open icon URL')))\n\n if not self._response:\n log.error('Can not read icon image data %s' % e)\n raise InputError(Ref(_('Can not open icon URL')))\n if str(self._response.status) != '200':\n raise InputError(Ref(_('Can not open icon URL')))\n self.type = self._response.getheader('Content-Type')\n if not self.type:\n self.type = 'image'\n self.length = self._response.getheader('Content-Length')\n if not self.length:\n self.length = 0\n if not self._response or self._response.closed:\n return ''\n try:\n if nbytes:\n return self._response.read(nbytes)\n else:\n return self._response.read()\n except (HTTPError, socket.error) as e:\n log.error('Can not read icon image data %s' % e)\n raise InputError(Ref(_('Can not read from icon URL')))\n\n def next(self):\n \"\"\"\n @see: Content.next\n \"\"\"\n return","sub_path":"pycfiles/liveblog-1.5.0-py3.2/icon_content.cpython-32.py","file_name":"icon_content.cpython-32.py","file_ext":"py","file_size_in_byte":3160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"410721224","text":"from socket import *\n\n# 1. 创建套接字\nsockfd = socket(AF_INET,SOCK_STREAM)\n\n# 2. 绑定服务端地址\nsockfd.bind(('0.0.0.0',8888)) # 元组\n\n# 3. 设置监听套接字\nsockfd.listen(5)\n\nwhile True:\n # 4. 等待处理客户端连接请求(等待接受连接)\n print('Waiting for connect...')\n connfd,addr = sockfd.accept() # 为每个客户端创建了一个新的套接字\n print('Connect from',addr)\n # 返回值: connfd 客户端连接套接字\n # addr 连接的客户端地址\n\n while True:\n # 5. 消息收发之接收\n data = connfd.recv(1024).decode() # 如果没有消息则会阻塞\n if not data:\n break\n print(data)\n # 5. 消息收发之发送 \n send_data = 'Received your message!'\n n = connfd.send(send_data.encode())#这个括号里若用b'...'的形式只能发送ascii字符\n print('发送了%d字节'%n)\n # 6. 关闭客户端连接套接字,关闭套接字\n connfd.close()\n\nsockfd.close()","sub_path":"pythonNet/tcp_server.py","file_name":"tcp_server.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"21501110","text":"import os\nfrom selenium import webdriver\nfrom tqdm import tqdm\nimport numpy as np\nimport PIL.Image as pilimg\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nfrom urllib import request\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torchvision.models as models\nimport torchvision.utils as utils\nimport torchvision.datasets as dset\nimport torchvision.transforms as transforms\nimport time\n\nclass AppURLopener(request.FancyURLopener):\n version = \"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.69 Safari/537.36\"\n\n\n\ndef download_imgs(urls):\n url_number = {}\n for i , url in enumerate(urls):\n try:\n savename = str(i) + \".png\"\n _urlopener = AppURLopener()\n _urlopener.retrieve(url, os.path.join('img/0',savename))\n url_number[i] = url\n # request.urlretrieve(url, os.path.join('img/0',savename))\n except Exception as e:\n print(url)\n print(e)\n pass\n return url_number\n\n\n\ndef test(test_data, model, device):\n result = []\n model.to(device)\n ephoc = 0\n index = 0\n for img_i , label_i in test_data:\n img_i , label_i = img_i.view(-1, 3, 224, 224).to(device) , label_i.view(-1)\n outputs = model(img_i)\n _, predicted = torch.max(outputs, 1)\n for i in range(0,len(predicted)):\n if (predicted[i]==0):\n print(img_i[i])\n result.append((ephoc , i))\n ephoc+=1\n\n return result\n\nif __name__ == \"__main__\":\n driver = webdriver.Chrome(r'C:\\Users\\hyeongy\\PycharmProjects\\AI_detect\\chromedriver.exe')\n driver.get('https://ko.chaturbate.com/?tour=LQps&disable_sound=0&join_overlay=1&campaign=pYoNZ&room=akdrh1234')\n #\n urls = []\n url_tag = {}\n imgs_tags = driver.find_elements_by_tag_name(\"img\")\n video_tags = driver.find_elements_by_tag_name(\"video\")\n #\n for i in imgs_tags:\n url = i.get_attribute('src')\n urls.append(url)\n url_tag[url] = i\n print(len(imgs_tags))\n\n\n url_number = download_imgs(urls)\n\n time.sleep(5)\n\n test_dataset = dset.ImageFolder(root=r\"./img\",\n transform=transforms.Compose([\n transforms.Scale(224),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5),\n (0.5, 0.5, 0.5)),\n ]))\n\n test_dataloader = torch.utils.data.DataLoader(test_dataset, batch_size=20,\n shuffle=False, )\n\n\n print(len(test_dataloader))\n\n\n PATH = r'./model/resnet5_224.pth'\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n model = models.resnet50()\n model.fc = nn.Linear(2048, 2)\n model.load_state_dict(torch.load(PATH))\n model.eval()\n result = test(test_dataloader, model, device) # test_data , model , device\n print(\" \")\n\n for i in result:\n ephoc = i[0]\n index = i[1]\n url_index = int(str(test_dataset.imgs[(ephoc*20)+index]).split('\\\\')[4].split(\".\")[0])\n driver.execute_script(\"arguments[0].src='http://203.246.112.137/static/a.jpg' \", url_tag[url_number[url_index]])\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"181685291","text":"# -*- conding:utf-8 -*-\n\n\"\"\" \n@author: Salted fish \n@file: modbus.py \n@time: 2019/01/12 \n\"\"\"\nimport modbus_tk.defines as cst\nimport modbus_tk.modbus_tcp as modbus_tcp\nimport config.config as config\nimport Utils\n\n\"\"\"\n获取配置文件\n\"\"\"\nconfigs = config.configs\nconnect_config = configs.MODBUS_SLAVE_CONNECT\n\n\ndef modbus_client():\n \"\"\"\n 连接从机\n :return:\n \"\"\"\n # 连接从机地址\n try:\n client = modbus_tcp.TcpMaster(connect_config.host, connect_config.port, configs.CONNECTION_TIMEOUT)\n except BaseException:\n Utils.log('连接从机失败 - ip:{ip},port:{port}'.format(ip = connect_config.host, port = connect_config.port), 'error')\n return client\n\n\nclient = modbus_client()\n\ndef get_keep_data(start_address, num):\n \"\"\"\n 保持寄存器数据\n :param start_address: 报文开始地址git\n :param num: 寄存器数量\n :return: tuple\n \"\"\"\n keep_data = ()\n Utils.log('获取保持寄存器数据 - 开始地址:{addr},寄存器数量:{num}'.format(addr = start_address, num = num))\n try:\n keep_data = client.execute(connect_config.slave_id, cst.READ_HOLDING_REGISTERS, start_address, num)\n except BaseException:\n Utils.log('modbusTCP获取保持寄存器数据失败 - 开始地址:{addr},寄存器数量:{num}'.format(addr = start_address, num = num), 'error')\n return keep_data\n\n\ndef get_digital_data(start_address, num):\n \"\"\"\n 数字量输入寄存器数据\n :param start_address: 报文开始地址\n :param num: 寄存器数量\n :return: tuple\n \"\"\"\n digital_data = ()\n Utils.log('获取数字量输入寄存器数据 - 开始地址:{addr},寄存器数量:{num}'.format(addr = start_address, num = num))\n try:\n digital_data = client.execute(connect_config.slave_id, cst.READ_DISCRETE_INPUTS, start_address, num)\n except BaseException:\n Utils.log('modbusTCP获取离散寄存器数据失败 - 开始地址:{addr},寄存器数量:{num}'.format(addr = start_address, num = num), 'error')\n return digital_data\n","sub_path":"tb-gateway1/modbus/modbus.py","file_name":"modbus.py","file_ext":"py","file_size_in_byte":2108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"456270574","text":"# -------------------------------------------------------------\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. 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,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n# -------------------------------------------------------------\n\n__all__ = [\"SystemDSContext\"]\n\nimport copy\nimport os\nimport socket\nimport time\nfrom glob import glob\nfrom queue import Empty, Queue\nfrom subprocess import PIPE, Popen\nfrom threading import Lock, Thread\nfrom time import sleep\nfrom typing import Dict, Iterable, Sequence, Tuple, Union\n\nimport numpy as np\nfrom py4j.java_gateway import GatewayParameters, JavaGateway\nfrom py4j.protocol import Py4JNetworkError\nfrom systemds.operator import OperationNode\nfrom systemds.script_building import OutputType\nfrom systemds.utils.consts import VALID_INPUT_TYPES\nfrom systemds.utils.helpers import get_module_dir\n\n\nclass SystemDSContext(object):\n \"\"\"A context with a connection to a java instance with which SystemDS operations are executed. \n The java process is started and is running using a random tcp port for instruction parsing.\"\"\"\n\n java_gateway: JavaGateway\n __stdout: Queue\n __stderr: Queue\n\n def __init__(self):\n \"\"\"Starts a new instance of SystemDSContext, in which the connection to a JVM systemds instance is handled\n Any new instance of this SystemDS Context, would start a separate new JVM.\n\n Standard out and standard error form the JVM is also handled in this class, filling up Queues,\n that can be read from to get the printed statements from the JVM.\n \"\"\"\n command = self.__build_startup_command()\n # TODO add an argument parser here\n port = self.__get_open_port()\n command.append(str(port))\n\n process = self.__try_startup(command)\n\n # Handle Std out from the subprocess.\n self.__stdout = Queue()\n self.__stderr = Queue()\n\n Thread(target=self.__enqueue_output, args=(\n process.stdout, self.__stdout), daemon=True).start()\n Thread(target=self.__enqueue_output, args=(\n process.stderr, self.__stderr), daemon=True).start()\n\n # Py4j connect to the started process.\n gwp = GatewayParameters(port=port, eager_load=True)\n self.java_gateway = JavaGateway(\n gateway_parameters=gwp, java_process=process)\n\n def get_stdout(self, lines: int = -1):\n \"\"\"Getter for the stdout of the java subprocess\n The output is taken from the stdout queue and returned in a new list.\n :param lines: The number of lines to try to read from the stdout queue.\n default -1 prints all current lines in the queue.\n \"\"\"\n if lines == -1 or self.__stdout.qsize() < lines:\n return [self.__stdout.get() for x in range(self.__stdout.qsize())]\n else:\n return [self.__stdout.get() for x in range(lines)]\n\n def get_stderr(self, lines: int = -1):\n \"\"\"Getter for the stderr of the java subprocess\n The output is taken from the stderr queue and returned in a new list.\n :param lines: The number of lines to try to read from the stderr queue.\n default -1 prints all current lines in the queue.\n \"\"\"\n if lines == -1 or self.__stderr.qsize() < lines:\n return [self.__stderr.get() for x in range(self.__stderr.qsize())]\n else:\n return [self.__stderr.get() for x in range(lines)]\n\n def exception_and_close(self, e):\n \"\"\"\n Method for printing exception, printing stdout and error, while also closing the context correctly.\n \"\"\"\n # e = sys.exc_info()[0]\n print(\"Exception Encountered! closing JVM\")\n print(\"standard out:\")\n [print(x) for x in self.get_stdout()]\n print(\"standard error\")\n [print(x) for x in self.get_stderr()]\n print(\"exception\")\n print(e)\n self.close()\n\n\n def __try_startup(self, command, rep = 0):\n try:\n process = Popen(command, stdout=PIPE, stdin=PIPE, stderr=PIPE)\n self.__verify_startup(process)\n return process\n except Exception as e:\n if rep > 3: \n raise Exception(\"Failed to start SystemDS context with \" + rep + \" repeated tries\")\n else:\n rep += 1\n print(\"Failed to startup JVM process, retrying: \" + rep)\n sleep(rep) # Sleeping increasingly long time, maybe this helps.\n return self.__try_startup(command, rep)\n\n def __verify_startup(self, process):\n first_stdout = process.stdout.readline()\n if(not b\"GatewayServer Started\" in first_stdout):\n stderr = process.stderr.readline().decode(\"utf-8\")\n if(len(stderr) > 1):\n raise Exception(\n \"Exception in startup of GatewayServer: \" + stderr)\n outputs = []\n outputs.append(first_stdout.decode(\"utf-8\"))\n max_tries = 10\n for i in range(max_tries):\n next_line = process.stdout.readline()\n if(b\"GatewayServer Started\" in next_line):\n print(\"WARNING: Stdout corrupted by prints: \" + str(outputs))\n print(\"Startup success\")\n break\n else:\n outputs.append(next_line)\n\n if (i == max_tries-1):\n raise Exception(\"Error in startup of systemDS gateway process: \\n gateway StdOut: \" + str(\n outputs) + \" \\n gateway StdErr\" + process.stderr.readline().decode(\"utf-8\"))\n\n def __build_startup_command(self):\n\n command = [\"java\", \"-cp\"]\n root = os.environ.get(\"SYSTEMDS_ROOT\")\n if root == None:\n # If there is no systemds install default to use the PIP packaged java files.\n root = os.path.join(get_module_dir(), \"systemds-java\")\n\n # nt means its Windows\n cp_separator = \";\" if os.name == \"nt\" else \":\"\n\n if os.environ.get(\"SYSTEMDS_ROOT\") != None:\n lib_cp = os.path.join(root, \"target\", \"lib\", \"*\")\n systemds_cp = os.path.join(root, \"target\", \"SystemDS.jar\")\n classpath = cp_separator.join([lib_cp, systemds_cp])\n\n command.append(classpath)\n files = glob(os.path.join(root, \"conf\", \"log4j*.properties\"))\n if len(files) > 1:\n print(\n \"WARNING: Multiple logging files found selecting: \" + files[0])\n if len(files) == 0:\n print(\"WARNING: No log4j file found at: \"\n + os.path.join(root, \"conf\")\n + \" therefore using default settings\")\n else:\n command.append(\"-Dlog4j.configuration=file:\" + files[0])\n else:\n lib_cp = os.path.join(root, \"lib\", \"*\")\n command.append(lib_cp)\n\n command.append(\"org.apache.sysds.api.PythonDMLScript\")\n\n return command\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.close()\n # no errors to handle to allow continuation\n return None\n\n def close(self):\n \"\"\"Close the connection to the java process and do necessary cleanup.\"\"\"\n process: Popen = self.java_gateway.java_process\n self.java_gateway.shutdown()\n # Send SigTerm\n os.kill(process.pid, 14)\n\n def __enqueue_output(self, out, queue):\n \"\"\"Method for handling the output from java.\n It is locating the string handeling inside a different thread, since the 'out.readline' is a blocking command.\n \"\"\"\n for line in iter(out.readline, b\"\"):\n queue.put(line.decode(\"utf-8\").strip())\n\n def __get_open_port(self):\n \"\"\"Get a random available port.\n and hope that no other process steals it while we wait for the JVM to startup\n \"\"\"\n # https://stackoverflow.com/questions/2838244/get-open-tcp-port-in-python\n\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.bind((\"\", 0))\n s.listen(1)\n port = s.getsockname()[1]\n s.close()\n return port\n\n def full(self, shape: Tuple[int, int], value: Union[float, int]) -> 'OperationNode':\n \"\"\"Generates a matrix completely filled with a value\n\n :param sds_context: SystemDS context\n :param shape: shape (rows and cols) of the matrix TODO tensor\n :param value: the value to fill all cells with\n :return: the OperationNode representing this operation\n \"\"\"\n unnamed_input_nodes = [value]\n named_input_nodes = {'rows': shape[0], 'cols': shape[1]}\n return OperationNode(self, 'matrix', unnamed_input_nodes, named_input_nodes)\n\n def seq(self, start: Union[float, int], stop: Union[float, int] = None,\n step: Union[float, int] = 1) -> 'OperationNode':\n \"\"\"Create a single column vector with values from `start` to `stop` and an increment of `step`.\n If no stop is defined and only one parameter is given, then start will be 0 and the parameter will be interpreted as\n stop.\n\n :param sds_context: SystemDS context\n :param start: the starting value\n :param stop: the maximum value\n :param step: the step size\n :return: the OperationNode representing this operation\n \"\"\"\n if stop is None:\n stop = start\n start = 0\n unnamed_input_nodes = [start, stop, step]\n return OperationNode(self, 'seq', unnamed_input_nodes)\n\n def rand(self, rows: int, cols: int,\n min: Union[float, int] = None, max: Union[float, int] = None, pdf: str = \"uniform\",\n sparsity: Union[float, int] = None, seed: Union[float, int] = None,\n lambd: Union[float, int] = 1) -> 'OperationNode':\n \"\"\"Generates a matrix filled with random values\n\n :param sds_context: SystemDS context\n :param rows: number of rows\n :param cols: number of cols\n :param min: min value for cells\n :param max: max value for cells\n :param pdf: \"uniform\"/\"normal\"/\"poison\" distribution\n :param sparsity: fraction of non-zero cells\n :param seed: random seed\n :param lambd: lamda value for \"poison\" distribution\n :return:\n \"\"\"\n available_pdfs = [\"uniform\", \"normal\", \"poisson\"]\n if rows < 0:\n raise ValueError(\"In rand statement, can only assign rows a long (integer) value >= 0 \"\n \"-- attempted to assign value: {r}\".format(r=rows))\n if cols < 0:\n raise ValueError(\"In rand statement, can only assign cols a long (integer) value >= 0 \"\n \"-- attempted to assign value: {c}\".format(c=cols))\n if pdf not in available_pdfs:\n raise ValueError(\"The pdf passed is invalid! given: {g}, expected: {e}\".format(\n g=pdf, e=available_pdfs))\n\n pdf = '\\\"' + pdf + '\\\"'\n named_input_nodes = {\n 'rows': rows, 'cols': cols, 'pdf': pdf, 'lambda': lambd}\n if min is not None:\n named_input_nodes['min'] = min\n if max is not None:\n named_input_nodes['max'] = max\n if sparsity is not None:\n named_input_nodes['sparsity'] = sparsity\n if seed is not None:\n named_input_nodes['seed'] = seed\n\n return OperationNode(self, 'rand', [], named_input_nodes=named_input_nodes)\n\n def read(self, path: os.PathLike, **kwargs: Dict[str, VALID_INPUT_TYPES]) -> 'OperationNode':\n \"\"\" Read an file from disk. Supportted types include:\n CSV, Matrix Market(coordinate), Text(i,j,v), SystemDS Binay\n See: http://apache.github.io/systemds/site/dml-language-reference#readwrite-built-in-functions for more details\n :return: an Operation Node, containing the read data.\n \"\"\"\n return OperationNode(self, 'read', [f'\"{path}\"'], named_input_nodes=kwargs, shape=(-1,))\n\n def scalar(self, v: Dict[str, VALID_INPUT_TYPES]) -> 'OperationNode':\n \"\"\" Construct an scalar value, this can contain str, float, double, integers and booleans.\n :return: An `OperationNode` containing the scalar value.\n \"\"\"\n if type(v) is str:\n if not ((v[0] == '\"' and v[-1] == '\"') or (v[0] == \"'\" and v[-1] == \"'\")):\n v = f'\"{v}\"'\n # output type assign simply assigns the given variable to the value\n # therefore the output type is assign.\n return OperationNode(self, v, output_type=OutputType.ASSIGN)\n","sub_path":"src/main/python/systemds/context/systemds_context.py","file_name":"systemds_context.py","file_ext":"py","file_size_in_byte":13248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"107392034","text":"# -*- coding: utf-8 -*-\n'''\nCreated on 2018年4月16日\n\n@author: zwp\n'''\n\n'''\n 分割 339*5825 数据集,\n 从原数据集中采集spa稀疏度的数据作为训练集,\n 剩下的数据中取spa稀疏度的数据作为测试集\n 将无效值从-1变为0,\n'''\n\nimport time;\nimport numpy as np;\nimport random;\nimport os;\nfrom sklearn.model_selection import train_test_split;\nfrom tools import SysCheck;\n\nbase_path = r'E:/work';\nif SysCheck.check()=='l':\n base_path='/home/zwp/work'\n \norigin_data_path = base_path+'/Dataset/ws/tpmatrix.txt';\ntrain_output_path = base_path+'/Dataset/ws/train_tp'\ntest_output_path = base_path+'/Dataset/ws/test_tp'\n\nspa_list=[5,10,15,20];\ncase_cout=10;\nreplace_param=[-1,-1];\n\n\n\ndef load_origin_data(ori_path,repalce_param=None):\n '''\n 加载一个原始数据集R,[339,5825],\n repalce_param:将R中所有[0]的值替换为[1];\n '''\n R = np.loadtxt(ori_path,float);\n if repalce_param != None:\n ind = np.where(R==repalce_param[0]);\n R[ind] = repalce_param[1];\n return R;\n\ndef mat_to_list(R):\n '''\n 将一个矩阵形式数据按照各个维度展开,\n 各个轴index从0开始\n 返回属性列表和标签列表\n '''\n us_shape = R.shape;\n feature=[];\n lable=[];\n for i in range(us_shape[0]):\n for j in range(us_shape[1]):\n feature.append([i,j]);\n lable.append(R[i,j]);\n return np.array(feature),np.array(lable)\n\ndef run():\n \n print('开始分割!分割序列=',spa_list);\n print ('加载数据开始');\n now = time.time();\n R = load_origin_data(origin_data_path,replace_param);\n print('原始数据:\\n',R);\n print ('加载数据完成,耗时 %.2f秒\\n'%((time.time() - now)));\n \n print ('转换数据开始');\n tnow = time.time();\n feature,lable=mat_to_list(R);\n n = len(feature);\n print ('转换数据开始,耗时 %.2f秒,总数据%d\\n'%((time.time() - tnow),n));\n \n \n for spa in spa_list:\n d_size = int(spa / 100.0 * n);\n test_path = test_output_path+'/sparseness%.1f'%(spa);\n if not os.path.isdir(test_path):\n os.makedirs(test_path);\n train_path = train_output_path+'/sparseness%.1f'%(spa);\n if not os.path.isdir(train_path):\n os.makedirs(train_path); \n for case in range(1,case_cout+1):\n print ('-->开始生成稀疏度%.1f%%数据,数据量%d,case=%d'%(spa,d_size,case));\n tnow = time.time();\n td_size = int(d_size/10);\n # td_size = int(d_size);\n test_x,left_x,test_y,left_y = train_test_split(feature,lable,train_size=td_size);\n test_y = test_y.reshape([td_size,1]);\n new_test=np.hstack((test_x,test_y));\n del test_y;\n del test_x;\n test_file = test_path+'/test%d.txt'%(case);\n np.savetxt(test_file,new_test,'%d %d %.2f');\n del new_test;\n \n train_x,_,train_y,_ = train_test_split(left_x,left_y,train_size=d_size);\n train_y = train_y.reshape([d_size,1]);\n new_train=np.hstack((train_x,train_y));\n del train_x;\n del train_y;\n train_file = train_path+'/training%d.txt'%(case);\n np.savetxt(train_file,new_train,'%d %d %.2f');\n del new_train; \n pass;\n\nif __name__ == '__main__':\n run();\n pass","sub_path":"src/tools/spliter339.py","file_name":"spliter339.py","file_ext":"py","file_size_in_byte":3416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"77621772","text":"import json\n\nfrom bluebottle.test.factory_models.payouts import ProjectPayoutFactory\nfrom django.core.management import call_command\n\nfrom bluebottle.test.factory_models.accounts import BlueBottleUserFactory\nfrom bluebottle.test.factory_models.donations import DonationFactory\nfrom bluebottle.test.factory_models.orders import OrderFactory\nfrom bluebottle.test.factory_models.payments import OrderPaymentFactory, PaymentFactory\nfrom bluebottle.test.factory_models.projects import ProjectFactory\nfrom bluebottle.test.utils import BluebottleTestCase, SessionTestMixin\nfrom moneyed.classes import Money\n\n\nclass TestPayoutExport(BluebottleTestCase, SessionTestMixin):\n def setUp(self):\n super(TestPayoutExport, self).setUp()\n self.project = ProjectFactory.create(amount_asked=5000)\n self.user = BlueBottleUserFactory.create()\n self.orders = OrderFactory.create_batch(7)\n for order in self.orders:\n DonationFactory.create(project=self.project, order=order)\n order_payment = OrderPaymentFactory(order=order)\n payment = PaymentFactory(order_payment=order_payment)\n payment.status = 'settled'\n payment.save()\n self.payout = ProjectPayoutFactory(\n project=self.project,\n amount_payable=Money(125.00, 'EUR'),\n amount_raised=Money(175.0, 'EUR'),\n status='settled'\n )\n\n def test_export(self):\n call_command('export_payouts', '--file', 'temp.json')\n with open('temp.json') as json_data:\n data = json.load(json_data)\n self.assertEqual(len(data), 1)\n self.assertEqual(len(data[0]['donations']), 7)\n self.assertEqual(data[0]['amount_payable'], {'currency': 'EUR', 'amount': 125.00})\n","sub_path":"bluebottle/payouts/tests/test_exports.py","file_name":"test_exports.py","file_ext":"py","file_size_in_byte":1779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"512426998","text":"from distutils.core import setup\nfrom setuptools import find_packages\n\nCLASSIFIERS = [\n'Development Status :: 3 - Alpha',\n'Intended Audience :: Developers',\n'License :: OSI Approved :: MIT License',\n'Programming Language :: Python',\n'Programming Language :: Python :: 2.7',\n'Programming Language :: Python :: 3.3',\n'Programming Language :: Python :: 3.4',\n'Programming Language :: Python :: 3.5',\n'Operating System :: Microsoft :: Windows',\n'Operating System :: POSIX',\n'Operating System :: Unix',\n'Operating System :: MacOS',\n'Natural Language :: English',\n]\n\nwith open('README.md') as fp:\n LONG_DESCRIPTION = ''.join(fp.readlines())\n\nsetup(\n name = 'sphinxcontrib-pyexec',\n version = '0.0.4',\n packages = find_packages(),\n install_requires = ['sphinx',\n 'docutils',\n ],\n author = 'Lindsey Heagy',\n author_email = 'lindsey@3ptscience.com',\n description = 'sphinxcontrib-pyexec',\n long_description = LONG_DESCRIPTION,\n license = 'MIT',\n keywords = 'sphinx documentation python execute',\n url = 'https://github.com/3ptscience/sphinxcontrib-pyexec',\n download_url = 'https://github.com/3ptscience/sphinxcontrib-pyexec',\n classifiers = CLASSIFIERS,\n platforms = ['Windows', 'Linux', 'Solaris', 'Mac OS-X', 'Unix'],\n use_2to3 = False,\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"109160878","text":"from .base import OnlineBase\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, LSTM\nimport numpy as np\n\n\nclass OnlineLSTM(OnlineBase):\n \"\"\"\n An online LSTM neural network.\n \"\"\"\n\n def __init__(self,\n history_length: int,\n epochs: int,\n forecast_length: int,\n delay: int,\n timesteps: int,\n optimizer: str = 'adam',\n verbose: bool = True):\n \"\"\"\n Constructor.\n\n :param history_length: number of units in LSTM\n :param epochs: number of epochs to train LSTM for at each timestep\n :param forecast_length: number of timesteps into the future for LSTM to predict at\n :param delay: number of timesteps between predictions\n :param timesteps: total number of timesteps to train LSTM for\n :param optimizer: the optimizer used to compile the model\n :param verbose: if True, logs current training timestep during training\n \"\"\"\n\n # Initialize base class\n super(OnlineLSTM, self).__init__(history_length, forecast_length, delay, timesteps, verbose=verbose)\n\n # Initialize epochs\n self._epochs = epochs\n\n # Initialize model\n self._lstm = Sequential([\n LSTM(self._history_length, input_shape=(self._history_length, 1)),\n Dense(1)\n ])\n self._lstm.compile(optimizer=optimizer, loss='mse')\n\n def _make_prediction(self) -> float:\n train = np.array(self._buffer[:self._history_length]).reshape((1, self._history_length, 1))\n target = np.array(self._buffer[-1]).reshape((1, 1))\n self._lstm.fit(train, target, epochs=self._epochs, verbose=0)\n return self._lstm.predict(\n np.array(self._buffer[self._forecast_length:]).reshape((1, self._history_length, 1))).item()\n","sub_path":"online_models/lstm.py","file_name":"lstm.py","file_ext":"py","file_size_in_byte":1892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"88499914","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# 条件\n# 锁\n# acquire release\n# notify()\n\nfrom threading import Thread, Condition\n\n\ndef func(con, i):\n con.acquire()\n con.wait()\n print('在第%s个循环里' % i)\n con.release()\n\ncon = Condition()\nfor i in range(10):\n Thread(target=func, args=(con,i)).start()\n\nwhile True:\n num = int(input('>>>'))\n con.acquire()\n con.notify(num)\n con.release()","sub_path":"多线程/7_条件.py","file_name":"7_条件.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"410894100","text":"import socket\r\nimport select\r\nimport sys\r\n\r\nfrom extra.user import User\r\n\r\n# Main variables\r\nPORT = 9090\r\nIP = socket.gethostname()\r\n\r\n\r\nclass Client(User):\r\n\r\n def __init__(self):\r\n self.socket = socket.socket()\r\n self.socket.connect((IP, PORT))\r\n self.socket.setblocking(False)\r\n\r\n\r\nclient = Client()\r\n\r\nwhile True:\r\n\r\n reads, _, _ = select.select([client.socket, sys.stdin], [], [])\r\n for to_do in reads:\r\n if to_do == client.socket:\r\n data = client.get_data()\r\n if data:\r\n print(data)\r\n else:\r\n data = input()\r\n if data:\r\n client.send_data(data)\r\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"469264108","text":"from collections import Counter\nfrom heapq import heappush, heappop\n\nclass Solution(object):\n def frequencySort(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n\n h, r = [], ''\n\n for c, n in Counter( s ).iteritems():\n heappush( h, ( -n, c ) )\n\n while h:\n n, c = heappop( h )\n r += c * -n\n\n return r\n","sub_path":"451.py","file_name":"451.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"69191637","text":"import re\nimport random\nimport rsa\nimport base64\nimport pathlib\nimport tempfile\nimport socket\nimport ssl\n\nfrom . import constant\n\n\ndef get_output_dir_for_statement(output_dir, session_id, stmt_id):\n if output_dir is None:\n output_dir = tempfile.gettempdir()\n\n full_path = pathlib.Path(output_dir) / f'{session_id}_{stmt_id}'\n full_path.mkdir(parents=True, exist_ok=True)\n\n return full_path\n\n\ndef encrypt_password(public_key_pem, password):\n pk = rsa.PublicKey.load_pkcs1(public_key_pem.encode())\n return base64.b64encode(rsa.encrypt(password.encode(), pk)).decode()\n\n\ndef get_random_host_port_from_dsn(dsn):\n \"\"\"\n Parse dsn, unpack it and return hosts in random order\n Random must happen here, otherwise people may put unbalanced load on Exasol nodes\n \"\"\"\n idx = dsn.find(':')\n\n if idx > -1:\n port = int(dsn[idx+1:])\n dsn = dsn[:idx]\n else:\n port = constant.DEFAULT_PORT\n\n res = []\n regexp = re.compile(r'^(.+?)(\\d+)\\.\\.(\\d+)(.*)$')\n\n for part in dsn.split(','):\n match = regexp.search(part)\n\n if match:\n for i in range(int(match.group(2)), int(match.group(3))):\n res.append((match.group(1) + str(i) + match.group(4), port))\n else:\n res.append((part, port))\n\n random.shuffle(res)\n\n return res\n\n\ndef get_host_ip_for_enter_parallel(ws_host):\n return socket.gethostbyname(ws_host)\n\n\ndef generate_adhoc_ssl_context():\n \"\"\"\n Create temporary self-signed certificate for encrypted HTTP transport\n Exasol does not check validity of certificates\n \"\"\"\n from OpenSSL import crypto\n\n k = crypto.PKey()\n k.generate_key(crypto.TYPE_RSA, 2048)\n\n cert = crypto.X509()\n cert.set_serial_number(1)\n cert.gmtime_adj_notBefore(0)\n cert.gmtime_adj_notAfter(60 * 60 * 24 * 365)\n\n cert.set_pubkey(k)\n cert.sign(k, 'sha256')\n\n cert_file = tempfile.NamedTemporaryFile()\n cert_file.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))\n cert_file.flush()\n\n key_file = tempfile.NamedTemporaryFile()\n key_file.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, k))\n key_file.flush()\n\n context = ssl.SSLContext()\n context.verify_mode = ssl.CERT_NONE\n context.load_cert_chain(certfile=cert_file.name, keyfile=key_file.name)\n\n cert_file.close()\n key_file.close()\n\n return context\n","sub_path":"pyexasol/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"23333169","text":"import mysql.connector, sys\nfrom mysql.connector import errorcode\n\n\n# Splits each line\ndef split_stuff(split_info):\n return split_info.split(',')\n\n\n# Creates dictionary\ndef ifs(ifs_info):\n ifs_dir = {}\n infos = ifs_info[:-2]\n for line_splitting in infos:\n temp_store = split_stuff(line_splitting)\n if 'directory' in temp_store[0] or 'default' in temp_store[0] or '\"' in temp_store:\n ifs_dir = {}\n elif '\"' in temp_store[1]:\n ifs_dir = {}\n else:\n for i in range(0, len(key_split)):\n ifs_dir[key_split[i]] = temp_store[i]\n check(ifs_dir)\n\n\n# Checks if the user/group is in the database\ndef check(checking):\n type = checking.get(\"Type\")\n user_id = checking.get(\"AppliesTo\")\n if type == \"user\":\n cursor.execute('SELECT user_name FROM user WHERE user_name = \"%s\"' % (user_id))\n user_in_db = cursor.fetchall()\n if not user_in_db:\n print(\"Not found in database %s (user), checking ldap\" % user_id)\n check_ldap_user(checking, type)\n else:\n add_ifs(checking, type)\n elif type == \"group\":\n cursor.execute('SELECT grp_name FROM grp WHERE grp_name = \"%s\"' % (user_id))\n user_in_db = cursor.fetchall()\n if not user_in_db:\n print(\"Not found in database %s (group), checking ldap\" % user_id)\n check_ldap_group(checking, type)\n else:\n add_ifs(checking, type)\n else:\n print(\"quotaType not found with %s\" % user_id)\n\n\n# Changes any empty space into zeros\ndef checking_for_nothing(check_zeros):\n if check_zeros == \"\":\n return \"0\"\n else:\n return check_zeros\n\n\n# Checks ldap and creates if not found in db\ndef check_ldap_user(name, types):\n # TODO add user search\n user_in_ldap = [1]\n if not user_in_ldap:\n print(\"%s (%s) not found in ldap\" % (name, types))\n else:\n # TODO get ldap info into variables\n user_name = \"\"\n first_name = \"\"\n last_name = \"\"\n email = \"\"\n gid = \"\"\n phone = \"\"\n # TODO need to fix the db insert statement\n try:\n cursor.execute('INSERT INTO user(user_name, first_name, last_name, email, gid, phone, created_at) VALUES(\"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", NOW())' % (user_name, first_name, last_name, email, gid, phone))\n print(\"New user %s created\" % user_name)\n add_ifs(name, types)\n except mysql.connector.Error as err:\n print(\"Insert create fail at %s (%s)\\nError (%s) \" % (user_name, types, err))\n\n\n# Checks ldap and creates if not found in db\ndef check_ldap_group(name, types):\n # TODO add ldap group search\n group_in_ldap = [1]\n if not group_in_ldap:\n print(\"%s (%s) not found in ldap\" % (name, types))\n else:\n # TODO get ldap info into variables\n group_name = \"\"\n user_name = \"\"\n gid = \"\"\n try:\n # TODO need to fix the db insert statement\n cursor.execute('INSERT INTO grp(grp_name, user_id, gid, created_at) VALUES(\"%s\", \"%s\", \"%s\", NOW())' % (group_name, user_name, gid,))\n print(\"New group %s created\" % user_name)\n add_ifs(name, types)\n except mysql.connector.Error as err:\n print(\"Insert create fail at %s (%s)\\nError (%s) \" % (group_name, types, err))\n\n\n# Breaks the information into groups, checks if it is usr or grp and adds it into the database\ndef add_ifs(adding, types):\n global date\n user_id = adding.get(\"AppliesTo\")\n path = adding.get(\"Path\")\n hard = checking_for_nothing(adding.get(\"Hard\"))\n soft = checking_for_nothing(adding.get(\"Soft\"))\n files = adding.get(\"Files\")\n with_over = checking_for_nothing(adding.get('\"With Overhead\"'))\n without_over = checking_for_nothing(adding.get('\"W/O Overhead\"'))\n enforced = adding.get(\"Enforced\")\n if types == \"user\":\n try:\n cursor.execute('INSERT INTO ifs(user_id, path, hard, soft, files, with_over, without_over, enforced, date) VALUES (\"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\")' % (user_id, path, hard, soft, files, with_over, without_over, enforced, date))\n except mysql.connector.Error as err:\n print(\"Insert fail at %s (user)\\nError (%s) \" % (user_id, err))\n elif types == \"group\":\n try:\n cursor.execute('INSERT INTO ifs(group_id, path, hard, soft, files, with_over, without_over, enforced, date) VALUES (\"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\")' % (user_id, path, hard, soft, files, with_over, without_over, enforced, date))\n except mysql.connector.Error as err:\n print(\"Insert fail at %s (group)\\nError (%s) \" % (user_id, err))\n else:\n print(\"Unable to find type\")\n\n\n# Gets year month and day from the user and looks for the file\nif __name__ == \"__main__\":\n dates = sys.argv\n date = dates[1] + \"-\" + dates[2] + \"-\" + dates[3]\n # TODO need to update the database info\n cnx = mysql.connector.connect(user='root', password='', database='user')\n cursor = cnx.cursor()\n # TODO need to add ldap connection\n try:\n # TODO need to change the path\n with open(\"/Users/chenw/desktop/logs/luna/quota-%s.csv\" % date, \"r\") as f:\n lines = f.read().splitlines()\n key = lines[0]\n key_split = split_stuff(key)\n data_info = lines[1:]\n except:\n print(\"File not found\")\n ifs(data_info)\n cnx.commit()\n cursor.close()\n cnx.close()\n\n\n","sub_path":"ifs4.py","file_name":"ifs4.py","file_ext":"py","file_size_in_byte":5534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"409908158","text":"class Solution(object):\n def majorityElement(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n length = len(nums)/2\n ans = 0\n max_ans = 0\n for n in set(nums):\n if nums.count(n) > max_ans:\n ans = n\n max_ans = nums.count(n)\n return ans\n ","sub_path":"0169-Majority-Element/0169-Majority-Element.py","file_name":"0169-Majority-Element.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"239679679","text":"from pysc2.env import sc2_env\nfrom pysc2.lib import actions, features, units\nimport numpy as np\n\nfrom absl import flags\n\nFLAGS = flags.FLAGS\nFLAGS([''])\n\n\nclass Env:\n metadata = {'render.modes': ['human']}\n default_settings = {\n 'map_name': \"CollectMineralShards\",\n 'players': [sc2_env.Agent(sc2_env.Race.terran)],\n 'agent_interface_format': features.AgentInterfaceFormat(\n feature_dimensions=features.Dimensions(screen=64, minimap=64),\n action_space=actions.ActionSpace.RAW,\n use_raw_units=True,\n raw_resolution=64),\n 'step_mul': 2,\n 'game_steps_per_episode' : 0,\n 'visualize' : True,\n 'realtime': False\n }\n\n def __init__(self, **kwargs):\n super().__init__()\n self.kwargs = kwargs\n self.env = None\n self.marine1 = None\n self.marine2 = None\n self.marine1_ID = None\n self.marine2_ID = None\n self.action_counter = 0\n self.state = np.zeros([3, 64, 64])\n\n def reset(self):\n if self.env is None:\n self.init_env()\n self.marine1 = None\n self.marine2 = None\n self.action_counter = 0\n self.state = np.zeros([3, 64, 64])\n\n raw_obs = self.env.reset()[0]\n return self.get_state_from_obs(raw_obs, True)\n\n def init_env(self):\n args = {**self.default_settings, **self.kwargs}\n self.env = sc2_env.SC2Env(**args)\n\n def get_state_from_obs(self, raw_obs, reset):\n marines = self.get_units_by_type(raw_obs, units.Terran.Marine)\n if reset:\n self.marine1_ID = marines[0].tag\n self.marine2_ID = marines[1].tag\n self.marine1 = marines[0]\n self.marine2 = marines[1]\n else:\n if self.marine1_ID == marines[0].tag:\n self.marine1 = marines[0]\n self.marine2 = marines[1]\n elif self.marine1_ID == marines[1].tag:\n self.marine1 = marines[1]\n self.marine2 = marines[0]\n else:\n assert False\n shard_matrix = np.array(raw_obs.observation.feature_minimap.player_relative)\n shard_matrix[shard_matrix < 2] = 0\n\n marine1_matrix = np.zeros([64, 64])\n marine1_matrix[self.marine1.x, int(self.marine1.y)] = 1\n\n marine2_matrix = np.zeros([64, 64])\n marine2_matrix[self.marine2.x, int(self.marine2.y)] = 2\n\n self.state = np.stack([shard_matrix, marine1_matrix, marine2_matrix], axis=0)\n return self.state\n\n def step(self, action):\n raw_obs = self.take_action(action)\n new_state = self.get_state_from_obs(raw_obs, False)\n return new_state, int(raw_obs.reward), raw_obs.last()\n\n def take_action(self, action):\n if action < 4096:\n x = action % 64\n y = int(action / 64)\n mapped_action = actions.RAW_FUNCTIONS.Move_pt(\"now\", self.marine1.tag, [x, y])\n else:\n action = action - 4096\n x = action % 64\n y = int(action / 64)\n mapped_action = actions.RAW_FUNCTIONS.Move_pt(\"now\", self.marine2.tag, [x, y])\n\n raw_obs = self.env.step([mapped_action])[0]\n\n return raw_obs\n\n def get_units_by_type(self, obs, unit_type):\n unit_list = []\n for unit in obs.observation.raw_units:\n if unit.unit_type == unit_type:\n unit_list.append(unit)\n return unit_list\n\n def close(self):\n if self.env is not None:\n self.env.close()\n super().close()","sub_path":"envs/sc2_shards_env_dqn.py","file_name":"sc2_shards_env_dqn.py","file_ext":"py","file_size_in_byte":3594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"487654614","text":"import unittest\nfrom Scripts.goal import Goal\nfrom Scripts.user import User\n\nclass TestGoal(unittest.TestCase):\n\n def test(self):\n goal1 = Goal(\"goal1\", \"Complete 1 workout\")\n goal2 = Goal(\"goal2\",\"Complete 5 workouts\")\n\n ## test constructor\n self.assertEqual(goal1.name, \"goal1\")\n self.assertEqual(goal2.description, \"Complete 5 workouts\")\n self.assertFalse(goal2.completed)\n\n ## test goalCompleted\n goal1.goalCompleted()\n self.assertTrue(goal1.completed)\n\n ## test editGoalName\n goal1.editGoalName(\"goal01\")\n self.assertEqual(goal1.name, \"goal01\")\n\n ## test editGoalDescription\n goal2.editGoalDescription(\"Complete 3 workouts\")\n self.assertEqual(goal2.description,\"Complete 3 workouts\")\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"Tests/testGoal.py","file_name":"testGoal.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"391797745","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Dec 14 11:51:46 2019\n\n@author: student\n\"\"\"\n\n#Multiple Linear Regrssion\n\n#Import the Libraries\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n#Importing the dataset\ndataset=pd.read_csv(\"50_Startups.csv\")\n#print(type(dataset))\nx=dataset.iloc[0:,:-1].values # values dataframe ko ndarray me convert karta hai \ny=dataset.iloc[:,4].values # single coulumn so it will be in Series\n#Printing the variables x & y\n#print(x)\n#print(y)\n#Convert categorical data into numarical data\nfrom sklearn.preprocessing import LabelEncoder,OneHotEncoder\n#label Encoder\nlabelencoder=LabelEncoder()\nx[:,3]=labelencoder.fit_transform(x[:,3])\n#print(x)\n\n#OneHotEncoder\nonehotencoder=OneHotEncoder(categorical_features=[3])\nx=onehotencoder.fit_transform(x).toarray()\n#print(x)\n#Avioding the dummy varaible trap\nx=x[:,1:]\nprint(x)\n\n#Splitting the dataset into the Training set and test set\nfrom sklearn.model_selection import train_test_split\nx_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=0)\n\n\n\n#fitting Multiple Linear Regression to the Training Set\nfrom sklearn.linear_model import LinearRegression\nregressor=LinearRegression() # creating its object\nregressor.fit(x_train,y_train)\n\n# to Print Coefficent\n\nprint(\"Co-efficent:\",regressor.coef_)\nprint(\"Intercepts:\",regressor.intercept_)\n\ny_pred=regressor.predict(x_test)\nfrom sklearn.metrics import mean_absolute_error,mean_squared_error,r2_score\nprint(\"mean squared:\",np.sqrt(mean_squared_error(y_test,y_pred)))\nprint(\"mean absolute error:\",mean_absolute_error(y_test,y_pred))\n\n\n\n\n\n\n\n\n#To Get t_test value and p value\n\nimport statsmodels.api as sm\n\nfrom scipy import stats\n# this is backward elimination untill all p values becomes less than 0.05\n##adding Extra Collumn at the beginning\nx=np.append(arr=np.ones((50,1)).astype(int),values=x,axis=1)\n#x_opt=x[:,[0,1,2,3,4,5]]\n#regressor_OLS=sm.OLS(endog=y,exog=x_opt)\n#est=regressor_OLS.fit()\n#print(est.summary())\n# Remove variable 2 because p value is high\n#x_opt=x[:,[0,1,3,4,5]]\n#regressor_OLS=sm.OLS(endog=y,exog=x_opt)\n#est=regressor_OLS.fit()\n#print(est.summary())\n# Remove variable 3 because p value is high\n#x_opt=x[:,[0,3,4,5]]\n#regressor_OLS=sm.OLS(endog=y,exog=x_opt)\n#est=regressor_OLS.fit()\n#print(est.summary())\n# Remove variable 5 because p value is high\n#x_opt=x[:,[0,3,4]]\n#regressor_OLS=sm.OLS(endog=y,exog=x_opt)\n#est=regressor_OLS.fit()\n#print(est.summary())\n# Remove variable 5 because p value is high\nx_opt=x[:,[0,3]]\nregressor_OLS=sm.OLS(endog=y,exog=x_opt)\nest=regressor_OLS.fit()\nprint(est.summary())\n\n# this is backward elimination untill all p values becomes less than 0.05\n","sub_path":"Bussiness Analytics/50start_multi.py","file_name":"50start_multi.py","file_ext":"py","file_size_in_byte":2700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"535728607","text":"#!/usr/bin/env python\n\nimport numpy as np\nimport kinpy as kp\nfrom scipy.optimize import minimize\n\nclass RobotKinematics:\n\n def __init__(self):\n self.chain = kp.build_chain_from_urdf(open(\"modello.urdf\").read())\n self.njoints = len( self.chain.get_joint_parameter_names() )\n self.end_link = \"link{}\".format(self.njoints)\n print(\"End link is: \", self.end_link)\n\n def calculate_direct_kinematic(self, joint_angles):\n\n assert len(joint_angles) == self.njoints\n\n joint_state = {}\n for i in range(0, len(joint_angles)):\n joint_state[\"joint{}\".format(i)] = joint_angles[i]\n\n all_link_positions = self.chain.forward_kinematics(joint_state)\n return all_link_positions[self.end_link].pos\n\n def get_joints_number(self):\n return self.njoints\n\n\n# create kinematics\nkin = RobotKinematics()\nN_JOINTS = kin.get_joints_number()\nJOINT_LIMIT = (np.pi - 0.0000001)/4.0\n\ninitial_state = np.array(N_JOINTS * [0.0]).astype(float)\ngoal_state = np.random.uniform(-JOINT_LIMIT, JOINT_LIMIT, N_JOINTS).astype(float)\ngoal_position = kin.calculate_direct_kinematic(goal_state)\n\n# create function to minimize\ndef distance_from_goal(joint_state):\n global kin, goal_state\n current_position = kin.calculate_direct_kinematic(joint_state)\n return np.linalg.norm(goal_position - current_position)\n\n# create bounds\nbounds = ( (-JOINT_LIMIT, JOINT_LIMIT), ) * N_JOINTS\n\n# run minimization\nsolution = minimize(distance_from_goal, initial_state, method='SLSQP', bounds=bounds)\n\n# get results\nfinal_state = solution.x\nfinal_position = kin.calculate_direct_kinematic(final_state)\nactual_distance = distance_from_goal(final_state)\n\nprint(goal_position)\nprint(final_position)\nprint(actual_distance)","sub_path":"snake-openai/old/snake-gym-optimization.py","file_name":"snake-gym-optimization.py","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"612904488","text":"from datetime import date\nfrom datetime import datetime\nimport base64\nimport json\nimport hmac\nimport hashlib\n\n\n\ndef calculate_age(born):\n if born == None:\n return date.today()\n else:\n today = date.today()\n return today.year - born.year - ((today.month, today.day) < (born.month, born.day))\n\n\ndef validate_one_character(string):\n\n if len(string) > 1:\n return False\n else:\n if string == \"1\" or string == \"0\":\n return True\n else:\n return False\n\n\n# App key + secret\nAPPLICATION_KEY = 'fe851d0c-f991-4ad7-8607-7bdd1695ae5d'\nAPPLICATION_SECRET = 'F9ckfxFEn0+2jtsq9/dDNA=='\n\n\ndef getAuthTicket(user):\n userTicket = {\n 'identity': {'type': 'username', 'endpoint': user['username']},\n 'expiresIn': 3600, #1 hour expiration time of session when created using this ticket\n 'applicationKey': APPLICATION_KEY,\n 'created': datetime.utcnow().isoformat()\n }\n\n try:\n userTicketJson = json.dumps(userTicket).replace(\" \", \"\")\n userTicketBase64 = base64.b64encode(userTicketJson.encode('ascii'))\n\n\n # TicketSignature = Base64 ( HMAC-SHA256 ( ApplicationSecret, UTF8 ( UserTicketJson ) ) )\n digest = hmac.new(base64.b64decode(APPLICATION_SECRET), msg=userTicketJson.encode('ascii'), digestmod=hashlib.sha256).digest()\n signature = base64.b64encode(digest)\n\n print(type(userTicketBase64))\n print(type(signature))\n two_points = b':'\n print(type(two_points))\n # UserTicket = TicketData + \":\" + TicketSignature\n #signedUserTicket = userTicketBase64 + ':' + signature\n signedUserTicket = userTicketBase64 + two_points + signature\n\n #return {'userTicket': signedUserTicket}\n return signedUserTicket\n except Exception as inst:\n print(inst)\n","sub_path":"midoc/api/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"417040032","text":"\"\"\"Self-Play module: where the games are played.\"\"\"\n\nfrom config import MuZeroConfig\nfrom game.game import AbstractGame\nfrom networks.network import AbstractNetwork\nfrom networks.shared_storage import SharedStorage\nfrom self_play.mcts import select_action\nimport random\nimport numpy as np\n\n\ndef run_selfplay(config: MuZeroConfig, storage: SharedStorage, game_name: str):\n \"\"\"Take the latest network, produces multiple games and save them in the shared replay buffer\"\"\"\n\n\n if int(game_name.split('_')[-1]) < 100: #We want to run random games initially to fill the replay buffer\n network = storage.uniform_network\n print('Initial training: using uniform network')\n else:\n network = storage.latest_network()\n game = play_game(config, network, game_name=game_name)\n game.env = 0\n rewards = int(sum(game.rewards))\n game.save_game_to_file(game_name+'_'+str(rewards)+'.pkl')\n game.save_gif(game_name+'_'+str(rewards))\n return rewards\n\n\ndef run_eval(config: MuZeroConfig, storage: SharedStorage, eval_episodes: int):\n network = storage.latest_network()\n returns = []\n for _ in range(eval_episodes):\n game = play_game(config, network, train=False)\n game.save_gif('eval')\n returns.append(sum(game.rewards))\n return sum(returns)*5 / eval_episodes if eval_episodes else 0\n\n\ndef play_game(config: MuZeroConfig, network: AbstractNetwork, train: bool = True, game_name: str = 'default_agent') -> AbstractGame:\n \"\"\"\n Each game is produced by starting at the initial board position, then\n repeatedly executing a learned search to select moves until the end\n of the game is reached.\n \"\"\"\n overworlds = ['1-1','2-1','3-1','3-2','4-1','5-1','5-2','6-1','6-2','7-1','8-1','8-2','8-3']\n underworlds = ['1-2','4-2']\n athletics = ['1-3','2-3','3-3','4-3','5-3','6-3','7-3']\n waterworlds = ['2-2','7-2']\n castles = ['1-4', '2-4', '3-4', '5-4', '6-4']\n game = config.new_game(overworlds) # Make a new game from one in the list\n mode_action_select = 'softmax' if train else 'max'\n noop = random.randint(0,config.initial_random_moves)\n while not game.terminal() and len(game.history) < config.max_moves:\n # We use the representation function to\n # obtain a hidden state given the current observation.\n current_observation = game.make_image(-1)\n inital_network_output = network.initial_inference(current_observation)\n # We evaluate the value of config.num_searches moves to\n # get our current ideal policy\n action_values = value_search(config, network, inital_network_output)\n\n # Set the root value of the current state\n game.root_values.append(np.mean(list(action_values.values())))\n # Normalize the values of our ideal policy\n min_value = sorted(action_values, key=action_values.get)[0]\n min_value = action_values[min_value]\n max_value = sorted(action_values, key=action_values.get)[-1]\n max_value = action_values[max_value]\n target_policy = []\n normalized_action_values = {}\n for action in inital_network_output.policy_logits.keys():\n current_value = (action_values[action] - min_value + 0.001) / (max_value - min_value + 0.001)\n target_policy.append(current_value)\n normalized_action_values[action] = current_value\n \n target_sum = sum(target_policy)\n target_policy = [i/target_sum for i in target_policy]\n # Save the current ideal policy\n game.child_visits.append(target_policy)\n # Select action to perform using our ideal policy as probabilities\n if len(game.history) < noop:\n action = select_action(config, len(game.history), normalized_action_values, mode='random')\n else:\n action = select_action(config, len(game.history), normalized_action_values, mode=mode_action_select)\n game.apply(action)\n\n game.close()\n return game\n\ndef value_search(config: MuZeroConfig, network: AbstractNetwork, inital_network_output):\n # Performs a search for the ideal move by taking the top\n # config.num_searches moves from our policy network and\n # predicting their value config.search_depth moves into the\n # future\n search_policy = inital_network_output.policy_softmax\n ranked_actions = sorted(search_policy, key=search_policy.get, reverse=True)\n actions_to_evaluate = ranked_actions[:config.num_searches]\n actions_to_infer = ranked_actions[config.num_searches:]\n action_values = {}\n for action in actions_to_evaluate:\n current_rewards = []\n current_values = [inital_network_output.value]\n current_hidden_state = inital_network_output.hidden_state\n current_action = action\n for i in range(config.search_depth):\n network_output = network.recurrent_inference(current_hidden_state, current_action)\n current_rewards.append(network_output.reward*config.discount**i)\n current_values.append(network_output.value*config.discount**i)\n current_hidden_state = network_output.hidden_state\n current_action = sorted(network_output.policy_softmax, key=network_output.policy_softmax.get, reverse=True)[0]\n action_values[action] = np.mean(current_values) + sum(current_rewards)\n min_value = min(action_values.values())\n for action in actions_to_infer:\n action_values[action] = min_value\n return action_values\n \n \n \n \n \n\n","sub_path":"muzero/self_play/self_play.py","file_name":"self_play.py","file_ext":"py","file_size_in_byte":5533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"175120687","text":"import sys, getopt\nfrom PIL import Image\nfrom numpy import array\n\ndef main(argv):\n inputfile = ''\n outputfile = ''\n try:\n opts, args = getopt.getopt(argv,\"hi:o:\",[\"ifile=\",\"ofile=\"])\n except getopt.GetoptError:\n print('image_transparent.py -i -o ')\n sys.exit(2)\n for opt, arg in opts:\n if opt == '-h':\n print ('image_transparent.py -i -o ')\n sys.exit()\n elif opt in (\"-i\", \"--ifile\"):\n inputfile = arg\n elif opt in (\"-o\", \"--ofile\"):\n outputfile = arg\n print('Input file is \"', inputfile)\n print('Output file is \"', outputfile)\n\n img = Image.open(inputfile)\n img_array = array(img)\n img_array[:,:,3] = 0\n img = Image.fromarray(img_array)\n if outputfile!= '':\n img.save(outputfile)\n else:\n img.save(inputfile+'_transparent.png')\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])","sub_path":"image_transparent.py","file_name":"image_transparent.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"639231658","text":"import cv2\nfrom facenet_pytorch import MTCNN\nfrom PIL import Image\n\nmtcnn = MTCNN(margin = 20,\n keep_all = True,\n post_process = False)\n\ndef detect_faces(image):\n\n #img = cv2.imread(image)\n img = image\n color = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n frame = Image.fromarray(color)\n\n boxes, probs, landmarks = mtcnn.detect(frame,\n landmarks = True)\n\n if boxes is None:\n boxes = \"No faces in picture\"\n else:\n boxes = boxes.astype(int)\n\n return(color,\n gray,\n frame,\n boxes)","sub_path":"code_vid_emo_blur/module_detect_faces.py","file_name":"module_detect_faces.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"246261992","text":"tab = [7, 5, [3, 6, [2]], 7, [1, [2, 3, [4]], 9, 2], 4]\r\n\r\ndef recursiveSum(numbers):\r\n result = 0\r\n for n in numbers:\r\n if isinstance(n, int):\r\n result += n\r\n elif isinstance(n, list):\r\n result += recursiveSum(n)\r\n \r\n return result\r\n\r\nprint(recursiveSum(tab))","sub_path":"04-Subroutines/zad36.py","file_name":"zad36.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"362176034","text":"from itertools import accumulate, chain, islice, permutations, count\n\nitems = [1, 2, 3, 4, 5, 4, 4, 3, 4, 5, 2, 0, 7, 4, 5, 6]\naccumulator = accumulate(items)\nprint(list(accumulator)) # [1, 3, 6, 10, 15, 19, 23, 26, 30, 35, 37, 37, 44, 48, 53, 59]\n\n\nlist1 = [1, 2, 3]\nlist2 = [4, 5, 6]\nlist3 = [7, 8, 9]\nchained_list = chain(list1, list2, list3) # chained list is an iterator, not a new list\nprint(list(chained_list)) # [1, 2, 3, 4, 5, 6, 7, 8, 9]\n\n\nstatement = 'she sells seashells by the seashore'\nprint(''.join(islice(statement, 10, 19))) # seashells\n\n\nstatement = 'python'\ndepth = 2\nprint([''.join(combo) for combo in permutations(statement,depth)])\n\n\nfor c1, c2 in zip(range(0, 10), count(0, 0.25)):\n print(c1, c2)","sub_path":"Optum Tech/IN1468 available until 12-31-20/IN1468_student_files/student_files/ch06_std_lib/04_itertools.py","file_name":"04_itertools.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"421828886","text":"#!/usr/bin/python3\n\nimport psycopg2\nimport sys\n\n\ndef main():\n\tif (len(sys.argv) != 2):\n\t\tprint(\"Invalid Syntax\", file=sys.stderr)\n\t\tprint(\"Usage: ./reset.py \", file=sys.stderr)\n\t\tsys.exit()\n\n\tprint (\"\\nSuccessfully loaded sql db:\", sys.argv[1])\n\n\tproj_db = sys.argv[1]\n\tconnect = psycopg2.connect(dbname = proj_db)\n\tif not connect:\n\t\tprint(\"Unable to connect to database.. quitting\", file=sys.stderr)\n\t\tsys.exit()\n\n\tcur = connect.cursor()\n\tcur.execute(\"DELETE FROM FIGHT\")\n\tprint (\"Successfully cleared fight table from sql db:\", sys.argv[1])\n\tconnect.commit()\n\tconnect.close()\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"reset.py","file_name":"reset.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"485416088","text":"__author__ = 'bazilio'\n\n\nfrom sklearn import cross_validation\nfrom sklearn import preprocessing\n\n\nclass PreProcessor:\n\n def __init__(self, X, y):\n\n self.X_train, self.X_test, \\\n self.y_train, self.y_test = \\\n cross_validation.train_test_split(X, y,\n test_size=0.1, random_state=0)\n\n def pre_process(self):\n self.X_train = preprocessing.normalize(self.X_train)\n self.X_train = preprocessing.scale(self.X_train)\n\n self.X_test = preprocessing.normalize(self.X_test)\n self.X_test = preprocessing.scale(self.X_test)\n\n return self.X_train, self.y_train, self.X_test, self.y_test","sub_path":"trainer_machine/preprocessor.py","file_name":"preprocessor.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"514125946","text":"# (C) Copyright 2004-2021 Enthought, Inc., Austin, TX\n# All rights reserved.\n#\n# This software is provided without warranty under the terms of the BSD\n# license included in LICENSE.txt and may be redistributed only under\n# the conditions described in the aforementioned license. The license\n# is also available online at http://www.enthought.com/licenses/BSD.txt\n#\n# Thanks for using Enthought open source!\n\nimport unittest\n\nfrom pyface.toolkit import toolkit_object\nfrom traits.api import HasTraits, Instance, List, Str, String\nfrom traitsui.api import InstanceEditor, Item, View\nfrom traitsui.tests._tools import (\n BaseTestMixin,\n requires_toolkit,\n ToolkitName,\n)\n\nfrom traitsui.testing.api import (\n DisplayedText,\n Index,\n IsEnabled,\n KeyClick,\n KeySequence,\n MouseClick,\n SelectedText,\n TargetByName,\n UITester\n)\n\nModalDialogTester = toolkit_object(\n \"util.modal_dialog_tester:ModalDialogTester\"\n)\nno_modal_dialog_tester = ModalDialogTester.__name__ == \"Unimplemented\"\n\n\nclass EditedInstance(HasTraits):\n value = Str()\n traits_view = View(Item(\"value\"), buttons=[\"OK\"])\n\n\nclass NamedInstance(HasTraits):\n name = Str()\n value = Str()\n traits_view = View(Item(\"value\"), buttons=[\"OK\"])\n\n\nclass ObjectWithInstance(HasTraits):\n inst = Instance(EditedInstance, args=())\n\n\nclass ObjectWithList(HasTraits):\n inst_list = List(Instance(NamedInstance))\n inst = Instance(NamedInstance, args=())\n\n def _inst_list_default(self):\n return [\n NamedInstance(name=value, value=value)\n for value in ['one', 'two', 'three']\n ]\n\n\nsimple_view = View(Item(\"inst\"), buttons=[\"OK\"])\ncustom_view = View(Item(\"inst\", style='custom'), buttons=[\"OK\"])\nselection_view = View(\n Item(\n \"inst\",\n editor=InstanceEditor(name='inst_list'),\n style='custom',\n ),\n buttons=[\"OK\"],\n)\nmodal_view = View(\n Item(\"inst\", style=\"simple\", editor=InstanceEditor(kind=\"modal\"))\n)\n\n\nclass ValidatedEditedInstance(HasTraits):\n some_string = String(\"A\", maxlen=3)\n\n traits_view = View(Item('some_string'))\n\n\nclass ObjectWithValidatedInstance(HasTraits):\n something = Instance(ValidatedEditedInstance, args=())\n\n traits_view = View(\n Item(\n 'something',\n editor=InstanceEditor(),\n style='custom'\n ),\n buttons=[\"OK\", \"Cancel\"],\n )\n\n\nclass ObjectWithValidatedList(HasTraits):\n inst_list = List(Instance(HasTraits))\n inst = Instance(HasTraits, ())\n\n def _inst_list_default(self):\n return [\n ValidatedEditedInstance(some_string=value)\n for value in ['a', 'b', 'c']\n ]\n\n\n@requires_toolkit([ToolkitName.qt, ToolkitName.wx])\nclass TestInstanceEditor(BaseTestMixin, unittest.TestCase):\n\n def setUp(self):\n BaseTestMixin.setUp(self)\n\n def tearDown(self):\n BaseTestMixin.tearDown(self)\n\n def test_simple_editor(self):\n obj = ObjectWithInstance()\n tester = UITester()\n with tester.create_ui(obj, {'view': simple_view}) as ui:\n instance = tester.find_by_name(ui, \"inst\")\n instance.perform(MouseClick())\n value_txt = instance.find_by_name(\"value\")\n value_txt.perform(KeySequence(\"abc\"))\n self.assertEqual(obj.inst.value, \"abc\")\n\n def test_custom_editor(self):\n obj = ObjectWithInstance()\n tester = UITester()\n with tester.create_ui(obj, {'view': custom_view}) as ui:\n value_txt = tester.find_by_name(ui, \"inst\").find_by_name(\"value\")\n value_txt.perform(KeySequence(\"abc\"))\n self.assertEqual(obj.inst.value, \"abc\")\n\n def test_custom_editor_with_selection(self):\n obj = ObjectWithList()\n tester = UITester()\n with tester.create_ui(obj, {'view': selection_view}) as ui:\n # test that the current object is None\n self.assertIsNone(obj.inst)\n\n # test that the displayed text is correct\n instance = tester.find_by_name(ui, \"inst\")\n text = instance.inspect(SelectedText())\n self.assertEqual(text, obj.inst_list[0].name)\n\n # test that changing selection works\n instance.locate(Index(1)).perform(MouseClick())\n self.assertIs(obj.inst, obj.inst_list[1])\n\n # test that the displayed text is correct\n text = instance.inspect(SelectedText())\n self.assertEqual(text, obj.inst_list[1].name)\n\n # test editing the view works\n value_txt = instance.find_by_name(\"value\")\n value_txt.perform(KeySequence(\"abc\"))\n self.assertEqual(obj.inst.value, \"twoabc\")\n\n def test_custom_editor_with_selection_initialized(self):\n obj = ObjectWithList()\n obj.inst = obj.inst_list[1]\n tester = UITester()\n with tester.create_ui(obj, {'view': selection_view}) as ui:\n # test that the current object is the correct one\n self.assertIs(obj.inst, obj.inst_list[1])\n\n # test that the displayed text is correct\n instance = tester.find_by_name(ui, \"inst\")\n text = instance.inspect(SelectedText())\n self.assertEqual(text, obj.inst.name)\n\n def test_custom_editor_resynch_editor(self):\n edited_inst = EditedInstance(value='hello')\n obj = ObjectWithInstance(inst=edited_inst)\n tester = UITester()\n with tester.create_ui(obj, {'view': custom_view}) as ui:\n value_txt = tester.find_by_name(ui, \"inst\").find_by_name(\"value\")\n displayed = value_txt.inspect(DisplayedText())\n self.assertEqual(displayed, \"hello\")\n edited_inst.value = \"bye\"\n displayed = value_txt.inspect(DisplayedText())\n self.assertEqual(displayed, \"bye\")\n\n def test_simple_editor_resynch_editor(self):\n edited_inst = EditedInstance(value='hello')\n obj = ObjectWithInstance(inst=edited_inst)\n tester = UITester()\n with tester.create_ui(obj, {'view': simple_view}) as ui:\n instance = tester.find_by_name(ui, \"inst\")\n instance.perform(MouseClick())\n\n value_txt = instance.find_by_name(\"value\")\n displayed = value_txt.inspect(DisplayedText())\n self.assertEqual(displayed, \"hello\")\n edited_inst.value = \"bye\"\n displayed = value_txt.inspect(DisplayedText())\n self.assertEqual(displayed, \"bye\")\n\n def test_simple_editor_parent_closed(self):\n obj = ObjectWithInstance()\n tester = UITester()\n with tester.create_ui(obj, {'view': simple_view}) as ui:\n instance = tester.find_by_name(ui, \"inst\")\n instance.perform(MouseClick())\n\n @unittest.skipIf(no_modal_dialog_tester, \"ModalDialogTester unavailable\")\n def test_simple_editor_modal(self):\n # Test launching the instance editor with kind set to 'modal'\n obj = ObjectWithInstance()\n ui_tester = UITester()\n\n with ui_tester.create_ui(obj, dict(view=modal_view)) as ui:\n\n def click_button():\n ui_tester.find_by_name(ui, \"inst\").perform(MouseClick())\n\n def when_opened(tester):\n with tester.capture_error():\n try:\n dialog_ui = tester.get_dialog_widget()._ui\n # If auto_process_events was not set to false, this\n # will block due to deadlocks with ModalDialogTester.\n ui_tester = UITester(auto_process_events=False)\n value = ui_tester.find_by_name(dialog_ui, \"value\")\n value.perform(KeySequence(\"Hello\"))\n self.assertEqual(obj.inst.value, \"\")\n ok_button = ui_tester.find_by_id(dialog_ui, \"OK\")\n ok_button.perform(MouseClick())\n finally:\n # If the block above fails, the dialog will block\n # forever. Close it regardless.\n if tester.get_dialog_widget() is not None:\n tester.close(accept=True)\n\n mdtester = ModalDialogTester(click_button)\n mdtester.open_and_run(when_opened=when_opened)\n self.assertTrue(mdtester.dialog_was_opened)\n self.assertEqual(obj.inst.value, \"Hello\")\n\n # A regression test for issue enthought/traitsui#1501\n def test_propagate_errors(self):\n obj = ObjectWithValidatedInstance()\n ui_tester = UITester()\n with ui_tester.create_ui(obj) as ui:\n something_ui = ui_tester.find_by_name(ui, \"something\")\n some_string_field = something_ui.locate(\n TargetByName('some_string')\n )\n some_string_field.perform(KeySequence(\"abcd\"))\n some_string_field.perform(KeyClick(\"Enter\"))\n\n ok_button = ui_tester.find_by_id(ui, \"OK\")\n\n instance_editor_ui = something_ui._target._ui\n instance_editor_ui_parent = something_ui._target._ui.parent\n self.assertNotEqual(\n instance_editor_ui, ui\n )\n self.assertEqual(\n instance_editor_ui_parent, ui\n )\n\n self.assertEqual(\n instance_editor_ui.errors, ui.errors\n )\n self.assertFalse(ok_button.inspect(IsEnabled()))\n\n def test_propagate_errors_switch_selection(self):\n obj = ObjectWithValidatedList()\n ui_tester = UITester()\n with ui_tester.create_ui(obj, {'view': selection_view}) as ui:\n something_ui = ui_tester.find_by_name(ui, \"inst\")\n\n something_ui.locate(Index(0)).perform(MouseClick())\n\n some_string_field = something_ui.locate(\n TargetByName('some_string')\n )\n some_string_field.perform(KeySequence(\"bcde\"))\n some_string_field.perform(KeyClick(\"Enter\"))\n\n ok_button = ui_tester.find_by_id(ui, \"OK\")\n\n instance_editor_ui = something_ui._target._ui\n instance_editor_ui_parent = something_ui._target._ui.parent\n self.assertNotEqual(\n instance_editor_ui, ui\n )\n self.assertEqual(\n instance_editor_ui_parent, ui\n )\n\n self.assertEqual(\n instance_editor_ui.errors, ui.errors\n )\n self.assertFalse(ok_button.inspect(IsEnabled()))\n\n # change to a different selected that is not in an error state\n something_ui.locate(Index(1)).perform(MouseClick())\n\n self.assertTrue(ok_button.inspect(IsEnabled()))\n","sub_path":"venv/lib/python3.8/site-packages/traitsui/tests/editors/test_instance_editor.py","file_name":"test_instance_editor.py","file_ext":"py","file_size_in_byte":10706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"163759371","text":"xfile = open('hello.txt')\ncount = 0\n\n#python reads line by line of the text file\nfor chess in xfile:\n count += 1\n print (count,chess)\n\nfor chess in xfile:\n chess_striped = chess.rstrip(f)\n if chess.startswith('from'):\n print(chess_striped)\n\n## read 10 million lines is problem\n# check methods or open object \ntext_file = xfile.read()\nprint(len(text_file))\n\n","sub_path":"read_file.py","file_name":"read_file.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"161155713","text":"#****************************************************#\n# This file is part of OPTALG. #\n# #\n# Copyright (c) 2015-2016, Tomas Tinoco De Rubira. #\n# #\n# OPTALG is released under the BSD 2-clause license. #\n#****************************************************#\n\nimport sys\nfrom distutils.core import setup,Extension\n\next_modules = []\n\n# mumps\nif '--no_mumps' in sys.argv:\n sys.argv.remove('--no_mumps')\nelse:\n ext_modules.append(Extension(name='optalg.lin_solver._mumps._dmumps',\n sources=['./optalg/lin_solver/_mumps/_dmumps.c'],\n libraries=['dmumps_seq'],\n library_dirs=[],\n extra_link_args=[]))\n\nsetup(name='OPTALG',\n version='1.1',\n description='Optimization Algorithms',\n author='Tomas Tinoco De Rubira',\n author_email='ttinoco5687@gmail.com',\n ext_modules=ext_modules,\n packages=['optalg',\n 'optalg.lin_solver',\n 'optalg.lin_solver._mumps',\n 'optalg.opt_solver',\n 'optalg.stoch_solver'],\n requires=['scipy',\n 'numpy',\n 'dill'])\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"432555484","text":"# __author__ == \"Priya\"\n\nimport pygame, sys\nfrom pygame.locals import *\n\n#Initialize\npygame.init()\n#display mode\nDISPLAYSURF = pygame.display.set_mode((400,300), 0, 32)\n#display caption\npygame.display.set_caption('Drawing')\n#Colors\nBLACK = (0, 0, 0)\nGREY = (128, 128, 128)\nRED = (255, 0, 0)\nGREEN = (0, 255, 0)\nBLUE = (0, 0, 255)\n#Fill Display with white\nDISPLAYSURF.fill(GREY)\n#Drawing different shapes\npygame.draw.polygon(DISPLAYSURF, BLACK, ((20, 130), (10,140), (60, 200), (120, 240), (78, 150)))\npygame.draw.line(DISPLAYSURF, GREEN, (130, 10), (250, 20),15)\npygame.draw.line(DISPLAYSURF, GREEN, (250,20),(180,60),15)\npygame.draw.line(DISPLAYSURF, GREEN, (180, 60), (130, 10),15)\npygame.draw.circle(DISPLAYSURF, BLUE, (300,100), 40, 0)\npygame.draw.rect(DISPLAYSURF, RED, (200,150,100,100))\n\n#Runs until we get quit command\nwhile True:\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n pygame.display.update()","sub_path":"Games/Pygame_intro.py","file_name":"Pygame_intro.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"159193788","text":"#\n# [687] Longest Univalue Path\n#\n# https://leetcode.com/problems/longest-univalue-path/description/\n#\n# algorithms\n# Easy (32.69%)\n# Total Accepted: 32.4K\n# Total Submissions: 99.1K\n# Testcase Example: '[5,4,5,1,1,5]'\n#\n# Given a binary tree, find the length of the longest path where each node in\n# the path has the same value. This path may or may not pass through the root.\n#\n# Note: The length of path between two nodes is represented by the number of\n# edges between them.\n#\n#\n# Example 1:\n#\n#\n#\n#\n# Input:\n#\n# ⁠ 5\n# ⁠ / \\\n# ⁠ 4 5\n# ⁠ / \\ \\\n# ⁠ 1 1 5\n#\n#\n#\n#\n# Output:\n#\n# 2\n#\n#\n#\n#\n# Example 2:\n#\n#\n#\n#\n# Input:\n#\n# ⁠ 1\n# ⁠ / \\\n# ⁠ 4 5\n# ⁠ / \\ \\\n# ⁠ 4 4 5\n#\n#\n#\n#\n# Output:\n#\n# 2\n#\n#\n#\n# Note:\n# The given binary tree has not more than 10000 nodes. The height of the tree\n# is not more than 1000.\n#\n#\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\n\nclass Solution:\n def longestUnivaluePath(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n self.res = 0\n self.DFS(root)\n return self.res\n\n def DFS(self, root):\n if root is None:\n return None, 0\n lv, lc = self.DFS(root.left)\n rv, rc = self.DFS(root.right)\n if root.val == lv == rv:\n self.res = max(self.res, lc+rc+2)\n c = max(lc, rc)+1\n elif root.val == lv:\n self.res = max(self.res, lc+1)\n c = lc+1\n elif root.val == rv:\n self.res = max(self.res, rc+1)\n c = rc+1\n else:\n c = 0\n return root.val, c\n","sub_path":"687.longest-univalue-path.python3.py","file_name":"687.longest-univalue-path.python3.py","file_ext":"py","file_size_in_byte":1818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"122115248","text":"from django.shortcuts import render,get_object_or_404\nfrom firstapp.forms import UserForm,UserProfileInform\nimport json\nfrom firstapp.models import UserProfileInfo,User\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponseRedirect,HttpResponse,JsonResponse\nfrom django.contrib.auth import authenticate,login as auth_login,logout\nfrom User.forms import SellItemInfoForm,CommentsForm,AuctionsForm\nfrom User.models import SellItemInfo,Chat,Notification,Comments,ServerInfo,Auctions,purchaseInfo,RatingInfo\nfrom django.core import serializers\nfrom django.forms.models import model_to_dict\nfrom itertools import chain,cycle\ntry:\n from itertools import zip_longest as zip_longest\nexcept:\n from itertools import izip_longest as zip_longest\nimport re\nfrom collections import Counter\nimport string\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.views.generic import RedirectView\nfrom django.utils import timezone\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.db.models import F\nfrom django.db.models import Q\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom datetime import date, datetime\nimport json\nimport decimal\nimport ast\nimport locale\nfrom django.core.serializers.json import DjangoJSONEncoder\nfrom django.db.models import Q\nfrom django.db.models import Count\nfrom django.db.models.query import QuerySet\n# from django.core import serializers\n# json_serializer = serializers.get_serializer(\"json\")()\n# companies = json_serializer.serialize(Notification.objects.all().order_by('id')[:5], ensure_ascii=False)\n\n# Create your views here.\n\nother = None\nnam = \"\"\niteuploader = None\nslugg_ = None\nteruser = None\n\n\n\ndef Rating(request):\n if request.method == \"POST\":\n rating = request.POST['dat']\n slug = request.POST['slug']\n print(rating)\n print(slug)\n ii = SellItemInfo.objects.get(slug=slug)\n r = RatingInfo.objects.filter(user=request.user,item=ii)\n u = RatingInfo.objects.all()\n k = RatingInfo.objects.filter(item=ii).values('rate').annotate(total=Count('rate')).order_by('-rate')\n \n hh = list(k.values('rate','total'))\n ll = []\n rr = []\n c = 0\n for i in hh:\n rr.insert(c,i.get('rate'))\n ll.insert(c,i.get('total'))\n c+=1\n\n # print(rr)\n # print(ll)\n if r.count()==0:\n rr = RatingInfo(user=request.user,item=ii,rate=rating)\n rr.save()\n k = RatingInfo.objects.filter(item=ii).values('rate').annotate(total=Count('rate')).order_by('-rate')\n \n hh = list(k.values('rate','total'))\n ll = []\n rr = []\n c = 0\n for i in hh:\n rr.insert(c,i.get('rate'))\n ll.insert(c,i.get('total'))\n c+=1\n return JsonResponse({ 'msg': \"Thank You For Rating This Item\" ,\"d\":\"done\",\"rr\":ll,\"lab\":rr, \"hh\":hh })\n else:\n rr = RatingInfo.objects.filter(user=request.user,item=ii).update(rate = rating)\n \n k = RatingInfo.objects.filter(item=ii).values('rate').annotate(total=Count('rate')).order_by('-rate')\n \n hh = list(k.values('rate','total'))\n ll = []\n rr = []\n c = 0\n for i in hh:\n rr.insert(c,i.get('rate'))\n ll.insert(c,i.get('total'))\n c+=1\n return JsonResponse({ 'msg': \"Thank You For Rating again\" ,\"d\":\"done\",\"rr\":ll,\"lab\":rr, \"hh\":hh})\n # return HttpResponse(rating)\ndef json_serial(obj):\n \"\"\"JSON serializer for objects not serializable by default json code\"\"\"\n\n if isinstance(obj, (datetime, date)):\n return obj.isoformat()\n raise TypeError (\"Type %s not serializable\" % type(obj))\n\ndef json_encode_decimal(obj):\n if isinstance(obj, decimal.Decimal):\n return str(obj)\n raise TypeError(repr(obj) + \" is not JSON serializable\")\n\n@login_required\ndef Mapdetailupdate(request):\n items = SellItemInfo.objects.all().exclude(uploader=request.user)\n hhh = list(items.values('uploader','item_name','item_lat','item_long','item_location','slug'))\n return HttpResponse(json.dumps(hhh,default=json_encode_decimal))\n\n@login_required\ndef Mapdetails(request):\n return render(request,'firstapp/locations.html',{},)\n\n@login_required\ndef bid(request,slug=None):\n form = AuctionsForm(request.POST or None)\n if request.method == 'POST':\n form = AuctionsForm(data=request.POST)\n bids = request.POST.get('bids', None)\n # print(bids)\n ii = SellItemInfo.objects.get(slug=slug)\n auctions_pre = Auctions.objects.filter(item=ii)\n ggg = list(auctions_pre.values('bids'))\n s = ggg[0].get('bids')\n if(s0):\n obj.delete()\n n = Notification(user=us,to=o.uploader.username,fromm=o.biders,count=slug,description=\"selected\")\n m = Notification.objects.filter(user=us,count=slug,to=o.uploader.username)\n if m.count()==0 :\n n.save()\n return HttpResponseRedirect(reverse('User:auctions'))\n\n\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import authentication, permissions\nclass PostLikeAPIToggle(APIView):\n authentication_classes = (authentication.SessionAuthentication,)\n permission_classes = (permissions.IsAuthenticated,)\n\n def get(self, request, slug=None, format=None):\n # slug = self.kwargs.get(\"slug\")\n obj = get_object_or_404(SellItemInfo, slug=slug)\n url_ = obj.get_absolute_url()\n user = self.request.user\n updated = False\n liked = False\n ne = 0\n if user.is_authenticated():\n if user in obj.likes.all():\n liked = False\n obj.likes.remove(user)\n obj.likecount-=1\n ne = obj.likecount\n obj.save()\n else:\n liked = True\n obj.likes.add(user)\n obj.likecount+=1\n ne = obj.likecount\n obj.save()\n updated = True\n data = {\n \"updated\": updated,\n \"liked\": liked,\n \"ne\" : ne\n }\n return Response(data)\n\n@login_required\ndef Purchasehistory(request):\n p = purchaseInfo.objects.filter(user=request.user).order_by(\"-timestemp\")\n args = {\n \"p\" : p\n }\n return render(request, 'firstapp/purchasehistory.html', args,)\n\n\n@login_required\ndef deleteitem(request):\n if request.method == \"POST\":\n name = request.POST.get('name', None)\n price = request.POST.get('price', None)\n slug = request.POST.get('slug', None)\n obj = SellItemInfo.objects.filter(slug=slug)\n obb = SellItemInfo.objects.get(slug=slug)\n\n p = purchaseInfo(user=request.user,itemname=slug,item_pic=obb.item_pic,buyer=name,price=price)\n p.save()\n if(obj.count()>0):\n\n obj.delete()\n\n obj1 = SellItemInfo.objects.filter(uploader=request.user)\n args = {\n \"items\" : obj1\n }\n return render(request, 'firstapp/profile.html', args,)\n\n@login_required\ndef Post(request):\n if request.method == \"POST\":\n msg = request.POST.get('msgbox', None)\n\n global other\n global iteuploader\n global teruser\n other = request.POST.get('hide', None)\n itemname = request.POST.get('itemname', None)\n iteuploader = request.POST.get('iteuploader', None)\n teruser = request.POST.get('docc',None)\n slug = request.POST.get('my',None)\n print(slug)\n # print(teruser)\n u = User.objects.get(username=iteuploader)\n\n print(u)\n if iteuploader == request.user.username:\n try:\n it = SellItemInfo.objects.get(uploader=u,slug=slug)\n print(it)\n except:\n pass\n c = Chat(user=request.user,item=it, message=msg,fromm=teruser,to=request.user.username)\n else:\n try:\n it = SellItemInfo.objects.get(uploader=u,slug=slug)\n print(it)\n except:\n pass\n c = Chat(user=request.user,item=it, message=msg,fromm=iteuploader,to=request.user.username)\n counter = SellItemInfo.objects.get(item_name=itemname)\n n = Notification(user=request.user,to=request.user.username,fromm=iteuploader,count=counter.get_slug(),description=msg)\n if iteuploader == request.user.username:\n m = Notification.objects.filter(user=request.user,count=counter.get_slug(),fromm=teruser)\n if msg != ' ':\n c.save()\n if m.count()==0 and request.user.username != iteuploader:\n n.save()\n elif m.count()==0 and request.user.username == iteuploader:\n nn = Notification(user=request.user,to=request.user.username,fromm=teruser,count=counter.get_slug(),description=msg)\n nn.save()\n else :\n m = Notification.objects.filter(user=request.user,count=counter.get_slug(),to=request.user.username)\n if msg != '':\n c.save()\n if m.count()==0 and request.user.username != iteuploader:\n n.save()\n elif m.count()==0 and request.user.username == iteuploader:\n nn = Notification(user=request.user,to=request.user.username,fromm=teruser,count=counter.get_slug(),description=msg)\n nn.save()\n\n return JsonResponse({ 'msg': msg, 'user': c.user.username })\n else:\n return HttpResponse('Request must be POST.')\n\n@login_required\ndef Messages(request,slug):\n\n print(slug)\n it = SellItemInfo.objects.get(slug=slug)\n print(it)\n c = Chat.objects.filter(item=it)\n # print(c)\n\n use = User.objects.exclude(username=request.user.username)\n # print(counter)\n hhh = list(use.values('username'))\n # print(json.dumps(hhh))\n # print(c)\n # print(request.user.username)\n # print(iteuploader)\n # print(teruser)\n return render(request, 'firstapp/messages.html', {'chat': c,'other':teruser,'iteuploader':iteuploader,'use':json.dumps(hhh) })\n\n\n\n\n@login_required\ndef Likesupdate(request,slug=None):\n\n if request.is_ajax():\n obj = SellItemInfo.objects.filter(slug=slug)\n\n obj_ = []\n\n obj_ = list(obj.values('likecount'))\n # print(json.dumps(obj_))\n return HttpResponse(json.dumps(obj_))\n\n\n@login_required\ndef Notifications(request,username='main'):\n\n if request.is_ajax():\n counter = Notification.objects.filter(fromm=request.user.username)\n # print(counter)\n hhh = list(counter.values('to','fromm','description','count','id'))\n index = 0\n lll = []\n for u in hhh:\n ss = User.objects.get(username=u.get('to'))\n bonus = UserProfileInfo.objects.filter(user=ss)\n # print(bonus)\n ggg = list(bonus.values('user','profilepic','user_id'))\n\n for o in ggg:\n # print(o.get('profilepic'))\n nnn = {\n 'id' : o.get('user'),\n 'profilepic' : o.get('profilepic'),\n 'to' : u.get('to'),\n 'description' : u.get('description'),\n 'count' : u.get('count'),\n 'fromm' : u.get('fromm')\n }\n lll.insert(index,nnn)\n index+=1\n # print(request.session['username'])\n try:\n del request.session['username']\n logout(request)\n return HttpResponseRedirect(reverse('index'))\n except KeyError:\n pass\n # print(request.session['username'])\n \n\n # print(json.dumps(lll))\n\n return HttpResponse(json.dumps(lll))\ndef compare(s1, s2):\n remove = string.punctuation + string.whitespace\n return s1.translate(None, remove) == s2.translate(None, remove)\ndef combine(list1, list2):\n list1 = iter(list1)\n for item2 in list2:\n if item2 == list2[0]:\n item1 = next(list1)\n yield ''.join(map(str, (item1, item2)))\n\n\n\ndef allitems(request,type=None):\n # print(type)\n it = SellItemInfo.objects.values('item_type').distinct()\n items_list = SellItemInfo.objects.all().order_by(\"-timestemp\")\n items_list = items_list.filter(\n Q(slug__icontains=type) |\n Q(item_name__icontains=type) |\n Q(item_location__icontains=type)|\n Q(item_type__icontains=type)\n ).distinct()\n paginator = Paginator(items_list,6)\n page_request_var = 'page'\n\n page = request.GET.get(page_request_var)\n try :\n items = paginator.page(page)\n except PageNotAnInteger:\n items = paginator.page(1)\n except:\n items = paginator.page(paginator.num_pages)\n args = {'items' : items,\"page_request_var\" : page_request_var,\"it\":it }\n return render(request,'firstapp/itemwithoulogin.html',args)\n\n\ndef Filter(request,keywrd):\n u = User.objects.get(username=request.user.username)\n counter = Notification.objects.filter(fromm=request.user.username)\n\n\n if keywrd != 'showall':\n items_list = SellItemInfo.objects.filter(item_type=keywrd).order_by(\"-timestemp\")\n else:\n keywrd = 'All'\n items_list = SellItemInfo.objects.all().order_by(\"-timestemp\")\n\n it = SellItemInfo.objects.values('item_type').distinct()\n queary = request.GET.get(\"q\")\n if queary :\n items_list = items_list.filter(\n Q(slug__icontains=queary) |\n Q(item_name__icontains=queary) |\n Q(item_location__icontains=queary)|\n Q(item_type__icontains=queary)\n ).distinct()\n\n paginator = Paginator(items_list,6)\n page_request_var = 'page'\n\n page = request.GET.get(page_request_var)\n try :\n items = paginator.page(page)\n except PageNotAnInteger:\n items = paginator.page(1)\n except:\n items = paginator.page(paginator.num_pages)\n\n # print(items_list)\n args = {'items' : items,'counter' : counter ,\"c\" : counter.count(),\"page_request_var\" : page_request_var,\"it\":it ,\"key\":keywrd}\n return args\n\n\n\n\n\n\n@login_required\ndef Filteritem(request,string):\n \n \n print(string)\n print(\"posted\")\n args = Filter(request,string)\n return render(request,'firstapp/userhome.html',args)\n\n\n@login_required\ndef userhome(request,username=None):\n print(request.POST)\n if 'showall' in request.POST :\n args = Filter(request,'showall')\n return render(request,'firstapp/userhome.html',args)\n elif 'phone' in request.POST:\n args = Filter(request,'phone')\n return render(request,'firstapp/userhome.html',args)\n elif 'guiter' in request.POST:\n args = Filter(request,'guiter')\n return render(request,'firstapp/userhome.html',args)\n elif 'laptop' in request.POST:\n args = Filter(request,'laptop')\n return render(request,'firstapp/userhome.html',args)\n elif 'tablet' in request.POST:\n args = Filter(request,'tablet')\n return render(request,'firstapp/userhome.html',args)\n elif 'camera' in request.POST:\n args = Filter(request,'camera')\n return render(request,'firstapp/userhome.html',args)\n elif 'console'in request.POST:\n args = Filter(request,'console')\n return render(request,'firstapp/userhome.html',args)\n elif 'range' in request.POST:\n # print(request.POST['range'])\n a = request.POST['range']\n u = User.objects.get(username=request.user.username)\n counter = Notification.objects.filter(fromm=request.user.username)\n items_list = SellItemInfo.objects.filter(item_exprice__lte=a).order_by(\"-timestemp\")\n it = SellItemInfo.objects.values('item_type').distinct()\n queary = request.GET.get(\"q\")\n if queary :\n items_list = items_list.filter(\n Q(slug__icontains=queary) |\n Q(item_name__icontains=queary) |\n Q(item_location__icontains=queary)|\n Q(item_type__icontains=queary)\n ).distinct()\n\n paginator = Paginator(items_list,6)\n page_request_var = 'page'\n\n page = request.GET.get(page_request_var)\n try :\n items = paginator.page(page)\n except PageNotAnInteger:\n items = paginator.page(1)\n except:\n items = paginator.page(paginator.num_pages)\n\n # print(items_list)\n args = {'items' : items,'counter' : counter ,\"c\" : counter.count(),\"page_request_var\" : page_request_var,\"it\":it,\"key\":\"All\" }\n return render(request,'firstapp/userhome.html',args)\n else:\n u = User.objects.get(username=request.user.username)\n\n counter = Notification.objects.filter(fromm=request.user.username)\n\n\n items_list = SellItemInfo.objects.all().order_by(\"-timestemp\")\n it = SellItemInfo.objects.values('item_type').distinct()\n queary = request.GET.get(\"q\")\n if queary :\n items_list = items_list.filter(\n Q(slug__icontains=queary) |\n Q(item_name__icontains=queary) |\n Q(item_location__icontains=queary)|\n Q(item_type__icontains=queary)\n ).distinct()\n\n paginator = Paginator(items_list,6)\n page_request_var = 'page'\n\n page = request.GET.get(page_request_var)\n try :\n items = paginator.page(page)\n except PageNotAnInteger:\n items = paginator.page(1)\n except:\n items = paginator.page(paginator.num_pages)\n\n # print(items_list)\n args = {'items' : items,'counter' : counter ,\"c\" : counter.count(),\"page_request_var\" : page_request_var,\"it\":it,\"key\":\"All\" }\n return render(request,'firstapp/userhome.html',args)\n\n@login_required\ndef userprofile(request,username=None,pk=None):\n i = ServerInfo.objects.all()\n # print(list(i.values('videos')))\n if pk:\n user = User.objects.get(pk=pk)\n username = user.username\n\n\n else:\n user = request.user\n username = user.username\n\n items = SellItemInfo.objects.filter(uploader=user)\n args = {'user': user,'items' : items,'i':i}\n return render(request, 'firstapp/profile.html', args,)\n\n\n\n@login_required\ndef Comment(request):\n\n\n if request.method == 'POST':\n co = request.POST['co']\n slug = request.POST['slug']\n\n # print(slug)\n # print(co)\n item = SellItemInfo.objects.get(slug=slug);\n username = request.user.username\n c = Comments(user=request.user,item=item,username=request.user.username,content=co)\n\n if co != '':\n c.save()\n\n return JsonResponse({ 'comm': co, 'user': request.user.username,'timestemp':c.timestemp,'profilepic' : request.user.userprofileinfo.profilepic.url })\n else:\n return HttpResponse('Request must be POST.')\n@login_required\ndef showitem(request,slug=None,id=None):\n\n\n instance = get_object_or_404(SellItemInfo,slug=slug);\n # instance = SellItemInfo.objects.get(item_name=item_name)\n comments = Comments.objects.filter(item=instance);\n\n\n c = Chat.objects.filter(user=request.user)\n if iteuploader == request.user.username:\n v = Chat.objects.all()\n else:\n v = Chat.objects.filter(fromm=teruser)\n # u = request.get('id')\n global nam\n namw = \"\"\n global slug_\n slug_ = slug\n obj = get_object_or_404(SellItemInfo, slug=slug)\n user = request.user\n liked = False\n if user.is_authenticated():\n if user in obj.likes.all():\n liked = \"Unlike\"\n else:\n liked = \"Like\"\n\n if slug!=None:\n try:\n ins = Notification.objects.get(count=slug,fromm=request.user.username)\n # print(ins)\n i = Notification.objects.get(count=slug,fromm=request.user.username)\n namw = i.to\n\n ins.delete()\n\n except ObjectDoesNotExist:\n ins = None\n i = None\n namw = \"\"\n\n\n # print(ins)\n\n\n # r = RatingInfo.objects.filter(item=instance)\n r = RatingInfo.objects.filter(item=instance).values('rate').annotate(total=Count('rate')).order_by('-rate')\n print(r)\n use = User.objects.exclude(username=request.user.username)\n # print(counter)\n hhh = list(use.values('username'))\n al = SellItemInfo.objects.all().exclude(slug=slug).exclude(uploader=request.user)\n print(al)\n # print(json.dumps(hhh))\n # for r in instance:\n # r.delete()\n nam = namw\n\n args = {\n \"instance\" : instance,\n 'chat': c,\n 'nam' : nam,\n \"liked\": liked,\n \"obj\" : obj,\n \"comments\" : comments,\n \"v\" : v,\n \"use\" : json.dumps(hhh),\n \"r\" : r,\n \"al\" : al,\n\n }\n return render(request, 'firstapp/details.html', args,)\n\n@login_required\ndef sellitem(request):\n\n isposted = False\n\n if request.method == \"POST\":\n # userform = UserForm(data=request.POST)\n selliteminfo = SellItemInfoForm(data=request.POST)\n\n if selliteminfo.is_valid():\n # user = userform.save()\n # user.set_password(user.password)\n # user.save()\n\n item = selliteminfo.save(commit=False)\n item.uploader = request.user\n item.save()\n # profile.user = user\n\n if 'item_pic' in request.FILES:\n item.item_pic = request.FILES['item_pic']\n\n item.save()\n isposted = True\n\n\n else:\n # userform = UserForm()\n selliteminfo = SellItemInfoForm() #sett item forms\n\n return render(request,'firstapp/sellitem.html',\n {\n\n 'selliteminfo':selliteminfo,\n 'isposted':isposted\n })\n","sub_path":"User/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":23973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"624583039","text":"import tweepy\nauth = tweepy.OAuthHandler(x,y)\nauth.set_access_token(a,b)\napi = tweepy.API(auth)\n\ndef pick_url(status):\n # pick media url from status\n if not isinstance(status,dict):\n status = status._json\n return status['extended_entities']['media'][0]['media_url_https']\n\ndef pick_id(status):\n # pick id from status\n if not isinstance(status,dict):\n status = status._json\n return status['id']\n\ndef upload(file,status):\n media = api.update_with_media(file,status)\n return pick_id(media),pick_url(media)\n\ndef get_pic(id):\n status = api.get_status(id)\n return pick_url(status)\n\nid,url = upload('lol.png','cats and dogs')\nurl = get_pic(id)\n","sub_path":"tweethost.py","file_name":"tweethost.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"529612269","text":"import unittest\nfrom sample.SolarAge import *\nfrom parameterized import parameterized, parameterized_class\n\nclass SolarAgeParameterizedTest(unittest.TestCase):\n\n def setUp(self):\n self.temp = SolarAge()\n\n @parameterized.expand([\n (31557600, \"Ziemia\", 1),\n (5215621652, \"Wenus\", 268.65),\n (125161212, \"jowisz\", 0.33),\n (245152121, \"Neptun\", 0.47)\n ])\n def test_solar_age_positive(self, seconds, planet, expected):\n self.assertEqual(self.temp.game(seconds, planet), expected)\n\n @parameterized.expand([\n (\"24112\", \"Ziemia\", \"Wrong arguments!\"),\n (5215621652, 130, \"Wrong arguments!\"),\n (True, \"jowisz\", \"Wrong arguments!\"),\n (245152121, False, \"Wrong arguments!\")\n ])\n def test_solar_age_exceptions(self, seconds, planet, expected):\n self.assertRaisesRegex(Exception, expected, self.temp.game, seconds, planet)\n\n\n@parameterized_class((\"seconds\", \"planet\", \"expected\"), [\n (521521521, \"Merkury\", 68.62),\n (598218952198, \"saturn\", 643.74),\n (1214211111211, \"Uran\", 4576.89),\n (421421412, \"Mars\", 7.1)\n])\nclass SolarAgeParameterizedTestClass(unittest.TestCase):\n\n def setUp(self):\n self.temp = SolarAge()\n\n def test_solar_age_positive_class(self):\n self.assertEqual(self.temp.game(self.seconds, self.planet), self.expected)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/SolarAgeParameterizedTest.py","file_name":"SolarAgeParameterizedTest.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"456348906","text":"from .settings import settings\nimport json\nimport urllib.request\nfrom api.database import SessionLocal, engine\nfrom api.models import DbStop\nfrom geoalchemy2 import functions\n\n\ndef run():\n \"\"\"\n Adapter to grab stops from the API of the City of Amsterdam\n via https://api.data.amsterdam.nl/dcatd/datasets/IuAYhr-__qZj9Q/purls/uEOyRO9EKBNIeA\n \"\"\"\n connect_string = settings.AMSTERDAM_STOPS\n url = urllib.request.urlopen(connect_string)\n if url.getcode() == 200:\n data = url.read()\n # Start inserting\n result = json.loads(data)\n db = SessionLocal()\n\n try:\n DbStop.__table__.create(engine)\n except:\n pass\n\n for entry in result[\"in_uitstaphaltes\"]:\n row = DbStop(\n source_url=settings.AMSTERDAM_STOPS,\n source_name=\"Amsterdam\",\n source_id=entry[\"in_uitstaphalte\"][\"title\"].split(\":\")[0],\n title=entry[\"in_uitstaphalte\"][\"title\"],\n name=entry[\"in_uitstaphalte\"][\"title\"].split(\":\")[1].strip(),\n description=entry[\"in_uitstaphalte\"][\"Bijzonderheden\"],\n spots_text=entry[\"in_uitstaphalte\"][\"Busplaatsen\"],\n spots=int(entry[\"in_uitstaphalte\"][\"Busplaatsen\"].split(\" \")[0]),\n point=functions.ST_GeomFromGeoJSON(entry[\"in_uitstaphalte\"][\"Lokatie\"])\n\n )\n db.merge(row)\n db.commit()\n","sub_path":"adapters/amsterdam/stops.py","file_name":"stops.py","file_ext":"py","file_size_in_byte":1437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"203738529","text":"import setuptools\n\nwith open(\"README.md\", \"r\") as f:\n long_description = f.read()\n\nsetuptools.setup(\n name=\"pylambdarest\",\n version=\"0.0.7\",\n author=\"Marwan Debbiche\",\n author_email=\"marwan.debbiche@gmail.com\",\n description=\"REST framework for serverless API (AWS Lambda + API Gateway)\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/MarwanDebbiche/pylambdarest\",\n packages=['pylambdarest'],\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n python_requires='>=3.8',\n install_requires=['jsonschema']\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"365333203","text":"######################################\n##Author: Ashish Anand\n##Date: 13 Dec 2011\n## Intent: Feed two sony ericssons vcf phonebooks and find those contacts which are present in others pb and not in John's contacts\n######################################\n_JOHNFILE=\"John.vcf\"\n_KOSHIFILE=\"koshi.vcf\"\n_DELTAFILE=\"B:\\\\Desktop\\\\DeltaContacts.vcf\"\n\nfrom UtilSonyPhoneBook import ParseVCardFile\nfrom UtilSonyPhoneBook import ContactList\n\ndef main():\n missingContacts = FindMissingContactsInJohnsBook(_JOHNFILE, _KOSHIFILE)\n PrintContactsToFile(_DELTAFILE, missingContacts)\n\ndef PrintContactsToFile(filePath, missingContacts):\n with open(filePath, \"w\") as f:\n ctr = 0\n for contact in missingContacts:\n contact.PrintAsVCard(f)\n ctr+=1\n print(\"Adding an entry for: \" + contact.name)\n print(str(ctr) + \" new entries written in \" + str(filePath))\n return\n\n\n\ndef FindMissingContactsInJohnsBook(johnFile, KoshiFile):\n johnContacts = ParseVCardFile(johnFile)\n koshiContacts = ParseVCardFile(KoshiFile)\n missingContacts = ContactList()\n for cn in koshiContacts:\n if cn not in johnContacts:\n missingContacts.append(cn)\n return missingContacts\n\nif __name__ == '__main__':\n try:\n main()\n except (RuntimeError, IOError) as err:\n print(\"Exception caught in main()-> {}\".format(str(err)))\n raise\n finally:\n #input(\"Press Enter to continue...\")\n pass\n","sub_path":"SonyPhoneBookMerge/Merge.py","file_name":"Merge.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"583336587","text":"from django.urls import path\n\nfrom announcements.views import AnnouncementAdminView, CreateAnnouncementView, EditAnnouncementView, \\\n DeleteAnnouncementView\n\nurlpatterns = [\n path('admin/', AnnouncementAdminView.as_view(), name=\"announcement_admin\"),\n path('create/', CreateAnnouncementView.as_view(), name=\"create_announcement\"),\n path('/edit/', EditAnnouncementView.as_view(), name=\"edit_announcement\"),\n path('/delete/', DeleteAnnouncementView.as_view(), name=\"delete_announcement\"),\n]\n","sub_path":"announcements/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"608700450","text":"import xmltodict\nimport slugify\nimport api\nimport common_functions as cf\n\nelection_id = 'europarl.europa.eu-cz-2004'\npath = '../data/EP2004reg/'\n\nwith open(path + \"eprkl_utf8.xml\") as fd:\n obj = xmltodict.parse(fd.read())\n\nparties = []\nfor item in obj['EP_RKL']['EP_RKL_ROW']:\n option = {\n 'id': slugify.slugify(item['NAZEVCELK']),\n 'identifier': item['VSTRANA'],\n 'name': item['NAZEVCELK'],\n 'type': 'organization',\n }\n cf.post_if_not_exist(\"options\", option, {\"identifier\": option['identifier']})\n\n other_names = [\n {\n 'name': item['NAZEV_STRE'],\n 'note': 'short_name_60',\n 'election_id': election_id\n },\n {\n 'name': item['ZKRATKAE30'],\n 'note': 'short_name_30',\n 'election_id': election_id\n },\n {\n 'name': item['ZKRATKAE8'],\n 'note': 'abbreviation',\n 'election_id': election_id \n }\n ]\n for other_name in other_names:\n cf.put_property_if_not_exist(\"options\", option, {\"identifier\": option['identifier']}, 'other_names', other_name) \n\n identifier = {\n 'identifier': item['ESTRANA'],\n 'election_id': election_id\n }\n cf.put_property_if_not_exist(\"options\", option, {\"identifier\": option['identifier']}, 'other_identifiers', identifier)\n","sub_path":"scripts/options_extractor_ep2004.py","file_name":"options_extractor_ep2004.py","file_ext":"py","file_size_in_byte":1426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"254431853","text":"# -*- coding: utf-8 -*-\nimport logging\nimport json\n\nfrom db.pay_record.model import PayRecord, PAY_STATUS\nfrom db.account.model import Appid\nfrom datetime import timedelta\nimport datetime\n\n_LOGGER = logging.getLogger(__name__)\n\n\ndef ban_dead_appid_():\n hours = 72\n now = datetime.datetime.utcnow()\n appid_objs = Appid.query.filter(Appid.valid == True).all()\n for appid_obj in appid_objs:\n if now - appid_obj.created_at < timedelta(hours=hours):\n continue\n appid = appid_obj.appid\n last_success_pay = PayRecord.query.filter(PayRecord.appid == appid) \\\n .filter(PayRecord.pay_status == PAY_STATUS.PAY_SUCCESS) \\\n .order_by(PayRecord.created_at.desc()).first()\n if not last_success_pay or \\\n now - last_success_pay.created_at >= timedelta(hours=hours):\n extend = json.loads(appid_obj.extend or '{}') or {}\n extend['banned_for'] = '72 hours no success pay'\n appid_obj.extend = json.dumps(extend)\n appid_obj.valid = False\n appid_obj.save()\n _LOGGER.info('ban dead appid [%s]' % appid)\n","sub_path":"pay-http/script/appid_risk_control.py","file_name":"appid_risk_control.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"295416357","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\"Makes working with XML feel like you are working with JSON\"\n\nfrom __future__ import print_function\n\nfrom xml.parsers import expat\nfrom xml.sax.saxutils import XMLGenerator\nfrom xml.sax.xmlreader import AttributesImpl\nfrom gi.repository import GObject, Soup\n\nimport sys, re, dbus\n\ntry: # pragma no cover\n import feedparser\nexcept ImportError: # pragma no cover\n feedparser = None\ntry: # pragma no cover\n from urllib.parse import urlparse\nexcept ImportError: # pragma no cover\n from urlparse import urlparse\ntry: # pragma no cover\n import json\nexcept ImportError: # pragma no cover\n import simplejson as json\n\ntry: # pragma no cover\n from cStringIO import StringIO\nexcept ImportError: # pragma no cover\n try:\n from StringIO import StringIO\n except ImportError:\n from io import StringIO\ntry: # pragma no cover\n from collections import OrderedDict\nexcept ImportError: # pragma no cover\n try:\n from ordereddict import OrderedDict\n except ImportError:\n OrderedDict = dict\n\ntry: # pragma no cover\n _basestring = basestring\nexcept NameError: # pragma no cover\n _basestring = str\ntry: # pragma no cover\n _unicode = unicode\nexcept NameError: # pragma no cover\n _unicode = str\n\n__author__ = 'Martin Blech'\n__version__ = '0.9.2'\n__license__ = 'MIT'\n\nSOUP_STATUS_CANCELLED = 1\n\nclass Downloader(GObject.GObject):\n __gsignals__ = {\n 'progress': (GObject.SignalFlags.RUN_FIRST,\n None,\n ([float])),\n 'got-chunk': (GObject.SignalFlags.RUN_FIRST,\n None,\n (object,)),\n 'complete': (GObject.SignalFlags.RUN_FIRST,\n None,\n (object,)),\n }\n \n def __init__(self, url, session=None, request_headers=None):\n GObject.GObject.__init__(self)\n self._uri = Soup.URI.new(url)\n self._session = session\n self._get_soup_session()\n self._pending_buffers = []\n self._downloaded_size = 0\n self._total_size = 0\n self._cancelling = False\n self._status_code = None\n self._output_file = None\n self._output_stream = None\n self._message = None\n self._request_headers = request_headers\n\n def _get_soup_session(self):\n if self._session is None:\n self._session = Soup.SessionAsync()\n self._session.set_property(\"timeout\", 60)\n self._session.set_property(\"idle-timeout\", 60)\n #self._session.set_property(\"user-agent\", \"cinnamon/%s\" % config.version)\n self._session.add_feature_by_type(Soup.ProxyResolverDefault)\n return self._session\n \n def _setup_message(self, method=\"GET\"):\n self._message = Soup.Message(method=method, uri=self._uri)\n self._message.connect('got-chunk', self._got_chunk_cb)\n self._message.connect('got-headers', self._headers_cb, None)\n if self._request_headers is not None:\n for header_key in self._request_headers.keys():\n self._message.request_headers.append(\n header_key, self._request_headers[header_key])\n\n def _soup_status_is_successful(self, status):\n return status >= 200 and status < 300\n\n def download_to_temp(self):\n \"\"\"\n Download the contents of the provided URL to temporary file storage.\n Use .get_local_file_path() to find the location of where the file\n is saved. Upon completion, a successful download is indicated by a\n result of None in the complete signal parameters.\n \"\"\"\n url = self._uri.to_string(False)\n temp_file_path = self._get_temp_file_path(url)\n self._output_file = Gio.File.new_for_path(temp_file_path)\n self._output_stream = self._output_file.create(\n Gio.FileCreateFlags.PRIVATE, None)\n self.download_chunked()\n \n def download_chunked(self):\n \"\"\"\n Download the contents of the provided URL into memory. The download\n is done in chunks, and each chunk is emitted over the 'got-chunk'\n signal. Upon completion, a successful download is indicated by a\n reuslt of None in the complete signal parameters.\n \"\"\"\n self._setup_message()\n self._message.response_body.set_accumulate(False)\n self._session.queue_message(self._message, self._message_cb, None)\n \n def download(self, start=None, end=None):\n \"\"\"\n Download the contents of the provided URL into memory.\n Upon completion, the downloaded data will be passed as GBytes to the\n result parameter of the complete signal handler.\n The start and end parameters can optionally be set to perform a\n partial read of the remote data.\n \"\"\"\n self._setup_message()\n if start is not None:\n self._message.request_headers.set_range(start, end)\n self._session.queue_message(self._message, self._message_cb, None)\n \n def get_size(self):\n \"\"\"\n Perform a HTTP HEAD request to find the size of the remote content.\n The size is returned in the result parameter of the 'complete' signal.\n \"\"\"\n self._setup_message(\"HEAD\")\n self._session.queue_message(self._message, self._message_cb, None)\n \n def _message_cb(self, session, message, user_data):\n self._status_code = message.status_code\n self._check_if_finished()\n \n def cancel(self):\n self._cancelling = True\n self._session.cancel_message(self._message, SOUP_STATUS_CANCELLED)\n \n def _headers_cb(self, message, user_data):\n if self._soup_status_is_successful(message.status_code):\n self._total_size = message.response_headers.get_content_length()\n \n def _got_chunk_cb(self, message, buf):\n if self._cancelling or \\\n not self._soup_status_is_successful(message.status_code):\n return\n \n data = buf.get_as_bytes()\n self.emit('got-chunk', data)\n if self._output_stream:\n self._pending_buffers.append(data)\n self._write_next_buffer()\n \n def __write_async_cb(self, output_stream, result, user_data):\n count = output_stream.write_bytes_finish(result)\n \n self._downloaded_size += count\n if self._total_size > 0:\n progress = self._downloaded_size / float(self._total_size)\n self.emit('progress', progress)\n \n self._check_if_finished()\n \n def _complete(self):\n if self._output_stream:\n self._output_stream.close(None)\n \n result = None\n if self._soup_status_is_successful(self._status_code):\n if self._message.method == \"HEAD\":\n # this is a get_size request\n result = self._total_size\n elif self._message.response_body.get_accumulate():\n # the message body must be flattened so that it can be\n # retrieved as GBytes because response_body.data gets\n # incorrectly treated by introspection as a NULL-terminated\n # string\n # https://bugzilla.gnome.org/show_bug.cgi?id=704105\n result = self._message.response_body.flatten().get_as_bytes()\n else:\n result = IOError(\"HTTP error code %d\" % self._status_code)\n\n self.emit('complete', result)\n \n def _check_if_finished(self):\n # To finish (for both successful completion and cancellation), we\n # require two conditions to become true:\n # 1. Soup message callback has been called\n # 2. Any pending output file write completes\n # Those conditions can become true in either order.\n if not self._output_stream:\n self._complete()\n return\n \n if self._cancelling or not self._pending_buffers:\n if self._status_code is not None \\\n and not self._output_stream.has_pending():\n self._complete()\n return\n\n self._write_next_buffer()\n \n def _write_next_buffer(self):\n if not self._output_stream.has_pending():\n data = self._pending_buffers.pop(0)\n self._output_stream.write_bytes_async(data, GObject.PRIORITY_LOW,\n None, self.__write_async_cb,\n None)\n '''\n def get_string_from_bytes(self, bytes_data):\n istream = Gio.MemoryInputStream.new()\n istream.add_bytes(bytes_data)\n if not self.istream.is_closed():\n self.istream.close(None)\n return \n '''\n\n def _get_temp_file_path(self, uri):\n # TODO: Should we use the HTTP headers for the file name?\n scheme_, netloc_, path, params_, query_, fragment_ = \\\n urlparse(uri)\n path = os.path.basename(path)\n\n tmp_dir = os.path.join(env.get_profile_path(), 'data')\n base_name, extension_ = os.path.splitext(path)\n fd, file_path = tempfile.mkstemp(dir=tmp_dir,\n prefix=base_name, suffix=extension_)\n os.close(fd)\n os.unlink(file_path)\n\n return file_pat\n\nclass ParsingInterrupted(Exception):\n pass\n\n\nclass _DictSAXHandler(object):\n def __init__(self,\n item_depth=0,\n item_callback=lambda *args: True,\n xml_attribs=True,\n attr_prefix='@',\n cdata_key='#text',\n force_cdata=False,\n cdata_separator='',\n postprocessor=None,\n dict_constructor=OrderedDict,\n strip_whitespace=True,\n namespace_separator=':',\n namespaces=None):\n self.path = []\n self.stack = []\n self.data = None\n self.item = None\n self.item_depth = item_depth\n self.xml_attribs = xml_attribs\n self.item_callback = item_callback\n self.attr_prefix = attr_prefix\n self.cdata_key = cdata_key\n self.force_cdata = force_cdata\n self.cdata_separator = cdata_separator\n self.postprocessor = postprocessor\n self.dict_constructor = dict_constructor\n self.strip_whitespace = strip_whitespace\n self.namespace_separator = namespace_separator\n self.namespaces = namespaces\n\n def _build_name(self, full_name):\n if not self.namespaces:\n return full_name\n i = full_name.rfind(self.namespace_separator)\n if i == -1:\n return full_name\n namespace, name = full_name[:i], full_name[i+1:]\n short_namespace = self.namespaces.get(namespace, namespace)\n if not short_namespace:\n return name\n else:\n return self.namespace_separator.join((short_namespace, name))\n\n def _attrs_to_dict(self, attrs):\n if isinstance(attrs, dict):\n return attrs\n return self.dict_constructor(zip(attrs[0::2], attrs[1::2]))\n\n def startElement(self, full_name, attrs):\n name = self._build_name(full_name)\n attrs = self._attrs_to_dict(attrs)\n self.path.append((name, attrs or None))\n if len(self.path) > self.item_depth:\n self.stack.append((self.item, self.data))\n if self.xml_attribs:\n attrs = self.dict_constructor(\n (self.attr_prefix+key, value)\n for (key, value) in attrs.items())\n else:\n attrs = None\n self.item = attrs or None\n self.data = None\n\n def endElement(self, full_name):\n name = self._build_name(full_name)\n if len(self.path) == self.item_depth:\n item = self.item\n if item is None:\n item = self.data\n should_continue = self.item_callback(self.path, item)\n if not should_continue:\n raise ParsingInterrupted()\n if len(self.stack):\n item, data = self.item, self.data\n self.item, self.data = self.stack.pop()\n if self.strip_whitespace and data is not None:\n data = data.strip() or None\n if data and self.force_cdata and item is None:\n item = self.dict_constructor()\n if item is not None:\n if data:\n self.push_data(item, self.cdata_key, data)\n self.item = self.push_data(self.item, name, item)\n else:\n self.item = self.push_data(self.item, name, data)\n else:\n self.item = self.data = None\n self.path.pop()\n\n def characters(self, data):\n if not self.data:\n self.data = data\n else:\n self.data += self.cdata_separator + data\n\n def push_data(self, item, key, data):\n if self.postprocessor is not None:\n result = self.postprocessor(self.path, key, data)\n if result is None:\n return item\n key, data = result\n if item is None:\n item = self.dict_constructor()\n try:\n value = item[key]\n if isinstance(value, list):\n value.append(data)\n else:\n item[key] = [value, data]\n except KeyError:\n item[key] = data\n return item\n\nclass XMLToJSON():\n def __init__(self):\n self.loop = GObject.MainLoop() \n\n def xml_to_json_format(self, xlm_string): \n result = self.parse(xlm_string)\n return json.dumps (result)\n\n def download_xml_to_string(self, request_id, request_url):\n downloader = Downloader(request_url)\n downloader.download()\n downloader.connect('complete', self.on_download_complete, request_id)\n self.loop.run()\n\n def on_download_complete(self, downloader, result, request_id):\n self.loop.quit()\n if result is not None:\n xml_string = result.get_data()\n try:\n xml_string = str(xml_string, encoding='UTF-8')\n except:\n pass\n regex = re.compile(r\"^<\\?xml\\s+.*\\?>$\", re.IGNORECASE)\n xml_string = regex.sub(\"\", xml_string)\n json_string = self.xml_to_json_format(xml_string)\n else:\n json_string = \"\"\n try:\n session_bus = dbus.SessionBus()\n dbus_object = session_bus.get_object(\"org.Cinnamon.FeedReader\", \"/org/Cinnamon/FeedReader\")\n if(dbus_object):\n SetJsonResult = dbus_object.get_dbus_method('SetJsonResult', 'org.Cinnamon.FeedReader')\n if(SetJsonResult):\n SetJsonResult(request_id, json_string)\n except:\n print(\"Error, could not find a Dbus implementation.\")\n \n def parse(self, xml_input, encoding=None, expat=expat, process_namespaces=False,\n namespace_separator=':', **kwargs):\n \"\"\"Parse the given XML input and convert it into a dictionary.\n\n `xml_input` can either be a `string` or a file-like object.\n\n If `xml_attribs` is `True`, element attributes are put in the dictionary\n among regular child elements, using `@` as a prefix to avoid collisions. If\n set to `False`, they are just ignored.\n\n Simple example::\n\n >>> import xmltodict\n >>> doc = xmltodict.parse(\\\"\\\"\\\"\n ... \n ... 1\n ... 2\n ... \n ... \\\"\\\"\\\")\n >>> doc['a']['@prop']\n u'x'\n >>> doc['a']['b']\n [u'1', u'2']\n\n If `item_depth` is `0`, the function returns a dictionary for the root\n element (default behavior). Otherwise, it calls `item_callback` every time\n an item at the specified depth is found and returns `None` in the end\n (streaming mode).\n\n The callback function receives two parameters: the `path` from the document\n root to the item (name-attribs pairs), and the `item` (dict). If the\n callback's return value is false-ish, parsing will be stopped with the\n :class:`ParsingInterrupted` exception.\n\n Streaming example::\n\n >>> def handle(path, item):\n ... print('path:%s item:%s' % (path, item))\n ... return True\n ...\n >>> xmltodict.parse(\\\"\\\"\\\"\n ... \n ... 1\n ... 2\n ... \\\"\\\"\\\", item_depth=2, item_callback=handle)\n path:[(u'a', {u'prop': u'x'}), (u'b', None)] item:1\n path:[(u'a', {u'prop': u'x'}), (u'b', None)] item:2\n\n The optional argument `postprocessor` is a function that takes `path`,\n `key` and `value` as positional arguments and returns a new `(key, value)`\n pair where both `key` and `value` may have changed. Usage example::\n\n >>> def postprocessor(path, key, value):\n ... try:\n ... return key + ':int', int(value)\n ... except (ValueError, TypeError):\n ... return key, value\n >>> xmltodict.parse('12x',\n ... postprocessor=postprocessor)\n OrderedDict([(u'a', OrderedDict([(u'b:int', [1, 2]), (u'b', u'x')]))])\n\n You can pass an alternate version of `expat` (such as `defusedexpat`) by\n using the `expat` parameter. E.g:\n\n >>> import defusedexpat\n >>> xmltodict.parse('hello', expat=defusedexpat.pyexpat)\n OrderedDict([(u'a', u'hello')])\n\n \"\"\"\n handler = _DictSAXHandler(namespace_separator=namespace_separator,\n **kwargs)\n if isinstance(xml_input, _unicode):\n if not encoding:\n encoding = 'utf-8'\n xml_input = xml_input.encode(encoding)\n if not process_namespaces:\n namespace_separator = None\n parser = expat.ParserCreate(\n encoding,\n namespace_separator\n )\n try:\n parser.ordered_attributes = True\n except AttributeError:\n # Jython's expat does not support ordered_attributes\n pass\n parser.StartElementHandler = handler.startElement\n parser.EndElementHandler = handler.endElement\n parser.CharacterDataHandler = handler.characters\n parser.buffer_text = True\n try:\n parser.ParseFile(xml_input)\n except (TypeError, AttributeError):\n parser.Parse(xml_input, True)\n return handler.item\n\n\n def _emit(self, key, value, content_handler,\n attr_prefix='@',\n cdata_key='#text',\n depth=0,\n preprocessor=None,\n pretty=False,\n newl='\\n',\n indent='\\t',\n full_document=True):\n if preprocessor is not None:\n result = preprocessor(key, value)\n if result is None:\n return\n key, value = result\n if not isinstance(value, (list, tuple)):\n value = [value]\n if full_document and depth == 0 and len(value) > 1:\n raise ValueError('document with multiple roots')\n for v in value:\n if v is None:\n v = OrderedDict()\n elif not isinstance(v, dict):\n v = _unicode(v)\n if isinstance(v, _basestring):\n v = OrderedDict(((cdata_key, v),))\n cdata = None\n attrs = OrderedDict()\n children = []\n for ik, iv in v.items():\n if ik == cdata_key:\n cdata = iv\n continue\n if ik.startswith(attr_prefix):\n attrs[ik[len(attr_prefix):]] = iv\n continue\n children.append((ik, iv))\n if pretty:\n content_handler.ignorableWhitespace(depth * indent)\n content_handler.startElement(key, AttributesImpl(attrs))\n if pretty and children:\n content_handler.ignorableWhitespace(newl)\n for child_key, child_value in children:\n self._emit(child_key, child_value, content_handler,\n attr_prefix, cdata_key, depth+1, preprocessor,\n pretty, newl, indent)\n if cdata is not None:\n content_handler.characters(cdata)\n if pretty and children:\n content_handler.ignorableWhitespace(depth * indent)\n content_handler.endElement(key)\n if pretty and depth:\n content_handler.ignorableWhitespace(newl)\n\n\n def unparse(self, input_dict, output=None, encoding='utf-8', full_document=True,\n **kwargs):\n \"\"\"Emit an XML document for the given `input_dict` (reverse of `parse`).\n\n The resulting XML document is returned as a string, but if `output` (a\n file-like object) is specified, it is written there instead.\n\n Dictionary keys prefixed with `attr_prefix` (default=`'@'`) are interpreted\n as XML node attributes, whereas keys equal to `cdata_key`\n (default=`'#text'`) are treated as character data.\n\n The `pretty` parameter (default=`False`) enables pretty-printing. In this\n mode, lines are terminated with `'\\n'` and indented with `'\\t'`, but this\n can be customized with the `newl` and `indent` parameters.\n\n \"\"\"\n if full_document and len(input_dict) != 1:\n raise ValueError('Document must have exactly one root.')\n must_return = False\n if output is None:\n output = StringIO()\n must_return = True\n content_handler = XMLGenerator(output, encoding)\n if full_document:\n content_handler.startDocument()\n for key, value in input_dict.items():\n self._emit(key, value, content_handler, full_document=full_document,\n **kwargs)\n if full_document:\n content_handler.endDocument()\n if must_return:\n value = output.getvalue()\n try: # pragma no cover\n value = value.decode(encoding)\n except AttributeError: # pragma no cover\n pass\n return value\n\ndef native_feedparser(request_id, request_url):\n feed = feedparser.parse(request_url)\n \n info = {}\n \n info[\"title\"] = feed[\"feed\"][\"title\"]\n info[\"description\"] = feed[\"feed\"][\"description\"]\n info[\"link\"] = feed[\"feed\"][\"link\"]\n \n #image is optional in the rss spec\n imageInfo = {}\n if \"image\" in feed[\"feed\"]:\n img = feed[\"feed\"][\"image\"]\n imageInfo[\"url\"] = img[\"url\"]\n imageInfo[\"width\"] = img[\"width\"]\n imageInfo[\"height\"] = img[\"height\"]\n elif \"logo\" in feed[\"feed\"]:\n imageInfo[\"url\"] = feed[\"feed\"][\"logo\"]\n\n info[\"image\"] = imageInfo\n info[\"entries\"] = []\n for item in feed[\"entries\"]:\n itemInfo = {}\n #guid is optional, so use link if it's not given\n if \"guid\" in item:\n itemInfo[\"id\"] = item[\"guid\"]\n else:\n itemInfo[\"id\"] = item[\"link\"]\n itemInfo[\"title\"] = item[\"title\"]\n itemInfo[\"link\"] = item[\"link\"]\n itemInfo[\"description\"] = item[\"description\"]\n info[\"entries\"].append(itemInfo)\n\n json_string = json.dumps({\"native\": info})\n\n try:\n session_bus = dbus.SessionBus()\n dbus_object = session_bus.get_object(\"org.Cinnamon.FeedReader\", \"/org/Cinnamon/FeedReader\")\n if(dbus_object):\n SetJsonResult = dbus_object.get_dbus_method('SetJsonResult', 'org.Cinnamon.FeedReader')\n if(SetJsonResult):\n SetJsonResult(request_id, json_string)\n except:\n print(\"Error, could not find a Dbus implementation.\")\n\nif __name__ == '__main__': # pragma: no cover\n if len(sys.argv) == 3:\n request_id = sys.argv[1]\n request_url = sys.argv[2]\n if(feedparser is not None):\n native_feedparser(request_id, request_url)\n else:\n xmltojson = XMLToJSON()\n xmltojson.download_xml_to_string(request_id, request_url)\n else:\n print(\"Invalid number of parameters\")\n","sub_path":"xmltojson.py","file_name":"xmltojson.py","file_ext":"py","file_size_in_byte":24373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"69101824","text":"import datetime\nimport pandas as pd\nimport numpy as np\nimport pickle\n\nfrom .utils import (compute_elo_ratting_dataframe_for_champ_v2, compute_elo_ratting_dataframe_for_champ_v3, delete_directory_contents)\nfrom os import sys, path\nsys.path.append(path.dirname(path.dirname(path.abspath(__file__))))\n\nclass Scoring(object):\n \"\"\"docstring for Scoring.\"\"\"\n def __init__(self, data=None, champs=None, teams=None):\n super(Scoring, self).__init__()\n self.teams = np.array(teams) # list\n self.data = data\n self.champs = champs\n\n def step_1_get_champs_specific_to_teams(self):\n data_of_interest = self.data[['home_team', 'away_team','championship']]\n champs = data_of_interest[data_of_interest.home_team.isin(self.teams)].championship.dropna().drop_duplicates().values\n del data_of_interest\n return champs\n\n def step_2_compute_scores_for_each_champ(self):\n champs = self.step_1_get_champs_specific_to_teams()\n elo_df = compute_elo_ratting_dataframe_for_champ_v2(self.data, champs)\n try:\n elo_df.to_csv('../data/elo_ratings/ratings/elo.csv')\n except Exception as e:\n elo_df.to_csv('./data/elo_ratings/ratings/elo.csv')\n return elo_df\n\n def step_2_1(self):\n jfile = {}\n\n try:\n delete_directory_contents('../data/elo_ratings/ratings/')\n except Exception as e:\n delete_directory_contents('./data/elo_ratings/ratings/')\n\n for champ in self.champs[:1]:\n print('[INFO]: ', champ)\n\n try:\n elo_df = compute_elo_ratting_dataframe_for_champ_v3(self.data, [champ]).iloc[:10]\n jfile = {champ:elo_df}\n except Exception as e:\n print('[ERROR]: Scoring-step_2_1', champ, e)\n return jfile\n\n\n def savit(self):\n print('[SAVING]...')\n try:\n with open('../data/elo_ratings/ratings/data.pkl', 'wb') as handle:\n pickle.dump(jsfile, handle, protocol=pickle.HIGHEST_PROTOCOL)\n except Exception as e:\n with open('./data/elo_ratings/ratings/data.pkl', 'wb') as handle:\n pickle.dump(jsfile, handle, protocol=pickle.HIGHEST_PROTOCOL)\n \n def main(self):\n if self.champs is not None:\n self.step_2_1()\n\nif __name__ == '__main__':\n df = pd.read_csv('/home/kasper/Dropbox/Scrapping/soccerway/csv/final_data_soccerway.csv', index_col='Unnamed: 0')\n df.loc[:,'date'] = pd.to_datetime(df.date)\n\n input_date = datetime.datetime(2018,1,31)\n input_data = df[df.date==input_date]\n training_data = df.loc[:input_data.index[0]-1]\n\n home_teams = input_data.home_team.dropna().drop_duplicates().values\n teams_grouped = df.groupby('home_team').size()\n home_teams_consider = teams_grouped[home_teams].sort_values(ascending=False)\n\n away_teams = input_data.away_team.dropna().drop_duplicates().values\n teams_grouped = df.groupby('away_team').size()\n away_teams_consider = teams_grouped[away_teams].sort_values(ascending=False)\n\n threshold = 300\n home_final_teams = home_teams_consider[home_teams_consider > threshold].index\n away_final_teams = away_teams_consider[away_teams_consider > threshold].index\n\n final_matches = input_data[(input_data.home_team.isin(home_final_teams)) & (input_data.away_team.isin(away_final_teams))]\n final_matches.to_csv('../data/predict.csv')\n champs_to_keep = final_matches.championship.dropna().drop_duplicates().values\n\n score = Scoring(data = training_data, champs= champs_to_keep, teams=None)\n elo_df = score.main()\n","sub_path":"preprocessing/step_1.py","file_name":"step_1.py","file_ext":"py","file_size_in_byte":3617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"15389131","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def rightSideView(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[int]\n \"\"\"\n data = []\n height = 0\n _rightSideView(root, data, height)\n return (data)\n\n\ndef _rightSideView(node, data, height):\n if node == None:\n return None\n else:\n\n if len(data) < height + 1:\n data.append(node.val)\n _rightSideView(node.right, data, height + 1)\n _rightSideView(node.left, data, height + 1)\n\n\n\n\n\n'''\nOnly add the vertex when reached at at particular height.\n\nit.e at each height add a single node. That single node must be of right piority first, \nif not then prioritize the left node\n\n'''","sub_path":"Archive/P/Trees/binary_tree_right_side_view_2.py","file_name":"binary_tree_right_side_view_2.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"117857174","text":"from django.contrib.auth import get_user_model\n\nfrom django import template\nfrom django.db.models import Count\n\nfrom posts.models import Post\n\nregister = template.Library()\n\nUser = get_user_model()\n\n\n@register.inclusion_tag(\n 'posts/snippets/rec_posts.html'\n)\ndef rec_posts(user):\n if isinstance(user, User):\n posts = Post.objects.annotate(q_count=Count('likes'))\\\n .order_by('-q_count')[:3]\n return {\"posts\": posts}\n","sub_path":"posts/templatetags/rec_posts.py","file_name":"rec_posts.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"61504453","text":"import pytest\n\nfrom ..area_of_triangle import area_triangle\n\n\n@pytest.mark.parametrize('a, b, c, expected', [\n (23, 45, 67, 183.8265),\n (3, 4, 3, 4.4721),\n (8, 44, 41, 156.8947)\n])\ndef test_area_triangle(a, b, c, expected):\n actual = area_triangle(a, b, c)\n assert actual == expected\n","sub_path":"arithmetic_03/test/test_area_of_a_triangle.py","file_name":"test_area_of_a_triangle.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"445376368","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport json\nimport re\nfrom pprint import pprint\nfrom kubernetes import client, config\nfrom kubernetes.utils.quantity import parse_quantity\n\n\ndef main():\n apiclient = config.new_client_from_config(\"/tmp/pre_kube_config\")\n crd_api = client.CustomObjectsApi(apiclient)\n limit = 9999999\n response = crd_api.list_cluster_custom_object(group='core.alibabacloud.com', version='v1', plural='quotas',\n limit=limit)\n for quota in response['items']:\n name = quota['metadata']['name']\n # 正则匹配 pay-as-you-go.md-[a-z]+\n if re.match(r'pay-as-you-go.md-[a-z]+', name, re.M | re.I):\n pprint(quota)\n print(name)\n print(parse_quantity(quota['spec']['admission']['cpu']))\n\n\nmain()\n","sub_path":"kubernetes/demo/python-sdk/get_crd_info.py","file_name":"get_crd_info.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"618941295","text":"# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\n# Copyright 2013 Midokura PTE LTD.\n# All Rights Reserved\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# 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, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n#\n# @author: Tomoe Sugihara , Midokura\n# @author: Ryu Ishimoto , Midokura\n\nimport exc\nimport httplib2\nimport json\nimport logging\nimport urllib\n\nLOG = logging.getLogger(__name__)\n\n\ndef do_request(uri, method, body=None, query=None, headers=None):\n\n LOG.debug(\"do_request: uri=%s, method=%s\" % (uri, method))\n LOG.debug(\"do_request: body=%s\" % body)\n LOG.debug(\"do_request: headers=%s\" % headers)\n\n if body != None:\n data = json.dumps(body)\n else:\n data = '{}'\n\n if query:\n uri += '?' + urllib.urlencode(query)\n\n if headers == None:\n headers = {}\n\n h = httplib2.Http()\n response, content = h.request(uri, method, data, headers=headers)\n\n LOG.debug(\"do_request: response=%s\" % response)\n LOG.debug(\"do_request: content=%s\" % content)\n\n if int(response['status']) > 300:\n e = exc.get_exception(response['status'])(content)\n LOG.error(\"Raising an exeption: (%r): %r\" % (e, str(e)))\n raise e\n try:\n body = json.loads(content) if content else None\n return response, body\n except ValueError:\n return response, content\n","sub_path":"src/midonetclient/api_lib.py","file_name":"api_lib.py","file_ext":"py","file_size_in_byte":1804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"299911315","text":"import pandas as pd\nimport numpy as np\nimport os\nimport re\nfrom xgboost import XGBClassifier\nfrom lightgbm import LGBMClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, confusion_matrix\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.preprocessing import LabelEncoder\nimport random\nimport warnings\n# for modeling demo (0602)\n\n# csv_file 부분에는 pandas dataframe 자체가 들어옴\n# Adv Modeling (2)\n# \t- Target encoding (Mean encoding) 적용\n# \t- 기존의 pandas type이 object였던 변수만 Target encoding 적용\n# confusion matrix에서 쓰일 label 역시 출력\ndef XGB_n_Target(df, json_info):\n\n\t# DataFrame Columns Data type 변환\n\tfor col in df.columns:\n\t\tdf[col] = df[col].astype(json_info[col]['changed_dtype'])\n\n\t# Target Feature 입력\n\tfor col in json_info:\n\t\tif json_info[col]['target'] == True :\n\t\t\ttarget = col\n\n\t# Target Feature Encoding : 데이터 값을 숫자 형태로 변환\n\t# Target Feature는 Categorical 변수라고 가정 (Classification 모델을 우선적으로 개발)\n\t# Object 데이터 값을 Numeric으로 변형한 경우 confusion label 리스트를 다시 cateogry(str)로 바꿔줌 \n\tif 'Numeric' in json_info[target]['possible_type']:\t\n\t\tconfusion_labels = list(set(df[target])) # set() : Sorted Unique Value in DF Series \n\n\telse: # Object(str) 형태의 데이터 값이 포함되어 있는 경우 숫자 형태로 변환\n\n\t\tori_col_unique = df[target].unique() # LabelEncoder를 하지 않은 String Unique Value List\n\t\tencoder = LabelEncoder()\n\t\tencoder.fit(df[target])\n\t\tdf[target] = encoder.transform(df[target])\n\n\t\t# LabelEncoder를 한 상태의 unique category\n\t\tencoded_col_unique = df[target].unique()\n\t\t# confusion matrix에서 정렬할 순서\n\t\tencoder_order = encoded_col_unique.argsort()\n\t\tconfusion_labels = encoded_col_unique[encoder_order].tolist()\n\t\t# encoder_order대로 original_label을 정렬\n\t\tori_ordered_labels = ori_col_unique[encoder_order].tolist()\n\n\tdf[target] = df[target].astype('int64') # Target Feature가 int 변수일때만 모델링 가능\n\n\t# Target 숫자형/범주형 변수 구분 (범주형 변수에는 Target Encoding 적용) (아래로 이동 예정)\n\tcategory_cols = [i for i in json_info if 'object' == json_info[i]['changed_dtype'] and json_info[i]['selected_type'] != 'Time' and i != target]\n\tnumeric_cols = [i for i in json_info if i not in category_cols and json_info[i]['selected_type'] != 'Time' and i != target] \n\n\tdf_X = df.drop(target, axis=1)\n\tdf_Y = df[target]\n\n\tdata_skf = StratifiedKFold(n_splits=5, random_state=42)\n\tencoding_skf = StratifiedKFold(n_splits=5, random_state=42)\n\n\tacc_ls = []\n\tpre_ls = []\n\trec_ls = []\n\tf1_ls = []\n\tconfusion_ls = []\n\timp_ls = []\n\n\t# train data와 val data 나누기 (by cross validation)\n\t# 이때 train 데이터의 경우 한번 더 cross validation을 통해 target encoding 시킴\n\n\tfor train_index, val_index in data_skf.split(df_X, df_Y):\n\t X_train = df_X.iloc[train_index].reset_index(drop=True,inplace=False)\n\t Y_train = df_Y[train_index].reset_index(drop=True,inplace=False)\n\t X_val = df_X.iloc[val_index].reset_index(drop=True,inplace=False)\n\t Y_val = df_Y[val_index].reset_index(drop=True,inplace=False)\n\n\t # new: target encoding시킬 X_train + Y_train 데이터\n\t # modeling train에 쓰일 데이터 생성\n\t new = df.iloc[train_index,:].reset_index(drop=True,inplace=False)\n\n\t for col in category_cols:\n\t new['{}_mean'.format(col)] = np.nan\n\t \n\t # cross validation을 통해 target_encoding된 훈련데이터를 만드는 과정\n\t for encoding_index, encoded_index in encoding_skf.split(X_train, Y_train):\n\t X_encoding = new.iloc[encoding_index,:]\n\t X_encoded = new.iloc[encoded_index,:]\n\n\t for col in category_cols:\n\t # 일반 target encoding \n\t object_mean = X_encoded[col].map(X_encoding.groupby(col)[target].mean()) # col 값에 대한 \n\t X_encoded['{}_mean'.format(col)] = object_mean\n\t new.iloc[encoded_index] = X_encoded\n\n\t global_mean = df[target].mean()\n\t for col in category_cols:\n\t new['{}_mean'.format(col)].fillna(global_mean, inplace=True)\n\t \n\t # not_obect cols + obeject_mean cols\n\t model_cols = ['{}_mean'.format(col) for col in category_cols] + numeric_cols + [target]\n\t model_train, train_target = new[model_cols].drop(target,axis=1), new[target]\n\t model_train.columns = [col if '_mean' not in col else col.replace('_mean','') for col in model_train.columns]\n\t \n\t # for validation\n\t # modeling validation에 쓰일 데이터 생성\n\t model_val, val_target = X_val[category_cols + numeric_cols], Y_val\n\t for col in category_cols:\n\t model_val[col] = model_val[col].map(new.groupby(col)['{}_mean'.format(col)].mean())\n\t model_val[col].fillna(new['{}_mean'.format(col)].mean(),inplace=True)\n\t \n\t model = XGBClassifier(random_state=42)\n\t model.fit(model_train, train_target)\n\t Y_predict = model.predict(model_val)\n\n\t acc = accuracy_score(val_target, Y_predict)\n\t acc_ls.append(acc)\n\n\t pre = precision_score(val_target, Y_predict)\n\t pre_ls.append(pre)\n\n\t rec = recall_score(val_target, Y_predict)\n\t rec_ls.append(rec)\n\n\t f1 = f1_score(val_target, Y_predict)\n\t f1_ls.append(f1)\n\n\t confusion = confusion_matrix(val_target, Y_predict, labels=confusion_labels)\n\t confusion_ls.append(confusion)\n\n\t # feature importance\n\t imp = model.feature_importances_\n\t imp_ls.append(imp)\n\n\tmean_acc = np.mean(acc_ls)\n\tmean_pre = np.mean(pre_ls)\n\tmean_rec = np.mean(rec_ls)\n\tmean_f1 = np.mean(f1_ls)\n\tmean_imp = (np.mean(imp_ls, axis=0))\n\t\n\t# F1 score가 가장 높은 값의 Confusion Matrix를 List 형태로 변환 (나중에 사용하기 편하게 아랫단부터 값 제공)\n\twhere = f1_ls.index(np.max(f1_ls))\n\tconfusion_final = confusion_ls[where]\n\tconfusion_final = confusion_final.tolist()[::-1]\n\n\t# Target Feature Label Encoding 한 경우 원래 값으로 변경 \n\tif 'Numeric' not in json_info[target]['possible_type']:\n\t\tconfusion_labels = ori_ordered_labels\n\n\t# Feature importance가 높은(descending) 순서대로 List 형태로 변환\n\timp_order = mean_imp.argsort()[::-1]\n\tdesc_imp = mean_imp[imp_order].tolist()\n\tdesc_name = np.array([col for col in model_train.columns])[imp_order].tolist()\n\n\tname = 'XGB{}'.format(round(random.random(), 8)).replace('0.','')\n\n\treturn name, mean_acc, mean_pre, mean_rec, mean_f1, confusion_final, confusion_labels, desc_name, desc_imp\n\t \ndef get_render_models(model_info, top=1):\n\t''' F1 Score를 기준으로 Rendering Model 선별 '''\n\n\tmodel_names = np.array([key for key in model_info.keys()])\n\tf1_ls = np.array([model_info[key]['f1_score'] for key in model_info.keys()])\n\tf1_order = f1_ls.argsort()[::-1]\n\n\tf1_model_names = model_names[f1_order].tolist()\n\tfinal_model_names = f1_model_names[:top]\n\tmodel_nums = ['Model {}'.format(i) for i in range(1,top+1)]\n\tmodel_zip = zip(final_model_names, model_nums)\n\n\treturn model_zip","sub_path":"MachineLearning/Report.py","file_name":"Report.py","file_ext":"py","file_size_in_byte":7071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"291846511","text":"import sys\nimport os\n\nBIN = os.path.expanduser(\"../\")\nif BIN not in sys.path:\n sys.path.append(BIN)\n\nimport numpy as np\nfrom warp_pyecloud_dipole import warp_pyecloud_dipole\n\nrun_in_other_process = False\n\nenable_trap = True\n\nfrom run_in_separate_process import run_in_separate_process\nnz = 100\nN_mp_max_slice = 60000\ninit_num_elecs_slice = 2*10**5\ndh = 3.e-4\nradius = 23e-3\nn_bunches = 50\n\nnx = int(np.ceil(2*radius/dh))\nny = int(np.ceil(2*radius/dh))\n\n# Compute sigmas\nnemittx = 2.5e-6\nnemitty = nemittx\nbeta_x = 100\nbeta_y = 100\n\nbeam_gamma = 479.\nbeam_beta = np.sqrt(1-1/(beam_gamma**2))\nsigmax = np.sqrt(beta_x*nemittx/(beam_gamma*beam_beta))\nsigmay = np.sqrt(beta_y*nemitty/(beam_gamma*beam_beta))\nprint(sigmax)\nkwargs = {'enable_trap': enable_trap,\n\t'z_length': 1.,\n\t'nx': nx,\n\t'ny': ny, \n\t'nz': nz,\n 'dh_t': dh, \n\t'n_bunches': n_bunches,\n 'b_spac' : 25e-9,\n 'beam_gamma': beam_gamma, \n\t'sigmax': sigmax,\n 'sigmay': sigmay, \n 'sigmat': 1.000000e-09/4.,\n 'bunch_intensity': 1.1e11, \n 'init_num_elecs': init_num_elecs_slice*nz,\n 'init_num_elecs_mp': int(0.7*N_mp_max_slice*nz), \n\t'By': 0.,\n 'pyecloud_nel_mp_ref': init_num_elecs_slice/(0.7*N_mp_max_slice),\n\t'dt': 25e-12,\n 'pyecloud_fact_clean': 1e-6,\n\t'pyecloud_fact_split': 1.5,\n 'chamber_type': 'circle', \n 'flag_save_video': False,\n 'Emax': 332., \n 'del_max': 1.7,\n 'R0': 0.7, \n 'E_th': 35, \n 'sigmafit': 1.0828, \n 'mufit': 1.6636,\n 'secondary_angle_distribution': 'cosine_3D', \n 'N_mp_max': N_mp_max_slice*nz,\n 'N_mp_target': N_mp_max_slice/3*nz,\n\t'flag_checkpointing': True,\n\t'checkpoints': np.linspace(1, n_bunches, n_bunches),\n 'flag_output': True,\n 'bunch_macro_particles': 1e5,\n 't_offs': 2.5e-9,\n 'output_name': 'warp_out_circle_drift.h5',\n 'flag_relativ_tracking': True,\n 'radius': radius\n}\n\nif run_in_other_process:\n res = run_in_separate_process(warp_pyecloud_dipole, kwargs=kwargs)\nelse:\n res = warp_pyecloud_dipole(**kwargs)\n\n\n","sub_path":"circ_drift/benchmark_pyecloud_script_circ_drift.py","file_name":"benchmark_pyecloud_script_circ_drift.py","file_ext":"py","file_size_in_byte":1985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"491370175","text":"import cv2\nimport matplotlib.pyplot as plt\nimport EmojiAnalyzer\nimport math\nimport os\nimport json\n\n\ndef cvToMatplt(image):\n \"\"\"\n Takes a cv2 image and converts it into an appropriate format for matplotlib\n :param image:\n :return:\n \"\"\"\n returnImg = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n return returnImg\n\n\ndef meanSquares(image, square_size):\n \"\"\"\n Splits an image in to squares of a given size and returns average colors as array\n :param image: Images in cv2 BGR format\n :param square_size: edge length of a square\n :return: array with mean values\n \"\"\"\n # calc number of squares in both directions\n x_dim = len(image)\n y_dim = len(image[0])\n x_amount = x_dim // square_size\n y_amount = y_dim // square_size\n\n mean_color_array = [[0 for y in range(y_amount)] for x in range(x_amount)]\n for x_square_num in range(0, x_amount): # assumes x > y\n for y_square_num in range(0, y_amount):\n # calc average from x_square * square_size and y_square * square_size on\n x_start = x_square_num * square_size\n y_start = y_square_num * square_size\n\n # sum up pixels in square\n colorsum = [0, 0, 0]\n for x in range(x_start, x_start + square_size):\n for y in range(y_start, y_start + square_size):\n colorsum[0] += image[x][y][0]\n colorsum[1] += image[x][y][1]\n colorsum[2] += image[x][y][2]\n\n # calc mean\n colorsum[:] = [x // (square_size ** 2) for x in colorsum]\n mean_color_array[x_square_num][y_square_num] = colorsum\n\n return mean_color_array\n\n\ndef emojify_image(image, emoji_dict, mean_array, square_size, path_of_folder='emoji'):\n \"\"\"\n Emojifies the image and returns it\n \"\"\"\n # TODO: move most other function calls here\n x_dim = len(image)\n y_dim = len(image[0])\n x_amount = x_dim // square_size\n y_amount = y_dim // square_size\n\n for x_square_num in range(0, x_amount):\n for y_square_num in range(0, y_amount):\n\n # calc closest matching emoji\n\n best_fit = ''\n minimum_distance = 1000000\n for key, val in emoji_dict.items():\n distance = math.sqrt(\n (mean_array[x_square_num][y_square_num][0] - val[0]) ** 2 +\n (mean_array[x_square_num][y_square_num][1] - val[1]) ** 2 +\n (mean_array[x_square_num][y_square_num][2] - val[2]) ** 2\n ) # euclidian distance\n if distance < minimum_distance:\n minimum_distance = distance\n best_fit = key\n\n # load and crop emoji\n\n emoji_img = cv2.imread(os.path.join(path_of_folder, best_fit), cv2.IMREAD_COLOR)\n emoji_cropped = cv2.resize(emoji_img, (square_size, square_size))\n\n # put emoji in image\n\n x_start = x_square_num * square_size\n y_start = y_square_num * square_size\n for x in range(square_size):\n for y in range(square_size):\n image[x + x_start][y + y_start] = emoji_cropped[x][y]\n\n cropped_image = image[0 : x_amount * square_size, 0 : y_amount * square_size]\n return cropped_image\n\n\ndef main():\n emoji_path = 'emoji'\n square_size = 100\n image_path = 'johannes.jpg'\n\n # generate or load emoji_dict\n emoji_dict = {}\n if (os.path.isfile('emoji_dict.json')):\n with open('emoji_dict.json', 'r') as f:\n emoji_dict = json.load(f)\n else:\n emoji_dict = EmojiAnalyzer.index_emoji(emoji_path)\n try:\n with open('emoji_dict.json', 'w') as f:\n json.dump(dict(emoji_dict), f)\n except Exception:\n print('Exception during json dump, removing json file.')\n if os.path.isfile('emoji_dict.json'):\n os.remove('emoji_dict.json')\n\n img = cv2.imread(image_path, cv2.IMREAD_COLOR)\n\n print('Calculating means...')\n mean_array = meanSquares(img, square_size)\n\n print('Emojifying image...')\n emojifyed_img = emojify_image(img, emoji_dict, mean_array, square_size, emoji_path)\n\n cv2.imwrite('output.jpg', emojifyed_img)\n\n plt.imshow(cvToMatplt(emojifyed_img))\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"ImageAnalyzer.py","file_name":"ImageAnalyzer.py","file_ext":"py","file_size_in_byte":4348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"220855833","text":"#Plotting COVID distribution by country in 2020 until March 14th 2020\r\n\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\n#import .xls table into python\r\ndf = pd.read_excel(r'C:\\Users\\Dia\\Documents\\UNI\\Data Science NBU\\semester 2\\Data visualization\\COVID distribution\\COVID_EU.xlsx')\r\ndf = df.iloc[:,[0,1,2]]\r\n\r\n#print(df)\r\n\r\ndf[\"DateRep\"] = pd.to_datetime(df[\"DateRep\"])\r\ndf = df.loc[(df['DateRep'] >= '2020-02-17') &(df['CountryExp'] != 'Italy')]\r\n#df.rename(columns={'Date':'DateRep', 'Country':'CountryExp'}, inplace = True)\r\ndf.columns = ['Date', 'Country', 'Daily cases']\r\nprint(df)\r\n\r\ndf.pivot(index = \"Date\", columns = \"Country\", values=\"Daily cases\").plot().legend(bbox_to_anchor=(1, 1))\r\n\r\nplt.show()\r\n\r\n#df = df.loc[(df['DateRep'] >= '2020-02-17') & (df['column_name'] <= B)]\r\n#df.pivot(index = \"DateRep\", columns = \"CountryExp\", values=\"NewConfCases\").plot()\r\n#plt.show()\r\n","sub_path":"COVID_time.py","file_name":"COVID_time.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"621102650","text":"from django.conf.urls import patterns, url\nfrom django.views.generic import TemplateView\nfrom app import views\n\nurlpatterns = patterns('',\n\n url(r'^$', views.home, name='home'),\n url(r'^home/$', views.home, name='home'),\n url(r'^aboutus/$', views.aboutus, name='aboutus'),\n url(r'^login/$', views.login_page, name='login'),\n url(r'^login2/$', views.login2, name='login'),\n url(r'^signup/$', views.signup, name='signup'),\n\t\t url(r'^orgsignup2/$', views.OrgSignUpRequest, name='OrgSignUp'),\n url(r'^volunteam/$', views.volunteam, name='volunteam'),\n url(r'^signup2/$', views.signupRequest, name='signup'),\n url(r'^showUsers/$', views.showUsers,\n name='Show users'),\n url(r'^events/$', views.events, name='Events'),\n url(r'^addevent/$', views.addevent, name='AddEvent'),\n url(r'^logout/$', views.logoutrequest, name='LogOut'),\n url(r'^OrgSignUp/$', views.OrgSignUp, name='OrgSignUp'),\n\t\t\turl(r'^managment/$', views.managment, name='managment'),\n )\n","sub_path":"project/app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"250447111","text":"from django.shortcuts import render\nfrom django.contrib import messages\nimport requests\nimport math\n\n### Webpages\n\n# Render the main page\ndef index(request):\n return render(request, 'Restaurants/basic.html')\n\n# Wait on the user's request\ndef search(request):\n if request.method == 'POST':\n #Grab the html values\n\n cost = request.POST.get('costTextfield', None)\n dist = request.POST.get('distTextfield', None)\n popu = request.POST.get('popuTextfield', None)\n imme = request.POST.get('immeTextfield', None)\n resultNum = request.POST.get('resuTextfield', None)\n typeS = request.POST.get('typeSelect', None)\n \n #Interpreting in the preferences\n data = [cost, dist, popu, imme]\n for x in range(0, len(data)):\n data[x] = make_num(data[x])\n if (str(data[x]) == \"nan\"): # Bind non-numerical outputs to 0\n data[x] = 0\n if (x == 0):\n messages.add_message(request, messages.INFO, 'Price')\n elif (x == 1):\n messages.add_message(request, messages.INFO, 'Distance')\n elif (x == 2):\n messages.add_message(request, messages.INFO, 'Popularity')\n elif (x == 3):\n messages.add_message(request, messages.INFO, 'Acclaim')\n elif (abs(data[x]) > 10): # Bind overlarge inputs to their max value\n data[x] = data[x] / abs(data[x]) * 10\n\n #Establish a dictionary to house the GET parameters for the API request\n params = {}\n\n #Locate the user\n lat = request.POST.get('latiTextfield', None)\n long = request.POST.get('longTextfield', None)\n\n error = 0\n if ((lat == \"Error\") or (long == \"Error\")):\n #LET THE USER KNOW THAT THEY NEED TO TURN ON LOCATION SERVICES TO GET RELEVANT RESULTS\n #The request needs something to go on... Give them an optional location input field? Or just give them random results?\n error = 1\n else:\n params[\"latitude\"] = float(lat)\n params[\"longitude\"] = float(long)\n\n #Cut down search space if the user wants someplace nearby\n rad = 40000 - data[1] * 2000\n if (rad > 40000):\n rad = 40000\n params[\"radius\"] = int(rad)\n\n #If user specified what they wanted, deal accordingly\n if typeS is not None:\n if (int(typeS) == 1):\n params[\"categories\"] = \"restaurants\"\n elif (int(typeS) == 2):\n params[\"categories\"] = \"active\"\n elif (int(typeS) == 3):\n params[\"categories\"] = \"arts\"\n elif (int(typeS) == 4):\n params[\"categories\"] = \"nightlife\"\n\n #Cut down search space if the user really wants to go to the place\n if (data[3] > 8):\n params[\"open_now\"] = 1\n\n #Don't make bad recommendations, except the user might want some, so don't actually\n #params[\"sort_by\"] = \"rating\"\n\n #Expand the search space as much as possible\n params[\"limit\"] = \"50\"\n\n #Fetch a solution space\n headers = {\n \"Authorization\": \"Bearer GDiZCRPhWsvt4Tm9iutxJo7dJPFbh7OKV1PwbI5j_8CdmETqvQWHIZ8nTRBYvSpnfXzNAShki4EwUwdmB28NW1psM4Bc2NCo_eBh8ccGaa-nevbE5vS91AK3LETMWHYx\"\n }\n\n if (error == 0):\n r = requests.get('https://api.yelp.com/v3/businesses/search',\n headers=headers, params=params)\n result = r.json()\n\n #Determine how many results max the user actually wants\n resultNum = make_num(resultNum)\n if (str(resultNum) == \"nan\"):\n resultNum = 3\n messages.add_message(request, messages.INFO, 'Number of Results')\n elif (resultNum > 50):\n resultNum = 50\n elif (resultNum < 0):\n resultNum = 0\n else:\n resultNum = abs(int(resultNum)) #Absolute value is redundant, but kept just in case\n\n # Optimize within the visible solution space given user preferences\n if (result['total'] < 50):\n searchSize = result['total']\n else:\n searchSize = 50\n\n if searchSize != 0:\n sortList = []\n reviewMax = 0\n rateMax = 0\n distMax = 0\n priceMax = 0\n\n #Determining the max value for each parameter to create a relative scale\n for i in range(0, searchSize):\n try:\n if (result['businesses'][i]['review_count'] > reviewMax):\n reviewMax = result['businesses'][i]['review_count']\n except:\n garbage = 1\n\n try:\n if (result['businesses'][i]['rating'] > rateMax):\n rateMax = result['businesses'][i]['rating']\n except:\n garbage = 1\n\n try:\n if (measure(float(lat), float(long), result['businesses'][i]['coordinates']['latitude'],\n result['businesses'][i]['coordinates']['longitude']) > distMax):\n distMax = measure(float(lat), float(long), result['businesses'][i]['coordinates']['latitude'],\n result['businesses'][i]['coordinates']['longitude'])\n except:\n garbage = 1\n\n try:\n if (len(result['businesses'][i]['price']) > priceMax):\n priceMax = len(result['businesses'][i]['price'])\n except:\n garbage = 1\n\n for i in range(0, searchSize):\n #Maintaining business indexes for easy sorting later\n score = 0\n try: #Minimize price (want the lowest score, so by default add a lot to scores of people who want low prices)\n score -= data[0] * len(result['businesses'][i]['price']) / priceMax\n except: #If no price listed, do nothing\n garbage = 1\n\n\n try: #Minimize distance\n score -= data[1] * measure(float(lat), float(long), result['businesses'][i]['coordinates']['latitude'],\n result['businesses'][i]['coordinates']['longitude']) / distMax\n dist = round(measure(float(lat), float(long), result['businesses'][i]['coordinates']['latitude'],\n result['businesses'][i]['coordinates']['longitude']) * 0.621371, 2) #Give a rough distance estimate\n except:\n garbage = 1\n\n try: #Maximize rating\n score -= data[2] * result['businesses'][i]['rating'] / rateMax\n except:\n garbage = 1\n\n try: #Maximize the number of reviews\n score -= data[3] * result['businesses'][i]['review_count'] / reviewMax\n except:\n garbage = 1\n\n sortList.append([i, score, dist])\n\n sortList.sort(key=lambda y: y[1]) # Determine the optimal choices given user inputs\n if (searchSize < resultNum): #If the search space is smaller than requested, return all of them\n resultNum = searchSize\n\n #Grab as many results as the user requested\n fetchList = sortList[0:resultNum]\n\n chosenList = []\n #Grabbing the optimal choices\n for z in range(0,len(fetchList)):\n chosenList.append(result['businesses'][fetchList[z][0]])\n chosenList[z]['NUMBER'] = str(z + 1) + \"/\" + str(len(fetchList))\n chosenList[z]['DIST'] = fetchList[z][2]\n\n else:\n error = 2\n\n\n if (error == 0): #If there aren't any errors, give them the results\n return render(request, 'Restaurants/search.html', {'contents': chosenList, 'coords': [str(lat), str(long)]})\n elif (error == 1): #Theoretically this should never be called as without allowing location data, the form shouldn't send.\n return render(request, 'Restaurants/search_fail.html', {'contents': \"Uh oh, it looks like we can't locate you. Urban Connoisseur needs to access your location information to give you relevant results.\"})\n else:\n return render(request, 'Restaurants/search_fail.html', {\n 'contents': \"Uh oh, it looks like Urban Connoisseur couldn't find any results for you. Sorry about that.\"})\n else:\n return render(request, 'Restaurants/basic.html')\n\n### Utility functions\n\n#Return the float of an input, or nan if the input cannot be cast as a float (as NaN casts as a float to nan...)\ndef make_num(s):\n try:\n float(s)\n return float(s)\n except:\n return \"nan\"\n\n#Approximate the number of meters between two lat/long coords (implemented in case a result with coordinates but no distance is returned)\ndef measure(lat1, lon1, lat2, lon2): #Haversine implementation\n R = 6378.137 # Radius of earth in KM\n dLat = lat2 * math.pi / 180 - lat1 * math.pi / 180\n dLon = lon2 * math.pi / 180 - lon1 * math.pi / 180\n a = math.sin(dLat/2) * math.sin(dLat/2) + math.cos(lat1 * math.pi / 180) * math.cos(lat2 * math.pi / 180) * math.sin(dLon/2) * math.sin(dLon/2)\n c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))\n d = R * c\n return d # kilometers\n","sub_path":"Restaurants/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"309986481","text":"import my_db\nclass Organisation:\n def __init__(self):\n self.code=-1\n self.status = \"\"\n self.contact_name = \"\"\n self.job_title = \"\"\n self.organisation_name = \"\"\n self.email = \"\"\n self.address = \"\"\n\n def insert_into_table(self):\n sql = \"insert into mytable\\\n (code,status,contact_name,job_title,organisation_name,email,address) \" \\\n \"values(?,?,?,?,?,?,?)\"\n db = my_db.getDB()\n cur = db.cursor()\n cur.execute(sql, [self.code, self.status, self.contact_name, self.job_title,\n self.organisation_name, self.email, self.address])\n db.commit()\n cur.close()\n db.close()\n\n","sub_path":"bean_organisation.py","file_name":"bean_organisation.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"615417450","text":"# which device to call: ffmpeg -f avfoundation -list_devices true -i \"\" (mac)\n# set up server: ffserver -d -f /etc/ffserver-gina.conf or ~/ffserver-rtp.conf\n\n# this function adds sliding bar features\n\n\nimport cv2\nimport numpy as np\nimport math\nimport time\nimport os\nimport subprocess as sp\nimport sys\n\ncap0 = cv2.VideoCapture(0)\n#cap1 = cv2.VideoCapture(2)\n#cap2 = cv2.VideoCapture(3)\n\ndef unwarp(frame, angle, centre, bw):\n # resize 16:9 to 4:3 images... eg. 640x480 to 960x480\n h, w = (frame.shape[0], frame.shape[1]*3/2)\n frame_resize = cv2.resize(frame, (w, h))#, interpolation=cv2.CV_INTER_CUBIC)\n\n # pad image... e.g. 960x960\n if (w !=h):\n #img_sq = np.ndarray(shape = (width, width, 3))\n diff = int((w-h)/2)\n # pad\n frame_pad = cv2.copyMakeBorder(frame_resize, diff, diff, 0, 0, cv2.BORDER_CONSTANT)\n # crop\n # img_sq = img[0:h, diff:(diff+h)] # crop only the middle\n h, w = frame_pad.shape[: 2]\n #print ('image is now squared of size ', (w, h) )\n else:\n frame_pad = frame_resize\n h, w = frame_pad.shape[: 2]\n\n # rotate 0 or 120 or 240\n rot_mat = cv2.getRotationMatrix2D((w/2, h/2), angle, 1.0) # center, angle, scale\n frame_align = cv2.warpAffine(frame_pad, rot_mat, (w, h), flags=cv2.INTER_LINEAR)\n\n # fisheye to rectlinear\n #frame_polar= cv2.logPolar(frame, (frame_resize.shape[0]/2, frame_resize.shape[1]/2), 80, cv2.WARP_FILL_OUTLIERS) # [0]: height; [1]: width\n frame_polar = cv2.linearPolar(frame_align, (w/2, h/2), h/2, cv2.WARP_FILL_OUTLIERS)\n h, w = frame_polar.shape[:2]\n #print(h, w)\n\n # rotate 90\n rot_mat = cv2.getRotationMatrix2D((w/2, h/2), -90, 1.0) # center, angle, scale\n frame_rot = cv2.warpAffine(frame_polar, rot_mat, (w, h), flags=cv2.INTER_LINEAR)\n\n # resize to pano view\n frame_pano = cv2.resize(frame_rot, (w*2, h/2))#, interpolation=cv2.CV_INTER_CUBIC)\n\n return frame_pano\n #cv2.imshow('preview', frame_pano)# % count, pano)\n # cv2.imshow('cam1', frame_pnao1)\n\n\nif __name__ == '__main__':\n\n# frame_out = np.\n\n while(cap0.isOpened() & cap1.isOpened()):\n ret, frame0 = cap0.read() #print(type(frame), frame.dtype)\n# ret, frame1 = cap1.read()\n # print(frame.shape[0], frame.shape[1])\n start = time.time()\n #pano = fish2pano(frame) #.astype('u8')q\n\n\n frame_pano0 = unwarp(frame0, 0, 180, 120) # centre, bandwidth in degrees\n# frame_pano1 = unwarp(frame1, 120, 60, 120)\n\n# frame_out = np.vstack((frame_pano0, frame_pano1))\n\n # option 1: play back\n #cv2.imwrite('frame_pano.png', frame_pano)\n cv2.imshow('cam', frame_out)# % count, pano)\n\n # option 2: send as mjpeg\n #sp.call('/usr/local/bin/ffmpeg -f image2 -s 1820x480 -i frame_pano.png -vcodec mjpeg http://localhost:8090/cam2.ffm', shell=True)\n\n\n # option 3: send down pipe (preferred)\n # convert bgr24 to yuv420p\n #print(frame_pano.dtype)\n # frame_yuv = cv2.cvtColor(frame_pano, cv2.COLOR_BGR2YUV_I420)\n #cv2.imshow('', frame_yuv)\n # sys.stdout.write( frame_pano.tostring() )\n\n # option 4: send as\n\n\n # option 5: send through sockCet\n\n #sp.call('/usr/local/bin/ffmpeg -f rawvideo -pix_fmt bgr24 -s 1820x480 -i sys.stdout.write(frame_pano.tostring) -f mpegts udp://localhost:8090/cam2.ffm', shell=True)\n #frame_pano.format\n\n end = time.time()\n #print(end-start) #cv2.waitKey(q1000)\n\n #sp.call(['/usr/local/bin/ffmpeg -f image2 -s 240x960 -r 1 -i image2pipe -vcodec mpeg4 -y mvoei.mpeg'], shell=True)\n\n cap.release()\n cv2.destroyAllWindows\n","sub_path":"fisheye/logpolar-play.py","file_name":"logpolar-play.py","file_ext":"py","file_size_in_byte":3671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"28302910","text":"#!/usr/bin/python2.7\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nucb = pd.read_csv(\"UCB.csv\", sep=\" \", names=['x', 'y'])\neps = pd.read_csv(\"epsilon.csv\", sep=\" \", names=['x', 'y'])\n\nfig = plt.figure()\n\nax1 = fig.add_subplot(111)\nax1.scatter(ucb['x'], ucb['y'])\n\nax2 = ax1.twiny()\nax2.scatter(eps['x'], eps['y'], color='red')\n\nplt.show()\n","sub_path":"plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"466260409","text":"from urllib.parse import unquote\nfrom re import finditer\nfrom base64 import b64decode\nfrom struct import unpack\n\n_KEY_PLAYERPREFS = b'e806f6'\n\n\ndef _xor_endec(b: bytes, key: bytes) -> bytes:\n return bytes([key[i % len(key)] ^ b[i] for i in range(len(b))])\n\n\ndef _dec_key(s: str) -> bytes:\n return _xor_endec(b64decode(unquote(s)), _KEY_PLAYERPREFS)\n\n\ndef _dec_val(key: str, s: str) -> bytes:\n b = b64decode(unquote(s))\n b = b[0:len(b) - (11 if b[-5] != 0 else 7)]\n return _xor_endec(b, key.encode() + _KEY_PLAYERPREFS)\n\n\ndef dec_xml(file: str) -> dict:\n res = {}\n\n with open(file, 'r') as f:\n content = f.read()\n\n for m in finditer(r'(.*)', content):\n try:\n key = _dec_key(m.group(1)).decode()\n except:\n continue\n\n val = _dec_val(key, m.group(2))\n\n if key == 'UDID':\n val = ''.join([chr(val[4 * i + 6] - 10) for i in range(36)])\n elif len(val) == 4:\n val = str(unpack('i', val)[0])\n\n res[key] = val\n\n return res","sub_path":"nowem/playerprefs.py","file_name":"playerprefs.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"54041440","text":"import numpy as np\nfrom scipy.stats import norm\nfrom parametric_analysis.core.signal_models import General_Signal_Model\nimport numpy.linalg as lg\nfrom copy import copy\nfrom scipy.optimize import minimize\n\n#MARK: Real Signals\n\nclass Nonlinear_Signal_Model(General_Signal_Model):\n \n \"\"\"This class constructs a Nonlinear Signal Model \"\"\"\n \n attributes_short_list=[\"w\",\"theta\",\"sigma2\"]\n \n def __init__(self,w,theta,N,sigma2,Fe=1,name=\"Linear Signal Model\"):\n self.w = np.array(w)\n self.L=len(w)\n self.N = N\n self.Fe=Fe\n self.theta=np.matrix(theta.reshape((len(theta),1)))\n self.sigma2=sigma2\n self.name=name\n \n def get_theta(self):\n return self.theta\n \n def get_sigma2s(self):\n \"\"\" Compute the signal energy \"\"\"\n H=self.get_H()\n theta=self.get_theta()\n N,L=H.shape\n \n x=H*theta\n sigma2s=np.ravel((x.T*x)/N)[0]\n return sigma2s\n\n def estimate(self,signal):\n self.N = len(signal)\n #Estimate w\n self.w=self.estimator_w.estimate(signal)\n H=self.get_H()\n self.theta=lg.pinv(H)*signal\n\n def realisation(self):\n \"\"\" Generate One realisation of the signal waveform \"\"\"\n H=self.get_H()\n theta=self.get_theta()\n N,L=H.shape\n \n n_vect=np.arange(N)/self.Fe\n signal=H*theta+norm.rvs(size=(N,1),scale=np.sqrt(self.sigma2))\n return n_vect,signal\n\n\nclass Fourier_Signal_Model(Nonlinear_Signal_Model):\n \n \"\"\"This class constructs a Real Fourier Signal Model\n \n .. math::\n \n x[n]=\\\\sum_{k=0}^{L-1} \\\\theta_{k}\\\\cos(w_k n) - \\\\theta_{k+L}\\\\sin(w_k n)+ b[n]\n \n \"\"\"\n \n def get_H(self):\n # Construct the matrix H\n omega=self.get_omega()\n n_vect=np.matrix(np.arange(self.N)).T\n omega_vect=np.matrix(omega)\n H_complex=np.exp(1j*n_vect*omega_vect)\n H=np.hstack((np.real(H_complex),-np.imag(H_complex)))\n \n return H\n\n def get_derivative_H_wrt_w(self,k):\n # Compute the derivative of H with respect the theta_k\n \n omega=self.get_omega()\n L=len(omega)\n \n derivative_complex=1j*np.matrix(np.zeros((self.N,L)))\n for n in range(self.N):\n derivative_complex[n,k]=n*np.exp(1j*omega[k]*n)\n\n derivative=np.hstack((-np.imag(derivative_complex),-np.real(derivative_complex)))\n return derivative\n\nclass Harmonic_Signal_Model(Fourier_Signal_Model):\n \n \"\"\"This class constructs an Harmonic Fourier Signal Model\n \n .. math::\n \n x[n]=\\\\sum_{l=0}^{L} a_{k}\\\\cos(lw_{0} n+phi_{k})+ b[n]\n \n \"\"\"\n \n attributes_short_list=[\"w\",\"theta\",\"sigma2\"]\n \n def __init__(self,L,N=None,w0=None,theta=None,sigma2=None,Fe=1,estimator_w=None,name=\"Real Fourier Signal Model\"):\n self.L=L\n self.N=N\n self.w=[w0]\n self.theta=theta\n if theta is not None:\n self.theta=np.matrix(theta.reshape((len(theta),1)))\n\n self.Fe=Fe\n self.sigma2=sigma2\n self.name=name\n self.estimator_w=estimator_w\n\n def get_omega(self):\n return self.w[0]*np.arange(1,self.L+1)\n \n def get_derivative_H_wrt_w(self,k):\n # Compute the derivative of H with respect the theta_k \"\"\"\n\n omega=self.get_omega()\n derivative_complex=1j*np.matrix(np.zeros((self.N,self.L)))\n \n for l in range(self.L):\n for n in range(self.N):\n derivative_complex[n,l]=(n*(l+1))*np.exp(1j*omega[l]*n)\n\n derivative=np.hstack((-np.imag(derivative_complex),-np.real(derivative_complex)))\n return derivative\n\n\n\n\n","sub_path":"parametric_analysis/nonlinear_signal_model/signal_model.py","file_name":"signal_model.py","file_ext":"py","file_size_in_byte":3733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"136692451","text":"intinput=open('input.txt','r')\noutput=open('output.txt','w')\nB=intinput.readlines()\nN=int(B[0])\nA=list(map(int,B[1].split()))\nmin=None\nfor i in range(len(A)):\n for j in range(len(A)):\n if i!=j:\n if (A[i]<0) and (i\" + results[-1][1] + \" \" + results[-1][2] + \"\" )\n f.write( \"Following: \" + results[-1][3] + \"
    \")\n f.write( \"Followers: \" + results[-1][4] + \"
    \" )\n f.write( \"\" )\n f.close()","sub_path":"extra.py","file_name":"extra.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"526866960","text":"from dataclasses import dataclass, field\nfrom typing import Any\n\n\n@dataclass\nclass Queue:\n items: list = field(default_factory=list)\n\n def put(self, value: Any):\n self.items.insert(0, value)\n\n def get(self):\n return self.items.pop()\n\n @property\n def size(self) -> int:\n return len(self.items)\n\n\nif __name__ == \"__main__\":\n q = Queue()\n\n print(q.size)\n\n q.put(11)\n q.put(\"Aa\")\n q.put(22)\n q.put(33)\n q.put(\"Bb\")\n\n print(q.items)\n\n print(q.get())\n print(q.get())\n print(q.items)\n","sub_path":"algorithms/custom_collections/queues.py","file_name":"queues.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"40333647","text":"'''\nCreated on 2013-12-27\n\n@author: wang.chl\n'''\n\nimport ConfigParser\nimport logging\nimport os\nimport time\n\n\nclass LoggingClass(object):\n moduleName = None\n LOG_FILENAME = None\n LOG_LEVEL = None\n LOG_FORMAT = None\n \n _levelNames = {\n 'CRITICAL' :logging.CRITICAL ,\n 'ERROR' :logging.ERROR,\n 'WARNING':logging.WARNING,\n 'INFO':logging.INFO,\n 'DEBUG':logging.DEBUG ,\n 'NOTSET':logging.NOTSET \n }\n \n\n def __init__(self, moduleName, confPath):\n self.moduleName = moduleName\n config = ConfigParser.ConfigParser()\n config.read(confPath)\n LOG_FILENAME = config.get(\"logging\", \"log.fileName\");\n LOG_LEVEL = config.get(\"logging\", \"log.level\")\n LOG_FORMAT = '<%(asctime)-15s [%(levelname)s] [%(thread)d] [line:%(lineno)d]> [%(moduleName)s] %(message)s'\n\n if(os.path.isfile(LOG_FILENAME)):\n updateTime = str(time.strftime(\"%Y%m%d\", time.localtime(os.stat(LOG_FILENAME).st_mtime)))\n now = str(time.strftime(\"%Y%m%d\", time.localtime()))\n if(updateTime.strip() != now.strip()):\n LOG_FILENAME_BACK = LOG_FILENAME + str('_') + str(updateTime);\n os.rename(LOG_FILENAME, str(LOG_FILENAME_BACK))\n logging.basicConfig(filename=LOG_FILENAME, level=self._levelNames.get(LOG_LEVEL), format=LOG_FORMAT)\n \n \n def debug(self, message):\n _format = {\n 'moduleName' : self.moduleName\n }\n logging.debug(message, extra=_format)\n \n def info(self, message):\n _format = {\n 'moduleName' : self.moduleName\n }\n logging.info(message, extra=_format)\n \n def warn(self, message):\n _format = {\n 'moduleName' : self.moduleName\n }\n logging.warn(message, extra=_format) \n \n def error(self, message):\n _format = {\n 'moduleName' : self.moduleName\n }\n logging.error(message, extra=_format)\n \n def critical(self, message):\n _format = {\n 'moduleName' : self.moduleName\n }\n logging.critical(message, extra=_format)\n \n","sub_path":"work/snmp_old/src/commons/ebs_logging.py","file_name":"ebs_logging.py","file_ext":"py","file_size_in_byte":2304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"518072085","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef read_EXCEL(filename, EXCEL_load):\n if 'xlsx' in filename.split('.'):\n df = pd.read_excel(EXCEL_load)\n print('read %s successfully' % filename)\n if 'csv' in filename.split('.'):\n df = pd.read_csv(EXCEL_load)\n print('read %s successfully' % filename)\n return df\n\ndef AGLMV(name, SP, FORMAT, df, filename = 'AGLMV.xlsx', Path = ''):\n '''plot r_f of your data\n \n ------paras\n name: str\n name of your AGMV plot\n SP: str, should be 'T' or others\n If you don't want to save picture, just assign SP != 'T'.\n FORMAT: str\n format of your picture\n df: panda.DataFrame\n output of read_EXCEL\n filename: str\n filename of your data. please read 'readme.png' to know the format of your file \n ######support file format: csv, excel\n \n ------output\n a picture\n '''\n \n if (SP == 'T') and (FORMAT == 'png' or 'pdf' or 'ps' or 'eps' or 'svg'): \n maker_list = ['D', 'o', 'v', '^', '<', '>', '1', '2', '3', '4']\n algo = [i for i in df['name']] #name of algorithm\n GLMV = [i for i in df['GL/MV']] #G/MV_1 of algorithm\n A = [i for i in df['Accuracy']] #Accuracy of algorithm\n\n fig, ax = plt.subplots()\n for i in range(len(algo)):\n x = GLMV[i]\n y = A[i]\n plt.plot(x, y, maker_list[i], label = algo[i], markersize = 8) \n\n ax.tick_params(axis='x', labelsize=15) \n ax.tick_params(axis='y', labelsize=15)\n #https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.ticklabel_format.html\n ax.ticklabel_format(axis='x', style='sci',scilimits=(0,2))\n plt.ylim([0, 1.1]) \n x_m = min(GLMV)\n x_M = max(GLMV)\n plt.xlim([0.95*x_m, 1.05*x_M])\n plt.title(name, size = 20)\n plt.xlabel('$GL^{0.15}/MV_1$', size = 20)\n plt.ylabel('Accuracy', size = 20)\n #https://stackoverflow.com/questions/6774086/why-is-my-xlabel-cut-off-in-my-matplotlib-plot\n plt.gcf().subplots_adjust(left = 0.17, bottom = 0.17)\n plt.legend(loc = 'best', prop = {'size': 15})\n\n fig.savefig(Path + 'AGLMV of ' + name + '.' + FORMAT, dpi = 300, format = FORMAT)\n plt.close()\n print('save figure successfully !')\n else:\n print('FORMAT is wrong or NO AGMV should be saved.')","sub_path":"In developing/A-GLMV plot/Module/mutili.py","file_name":"mutili.py","file_ext":"py","file_size_in_byte":2399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"510902853","text":"from functools import lru_cache\n\n# Nahrbtnik\n# =========\n#\n# Na nagradni igri ste zadeli kupon, ki vam omogoča, da v Mercatorju kupite\n# poljubne izdelke, katerih skupna masa ne presega k kilogramov. (Podelili so\n# tri nagrade in sicer s parametrom k = 1, k = 2 in k = 5). Napišite funkcijo\n# nahrbtnik(seznam_artiklov, k), ki poišče največjo ceno, ki jo lahko odnesemo\n# iz trgovine. Naredite dve verziji: pri prvi lahko vzamemo samo en artikel iste\n# vrste, pri drugi pa poljubno število artiklov iste vrste.\n\nizdelki = [\n\t('jogurt', 0.39, 0.18),\n\t('mleko', 0.89, 1.03),\n ('kava', 2.19, 0.2),\n ('maslo', 1.49, 0.25),\n ('kvas', 0.22, 0.042),\n ('jajca', 2.39, 0.69),\n ('klobasa', 3.76, 0.50),\n ('čebula', 1.29, 2.0),\n ('kruh', 2.99, 1.0),\n ('Nutella', 4.99, 0.75),\n ('sok', 1.15, 2.0)\n]\n\n\ndef nahrbtnik_unique(seznam_artiklov, k):\n if len(seznam_artiklov) == 0:\n return 0\n else:\n for _, cena, teza in seznam_artiklov:\n if (k - teza) <= 0:\n return nahrbtnik_unique(seznam_artiklov[1:], k)\n else:\n moznost1 = nahrbtnik_unique(seznam_artiklov[1:], k)\n moznost2 = cena + nahrbtnik_unique(seznam_artiklov[1:], k - teza)\n return max(moznost1, moznost2)\n\n\n# Jajca\n# =====\n###############################################################################\n# Napisite funkcijo [najdaljse_narascajoce_podazporedje], ki sprejme seznam in\n# poisce najdaljse (ne strogo) narascajoce podzaporedje stevil v seznamu.\n#\n# Na primer: V seznamu [2, 3, 6, 8, 4, 4, 6, 7, 12, 8, 9] je najdaljse naj vrne\n# rezultat [2, 3, 4, 4, 6, 7, 8, 9].\n###############################################################################\n\n\ndef najdaljse_narascajoce_podzaporedje(sez):\n return None\n\n###############################################################################\n# Nepreviden študent je pustil robotka z umetno inteligenco nenadzorovanega.\n# Robotek želi pobegniti iz laboratorija, ki ga ima v pomnilniku\n# predstavljenega kot matriko števil:\n# - ničla predstavlja prosto pot\n# - enica predstavlja izhod iz laboratorija\n# - katerikoli drugi znak označuje oviro, na katero robotek ne more zaplejati\n\n# Robotek se lahko premika le gor, dol, levo in desno, ter ima omejeno količino\n# goriva. Napišite funkcijo [pobeg], ki sprejme matriko, ki predstavlja sobo,\n# začetno pozicijo in pa število korakov, ki jih robotek lahko naredi z\n# gorivom, in izračuna ali lahko robotek pobegne. Soba ima vedno vsaj eno\n# polje.\n#\n# Na primer za laboratorij:\n# [[0, 1, 0, 0, 2],\n# [0, 2, 2, 0, 0],\n# [0, 0, 2, 2, 0],\n# [2, 0, 0, 2, 0],\n# [0, 2, 2, 0, 0],\n# [0, 0, 0, 2, 2]]\n#\n# Napišite funkcij, ki bo izračunala maksimalno število metov (v najslabšem primeru), da ugotovimo\n# številko kritičnega nadstropja, če imamo na voljo točko k jajc.\n\n\n\n# We are solving the problem of alternatingly colored towers. There are four\n# different types of building blocks, two of them blue and two red. The blue\n# blocks have heights 2 and 3 and the red ones 1 and 2.\n\n# Write the function [alternating_towers] for a given height calculates the\n# number of different towers of given height that we can build using alternatingly\n# colored blocks (red on blue, blue on red etc.). We may start with any color.\n\n# Hint: Use two mutually recursive auxilary functions using the keyword \"and\".\n# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n# # alternating_towers 10;;\n# - : int = 35\n\n@ lru_cache(maxsize=None)\ndef stolpi(n, barva):\n if n == 0:\n return 1\n elif n < 0:\n return 0\n else:\n if barva == 'red':\n option1 = stolpi(n - 1, 'blue')\n option2 = stolpi(n - 2, 'red')\n return option1 + option2\n else:\n option3 = stolpi(n - 2, 'red')\n option4 = stolpi(n - 3, 'red')\n return option3 + option4\n\n\ndef alternajoci_stolpi(n):\n return stolpi(n, 'red') + stolpi(n, 'blue')\n\n# robotek iz pozicije (3, 1) pobegne čim ima vsaj 5 korakov, iz pozicije (5, 0)\n# pa v nobenem primeru ne more, saj je zagrajen.\n###############################################################################\n\nsoba = [[0, 1, 0, 0, 2],\n [0, 2, 2, 0, 0],\n [0, 0, 2, 2, 0],\n [2, 0, 0, 2, 0],\n [0, 2, 2, 0, 0],\n [0, 0, 0, 2, 2]]\n\n\ndef pobeg(soba, pozicija, koraki):\n return None\n","sub_path":"13-memoizacija/vaje/dodatne_vaje.py","file_name":"dodatne_vaje.py","file_ext":"py","file_size_in_byte":4436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"483702995","text":"# запрашиваем возраст. предполагаем что на ввод подается целочисленное значение\n\n\ndef check_occupation(age):\n if age < 6:\n occupation = 'a baby'\n elif age < 17:\n occupation = 'a schoolboy'\n elif age < 25:\n occupation = 'a student'\n elif age < 65:\n occupation = 'a proffesional'\n elif age < 100:\n occupation = 'a pensioner'\n else:\n occupation = 'not living'\n return 'You must be {}'.format(occupation)\n\n\nif __name__ == '__main__':\n user_age = int(input('Enter your age: '))\n print(check_occupation(user_age))\n","sub_path":"task1_if_age.py","file_name":"task1_if_age.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"305823895","text":"from cerberus import Validator\nfrom .models import Emitter\nfrom ..exercises.models import Exercise\nfrom .models import EmitterAttribute\n\n\ndef emitter_create_schema(exercise_slug):\n return {'name': {'required': True,\n 'minlength': 4,\n 'maxlength': 25,\n 'unique_emitter_in_ex': exercise_slug,\n 'regex': \"^[a-zA-Z0-9\\s_']*\"},\n 'position': {'required': True,\n 'regex': '^\\d{1,2}[^ABIOYZabioyz][A-Za-z]{2}([0-9][0-9])+$'},\n\n # the auto movement part of Emitters\n 'autoMove': {'type': 'boolean', 'nullable': False},\n 'autoMoveType': {'type': 'string',\n 'required': False,\n 'allowed': ['minutes', 'hours', 'days'],\n 'dependencies': {'autoMove': True}},\n 'autoMoveInterval': {'type': 'integer',\n 'required': False,\n 'dependencies': {'autoMove': True}},\n 'autoMoveDistance': {'type': 'integer',\n 'required': False,\n 'dependencies': {'autoMove': True}},\n 'autoMoveDirection': {'type': 'integer',\n 'min': 0,\n 'max': 360,\n 'required': False,\n 'dependencies': {'autoMove': True}},\n\n 'attributes': {'type': 'list',\n 'schema': {'type': 'dict',\n\n # this is the schema for individual attributes\n 'schema': {'name': {'type': 'string',\n 'regex': '^[a-zA-Z0-9_]+$'},\n 'value': {'type': 'string',\n 'regex': '^[a-zA-Z0-9_]+$'},\n 'autoIncrement': {'type': 'boolean',\n 'nullable': True},\n 'autoIncrementType': {'type': 'string',\n 'nullable': True,\n 'allowed': ['minutes',\n 'hours',\n 'days']},\n 'autoIncrementInterval': {'type': 'integer',\n 'nullable': True},\n 'autoIncrementValue': {'type': 'integer',\n 'nullable': True,\n 'dependencies': 'autoIncrementInterval'}}}}}\n\n\ndef emitter_edit_schema(exercise_slug):\n schema = emitter_create_schema(exercise_slug)\n schema['id'] = {'type': 'integer', 'emitter_exists_in_ex': exercise_slug}\n schema['name'] = {'type': 'string', 'minlength': 4, 'maxlength': 25, 'regex': '^[a-zA-Z0-9\\s_]+$'}\n return schema\n\n\nclass EmitterValidator(Validator):\n\n def _validate_unique_emitter_in_ex(self, exercise_slug, field, value):\n if Emitter.query.filter_by(name=value)\\\n .join(Exercise)\\\n .filter(Exercise.slug == exercise_slug)\\\n .first() is not None:\n self._error(field, \"Emitter name taken\")\n\n def _validate_emitter_exists_in_ex(self, exercise_slug, field, value):\n e = Emitter.query.get(value)\n if e is None or e.exercise.slug != exercise_slug:\n self._error(field, \"Invalid emitter for exercise {}\".format(exercise_slug))\n\n def populate_emitter(self, emitter):\n emitter.name = self.document['name']\n emitter.position = self.document['position']\n emitter.auto_move = self.document['autoMove']\n if emitter.auto_move:\n emitter.auto_move_type = self.document['autoMoveType']\n emitter.auto_move_interval = self.document['autoMoveInterval']\n emitter.auto_move_distance = self.document['autoMoveDistance']\n emitter.auto_move_direction = self.document['autoMoveDirection']\n else:\n emitter.auto_move_type = None\n emitter.auto_move_interval = None\n emitter.auto_move_distance = None\n emitter.auto_move_direction = None\n\n for attr in self.document['attributes']:\n ea = EmitterAttribute(name=attr['name'],\n value=attr['value'],\n auto_increment=attr['autoIncrement'])\n if ea.auto_increment:\n ea.auto_increment_type = attr['autoIncrementType']\n ea.auto_increment_interval = attr['autoIncrementInterval']\n ea.auto_increment_value = attr['autoIncrementValue']\n emitter.attributes.append(ea)\n\n","sub_path":"backend/app/emitters/validators.py","file_name":"validators.py","file_ext":"py","file_size_in_byte":5270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"615895614","text":"from test import Test\nfrom game import Game\nclass GameTest(Test):\n\n def __init__(self):\n Test.__init__(self)\n self.game = Game(5000)\n\n def testBoardCardAreDealtCorrectly(self):\n self.game.dealBoardCard(3)\n self.assertEqual(3, len(self.game.board))\n self.assertEqual(49, self.game.deck.length())\n for card in self.game.board:\n self.assertNotIn(card, self.game.deck.cards)\n","sub_path":"tests/gameTest.py","file_name":"gameTest.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"446698472","text":"import spotipy\r\nimport spotipy.util as util\r\nimport random\r\nimport requests\r\nimport time\r\nfrom bs4 import BeautifulSoup\r\nimport time\r\nimport wx\r\nfrom GUI_Main import guiMain\r\nfrom threading import Thread\r\nfrom gui import SpotifyLyrics\r\n\r\n\r\ndef progressBar(progress, duration):\r\n progressSeconds = int((progress / 1000)%60)\r\n progressMinutes = int((progress / (1000*60))%60)\r\n durationSeconds = int((duration / 1000)%60)\r\n durationMinutes = int((duration / (1000*60))%60)\r\n percentage = int((progress / duration) * 100)\r\n r = [progressSeconds, progressMinutes, durationSeconds, durationMinutes, percentage]\r\n return r\r\n\r\ndef request_song_info(song_title, artist_name):\r\n base_url = 'https://api.genius.com'\r\n headers = {'Authorization': 'Bearer ' + 'H1yVKgAtF3p6BczQ_idi34ePGCu9lPPs7Bc7CwFgT8_W6ugkAObB_WpCxzQu2iEd'}\r\n search_url = base_url + '/search'\r\n data = {'q': song_title + ' ' + artist_name}\r\n response = requests.get(search_url, data=data, headers=headers)\r\n return response\r\n\r\ndef scrap_song_url(url):\r\n page = requests.get(url)\r\n html = BeautifulSoup(page.text, 'html.parser')\r\n lyrics = html.find('div', class_='lyrics').get_text()\r\n return lyrics\r\n\r\ndef run(self):\r\n update = False\r\n currentTrack = None\r\n duration = 0\r\n progress = 0\r\n while(True):\r\n scope = 'user-read-playback-state'\r\n token = util.prompt_for_user_token('thornbird116', scope, client_id='7ef6e7b8699046f3a23bf7be5ac8ec86', client_secret='126128f52f1c44fb8900fba37fcb5f08', redirect_uri='http://localhost:8080')\r\n spotify = spotipy.Spotify(auth=token)\r\n currentlyPlaying = spotify.currently_playing()\r\n\r\n\r\n track = currentlyPlaying['item']\r\n progress = currentlyPlaying['progress_ms']\r\n duration = track['duration_ms']\r\n name = track['name']\r\n artists = track['artists']\r\n names = []\r\n for a in artists:\r\n names.append(a['name'])\r\n mainArtist = names[0]\r\n if currentTrack is None:\r\n currentTrack = name\r\n update = True\r\n elif currentTrack != name:\r\n currentTrack = name\r\n update = True\r\n else:\r\n update = False\r\n\r\n if(update == True):\r\n response = request_song_info(name, mainArtist)\r\n json = response.json()\r\n remote_song_info = None\r\n\r\n for hit in json['response']['hits']:\r\n if mainArtist.lower() in hit['result']['primary_artist']['name'].lower():\r\n remote_song_info = hit\r\n break\r\n if remote_song_info:\r\n song_url = remote_song_info['result']['url']\r\n finalPrint = \"Currently Playing: \" + currentTrack + \" by \" + names[0] + \"\\n\" + scrap_song_url(song_url)\r\n self.updateText(finalPrint)\r\n else:\r\n self.updateText(\"Stop listening to weeb shit\")\r\n\r\n r = progressBar(progress, duration)\r\n print(r[0], r[1], r[2], r[3], r[4])\r\n self.updateTime(r[0], r[1], r[2], r[3], r[4])\r\n time.sleep(1)\r\ndef main():\r\n\r\n app = wx.App()\r\n frm = SpotifyLyrics(None)\r\n thread = Thread(target = run, args = (frm, ))\r\n thread.start()\r\n mainFrm = guiMain(frm)\r\n frm.Show()\r\n app.MainLoop()\r\n#\r\n# update = False\r\n# currentTrack = None\r\n# duration = 0\r\n# progress = 0\r\n# while(True):\r\n# scope = 'user-read-playback-state'\r\n# token = util.prompt_for_user_token('thornbird116', scope, client_id='7ef6e7b8699046f3a23bf7be5ac8ec86', client_secret='126128f52f1c44fb8900fba37fcb5f08', redirect_uri='http://localhost:8080')\r\n# spotify = spotipy.Spotify(auth=token)\r\n#\r\n# currentlyPlaying = spotify.currently_playing()\r\n# track = currentlyPlaying['item']\r\n# progress = currentlyPlaying['progress_ms']\r\n# duration = track['duration_ms']\r\n# name = track['name']\r\n# artists = track['artists']\r\n# names = []\r\n# for a in artists:\r\n# names.append(a['name'])\r\n# mainArtist = names[0]\r\n#\r\n# if currentTrack is None:\r\n# currentTrack = name\r\n# update = True\r\n# elif currentTrack != name:\r\n# currentTrack = name\r\n# update = True\r\n# else:\r\n# update = False\r\n#\r\n# if(update == True):\r\n# response = request_song_info(name, mainArtist)\r\n# json = response.json()\r\n# remote_song_info = None\r\n#\r\n# for hit in json['response']['hits']:\r\n# if mainArtist.lower() in hit['result']['primary_artist']['name'].lower():\r\n# remote_song_info = hit\r\n# break\r\n#\r\n# if remote_song_info:\r\n# song_url = remote_song_info['result']['url']\r\n# print(\"-------------------------------------------------------------------------------------------\")\r\n# finalPrint = \"Currently Playing: \" + currentTrack + \" by \" + names[0] + \"\\n\" + scrap_song_url(song_url)\r\n# print(finalPrint)\r\n# print(\"-------------------------------------------------------------------------------------------\")\r\n#\r\n# else:\r\n# print(\"-------------------------------------------------------------------------------------------\")\r\n# print(\"Stop listening to weeb shit\")\r\n# print(\"-------------------------------------------------------------------------------------------\")\r\n# progressBar(progress, duration)\r\n# time.sleep(1)\r\n#\r\n#\r\nif __name__ == \"__main__\": main()\r\n","sub_path":"lyricFetcher.py","file_name":"lyricFetcher.py","file_ext":"py","file_size_in_byte":5707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"10098019","text":"\n\nimport dash\nfrom dash.dependencies import Output, Input\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport plotly\nimport random\nimport plotly.graph_objs as go\nfrom math import exp,tanh\nfrom collections import deque\nimport dash_table\nimport numpy as np\n\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\n\nclass Constants:\n\n ACTUAL_SPEED = \"actual_speed\"\n DESIRABLE_SPEED = \"desirable_speed\"\n ACTUAL_STEERING = \"actual_steering\"\n DESIRABLE_STEERING = \"desirable_steering\"\n COEFF_A=\"coeff_A\"\n COEFF_B=\"coeff_B\"\n COEFF_C=\"coeff_C\"\n COEFF_D=\"coeff_D\"\n GAS=\"gas\"\n BREAK=\"break\"\n POLYNOMIAL_A_COEFF_a = \"polynomial_A_coeef_a\"\n POLYNOMIAL_A_COEFF_b = \"polynomial_A_coeef_b\"\n POLYNOMIAL_A_COEFF_c = \"polynomial_A_coeef_c\"\n POLYNOMIAL_A_COEFF_d = \"polynomial_A_coeef_d\"\n POLYNOMIAL_B_COEFF_a = \"polynomial_B_coeef_a\"\n POLYNOMIAL_B_COEFF_b = \"polynomial_B_coeef_b\"\n POLYNOMIAL_B_COEFF_c = \"polynomial_B_coeef_c\"\n POLYNOMIAL_B_COEFF_d = \"polynomial_B_coeef_d\"\n POLYNOMIAL_C_COEFF_a = \"polynomial_C_coeef_a\"\n POLYNOMIAL_C_COEFF_b = \"polynomial_C_coeef_b\"\n POLYNOMIAL_C_COEFF_c = \"polynomial_C_coeef_c\"\n POLYNOMIAL_C_COEFF_d = \"polynomial_C_coeef_d\"\n POLYNOMIAL_A = \"polynomial_A\"\n POLYNOMIAL_B = \"polynomial_B\"\n POLYNOMIAL_C = \"polynomial_C\"\n Cones = \"cones\"\n Cones_X = \"cones_x\"\n Cones_Y = \"cones_y\"\n\n\n# POLYNOMIAL_B_ = \"polynomial_b\"\n# POLYNOMIAL_C = \"polynomial_c\"\n TIME =\"time\"\n X = \"x\"\n Y = \"y\"\n ACCURACY_SPEED = \"accuracy_speed\"\n ACCURACY_STEERING = \"accuracy_steering\"\n\nclass Dash:\n\n def __init__(self,state:{}):\n actual_speed = state[Constants.ACTUAL_SPEED]\n desirable_speed = state[Constants.DESIRABLE_SPEED]\n actual_steering = state[Constants.ACTUAL_STEERING]\n gas = state[Constants.GAS]\n breaks= state[Constants.BREAK]\n desirable_steering = state[Constants.DESIRABLE_STEERING]\n polynomial_a = state[Constants.POLYNOMIAL_A]\n polynomial_b = state[Constants.POLYNOMIAL_B]\n polynomial_c = state[Constants.POLYNOMIAL_C]\n polynomial_a_coeef_a =polynomial_a[Constants.COEFF_A]\n polynomial_a_coeef_b=polynomial_a[Constants.COEFF_B]\n polynomial_a_coeef_c=polynomial_a[Constants.COEFF_C]\n polynomial_a_coeef_d=polynomial_a[Constants.COEFF_D]\n polynomial_b_coeef_a = polynomial_b[Constants.COEFF_A]\n polynomial_b_coeef_b = polynomial_b[Constants.COEFF_B]\n polynomial_b_coeef_c = polynomial_b[Constants.COEFF_C]\n polynomial_b_coeef_d = polynomial_b[Constants.COEFF_D]\n polynomial_c_coeef_a = polynomial_c[Constants.COEFF_A]\n polynomial_c_coeef_b = polynomial_c[Constants.COEFF_B]\n polynomial_c_coeef_c = polynomial_c[Constants.COEFF_C]\n polynomial_c_coeef_d = polynomial_c[Constants.COEFF_D]\n cones_x = state[Constants.Cones][Constants.Cones_X]\n cones_y = state[Constants.Cones][Constants.Cones_Y]\n polynomial_b = state[Constants.POLYNOMIAL_B]\n polynomial_c = state[Constants.POLYNOMIAL_C]\n time = state[Constants.TIME]\n\n\n x_const =[i for i in range(max(time)+10)]\n self.app = dash.Dash(__name__)\n\n # SPEED\n\n self.speed_fig =go.Figure()\n self.speed_fig.add_trace(go.Scatter(x=time,y=actual_speed, name=\"actual speed\"))\n self.speed_fig.add_trace(go.Scatter(x=time,y=desirable_speed, name=\"desirable speed\"))\n self.speed_fig.add_trace(go.Scatter(x=time,y=actual_speed, name=\"actual speed -kmh\"))\n self.speed_fig.add_trace(go.Scatter(x=x_const,y=[30/3.6]*len(x_const),name=\"30-kmh - 1\"))\n self.speed_fig.add_trace(go.Scatter(x=x_const,y=[60/3.6]*len(x_const),name=\"60-kmh - 2\"))\n\n self.speed_fig.update_layout(\n xaxis_title = \"Time[second]\",\n yaxis_title = \"Speed[meter/second]\",\n xaxis = dict(range =[0,max(time)+10]),\n yaxis = dict(range =[0,100/3.6])\n )\n\n value =lambda mona,machna: tanh(mona/(machna+0.001)) if mona0:\n print(\"data\", key, \"sebanyak\", len(pos), \"ditemukan di posisi\", pos)\n else :\n print(\"Data tidak ditemukan\")\n return pos\n\na = 'rafsanjani rahadi'\nSqesearch(a, 'r')","sub_path":"Alpro 1/P6-a.py","file_name":"P6-a.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"497141245","text":"# ----------------------------------------------------------------------\n# ManagedObjectProfile config mirror settings\n# ----------------------------------------------------------------------\n# Copyright (C) 2007-2019 The NOC Project\n# See LICENSE for details\n# ----------------------------------------------------------------------\n\n# Third-party modules\nfrom django.db import models\n\n# NOC modules\nfrom noc.core.migration.base import BaseMigration\nfrom noc.core.model.fields import DocumentReferenceField\n\n\nclass Migration(BaseMigration):\n def migrate(self):\n Template = self.db.mock_model(model_name=\"Template\", db_table=\"main_template\")\n\n self.db.add_column(\n \"sa_managedobjectprofile\",\n \"beef_storage\",\n DocumentReferenceField(\"main.ExtStorage\", null=True, blank=True),\n )\n self.db.add_column(\n \"sa_managedobjectprofile\",\n \"beef_path_template\",\n models.ForeignKey(\n Template,\n verbose_name=\"Config Mirror Template\",\n blank=True,\n null=True,\n on_delete=models.CASCADE,\n ),\n )\n self.db.add_column(\n \"sa_managedobjectprofile\",\n \"beef_policy\",\n models.CharField(\n \"Beef Policy\",\n max_length=1,\n choices=[(\"D\", \"Disable\"), (\"A\", \"Always\"), (\"C\", \"Change\")],\n default=\"D\",\n ),\n )\n","sub_path":"sa/migrations/0180_managedobjectprofile_beef.py","file_name":"0180_managedobjectprofile_beef.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"546225657","text":"from datadog import initialize, api\r\n\r\noptions = {\r\n 'api_key': '45e60fd7093756732f22bbe731c2238c',\r\n 'app_key': 'de4e086314090cadf4cda99b6228bc755e2f0bf6'\r\n}\r\n\r\ninitialize(**options)\r\n\r\ntitle = \"My_Metric API Created Timeboard Graph\"\r\ndescription = \"An API creted timeboard.\"\r\ngraphs = [{\r\n \"graphs\" : [{\r\n \"title\": \"Rhys My_Metric API Graph\",\r\n \"definition\": {\r\n \"events\": [],\r\n \"requests\": [\r\n {\"q\": \"avg:My.Metric{host:precise64}\"} ,\r\n\t\t\t {\"q\": \"anomalies(avg:mongodb.network.bytesoutps{*}, 'basic', 2)\"},\t\t\t\r\n\t\t\t {\"q\": \"sum:my_metric{*}.rollup(3600)\"}\r\n ]\r\n },\r\n \"viz\": \"timeseries\"\r\n }],\r\n \"title\" : \"Rhys My_Metric Dashboard API Created\",\r\n \"description\" : \"A dashboard with the average My_Metric data.\",\r\n \"template_variables\": [{\r\n \"name\": \"host1\",\r\n \"prefix\": \"host\",\r\n \"default\": \"host:precise64\"\r\n }],\r\n \"read_only\": \"True\"\r\n}]\r\n\r\ntemplate_variables = [{\r\n \"name\": \"host1\",\r\n \"prefix\": \"host\",\r\n \"default\": \"host:my-host\"\r\n}]\r\n\r\nread_only = True\r\n\r\napi.Timeboard.create(title=title, description=description, graphs=graphs, template_variables=template_variables, read_only=read_only)","sub_path":"TimeboardAPI.py","file_name":"TimeboardAPI.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"85641128","text":"#Chapter 11\nimport doctest\n#5 \ndef subatomic(atomic):\n smallest = 1\n name = ''\n for particle in atomic:\n probability = atomic[particle]\n if probability < smallest:\n smallest = probability\n name = particle\n\n return particle\n\n#6\ndef count_duplicates(dictionary):\n duplicates = 0\n values = list(dictionary.values())\n\n for item in values:\n if values.count(item) >= 2:\n duplicates = duplicates +1\n\n num_occurrences = values.count(item)\n for i in range(num_occurrences):\n values.remove(item)\n return duplicates\n\n#7\ndef is_balanced(dictionary):\n '''(dict of {str: float}) -> bool\n\n Return True if and only if color_to_factor represents a balanced color.\n >>> is_balanced({'R': 0.5, 'G': 0.4, 'B': 0.7})\n False\n >>> is_balanced({'R': 0.3, 'G': 0.5, 'B': 0.2})\n True\n\n '''\n \n val = list(dictionary.values())\n val = sum(val)\n if val == 1:\n return True\n else:\n return False\n\n#8\ndef dict_interest(dic1,dic2):\n ''' (dict, dict) -> dict\n\n Return a new dictionary that contains only the key/value pairs that occur\n in both dict1 and dict2.\n\n >>> dict_interest({'a': 1, 'b': 2, 'c': 3}, {'a': 1, 'd': 2, 'b': 2})\n {'a': 1, 'b': 2}\n\n '''\n dicset = {}\n \n for k1,v1 in dic1.items():\n if k1 in dic2 and v1 == dic2[k1]:\n dicset[k1] = v1\n\n return dicset\n\n#9\ndef db_headings(dict_of_dict):\n '''(dict of dict) -> set\n\n Return a set of the keys in the inner dictionaries in dict_of_dict.\n\n >>> db_headings({'A': {1: 'a', 2: 'b'}, 'B': {2: 'c', 3: 'd'}})\n {1, 2, 3}\n\n '''\n inner_keys = set()\n\n for key in dict_of_dict:\n for keysub in dict_of_dict[key]:\n inner_keys.add(keysub)\n\n return inner_keys\n\n#10\ndef db_consistent(dict_of_dict):\n '''(dict of dict) -> set\n\n Return whether all inner dictionaries in dict_of_dict contain the same keys.\n\n >>> db_consistent({'A': {1: 'a', 2: 'b'}, 'B': {2: 'c', 3: 'd'}})\n False\n >>> db_consistent({'A': {1: 'a', 2: 'b'}, 'B': {2: 'c', 1: 'd'}})\n True\n\n '''\n inner_keys_list = [] #list \n\n for key in dict_of_dict:\n inner_keys = list(dict_of_dict[key].keys())\n inner_keys.sort()\n inner_keys_list.append(inner_keys)\n\n\n for i in range(1, len(inner_keys_list)):\n if len(inner_keys_list[0]) != len(inner_keys_list[i]):\n return False\n\n for j in range(len(inner_keys_list[0])):\n if inner_keys_list[0][j] != inner_keys_list[i][j]:\n return False\n\n return True \n\n#11\n#a\ndef sparse_add(vec1,vec2):\n \"\"\" (dict of {int: int}, dict of {int: int} -> dict of {int: int})\n\n Return the sum of sparse vectors vector1 and vector2.\n\n >>> sparse_add({1: 3, 3: 4}, {2: 4, 3: 5, 5: 6})\n {1: 3, 2: 4, 3: 9, 5: 6}\n \"\"\" \n sum1 = vec1.copy()\n\n for key in vec2:\n if key in sum1:\n sum1[key] = sum1[key] + vec2[key]\n else:\n sum1[key] = vec2[key]\n return sum1\n\n#b\ndef sparse_dot(vec1,vec2):\n \"\"\" (dict of {int: int}, dict of {int: int} -> dict of {int: int})\n\n Return the dot product of sparse vectors vector1 and vector2.\n\n >>> sparse_dot({1: 3, 3: 4}, {2: 4, 3: 5, 5: 6})\n 20\n \"\"\"\n dot = 0\n\n for key1 in vec1:\n if key1 in vec2:\n dot = dot + vec1[key1] * vec2[key1]\n return dot\n \n#c \n#Since only non-zero entries are stored, will the last entry always be non-zero?\n# If not, how will the last entry be represented in the dictionary?\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nprint(doctest.testmod())\n","sub_path":"CIS122 Introduction to Programming and Problem Solving/Python Group Meeting 2.py","file_name":"Python Group Meeting 2.py","file_ext":"py","file_size_in_byte":3633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"259939023","text":"import os\nimport pickle\nimport torch\nimport numpy as np\nfrom math import ceil\nfrom model_vc import Generator\nimport pickle\nimport torch\nimport torch.nn.functional as F\n\nspeaker_emb_dim = 19\nlambda_cd = 1\n\ndef pad_seq(x, base=32):\n len_out = int(base * ceil(float(x.shape[0])/base))\n len_pad = len_out - x.shape[0]\n assert len_pad >= 0\n return np.pad(x, ((0,len_pad),(0,0)), 'constant'), len_pad\n\ndevice = 'cuda:0'\nG = Generator(32,speaker_emb_dim,512,32).eval().to(device) # 2nd number is onehot\n\n#g_checkpoint = torch.load('autovc.ckpt' ,map_location='cuda:0')\n\nprint('loading model')\n\ng_checkpoint = torch.load('checkpoint/chkpt_340000' ,map_location='cuda:0')\nG.load_state_dict(g_checkpoint['model'])\n\n\n# generate the metadata\n#\n\nprint('gen metadata')\n\nmetadata = []\n\n\n\n#rootDir = r'C:\\Users\\ACTUS\\Desktop\\pyscripts\\autovc\\data\\autovc_train'\nrootDir = r'autovc_train'\n\n#musicDir = r'C:\\Users\\ACTUS\\Desktop\\pyscripts\\autovc\\data\\autovc_train\\\\'\nmusicDir = 'autovc_train/'\n\nwith open(os.path.join(rootDir, 'train.pkl'), 'rb') as handle:\n speakers = pickle.load(handle)\n\n\nerrors = []\n\nfor speaker in speakers:\n\n emb_org = torch.from_numpy(speaker[1][np.newaxis, :]).to(device)\n\n for sample in speaker[2:]:\n\n x_org = np.load(musicDir+sample)\n x_org, len_pad = pad_seq(x_org)\n\n uttr_org = torch.from_numpy(x_org[np.newaxis, :, :]).to(device)\n\n # no, look at solver_encoder.py to do this part\n # to calc error\n\n\n with torch.no_grad():\n x_identic, x_identic_psnt, code_real = G(uttr_org, emb_org, emb_org)\n\n # Identity mapping loss\n g_loss_id = F.mse_loss(uttr_org, x_identic)\n g_loss_id_psnt = F.mse_loss(uttr_org, x_identic_psnt)\n\n # Code semantic loss.\n code_reconst = G(x_identic_psnt, emb_org, None)\n g_loss_cd = F.l1_loss(code_real , code_reconst)\n\n# g_loss = g_loss_id + g_loss_id_psnt + lambda_cd * g_loss_cd\n\n errors.append(( speaker[0] , sample , g_loss_id.item(), g_loss_id_psnt.item(), g_loss_cd.item(), g_loss_id.item() + g_loss_id_psnt.item() + g_loss_cd.item()))\n\n\n\nerrors = sorted(errors, key=lambda x: x[4], reverse=True)\n\nfor i in errors[:20]:\n print(i)\n\nprint('complete')\n\n\n## g_loss_id is error from pre-postnet, L_recon0\n## g_loss_id_psnt is error after postnet, L_recon\n## g_loss_cd is content error, x_1->1 -> C_1 difference.","sub_path":"compareerror.py","file_name":"compareerror.py","file_ext":"py","file_size_in_byte":2378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"472607895","text":"# -*- coding: utf-8 -*-\n\"\"\"\nDOCUMENTATION\n Qt.py was born in the film and visual effects industry to address\n the growing need for the development of software capable of running\n with more than one flavour of the Qt bindings for Python - PySide,\n PySide2, PyQt4 and PyQt5.\n\n 1. Build for one, run with all\n 2. Explicit is better than implicit\n 3. Support co-existence\n\n Default resolution order:\n - PySide2\n - PyQt5\n - PySide\n - PyQt4\n\"\"\"\nimport os\nimport sys\nimport types\nimport shutil\n\nfrom .membership import common_members, _compatibility_members, _misplaced_members\n\n__version__ = \"1.1.0\"\n\n# Enable support for `from Qt import *`\n__all__ = []\n\n# Flags from environment variables\nQT_VERBOSE = bool(os.getenv(\"QT_VERBOSE\"))\nQT_PREFERRED_BINDING = os.getenv(\"QT_PREFERRED_BINDING\", \"\")\nQT_SIP_API_HINT = os.getenv(\"QT_SIP_API_HINT\")\n\n# Reference to Qt.py\nQt = sys.modules[__name__]\nQt.QtCompat = types.ModuleType(\"QtCompat\")\n\ntry:\n long\nexcept NameError:\n # Python 3 compatibility\n long = int\n\n\ndef _apply_site_config():\n try:\n import QtSiteConfig\n except ImportError:\n # If no QtSiteConfig module found, no modifications\n # to common_members are needed.\n pass\n else:\n # Provide the ability to modify the dicts used to build Qt.py\n if hasattr(QtSiteConfig, 'update_members'):\n QtSiteConfig.update_members(common_members)\n\n if hasattr(QtSiteConfig, 'update_misplaced_members'):\n QtSiteConfig.update_misplaced_members(members=_misplaced_members)\n\n if hasattr(QtSiteConfig, 'update_compatibility_members'):\n QtSiteConfig.update_compatibility_members(\n members=_compatibility_members)\n\n\ndef _new_module(name):\n return types.ModuleType(__name__ + \".\" + name)\n\n\ndef _import_sub_module(module, name):\n \"\"\"import_sub_module will mimic the function of importlib.import_module\"\"\"\n module = __import__(module.__name__ + \".\" + name)\n for level in name.split(\".\"):\n module = getattr(module, level)\n return module\n\n\ndef _setup(module, extras):\n \"\"\"Install common submodules\"\"\"\n\n Qt.__binding__ = module.__name__\n\n for name in list(common_members) + extras:\n try:\n submodule = _import_sub_module(\n module, name)\n except ImportError:\n continue\n\n setattr(Qt, \"_\" + name, submodule)\n\n if name not in extras:\n # Store reference to original binding,\n # but don't store speciality modules\n # such as uic or QtUiTools\n setattr(Qt, name, _new_module(name))\n\n\ndef _wrapinstance(func, ptr, base=None):\n \"\"\"Enable implicit cast of pointer to most suitable class\n\n This behaviour is available in sip per default.\n\n Based on http://nathanhorne.com/pyqtpyside-wrap-instance\n\n Usage:\n This mechanism kicks in under these circumstances.\n 1. Qt.py is using PySide 1 or 2.\n 2. A `base` argument is not provided.\n\n See :func:`QtCompat.wrapInstance()`\n\n Arguments:\n func (function): Original function\n ptr (long): Pointer to QObject in memory\n base (QObject, optional): Base class to wrap with. Defaults to QObject,\n which should handle anything.\n\n \"\"\"\n\n assert isinstance(ptr, long), \"Argument 'ptr' must be of type \"\n assert (base is None) or issubclass(base, Qt.QtCore.QObject), (\n \"Argument 'base' must be of type \")\n\n if base is None:\n q_object = func(long(ptr), Qt.QtCore.QObject)\n meta_object = q_object.metaObject()\n class_name = meta_object.className()\n super_class_name = meta_object.superClass().className()\n\n if hasattr(Qt.QtWidgets, class_name):\n base = getattr(Qt.QtWidgets, class_name)\n\n elif hasattr(Qt.QtWidgets, super_class_name):\n base = getattr(Qt.QtWidgets, super_class_name)\n\n else:\n base = Qt.QtCore.QObject\n\n return func(long(ptr), base)\n\n\ndef _reassign_misplaced_members(binding):\n \"\"\"Apply misplaced members from `binding` to Qt.py\n\n Arguments:\n binding (dict): Misplaced members\n\n \"\"\"\n\n for src, dst in _misplaced_members[binding].items():\n src_module, src_member = src.split(\".\")\n dst_module, dst_member = dst.split(\".\")\n\n # Get the member we want to store in the namesapce.\n try:\n dst_value = getattr(getattr(Qt, \"_\" + src_module), src_member)\n except AttributeError:\n # If the member we want to store in the namespace does not exist,\n # there is no need to continue. This can happen if a request was\n # made to rename a member that didn't exist, for example\n # if QtWidgets isn't available on the target platform.\n _log(\"Misplaced member has no source: {}\".format(src))\n continue\n\n try:\n src_object = getattr(Qt, dst_module)\n except AttributeError:\n if dst_module not in common_members:\n # Only create the Qt parent module if its listed in\n # common_members. Without this check, if you remove QtCore\n # from common_members, the default _misplaced_members will add\n # Qt.QtCore so it can add Signal, Slot, etc.\n msg = 'Not creating missing member module \"{m}\" for \"{c}\"'\n _log(msg.format(m=dst_module, c=dst_member))\n continue\n # If the dst is valid but the Qt parent module does not exist\n # then go ahead and create a new module to contain the member.\n setattr(Qt, dst_module, _new_module(dst_module))\n src_object = getattr(Qt, dst_module)\n # Enable direct import of the new module\n sys.modules[__name__ + \".\" + dst_module] = src_object\n\n setattr(\n src_object,\n dst_member,\n dst_value\n )\n\n\ndef _build_compatibility_members(binding, decorators=None):\n \"\"\"Apply `binding` to QtCompat\n\n Arguments:\n binding (str): Top level binding in _compatibility_members.\n decorators (dict, optional): Provides the ability to decorate the\n original Qt methods when needed by a binding. This can be used\n to change the returned value to a standard value. The key should\n be the classname, the value is a dict where the keys are the\n target method names, and the values are the decorator functions.\n\n \"\"\"\n\n decorators = decorators or dict()\n\n # Allow optional site-level customization of the compatibility members.\n # This method does not need to be implemented in QtSiteConfig.\n try:\n import QtSiteConfig\n except ImportError:\n pass\n else:\n if hasattr(QtSiteConfig, 'update_compatibility_decorators'):\n QtSiteConfig.update_compatibility_decorators(binding, decorators)\n\n _QtCompat = type(\"QtCompat\", (object,), {})\n\n for classname, bindings in _compatibility_members[binding].items():\n attrs = {}\n for target, binding in bindings.items():\n namespaces = binding.split('.')\n try:\n src_object = getattr(Qt, \"_\" + namespaces[0])\n except AttributeError as e:\n _log(\"QtCompat: AttributeError: %s\" % e)\n # Skip reassignment of non-existing members.\n # This can happen if a request was made to\n # rename a member that didn't exist, for example\n # if QtWidgets isn't available on the target platform.\n continue\n\n # Walk down any remaining namespace getting the object assuming\n # that if the first namespace exists the rest will exist.\n for namespace in namespaces[1:]:\n src_object = getattr(src_object, namespace)\n\n # decorate the Qt method if a decorator was provided.\n if target in decorators.get(classname, []):\n # staticmethod must be called on the decorated method to\n # prevent a TypeError being raised when the decorated method\n # is called.\n src_object = staticmethod(\n decorators[classname][target](src_object))\n\n attrs[target] = src_object\n\n # Create the QtCompat class and install it into the namespace\n compat_class = type(classname, (_QtCompat,), attrs)\n setattr(Qt.QtCompat, classname, compat_class)\n\n\ndef _pyside2():\n \"\"\"Initialise PySide2\n\n These functions serve to test the existence of a binding\n along with set it up in such a way that it aligns with\n the final step; adding members from the original binding\n to Qt.py\n\n \"\"\"\n import PySide2 as module\n _setup(module, [\"QtUiTools\"])\n\n Qt.__binding_version__ = module.__version__\n\n try:\n try:\n # Before merge of PySide and shiboken\n import shiboken2\n except ImportError:\n # After merge of PySide and shiboken, May 2017\n from PySide2 import shiboken2\n\n Qt.QtCompat.wrapInstance = (\n lambda ptr, base=None: _wrapinstance(\n shiboken2.wrapInstance, ptr, base)\n )\n Qt.QtCompat.getCppPointer = lambda object: \\\n shiboken2.getCppPointer(object)[0]\n\n except ImportError:\n pass # Optional\n\n if hasattr(Qt, \"_QtUiTools\"):\n Qt.QtCompat.loadUi = _loadUi\n\n if hasattr(Qt, \"_QtCore\"):\n Qt.__qt_version__ = Qt._QtCore.qVersion()\n Qt.QtCompat.qInstallMessageHandler = _qInstallMessageHandler\n Qt.QtCompat.translate = Qt._QtCore.QCoreApplication.translate\n\n if hasattr(Qt, \"_QtWidgets\"):\n Qt.QtCompat.setSectionResizeMode = \\\n Qt._QtWidgets.QHeaderView.setSectionResizeMode\n\n _reassign_misplaced_members(\"PySide2\")\n _build_compatibility_members(\"PySide2\")\n\n\ndef _pyside():\n \"\"\"Initialise PySide\"\"\"\n\n import PySide as module\n _setup(module, [\"QtUiTools\"])\n\n Qt.__binding_version__ = module.__version__\n\n try:\n try:\n # Before merge of PySide and shiboken\n import shiboken\n except ImportError:\n # After merge of PySide and shiboken, May 2017\n from PySide import shiboken\n\n Qt.QtCompat.wrapInstance = (\n lambda ptr, base=None: _wrapinstance(\n shiboken.wrapInstance, ptr, base)\n )\n Qt.QtCompat.getCppPointer = lambda object: \\\n shiboken.getCppPointer(object)[0]\n\n except ImportError:\n pass # Optional\n\n if hasattr(Qt, \"_QtUiTools\"):\n Qt.QtCompat.loadUi = _loadUi\n\n if hasattr(Qt, \"_QtGui\"):\n setattr(Qt, \"QtWidgets\", _new_module(\"QtWidgets\"))\n setattr(Qt, \"_QtWidgets\", Qt._QtGui)\n if hasattr(Qt._QtGui, \"QX11Info\"):\n setattr(Qt, \"QtX11Extras\", _new_module(\"QtX11Extras\"))\n Qt.QtX11Extras.QX11Info = Qt._QtGui.QX11Info\n\n Qt.QtCompat.setSectionResizeMode = Qt._QtGui.QHeaderView.setResizeMode\n\n if hasattr(Qt, \"_QtCore\"):\n Qt.__qt_version__ = Qt._QtCore.qVersion()\n QCoreApplication = Qt._QtCore.QCoreApplication\n Qt.QtCompat.qInstallMessageHandler = _qInstallMessageHandler\n Qt.QtCompat.translate = (\n lambda context, sourceText, disambiguation, n:\n QCoreApplication.translate(\n context,\n sourceText,\n disambiguation,\n QCoreApplication.CodecForTr,\n n\n )\n )\n\n _reassign_misplaced_members(\"PySide\")\n _build_compatibility_members(\"PySide\")\n\n\ndef _pyqt5():\n \"\"\"Initialise PyQt5\"\"\"\n\n import PyQt5 as module\n _setup(module, [\"uic\"])\n\n try:\n import sip\n Qt.QtCompat.wrapInstance = (\n lambda ptr, base=None: _wrapinstance(\n sip.wrapinstance, ptr, base)\n )\n Qt.QtCompat.getCppPointer = lambda object: \\\n sip.unwrapinstance(object)\n\n except ImportError:\n pass # Optional\n\n if hasattr(Qt, \"_uic\"):\n Qt.QtCompat.loadUi = _loadUi\n\n if hasattr(Qt, \"_QtCore\"):\n Qt.__binding_version__ = Qt._QtCore.PYQT_VERSION_STR\n Qt.__qt_version__ = Qt._QtCore.QT_VERSION_STR\n Qt.QtCompat.qInstallMessageHandler = _qInstallMessageHandler\n Qt.QtCompat.translate = Qt._QtCore.QCoreApplication.translate\n\n if hasattr(Qt, \"_QtWidgets\"):\n Qt.QtCompat.setSectionResizeMode = \\\n Qt._QtWidgets.QHeaderView.setSectionResizeMode\n\n _reassign_misplaced_members(\"PyQt5\")\n _build_compatibility_members('PyQt5')\n\n\ndef _pyqt4():\n \"\"\"Initialise PyQt4\"\"\"\n\n import sip\n\n # Validation of envivornment variable. Prevents an error if\n # the variable is invalid since it's just a hint.\n try:\n hint = int(QT_SIP_API_HINT)\n except TypeError:\n hint = None # Variable was None, i.e. not set.\n except ValueError:\n raise ImportError(\"QT_SIP_API_HINT=%s must be a 1 or 2\")\n\n for api in (\"QString\",\n \"QVariant\",\n \"QDate\",\n \"QDateTime\",\n \"QTextStream\",\n \"QTime\",\n \"QUrl\"):\n try:\n sip.setapi(api, hint or 2)\n except AttributeError:\n raise ImportError(\"PyQt4 < 4.6 isn't supported by Qt.py\")\n except ValueError:\n actual = sip.getapi(api)\n if not hint:\n raise ImportError(\"API version already set to %d\" % actual)\n else:\n # Having provided a hint indicates a soft constraint, one\n # that doesn't throw an exception.\n sys.stderr.write(\n \"Warning: API '%s' has already been set to %d.\\n\"\n % (api, actual)\n )\n\n import PyQt4 as module\n _setup(module, [\"uic\"])\n\n try:\n import sip\n Qt.QtCompat.wrapInstance = (\n lambda ptr, base=None: _wrapinstance(\n sip.wrapinstance, ptr, base)\n )\n Qt.QtCompat.getCppPointer = lambda object: \\\n sip.unwrapinstance(object)\n\n except ImportError:\n pass # Optional\n\n if hasattr(Qt, \"_uic\"):\n Qt.QtCompat.loadUi = _loadUi\n\n if hasattr(Qt, \"_QtGui\"):\n setattr(Qt, \"QtWidgets\", _new_module(\"QtWidgets\"))\n setattr(Qt, \"_QtWidgets\", Qt._QtGui)\n if hasattr(Qt._QtGui, \"QX11Info\"):\n setattr(Qt, \"QtX11Extras\", _new_module(\"QtX11Extras\"))\n Qt.QtX11Extras.QX11Info = Qt._QtGui.QX11Info\n\n Qt.QtCompat.setSectionResizeMode = \\\n Qt._QtGui.QHeaderView.setResizeMode\n\n if hasattr(Qt, \"_QtCore\"):\n Qt.__binding_version__ = Qt._QtCore.PYQT_VERSION_STR\n Qt.__qt_version__ = Qt._QtCore.QT_VERSION_STR\n QCoreApplication = Qt._QtCore.QCoreApplication\n Qt.QtCompat.qInstallMessageHandler = _qInstallMessageHandler\n Qt.QtCompat.translate = (\n lambda context, sourceText, disambiguation, n:\n QCoreApplication.translate(\n context,\n sourceText,\n disambiguation,\n QCoreApplication.CodecForTr,\n n)\n )\n\n _reassign_misplaced_members(\"PyQt4\")\n\n # QFileDialog QtCompat decorator\n def _standardizeQFileDialog(some_function):\n \"\"\"Decorator that makes PyQt4 return conform to other bindings\"\"\"\n def wrapper(*args, **kwargs):\n ret = (some_function(*args, **kwargs))\n\n # PyQt4 only returns the selected filename, force it to a\n # standard return of the selected filename, and a empty string\n # for the selected filter\n return ret, ''\n\n wrapper.__doc__ = some_function.__doc__\n wrapper.__name__ = some_function.__name__\n\n return wrapper\n\n decorators = {\n \"QFileDialog\": {\n \"getOpenFileName\": _standardizeQFileDialog,\n \"getOpenFileNames\": _standardizeQFileDialog,\n \"getSaveFileName\": _standardizeQFileDialog,\n }\n }\n _build_compatibility_members('PyQt4', decorators)\n\n\ndef _none():\n \"\"\"Internal option (used in installer)\"\"\"\n\n Mock = type(\"Mock\", (), {\"__getattr__\": lambda Qt, attr: None})\n\n Qt.__binding__ = \"None\"\n Qt.__qt_version__ = \"0.0.0\"\n Qt.__binding_version__ = \"0.0.0\"\n Qt.QtCompat.loadUi = lambda uifile, baseinstance=None: None\n Qt.QtCompat.setSectionResizeMode = lambda *args, **kwargs: None\n\n for submodule in common_members.keys():\n setattr(Qt, submodule, Mock())\n setattr(Qt, \"_\" + submodule, Mock())\n\n\ndef _log(text):\n if QT_VERBOSE:\n sys.stdout.write(text + \"\\n\")\n\n\ndef _loadUi(uifile, baseinstance=None):\n \"\"\"Dynamically load a user interface from the given `uifile`\n\n This function calls `uic.loadUi` if using PyQt bindings,\n else it implements a comparable binding for PySide.\n\n Documentation:\n http://pyqt.sourceforge.net/Docs/PyQt5/designer.html#PyQt5.uic.loadUi\n\n Arguments:\n uifile (str): Absolute path to Qt Designer file.\n baseinstance (QWidget): Instantiated QWidget or subclass thereof\n\n Return:\n baseinstance if `baseinstance` is not `None`. Otherwise\n return the newly created instance of the user interface.\n\n \"\"\"\n\n if hasattr(Qt, \"_uic\"):\n return Qt._uic.loadUi(uifile, baseinstance)\n\n elif hasattr(Qt, \"_QtUiTools\"):\n # Implement `PyQt5.uic.loadUi` for PySide(2)\n\n class _UiLoader(Qt._QtUiTools.QUiLoader):\n \"\"\"Create the user interface in a base instance.\n\n Unlike `Qt._QtUiTools.QUiLoader` itself this class does not\n create a new instance of the top-level widget, but creates the user\n interface in an existing instance of the top-level class if needed.\n\n This mimics the behaviour of `PyQt5.uic.loadUi`.\n\n \"\"\"\n\n def __init__(self, baseinstance):\n super(_UiLoader, self).__init__(baseinstance)\n self.baseinstance = baseinstance\n\n def load(self, uifile, *args, **kwargs):\n from xml.etree.ElementTree import ElementTree\n\n # For whatever reason, if this doesn't happen then\n # reading an invalid or non-existing .ui file throws\n # a RuntimeError.\n etree = ElementTree()\n etree.parse(uifile)\n\n widget = Qt._QtUiTools.QUiLoader.load(\n self, uifile, *args, **kwargs)\n\n # Workaround for PySide 1.0.9, see issue #208\n widget.parentWidget()\n\n return widget\n\n def createWidget(self, class_name, parent=None, name=\"\"):\n \"\"\"Called for each widget defined in ui file\n\n Overridden here to populate `baseinstance` instead.\n\n \"\"\"\n\n if parent is None and self.baseinstance:\n # Supposed to create the top-level widget,\n # return the base instance instead\n return self.baseinstance\n\n # For some reason, Line is not in the list of available\n # widgets, but works fine, so we have to special case it here.\n if class_name in self.availableWidgets() + [\"Line\"]:\n # Create a new widget for child widgets\n widget = Qt._QtUiTools.QUiLoader.createWidget(self,\n class_name,\n parent,\n name)\n\n else:\n raise Exception(\"Custom widget '%s' not supported\"\n % class_name)\n\n if self.baseinstance:\n # Set an attribute for the new child widget on the base\n # instance, just like PyQt5.uic.loadUi does.\n setattr(self.baseinstance, name, widget)\n\n return widget\n\n widget = _UiLoader(baseinstance).load(uifile)\n Qt.QtCore.QMetaObject.connectSlotsByName(widget)\n\n return widget\n\n else:\n raise NotImplementedError(\"No implementation available for loadUi\")\n\n\ndef _qInstallMessageHandler(handler):\n \"\"\"Install a message handler that works in all bindings\n\n Args:\n handler: A function that takes 3 arguments, or None\n \"\"\"\n def messageOutputHandler(*args):\n # In Qt4 bindings, message handlers are passed 2 arguments\n # In Qt5 bindings, message handlers are passed 3 arguments\n # The first argument is a QtMsgType\n # The last argument is the message to be printed\n # The Middle argument (if passed) is a QMessageLogContext\n if len(args) == 3:\n msgType, logContext, msg = args\n elif len(args) == 2:\n msgType, msg = args\n logContext = None\n else:\n raise TypeError(\n \"handler expected 2 or 3 arguments, got {0}\".format(len(args)))\n\n if isinstance(msg, bytes):\n # In python 3, some bindings pass a bytestring, which cannot be\n # used elsewhere. Decoding a python 2 or 3 bytestring object will\n # consistently return a unicode object.\n msg = msg.decode()\n\n handler(msgType, logContext, msg)\n\n passObject = messageOutputHandler if handler else handler\n if Qt.IsPySide or Qt.IsPyQt4:\n return Qt._QtCore.qInstallMsgHandler(passObject)\n elif Qt.IsPySide2 or Qt.IsPyQt5:\n return Qt._QtCore.qInstallMessageHandler(passObject)\n\n\n\ndef _convert(lines):\n \"\"\"Convert compiled .ui file from PySide2 to Qt.py\n\n Arguments:\n lines (list): Each line of of .ui file\n\n Usage:\n >> with open(\"myui.py\") as f:\n .. lines = _convert(f.readlines())\n\n \"\"\"\n\n def parse(line):\n line = line.replace(\"from PySide2 import\", \"from Qt import QtCompat,\")\n line = line.replace(\"QtWidgets.QApplication.translate\",\n \"QtCompat.translate\")\n if \"QtCore.SIGNAL\" in line:\n raise NotImplementedError(\"QtCore.SIGNAL is missing from PyQt5 \"\n \"and so Qt.py does not support it: you \"\n \"should avoid defining signals inside \"\n \"your ui files.\")\n return line\n\n parsed = list()\n for line in lines:\n line = parse(line)\n parsed.append(line)\n\n return parsed\n\n\ndef _cli(args):\n \"\"\"Qt.py command-line interface\"\"\"\n import argparse\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--convert\",\n help=\"Path to compiled Python module, e.g. my_ui.py\")\n parser.add_argument(\"--compile\",\n help=\"Accept raw .ui file and compile with native \"\n \"PySide2 compiler.\")\n parser.add_argument(\"--stdout\",\n help=\"Write to stdout instead of file\",\n action=\"store_true\")\n parser.add_argument(\"--stdin\",\n help=\"Read from stdin instead of file\",\n action=\"store_true\")\n\n args = parser.parse_args(args)\n\n if args.stdout:\n raise NotImplementedError(\"--stdout\")\n\n if args.stdin:\n raise NotImplementedError(\"--stdin\")\n\n if args.compile:\n raise NotImplementedError(\"--compile\")\n\n if args.convert:\n sys.stdout.write(\"#\\n\"\n \"# WARNING: --convert is an ALPHA feature.\\n#\\n\"\n \"# See https://github.com/mottosso/Qt.py/pull/132\\n\"\n \"# for details.\\n\"\n \"#\\n\")\n\n with open(args.convert) as f:\n lines = _convert(f.readlines())\n\n backup = \"%s_backup%s\" % os.path.splitext(args.convert)\n sys.stdout.write(\"Creating \\\"%s\\\"..\\n\" % backup)\n shutil.copy(args.convert, backup)\n\n with open(args.convert, \"w\") as f:\n f.write(\"\".join(lines))\n\n sys.stdout.write(\"Successfully converted \\\"%s\\\"\\n\" % args.convert)\n\n\ndef _install():\n # Default order (customise order and content via QT_PREFERRED_BINDING)\n default_order = (\"PySide2\", \"PyQt5\", \"PySide\", \"PyQt4\")\n preferred_order = list(\n b for b in QT_PREFERRED_BINDING.split(os.pathsep) if b\n )\n\n order = preferred_order or default_order\n\n available = {\n \"PySide2\": _pyside2,\n \"PyQt5\": _pyqt5,\n \"PySide\": _pyside,\n \"PyQt4\": _pyqt4,\n \"None\": _none\n }\n\n _log(\"Order: '%s'\" % \"', '\".join(order))\n\n # Allow site-level customization of the available modules.\n _apply_site_config()\n\n found_binding = False\n for name in order:\n _log(\"Trying %s\" % name)\n\n try:\n available[name]()\n found_binding = True\n break\n\n except ImportError as e:\n _log(\"ImportError: %s\" % e)\n\n except KeyError:\n _log(\"ImportError: Preferred binding '%s' not found.\" % name)\n\n if not found_binding:\n # If not binding were found, throw this error\n raise ImportError(\"No Qt binding were found.\")\n\n # Install individual members\n for name, members in common_members.items():\n try:\n their_submodule = getattr(Qt, \"_%s\" % name)\n except AttributeError:\n continue\n\n our_submodule = getattr(Qt, name)\n\n # Enable import *\n __all__.append(name)\n\n # Enable direct import of submodule,\n # e.g. import Qt.QtCore\n sys.modules[__name__ + \".\" + name] = our_submodule\n\n for member in members:\n # Accept that a submodule may miss certain members.\n try:\n their_member = getattr(their_submodule, member)\n except AttributeError:\n _log(\"'%s.%s' was missing.\" % (name, member))\n continue\n\n setattr(our_submodule, member, their_member)\n\n # Enable direct import of QtCompat\n sys.modules['Qt.QtCompat'] = Qt.QtCompat\n\n # Backwards compatibility\n if hasattr(Qt.QtCompat, 'loadUi'):\n Qt.QtCompat.load_ui = Qt.QtCompat.loadUi\n\n\n_install()\n\n# Setup Binding Enum states\nQt.IsPySide2 = Qt.__binding__ == 'PySide2'\nQt.IsPyQt5 = Qt.__binding__ == 'PyQt5'\nQt.IsPySide = Qt.__binding__ == 'PySide'\nQt.IsPyQt4 = Qt.__binding__ == 'PyQt4'\n\n\"\"\"\nAugment QtCompat\n\nQtCompat contains wrappers and added functionality\nto the original bindings, such as the CLI interface\nand otherwise incompatible members between bindings,\nsuch as `QHeaderView.setSectionResizeMode`.\n\n\"\"\"\n\nQt.QtCompat._cli = _cli\nQt.QtCompat._convert = _convert\n\n# Enable command-line interface\nif __name__ == \"__main__\":\n _cli(sys.argv[1:])\n\n","sub_path":"src/Qt/bindings/builder.py","file_name":"builder.py","file_ext":"py","file_size_in_byte":26908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"19242236","text":"import numpy as np\nfrom numpy import math\nfrom matplotlib import pyplot as plt\n\nx = [-1.5, -1., -.5, 0., .5, 1., 1.5, .75, -.75]\ny = [0., -1., -2., -2., -2., -1., 0., 2., 2.]\n\nA = np.array([x, y])\n\n\ndef strc(A, x, y):\n strec = np.array([[x, 0.], [0., y]])\n newA = np.dot(strec, A)\n\n plt.subplot(2, 1, 1)\n plt.plot(A[0], A[1], '.')\n plt.xlim(-5, 5)\n plt.ylim(-5, 5)\n plt.subplot(2, 1, 2)\n plt.plot(newA[0], newA[1], '.')\n plt.xlim(-5, 5)\n plt.ylim(-5, 5)\n plt.show()\n\n\ndef rotate(A, ang):\n c, s = math.cos(ang), math.sin(ang)\n\n rotat = np.array([[c, -s], [s, c]])\n newA = np.dot(rotat, A)\n \n plt.subplot(2, 1, 1)\n plt.plot(A[0], A[1], '.')\n plt.xlim(-5, 5)\n plt.ylim(-5, 5)\n plt.subplot(2, 1, 2)\n plt.plot(newA[0], newA[1], '.')\n plt.xlim(-5, 5)\n plt.ylim(-5, 5)\n plt.show()\n\n\ndef shift(A, x, y):\n shift = np.array([[x], [y]])\n newA = A+shift\n \n plt.subplot(2, 1, 1)\n plt.plot(A[0], A[1], '.')\n plt.xlim(-5, 5)\n plt.ylim(-5, 5)\n plt.subplot(2, 1, 2)\n plt.plot(newA[0], newA[1], '.')\n plt.xlim(-5, 5)\n plt.ylim(-5, 5)\n plt.show()\n\n\ndef combo(A, strX, strY, ang, shiftX, shiftY):\n c, s = math.cos(ang), math.sin(ang)\n\n strec = np.array([[strX, 0.], [0., strY]])\n rotat = np.array([[c, -s], [s, c]])\n shift = np.array([[shiftX], [shiftY]])\n newA = rotat.dot(strec).dot(A)+shift\n\n plt.subplot(2, 1, 1)\n plt.plot(A[0], A[1], '.')\n plt.xlim(-8, 8)\n plt.ylim(-8, 8)\n plt.subplot(2, 1, 2)\n plt.plot(newA[0], newA[1], '.')\n plt.xlim(-8, 8)\n plt.ylim(-8, 8)\n plt.show()\n\n\n\ndef imgR(img, ang):\n m, n = img.shape[:2]\n c, s = math.cos(ang), math.sin(ang)\n\n q = int(max(m, n)*1.5)\n newImg = np.ones((q, q, 3))\n for i in xrange(m):\n for j in xrange(n):\n k = int(round((i-m/2)*c+(j-n/2)*-s+q/2))\n l = int(round((i-m/2)*s+(j-n/2)*c+q/2))\n newImg[k, l,:] = img[i, j,:]\n plt.imshow(newImg)\n plt.show()\n\ndef rotImg():\n img_color = plt.imread('dream.png')\n\n ang = 2*np.pi/8.\n imgR(img_color[:,:], ang)\n\n\n plt.imshow(img_color)\n plt.show()\n\nif __name__ == \"__main__\":\n strc(A, 2, 1.5)\n\n ang = 3*np.pi/16.\n rotate(A, ang)\n\n shift(A, 2, 1.5)\n\n ang = 3*np.pi/4.\n combo(A, 2., 2., ang, 1., -2.)\n\n rotImg()\n","sub_path":"Algorithms/ChangeBasis/basis.py","file_name":"basis.py","file_ext":"py","file_size_in_byte":2326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"310775177","text":"#\n# Lead-acid LOQS model\n#\nimport pybamm\nfrom .base_lead_acid_model import BaseModel\n\n\nclass LOQS(BaseModel):\n \"\"\"Leading-Order Quasi-Static model for lead-acid, from [1]_.\n\n Parameters\n ----------\n options : dict, optional\n A dictionary of options to be passed to the model.\n name : str, optional\n The name of the model.\n build : bool, optional\n Whether to build the model on instantiation. Default is True. Setting this\n option to False allows users to change any number of the submodels before\n building the complete model (submodels cannot be changed after the model is\n built).\n\n References\n ----------\n .. [1] V Sulzer, SJ Chapman, CP Please, DA Howey, and CW Monroe. Faster lead-acid\n battery simulations from porous-electrode theory: Part II. Asymptotic\n analysis. Journal of The Electrochemical Society 166.12 (2019), A2372–A2382.\n\n\n **Extends:** :class:`pybamm.lead_acid.BaseModel`\n \"\"\"\n\n def __init__(self, options=None, name=\"LOQS model\", build=True):\n super().__init__(options, name)\n\n self.set_external_circuit_submodel()\n self.set_interfacial_submodel()\n self.set_convection_submodel()\n self.set_porosity_submodel()\n self.set_active_material_submodel()\n self.set_tortuosity_submodels()\n self.set_electrolyte_submodel()\n self.set_electrode_submodels()\n self.set_thermal_submodel()\n self.set_side_reaction_submodels()\n self.set_current_collector_submodel()\n self.set_sei_submodel()\n self.set_lithium_plating_submodel()\n\n if build:\n self.build_model()\n\n if self.options[\"dimensionality\"] == 0:\n self.use_jacobian = False\n\n pybamm.citations.register(\"Sulzer2019asymptotic\")\n\n def set_external_circuit_submodel(self):\n \"\"\"\n Define how the external circuit defines the boundary conditions for the model,\n e.g. (not necessarily constant-) current, voltage, etc\n \"\"\"\n if self.options[\"operating mode\"] == \"current\":\n self.submodels[\n \"leading order external circuit\"\n ] = pybamm.external_circuit.LeadingOrderCurrentControl(self.param)\n elif self.options[\"operating mode\"] == \"voltage\":\n self.submodels[\n \"leading order external circuit\"\n ] = pybamm.external_circuit.LeadingOrderVoltageFunctionControl(self.param)\n elif self.options[\"operating mode\"] == \"power\":\n self.submodels[\n \"leading order external circuit\"\n ] = pybamm.external_circuit.LeadingOrderPowerFunctionControl(self.param)\n elif callable(self.options[\"operating mode\"]):\n self.submodels[\n \"leading order external circuit\"\n ] = pybamm.external_circuit.LeadingOrderFunctionControl(\n self.param, self.options[\"operating mode\"]\n )\n\n def set_current_collector_submodel(self):\n\n if self.options[\"current collector\"] in [\n \"uniform\",\n \"potential pair quite conductive\",\n ]:\n submodel = pybamm.current_collector.Uniform(self.param)\n elif self.options[\"current collector\"] == \"potential pair\":\n if self.options[\"dimensionality\"] == 1:\n submodel = pybamm.current_collector.PotentialPair1plus1D(self.param)\n elif self.options[\"dimensionality\"] == 2:\n submodel = pybamm.current_collector.PotentialPair2plus1D(self.param)\n self.submodels[\"leading-order current collector\"] = submodel\n\n def set_porosity_submodel(self):\n\n self.submodels[\"leading-order porosity\"] = pybamm.porosity.LeadingOrder(\n self.param\n )\n\n def set_tortuosity_submodels(self):\n self.submodels[\n \"leading-order electrolyte tortuosity\"\n ] = pybamm.tortuosity.Bruggeman(self.param, \"Electrolyte\")\n self.submodels[\n \"leading-order electrode tortuosity\"\n ] = pybamm.tortuosity.Bruggeman(self.param, \"Electrode\")\n\n def set_convection_submodel(self):\n\n if self.options[\"convection\"] == \"none\":\n self.submodels[\n \"leading-order transverse convection\"\n ] = pybamm.convection.transverse.NoConvection(self.param)\n self.submodels[\n \"leading-order through-cell convection\"\n ] = pybamm.convection.through_cell.NoConvection(self.param)\n else:\n if self.options[\"convection\"] == \"uniform transverse\":\n self.submodels[\n \"leading-order transverse convection\"\n ] = pybamm.convection.transverse.Uniform(self.param)\n elif self.options[\"convection\"] == \"full transverse\":\n self.submodels[\n \"leading-order transverse convection\"\n ] = pybamm.convection.transverse.Full(self.param)\n self.submodels[\n \"leading-order through-cell convection\"\n ] = pybamm.convection.through_cell.Explicit(self.param)\n\n def set_interfacial_submodel(self):\n\n if self.options[\"surface form\"] == \"false\":\n self.submodels[\n \"leading-order negative interface\"\n ] = pybamm.interface.InverseButlerVolmer(\n self.param, \"Negative\", \"lead-acid main\", self.options\n )\n self.submodels[\n \"leading-order positive interface\"\n ] = pybamm.interface.InverseButlerVolmer(\n self.param, \"Positive\", \"lead-acid main\", self.options\n )\n self.submodels[\n \"negative interface current\"\n ] = pybamm.interface.CurrentForInverseButlerVolmer(\n self.param, \"Negative\", \"lead-acid main\"\n )\n self.submodels[\n \"positive interface current\"\n ] = pybamm.interface.CurrentForInverseButlerVolmer(\n self.param, \"Positive\", \"lead-acid main\"\n )\n else:\n self.submodels[\n \"leading-order negative interface\"\n ] = pybamm.interface.ButlerVolmer(\n self.param, \"Negative\", \"lead-acid main\", self.options\n )\n\n self.submodels[\n \"leading-order positive interface\"\n ] = pybamm.interface.ButlerVolmer(\n self.param, \"Positive\", \"lead-acid main\", self.options\n )\n # always use forward Butler-Volmer for the reaction submodel to be passed to the\n # higher order model\n self.reaction_submodels = {\n \"Negative\": [\n pybamm.interface.ButlerVolmer(\n self.param, \"Negative\", \"lead-acid main\", self.options\n )\n ],\n \"Positive\": [\n pybamm.interface.ButlerVolmer(\n self.param, \"Positive\", \"lead-acid main\", self.options\n )\n ],\n }\n\n def set_electrode_submodels(self):\n\n self.submodels[\n \"leading-order negative electrode potential\"\n ] = pybamm.electrode.ohm.LeadingOrder(self.param, \"Negative\")\n self.submodels[\n \"leading-order positive electrode potential\"\n ] = pybamm.electrode.ohm.LeadingOrder(self.param, \"Positive\")\n\n def set_electrolyte_submodel(self):\n\n surf_form = pybamm.electrolyte_conductivity.surface_potential_form\n\n if self.options[\"surface form\"] == \"false\":\n self.submodels[\n \"leading-order electrolyte conductivity\"\n ] = pybamm.electrolyte_conductivity.LeadingOrder(self.param)\n\n elif self.options[\"surface form\"] == \"differential\":\n for domain in [\"Negative\", \"Separator\", \"Positive\"]:\n self.submodels[\n \"leading-order \" + domain.lower() + \" electrolyte conductivity\"\n ] = surf_form.LeadingOrderDifferential(self.param, domain)\n\n elif self.options[\"surface form\"] == \"algebraic\":\n for domain in [\"Negative\", \"Separator\", \"Positive\"]:\n self.submodels[\n \"leading-order \" + domain.lower() + \" electrolyte conductivity\"\n ] = surf_form.LeadingOrderAlgebraic(self.param, domain)\n\n self.submodels[\n \"electrolyte diffusion\"\n ] = pybamm.electrolyte_diffusion.LeadingOrder(self.param)\n\n def set_side_reaction_submodels(self):\n if \"oxygen\" in self.options[\"side reactions\"]:\n self.submodels[\n \"leading-order oxygen diffusion\"\n ] = pybamm.oxygen_diffusion.LeadingOrder(self.param)\n self.submodels[\n \"leading-order positive oxygen interface\"\n ] = pybamm.interface.ForwardTafel(\n self.param, \"Positive\", \"lead-acid oxygen\", self.options\n )\n self.submodels[\n \"leading-order negative oxygen interface\"\n ] = pybamm.interface.DiffusionLimited(\n self.param, \"Negative\", \"lead-acid oxygen\", order=\"leading\"\n )\n else:\n self.submodels[\n \"leading-order oxygen diffusion\"\n ] = pybamm.oxygen_diffusion.NoOxygen(self.param)\n self.submodels[\n \"leading-order negative oxygen interface\"\n ] = pybamm.interface.NoReaction(self.param, \"Negative\", \"lead-acid oxygen\")\n self.submodels[\n \"leading-order positive oxygen interface\"\n ] = pybamm.interface.NoReaction(self.param, \"Positive\", \"lead-acid oxygen\")\n self.reaction_submodels[\"Negative\"].append(\n self.submodels[\"leading-order negative oxygen interface\"]\n )\n self.reaction_submodels[\"Positive\"].append(\n self.submodels[\"leading-order positive oxygen interface\"]\n )\n","sub_path":"pybamm/models/full_battery_models/lead_acid/loqs.py","file_name":"loqs.py","file_ext":"py","file_size_in_byte":9908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"522330165","text":"__author__ = 'aniket'\n\nimport cv2\nimport numpy as np\n\nimg = cv2.imread('paka.jpg',0)\nrows,cols = img.shape\n\nM = np.float32([[1,0,1000],[0,1,50]])\ndst = cv2.warpAffine(img, M, (cols,rows))\n\ncv2.imshow('img',dst)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n\"\"\"This code translates the image to a new position\"\"\"\n","sub_path":"Resources/Examples/PycharmProjects/Geometric Transformations/Translation.py","file_name":"Translation.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"81788477","text":"from __future__ import print_function\n\n# --------------- Main handler ------------------\n\ndef lambda_handler(event, context):\n \"\"\" Route the incoming request based on type (LaunchRequest, IntentRequest,\n etc.) The JSON body of the request is provided in the event parameter.\n \"\"\"\n print(\"event.session.application.applicationId=\" +\n event['session']['application']['applicationId'])\n \"\"\"\n Uncomment this if statement and populate with your skill's application ID to\n prevent someone else from configuring a skill that sends requests to this\n function.\n \"\"\"\n # if (event['session']['application']['applicationId'] !=\n # \"amzn1.echo-sdk-ams.app.[unique-value-here]\"):\n # raise ValueError(\"Invalid Application ID\")\n \n if event['request']['type'] == \"LaunchRequest\":\n return on_launch(event, context)\n\n elif event['request']['type'] == \"IntentRequest\":\n return intent_router(event, context)\n \n# --------------- Intent Routing ------------------\n\ndef intent_router(event, context):\n intent = event['request']['intent']['name']\n \n # Custom Intent\n \n if intent == \"Account_balance\":\n return balance_enquiry(event, context)\n\n # Required Intents\n\n if intent == \"AMAZON.CancelIntent\":\n return cancel_intent()\n\n if intent == \"AMAZON.HelpIntent\":\n return help_intent()\n\n if intent == \"AMAZON.StopIntent\":\n return stop_intent()\n\n# --------------- Lauch Event Request ------------------\n\ndef on_launch(event, context):\n return statement(\"title\", \"body\")\n\n\n# --------------- Intent Request ------------------\n\n# +++++++++++++ Custom Intent ++++++++++++++\n\ndef balance_enquiry(event, context):\n dialog_state = event['request']['dialogState']\n \n if dialog_state in (\"STARTED\", \"IN_PROGRESS\"):\n return continue_dialog()\n \n elif dialog_state == \"COMPLETED\":\n return statement(\"balance_enquiry\", \"Thanks for calling ABC Bank\")\n \n else:\n return statement(\"balance_enquiry\", \"No dialog\")\n \n \n# ++++++++++++++ Required Default Intents ++++++++++++++\n\ndef cancel_intent():\n return statement(\"CancelIntent\", \"You want to cancel\")\n\n\ndef help_intent():\n return statement(\"CancelIntent\", \"You want help\")\n\n\ndef stop_intent():\n return statement(\"StopIntent\", \"You want to stop\")\n\n\n# --------------- Build Responses ------------------\n\ndef conversation(title, body, session_attributes):\n speechlet = {}\n speechlet['outputSpeech'] = build_PlainSpeech(body)\n speechlet['card'] = build_SimpleCard(title, body)\n speechlet['shouldEndSession'] = False\n return build_response(speechlet, session_attributes=session_attributes)\n\n\ndef statement(title, body):\n speechlet = {}\n speechlet['outputSpeech'] = build_PlainSpeech(body)\n speechlet['card'] = build_SimpleCard(title, body)\n speechlet['shouldEndSession'] = True\n return build_response(speechlet)\n\n\ndef continue_dialog():\n message = {}\n message['shouldEndSession'] = False\n message['directives'] = [{'type': 'Dialog.Delegate'}]\n return build_response(message)\n\n# --------------- Helpers for Responses ------------------\n \ndef build_PlainSpeech(body):\n speech = {}\n speech['type'] = 'PlainText'\n speech['text'] = body\n return speech\n\n\ndef build_response(message, session_attributes={}):\n response = {}\n response['version'] = '1.0'\n response['sessionAttributes'] = session_attributes\n response['response'] = message\n return response\n\n\ndef build_SimpleCard(title, body):\n card = {}\n card['type'] = 'Simple'\n card['title'] = title\n card['content'] = body\n return card\n\n# --------------- Custom handlers ------------------\n","sub_path":"to try.py","file_name":"to try.py","file_ext":"py","file_size_in_byte":3717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"540446381","text":"import math\n\nWIDTH = 1200\nHEIGHT = 600 \n\ndef rectLineIntersect (x, y, w, h, pt1, pt2):\n rectL1 = ((x,y), (x+w,y))\n rectL2 = ((x,y), (x,y+h))\n rectL3 = ((x+w,y), (x+w,y+h))\n rectL4 = ((x,y+h), (x+w,y+h))\n\n poi1 = calculatePOI((x,y),(x+w,y), pt1, pt2) != False\n poi2 = calculatePOI((x,y),(x,y+h), pt1, pt2) != False\n poi3 = calculatePOI((x+w,y),(x+w,y+h), pt1, pt2) != False\n poi4 = calculatePOI((x,y+h),(x+w,y+h), pt1, pt2) != False\n\n return poi1 or poi2 or poi3 or poi4\n\ndef getSlope (pt1, pt2):\n x1, x2, y1, y2 = pt1[0], pt2[0], pt1[1], pt2[1]\n slope = None\n\n if ((x2 - x1) != 0):\n slope = (y2 - y1) / (x2 - x1)\n\ndef distance (pt1, pt2):\n return int (math.sqrt((pt1[0] - pt2[0])**2 + (pt1[1] - pt2[1])**2))\n\ndef pointOnLine (ptA, pt1, pt2):\n offset = 1\n\n x1, x2, y1, y2 = pt1[0], pt2[0], pt1[1], pt2[1]\n slopeOne = None\n\n if ((x2 - x1) != 0):\n slopeOne = (y2 - y1) / (x2 - x1)\n\n #next, calculate the y intercept of each line (b value)\n if (slopeOne != None):\n bOne = pt1[1] - (slopeOne) * pt1[0]\n else:\n bOne = pt1[0]\n\n if slopeOne == None:\n return abs( pt1[0] - ptA[0] ) <= offset\n elif slopeOne == 0:\n return abs( ptA[1] - bOne ) <= offset\n elif slopeIsValid(slopeOne):\n return abs( ptA[1] - ( slopeOne * ptA[0] + bOne) ) <= offset\n \ndef calculatePOI (pt1, pt2, ptA, ptB):\n\n #first, calculate slope of each line\n x1, x2, y1, y2 = pt1[0], pt2[0], pt1[1], pt2[1]\n slopeOne = None\n\n if ((x2 - x1) != 0):\n slopeOne = (y2 - y1) / (x2 - x1)\n\n x1, x2, y1, y2 = ptA[0], ptB[0], ptA[1], ptB[1]\n #print (x1, x2)\n slopeTwo = None\n if ((x2 - x1) != 0):\n slopeTwo = (y2 - y1) / (x2 - x1)\n\n #next, calculate the y intercept of each line (b value)\n if (slopeOne != None):\n bOne = pt1[1] - (slopeOne) * pt1[0]\n else:\n bOne = pt1[0]\n\n if (slopeTwo != None):\n bTwo = ptA[1] - (slopeTwo) * ptA[0]\n else:\n bTwo = ptA[0]\n\n if slopeOne == slopeTwo:\n return False\n elif slopeOne == None and slopeTwo == 0:\n poi = (pt1[0], ptA[1])\n elif (slopeOne == 0 and slopeTwo == None):\n poi = (ptA[0], pt1[1])\n elif (slopeIsValid(slopeOne) and slopeTwo == None):\n poi = (ptA[0], ptA[0]*slopeOne + bOne)\n elif (slopeIsValid(slopeTwo) and slopeOne == None):\n poi = (pt1[0], pt1[0]*slopeTwo + bTwo)\n elif (slopeIsValid(slopeOne) and slopeTwo == 0):\n poi = ((bTwo - bOne) / slopeOne, bTwo)\n elif (slopeIsValid(slopeTwo) and slopeOne == 0):\n poi = ((bOne - bTwo) / slopeTwo, bOne)\n elif (slopeIsValid(slopeOne) and slopeIsValid(slopeTwo) and slopeTwo < 0) :\n poi = ((bTwo - bOne) / (slopeOne - slopeTwo), slopeOne * ((bTwo - bOne) / (slopeOne - slopeTwo)) + bOne)\n elif (slopeIsValid(slopeOne) and slopeIsValid(slopeTwo) and slopeTwo > 0) :\n poi = ((bOne - bTwo) / (slopeTwo - slopeOne), slopeTwo * ((bOne - bTwo) / (slopeTwo - slopeOne)) + bTwo)\n\n if (poiIsValid(poi, pt1, pt2, ptA, ptB)):\n return (int(poi[0]), int(poi[1]))\n else:\n return False\n\ndef slopeIsValid (number):\n return number != 0 and number != None\n\ndef isBetween (poi, pt1, pt2, ptA, ptB):\n\n #Checking if POI is in the sensor range\n minX = min([item[0] for item in [pt1, pt2]])\n minY = min([item[1] for item in [pt1, pt2]])\n maxX = max([item[0] for item in [pt1, pt2]])\n maxY = max([item[1] for item in [pt1, pt2]])\n inSensorRange = poi[0] >= minX and poi[0] <= maxX and poi[1] >= minY and poi[1] <= maxY\n\n #Checking if POI is in the line's range\n minX = min([item[0] for item in [ptA, ptB]])\n minY = min([item[1] for item in [ptA, ptB]])\n maxX = max([item[0] for item in [ptA, ptB]])\n maxY = max([item[1] for item in [ptA, ptB]])\n inLinesRange = poi[0] >= minX and poi[0] <= maxX and poi[1] >= minY and poi[1] <= maxY\n\n return inSensorRange and inLinesRange\n\ndef poiIsValid (poi, pt1, pt2, ptA, ptB):\n if (poi[0] >= 0 and poi[0] <= WIDTH and poi[1] >= 0 and poi[1] <= HEIGHT):\n if (pointOnLine(poi, pt1, pt2)):\n if (isBetween(poi, pt1, pt2, ptA, ptB)):\n return True\n\n return False\n\ndef angleOfIntersection (pt1, pt2, ptA, ptB):\n #first, calculate slope of each line\n x1, x2, y1, y2 = pt1[0], pt2[0], pt1[1], pt2[1]\n slopeOne = None\n\n if ((x2 - x1) != 0):\n slopeOne = (y2 - y1) / (x2 - x1)\n\n x1, x2, y1, y2 = ptA[0], ptB[0], ptA[1], ptB[1]\n slopeTwo = None\n if ((x2 - x1) != 0):\n slopeTwo = (y2 - y1) / (x2 - x1)\n\n if (slopeOne == slopeTwo):\n return False\n elif (slopeOne == None and slopeTwo == 0):\n return 90\n elif (slopeTwo == None and slopeOne == 0):\n return 90\n elif (slopeIsValid(slopeOne) and slopeTwo == None):\n return abs( 180 - abs(int(0 - math.degrees((math.atan(slopeOne))))))\n elif (slopeIsValid(slopeTwo) and slopeOne == None):\n return abs( 180 - abs(int(0 - math.degrees((math.atan(slopeTwo))))))\n else:\n return abs(180 - int (abs(int((math.degrees((math.atan(slopeOne))) - math.degrees((math.atan(slopeTwo))) )))))","sub_path":"poilinemath.py","file_name":"poilinemath.py","file_ext":"py","file_size_in_byte":5158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"523388693","text":"# -- coding: utf-8 --\n\nfrom nose.tools import *\nfrom pixivsort.main import Main\nimport re, os, shutil\n\n\ndef test_arguments():\n \"\"\"Test if arguments are read correctly.\"\"\"\n src_path = \"./test/testsource\"\n dst_path = \"./test/testdestination\"\n \n argv = (\"main.py\", src_path, dst_path)\n \n main = Main(argv)\n \n assert(main.src_path == src_path)\n assert(main.dst_path == dst_path)\n\n@raises(SystemExit)\ndef test_missing_arguments():\n \"\"\"Test if script exits on too few arguments.\"\"\"\n src_path = \"./test/testsource\"\n \n argv = (\"main.py\", src_path)\n main = Main(argv)\n\n@raises(SystemExit)\ndef test_additional_arguments():\n \"\"\"Test if script exits on too many arguments.\"\"\"\n src_path = \"./test/testsource\"\n dst_path = \"./test/testdestination\"\n \n argv = (\"main.py\", src_path, dst_path, dst_path)\n main = Main(argv)\n\n@raises(SystemExit)\ndef test_wrong_src_argument():\n \"\"\"Test if script exits when source argument is a file.\"\"\"\n src_path = \"./test/testsource/(814837) ろさ - 空と私.jpg\"\n dst_path = \"./test/testdestination\"\n \n argv = (\"main.py\", src_path, dst_path)\n main = Main(argv)\n\n@raises(SystemExit)\ndef test_wrong_dst_argument():\n \"\"\"Test if script exits when destination argument is a file\"\"\"\n src_path = \"./test/testsource/(814837) ろさ - 空と私.jpg\"\n dst_path = \"./test/testdestination\"\n \n argv = (\"main.py\", dst_path, src_path)\n main = Main(argv)\n\ndef test_run():\n \"\"\"Test a full run.\"\"\"\n src_path = \"./test/testsource\"\n dst_path = \"./test/testdestination\"\n \n argv = (\"main.py\", src_path, dst_path)\n \n main = Main(argv)\n main.run()\n \n destfile1 = \"./test/testdestination/rosa (814837)/\"\n destfile1 += \"(814837) ろさ - 空と私.jpg\"\n print(destfile1)\n assert os.path.exists(destfile1)\n destfile2 = \"./test/testdestination/cherrypin (206921)/\"\n destfile2 += \"(206921) cherrypin - イラスト集め\"\n assert os.path.exists(destfile2)\n \n # Copy files back\n shutil.copy2(destfile1, src_path)\n os.remove(destfile1)\n \n shutil.copytree(destfile2, \n \"./test/testsource/(206921) cherrypin - イラスト集め\")\n shutil.rmtree(destfile2)\n \n srcfile1 = \"./test/testsource/(814837) ろさ - 空と私.jpg\"\n assert os.path.exists(srcfile1)\n srcfile2 = \"./test/testsource/(206921) cherrypin - イラスト集め\"\n assert os.path.exists(srcfile2)","sub_path":"pixivsort/test/main_tests.py","file_name":"main_tests.py","file_ext":"py","file_size_in_byte":2446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"557006956","text":"import tkinter\nimport tkinter.messagebox as mb\nfrom sqlalchemy import Column, Integer, String, create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.ext.declarative import declarative_base\nimport os, sys\nfrom tkinter import *\nfrom tkinter.font import Font\nfrom tkinter.ttk import *\nfrom tkinter.messagebox import *\nfrom Game import *\n\n# 创建对象的基类\nBase = declarative_base()\n\n\n# 定义USer对象\nclass User(Base):\n # 数据库中表的名字\n __tablename__ = 'user'\n # 数据库表结构对应的字段\n id = Column(Integer(), primary_key=True)\n name = Column(String(20))\n password = Column(String(20))\n boun = Column(Integer())\n\n\n# 初始化数据库连接\nengine = create_engine('mysql+pymysql://root:sunhao2268411762@localhost:3306/python?charset=utf8')\n\n# 创建DBSession类型\nDbsession = sessionmaker(bind=engine)\nsession = Dbsession()\n\n\n# import tkinter.filedialog as tkFileDialog\n# import tkinter.simpledialog as tkSimpleDialog #askstring()\n\n################################################################\n# 注册窗口\nclass Application_zc(Frame):\n # 这个类仅实现界面生成功能,具体事件处理代码在子类Application中。\n def __init__(self, master=None):\n Frame.__init__(self, master)\n self.master.title('注册')\n self.master.geometry('600x600')\n self.createWidgets()\n\n def createWidgets(self):\n self.top = self.winfo_toplevel()\n\n self.style = Style()\n\n self.style.configure('Command3.TButton', font=('宋体', 9))\n self.Command3 = Button(self.top, text='注册', command=self.Command3_Cmd, style='Command3.TButton')\n self.Command3.place(relx=0.383, rely=0.504, relwidth=0.211, relheight=0.095)\n\n self.Text2Var = StringVar(value='Text2')\n self.Text2 = Entry(self.top, text='', textvariable=self.Text2Var, font=('宋体', 9))\n self.Text2.place(relx=0.209, rely=0.367, relwidth=0.698, relheight=0.072)\n\n self.Text1Var = StringVar(value='Text1')\n self.Text1 = Entry(self.top, text='', textvariable=self.Text1Var, font=('宋体', 9))\n self.Text1.place(relx=0.209, rely=0.183, relwidth=0.698, relheight=0.072)\n\n self.style.configure('Label1.TLabel', anchor='w', font=('宋体', 9))\n self.Label1 = Label(self.top, text='用户名:', style='Label1.TLabel')\n self.Label1.place(relx=0.087, rely=0.183, relwidth=0.089, relheight=0.072)\n\n self.style.configure('Label2.TLabel', anchor='w', font=('宋体', 9))\n self.Label2 = Label(self.top, text=' 密 码:', style='Label2.TLabel')\n self.Label2.place(relx=0.07, rely=0.367, relwidth=0.107, relheight=0.072)\n\n\nclass Application_ZC(Application_zc):\n # 这个类实现具体的事件处理回调函数。界面生成代码在Application_ui中。\n def __init__(self, master=None):\n Application_ui.__init__(self, master)\n\n def Command3_Cmd(self, event=None):\n # TODO, Please finish the function here!\n n = self.Text1.get()\n p = self.Text2.get()\n\n if session.query(User).filter(User.name.in_([n])).all():\n ret = session.query(User).filter_by(name=n).first()\n tkinter.messagebox.showinfo(\"注册\", \"该用户已注册!\")\n else:\n tkinter.messagebox.showinfo(\"注册\", \"注册成功,进入游戏!\")\n print(n + \"进入游戏\")\n global top\n top.destroy()\n main()\n newPlayer = User(name=n, password=p)\n # 添加到session\n session.add(newPlayer)\n # 提交即保存到数据库\n session.commit()\n\n\n##################################################\nclass Application_ui(Frame):\n # 这个类仅实现界面生成功能,具体事件处理代码在子类Application中。\n def __init__(self, master=None):\n Frame.__init__(self, master)\n self.master.title('登录')\n self.master.geometry('600x600')\n self.createWidgets()\n\n def createWidgets(self):\n self.top = self.winfo_toplevel()\n\n self.style = Style()\n\n self.style.configure('Label1.TLabel', anchor='w', font=('宋体', 9))\n self.Label1 = Label(self.top, text='用户名:', style='Label1.TLabel')\n self.Label1.place(relx=0.087, rely=0.183, relwidth=0.089, relheight=0.072)\n\n self.style.configure('Label2.TLabel', anchor='w', font=('宋体', 9))\n self.Label2 = Label(self.top, text=' 密 码:', style='Label2.TLabel')\n self.Label2.place(relx=0.07, rely=0.367, relwidth=0.107, relheight=0.072)\n\n self.Text1Var = StringVar(value='')\n self.Text1 = Entry(self.top, text='', textvariable=self.Text1Var, font=('宋体', 9))\n self.Text1.place(relx=0.209, rely=0.183, relwidth=0.698, relheight=0.072)\n\n self.Text2Var = StringVar(value='')\n self.Text2 = Entry(self.top, text='', textvariable=self.Text2Var, font=('宋体', 9))\n self.Text2.place(relx=0.209, rely=0.367, relwidth=0.698, relheight=0.072)\n\n self.style.configure('Command1.TButton', font=('宋体', 9))\n self.Command1 = Button(self.top, text='注册', command=self.Command1_Cmd, style='Command1.TButton')\n self.Command1.place(relx=0.035, rely=0.917, relwidth=0.141, relheight=0.049)\n\n self.style.configure('Command2.TButton', font=('宋体', 9))\n self.Command2 = Button(self.top, text='退出', command=self.Command2_Cmd, style='Command2.TButton')\n self.Command2.place(relx=0.8, rely=0.917, relwidth=0.159, relheight=0.049)\n\n self.style.configure('Command3.TButton', font=('宋体', 9))\n self.Command3 = Button(self.top, text='登录', command=self.Command3_Cmd, style='Command3.TButton')\n self.Command3.place(relx=0.383, rely=0.504, relwidth=0.211, relheight=0.095)\n\n\nclass Application(Application_ui):\n # 这个类实现具体的事件处理回调函数。界面生成代码在Application_ui中。\n def __init__(self, master=None):\n Application_ui.__init__(self, master)\n\n def Command1_Cmd(self, event=None):\n # TODO, Please finish the function here!\n top1 = Tk()\n Application_ZC(top1).mainloop()\n top.destroy()\n\n def Command2_Cmd(self, event=None):\n # TODO, Please finish the function here!\n self.quit()\n\n def Command3_Cmd(self, event=None):\n # TODO, Please finish the function here!\n n = self.Text1.get()\n p = self.Text2.get()\n\n if session.query(User).filter(User.name.in_([n])).all():\n ret = session.query(User).filter_by(name=n).first()\n print(ret.name + \"进入游戏\")\n if ret.password == p:\n tkinter.messagebox.showinfo(\"登录\", \"登录成功!\")\n global top\n top.destroy()\n main()\n else:\n tkinter.messagebox.showinfo(\"登录\", \"登录失败,请检查密码!\")\n else:\n tkinter.messagebox.showinfo(\"登录\", \"登录失败,没有该用户,请注册!\")\n session.commit()\n session.close()\n\n\n'''test'''\nif __name__ == \"__main__\":\n top = Tk()\n Application(top).mainloop()\n","sub_path":"SXB/venv/奥特消消消/start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":7179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"285011324","text":"# encoding: utf-8\n\n\"\"\"Test suite for pptx.oxml.table module.\"\"\"\n\nfrom __future__ import absolute_import\n\nfrom hamcrest import assert_that, equal_to, is_\n\nfrom pptx.enum.text import MSO_ANCHOR\nfrom pptx.oxml.ns import nsdecls\nfrom pptx.oxml.shapes.table import CT_Table\n\nfrom ...oxml.unitdata.table import a_tbl, test_table_elements, test_table_xml\nfrom ...unitutil import TestCase\n\n\nclass TestCT_Table(TestCase):\n \"\"\"Test CT_Table\"\"\"\n boolprops = ('bandRow', 'firstRow', 'lastRow',\n 'bandCol', 'firstCol', 'lastCol')\n\n def test_new_tbl_generates_correct_xml(self):\n \"\"\"CT_Table._new_tbl() returns correct XML\"\"\"\n # setup ------------------------\n rows, cols = 2, 3\n width, height = 334, 445\n xml = (\n '\\n \\n {5C22544A-7EE6-4342-B048-85BDC9FD1C3A}\\n '\n ' \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n '\n ' \\n \\n \\n <'\n 'a:tcPr/>\\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 ' \\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'\n % nsdecls('a')\n )\n # exercise ---------------------\n tbl = CT_Table.new_tbl(rows, cols, width, height)\n # verify -----------------------\n self.assertEqualLineByLine(xml, tbl)\n\n def test_boolean_property_value_is_correct(self):\n \"\"\"CT_Table boolean property value is correct\"\"\"\n def getter_cases(propname):\n \"\"\"Test cases for boolean property getter tests\"\"\"\n return (\n # defaults to False if no tblPr element present\n (a_tbl(), False),\n # defaults to False if tblPr element is empty\n (a_tbl().with_tblPr, False),\n # returns True if firstCol is valid truthy value\n (a_tbl().with_prop(propname, '1'), True),\n (a_tbl().with_prop(propname, 'true'), True),\n # returns False if firstCol has valid False value\n (a_tbl().with_prop(propname, '0'), False),\n (a_tbl().with_prop(propname, 'false'), False),\n # returns False if firstCol is not valid xsd:boolean value\n (a_tbl().with_prop(propname, 'foobar'), False),\n )\n for propname in self.boolprops:\n cases = getter_cases(propname)\n for tbl_builder, expected_property_value in cases:\n reason = (\n 'tbl.%s did not return %s for this XML:\\n\\n%s' %\n (propname, expected_property_value, tbl_builder.xml)\n )\n assert_that(\n getattr(tbl_builder.element, propname),\n is_(equal_to(expected_property_value)),\n reason\n )\n\n def test_assignment_to_boolean_property_produces_correct_xml(self):\n \"\"\"Assignment to boolean property of CT_Table produces correct XML\"\"\"\n def xml_check_cases(propname):\n return (\n # => True: tblPr and attribute should be added\n (a_tbl(), True, a_tbl().with_prop(propname, '1')),\n # => False: attribute should be removed if false\n (a_tbl().with_prop(propname, '1'), False, a_tbl().with_tblPr),\n # => False: attribute should not be added if false\n (a_tbl(), False, a_tbl()),\n )\n for propname in self.boolprops:\n cases = xml_check_cases(propname)\n for tc_builder, assigned_value, expected_tc_builder in cases:\n tc = tc_builder.element\n setattr(tc, propname, assigned_value)\n self.assertEqualLineByLine(expected_tc_builder.xml, tc)\n\n\nclass TestCT_TableCell(TestCase):\n \"\"\"Test CT_TableCell\"\"\"\n def test_anchor_property_value_is_correct(self):\n # setup ------------------------\n cases = (\n (test_table_elements.cell, None),\n (test_table_elements.top_aligned_cell, MSO_ANCHOR.TOP)\n )\n # verify -----------------------\n for tc, expected_text_anchoring_type in cases:\n assert_that(tc.anchor,\n is_(equal_to(expected_text_anchoring_type)))\n\n def test_assignment_to_anchor_sets_anchor_value(self):\n \"\"\"Assignment to CT_TableCell.anchor sets anchor value\"\"\"\n # setup ------------------------\n cases = (\n # something => something else\n (test_table_elements.top_aligned_cell, MSO_ANCHOR.MIDDLE),\n # something => None\n (test_table_elements.top_aligned_cell, None),\n # None => something\n (test_table_elements.cell, MSO_ANCHOR.BOTTOM),\n # None => None\n (test_table_elements.cell, None)\n )\n # verify -----------------------\n for tc, anchor in cases:\n tc.anchor = anchor\n assert_that(tc.anchor, is_(equal_to(anchor)))\n\n def test_assignment_to_anchor_produces_correct_xml(self):\n \"\"\"Assigning value to CT_TableCell.anchor produces correct XML\"\"\"\n # setup ------------------------\n cases = (\n # None => something\n (test_table_elements.cell, MSO_ANCHOR.TOP,\n test_table_xml.top_aligned_cell),\n # something => None\n (test_table_elements.top_aligned_cell, None,\n test_table_xml.cell)\n )\n # verify -----------------------\n for tc, text_anchoring_type, expected_xml in cases:\n tc.anchor = text_anchoring_type\n self.assertEqualLineByLine(expected_xml, tc)\n\n def test_marX_property_values_are_correct(self):\n \"\"\"CT_TableCell.marX property values are correct\"\"\"\n # setup ------------------------\n cases = (\n (test_table_elements.cell_with_margins, 12, 34, 56, 78),\n (test_table_elements.cell, 45720, 91440, 45720, 91440)\n )\n # verify -----------------------\n for tc, exp_marT, exp_marR, exp_marB, exp_marL in cases:\n assert_that(tc.marT, is_(equal_to(exp_marT)))\n assert_that(tc.marR, is_(equal_to(exp_marR)))\n assert_that(tc.marB, is_(equal_to(exp_marB)))\n assert_that(tc.marL, is_(equal_to(exp_marL)))\n\n def test_assignment_to_marX_sets_value(self):\n \"\"\"Assignment to CT_TableCell.marX sets marX value\"\"\"\n # setup ------------------------\n cases = (\n # something => something else\n (\n test_table_elements.cell_with_margins,\n (98, 76, 54, 32),\n (98, 76, 54, 32)\n ),\n # something => None\n (\n test_table_elements.cell_with_margins,\n (None, None, None, None),\n (45720, 91440, 45720, 91440)\n ),\n # None => something\n (\n test_table_elements.cell,\n (98, 76, 54, 32),\n (98, 76, 54, 32)\n ),\n # None => None\n (\n test_table_elements.cell,\n (None, None, None, None),\n (45720, 91440, 45720, 91440)\n )\n )\n # verify -----------------------\n for tc, marX, expected_marX in cases:\n tc.marT, tc.marR, tc.marB, tc.marL = marX\n exp_marT, exp_marR, exp_marB, exp_marL = expected_marX\n assert_that(tc.marT, is_(equal_to(exp_marT)))\n assert_that(tc.marR, is_(equal_to(exp_marR)))\n assert_that(tc.marB, is_(equal_to(exp_marB)))\n assert_that(tc.marL, is_(equal_to(exp_marL)))\n\n def test_assignment_to_marX_produces_correct_xml(self):\n \"\"\"Assigning value to CT_TableCell.marX produces correct XML\"\"\"\n # setup ------------------------\n cases = (\n # None => something\n (\n test_table_elements.cell,\n (12, 34, 56, 78),\n test_table_xml.cell_with_margins\n ),\n # something => None\n (\n test_table_elements.cell_with_margins,\n (None, None, None, None),\n test_table_xml.cell\n )\n )\n # verify -----------------------\n for tc, marX, expected_xml in cases:\n tc.marT, tc.marR, tc.marB, tc.marL = marX\n self.assertEqualLineByLine(expected_xml, tc)\n","sub_path":"tests/oxml/shapes/test_table.py","file_name":"test_table.py","file_ext":"py","file_size_in_byte":9523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"571059874","text":"# -*- coding: utf-8 -*-\n\nfrom volcanoes import Volcanoes\nfrom drawable_map import DrawableMap\nimport folium\n\nclass Manager():\n\t\"\"\"\n\tThis class manages the interaction between the volcanoes and the map\n\t\"\"\"\n\n\tdef __init__(self, lat=20.666954, lon=-103.284624, zoom_start=10, tiles=\"OpenStreetMap\"):\n\t\tself.volcanoes = Volcanoes('../files/volcanoes.csv')\n\t\tself.volcanoes.printVolcanoes() # --debug\n\t\tself.map = DrawableMap(lat=lat, lon=lon, zoom_start=zoom_start, tiles=tiles)\n\n\tdef addCircleMarkers(self, radius=1000, color='gray'):\n\t\tfor volcano in self.volcanoes.volcanoes:\n\t\t\tself.map.addCircle(location=[volcano.latitude, volcano.longitude], radius=radius, color=color,\n\t\t\t\tfill=True, fill_color=volcano.getElevationColor(), fill_opacity=0.77, \n\t\t\t\tpopup=folium.Popup(volcano.name, parse_html=True))\n\n\tdef closeMap(self, filename='map.html'):\n\t\tself.map.addAllFeatureGroups()\n\t\tself.map.saveMap(filename)\n\nif __name__ == '__main__':\n\tmanager = Manager()\n\tmanager.addCircleMarkers(10000, 'blue')\n\tmanager.map.addGeoJson()\n\tmanager.closeMap()\n\n","sub_path":"app_2_map/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"434981942","text":"from django.shortcuts import render\nfrom django.http import FileResponse, HttpResponse\nfrom config import Config\nimport os\n\n\ndef theconomist(request, *args):\n now_path = request.path.strip('/')\n local_path = os.path.join(Config.TEMPLATE, now_path)\n if os.path.isdir(local_path):\n sort_list = sorted(os.listdir(local_path))\n if 'images' in sort_list:\n sort_list.remove('images')\n if '.git' in sort_list:\n sort_list.remove('.git')\n if 'economist.json' in sort_list:\n sort_list.remove('economist.json')\n if 'cover.jpg' in sort_list:\n sort_list.remove('cover.jpg')\n context = {'now_path': now_path, 'dir_content': sort_list}\n return render(request, 'theconomist/path.html', context)\n else:\n if local_path.endswith('.md'):\n md = open(local_path, mode='r').read()\n md.replace('>', '>')\n return render(request, 'theconomist/markdown.html', {'md': md.replace('\\n', '\\\\n').replace('images/', '../images/')})\n sending = open(local_path, mode='rb')\n return FileResponse(sending)\n","sub_path":"theconomist/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"75610991","text":"from django.conf.urls import patterns, include, url\n\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n url(r'^$', 'main.views.index', name='index'),\n #url(r'^success$', 'main.views.success', name='success'),\n url(r'^home$', 'main.views.home', name='home'),\n url(r'^refresh/?$', 'main.views.refresh', name='refresh'),\n url(r'^login/?', 'main.views.login', name='login'),\n #url(r'^slashsaved/', include('slashsaved.foo.urls')),\n #url(r'^accounts/profile/?$', 'main.views.success', name='success'),\n\t#(r'^accounts/', include('allauth.urls')),\n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n url(r'^admin/', include(admin.site.urls)),\n)\n","sub_path":"slashsaved/slashsaved/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"101169135","text":"import tensorflow as tf\nfrom tensorflow.contrib import rnn\n\nclass Model:\n def __init__(self, input_size, batch_size):\n self.input_size = input_size\n self.batch_size = batch_size\n\n with tf.name_scope('input_layer'):\n self.add_input_layer()\n\n with tf.variable_scope('regression_layer'):\n self.add_regression_layer()\n\n with tf.name_scope('compute_cost'):\n self.compute_mse_cost()\n\n with tf.name_scope('train_step'):\n self.add_train_step()\n\n def add_input_layer(self):\n self.xs = tf.placeholder(\n tf.float64,\n [None, self.input_size],\n name='xs'\n )\n self.ys = tf.placeholder(\n tf.float64,\n [None, 1],\n name='ys'\n )\n self.learning_rate = tf.placeholder(\n tf.float32,\n name='learning_rate'\n )\n\n def add_regression_layer(self):\n weights = tf.Variable(tf.random_normal(\n [self.input_size, 1],\n stddev=0.5,\n dtype=tf.float64\n ), name='weights')\n biases = tf.Variable(tf.random_normal(\n [1],\n stddev=0.5,\n dtype=tf.float64\n ), name='biases')\n\n self.prediction = tf.matmul(self.xs, weights) + biases\n\n def compute_mse_cost(self):\n self.error = tf.reduce_mean(tf.square(tf.subtract(\n self.ys,\n self.prediction\n )))\n\n def add_train_step(self):\n # self.train_step = tf.train.MomentumOptimizer(self.learning_rate, 0.9).minimize(self.error)\n self.train_step = tf.train.AdamOptimizer(self.learning_rate).minimize(self.error)\n","sub_path":"src/models/Linear_Regression.py","file_name":"Linear_Regression.py","file_ext":"py","file_size_in_byte":1690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"185265526","text":"# functions for grooming, accessioning a dataset\n# 22 Mar 2021\n\nfrom copy import deepcopy\nfrom elastic.es_utils import *\nfrom elasticsearch import Elasticsearch \nes = Elasticsearch([{'host': 'localhost', 'port': 9200}])\nidx='whg'\n# use by datasets.align_whg_testy(), eventually: \n# align_idx(dsid)\n# for place in ds.places.all()\n# build_qobj(pid)\n# es_lookup_whg(qobj)\n# run q0a, then q0b\n# > hitlist (hl)\n# hlAnalyze(pid, hl)\n# addChild() or demoteParent()\n# write Hit records w/normalized json fields \n# \n# use by groom_idx.py\n# pids = [place_id] all indexed places for a dataset\n# groomy(pids)\n# for pid in pids:\n# doc = es.search(body = match place_id)['hits']['hits'][0]\n# profile = profileHit(doc)\n# if profile['links]:\n# hitlist = es.search(profile['links])\n# append all to profiles[]\n# processProfiles(pid, profiles)\n\n# used in accessioning, not grooming\ndef addChild(place, parent_id):\n print('adding', place, 'as child of', parent_id)\n # child_doc = makeDoc(place)\n # relation = {'name':'child', 'parent': parent_id}\n # child_doc['relation'] = relation\t\n # ** refactor tasks.align_idx::1716 **\n #_id == pid\n #add _id to parent children[]\n #add variants to parent searchy[]\n\ndef demoteParents(demoted, winner_id, pid):\n #demoted = ['14156468']\n #newparent_id = winner_id\n print('demoteParents()',demoted, winner_id, pid)\n #qget = \"\"\"{\"query\": {\"bool\": {\"must\": [{\"match\":{\"_id\": \"%s\" }}]}}}\"\"\"\n \n # updates 'winner' with children & names from demoted\n def q_updatewinner(kids, names):\n return {\"script\":{\n\t\"source\": \"\"\"ctx._source.children.addAll(params.newkids);\n\tctx._source.suggest.input.addAll(params.names);\n\tctx._source.searchy.addAll(params.names);\n \"\"\",\n\t\"lang\": \"painless\",\n\t\"params\":{\n\t\t\"newkids\": kids,\n\t\t\"names\": names }\n }}\n\n for d in demoted:\n # get the demoted doc, its names and kids if any\n #d = demoted[0]\n #d = '14156468'\n #winner_id = '14156467'\n qget = \"\"\"{\"query\": {\"bool\": {\"must\": [{\"match\":{\"_id\": \"%s\" }}]}}}\"\"\" \n try: \n qget = qget % (d)\n doc = es.search(index='whg', body=qget)['hits']['hits'][0]\n except:\n print('failed getting winner; winner_id, pid',winner_id, pid)\n sys.exit(sys.exc_info())\n srcd = doc['_source']\n kids = srcd['children']\n # add this doc b/c it's now a kid\n kids.append(doc['_id'])\n names = list(set(srcd['suggest']['input']))\n \n # first update the 'winner' parent\n q=q_updatewinner(kids, names)\n try:\n es.update(idx,winner_id,body=q,doc_type='place')\n except:\n print('q_updatewinner failed (pid, winner_id)',pid,winner_id)\n sys.exit(sys.exc_info())\n\n # then modify copy of demoted,\n # delete the old, index the new\n # --------------\n newsrcd = deepcopy(srcd)\n newsrcd['relation'] = {\"name\":\"child\",\"parent\":winner_id}\n newsrcd['children'] = []\n if 'whg_id' in newsrcd:\n newsrcd.pop('whg_id')\n # zap the old demoted, index the modified\n try: \n es.delete('whg', d, doc_type='place')\n es.index(index='whg',doc_type='place',id=d,body=newsrcd,routing=1)\n except:\n print('reindex failed (pid, demoted)',pid,d)\n sys.exit(sys.exc_info())\n\n\ndef topParent(parents, form):\n #print('topParent():', parents) \n if form == 'set':\n # if eq # of kids, use lowest _id\n parents.sort(key=lambda x:(-x[1], x[0]))\n top = parents[0][0]\n else:\n # a list of external parent _ids\n # get one with most children, or just the first?\n top = parents[0]\n #print('winner_id is', top)\n return top\n\n# HITLIST EXAMPLES \n# case3: (6595829) parent/child plus child w/external parent \nhl3 = [\n {\n \"_id\": \"14125428\",\n \"pid\": 5580275,\n \"title\": \"Toru\\u0144\",\n \"pass\": \"pass0\",\n \"links\": [\n \"tgn:7007831\"\n ],\n \"role\": \"parent\",\n \"children\": [\n \"90272\"\n ]\n },\n {\n \"_id\": \"90272\",\n \"pid\": 90272,\n \"title\": \"Thorn\",\n \"pass\": \"pass0\",\n \"links\": [\n \"tgn:7007831\"\n ],\n \"role\": \"child\",\n \"children\": [],\n \"parent\": \"14125428\"\n },\n {\n \"_id\": \"6370246\",\n \"pid\": 6370246,\n \"title\": \"Toru\\u0144\",\n \"pass\": \"pass0\",\n \"links\": [\n \"wd:Q47554\",\n \"gn:3083271\",\n \"viaf:149128250\"\n ],\n \"role\": \"child\",\n \"children\": [],\n \"parent\": \"14154739\"\n }\n]\n# case2: (6595984) 2 parents, both with same kid \nhl2 = [\n {\n \"_id\": \"88534\",\n \"pid\": 88534,\n \"title\": \"Pskov\",\n \"pass\": \"pass0\",\n \"links\": [\n \"dbp:Pskov\",\n \"tgn:7010261\"\n ],\n \"role\": \"child\",\n \"children\": [],\n \"parent\": \"12841451\"\n },\n {\n \"_id\": \"12841451\",\n \"pid\": 6099720,\n \"title\": \"Pskov\",\n \"pass\": \"pass0\",\n \"links\": [\n \"tgn:7010261\"\n ],\n \"role\": \"parent\",\n \"children\": [\n \"88534\"\n ]\n },\n {\n \"_id\": \"14153017\",\n \"pid\": 88535,\n \"title\": \"Pskov\",\n \"pass\": \"pass0b\",\n \"links\": [\n \"dbp:Pskov\"\n ],\n \"role\": \"parent\",\n \"children\": [\n \"88534\"\n ]\n }\n]\n\n# case1: (6595825) 1 parent w/2 children\nhl1 = [\n {\n \"_id\": \"86746\",\n \"pid\": 86746,\n \"title\": \"Marienburg\",\n \"pass\": \"pass0\",\n \"links\": [\n \"gn:3092472\",\n \"wd:Q35723337\",\n \"dbp:Malbork\",\n \"tgn:7007740\"\n ],\n \"role\": \"child\",\n \"children\": [],\n \"parent\": \"13511942\"\n },\n {\n \"_id\": \"13511942\",\n \"pid\": 4966395,\n \"title\": \"Malbork\",\n \"pass\": \"pass0\",\n \"links\": [\n \"tgn:7007740\"\n ],\n \"role\": \"parent\",\n \"children\": [\n \"86746\",\n \"6370425\"\n ]\n },\n {\n \"_id\": \"6370425\",\n \"pid\": 6370425,\n \"title\": \"Malbork\",\n \"pass\": \"pass0\",\n \"links\": [\n \"viaf:168429967\",\n \"loc:n50056727\",\n \"wd:Q146820\",\n \"viaf:146067891\",\n \"gn:7531264\",\n \"gn:3092472\"\n ],\n \"role\": \"child\",\n \"children\": [],\n \"parent\": \"13511942\"\n }\n]\n\n #q_demote = {\"script\":{\n #\"source\":\"ctx._source.relation.name=params.name;ctx._source.relation.parent=params.parent\",\n #\"lang\": \"painless\",\n #\"params\":{\n #\"name\":\"child\",\n #\"parent\": winner_id}\n #}}\n #q_demote_ubq = {\"script\": {\n #\"source\": \"\"\"ctx._source.relation=params.relation;ctx._source.children=[];\"\"\", \n #\"lang\": \"painless\", \n #\"params\": {\n #\"relation\": {\"name\": \"child\", \"parent\": winner_id}\n #}, \n #\"query\": {\"match\": {\"_id\": d}}}}\n \n # then modify and replace demoted\n #es.update(idx, int(d), q_demote)\n # Document mapping type name can't start with '_'\n \n #es.update('whg', d, q_demote, doc_type='place')\n # '[place][14156468]: document missing'\n \n #es.update_by_query(idx, body=q_demote_ubq)\n # \n \n#es.index(index='whg',doc_type='place',id=winner_id,body=src_w)\n","sub_path":"elastic/accession.py","file_name":"accession.py","file_ext":"py","file_size_in_byte":6890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"45222068","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2018/3/2 14:07\n# @Author : Yajun Yin\n# @Note : copied in \n\nimport tensorflow as tf\nfrom preprocessing_image import preprocess_for_train\n\ntrain_files = tf.train.match_filenames_once(\"train_file_*\")\ntest_files = tf.train.match_filenames_once(\"test_file_*\")\n\n\n# parse TFRecord\ndef parser(record):\n features = tf.parse_single_example(record, features={'image': tf.FixedLenFeature([], tf.string),\n 'label': tf.FixedLenFeature([], tf.int64),\n 'height': tf.FixedLenFeature([], tf.int64),\n 'width': tf.FixedLenFeature([], tf.int64),\n 'channel': tf.FixedLenFeature([], tf.int64)})\n # deserialize string to array\n decoded_image = tf.decode_raw(features['image'], tf.uint8)\n decoded_image.set_shape([features['height'], features['width'], features['channel']])\n label = features['label']\n return decoded_image, label\n\n\nimage_size = 299\nbatch_size = 100\nshuffle_buffer = 10000 # min_after_dequeue\nNUM_EPOCHS = 10\n\n# *************** train **************\n\n'''NO.1 step: generate dataset'''\ndataset = tf.contrib.data.TFRecordDataset(train_files)\ndataset = dataset.map(parser)\n# preprocessing\ndataset = dataset.map(lambda image, label: (preprocess_for_train(image, image_size, image_size, None), label))\n# shuffle\ndataset = dataset.shuffle(shuffle_buffer).batch(batch_size)\n# repeat for epochs\ndataset = dataset.repeat(NUM_EPOCHS)\n\n'''No.2 step: initialize iterator'''\niterator = dataset.make_initializable_iterator()\n\n'''No.3 step: get input from iterator'''\nimage_batch, label_batch = iterator.get_next()\n\n# neural network\nlearning_rate = 0.01\nlogit = inference(image_batch)\nloss = calc_loss(logit, label_batch)\ntrain_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)\n\n# *************** test **************\ntest_dataset = tf.contrib.data.TFRecordDataset(test_files)\ntest_dataset = test_dataset.map(parser).map(\n lambda image, label: (tf.image.resize_images(image, [image_size, image_size]), label))\ntest_dataset = test_dataset.batch(batch_size)\n\ntest_iterator = test_dataset.make_initializable_iterator()\n\ntest_image_batch, test_label_batch = test_iterator.get_next()\n\ntest_logit = inference(test_image_batch)\npredictions = tf.argmax(test_logit, axis=-1, output_type=tf.int32)\n\nwith tf.Session() as sess:\n sess.run([tf.global_variables_initializer(), tf.local_variables_initializer()])\n\n sess.run(iterator.initializer)\n\n while True:\n try:\n sess.run(train_step)\n except tf.errors.OutOfRangeError as e:\n break\n\n sess.run(test_iterator.initializer)\n\n test_results = []\n test_labels = []\n while True:\n try:\n pred, label = sess.run([predictions, test_label_batch])\n test_results.extend(pred)\n test_labels.extend(label)\n except tf.errors.OutOfRangeError:\n break\n correct = [float(y == y_) for (y, y_) in zip(test_results, test_labels)]\n accuracy = sum(correct) / len(correct)\n print(\"Test accuracy is:\", accuracy)\n","sub_path":"Practice-In-Tensorflow/formatted_input_dataset.py","file_name":"formatted_input_dataset.py","file_ext":"py","file_size_in_byte":3292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"174167602","text":"# -*- coding: utf-8 -*-\n\nfrom openerp import models, fields, api, _\nimport datetime\nfrom openerp.exceptions import except_orm\nimport copy\n\nclass taylor_template(models.Model):\n \"\"\"\n 在产品中添加相关价格表关联\n 这样可以有效减少业务人员的操作量\n \"\"\"\n _inherit = 'product.template'\n\n # 关联字段\n ref_pricelist_prolate = fields.One2many('pricelist.prolate.relation', 'ref_product_template', string='关联的价格表')\n is_gifts = fields.Boolean(u'有赠品')\n gifts_ids = fields.One2many('product.template.gifts','gifts_partner',u'赠品')\n\n _defaults = {\n 'is_gifts':False\n }\n\nclass qdodoo_gifts_line(models.Model):\n _name = 'product.template.gifts'\n\n gifts_partner = fields.Many2one('product.template',u'谁的赠品')\n name = fields.Many2one('product.template',u'赠品')\n number = fields.Float(u'数量')\n\n _defaults = {\n 'number':1.0\n }\n\nclass pricelist_prolate_relation(models.Model):\n _name = \"pricelist.prolate.relation\"\n\n proce_version=fields.Many2one('product.pricelist.version','价格表版本',required=True)\n proportion = fields.Float('折扣')\n fixed = fields.Float('额外')\n to_toal = fields.Float(string='单价', required=True, compute=\"compute_toal\")\n success = fields.Boolean(string='是否创建', readonly=True)\n comparison = fields.Float(string=\"对比值\", readonly=True)\n multipl=fields.Float(string='倍数')\n company = fields.Many2one('res.company', string='公司')\n price_version_item_id = fields.Many2one('product.pricelist.item',string='对应的价格表版本行')\n\n # 关联字段\n ref_product_pricelist = fields.Many2one('product.pricelist', '价格表',\n domain=['&', ('type', '=', 'sale'), ('company_id', '=', False)])\n ref_product_template = fields.Many2one('product.template', string='产品模版')\n\n # 获取当前登录人的公司\n def _get_company(self, cr, uid, ids, context=None):\n user = self.pool.get('res.users')\n return user.browse(cr, uid, uid).company_id.id\n\n _defaults = {\n 'company': _get_company,\n 'multipl':1,\n }\n\n # 根据价格表版本,产品模板,查询是否有对应的明细,返回明细lst\n def _get_version_price(self, cr, uid, version_id, product_tmpl_id, context=None):\n version_obj = self.pool.get('product.pricelist.version')\n lst = []\n for line in version_obj.browse(cr, uid, version_id).items_id:\n if line.product_tmpl_id.id == product_tmpl_id:\n lst.append(line.id)\n return lst\n\n # 倍数必须大于0\n @api.constrains('multipl')\n def _check_quantity_price(self):\n if self.multipl<0:\n raise except_orm(_('Warning!'),_('警告,倍数必须大于0!'))\n\n # 计算单价\n def compute_toal(self):\n for self_obj in self:\n self_obj.to_toal = (1 + self_obj.proportion) * self_obj.ref_product_template.list_price + self_obj.fixed\n\n # 根据产品模板获取产品id\n def get_product_tmpl(self, cr, uid, product_tmpl_id, context=None):\n product_obj = self.pool.get('product.product')\n template_ids = product_obj.search(cr, uid, [('product_tmpl_id','=',product_tmpl_id)])\n return template_ids\n\n # 创建时同步更新对应明细数据\n def create(self, cr, uid, value, context=None):\n re_id = super(pricelist_prolate_relation, self).create(cr, uid, value, context=context)\n version_obj = self.pool.get('product.pricelist.item')\n proce_version = value.get('proce_version')\n ref_product_template = value.get('ref_product_template')\n res_id = self._get_version_price(cr, uid, proce_version, ref_product_template, context=context)\n if res_id:\n version_obj.write(cr, uid, res_id, {'price_discount':value.get('proportion'),'price_surcharge':value.get('fixed'),'multipl':value.get('multipl')})\n else:\n for line in self.get_product_tmpl(cr, uid, ref_product_template, context=context):\n version_obj.create(cr, uid, {'price_discount':value.get('proportion'),'price_surcharge':value.get('fixed'),'multipl':value.get('multipl'),\n 'price_version_item_id':re_id,'price_version_id':proce_version,'product_id':line,'product_tmpl_id':ref_product_template}, context=context)\n return re_id\n\n # 修改数据时同步更新对应明细数据\n def write(self, cr, uid, ids, valus, context=None):\n super(pricelist_prolate_relation, self).write(cr, uid, ids, valus, context=context)\n item_obj = self.pool.get('product.pricelist.item')\n for obj in self.browse(cr, uid, ids):\n item_ids = item_obj.search(cr, uid, [('price_version_item_id','=',obj.id)])\n if valus.get('proce_version'):\n # 查询关联的价格表版本信息,删除掉\n item_obj.unlink(cr, uid, item_ids, context={'version':True})\n # 创建新的信息\n for line in self.get_product_tmpl(cr, uid, obj.ref_product_template.id, context=context):\n item_obj.create(cr, uid, {'price_discount':obj.proportion,'price_surcharge':obj.fixed,'multipl':obj.multipl,\n 'price_version_item_id':obj.id,'price_version_id':valus.get('proce_version'),'product_id':line,'product_tmpl_id':obj.ref_product_template.id}, context=context)\n else:\n item_obj.write(cr, uid, item_ids, {'price_discount':obj.proportion,'price_surcharge':obj.fixed,'multipl':obj.multipl,'price_version_item_id':obj.id})\n return True\n\n # 删除同步更新数据\n def unlink(self, cr, uid, ids, context={}):\n item_obj = self.pool.get('product.pricelist.item')\n if not context.get('item'):\n # 查询关联的明细\n for obj in self.browse(cr, uid, ids):\n item_ids = item_obj.search(cr, uid, [('price_version_item_id','=',obj.id)])\n item_obj.unlink(cr, uid, item_ids)\n return super(pricelist_prolate_relation, self).unlink(cr, uid, ids, context=context)\n\nclass qdodoo_sale_order_line_inherit_tfs(models.Model):\n _inherit = 'sale.order.line'\n\n multiple_number = fields.Float(u'数量',help=\"未乘倍数前的数量\")\n\nclass qdodoo_sale_order_inherit_tfs(models.Model):\n _inherit = 'sale.order'\n\n all_money = fields.Float(u'合计',compute='_get_all_money')\n minus_money = fields.Float(u'优惠金额')\n is_website = fields.Boolean(u'是否是网络报货生成的订单', default=False)\n\n def create(self, cr, uid, vals, context=None):\n partner_obj = self.pool.get('res.partner')\n if vals.get('partner_id'):\n if not vals.get('project_id'):\n vals['project_id'] = partner_obj.browse(cr, 1, vals.get('partner_id')).analytic_account_id.id\n if not vals.get('warehouse_id'):\n vals['warehouse_id'] = partner_obj.browse(cr, 1, vals.get('partner_id')).out_stock.id\n return super(qdodoo_sale_order_inherit_tfs, self).create(cr, uid, vals, context=context)\n\n # 计算合计金额\n def _get_all_money(self):\n num = 0.0\n for line in self.order_line:\n num += line.multiple_number * line.price_unit\n self.all_money = num - self.minus_money\n\nclass qdodoo_sale_order_return(models.Model):\n \"\"\"\n 销售订单上的反向转移\n \"\"\"\n _name = 'qdodoo.sale.order.return'\n\n def _get_invoice_state(self):\n invoice_state = 'none'\n if self._context.get('active_id'):\n order_policy = self.env['sale.order'].browse(self._context.get('active_id')).order_policy\n if order_policy == 'picking':\n invoice_state = '2binvoiced'\n return invoice_state\n\n order_line = fields.One2many('qdodoo.sale.order.return.line','order_id',u'产品明细')\n invoice_state = fields.Selection([('2binvoiced',u'开票'),('none',u'没有发票')],u'开发票',default=_get_invoice_state)\n\n # 获取默认明细产品\n @api.model\n def default_get(self, fields_list):\n res = super(qdodoo_sale_order_return, self).default_get(fields_list)\n # 获取销售订单数据\n sale_id = self.env['sale.order'].browse(self._context.get('active_id'))\n order_line = []\n for line in sale_id.order_line:\n order_line.append({'product_id':line.product_id.id,'quantity':line.product_uom_qty})\n res.update({'order_line': order_line})\n return res\n\n @api.multi\n def get_bom_product(self):\n bom_ids = self.env['mrp.bom'].search([('type','=','phantom')])\n res = {}\n for bom_id in bom_ids:\n res[bom_id.product_tmpl_id] = bom_id\n return res\n\n @api.multi\n def btn_return(self):\n # 获取销售订单数据\n sale_id = self.env['sale.order'].browse(self._context.get('active_id'))\n move_obj = self.env['stock.move']\n picking_ids = []\n # 获取所有组合品对应的bom\n bom_product = self.get_bom_product()\n # 获取销售订单的所有出库单\n for picking_id in sale_id.picking_ids:\n if picking_id.state == 'done' and picking_id.origin == sale_id.name:\n picking_ids.append(picking_id.id)\n if not picking_ids:\n raise except_orm(_(u'警告!'),_(u'销售订单没有有效的出库单!'))\n else:\n product_dict = {} #{产品:数量}\n for line in self.order_line:\n # 如果产品是组合品,则拆分对应的明细\n if line.product_id.product_tmpl_id in bom_product:\n for bom_line in bom_product[line.product_id.product_tmpl_id].bom_line_ids:\n if bom_line.product_id in product_dict:\n product_dict[bom_line.product_id] += line.quantity/bom_product[line.product_id.product_tmpl_id].product_qty*bom_line.product_qty\n else:\n product_dict[bom_line.product_id] = line.quantity/bom_product[line.product_id.product_tmpl_id].product_qty*bom_line.product_qty\n else:\n if line.product_id in product_dict:\n product_dict[line.product_id] += line.quantity\n else:\n product_dict[line.product_id] = line.quantity\n # 创建对应的反向转移数据\n valu = {}\n product_return_moves = []\n for key,value in product_dict.items():\n # 查询产品对应的调拨单\n move_ids = move_obj.search([('state','=','done'),('product_id','=',key.id),('picking_id','in',picking_ids)])\n if move_ids:\n product_return_moves.append((0,0,{'product_id':key.id,'quantity':value,'move_id':move_ids[0].id}))\n else:\n raise except_orm(_(u'警告!'),_(u'产品%s没有关联有效的出库单!')%key.name)\n valu['invoice_state'] = self.invoice_state\n valu['product_return_moves'] = product_return_moves\n ctx = dict(self._context)\n ctx['active_id'] = picking_ids[0]\n ctx['active_ids'] = [picking_ids[0]]\n ctx['active_model'] = 'stock.picking'\n res = self.env['stock.return.picking'].with_context(ctx).create(valu)\n return res.create_returns()\n\nclass qdodoo_sale_order_return_line(models.TransientModel):\n \"\"\"\n 销售订单上的反向转移明细\n \"\"\"\n _name = 'qdodoo.sale.order.return.line'\n\n order_id = fields.Many2one('qdodoo.sale.order.return',u'反向转移')\n product_id = fields.Many2one('product.product',u'产品')\n quantity = fields.Float(u'数量')\n\n\nclass qdodoo_product_category_inherit(models.Model):\n \"\"\"\n 产品分类增加网络报货倍数\n \"\"\"\n _inherit = 'product.category'\n\n fold = fields.Float(u'倍数')\n\n","sub_path":"qdodoo_websale_update/models/taylor_product.py","file_name":"taylor_product.py","file_ext":"py","file_size_in_byte":11966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"193559702","text":"from pypxlib import Table\nfrom csv import DictWriter\nfrom glob import glob\nfrom traceback import print_exc\n\nnames = glob('./*.db')\nfor name in names:\n table = Table(name, encoding='cp1251')\n try:\n with open(name[:-3]+'.csv', 'w', encoding='utf-8', newline='') as file:\n fields = [ a for a in table.fields if not a.startswith('Date')]\n writer = DictWriter(file, fields, extrasaction='ignore')\n writer.writeheader()\n for row in table:\n row2 = { key: row[key] for key in fields }\n writer.writerow(row2)\n except:\n print_exc()\n finally:\n table.close()\n","sub_path":"allergens-old/tools/paradox_to_csv.py","file_name":"paradox_to_csv.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"530901107","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport math\nimport os\nimport random\nimport zipfile\nimport cPickle as pickle\nimport numpy as np\nfrom six.moves import urllib\nfrom six.moves import xrange # pylint: disable\nfrom scipy.sparse import csr_matrix\nimport bisect\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport subprocess as sp\nimport argparse\n\ndef read_data(filename):\n \"\"\"Extract the first file enclosed in a zip file as a list of words.\"\"\"\n with zipfile.ZipFile(filename) as f:\n data = tf.compat.as_str(f.read(f.namelist()[0])).split()\n return data\n\ndef build_dataset(words, n_words, with_UNK = True, shuffle = False, count = None):\n \"\"\"Process raw inputs into a dataset.\"\"\"\n if count is None:\n if with_UNK:\n count = [['UNK', -1]]\n count.extend(collections.Counter(words).most_common(n_words - 1))\n else:\n count = []\n count.extend(collections.Counter(words).most_common(n_words))\n\n if shuffle:\n count = np.random.permutation(count)\n else:\n count = count\n dictionary = dict()\n for word, _ in count:\n dictionary[word] = len(dictionary)\n data = list()\n unk_count = 0\n for word in words:\n if word in dictionary:\n index = dictionary[word]\n data.append(index)\n else:\n index = dictionary['UNK']\n unk_count += 1\n if with_UNK:\n data.append(index)\n if with_UNK:\n count[dictionary['UNK']][1] = unk_count\n reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys()))\n return data, count, dictionary, reversed_dictionary\n\n\ndef build_cooccurance_dict(data, count, dictionary, reverse_dictionary, skip_window):\n cooccurance_count = collections.defaultdict(collections.Counter)\n for idx, center_word in enumerate(data):\n center_word_id = center_word\n if idx >= skip_window - 1 and idx < len(data) - skip_window:\n for i in range(skip_window):\n cooccurance_count[center_word_id][data[idx-i-1]] += 1\n cooccurance_count[center_word_id][data[idx+i+1]] += 1\n elif idx < skip_window - 1:\n for i in range(skip_window):\n cooccurance_count[center_word_id][data[idx+i+1]] += 1\n for i in range(idx):\n cooccurance_count[center_word_id][data[i]] += 1\n else:\n for i in range(skip_window):\n cooccurance_count[center_word_id][data[idx-i-1]] += 1\n for i in range(idx+1, len(data)):\n cooccurance_count[center_word_id][data[i]] += 1\n return cooccurance_count\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='estimation of noise given a corpus')\n parser.add_argument('--filename', required=True, type=str, help='vocabulary siz3')\n parser.add_argument('--vocabulary_size', default=10000, type=int, help='vocabulary siz3')\n parser.add_argument('--window_size', default=5, type=int, help='window size')\n parser.add_argument('intrinsic_test', action='store_false')\n args = parser.parse_args()\n filename = args.filename\n vocabulary_size = args.vocabulary_size\n skip_window = args.window_size\n save_path = 'dat_{}/'.format(vocabulary_size)\n\n try:\n with open(save_path + 'data.pkl', 'r') as f:\n data = pickle.dump(f)\n with open(save_path + 'data_test.pkl', 'r') as f:\n data_test = pickle.load(f)\n with open(save_path + 'count.pkl', 'r') as f:\n count = pickle.load(f)\n with open(save_path + 'dictionary.pkl', 'r') as f:\n dictionary = pickle.load(f)\n with open(save_path + 'reverse_dictionary.pkl', 'r') as f:\n reverse_dictionary = pickle.load(f)\n with open(save_path + 'count_test.pkl', 'r') as f:\n count_test = pickle.load(f)\n with open(save_path + 'dictionary_test.pkl', 'r') as f:\n dictionary_test = pickle.load(f)\n with open(save_path + 'reverse_dictionary_test.pkl', 'r') as f:\n reverse_dictionary_test = pickle.load(f)\n\n except:\n\n # Read the data into a list of strings.\n vocabulary = read_data(filename)\n vocabulary_size = args.vocabulary_size\n\n splits = len(vocabulary) // 1000\n train_set, test_set = [], []\n for i in range(500):\n train_set += vocabulary[(2*i)*splits:(2*i+1)*splits]\n test_set += vocabulary[(2*i+1)*splits:(2*i+2)*splits]\n\n del vocabulary\n\n\n data, count, dictionary, reverse_dictionary = build_dataset(train_set,\n vocabulary_size)\n data_test, count_test, dictionary_test, reverse_dictionary_test = build_dataset(\n test_set, vocabulary_size, shuffle = False, count = count)\n vocabulary_size = min(vocabulary_size, len(count))\n\n # save data\n sp.check_output('mkdir -p {}'.format(save_path), shell=True)\n with open(save_path + 'data.pkl', 'w') as f:\n pickle.dump(data, f)\n with open(save_path + 'data_test.pkl', 'w') as f:\n pickle.dump(data_test, f)\n with open(save_path + 'count.pkl', 'w') as f:\n pickle.dump(count, f)\n with open(save_path + 'dictionary.pkl', 'w') as f:\n pickle.dump(dictionary, f)\n with open(save_path + 'reverse_dictionary.pkl', 'w') as f:\n pickle.dump(reverse_dictionary, f)\n with open(save_path + 'count_test.pkl', 'w') as f:\n pickle.dump(count_test, f)\n with open(save_path + 'dictionary_test.pkl', 'w') as f:\n pickle.dump(dictionary_test, f)\n with open(save_path + 'reverse_dictionary_test.pkl', 'w') as f:\n pickle.dump(reverse_dictionary_test, f)\n\n\n count = count[:vocabulary_size]\n\n\n skip_window = args.window_size\n try:\n with open(save_path + 'cooccur.pkl', 'r') as f:\n cooccur = pickle.load(f)\n with open(save_path + 'cooccur_test.pkl', 'r') as f:\n cooccur_test = pickle.load(f)\n with open(save_path + 'cooccur_matrix.pkl', 'r') as f:\n cooccur_matrix = pickle.load(f)\n cooccur_test_matrix = np.zeros([vocabulary_size, vocabulary_size])\n with open(save_path + 'cooccur_matrix_test.pkl', 'r') as f:\n cooccur_test_matrix = pickle.load(f)\n del data\n del data_test\n\n except:\n cooccur = build_cooccurance_dict(data, count, dictionary, reverse_dictionary, skip_window)\n with open(save_path + 'cooccur.pkl', 'w') as f:\n pickle.dump(cooccur, f)\n\n\n #---------------------------build for second part of data---------------------\n cooccur_test = build_cooccurance_dict(data_test, count_test, \n dictionary_test, reverse_dictionary_test, skip_window)\n\n with open(save_path + 'cooccur_test.pkl', 'w') as f:\n pickle.dump(cooccur_test, f)\n\n\n cooccur_matrix = np.zeros([vocabulary_size, vocabulary_size])\n for k1, v1 in cooccur.iteritems():\n for k2, v2 in v1.iteritems():\n cooccur_matrix[k1, k2] = v2\n del data\n with open(save_path + 'cooccur_matrix.pkl', 'w') as f:\n pickle.dump(cooccur_matrix, f)\n cooccur_test_matrix = np.zeros([vocabulary_size, vocabulary_size])\n for k1, v1 in cooccur_test.iteritems():\n for k2, v2 in v1.iteritems():\n cooccur_test_matrix[k1, k2] = v2\n del data_test\n\n with open(save_path + 'cooccur_matrix_test.pkl', 'w') as f:\n pickle.dump(cooccur_test_matrix, f)\n\n\n Nij = np.zeros([vocabulary_size, vocabulary_size])\n for i in range(vocabulary_size):\n for j in range(vocabulary_size):\n Nij[i,j] += cooccur[i][j]\n\n log_count = np.log(1 + Nij)\n\n Nij_test = np.zeros([vocabulary_size, vocabulary_size])\n for i in range(vocabulary_size):\n for j in range(vocabulary_size):\n Nij_test[i,j] += cooccur_test[i][j]\n log_count_test = np.log(1 + Nij_test)\n\n diff = log_count - log_count_test\n print(\"mean is {}\".format(np.mean(diff)))\n print(\"est std is {}\".format(0.5 * np.std(diff)))\n with open(\"param.yml\", \"w\") as f:\n f.write(\"sigma: {}\\n\".format(0.5 * np.std(diff)))\n f.write(\"alpha: {}\\n\".format(0.5)) #symmetric factorization\n f.write(\"data: {}\".format(\"text8_logcount\"))\n","sub_path":"optimal_dimensionality/glove/noise_est_log_count.py","file_name":"noise_est_log_count.py","file_ext":"py","file_size_in_byte":7817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"622724768","text":"from urllib.request import urlopen\nimport urllib.request\nimport urllib.parse\n\ndef read_file():\n contents = open(\"/home/parvez/PycharmProjects/first/samples/cursewords/movie_quotes1.txt\")\n quotes = contents.read()\n #print(quotes)\n check_badwords(quotes)\n\n\ndef check_badwords(words_tocheck):\n connection = urlopen(\"http://www.wdylike.appspot.com/?q=\",words_tocheck)\n output = connection.read()\n print(output)\n\nread_file()\ncheck_badwords()","sub_path":"samples/curse_words.py","file_name":"curse_words.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"319677257","text":"from pypost.data import DataManager\nfrom pypost.mappings import DataManipulator\nfrom pypost.mappings import Mapping\nimport numpy as np\n\n#define our mapping class. A mapping is a callable object, where the call function is implemented by the MappingMethod decorator\n\nclass DummyMapping(Mapping):\n\n def __init__(self, dataManager):\n Mapping.__init__(self, dataManager, inputVariables=['X'], outputVariables='X')\n\n @Mapping.MappingMethod()\n def computeSomething(self, X):\n return X + 1\n\n @DataManipulator.DataMethod(inputArguments=[], outputArguments=['X'], takesNumElements=True)\n def reset(self, numElements):\n return np.zeros((numElements,2))\n\n# Create a dataManager that can handle the input (X) and output (Y) of a 1 dimensional\n# function\ndataManager = DataManager('values')\ndataManager.addDataEntry('X', 2)\n\ndata = dataManager.createDataObject([10])\n\nmapping = DummyMapping(dataManager)\n\nprint(data[...].X)\n\n# apply mapping\ndata[...] >> mapping >> data\nprint(data[...].X)\n\nmapping.reset >> data\n\n\n# Applying the >> to the mapping and writing the result back to data. Using the >> operator for the second operation returns the data object\ndata[slice(0,5)] >> mapping >> data\nprint(data[...].X)\n\n# Applying the >> to the mapping and writing the result back to data. Using the >= operator for the second operation returns the resulting matrices\ntemp = data[...] >> mapping >= data\nprint(data[...].X, temp)\n\n\n","sub_path":"src/pypost/tutorials/mappings/mappings.py","file_name":"mappings.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"342278577","text":"from django.shortcuts import render\nfrom django.views.generic import TemplateView # Import TemplateView\n\n# Add the two views we have been talking about all this time :)\nclass HomePageView(TemplateView):\n template_name = \"index.html\"\n\nclass AboutPageView(TemplateView):\n template_name = \"about.html\"\n \nclass DataPageView(TemplateView):\n def get(self, request, **kwargs):\n # we will pass this context object into the\n # template so that we can access the data\n # list in the template\n context = {\n 'data': [\n {\n 'name': 'T H I C C',\n 'value': '$500'\n },\n {\n 'name': 'T H I C C E R',\n 'value': '$1000'\n },\n {\n 'name': 'T H I C C E S T',\n 'value': '100000'\n }\n ]\n }\n\n return render(request, 'data.html', context)","sub_path":"bop/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"235836286","text":"from Pages.Histogram import HistogramPage\nfrom Pages.PicturePage import PicturePage\nfrom tkinter import ttk\nfrom PIL import ImageTk\n\nimport matplotlib.pyplot as plt\nimport tkinter as tk\nLARGE_FONT = (\"Verdana\", 12)\n\nstrech_native_histDictionary = {}\n\nclass StrechPage(tk.Frame):\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n label = tk.Label(self, text=\"Page One!!!\", font=LARGE_FONT)\n label.pack(pady=10, padx=10)\n\n button1 = ttk.Button(self, text=\"Back\",\n command=lambda: controller.show_frame(\"PicturePage\"))\n button1.pack(padx=5, pady=10,side=tk.LEFT, anchor=\"nw\")\n\n button2 = ttk.Button(self, text=\"Strech Hist Values\",\n command=lambda: self.strech_histValuesL())\n button2.pack(padx=5, pady=10, side=tk.LEFT, anchor=\"nw\")\n\n button3 = ttk.Button(self, text=\"Show Strech Histogram\",\n command=lambda: self.show_strech_histValuesL())\n button3.pack(padx=5, pady=10, side=tk.LEFT, anchor=\"nw\")\n\n button4 = ttk.Button(self, text=\"Show Picture\",\n command=lambda: self.show_strech_picture())\n button4.pack(padx=5, pady=10, side=tk.LEFT, anchor=\"nw\")\n\n def strech_histValuesL(self):\n\n self.im = PicturePage.load.convert('L')\n min_value = 300\n max_value = -1\n\n for i in range(256):\n if (HistogramPage.native_histDictionary[i] != 0 and min_value > i):\n min_value = i\n if (HistogramPage.native_histDictionary[i] != 0 and max_value < i):\n max_value = i\n\n print(\"max\", max_value)\n print(\"min\", min_value)\n\n\n width, height = PicturePage.load.size\n for row in range(width):\n for col in range(height):\n pixel = self.im.getpixel((row, col))\n\n strech_pixel = int((pixel - min_value)*255/(max_value-min_value))\n strech_native_histDictionary[strech_pixel] = strech_native_histDictionary.get(strech_pixel, 0) + 1\n print(strech_pixel)\n\n self.im.putpixel((row, col), strech_pixel)\n\n def show_strech_histValuesL(self):\n\n plt.figure(figsize=(20, 10))\n\n plt.subplot(311)\n plt.bar(list(strech_native_histDictionary.keys()), strech_native_histDictionary.values(), color='black')\n plt.grid(axis='y', alpha=0.75)\n plt.xlabel('Value')\n plt.ylabel('Frequency')\n plt.title('Strech Histogram')\n\n plt.subplot(313)\n plt.bar(list(HistogramPage.native_histDictionary.keys()), HistogramPage.native_histDictionary.values(), color='black')\n plt.grid(axis='y', alpha=0.75)\n plt.xlabel('Value')\n plt.ylabel('Frequency')\n plt.title('Original Histogram')\n plt.show()\n\n def show_strech_picture(self):\n width, height = PicturePage.load.size\n\n canvas = tk.Canvas(self, width=width, height=height)\n canvas.pack(expand=True, fill=tk.BOTH)\n\n canvas.image = ImageTk.PhotoImage(self.im)\n self.strech_image = canvas.image\n canvas.create_image(0, 0, image=canvas.image, anchor=\"nw\")\n canvas.place(x=20, y=100)\n","sub_path":"HistogramProject/Pages/Histogram/StrechPage.py","file_name":"StrechPage.py","file_ext":"py","file_size_in_byte":3227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"314185753","text":"# %%\nimport pyspark as py\nimport pyspark.sql.types as typ\nimport pyspark.sql.functions as func\nimport pyspark.ml.feature as ft\nimport numpy as np\nimport pyspark.mllib.stat as st\nfrom pyspark.ml import Pipeline\nimport pyspark.ml.evaluation as ev\nimport pyspark.ml.regression as rg\n\nconf = py.SparkConf().setAppName('test')\nsc = py.SparkContext(conf=conf)\n\n# %%\ndata = py.SQLContext(sc).read.csv(\n 'hdfs://master:9000/user/stm/test/donations2.csv',\n header=True,\n nullValue=False)\n\n# %%\ndata.printSchema()\n\ndata = data.drop('ID').filter(data.TARGET_B == '1').drop('TARGET_B')\ndata.describe().show()\n# 总列数为4843 其中 GiftAvgCard36 为4111 DemAge 为3679\n\n# %% GiftAvgCard36 DemAge 以中位数补充\nlist_GiftAvgCard36 = data.select('GiftAvgCard36').rdd.map(\n lambda row: row['GiftAvgCard36']).collect()\nlist_DemAge = data.select('DemAge').rdd.map(\n lambda row: row['DemAge']).collect()\n\n\ndef find_median(values_list):\n '''获取list的中位数'''\n try:\n # 剔除list中的None, 将list中的值转为float\n values_list = [float(x) for x in values_list if x is not None]\n median = np.nanmedian(values_list)\n return round(float(median), 2)\n except Exception:\n return None\n\n\nmedian_GiftAvgCard36 = find_median(list_GiftAvgCard36) # 11\ndata = data.fillna({'GiftAvgCard36': '11'})\n\nmedian_DemAge = find_median(list_DemAge) # 61\ndata = data.fillna({'DemAge': '61'})\n\n# %%\ny = ['TARGET_D']\nvar_d = ['StatusCat96NK', 'StatusCatStarAll', 'DemCluster', 'DemGender', 'DemHomeOwner']\nvar_c = list(set(data.columns) - set(y) - set(var_d))\n\n# %% str2float\nfor col in var_c + y:\n data = data.withColumn(col, data[col].cast(typ.FloatType()))\n\n\n# %%\ndata.select('DemHomeOwner').distinct().show()\n# %%\ndef str2float_StatusCat96NK(feat):\n return func \\\n .when(func.col(feat) == 'A', 1) \\\n .when(func.col(feat) == 'E', 2) \\\n .when(func.col(feat) == 'F', 3) \\\n .when(func.col(feat) == 'L', 4) \\\n .when(func.col(feat) == 'N', 5) \\\n .when(func.col(feat) == 'S', 6) \\\n .otherwise(99).cast(typ.FloatType())\n\n\ndef str2float_DemGender(feat):\n return func \\\n .when(func.col(feat) == 'F', 1) \\\n .when(func.col(feat) == 'M', 2) \\\n .when(func.col(feat) == 'U', 3) \\\n .otherwise(99).cast(typ.FloatType())\n\n\ndef str2float_DemHomeOwner(feat):\n return func \\\n .when(func.col(feat) == 'U', 1) \\\n .when(func.col(feat) == 'H', 2) \\\n .otherwise(99).cast(typ.FloatType())\n\n\ndata = data.withColumn('StatusCat96NK', str2float_StatusCat96NK('StatusCat96NK')) \\\n .withColumn('StatusCatStarAll', data['StatusCatStarAll'].cast(typ.FloatType())) \\\n .withColumn('DemCluster', data['DemCluster'].cast(typ.FloatType())) \\\n .withColumn('DemGender', str2float_DemGender('DemGender')) \\\n .withColumn('DemHomeOwner', str2float_DemHomeOwner('DemHomeOwner'))\n\ndata.printSchema()\n\n# %% 连续变量相关性 此处使用rdd的corr方法 dataframe的corr目前仅支持pearson\ncorrs = []\nfor col in var_c:\n tmp = data.select(y[0], col).rdd.map(lambda row: [e for e in row])\n corr_p = st.Statistics.corr(tmp, method='pearson')\n corr_s = st.Statistics.corr(tmp, method='spearman')\n corrs.append((col, abs(corr_p[0][1]), abs(corr_s[0][1])))\n\nprint(corrs)\n\n# %%\nvar_c_k = []\nfor corr in list(filter(lambda x: x[1] > 0.1 and x[2] > 0.1, corrs)):\n var_c_k.append(corr[0])\nprint(var_c_k)\n\n\n# %% 分类变量 方差分析\ndef anova(data, y, col):\n list_all = data.select(y).rdd.map(lambda row: row[y]).collect()\n mean_all = np.mean(list_all)\n # sst = sum([(i - mean_all)**2 for i in list_all])\n varlist = data.select(col).distinct().rdd.map(lambda row: row[col]).collect()\n ssa = 0\n sse = 0\n for var in varlist:\n tmpList = data.filter(\"\" + col + \" == '\" + str(var) + \"'\").select(y).rdd.map(lambda row: row[y]).collect()\n ssa += len(tmpList) * (np.mean(tmpList) - mean_all)**2\n sse += sum([(i - np.mean(tmpList))**2 for i in tmpList])\n k1 = len(varlist) - 1\n k2 = data.count() - len(varlist)\n msa = ssa / k1\n mse = sse / k2\n return k1, k2, msa / mse\n\n\n# %%\nanova_list = []\nfor var in var_d:\n k1, k2, m = anova(data, y[0], var)\n anova_list.append((var, k1, k2, m))\nprint(anova_list)\n# DemGender DemHomeOwner 不显著\n# [('StatusCat96NK', 5, 4837, 63.690217741977776),\n# ('StatusCatStarAll', 1, 4841, 235.53469115420407),\n# ('DemCluster', 53, 4789, 2.4466412678440372),\n# ('DemGender', 2, 4840, 5.019571166905953),\n# ('DemHomeOwner', 1, 4841, 0.29102047886029714)]\n\n# %%\nvar_d_k = ['StatusCat96NK', 'StatusCatStarAll', 'DemCluster']\nvar_k = var_c_k + var_d_k\n\n# %%\ndata_k = data.select(y+var_k)\ndata_k.printSchema()\ndata_train, data_test = data_k.randomSplit([0.6, 0.4], seed=500)\nlinear = rg.LinearRegression(\n maxIter=10,\n regParam=0.01,\n labelCol='TARGET_D'\n)\n\nfeaturesCreator = ft.VectorAssembler(\n inputCols=[col for col in var_k],\n outputCol='features')\n\npipeline_val = Pipeline(stages=[featuresCreator, linear])\nmodel_val = pipeline_val.fit(data_train)\ntest_model_val = model_val.transform(data_test)\n\nevaluator_val = ev.RegressionEvaluator(\n predictionCol='prediction',\n labelCol='TARGET_D'\n)\n\nprint(evaluator_val.evaluate(test_model_val, \n {evaluator_val.metricName: 'rmse'}))\n\nprint(evaluator_val.evaluate(test_model_val, \n {evaluator_val.metricName: 'r2'}))\n\n# 8.767976277599127\n# 0.48206050111509446\n","sub_path":"cases/twostepmodel/donation3_2.py","file_name":"donation3_2.py","file_ext":"py","file_size_in_byte":5444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"527004627","text":"# import pathlib\nimport datetime\nimport random\nimport os\n\nfrom shutil import copyfile\n\nfrom text_shuffle import get_pattern_list, shuffle_str_list, check_if_already_obfusc\nfrom helper_funcs import recursive_file_search\n\ninput_folder_path = \"input_texts/\"\noutput_folder_path = \"input_texts2/\"\n\nobfuscated_tag = \"\"\n\npattern_l = get_pattern_list()\n\n\ndef create_folder(folder_path):\n from pathlib import Path\n Path(folder_path).mkdir(parents=True, exist_ok=True)\n # https://stackoverflow.com/questions/273192/how_can_i_safely_create_a_nested_directory\n\n\ndef read_file2list(f_path):\n temp_l = []\n with open(f_path) as f:\n temp_l = f.readlines()\n return temp_l\n\n\ndef write_l2file(path, shuffled_l):\n with open(path, 'w') as f:\n for i in range(len(shuffled_l)):\n f.write(shuffled_l[i])\n f.write(\"\\n\" + obfuscated_tag)\n\n\ndef clean_str_list(i_list):\n for i in range(len(i_list)):\n temp_str = i_list[i]\n i_list[i] = temp_str.strip()\n return i_list\n\n\n# get a human_readable timestamp\ndef human_timestamp():\n now = datetime.datetime.now()\n time_st = now.strftime('%y%m%d%h%m%s%f')[:-3]\n time_st += str(random.randint(0, 9)) # to avoid rewriting the log if made at the same millisecond\n return time_st\n\n\n# print(human_timestamp())\n\n# get list of input files\nf_list = recursive_file_search(input_folder_path, \".txt\")\n# print(f_list)\n\n# backup input files to avoid possible data loss\nbackup_folder = \"input_texts_backup\" + human_timestamp() + \"/\"\ncreate_folder(backup_folder)\nfor i in range(len(f_list)): # using copyfile instead of copytree because copytree doesnt work on android\n src_f_path = f_list[i]\n dst_f_path = backup_folder + os.path.basename(src_f_path)\n copyfile(src_f_path, dst_f_path)\nprint(\"the input files were backed up to \" + backup_folder + \"\\n\")\n\nfor i in range(len(f_list)):\n in_path = f_list[i]\n str_l = read_file2list(in_path)\n # str_l = clean_str_list(str_l)\n if check_if_already_obfusc(str_l):\n print(in_path + \" is already obfuscated. exiting to prevent data loss.\")\n exit()\n\n shuffled_l = shuffle_str_list(str_l, pattern_l, \"obfuscate\")\n\n # s_path =output_folder_path + in_path[len(input_folder_path):]\n\n write_l2file(in_path, shuffled_l)\n print(\"obfuscated \" + in_path)\n\nprint(\"done\")\n","sub_path":"schuffler.py","file_name":"schuffler.py","file_ext":"py","file_size_in_byte":2349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"177222713","text":"\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\nimport matplotlib.pyplot as plt\n\n \n\nif __name__ == \"__main__\":\n # Load training and eval data\n mnist = tf.contrib.learn.datasets.load_dataset(\"mnist\")\n # mnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True) #MNIST数据输入\n # mnist = input_data.read_data_sets(\"mnist_cnn_LeCun/MNIST_data/\", one_hot=True) #MNIST数据输入\n # train_data = mnist.train.images # Returns np.array\n # train_labels = np.asarray(mnist.train.labels, dtype=np.int32)\n eval_data = mnist.test.images # Returns np.array\n eval_labels = np.asarray(mnist.test.labels, dtype=np.int32)\n \n print('done')\n # print(train_data)\n print(eval_data.shape)\n print(eval_labels.shape)\n print(eval_labels)\n with tf.Session() as ssess:\n print(eval_data.eval())\n '''\n image = tf.reshape(train_data[0], [28, 28]) #最后一维代表通道数目,如果是rgb则为3 \n\n # tensor to matrix\n with tf.Session() as ssess:\n image_2d = (image.eval() *255).astype(int)\n print(image_2d) \n\n plt.imshow(image_2d, cmap='gray')\n plt.show()\n '''\n","sub_path":"mnist_cnn_LeCun/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"288300737","text":"# coding: utf-8\n\nfrom .content_generator import ContentGenerator\nfrom .font_selector import FontSelector\nfrom . import drawer\nfrom PIL import Image, ImageDraw\nfrom imgaug import augmenters as iaa\nimport numpy as np\nimport random\nimport yaml\n\nclass NoisTextGenerator(object):\n \"\"\"docstring for NoisTextGenerator\"\"\"\n def __init__(self, config_path):\n super(NoisTextGenerator, self).__init__()\n self.config_path = config_path\n self.config = self.load_config(config_path)\n self.content_generator = ContentGenerator(config_path)\n self.font_gen = None\n\n def load_config(self, config_path):\n result = None\n with open(config_path, 'r') as f:\n content = f.read()\n result = yaml.load(content)\n\n return result\n\n def init_fonts(self, font_dir, font_chars_path=None):\n self.font_gen = FontSelector(font_dir, self.config_path, font_chars_path)\n\n def get_color(self):\n rgb_range = [(0, 80), (0, 80), (0, 80)]\n c_list = []\n for i in range(3):\n v = random.randint(rgb_range[i][0], rgb_range[i][1])\n c_list.append(v)\n return tuple(c_list)\n\n def aug_text_img(self, img):\n np_img = np.array(img)\n seq = iaa.SomeOf((1, 3), [\n iaa.GaussianBlur(sigma=(0.0, 2.0)),\n iaa.AverageBlur(k=((5, 11), (1, 3))),\n iaa.PiecewiseAffine(scale=(0.01, 0.03)),\n iaa.Noop(),\n ])\n img_aug = seq.augment_image(np_img)\n img = Image.fromarray(img_aug)\n return img\n\n def process(self):\n gen_num = random.randint(0, self.config['max_gen_number'])\n text_img_list = []\n for i in range(gen_num):\n text = self.content_generator.process()\n font, font_path, font_size = self.font_gen.get_font(text)\n font_color = self.get_color()\n word_img = drawer.get_word_img(text, font, font_color, is_decorate=False)\n text_img_list.append(word_img)\n return text_img_list","sub_path":"seal_data_generator/libs/nois_text.py","file_name":"nois_text.py","file_ext":"py","file_size_in_byte":2051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"116278859","text":"from flask_restx import fields\nfrom dollar.api.restx import api\n\norder = api.model('Order', {\n 'id_company': fields.Integer(readOnly=True),\n 'delivery_time': fields.Integer(),\n 'delivery_cost': fields.Integer(),\n 'good': fields.Integer(),\n 'bad': fields.Integer(),\n 'feedback': fields.Integer(),\n 'call': fields.Integer(),\n})\n\nproduct = api.model('Product', {\n 'id_company': fields.Integer(readOnly=True),\n 'price': fields.Integer(),\n 'sale': fields.Integer(),\n 'views': fields.Integer(),\n})\n\ncompany = api.model('Company', {\n 'id': fields.Integer(readOnly=True, description='The unique identifier'),\n 'company': fields.String(readOnly=True, description='Company name'),\n 'category': fields.Integer(readOnly=True),\n 'verification': fields.Integer(readOnly=True),\n 'own': fields.Integer(readOnly=True),\n 'days_online': fields.Integer(readOnly=True),\n 'median_delivery_time': fields.Float(readOnly=True),\n 'mean_product_price': fields.Float(readOnly=True),\n 'part_good_order': fields.Float(readOnly=True),\n 'good_orders': fields.Integer(readOnly=True),\n 'bad_orders': fields.Integer(readOnly=True),\n 'mean_feedback': fields.Float(readOnly=True),\n 'mean_call': fields.Float(readOnly=True),\n 'mean_cost_delivery': fields.Float(readOnly=True),\n 'count_products': fields.Integer(readOnly=True),\n 'median_sale': fields.Float(readOnly=True),\n 'sum_views': fields.Integer(readOnly=True),\n 'part_orders_of_online': fields.Float(readOnly=True),\n 'part_orders_of_views': fields.Float(readOnly=True),\n 'median_product_price': fields.Float(readOnly=True),\n 'max_product_price': fields.Float(readOnly=True),\n 'min_product_price': fields.Float(readOnly=True),\n 'max_sale': fields.Float(readOnly=True),\n 'min_sale': fields.Float(readOnly=True),\n 'mean_sale': fields.Float(readOnly=True),\n 'rate': fields.Float(readOnly=True),\n})\n\ncompany_extended = api.inherit('Extended company', company, {\n 'orders': fields.List(fields.Nested(order)),\n 'products': fields.List(fields.Nested(product)),\n})\n\nsettings = api.model('Settings', {\n 'verification': fields.Float(required=True, description='Coefficient of something'),\n 'part_orders_of_online': fields.Float(required=True, description='Coefficient of something'),\n 'own': fields.Float(required=True, description='Coefficient of something'),\n 'median_delivery_time': fields.Float(required=True, description='Coefficient of something'),\n 'mean_product_price': fields.Float(required=True, description='Coefficient of something'),\n 'part_good_order': fields.Float(required=True, description='Coefficient of something'),\n 'mean_feedback': fields.Float(required=True, description='Coefficient of something'),\n 'mean_call': fields.Float(required=True, description='Coefficient of something'),\n 'mean_cost_delivery': fields.Float(required=True, description='Coefficient of something'),\n 'count_products': fields.Float(required=True, description='Coefficient of something'),\n 'median_sale': fields.Float(required=True, description='Coefficient of something'),\n 'part_orders_of_views': fields.Float(required=True, description='Coefficient of something'),\n})\n\npagination = api.model('A page of results', {\n 'page': fields.Integer(description='Number of this page of results'),\n 'per_page': fields.Integer(description='Number of items per page of results'),\n 'total': fields.Integer(description='Total number of results'),\n 'is_descending': fields.Boolean(description='Are results descending'),\n 'sort_by': fields.String(description='Results sorted by'),\n})\n\npage_of_companies = api.inherit('Page of companies', pagination, {\n 'items': fields.List(fields.Nested(company))\n})\n","sub_path":"python-backend/dollar/api/models/responses.py","file_name":"responses.py","file_ext":"py","file_size_in_byte":3761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"58528166","text":"from flask import Flask, render_template, url_for, request, redirect\n# CRUD operations\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom database_setup import Base, Restaurant, MenuItem\n\napp = Flask(__name__)\n\n# session creating to enable DB connection\nengine = create_engine('sqlite:///restaurantmenu.db')\nBase.metadata.bind = engine\nDBSession = sessionmaker(bind=engine)\nsession = DBSession()\n\n@app.route('/')\n# @app.route('/restaurants')\n# @app.route('/hello')\n@app.route('/restaurants//')\ndef restaurantMenu(restaurant_id):\n # return \"Hello World\"\n restaurant = session.query(Restaurant).filter_by(id=restaurant_id).one()\n menu_items = session.query(MenuItem).filter_by(restaurant_id=restaurant.id)\n return render_template('menu.html', restaurant=restaurant, menu_items=menu_items)\n '''output = ''\n for item in menu_items:\n output += item.name\n output += '
    '\n output += item.price\n output += '
    '\n output += item.description\n output += '

    '\n return output'''\n\n# Task 1: Create route for newMenuItem function here\n@app.route('/restaurant//new/', methods=['GET', 'POST'])\ndef newMenuItem(restaurant_id):\n if request.method == 'POST':\n newItem = MenuItem(name=request.form['name'], restaurant_id=restaurant_id)\n session.add(newItem)\n session.commit()\n return redirect(url_for('restaurantMenu', restaurant_id=restaurant_id))\n else:\n return render_template('newmenuitem.html', restaurant_id=restaurant_id)\n # return \"page to create a new menu item. Task 1 complete!\"\n\n# Task 2: Create route for editMenuItem function here\n@app.route('/restaurant///edit/')\ndef editMenuItem(restaurant_id, menu_id):\n return \"page to edit a menu item. Task 2 complete!\"\n\n# Task 3: Create a route for deleteMenuItem function here\n@app.route('/restaurant///delete/')\ndef deleteMenuItem(restaurant_id, menu_id):\n return \"page to delete a menu item. Task 3 complete!\"\n\nif __name__ == '__main__':\n app.debug = True\n app.run(host = '0.0.0.0', port = 5000)","sub_path":"vagrant/restaurant/project-old.py","file_name":"project-old.py","file_ext":"py","file_size_in_byte":2194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"47500431","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n\n\nimport asyncio\n\nasync def hello(t):\n print('Start Hello %s' %t)\n await asyncio.sleep(t) # 表示不同时间的IO操作\n print('End Hello %s' %t)\n\n# 获取 EventLoop\nloop = asyncio.get_event_loop()\ntasks = [hello(3), hello(2)]\n# 执行coroutine\nloop.run_until_complete(asyncio.wait(tasks))\nloop.close()","sub_path":"async_sync/async_await_hello.py","file_name":"async_await_hello.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"392731245","text":"#List Comprehension\r\ndef fizzbuzz(number=100):\r\n values = ((3, \"Fizz\"), (5, \"Buzz\"))\r\n for n in range(number+1):\r\n res = ''.join(v for (k, v) in values if not n % k)\r\n print(res if res else n)\r\n\r\n\r\nif __name__ == '__main__':\r\n fizzbuzz()\r\n\r\n","sub_path":"FizzBuzz_ListComp.py","file_name":"FizzBuzz_ListComp.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"90768536","text":"\"\"\"\n gevent 协程模块\n\"\"\"\n\nimport gevent\nfrom gevent import monkey\n\nmonkey.patch_time()\nfrom time import sleep\n\n\n# 协程函数\ndef foo(a, b):\n print(\"Running foo...\", a, b)\n # gevent.sleep(2) # 睡眠阻塞会自动查看其他可以执行的协程\n sleep(2)\n print(\"Foo again...\")\n\n\ndef bar():\n print(\"Running bar...\")\n # gevent.sleep(3)\n sleep(3)\n print(\"Bar again...\")\n\n\n# 生成携程对象\nf = gevent.spawn(foo, 1, 2)\nb = gevent.spawn(bar)\n\n\ngevent.joinall([f, b]) # 阻塞等待f,b两个协程执行完毕\n\n# gevent.sleep(5) # gevent睡眠阻塞\n","sub_path":"month02/code/Concur_Program/day06/gevent_test.py","file_name":"gevent_test.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"23235218","text":"import os\nimport time\nimport requests\nfrom subprocess import check_output\nfrom subprocess import check_output\n\nips = check_output(['hostname', '--all-ip-addresses'])\nip = str(ips)\nip = ip[2:-4]\nprint(len(ip))\nprint(\"Instances's IP:\", ip)\ncondition = True\nwhile condition == True:\n time.sleep(1)\n CPU_Pct = str(round(float(\n os.popen('''grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage }' ''').readline()),\n 2))\n if float(CPU_Pct) <= 35:\n condition = False\n else:\n condition = True\nACK_message = \"ACK\"\nr = requests.post('http://192.168.1.111:9999/ACKmessage', data=ACK_message)\nprint(\"\".format(status_code=r.status_code, reason=r.reason))\n\nwhile True:\n CPU_Pct = str(round(float(\n os.popen('''grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage }' ''').readline()),\n 2))\n\n # print results\n mem = str(os.popen('free -t -m').readlines())\n\n T_ind = mem.index('M')\n\n mem_G = mem[T_ind + 14:-4]\n Total_mem = mem_G.split()[0]\n Used_mem = mem_G.split()[1]\n mem_U_in_Percent = (int(Used_mem) / int(Total_mem)) * 100\n mem_U_in_Percent = round(mem_U_in_Percent, 2)\n print(\"*******************************\")\n print(\"CPU Usage = \" + CPU_Pct, \"%\")\n print(\"Total mem:\", Total_mem, \"Mb\")\n print(\"Used mem:\", Used_mem, \"Mb\")\n print('Mem usage in percent:', mem_U_in_Percent, \"%\")\n print(\"*******************************\")\n time.sleep(1)\n # print(type(CPU_Pct))\n payload = \"{ip}, {CPU_Pct}\".format(ip=ip, CPU_Pct=CPU_Pct)\n r = requests.post('http://192.168.1.111:9999/Instances', data=payload)\n # print(\"\".format(a=r.status_code))\n print(\"\".format(status_code=r.status_code, reason=r.reason))\n","sub_path":"MonitorInstances.py","file_name":"MonitorInstances.py","file_ext":"py","file_size_in_byte":1849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"95127709","text":"import json\nimport plotly\nimport pandas as pd\n\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.tokenize import word_tokenize\n\nfrom flask import Flask\nfrom flask import render_template, request, jsonify\nfrom plotly.graph_objs import Bar\nfrom sklearn.externals import joblib\nfrom sqlalchemy import create_engine\n\n\napp = Flask(__name__)\n\ndef tokenize(text):\n ''' Tokenize, normalize and clean user messages entered directly into the web app\n\n return clean tokens\n '''\n tokens = word_tokenize(text)\n lemmatizer = WordNetLemmatizer()\n\n clean_tokens = []\n for tok in tokens:\n clean_tok = lemmatizer.lemmatize(tok).lower().strip()\n clean_tokens.append(clean_tok)\n\n return clean_tokens\n\n# load data\nengine = create_engine('sqlite:///../data/DisasterResponse.db')\ndf = pd.read_sql_table('DisasterResponse', engine)\n\n# load model\nmodel = joblib.load(\"../models/classifier.pkl\")\n\n\n# index webpage displays cool visuals and receives user input text for model\n@app.route('/')\n@app.route('/index')\ndef index():\n ''' Use the dataframe queries below for the data used in the charts shown\n on the app landing webpage\n\n returns bar charts of Message Genre Counts, Top 5 message Categories and\n a chart of 'related' category messages, grouped by genre\n '''\n # Data for Genre Counts\n genre_counts = df.groupby('genre').count()['message'].sort_values(ascending=False)\n genre_names = list(genre_counts.index.str.title())\n\n #Data for Top 5 Categories of All Messages\n top_5_category_counts = df.drop(['message','original','genre','id'], axis=1).sum().sort_values(ascending=False).head(5)\n top_5_category_names = list(top_5_category_counts.index.str.title())\n\n #Data for related column by genre\n related_col=df[df['related'] ==1].groupby(['genre']).related.sum().sort_values(ascending=True)\n\n #Landing page graphs\n graphs = [\n {\n #Bar Graph of Database Genres\n 'data': [\n Bar(\n x=genre_names,\n y=genre_counts,\n marker=dict(color= ['176BA0', '19AADE','1DE4BD'])\n )\n\n ],\n\n 'layout': {\n 'title': 'Distribution of Message Genres',\n 'yaxis': {\n 'title': \"Count\"\n },\n 'xaxis': {\n 'title': \"Genre\"\n }\n }\n\n },\n {#Bar Graph of Top Five Message Cateorgies\n 'data': [\n Bar(\n x=top_5_category_names,\n y=top_5_category_counts,\n marker=dict(color=[\"teal\", 'goldenrod','salmon','orange','seagreen'])\n\n )\n\n ],\n\n 'layout': {\n 'title': 'Top 5 Message Categories',\n 'yaxis': {\n 'title': \"Count\"\n },\n 'xaxis': {\n 'title': \"Categories\"\n }\n }\n\n },\n { #Bar Graph of'Related' category, shown by Genres\n 'data': [\n Bar(\n x=related_col,\n y=list(related_col.index.str.title()),\n orientation ='h',\n marker=dict(color=[\"darkblue\", 'blue','lightblue','orange','seagreen'],\n )\n\n )\n\n ],\n\n 'layout': {\n 'title': 'Genre of Related Messages',\n 'yaxis': {\n 'title': \"Genre\"\n },\n 'xaxis': {\n 'title': \"Message Count\"\n }\n }\n\n }\n ]\n\n\n # encode plotly graphs in JSON\n ids = [\"graph-{}\".format(i) for i, _ in enumerate(graphs)]\n graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)\n\n # render web page with plotly graphs\n return render_template('master.html', ids=ids, graphJSON=graphJSON)\n\n\n# web page that handles user query and displays model results\n@app.route('/go')\ndef go():\n # save user input in query\n query = request.args.get('query', '')\n\n # use model to predict classification for query\n classification_labels = model.predict([query])[0]\n classification_results = dict(zip(df.columns[4:], classification_labels))\n\n # This will render the go.html Please see that file.\n return render_template(\n 'go.html',\n query=query,\n classification_result=classification_results\n )\n\n\ndef main():\n ''' Function to launch app\n '''\n app.run(host='0.0.0.0', port=3001, debug=True)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"app/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":4664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"200944799","text":"\"\"\"\nClass that handles all the individual files.\n-> Holds all of the information that a file would have.\n--> Filename, file doc_type, potential tags, etc.\n\"\"\"\n\nimport boto3\nfrom Source import CLIMenu\n\nclient = boto3.client('s3')\n\n\nclass FileHandle:\n \"\"\"A class that is used to manipulate (handle) the files themselves.\"\"\"\n\n file_name = \"\"\n file_type = \"\"\n bucket = \"\"\n tags = []\n\n def __init__(self, name):\n self.file_name = name\n if self.file_name.endswith('.pdf'):\n self.file_type = 'pdf'\n elif self.file_name.endswith('.docx'):\n self.file_type = 'docx'\n elif self.file_name.endswith('.jpg'):\n self.file_type = 'jpg'\n elif self.file_name.endswith('.png'):\n self.file_type = 'png'\n else:\n raise TypeError(\"Filename: \" + self.file_name +\n \"is not of type docx or pdf. Please only use supported filetypes.\")\n self.bucket = CLIMenu.current_bucket\n\n def add_tag(self, tags):\n self.tags.append(tags)\n","sub_path":"Source/FileHandle.py","file_name":"FileHandle.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"60421644","text":"def conta_bigramas(palavra):\n dicio={}\n i=0\n g=0\n nao=True\n \n while i<(len(palavra)-1):\n davez=palavra[i]+palavra[i+1]\n count=0\n for e in dicio:\n if e==davez:\n nao=False\n else:\n nao=True\n while g<(len(palavra)-1) and nao==True:\n if davez==palavra[g]+palavra[g+1]:\n count=count+1\n g=g+1 \n if nao==True:\n dicio[davez]=count\n i=i+1","sub_path":"backup/user_006/ch74_2020_04_13_13_05_59_665036.py","file_name":"ch74_2020_04_13_13_05_59_665036.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"147112099","text":"import json\nimport os\nfrom django.test import TestCase\nimport sqlalchemy\nfrom corehq.apps.userreports.models import DataSourceConfiguration\nfrom corehq.apps.userreports.pillow import ConfigurableIndicatorPillow\nfrom corehq.apps.userreports.sql import IndicatorSqlAdapter\nfrom corehq.apps.userreports.tests import get_sample_doc_and_indicators\n\n\nclass IndicatorPillowTest(TestCase):\n\n def setUp(self):\n folder = os.path.join(os.path.dirname(__file__), 'data', 'configs')\n sample_file = os.path.join(folder, 'sample_indicator_config.json')\n self.pillow = ConfigurableIndicatorPillow()\n self.engine = self.pillow.get_sql_engine()\n with open(sample_file) as f:\n structure = json.loads(f.read())\n self.config = DataSourceConfiguration.wrap(structure)\n self.pillow.bootstrap(configs=[self.config])\n\n self.adapter = IndicatorSqlAdapter(self.engine, self.config)\n self.adapter.rebuild_table()\n\n def tearDown(self):\n self.adapter.drop_table()\n self.engine.dispose()\n\n def testFilter(self):\n # note: this is a silly test now that python_filter always returns true\n not_matching = [\n dict(doc_type=\"NotCommCareCase\", domain='user-reports', type='ticket'),\n dict(doc_type=\"CommCareCase\", domain='not-user-reports', type='ticket'),\n dict(doc_type=\"CommCareCase\", domain='user-reports', type='not-ticket'),\n ]\n for document in not_matching:\n self.assertTrue(self.pillow.python_filter(document))\n\n self.assertTrue(self.pillow.python_filter(\n dict(doc_type=\"CommCareCase\", domain='user-reports', type='ticket')\n ))\n\n def testChangeTransport(self):\n # indicators\n sample_doc, expected_indicators = get_sample_doc_and_indicators()\n self.pillow.change_transport(sample_doc)\n with self.engine.begin() as connection:\n rows = connection.execute(sqlalchemy.select([self.adapter.get_table()]))\n self.assertEqual(1, rows.rowcount)\n row = rows.fetchone()\n for k, v in row.items():\n self.assertEqual(expected_indicators[k], v)\n","sub_path":"corehq/apps/userreports/tests/test_pillow.py","file_name":"test_pillow.py","file_ext":"py","file_size_in_byte":2192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"269738869","text":"import pandas as pd\nimport numpy as np\nfrom SelectGeneFeatures import select_gene_features\n\n\ngene_counts = pd.read_csv(\"RNAseq.csv\", encoding=\"ISO-8859-1\", dtype={'lab_id': str})\ngene_counts.set_index('lab_id', inplace=True)\ngene_counts_transpose = gene_counts.transpose()\ngene_names = gene_counts.index\ngene_count_ids = gene_counts_transpose.index\n\n\n# Gene Feature Selection\ngene_features = select_gene_features()\ntop_gene_counts = gene_counts.loc[gene_features]\ntop_gene_counts_t = top_gene_counts.transpose()\n\n\ndrug_responses = pd.read_csv(\"DrugResponses.csv\")\ninhibitors_list = drug_responses.inhibitor.unique()\ndel drug_responses['ic50']\npivot_drug_response = pd.pivot_table(drug_responses, index='lab_id', columns='inhibitor', aggfunc=np.max, fill_value=0)\n# Remove NA values\npivot_drug_response = pivot_drug_response[np.isfinite(pivot_drug_response)]\n\n\ndef select_samples(drug_num):\n sort_by_drug = pivot_drug_response.reindex(\n pivot_drug_response['auc'].sort_values(by=inhibitors_list[drug_num], ascending=False).index)\n sort_by_drug = sort_by_drug[sort_by_drug > 0]\n print(sort_by_drug.shape)\n print(sort_by_drug.head())\n drug_response = sort_by_drug['auc'][inhibitors_list[drug_num]]\n drug_response = drug_response.dropna()\n drug_response_ids = drug_response.index\n combined_ids = list(set(gene_count_ids) & set(drug_response_ids))\n print(\"Selected Samples: \")\n print(combined_ids)\n drug_sample_genetics = top_gene_counts_t.loc[combined_ids]\n drug_sample_genetics = drug_sample_genetics.dropna(axis='columns')\n drug_response = drug_response.loc[combined_ids]\n X = drug_sample_genetics.sort_index()\n Y = drug_response.sort_index()\n X.to_csv('./model_outputs/X' + inhibitors_list[drug_num] + '.csv')\n Y.to_csv('./model_outputs/Y' + inhibitors_list[drug_num] + '.csv')\n Y = threshold_adjust(Y)\n return X, Y\n\n\ndef threshold_adjust(y):\n threshold = np.percentile(y, 80)\n for i in range(0, len(y.index)):\n if y.iloc[i] >= threshold:\n y.iloc[i] = 1\n else:\n y.iloc[i] = 0\n return y\n\n\n","sub_path":"Classification_code/SelectSamples.py","file_name":"SelectSamples.py","file_ext":"py","file_size_in_byte":2097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"444460888","text":"from django.conf.urls import patterns, include, url\nfrom podcast.feeds import PodcastFeed\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'mysite.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n\n url(r'^$', 'podcast.views.index', name='podcast-index'),\n url(r'^(?P[-\\w]+)/$', 'podcast.views.podcast_list', name='view-podcast'),\n url(r'^(?P[-\\w]+)/(?P\\d+)/$', 'podcast.views.podcast_detail', name='view-podcast-episode'),\n url(r'^(?P[-\\w]+)/feed/$', PodcastFeed()),\n)","sub_path":"podcast/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"598485762","text":"# -*- coding: utf-8 -*-\n#\n\"\"\"\n\"\"\"\nimport data_auras\n\n# This is needed below for the eval method of script\nfrom auras.HarmfulAura import HarmfulAura\nfrom auras.HelpfulAura import HelpfulAura\n\n_g_auras = {}\n\ndef onInit():\n\t\"\"\"\n\tinit auras.\n\t\"\"\"\n\tfor key, data in data_auras.data.items():\n\t\tscript = data['script']\n\t\tscriptinst = eval(script)()\n\t\t_g_auras[key] = scriptinst\n\t\tscriptinst.loadFromDict(data)\n\ndef getAuraByIndex(auraIndex):\n\treturn _g_auras.get(auraIndex)\n\ndef getAuraByID(auraID):\n\t#print(_g_auras)\n\tfor key, aura in _g_auras.items():\n\t\tif aura.getID() == auraID:\n\t\t\treturn aura\n","sub_path":"prototyping/InitFix.py","file_name":"InitFix.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"275996233","text":"#Get the sentiment of text from a website\n\nfrom textblob import TextBlob\nimport nltk\nfrom newspaper import Article\n\nurl = 'https://everythingcomputerscience.com'\narticle = Article(url)\n\n#Do some NLP\narticle.download()\narticle.parse()\nnltk.download('punkt')\narticle.nlp()\n\n#Get the summary of the article\ntext = article.summary\n\n#print the text\nprint(text)\n\n#create a text blob object\ntextBlob = TextBlob(text)\n#returns a value between -1(negitive) and 1(positive)\nsentiment = textBlob.sentiment.polarity\nprint(sentiment)\n\nif sentiment == 0:\n print('The text is neutral')\nelif sentiment > 0:\n print('This text is positive')\nelif sentiment < 0:\n print('This text is negitive')\nelse:\n print('Something went wrong when analizing the text and the sentiment is ',sentiment)\n\n","sub_path":"Python/A__Scripts/sentimentAnalysis.py","file_name":"sentimentAnalysis.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"77808192","text":"from COMPS.Data import WorkItem\n\nfrom simtools.Services.ObejctCatelog.ObjectInfoSvc import ObjectInfoSvc\nfrom simtools.Utilities.COMPSUtilities import COMPS_login\n\n\nclass StatusSvc:\n\n @staticmethod\n def get_status(item_id):\n info = ObjectInfoSvc.get_item_info(item_id)\n\n if info:\n endpoint = info[\"provider_info\"].get(\"endpoint\", None)\n if info['type'] == 'WI' and info['provider'] == 'COMPS':\n COMPS_login(endpoint)\n wi = WorkItem.get(info['item_id'])\n return wi.state\n","sub_path":"simtools/Services/Status/StatusSvc.py","file_name":"StatusSvc.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"297357873","text":"#!/usr/bin/env python3\nimport argparse\nimport json\nimport re\nimport base64\nfrom urllib.parse import urlparse\n\n\nfrom iroha2 import Client\nfrom iroha2.data_model import *\nfrom iroha2.data_model.account import Id as AccountId\nfrom iroha2.data_model.asset import Id as AssetId\nfrom iroha2.data_model.expression import *\nfrom iroha2.sys.iroha_data_model import IdBox\nfrom iroha2.sys.iroha_data_model.asset import DefinitionId\nfrom iroha2.sys.iroha_data_model.query.account import FindAccountById\nfrom iroha2.sys.iroha_data_model.query.asset import FindAssetById\nfrom iroha2.sys.iroha_data_model.query.transaction import FindTransactionsByAccountId\n\nACCOUNT_ASSETS_OPERATION = 'account_assets'\nASSET_DETAILS_OPERATION = 'asset_details'\nALL_USER_TRANSACTIONS = 'all_tx'\nLATEST_USER_TRANSACTION = 'last_tx'\n\n\ndef parse_arguments():\n parser = argparse.ArgumentParser(description='Execute queries to iroha2')\n parser.add_argument('iroha_url', type=str, help='Url of iroha node (user:pass@example.com:port)')\n subparsers = parser.add_subparsers(dest='operation')\n\n parser_account_assets = subparsers.add_parser(ACCOUNT_ASSETS_OPERATION, help='Find account assets by account id')\n parser_account_assets.add_argument('account_id', type=str, help='Account ID (account@domain)')\n\n parser_asset_details = subparsers.add_parser(ASSET_DETAILS_OPERATION, help='Find asset details by asset id')\n parser_asset_details.add_argument('account_id', type=str, help='Account ID (account@domain)')\n parser_asset_details.add_argument('asset_id', type=str, help='Asset ID (token#domain)')\n\n parser_last_tx = subparsers.add_parser(ALL_USER_TRANSACTIONS, help='Find transactions by account id')\n parser_last_tx.add_argument('account_id', type=str, help='Account ID (account@domain)')\n\n parser_latest_block = subparsers.add_parser(LATEST_USER_TRANSACTION, help='Find latest transaction by account id')\n parser_latest_block.add_argument('account_id', type=str, help='Account ID (account@domain)')\n\n parser.add_argument('--public_key', type=str,\n help='Change default public key')\n parser.add_argument('--private_key', type=str,\n help='Change default private key')\n return parser.parse_args()\n\n\ndef get_account_parts(account_id):\n return account_id.split('@')\n\n\ndef get_asset_parts(asset_id):\n return asset_id.split('#')\n\n\ndef find_account_by_id(account_id):\n return iroha_client.query(\n FindAccountById(\n Expression(\n Value(\n IdBox(\n AccountId(*get_account_parts(account_id))\n )\n )\n )\n )\n )\n\n\ndef find_asset_by_id(account_id, asset_id):\n return iroha_client.query(\n FindAssetById(\n Expression(\n Value(\n IdBox(\n AssetId(\n DefinitionId(*get_asset_parts(asset_id)),\n AccountId(*get_account_parts(account_id))\n )\n )\n )\n )\n )\n )\n\n\ndef find_transactions_by_account_id(account_id):\n return iroha_client.query(\n FindTransactionsByAccountId(\n Expression(\n Value(\n IdBox(\n AccountId(*get_account_parts(account_id))\n )\n )\n )\n )\n )\n\n\ndef extract_key():\n return lambda exp: '{}\"{}\":'.format(exp.groups()[0], eval(exp.groups()[1])['definition_id']['name'])\n\n\ndef parse_response(response):\n try:\n dict_converted = re.sub(\"([\\'\\\"])?([a-zA-Z0-9_\\-.]+)([\\'\\\"])?\", r'\"\\2\"', str(response)).replace('\" \"', ' ')\n key_replaced = re.sub(\"([{,])({\\\"(definition|account).*?}):\", extract_key(), dict_converted)\n return eval(key_replaced)\n except Exception as ex:\n raise\n\n\ndef parse_url_authorization(client, config):\n url_parts = urlparse(args.iroha_url)\n if url_parts.username and url_parts.password:\n encoded_credentials = base64.b64encode(\"{}:{}\".format(url_parts.username, url_parts.password).encode('ascii')) \\\n .decode('ascii')\n client.headers = {\"Authorization\": \"Basic \" + str(encoded_credentials)}\n url = \"{}://{}\".format(url_parts.scheme if url_parts.scheme else \"http\", url_parts.hostname)\n if url_parts.port:\n url += \":\" + str(url_parts.port)\n config['TORII_API_URL'] = url\n\n\nif __name__ == '__main__':\n args = parse_arguments()\n cfg = json.loads(open(\"./config.json\").read())\n cfg['TORII_API_URL'] = args.iroha_url\n if args.public_key and args.private_key:\n cfg['PUBLIC_KEY'] = args.public_key\n cfg['PRIVATE_KEY']['payload'] = args.private_key\n\n iroha_client = Client(cfg)\n parse_url_authorization(iroha_client, cfg)\n\n response = \"\"\n try:\n if args.operation == ACCOUNT_ASSETS_OPERATION:\n response = parse_response(find_account_by_id(args.account_id)) \\\n .get('Identifiable', {}).get('Account', {}).get('assets', {})\n elif args.operation == ASSET_DETAILS_OPERATION:\n response = parse_response(find_asset_by_id(args.account_id, args.asset_id))\n elif args.operation == ALL_USER_TRANSACTIONS:\n response = parse_response(find_transactions_by_account_id(args.account_id)).get('Vec', [])\n elif args.operation == LATEST_USER_TRANSACTION:\n txs = {}\n for tx in parse_response(find_transactions_by_account_id(args.account_id)).get('Vec', []):\n block = tx.get('TransactionValue', {}).get('Transaction', {})\n if block:\n txs[int(block.get('creation_time', '0'))] = block\n if txs:\n response = txs[sorted(txs.keys())[-1]]\n else:\n response = \"No committed transactions for this account\"\n else:\n response = \"Operation doesn't exists\"\n\n print(json.dumps(response, sort_keys=True, indent=2))\n except Exception as e:\n print(\"Could not execute query: \", e)\n raise\n\n\n","sub_path":"iroha2-query-tool/iroha2-query-tool.py","file_name":"iroha2-query-tool.py","file_ext":"py","file_size_in_byte":6148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"513514142","text":"from Adafruit_PWM_Servo_Driver import PWM\nimport time\nimport curses\n\npwm = PWM(0x40, debug=True)\n\npwm.setPWMFreq(60) # Set frequency to 60 Hz\n\nscreen = curses.initscr()\n# turn off input echoing\ncurses.noecho()\n# respond to keys immediately (don't wait for enter)\ncurses.cbreak()\n# map arrow keys to special values\nscreen.keypad(True)\n\ndone=False\nnumbmax = 600\nnumbmin = 200\nnumb = numbmin\ninc = 10\n\ntry:\n while not done:\n char = screen.getch()\n if char == ord('q'):\n done=True\n else:\n if char == curses.KEY_UP:\n if numb < numbmax:\n numb += inc\n elif char == curses.KEY_DOWN:\n if numb > numbmin: \n numb -= inc\n elif char == ord('t'):\n numb = numbmax\n elif char == ord('b'):\n numb = numbmin\n pwm.setPWM(0,0,numb)\n\nfinally:\n curses.nocbreak(); screen.keypad(0); curses.echo()\n curses.endwin()\n print(numb)\n","sub_path":"esc_test2.py","file_name":"esc_test2.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"59021646","text":"from crispy_forms.helper import FormHelper\nfrom django.core.exceptions import ObjectDoesNotExist, ValidationError\nfrom django.forms import (\n BooleanField,\n CharField,\n FloatField,\n Form,\n IntegerField,\n JSONField,\n ModelForm,\n ModelMultipleChoiceField,\n TextInput,\n)\nfrom django.utils.text import format_lazy\nfrom django_select2.forms import Select2MultipleWidget\n\nfrom grandchallenge.algorithms.models import (\n Algorithm,\n AlgorithmImage,\n AlgorithmPermissionRequest,\n Job,\n)\nfrom grandchallenge.cases.forms import IMAGE_UPLOAD_HELP_TEXT\nfrom grandchallenge.components.models import ComponentInterface, InterfaceKind\nfrom grandchallenge.core.forms import (\n PermissionRequestUpdateForm,\n SaveFormInitMixin,\n WorkstationUserFilterMixin,\n)\nfrom grandchallenge.core.templatetags.bleach import clean\nfrom grandchallenge.core.validators import ExtensionValidator\nfrom grandchallenge.core.widgets import JSONEditorWidget, MarkdownEditorWidget\nfrom grandchallenge.groups.forms import UserGroupForm\nfrom grandchallenge.jqfileupload.widgets import uploader\nfrom grandchallenge.jqfileupload.widgets.uploader import UploadedAjaxFileList\nfrom grandchallenge.reader_studies.models import ANSWER_TYPE_SCHEMA\nfrom grandchallenge.subdomains.utils import reverse_lazy\n\nfile_upload_text = (\n \"The total size of all files uploaded in a single session \"\n \"cannot exceed 10 GB.
    \"\n \"The following file formats are supported: \"\n)\n\n\ndef _join_with_br(a, b):\n if a:\n return f\"{a}
    {b}\"\n else:\n return b\n\n\nclass InterfaceFormField:\n def __init__(\n self,\n *,\n kind: InterfaceKind.InterfaceKindChoices,\n initial=None,\n user=None,\n help_text=\"\",\n ):\n field_type = field_for_interface(kind)\n\n # bool can't be required\n kwargs = {\n \"required\": (kind != InterfaceKind.InterfaceKindChoices.BOOL),\n }\n\n extra_help = \"\"\n\n if initial is not None:\n kwargs[\"initial\"] = initial\n if kind in InterfaceKind.interface_type_annotation():\n kwargs[\"widget\"] = JSONEditorWidget(\n schema=ANSWER_TYPE_SCHEMA[\"definitions\"][kind]\n )\n if kind in InterfaceKind.interface_type_file():\n kwargs[\"widget\"] = uploader.AjaxUploadWidget(\n multifile=False, auto_commit=False\n )\n kwargs[\"validators\"] = [\n ExtensionValidator(allowed_extensions=(f\".{kind.lower()}\",))\n ]\n extra_help = f\"{file_upload_text} .{kind.lower()}\"\n if kind in InterfaceKind.interface_type_image():\n kwargs[\"widget\"] = uploader.AjaxUploadWidget(\n multifile=True, auto_commit=False\n )\n extra_help = IMAGE_UPLOAD_HELP_TEXT\n\n self._field = field_type(\n help_text=_join_with_br(help_text, extra_help), **kwargs\n )\n\n if user:\n self._field.widget.user = user\n\n @property\n def field(self):\n return self._field\n\n\ndef field_for_interface(i: InterfaceKind.InterfaceKindChoices):\n fields = {}\n for kind in InterfaceKind.interface_type_annotation():\n fields[kind] = JSONField\n for kind in (\n InterfaceKind.interface_type_image()\n + InterfaceKind.interface_type_file()\n ):\n fields[kind] = UploadedAjaxFileList\n fields.update(\n {\n InterfaceKind.InterfaceKindChoices.BOOL: BooleanField,\n InterfaceKind.InterfaceKindChoices.STRING: CharField,\n InterfaceKind.InterfaceKindChoices.INTEGER: IntegerField,\n InterfaceKind.InterfaceKindChoices.FLOAT: FloatField,\n }\n )\n return fields[i]\n\n\nclass AlgorithmInputsForm(SaveFormInitMixin, Form):\n def __init__(self, *args, algorithm=None, user=None, **kwargs):\n super().__init__(*args, **kwargs)\n\n if algorithm is None:\n return\n\n self.helper = FormHelper()\n\n for inp in algorithm.inputs.all():\n self.fields[inp.slug] = InterfaceFormField(\n kind=inp.kind,\n initial=inp.default_value,\n user=user,\n help_text=clean(inp.description) if inp.description else \"\",\n ).field\n\n\n# Exclude interfaces that are not aimed at algorithms from user selection\nNON_ALGORITHM_INTERFACES = [\n \"predictions-csv-file\",\n \"predictions-json-file\",\n \"predictions-zip-file\",\n \"metrics-json-file\",\n]\n\n\nclass AlgorithmForm(WorkstationUserFilterMixin, SaveFormInitMixin, ModelForm):\n inputs = ModelMultipleChoiceField(\n queryset=ComponentInterface.objects.exclude(\n slug__in=[*NON_ALGORITHM_INTERFACES, \"results-json-file\"]\n ),\n widget=Select2MultipleWidget,\n help_text=format_lazy(\n (\n \"The inputs to this algorithm. \"\n 'See the list of interfaces for more '\n \"information about each interface. \"\n \"Please contact support if your desired input is missing.\"\n ),\n reverse_lazy(\"algorithms:component-interface-list\"),\n ),\n )\n outputs = ModelMultipleChoiceField(\n queryset=ComponentInterface.objects.exclude(\n slug__in=NON_ALGORITHM_INTERFACES\n ),\n widget=Select2MultipleWidget,\n help_text=format_lazy(\n (\n \"The outputs to this algorithm. \"\n 'See the list of interfaces for more '\n \"information about each interface. \"\n \"Please contact support if your desired output is missing.\"\n ),\n reverse_lazy(\"algorithms:component-interface-list\"),\n ),\n )\n\n class Meta:\n model = Algorithm\n fields = (\n \"title\",\n \"description\",\n \"publications\",\n \"modalities\",\n \"structures\",\n \"organizations\",\n \"logo\",\n \"social_image\",\n \"public\",\n \"use_flexible_inputs\",\n \"inputs\",\n \"outputs\",\n \"workstation\",\n \"workstation_config\",\n \"credits_per_job\",\n \"detail_page_markdown\",\n \"job_create_page_markdown\",\n \"additional_terms_markdown\",\n \"result_template\",\n )\n widgets = {\n \"description\": TextInput,\n \"detail_page_markdown\": MarkdownEditorWidget,\n \"job_create_page_markdown\": MarkdownEditorWidget,\n \"additional_terms_markdown\": MarkdownEditorWidget,\n \"result_template\": MarkdownEditorWidget,\n \"publications\": Select2MultipleWidget,\n \"modalities\": Select2MultipleWidget,\n \"structures\": Select2MultipleWidget,\n \"organizations\": Select2MultipleWidget,\n }\n help_texts = {\n \"workstation_config\": format_lazy(\n (\n \"The workstation configuration to use for this algorithm. \"\n \"If a suitable configuration does not exist you can \"\n 'create a new one.'\n ),\n reverse_lazy(\"workstation-configs:create\"),\n )\n }\n\n def clean(self):\n cleaned_data = super().clean()\n\n inputs = {inpt.slug for inpt in cleaned_data[\"inputs\"]}\n\n if (\n inputs != {\"generic-medical-image\"}\n and not cleaned_data[\"use_flexible_inputs\"]\n ):\n raise ValidationError(\n \"'Use Flexible Inputs' must also be selected when using the \"\n \"set of inputs you have selected.\"\n )\n\n return cleaned_data\n\n\nclass AlgorithmImageForm(ModelForm):\n chunked_upload = UploadedAjaxFileList(\n widget=uploader.AjaxUploadWidget(multifile=False),\n label=\"Algorithm Image\",\n validators=[\n ExtensionValidator(allowed_extensions=(\".tar\", \".tar.gz\"))\n ],\n help_text=(\n \".tar.gz archive of the container image produced from the command \"\n \"'docker save IMAGE | gzip -c > IMAGE.tar.gz'. See \"\n \"https://docs.docker.com/engine/reference/commandline/save/\"\n ),\n )\n requires_memory_gb = IntegerField(\n min_value=1,\n max_value=24,\n initial=4,\n help_text=\"The maximum system memory required by the algorithm in gigabytes.\",\n )\n\n def __init__(self, *args, user, **kwargs):\n super().__init__(*args, **kwargs)\n self.helper = FormHelper(self)\n self.fields[\"chunked_upload\"].widget.user = user\n\n class Meta:\n model = AlgorithmImage\n fields = (\"requires_gpu\", \"requires_memory_gb\", \"chunked_upload\")\n\n\nclass AlgorithmImageUpdateForm(SaveFormInitMixin, ModelForm):\n requires_memory_gb = IntegerField(\n min_value=1,\n max_value=24,\n help_text=\"The maximum system memory required by the algorithm in gigabytes.\",\n )\n\n class Meta:\n model = AlgorithmImage\n fields = (\"requires_gpu\", \"requires_memory_gb\")\n\n\nclass UsersForm(UserGroupForm):\n role = \"user\"\n\n def add_or_remove_user(self, *, obj):\n super().add_or_remove_user(obj=obj)\n\n user = self.cleaned_data[\"user\"]\n\n try:\n permission_request = AlgorithmPermissionRequest.objects.get(\n user=user, algorithm=obj\n )\n except ObjectDoesNotExist:\n return\n\n if self.cleaned_data[\"action\"] == self.REMOVE:\n permission_request.status = AlgorithmPermissionRequest.REJECTED\n else:\n permission_request.status = AlgorithmPermissionRequest.ACCEPTED\n\n permission_request.save()\n\n\nclass ViewersForm(UserGroupForm):\n role = \"viewer\"\n\n\nclass JobForm(SaveFormInitMixin, ModelForm):\n class Meta:\n model = Job\n fields = (\"comment\", \"public\")\n\n\nclass AlgorithmPermissionRequestUpdateForm(PermissionRequestUpdateForm):\n class Meta(PermissionRequestUpdateForm.Meta):\n model = AlgorithmPermissionRequest\n","sub_path":"app/grandchallenge/algorithms/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":10103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"167652085","text":"\"\"\"YOLO v3 output\n\"\"\"\n\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport time\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom keras.models import load_model\nimport cv2\n\n\ndef process_image(img):\n \"\"\"\n Resize, reduce and expand image.\n # Argument:\n img: original image.\n\n # Returns\n image: ndarray(64, 64, 3), processed image.\n \"\"\"\n image = cv2.resize(img, (416, 416),\n interpolation=cv2.INTER_CUBIC)\n image = np.array(image, dtype='float32')\n image /= 255.\n image = np.expand_dims(image, axis=0)\n return image\n\n\n\nclass YOLO:\n def __init__(self, obj_threshold, nms_threshold):\n \"\"\"Init.\n # Arguments\n obj_threshold: Integer, threshold for object.\n nms_threshold: Integer, threshold for box.\n \"\"\"\n self._t1 = obj_threshold\n self._t2 = nms_threshold\n self._yolo = load_model('../data/yolo.h5')\n\n def _sigmoid(self, x):\n \"\"\"sigmoid.\n # Arguments\n x: Tensor.\n # Returns\n numpy ndarray.\n \"\"\"\n return 1 / (1 + np.exp(-x))\n\n def _process_feats(self, out, anchors, mask):\n \"\"\"process output features.\n # Arguments\n out: Tensor (N, N, 3, 4 + 1 +80), output feature map of yolo.\n anchors: List, anchors for box.\n mask: List, mask for anchors.\n # Returns\n boxes: ndarray (N, N, 3, 4), x,y,w,h for per box.\n box_confidence: ndarray (N, N, 3, 1), confidence for per box.\n box_class_probs: ndarray (N, N, 3, 80), class probs for per box.\n \"\"\"\n grid_h, grid_w, num_boxes = map(int, out.shape[1: 4])\n\n anchors = [anchors[i] for i in mask]\n anchors_tensor = np.array(anchors).reshape(1, 1, len(anchors), 2)\n\n # Reshape to batch, height, width, num_anchors, box_params.\n #out = out[0]\n box_xy = self._sigmoid(out[..., :2])\n box_wh = np.exp(out[..., 2:4])\n box_wh = box_wh * anchors_tensor\n\n box_confidence = self._sigmoid(out[..., 4])\n box_confidence = np.expand_dims(box_confidence, axis=-1)\n box_class_probs = self._sigmoid(out[..., 5:])\n\n col = np.tile(np.arange(0, grid_w), grid_w).reshape(-1, grid_w)\n row = np.tile(np.arange(0, grid_h).reshape(-1, 1), grid_h)\n\n col = col.reshape(grid_h, grid_w, 1, 1).repeat(3, axis=-2)\n row = row.reshape(grid_h, grid_w, 1, 1).repeat(3, axis=-2)\n grid = np.concatenate((col, row), axis=-1)\n\n box_xy += grid\n box_xy /= (grid_w, grid_h)\n box_wh /= (416, 416)\n box_xy -= (box_wh / 2.)\n boxes = np.concatenate((box_xy, box_wh), axis=-1)\n\n return boxes, box_confidence, box_class_probs\n\n def _filter_boxes(self, boxes, box_confidences, box_class_probs):\n \"\"\"Filter boxes with object threshold.\n # Arguments\n boxes: ndarray, boxes of objects.\n box_confidences: ndarray, confidences of objects.\n box_class_probs: ndarray, class_probs of objects.\n # Returns\n boxes: ndarray, filtered boxes.\n classes: ndarray, classes for boxes.\n scores: ndarray, scores for boxes.\n \"\"\"\n box_scores = box_confidences * box_class_probs\n box_classes = np.argmax(box_scores, axis=-1)\n box_class_scores = np.max(box_scores, axis=-1)\n pos = np.where(box_class_scores >= self._t1)\n\n boxes = boxes[pos]\n classes = box_classes[pos]\n scores = box_class_scores[pos]\n\n return boxes, classes, scores\n\n def _nms_boxes(self, boxes, scores):\n \"\"\"Suppress non-maximal boxes.\n # Arguments\n boxes: ndarray, boxes of objects.\n scores: ndarray, scores of objects.\n # Returns\n keep: ndarray, index of effective boxes.\n \"\"\"\n x = boxes[:, 0]\n y = boxes[:, 1]\n w = boxes[:, 2]\n h = boxes[:, 3]\n\n areas = w * h\n # Arrange the scores in reverse order, and put the largest in the first order\n order = scores.argsort()[::-1]\n\n keep = []\n while order.size > 0:\n i = order[0]\n keep.append(i)\n\n # calculate object score on most possible box and other boxes\n xx1 = np.maximum(x[i], x[order[1:]])\n yy1 = np.maximum(y[i], y[order[1:]])\n xx2 = np.minimum(x[i] + w[i], x[order[1:]] + w[order[1:]])\n yy2 = np.minimum(y[i] + h[i], y[order[1:]] + h[order[1:]])\n\n w1 = np.maximum(0.0, xx2 - xx1 + 1)\n h1 = np.maximum(0.0, yy2 - yy1 + 1)\n inter = w1 * h1\n ovr = inter / (areas[i] + areas[order[1:]] - inter)\n \n # compare with threshold, choose the boxes whose MNS is smaller than threshold\n inds = np.where(ovr <= self._t2)[0]\n order = order[inds + 1]\n\n keep = np.array(keep)\n\n return keep\n\n def _yolo_out(self, outs, shape):\n \"\"\"Process output of yolo base net.\n # Argument:\n outs: output of yolo base net.\n shape: shape of original image.\n # Returns:\n boxes: ndarray, boxes of objects.\n classes: ndarray, classes of objects.\n scores: ndarray, scores of objects.\n \"\"\"\n masks = [[6, 7, 8], [3, 4, 5], [0, 1, 2]]\n anchors = [[10, 13], [16, 30], [33, 23], [30, 61], [62, 45],\n [59, 119], [116, 90], [156, 198], [373, 326]]\n\n boxes, classes, scores = [], [], []\n\n for out, mask in zip(outs, masks):\n b, c, s = self._process_feats(out, anchors, mask)\n b, c, s = self._filter_boxes(b, c, s)\n boxes.append(b)\n classes.append(c)\n scores.append(s)\n\n boxes = np.concatenate(boxes, axis = 0)\n classes = np.concatenate(classes, axis = 0)\n scores = np.concatenate(scores, axis = 0)\n \n # Scale boxes back to original image shape.\n width, height = shape[1], shape[0]\n image_dims = [width, height, width, height]\n boxes = boxes * image_dims\n\n nboxes, nclasses, nscores = [], [], []\n for c in set(classes):\n # Here, use set function to remove duplicate classes, and judge NMS according to class in for loop\n inds = np.where(classes == c)\n b = boxes[inds]\n c = classes[inds]\n s = scores[inds]\n\n keep = self._nms_boxes(b, s)\n\n nboxes.append(b[keep])\n nclasses.append(c[keep])\n nscores.append(s[keep])\n\n if not nclasses and not nscores:\n return [], [], []\n\n boxes = np.concatenate(nboxes)\n classes = np.concatenate(nclasses)\n scores = np.concatenate(nscores)\n\n return boxes, classes, scores\n\n def predict(self, image, shape):\n \"\"\"Detect the objects with yolo.\n # Arguments\n image: ndarray, processed input image.\n shape: shape of original image.\n # Returns\n boxes: ndarray, boxes of objects.\n classes: ndarray, classes of objects.\n scores: ndarray, scores of objects.\n \"\"\"\n\n outs = self._yolo.predict(image)\n boxes, classes, scores = self._yolo_out(outs, shape)\n\n return boxes, classes, scores\n \n\ndef vis_bbox(img, bbox, label=None, score=None, path=None):\n \"\"\"Visualize bounding boxes inside image.\n\n Args:\n img (~numpy.ndarray): An array of shape :math:`(3, height, width)`.\n This is in RGB format and the range of its value is\n :math:`[0, 255]`.\n bbox (~numpy.ndarray): An array of shape :math:`(R, 4)`, where\n :math:`R` is the number of bounding boxes in the image.\n Each element is organized\n by :math:`(y_{min}, x_{min}, y_{max}, x_{max})` in the second axis.\n label (~numpy.ndarray): An integer array of shape :math:`(R,)`.\n The values correspond to id for label names stored in\n :obj:`label_names`. This is optional.\n score (~numpy.ndarray): A float array of shape :math:`(R,)`.\n Each value indicates how confident the prediction is.\n This is optional.\n label_names (iterable of strings): Name of labels ordered according\n to label ids. If this is :obj:`None`, labels will be skipped.\n ax (matplotlib.axes.Axis): The visualization is displayed on this\n axis. If this is :obj:`None` (default), a new axis is created.\n\n Returns:\n ~matploblib.axes.Axes:\n Returns the Axes object with the plot for further tweaking.\n\n \"\"\"\n file = '../data/coco_classes.txt'\n with open(file) as f:\n class_names = f.readlines()\n VOC_BBOX_LABEL_NAMES = [c.strip() for c in class_names]\n\n label_names = list(VOC_BBOX_LABEL_NAMES) + ['bg']\n # add for index `-1`\n if label is not None and not len(bbox) == len(label):\n raise ValueError('The length of label must be same as that of bbox')\n if score is not None and not len(bbox) == len(score):\n raise ValueError('The length of score must be same as that of bbox')\n\n # Returns newly instantiated matplotlib.axes.Axes object if ax is None\n #ax = vis_image(img, ax=ax)\n \n fig = plt.figure()\n plt.imshow(img)\n ax = fig.add_subplot(111)\n\n # If there is no bounding box to display, visualize the image and exit.\n if len(bbox) != 0:\n for i, bb in enumerate(bbox):\n xy = (bb[0], bb[1])\n height = bb[3] - bb[1]\n width = bb[2] - bb[0]\n ax.add_patch(plt.Rectangle(\n xy, width, height, fill=False, edgecolor='red', linewidth=2))\n \n caption = list()\n \n if label is not None and label_names is not None:\n lb = int(label[i])\n if not (-1 <= lb < len(label_names)): # modfy here to add backgroud\n raise ValueError('No corresponding name is given')\n caption.append(label_names[lb])\n if score is not None:\n sc = score[i]\n caption.append('{:.2f}'.format(sc))\n \n if len(caption) > 0:\n plt.text(bb[0], bb[1],\n ': '.join(caption),\n style='italic',\n bbox={'facecolor': 'white', 'alpha': 0.5, 'pad': 0})\n if path:\n plt.savefig(path, dpi=200)\n else:\n plt.show()\n \n plt.close()\n\n\n","sub_path":"YOLO_attacker/object_attack/yolo_model.py","file_name":"yolo_model.py","file_ext":"py","file_size_in_byte":10526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"284255913","text":"from django.conf.urls import url, patterns\nfrom condowatcher.views import AdListView, AdDetailView, ApplicantView, ApplicantDetailView, ApplicantFormView, ApplicantUpdateView, LinkFormView, LinkDeleteView, ScraperFormView\n\nurlpatterns = patterns(\n '',\n\n url(regex=r'^$',\n view=AdListView.as_view(),\n name='ad_list'),\n\n url(regex=r'^(?P[0-9]+)/$',\n view=AdDetailView.as_view(),\n name='ad_detail'),\n\n url(regex=r'^scraper/$',\n view=ScraperFormView.as_view(),\n name='scraper_form'),\n\n url(regex=r'^applicant/$',\n view=ApplicantView.as_view(),\n name='applicant'),\n\n url(regex=r'^applicant/new/$',\n view=ApplicantFormView.as_view(),\n name=\"applicant_form\"),\n\n url(regex=r'^applicant/link/new/$',\n view=LinkFormView.as_view(),\n name=\"link_form\"),\n\n url(regex=r'^applicant/link/(?P\\d+)/delete/$',\n view=LinkDeleteView.as_view(),\n name=\"link_delete\"),\n\n url(regex=r'^applicant/(?P\\d+)/$',\n view=ApplicantDetailView.as_view(),\n name='applicant_detail'),\n\n url(regex=r'^applicant/(?P\\d+)/edit/$',\n view=ApplicantUpdateView.as_view(),\n name=\"applicant_update\"),\n)\n","sub_path":"condowatcher/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"142230683","text":"from binascii import hexlify\nfrom csv import reader\nfrom collections import OrderedDict as odict\n\n#pylint: disable-msg=invalid-name\n#pylint: disable-msg=missing-docstring\n\n\nclass SaleaeParser:\n\n def __init__(self):\n self.cs_idle = True\n self.cs_active = not self.cs_idle\n self.clk_idle = False\n self.clk_sample = True\n\n def parse(self, cfp):\n csvreader = reader(cfp)\n cols = None\n started = False\n in_frame = False\n sclk = None\n mosi = None\n cs = None\n byte = 0\n bit_count = 0\n byte_count = 0\n last_sclk = self.clk_idle\n sof_time = None\n eof_time = None\n command = False\n spi_clock = None\n frames = []\n resume_frame = False\n for row in csvreader:\n if not cols:\n # obtain columns headers (use once)\n cols = {v.lower(): k for k, v in\n enumerate(['TS'] + [x.strip() for x in row[1:]])}\n # print(cols)\n sclk = cols['sclk']\n mosi = cols['mosi']\n cs = cols['cs']\n continue\n row = [float(row[0])] + [bool(int(x)) for x in row[1:]]\n if not started:\n # skip all data until /CS is initially IDLE\n if row[cols['cs']] == self.cs_idle:\n continue\n # print('Started @ %.3f ms' % (row[0]*1e3))\n started = True\n if not in_frame:\n # /CS line is for now idle\n if row[cs] == self.cs_active:\n sof_time = row[0]\n in_frame = True\n if eof_time is not None and \\\n spi_clock is not None and \\\n frames:\n delta = sof_time - eof_time\n # append next byte to the current frame if the\n # delay between bytes is short enough\n resume_frame = delta < (4 * spi_clock)\n #print('Frame spacing: %.3f ms clock %.3f ms' %\n # (delta * 1e3, spi_clock * 1e3))\n # print('Frame start @ %.3f ms' % (row[0]*1e3))\n byte = 0\n bit_count = 0\n last_sclk = row[sclk]\n command = not row[cols['a0']]\n continue\n if in_frame:\n # /CS line is for now active\n if row[cs] != self.cs_active:\n delta = row[0] - sof_time\n in_frame = False\n eof_time = row[0]\n # print('--- EOF [%.1f µs]' % (delta*1e6))\n continue\n if row[sclk] == last_sclk:\n continue\n if row[sclk] == self.clk_sample:\n if bit_count == 0:\n clock = row[0]\n bit = row[mosi]\n byte <<= 1\n byte |= bit\n bit_count += 1\n if bit_count == 8:\n # print(hex(byte), command)\n if resume_frame:\n # disable resume_frame if not of same kind\n resume_frame = frames[-1][1] == command\n if resume_frame:\n frames[-1][2].append(byte)\n else:\n frames.append((sof_time, command, [byte]))\n byte_count += 1\n byte = 0\n elif bit_count == 8 and row[sclk] == self.clk_idle:\n bit_count = 0\n spi_clock = (row[0] - clock) / 8\n #frequency = 1 / spi_clock\n #print('FREQ %.0f KHz' % (frequency/1.e3))\n last_sclk = row[sclk]\n if byte_count > 10000:\n break\n dataframes = []\n for frame in frames:\n dataframes.append((frames[0], frame[1], bytes(frame[2])))\n return dataframes\n\n #for fts, cmd, data in frames:\n # print('%.3f ms %s %s' %\n # (fts*1e3, 'I' if cmd else 'D',\n # hexlify(bytes(data)).decode()))\n\n","sub_path":"Python/pallaza/saleae.py","file_name":"saleae.py","file_ext":"py","file_size_in_byte":4242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"554488161","text":"#!/usr/bin/env python\n\n\"\"\"\nsends a \"die\" command to the llh service\ncauses a running llh service to exit its work loop\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\n__author__ = \"Aaron Fienberg\"\n\nimport argparse\nimport json\nimport sys\n\nimport zmq\n\n\ndef main():\n parser = argparse.ArgumentParser(\n description=\"Attempts to kill a running LLH service\"\n )\n parser.add_argument(\n \"-c\", \"--conf_file\", type=str, help=\"service configuration file\", required=True\n )\n args = parser.parse_args()\n\n with open(args.conf_file) as f:\n params = json.load(f)\n\n ctrl_sock = zmq.Context.instance().socket(zmq.REQ)\n\n ctrl_sock.setsockopt(zmq.LINGER, 0)\n ctrl_sock.setsockopt(zmq.RCVTIMEO, 1000)\n ctrl_sock.connect(params[\"ctrl_addr\"])\n\n ctrl_sock.send_string(\"die\")\n try:\n print(f\"service response: {ctrl_sock.recv_string()}\")\n except zmq.error.Again:\n print(f\"No response from LLH service\")\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","sub_path":"examples/service_test/kill_service.py","file_name":"kill_service.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"180130285","text":"from picamera import PiCamera\nfrom time import sleep\n\ncamera = PiCamera()\n\ncamera.start_preview()\nname = raw_input(\"What should the video name be?\")\ncamera.start_recording(str(name) + '.h264')\nsleep(10)\ncamera.stop_recording()\ncamera.stop_preview()\n","sub_path":"archive/recordVideo.py","file_name":"recordVideo.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"133773419","text":"#!/usr/bin/python\n\nimport networkx as nx\nimport random\nimport math\n\n# INDEPENDENT CASCADE MODEL\n# graph may have edge prob\ndef cascade(graph,active,prob):\n if len(active)>0:\n newactive=set()\n for i in active:\n graph.node[i]['active']=True\n for j in graph[i]:\n if 'active' not in graph.node[j]:\n r=random.random()\n if r <= prob:\n newactive.add(j)\n cascade(graph,newactive,prob)\n return graph\n\n# LINEAR THRESHOLD MODEL (a node can change only once)\ndef threshold(graph,active):\n thresholds = nx.get_node_attributes(graph,'threshold')\n if len(thresholds) == 0:\n for i in graph.nodes():\n graph.node[i]['threshold']=random.random()\n\n if len(active)>0:\n newactive=set()\n for i in active:\n graph.node[i]['active']=True\n for j in graph[i]:\n if 'active' not in graph.node[j]:\n if 'act_neigh' in graph.node[j]:\n graph.node[j]['act_neigh'] += 1/len(graph[j])\n else:\n graph.node[j]['act_neigh'] = 1/len(graph[j])\n if graph.node[j]['act_neigh'] >= graph.node[j]['threshold']:\n newactive.add(j)\n threshold(graph,newactive)\n \n return graph\n \n# MAJORITY DYNAMICS (a node can change multiple time)\n# result may depend on the order\n# single update at each time (it may not converge otherwise)\ndef majority(graph,act,nact):\n if len(act)>0 or len(nact)>0:\n for i in act:\n if 'active' not in graph.node[i] or not graph.node[i]['active']:\n graph.node[i]['active']=True\n for j in graph[i]:\n if 'act_neigh' in graph.node[j]:\n graph.node[j]['act_neigh'] += 1\n else:\n graph.node[j]['act_neigh'] = 1\n for i in nact:\n if 'active' not in graph.node[i] or graph.node[i]['active']:\n graph.node[i]['active']=False\n for j in graph[i]:\n if 'act_neigh' in graph.node[j]:\n graph.node[j]['act_neigh'] -= 1\n else:\n graph.node[j]['act_neigh'] = 0\n \n for i in graph.nodes():\n if 'act_neigh' in graph.node[i] and graph.node[i]['act_neigh'] >= len(graph[i])/2 and ('active' not in graph.node[i] or not graph.node[i]['active']):\n majority(graph,{i},{})\n break\n if ('act_neigh' not in graph.node[i] or graph.node[i]['act_neigh'] < len(graph[i])/2) and ('active' in graph.node[i] and graph.node[i]['active']):\n majority(graph,{},{i})\n break\n \n return graph\n\n# BEST RESPONSE DYNAMICS FOR NETWORK COORDINATION GAMES (a node can change multiple times)\ndef best_resp(graph,act,nact):\n thresholds = nx.get_node_attributes(graph,'threshold')\n if len(thresholds) == 0:\n for i in graph.nodes():\n graph.node[i]['threshold']=random.random()*len(graph[i])\n \n if len(act)>0 or len(nact)>0:\n for i in act:\n if 'active' not in graph.node[i] or not graph.node[i]['active']:\n graph.node[i]['active']=True\n for j in graph[i]:\n if 'act_neigh' in graph.node[j]:\n graph.node[j]['act_neigh'] += 1\n else:\n graph.node[j]['act_neigh'] = 1\n for i in nact:\n if 'active' not in graph.node[i] or graph.node[i]['active']:\n graph.node[i]['active']=False\n for j in graph[i]:\n if 'act_neigh' in graph.node[j]:\n graph.node[j]['act_neigh'] -= 1\n else:\n graph.node[j]['act_neigh'] = 0\n \n for i in graph.nodes():\n if 'act_neigh' in graph.node[i] and graph.node[i]['act_neigh'] >= graph.node[i]['threshold'] and ('active' not in graph.node[i] or not graph.node[i]['active']):\n best_resp(graph,{i},{})\n break\n if ('act_neigh' not in graph.node[i] or graph.node[i]['act_neigh'] < graph.node[i]['threshold']) and ('active' in graph.node[i] and graph.node[i]['active']):\n best_resp(graph,{},{i})\n break\n \n return graph\n\n# VOTER MODEL\ndef voter(graph, seed, num_steps):\n for i in graph.nodes():\n if i in seed:\n graph.node[i]['active'] = True\n else:\n graph.node[i]['active'] = False\n \n for t in range(num_steps):\n u=random.choice(list(graph.nodes()))\n v=random.choice(list(graph[u]))\n graph.node[u]['active'] = graph.node[v]['active']\n \n return graph\nif __name__ == '__main__':\n\n G=nx.Graph()\n G.add_edge('A','B')\n G.add_edge('A','C')\n G.add_edge('B','C')\n G.add_edge('B','D')\n G.add_edge('D','E')\n G.add_edge('D','F')\n G.add_edge('D','G')\n G.add_edge('E','F')\n G.add_edge('F','G')\n seed={'B'}\n #UNCOMMENT FOR TEST\n #INDEPENDENT CASCADE\n # print(list(nx.get_node_attributes(cascade(G,seed,2/3),'active').keys()))\n #\n # #LINEAR THRESHOLD\n # print(list(nx.get_node_attributes(threshold(G,seed),'active').keys()))\n\n #MAJORITY\n # active = nx.get_node_attributes(majority(G,seed,{}),'active')\n # print([i for i in active.keys() if active[i]])\n\n #BEST RESPONSE\n active = nx.get_node_attributes(best_resp(G,seed,{}),'active')\n print([i for i in active.keys() if active[i]])\n\n #VOTER\n #active = nx.get_node_attributes(voter(G,seed,10),'active')\n #print([i for i in active.keys() if active[i]])\n","sub_path":"Esercitazioni/esercitazione_7/Dynamics.py","file_name":"Dynamics.py","file_ext":"py","file_size_in_byte":5798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"153866293","text":"# -*- coding: utf-8 -*-\n# @Author: lujianhong\n# @Date: 2019-07-23 15:08:48\n# @Last Modified by: lujianhong\n# @Last Modified time: 2019-07-23 15:17:17\nclass Solution:\n\tdef peakIndexInMountainArray(self, A):\n\t\ti = 0\n\t\twhile i < len(A):\n\t\t\tif A[i] < A[i+1]:\n\t\t\t\ti = i + 1\n\t\t\t\tcontinue\n\t\t\telif A[i] > A[i+1]:\n\t\t\t\treturn i\nsolution = Solution()\nprint(solution.peakIndexInMountainArray([0,2,1,0]))\n\n# class Solution:\n# \t\tdef peakIndexInMountainArray(self, A):\n# \t\t\treturn A.index(max(A))","sub_path":"852. Peak Index in a Mountain Array/peakIndexInMountainArray.py","file_name":"peakIndexInMountainArray.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"54274251","text":"from unittest import mock\nfrom uuid import uuid4\n\nfrom river.common.analyzer import Analyzer\nfrom river.common.analyzer.attribute import Attribute\nfrom river.common.analyzer.condition import Condition\nfrom river.common.analyzer.input_group import InputGroup\nfrom river.common.analyzer.sql_column import SqlColumn\nfrom river.common.analyzer.sql_filter import SqlFilter\nfrom river.common.analyzer.sql_join import SqlJoin\n\n\ndef test_cache_analysis_redis(patient_mapping):\n batch_id, resource_id = (uuid4(), uuid4())\n analyzer = Analyzer()\n\n res = analyzer.cache_analysis(batch_id, resource_id, patient_mapping)\n\n assert res.definition_id == \"Patient\"\n assert res.primary_key_column.table == \"patients\"\n assert res.primary_key_column.column == \"row_id\"\n\n assert analyzer.analyses[f\"{batch_id}:{resource_id}\"].definition_id == \"Patient\"\n assert analyzer.analyses[f\"{batch_id}:{resource_id}\"].primary_key_column.table == \"patients\"\n assert analyzer.analyses[f\"{batch_id}:{resource_id}\"].primary_key_column.column == \"row_id\"\n\n cached_res = analyzer.load_analysis(batch_id, resource_id)\n\n assert cached_res is not None\n assert cached_res == res\n\n\ndef test_get_primary_key():\n analyzer = Analyzer()\n\n # With owner\n resource_mapping = {\n \"primaryKeyOwner\": {\"name\": \"owner\"},\n \"primaryKeyTable\": \"table\",\n \"primaryKeyColumn\": \"col\",\n }\n primary_key = analyzer.get_primary_key(resource_mapping)\n\n assert primary_key == SqlColumn(\"owner\", \"table\", \"col\")\n\n # With missing field\n resource_mapping = {\n \"primaryKeyTable\": \"\",\n \"primaryKeyColumn\": \"col\",\n \"primaryKeyOwner\": {\"name\": \"owner\"},\n \"definitionId\": \"fhirtype\",\n }\n assert analyzer.get_primary_key(resource_mapping) is None\n\n\ndef test_analyze_mapping(patient_mapping):\n analyzer = Analyzer()\n\n analysis = analyzer.analyze_mapping(patient_mapping)\n\n assert len(analysis.attributes) == 18\n\n assert analyzer.get_analysis_columns(analysis) == {\n SqlColumn(\"mimiciii\", \"patients\", \"row_id\"),\n SqlColumn(\"mimiciii\", \"patients\", \"subject_id\"),\n SqlColumn(\"mimiciii\", \"patients\", \"dob\"),\n SqlColumn(\"mimiciii\", \"patients\", \"dod\"),\n SqlColumn(\"mimiciii\", \"patients\", \"expire_flag\"),\n SqlColumn(\"mimiciii\", \"patients\", \"gender\"),\n SqlColumn(\n \"mimiciii\",\n \"admissions\",\n \"admittime\",\n joins=[\n SqlJoin(\n SqlColumn(\"mimiciii\", \"patients\", \"subject_id\"), SqlColumn(\"mimiciii\", \"admissions\", \"subject_id\")\n )\n ],\n ),\n SqlColumn(\n \"mimiciii\",\n \"admissions\",\n \"marital_status\",\n joins=[\n SqlJoin(\n SqlColumn(\"mimiciii\", \"patients\", \"subject_id\"), SqlColumn(\"mimiciii\", \"admissions\", \"subject_id\")\n )\n ],\n ),\n SqlColumn(\n \"mimiciii\",\n \"admissions\",\n \"language\",\n joins=[\n SqlJoin(\n SqlColumn(\"mimiciii\", \"patients\", \"subject_id\"), SqlColumn(\"mimiciii\", \"admissions\", \"subject_id\")\n )\n ],\n ),\n }\n assert analysis.filters == [\n SqlFilter(\n SqlColumn(\n \"mimiciii\",\n \"admissions\",\n \"adm_date\",\n joins=[\n SqlJoin(\n SqlColumn(\"mimiciii\", \"patients\", \"subject_id\"),\n SqlColumn(\"mimiciii\", \"admissions\", \"subject_id\"),\n )\n ],\n ),\n \">=\",\n \"2012\",\n ),\n ]\n assert analyzer.get_analysis_joins(analysis) == {\n SqlJoin(SqlColumn(\"mimiciii\", \"patients\", \"subject_id\"), SqlColumn(\"mimiciii\", \"admissions\", \"subject_id\")),\n }\n assert analysis.reference_paths == [[\"generalPractitioner\"], [\"link\", \"other\"]]\n\n\ndef test_analyze_attribute(dict_map_gender):\n analyzer = Analyzer()\n analyzer._cur_analysis.primary_key_column = SqlColumn(\"mimiciii\", \"patients\", \"subject_id\")\n\n attribute_mapping = {\n \"id\": \"ck8ooenpu26984kp4wyiz4yc2\",\n \"path\": \"gender\",\n \"sliceName\": None,\n \"definitionId\": \"code\",\n \"resourceId\": \"ck8oo3on226974kp4ns32n7xs\",\n \"comments\": [],\n \"inputGroups\": [\n {\n \"id\": \"ckdom8lgq0045m29ksz6vudvc\",\n \"mergingScript\": None,\n \"attributeId\": \"ck8ooenpu26984kp4wyiz4yc2\",\n \"inputs\": [\n {\n \"id\": \"ck8ooenw826994kp4whpirhdo\",\n \"script\": None,\n \"conceptMapId\": \"id_cm_gender\",\n \"conceptMap\": dict_map_gender,\n \"staticValue\": None,\n \"sqlValueId\": \"ck8ooenw827004kp41nv3kcmq\",\n \"inputGroupId\": \"ckdom8lgq0045m29ksz6vudvc\",\n \"sqlValue\": {\n \"id\": \"ck8ooenw827004kp41nv3kcmq\",\n \"owner\": {\"name\": \"mimiciii\"},\n \"table\": \"patients\",\n \"column\": \"gender\",\n \"joinId\": None,\n \"joins\": [\n {\n \"id\": \"ckdyl65kj0195gu9k43qei6xp\",\n \"columnId\": \"ckdyl65kj0194gu9k6ez7yirb\",\n \"tables\": [\n {\n \"id\": \"ckdyl65kj0196gu9ku2dy0ygg\",\n \"owner\": {\"name\": \"mimiciii\"},\n \"table\": \"patients\",\n \"column\": \"subject_id\",\n \"joinId\": \"ckdyl65kj0195gu9k43qei6xp\",\n },\n {\n \"id\": \"ckdyl65kj0197gu9k1lrvx3bl\",\n \"owner\": {\"name\": \"mimiciii\"},\n \"table\": \"admissions\",\n \"column\": \"subject_id\",\n \"joinId\": \"ckdyl65kj0195gu9k43qei6xp\",\n },\n ],\n }\n ],\n },\n }\n ],\n \"conditions\": [\n {\n \"id\": \"ckdyl65kl0334gu9ky8x57zvb\",\n \"action\": \"EXCLUDE\",\n \"columnId\": \"ckdyl65kl0335gu9kup0hwhe0\",\n \"relation\": \"EQ\",\n \"value\": \"1\",\n \"inputGroupId\": \"ckdyl65kl0331gu9kjada4vf4\",\n \"sqlValue\": {\n \"id\": \"ckdyl65kl0335gu9kup0hwhe0\",\n \"owner\": {\"name\": \"mimiciii\"},\n \"table\": \"admissions\",\n \"column\": \"expire_flag\",\n \"joinId\": \"ckdyl65kj0195gu9k43qei6xq\",\n \"joins\": [\n {\n \"id\": \"ckdyl65kj0195gu9k43qei6xp\",\n \"columnId\": \"ckdyl65kj0194gu9k6ez7yirb\",\n \"tables\": [\n {\n \"id\": \"ckdyl65kj0196gu9ku2dy0ygg\",\n \"owner\": {\"name\": \"mimiciii\"},\n \"table\": \"patients\",\n \"column\": \"subject_id\",\n \"joinId\": \"ckdyl65kj0195gu9k43qei6xp\",\n },\n {\n \"id\": \"ckdyl65kj0197gu9k1lrvx3bl\",\n \"owner\": {\"name\": \"mimiciii\"},\n \"table\": \"join_table\",\n \"column\": \"subject_id\",\n \"joinId\": \"ckdyl65kj0195gu9k43qei6xp\",\n },\n ],\n },\n {\n \"id\": \"ckdyl65kj0195gu9k43qei6xp\",\n \"columnId\": \"ckdyl65kj0194gu9k6ez7yirb\",\n \"tables\": [\n {\n \"id\": \"ckdyl65kj0196gu9ku2dy0ygg\",\n \"owner\": {\"name\": \"mimiciii\"},\n \"table\": \"join_table\",\n \"column\": \"adm_id\",\n \"joinId\": \"ckdyl65kj0195gu9k43qei6xp\",\n },\n {\n \"id\": \"ckdyl65kj0197gu9k1lrvx3bl\",\n \"owner\": {\"name\": \"mimiciii\"},\n \"table\": \"admissions\",\n \"column\": \"adm_id\",\n \"joinId\": \"ckdyl65kj0195gu9k43qei6xp\",\n },\n ],\n },\n ],\n },\n }\n ],\n }\n ],\n }\n\n actual = analyzer.analyze_attribute(attribute_mapping)\n\n expected = Attribute(\"gender\")\n\n group = InputGroup(\n id_=\"ckdom8lgq0045m29ksz6vudvc\",\n attribute=expected,\n conditions=[\n Condition(\n \"EXCLUDE\",\n SqlColumn(\n \"mimiciii\",\n \"admissions\",\n \"expire_flag\",\n joins=[\n SqlJoin(\n SqlColumn(\"mimiciii\", \"patients\", \"subject_id\"),\n SqlColumn(\"mimiciii\", \"join_table\", \"subject_id\"),\n ),\n SqlJoin(\n SqlColumn(\"mimiciii\", \"join_table\", \"adm_id\"),\n SqlColumn(\"mimiciii\", \"admissions\", \"adm_id\"),\n ),\n ],\n ),\n \"EQ\",\n \"1\",\n )\n ],\n columns=[\n SqlColumn(\n \"mimiciii\",\n \"patients\",\n \"gender\",\n joins=[\n SqlJoin(\n SqlColumn(\"mimiciii\", \"patients\", \"subject_id\"),\n SqlColumn(\"mimiciii\", \"admissions\", \"subject_id\"),\n )\n ],\n )\n ],\n static_inputs=[],\n merging_script=None,\n )\n expected.add_input_group(group)\n\n assert actual == expected\n","sub_path":"tests/river/unit/analyzer/test_analyzer.py","file_name":"test_analyzer.py","file_ext":"py","file_size_in_byte":11438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"383710786","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 4 19:26:32 2021\n\n@author: Majoju Krishna Sai Prahlad\n\"\"\"\n\nfrom flask import Flask, jsonify, render_template, request\nimport numpy as np\nimport pickle\nfrom keras.models import load_model\napp = Flask(__name__)\n# model = pickle.load(open('chronic_k_d.pkl', 'rb'))\nmodel = load_model('C_k_d.h5')\n# l=[0.75,\t0.0,\t0.012712,\t0.768707,\t0.666667,\t0.0]\n# a=np.array(l)\n# print(a.shape)\n# pred=(model.predict([[a]]))\n\n\n@app.route('/', methods=['GET'])\ndef home():\n return render_template('index.html')\n\n\n@app.route('/predict', methods=['GET', 'POST'])\ndef predict():\n '''\n For rendering results on HTML GUI\n '''\n if request.method == 'POST':\n\n int_features = [float(x) for x in request.form.values()]\n final_features = [np.array(int_features)]\n print(final_features)\n roi = np.expand_dims(final_features, axis=0)\n prediction = model.predict([roi])\n print(prediction)\n output = \"\"\n if(prediction == 0):\n output = (\"Not a Chronic\")\n else:\n output = (\"Chronic\")\n\n #output = round(prediction[0], 2)\n\n return render_template('index.html', prediction_text='It is {} a Kidney Disease Presence'.format(output))\n return None\n# =============================================================================\n#\n# @app.route('/predict_api',methods=['POST'])\n# def predict_api():\n# '''\n# For direct API calls trought request\n# '''\n# data = request.get_json(force=True)\n# prediction = model.predict([np.array(list(data.values()))])\n#\n# output1=\"\"\n# if(prediction==0):\n# output1=(\"Not a Chronic\")\n# else:\n# output1=(\"Chronic\")\n# return jsonify(output1)\n# =============================================================================\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"430503243","text":"from src.game.entities import Team, Monkey, Queen\nfrom src.game.board import Board\nfrom src.game.geo import Vec2I\nfrom src.game.command import Command\nimport random\n\n\"\"\"\nCode your AI in this file.\n\"\"\"\n\n# Define your persistent variables here\n\n\ndef make_play(board, your_team, last_move):\n \"\"\"\n Your AI entry point. This function gets called every time your AI is asked to make a play.\n The parameters contains all the information you need to picture the game state.\n\n The given lists of entities, queen information, etc... are a deep copy of the current game state, so don't try\n changing values there as this won't impact the game :p\n\n The execution time of this function is taken into account at each move, and a time limit is given to each team.\n\n :param board: the whole game state\n\n :param your_team: your team. Either Team.WHITE or Team.BLACK\n\n :param last_move: a tuple of two Vec2I (Vec2I(x_from, y_from), Vec2I(x_to, y_to)) of your opponent's last move.\n None if you are doing the first game move.\n\n :return: two objects Vec2I, Vec2I. The first object is the position of the piece you want to move, the second\n \"\"\"\n\n # a list containing all the entities from all the teams (either Monkeys or Queens)\n entities = board.get_entities()\n\n # just like entities, but into a map (dictionary). The key is a Vec2I object containing the position where you\n # want to get the entity. Use entity_map.get(Vec2I(x, y)) instead of entity_map[Vec2I(x, y)] if you want to avoid\n # raising a KeyError. Vec2I is used for the positions\n entity_map = board.get_entity_map()\n\n # List all the possible legal moves\n all_possible_moves = board.get_legal_moves(your_team)\n\n # You can iterate over all the entities like so:\n for entity in entities:\n position = entity.get_position()\n team = entity.get_team()\n print('Entity at position {}, is from team {}'.format(position, team))\n\n # You can get other information from the board functions.\n your_queen = board.search_queen(your_team)\n\n # There are only two teams, either Team.WHITE or Team.BLACK\n enemy_team = None\n if your_team == Team.WHITE:\n enemy_team = Team.BLACK\n else:\n enemy_team = Team.WHITE\n\n # you can do the same with this one liner\n enemy_team = Team.WHITE if your_team == Team.BLACK else Team.BLACK\n\n # get the enemy queen info from the board\n enemy_queen = board.search_queen(enemy_team)\n\n # Get the position of an entity, for example, with this queen\n # This can also work with Monkeys\n your_queen_position = enemy_queen.get_position()\n\n # Get the queen stack (number of remaining monkeys)\n your_queen_stack = your_queen.get_stack()\n\n # Print the position information, positions use the object Vec2I, defined in the file src/game/geo.py\n print(your_queen_position.x, your_queen_position.y)\n\n # Get all the possible moves for your queen\n possible_moves = your_queen.get_legal_moves()\n\n # We want to move our queen one cell down\n your_queen_x = your_queen_position.x\n your_queen_y = your_queen_position.y\n\n # Again, the game uses the Vec2I object for the positions\n new_position = Vec2I(your_queen_x, your_queen_y + 1)\n\n # As the board is a DEEP COPY of the real board, you can use it to forecast the future, for example, if you\n # want to list all your enemy moves after the move you want to select\n\n # As said, you have to return a tuple of Vec2I from this function, but to make a play you have to put those\n # two Vec2I in a Command object\n move_command = Command(your_queen_position, new_position)\n\n # Make a copy of the current game state\n current_board = board.copy_state()\n\n # Plays the command, now the board is just like you have played your decised move\n board.make_play(move_command)\n\n # Forecast all the legal moves from your opponent\n opponent_possible_responses = board.get_legal_moves()\n\n # We check if the new position is a legal move\n if new_position in possible_moves:\n # We make this play by returning the new_position\n return your_queen_position, new_position\n else:\n new_position = random.choice(possible_moves)\n return your_queen_position, new_position\n","sub_path":"src/ai/my_ai.py","file_name":"my_ai.py","file_ext":"py","file_size_in_byte":4265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"188146827","text":"# -*- coding: utf-8 -*-\r\nfrom odoo import models, fields, api, _, exceptions\r\n\r\n\r\nclass EmcsLine(models.Model):\r\n _name = \"emcs.line\"\r\n _order = \"excise_type_id, excise_code_id\"\r\n\r\n purchase_order_id = fields.Many2one('purchase.order')\r\n product_id = fields.Many2one('product.template', string=\"Product\")\r\n excise_type_id = fields.Many2one('drink.excise.type', string=\"Excise Type\")\r\n excise_code_id = fields.Many2one('drink.excise.code', string=\"Excise Code\")\r\n excise_code_code = fields.Char(related=\"excise_code_id.code\")\r\n excise_code_desc = fields.Char(related=\"excise_code_id.name\")\r\n delivered_volume = fields.Float(digits=(12,3))\r\n delivered_qty = fields.Float(string=\"Delivered Quantity\")\r\n gross_weight = fields.Float()\r\n net_weight = fields.Float()\r\n average_alcohol_degree = fields.Float()","sub_path":"vertical_drink/models/emcs_line.py","file_name":"emcs_line.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"33874111","text":"from dual_mc33926_rpi import motors, MAX_SPEED\r\nimport pygame\r\nimport wiringpi\r\n\r\n\"\"\"\r\nDS4 Controller axis maps:\r\nAxis0: Left stick l-r (-1 left, 1 right)\r\nAxis1: Left stick u-d (-1 up, ` 1 down)\r\nAxis2: Left Trigger (-1 unpressed, 1 completely pressed)\r\nAxis3: Right stick l-r (-1 left, 1 right)\r\nAxis4: Right stick u-d (-1 up, 1 down)\r\nAxis5: Right trigger (-1 unpressed, 1 completely pressed)\r\n\"\"\"\r\n\r\n#Defines for button numbers\r\nBUTTON_SQUARE = 3\r\nBUTTON_CROSS = 0\r\nBUTTON_CIRCLE = 1\r\nBUTTON_TRIANGLE = 2\r\nBUTTON_L1 = 4\r\nBUTTON_R1 = 5\r\nBUTTON_L2 = 6\r\nBUTTON_R2 = 7\r\nBUTTON_SHARE = 8\r\nBUTTON_OPTIONS = 9\r\nBUTTON_LEFT_STICK = 11\r\nBUTTON_RIGHT_STICK = 12\r\nBUTTON_PS = 10\r\nBUTTON_BUTTON_PAD = 13\r\n\r\n#Defines for analog inputs\r\nLStickHorz \t= 0\r\nLStickVert \t= 1\r\nLTrigg \t\t= 2\r\nRStickHorz \t= 3\r\nRStickVert \t= 4\r\nRTrigg \t\t= 5\r\n\r\ndef Init_Controller():\r\n screen = pygame.display.set_mode([50,50])\r\n pygame.joystick.init() # find the joysticks\r\n controller = pygame.joystick.Joystick(0)\r\n controller.init()\r\n assert controller.get_init()\r\n# print(controller.get_numbuttons())\r\n #print(controller)\r\n return controller\r\n\r\n\r\ndef Init_Drive_ESC():\r\n global l_drive\r\n l_drive = 0\r\n global r_drive\r\n r_drive = 0\r\n wiringpi.wiringPiSetup()\r\n global Motor1PWM\r\n Motor1PWM = 1 # gpio pin 12 = wiringpi no 1 (BCM 18)\r\n global Motor1AIN1\r\n Motor1AIN1 = 4 # gpio pin 16 = wiringpi no. 4 (BCM 23)\r\n global Motor1AIN2\r\n Motor1AIN2 = 5 # gpio pin 18 = wiringpi no. 5 (BCM 24)\r\n global MotorStandby\r\n MotorStandby = 6 # gpio pin 22 = wiringpi no. 6 (BCM 25)\r\n global Motor2PWM\r\n Motor2PWM = 23 # gpio pin 33 = wiringpi no. 23 (BCM 13)\r\n global Motor2AIN1\r\n Motor2AIN1 = 21 # gpio pin 29 = wiringpi no. 21 (BCM 5)\r\n global Motor2AIN2\r\n Motor2AIN2 = 22 # gpio pin 31 = wiringpi no. 22 (BCM 6)\r\n\r\n wiringpi.pinMode(Motor1PWM, 2) \t# PWM mode\r\n wiringpi.pinMode(Motor1AIN1, \t 1) \t# Digital out mode\r\n wiringpi.pinMode(Motor1AIN2, \t 1) \t# Digital out mode\r\n # wiringpi.pinMode(MotorStandby, \t 1) \t# Ditial out mode\r\n wiringpi.pinMode(Motor2PWM, \t 2) # PWM mode\r\n wiringpi.pinMode(Motor2AIN1, 1) \t# Digital out mode\r\n wiringpi.pinMode(Motor2AIN2, 1) \t# Digital out mode\r\n\r\n\r\ndef Normalize(minimum, maximum, value):\r\n num = value - minimum\r\n den = maximum - minimum\r\n return num / den\r\n\r\n\r\ndef Get_Trigg_Vals(controller):\r\n LEFT_Trigg = -controller.get_axis(2)\r\n RIGHT_Trigg = -controller.get_axis(5)\r\n# print(\"Leftdrive: \", LEFT_Trigg, \" Rightdrive: \", RIGHT_Trigg, end='\\r')\r\n return LEFT_Trigg, RIGHT_Trigg\r\n\r\ndef Get_Stick_Vals(controller):\r\n Left_Vert = -controller.get_axis(LStickVert)\r\n Left_Horz = -controller.get_axis(LStickHorz)\r\n Right_Vert = -controller.get_axis(RStickVert)\r\n Right_Horz = -controller.get_axis(RStickHorz)\r\n# print(\"LVert: \", Left_Vert, \" LHorz: \", Left_Horz, \" RVert: \", Right_Vert, \" RHorz: \", Right_Horz, \" \", end='\\r')\r\n return Left_Vert, Left_Horz, Right_Vert, Right_Horz\r\n\r\ndef Send_Drive_Commands(cont):\r\n for event in pygame.event.get():\r\n button = True\r\n #if event.type == pygame.JOYBUTTONDOWN:\r\n # button = True\r\n #if event.type == pygame.JOYBUTTONUP:\r\n # button = False\r\n \r\n ltrigg, rtrigg = Get_Trigg_Vals(cont) \r\n #l_drive = ltrigg\r\n #r_drive = rtrigg\r\n #l_drive, r_drive = Get_Trigg_Vals(cont)\r\n lvert, lhorz, rvert, rhorz = Get_Stick_Vals(cont)\r\n print(\"LTrig: \", round(ltrigg,2), \" RTrig: \", round(rtrigg,2), \" LVert: \", round(lvert,2), \" LHorz: \", round(lhorz,2), \" RVert: \", round(rvert,2), \" RHorz: \", round(rhorz,2), \" \", end='\\r')\r\n# print(\"Leftstick: \", l_drive, \" Rightstick: \", r_drive, \" \", end='\\r')\r\n if l_drive < 0:\r\n scaled_l = l_drive * -480\r\n wiringpi.pwmWrite(Motor1PWM, scaled_l)\r\n wiringpi.digitalWrite(Motor1AIN1, 1)\r\n wiringpi.digitalWrite(Motor1AIN2, 0)\r\n elif l_drive > 0:\r\n scaled_l = l_drive * 480\r\n wiringpi.pwmWrite(Motor1PWM, scaled_l)\r\n wiringpi.digitalWrite(Motor1AIN1, 1)\r\n wiringpi.digitalWrite(Motor1AIN2, 0)\r\n elif l_drive == 0:\r\n scaled_l = 0\r\n wiringpi.pwmWrite(Motor1PWM, scaled_l)\r\n wiringpi.digitalWrite(Motor1AIN1, 1)\r\n wiringpi.digitalWrite(Motor1AIN2, 0)\r\n\r\n if r_drive < 0:\r\n scaled_r = r_drive * -480\r\n wiringpi.pwmWrite(Motor2PWM, scaled_r)\r\n wiringpi.digitalWrite(Motor2AIN1, 0)\r\n wiringpi.digitalWrite(Motor2AIN2, 1)\r\n elif r_drive > 0:\r\n scaled_r = r_stick * 480\r\n wiringpi.pwmWrite(Motor2PWM, scaled_r)\r\n wiringpi.digitalWrite(Motor2AIN1, 0)\r\n wiringpi.digitalWrite(Motor2AIN2, 1)\r\n elif r_drive == 0:\r\n scaled_r = 0\r\n wiringpi.pwmWrite(Motor2PWM, scaled_r)\r\n wiringpi.digitalWrite(Motor2AIN1, 0)\r\n wiringpi.digitalWrite(Motor2AIN2, 1)\r\n\r\n wiringpi.digitalWrite(MotorStandby, 0)\r\n\r\nprint(\"Running\")\r\ncont = Init_Controller()\r\nInit_Drive_ESC()\r\nwhile True:\r\n#Get_Stick_Vals(cont)\r\n Send_Drive_Commands(cont)\r\n","sub_path":"dual-mc33926-motor-driver-rpi/drive_code.py","file_name":"drive_code.py","file_ext":"py","file_size_in_byte":5299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"443089595","text":"#主成分降维\r\n\"\"\"\r\n第一次修改内容:\r\n 代码规范化\r\n 矩阵乘法规范化\r\n\"\"\"\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\ndef PCA(X):\r\n\tX = np.mat(X)\r\n\t#求数据矩阵X的样本协方差矩阵\r\n\ts = np.cov(X.T)\r\n\t#求样本协方差矩阵的特征值与特征向量\r\n\t#a是特征值矩阵,b是经过正交标准化的特征向量矩阵\r\n\ta,b = np.linalg.eig(s)\r\n\t#调整a使得特征值从小到大排列,同时b也改变\r\n\ta_sort,b_sort = sort(a,b)\r\n\t#系数矩阵\r\n\tA = b_sort.T\r\n\t#主成分矩阵\r\n\t#Y = A*X.T\r\n\tY = np.dot(A,X.T)\r\n\ta_cc = cumulative_contribution(a)\r\n\t#依次返回主成分矩阵,系数矩阵,特征值矩阵,累计贡献度矩阵\r\n\treturn Y.T,A,a_sort,a_cc\r\n\r\n#调整特征值矩阵a使得特征值从小到大排列,同时特征向量矩阵b也改变\r\ndef sort(a,b):\r\n\tt = np.vstack((a,b))\r\n\t#矩阵的行数与列数\r\n\tsize_r,size_c = t.shape\r\n\trecord = np.zeros((size_r,1))\r\n\t#排序\r\n\tfor i in range(size_c):\r\n\t\tfor j in range(i,size_c-1):\r\n\t\t\tif t[0,i] < t[0,j+1]:\r\n\t\t\t\trecord = 1*t[:,i]\r\n\t\t\t\tt[:,i] = t[:,j+1]\r\n\t\t\t\tt[:,j+1] = record\r\n\ta_sort = t[0,:]\r\n\tb_sort = t[1:,:]\r\n\treturn a_sort,b_sort\r\n\r\n#计算累计贡献度\r\ndef cumulative_contribution(a):\r\n\ta = np.abs(a)\r\n\ta_all = 0\r\n\tfor i in range(len(a)):\r\n\t\ta_all = a_all + a[i]\r\n\tfor i in range(len(a)):\r\n\t\tif i == 0:\r\n\t\t\ta[i] = a[i] / a_all\r\n\t\telse:\r\n\t\t\ta[i] = a[i - 1] + (a[i] / a_all)\r\n\treturn a\r\n\r\n\r\n","sub_path":"幸福感预测/PCA.py","file_name":"PCA.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"529315707","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\nclass SmPlusPlus(nn.Module):\n def __init__(self, config):\n super(SmPlusPlus, self).__init__()\n output_channel = config.output_channel\n questions_num = config.questions_num\n answers_num = config.answers_num\n words_dim = config.words_dim\n filter_width = config.filter_width\n self.mode = config.mode\n\n n_classes = config.target_class\n ext_feats_size = 4\n\n if self.mode == 'multichannel':\n input_channel = 2\n else:\n input_channel = 1\n\n self.question_embed = nn.Embedding(questions_num, words_dim)\n self.answer_embed = nn.Embedding(answers_num, words_dim)\n self.static_question_embed = nn.Embedding(questions_num, words_dim)\n self.nonstatic_question_embed = nn.Embedding(questions_num, words_dim)\n self.static_answer_embed = nn.Embedding(answers_num, words_dim)\n self.nonstatic_answer_embed = nn.Embedding(answers_num, words_dim)\n self.static_question_embed.weight.requires_grad = False\n self.static_answer_embed.weight.requires_grad = False\n\n self.conv_q = nn.Conv2d(input_channel, output_channel, (filter_width, words_dim), padding=(filter_width - 1, 0))\n self.conv_a = nn.Conv2d(input_channel, output_channel, (filter_width, words_dim), padding=(filter_width - 1, 0))\n self.conv_qa = nn.Conv2d(2, output_channel, (filter_width, words_dim), padding=(7, 0))\n\n self.dropout = nn.Dropout(config.dropout)\n n_hidden = 3 * output_channel + ext_feats_size\n\n self.combined_feature_vector = nn.Linear(n_hidden, n_hidden)\n self.hidden = nn.Linear(n_hidden, n_classes)\n\n def forward(self, x):\n x_question = x.question\n x_answer = x.answer\n x_ext = x.ext_feat\n\n if self.mode == 'rand':\n question = self.question_embed(x_question).unsqueeze(1)\n answer = self.answer_embed(x_answer).unsqueeze(1) # (batch, sent_len, embed_dim)\n x = [F.tanh(self.conv_q(question)).squeeze(3), F.tanh(self.conv_a(answer)).squeeze(3)]\n x = [F.max_pool1d(i, i.size(2)).squeeze(2) for i in x] # max-over-time pooling\n # actual SM model mode (Severyn & Moschitti, 2015)\n elif self.mode == 'static':\n question = self.static_question_embed(x_question).unsqueeze(1)\n answer = self.static_answer_embed(x_answer).unsqueeze(1) # (batch, sent_len, embed_dim)\n padding = Variable(torch.zeros(answer.size(0), answer.size(1), answer.size(2) - question.size(2), answer.size(3)))\n padded_question = torch.cat([question, padding], 2)\n qa_combined = torch.stack([padded_question, answer], dim=1).squeeze(2)\n x = [F.tanh(self.conv_q(question)).squeeze(3), F.tanh(self.conv_a(answer)).squeeze(3), F.tanh(self.conv_qa(qa_combined)).squeeze(3)]\n x = [F.max_pool1d(i, i.size(2)).squeeze(2) for i in x] # max-over-time pooling\n elif self.mode == 'non-static':\n question = self.nonstatic_question_embed(x_question).unsqueeze(1)\n answer = self.nonstatic_answer_embed(x_answer).unsqueeze(1) # (batch, sent_len, embed_dim)\n padding = Variable(torch.zeros(answer.size(0), answer.size(1), answer.size(2) - question.size(2), answer.size(3)))\n padded_question = torch.cat([question, padding], 2)\n qa_combined = torch.stack([padded_question, answer], dim=1).squeeze(2)\n x = [F.tanh(self.conv_q(question)).squeeze(3), F.tanh(self.conv_a(answer)).squeeze(3), F.tanh(self.conv_qa(qa_combined)).squeeze(3)]\n x = [F.max_pool1d(i, i.size(2)).squeeze(2) for i in x] # max-over-time pooling\n elif self.mode == 'multichannel':\n question_static = self.static_question_embed(x_question)\n answer_static = self.static_answer_embed(x_answer)\n question_nonstatic = self.nonstatic_question_embed(x_question)\n answer_nonstatic = self.nonstatic_answer_embed(x_answer)\n question = torch.stack([question_static, question_nonstatic], dim=1)\n answer = torch.stack([answer_static, answer_nonstatic], dim=1)\n\n question_comb_static = self.static_question_embed(x_question).unsqueeze(1)\n answer_comb_static = self.static_answer_embed(x_answer).unsqueeze(1) # (batch, sent_len, embed_dim)\n padding = Variable(torch.zeros(answer_comb_static.size(0), answer_comb_static.size(1),\n answer_comb_static.size(2) - question_comb_static.size(2), answer_comb_static.size(3)))\n padded_question_static = torch.cat([question_comb_static, padding], 2)\n qa_combined_static = torch.stack([padded_question_static, answer_comb_static], dim=1).squeeze(2)\n\n # question_comb = self.nonstatic_question_embed(x_question).unsqueeze(1)\n # answer_comb = self.nonstatic_answer_embed(x_answer).unsqueeze(1) # (batch, sent_len, embed_dim)\n # padding = Variable(torch.zeros(answer_comb.size(0), answer_comb.size(1), answer_comb.size(2)\n # - question_comb.size(2), answer_comb.size(3)))\n # padded_question = torch.cat([question_comb, padding], 2)\n # qa_combined_nonstatic = torch.stack([padded_question, answer_comb], dim=1).squeeze(2)\n # print(qa_combined_static.size(), qa_combined_nonstatic.static())\n # qa_multichannel = torch.stack([qa_combined_static, qa_combined_nonstatic], dim=1).squeeze(2)\n # print(qa_multichannel.size())\n\n x = [F.tanh(self.conv_q(question)).squeeze(3), F.tanh(self.conv_a(answer)).squeeze(3),\n F.tanh(self.conv_qa(qa_combined_static)).squeeze(3)]\n x = [F.max_pool1d(i, i.size(2)).squeeze(2) for i in x] # max-over-time pooling\n else:\n print(\"Unsupported Mode\")\n exit()\n\n # append external features and feed to fc\n x.append(x_ext)\n x = torch.cat(x, 1)\n\n x = F.tanh(self.combined_feature_vector(x))\n x = self.dropout(x)\n x = self.hidden(x)\n return x","sub_path":"sm_modified_cnn/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":6232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"401598464","text":"class Solution(object):\n def repeatedSubstringPattern(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n kmp=[0]*len(s)\n \n for i in range(1, len(s)):\n j=kmp[i-1] #for suffix\n \n while j>0 and s[i]!=s[j]:\n j=kmp[j-1]\n \n if s[i]==s[j]: #prefix and suffix match\n j+=1\n \n kmp[i]=j \n\n p=kmp[len(s)-1]\n \n return p!=0 and len(s)%(len(s)-p)==0 # check if it's repeated pattern string\n \n \n# Time complexity: O(N). During the execution, j could be decreased at most N times and then increased at most N times, that makes overall execution time to be linear O(N).\n\n# Space complexity: O(N) to keep the lookup table.\n","sub_path":"RepeatedSubstringPattern.py","file_name":"RepeatedSubstringPattern.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"29948308","text":"from common.commons import *\nDATA_PATH = os.environ[\"DATA_PATH\"]\nPROJECT_TYPE = os.environ[\"PROJECT_TYPE\"]\n\n\ndef bStats():\n if isfile(join(DATA_PATH, 'studyBugReports.pickle')):\n studyBugReports = load_zipped_pickle(join(DATA_PATH, 'studyBugReports.pickle'))\n else:\n brs = load_zipped_pickle(join(DATA_PATH, args.subject + \"bugReportsComplete.pickle\"))\n commits = load_zipped_pickle(join(DATA_PATH, 'singleBR.pickle'))\n\n dbDir = join(DATA_PATH, 'redis')\n\n portInner = '6399'\n startDB(dbDir, portInner, PROJECT_TYPE)\n\n import redis\n\n redis_db = redis.StrictRedis(host=\"localhost\", port=portInner, db=0)\n keys = redis_db.scan(0, match='*', count='1000000')\n\n matches = pd.DataFrame(keys[1], columns=['pairs_key'])\n\n # matches = load_zipped_pickle(join(DATA_PATH,'singleHunks'))\n matches['pairs_key'] = matches['pairs_key'].apply(lambda x: x.decode())\n matches['root'] = matches['pairs_key'].apply(lambda x: x.split('/')[0])\n matches['size'] = matches['pairs_key'].apply(lambda x: x.split('/')[1])\n matches['file'] = matches['pairs_key'].apply(lambda x: x.split('/')[2])\n matches['repo'] = matches['file'].apply(lambda x: x.split('_')[0])\n matches['commit'] = matches['file'].apply(lambda x: x.split('_')[1])\n\n subjects = pd.read_csv(join(DATA_PATH, 'subjects.csv'))\n\n def getBID(x):\n try:\n if x['repo'].endswith('.git'):\n return None\n subject = subjects.query(\"Repo == '{0}'\".format(x['repo'])).Subject.tolist()[0]\n bids = commits.query(\n \"commit.str.startswith('{0}') and project== '{1}'\".format(x['commit'], subject)).bid.tolist()\n return bids[0]\n except Exception as e:\n logging.error(e)\n\n matches = matches[~matches.repo.apply(\n lambda i: (i.startswith('commons-math') or i.startswith('commons-lang') or i.startswith(\n 'closure-compiler') or i.startswith('joda-time') or i.startswith('mockito') or i.startswith(\n 'jfreechart')))]\n matches['bid'] = matches.apply(lambda x: getBID(x), axis=1)\n\n subjects\n # res = pd.merge(matches, brs, on=['bid'])\n save_zipped_pickle(matches, join(DATA_PATH, 'studyDataset.pickle'))\n studyBugReports = brs[brs.bid.isin(matches.bid.unique())]\n save_zipped_pickle(studyBugReports, join(DATA_PATH, 'studyBugReports.pickle'))\n if isfile(join(DATA_PATH, 'studyBR_DTM_index')):\n brIndexes = load_zipped_pickle(join(DATA_PATH, 'studyBR_DTM_index'))\n bugDTM = load_zipped_pickle(join(DATA_PATH, 'studyBR_DTM'))\n vectorDF = load_zipped_pickle(join(DATA_PATH, 'studyBR_vector'))\n matches = load_zipped_pickle(join(DATA_PATH, 'studyDataset.pickle'))\n else:\n studyBugReports['description'] = studyBugReports['description'].fillna(\"\")\n studyBugReports['sumDesc'] = studyBugReports['summary'] + studyBugReports['description']\n # corpus['sumDesc'] = corpus['summary'] + corpus['desc']\n # from common.preprocessing import\n # result, aVector = getVectorAndDtm(corpus, 'summary')\n from common.preprocessing import calculateTfIdfNLList\n\n corpusBug = studyBugReports['sumDesc'].values.tolist()\n from common.preprocessing import preprocessingNL\n\n preCorpusBug = list(map(preprocessingNL, corpusBug))\n\n v = calculateTfIdfNLList(preCorpusBug)\n bugDTM = v.transform(preCorpusBug)\n bugDTM\n save_zipped_pickle(bugDTM, join(DATA_PATH, 'studyBR_DTM'))\n brIndexes = studyBugReports['bid'].values.tolist()\n\n save_zipped_pickle(brIndexes, join(DATA_PATH, 'studyBR_DTM_index'))\n # from sklearn.metrics.pairwise import cosine_similarity\n # cosine_similarity(bugDTM[11701], bugDTM[11111])\n vectorDF = pd.DataFrame(columns=['bid', 'dtm'])\n # idx = 0\n for idx, val in enumerate(brIndexes):\n vectorDF.loc[idx] = [val, bugDTM[idx]]\n vectorDF\n\n save_zipped_pickle(vectorDF, join(DATA_PATH, 'studyBR_vector'))\n\n matches\n if isfile(join(DATA_PATH, 'study_clusters')):\n clustersDF = load_zipped_pickle(join(DATA_PATH, 'study_clusters'))\n else:\n clustersDF = pd.DataFrame(columns=['cid', 'type', 'members'])\n idx = 0\n\n def statsCore(cs, type):\n global idx\n\n cs = [i for i in cs if not (i.startswith('commons-math') or i.startswith('commons-lang') or i.startswith(\n 'closure-compiler') or i.startswith('joda-time') or i.startswith('mockito') or i.startswith(\n 'jfreechart'))]\n # print('Cluster %s : member size %s' % (shape+\"-\"+size +\"-\"+cluster, len(cs)))\n if len(cs) > 0:\n if token is None:\n if action is None:\n t = shape + \"-\" + size + \"-\" + cluster\n\n clustersDF.loc[idx] = [t, type, cs]\n idx = idx + 1\n else:\n t = shape + \"-\" + size + \"-\" + cluster + \"-\" + action # , len(cs)\n clustersDF.loc[idx] = [t, type, cs]\n idx = idx + 1\n else:\n # clusterSize = len(cs)\n # if clusterSize > 0:\n # clusterSize = len(set([re.split('.txt_[0-9]+', i)[0] for i in cs]))\n t = shape + \"-\" + size + \"-\" + cluster + \"-\" + action + \"-\" + token # , clusterSize\n clustersDF.loc[idx] = [t, type, cs]\n idx = idx + 1\n\n for type in ['tokens', 'actions', 'shapes']:\n shapesPath = join(DATA_PATH, type)\n shapes = listdir(shapesPath)\n shapes = [f for f in shapes if isdir(join(shapesPath, f))]\n shape = size = cluster = action = token = None\n\n for shape in shapes:\n if shape.startswith('.'):\n continue\n sizes = listdir(join(shapesPath, shape))\n\n for size in sizes:\n if size.startswith('.'):\n continue\n clusters = listdir(join(shapesPath, shape, size))\n for cluster in clusters:\n if cluster.startswith('.'):\n continue\n cs = listdir(join(shapesPath, shape, size, cluster))\n\n if shapesPath.endswith('shapes'):\n cs = listdir(join(shapesPath, shape, size, cluster))\n statsCore(cs, 'shapes')\n else:\n # level3\n for action in cs:\n if action.startswith('.'):\n continue\n tokens = listdir(join(shapesPath, shape, size, cluster, action))\n if shapesPath.endswith('actions'):\n statsCore(tokens, 'actions')\n else:\n for token in tokens:\n if token.startswith('.'):\n continue\n cs = listdir(join(shapesPath, shape, size, cluster, action, token))\n statsCore(cs, 'tokens')\n\n clustersDF\n save_zipped_pickle(clustersDF, join(DATA_PATH, 'study_clusters'))\n clustersDF\n\n # selected = clustersDF[clustersDF.type =='shapes']\n\n from sklearn.metrics.pairwise import cosine_similarity\n # cosine_similarity(bugDTM[11701], bugDTM[11111])\n def getSimilarity(x):\n try:\n if len(x) == 1:\n return [1]\n else:\n filenames = list(set([re.split('.txt_[0-9]+', i)[0] for i in x]))\n if len(filenames) == 1:\n return [1]\n else:\n bids2Compare = [matches[matches.file.str.startswith(fn)].bid.unique()[0] for fn in filenames]\n\n pairs = list(itertools.combinations(bids2Compare, 2))\n pairs\n res = []\n for p in pairs:\n p\n simi = cosine_similarity(vectorDF[vectorDF.bid == p[0]].iloc[0].dtm,\n vectorDF[vectorDF.bid == p[1]].iloc[0].dtm)\n res.append(simi[0][0])\n return res\n except Exception as e:\n logging.error(e)\n\n # import swifter\n clustersDF['simi'] = clustersDF.members.apply(lambda x: getSimilarity(x))\n save_zipped_pickle(clustersDF, join(DATA_PATH, 'study_clusters'))\n\n clustersDF\n\n shapes = clustersDF[clustersDF.type == 'shapes']\n actions = clustersDF[clustersDF.type == 'actions']\n tokens = clustersDF[clustersDF.type == 'tokens']\n\n # shapes\n # yList = [list(itertools.chain.from_iterable(shapes.simi.values.tolist())),\n # list(itertools.chain.from_iterable(actions.simi.values.tolist())),\n # list(itertools.chain.from_iterable(tokens.simi.values.tolist()))]\n # colNames = ['shapes','actions','tokens']\n\n ys = []\n cols = []\n means = []\n # plotBox(yList, colNames, 'bugReport' + '.pdf', True)\n for ds in [shapes, actions, tokens]:\n ds['ms'] = ds.members.str.len()\n ds.sort_values(by=['ms'], ascending=False, inplace=True)\n top10 = ds.head(20)\n\n colNames = top10.cid.values.tolist()\n # colNames = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]\n colNames = list(range(len(colNames)))\n yList = yList = top10.simi.values.tolist()\n # yList = [np.mean(i) for i in yList]\n # colNames.insert(0,'ALL')\n # yList.insert(0,list(itertools.chain.from_iterable(ds.simi.values.tolist())))\n mean = np.mean(list(itertools.chain.from_iterable(ds.simi.values.tolist())))\n type = ds.type.iloc[0]\n # from common.commons import plotBox\n # plotBox(yList,colNames,type+'.pdf',False)\n ys.append(yList)\n cols.append(colNames)\n means.append(mean)\n plotBox2(ys, cols, 'test.pdf', means, False)\n","sub_path":"python/bugstats.py","file_name":"bugstats.py","file_ext":"py","file_size_in_byte":10485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"375895461","text":"import numpy as np\ndef RandomMotifs(Dna, k, t):\n import random\n return [text[random.randint(0,len(text)-k):][0:k] for text in Dna]\n\ndef Consensus(Motifs):\n count,k = CountWithPseudocounts(Motifs)\n consensus = \"\"\n for j in range(k):\n m = 0\n frequentSymbol = \"\"\n for symbol in \"ACGT\":\n if count[symbol][j] > m:\n m = count[symbol][j]\n frequentSymbol = symbol\n consensus += frequentSymbol\n return consensus\n\ndef Entropy(Motifs):\n ()\ndef Score(Motifs):\n count,k = CountWithPseudocounts(Motifs)\n median_motif = Consensus(Motifs)\n score = 0;\n #print(count)\n for i in range(k):\n for j in 'ACGT':\n if j != median_motif[i]:\n score += count[j][i]\n return score\n\ndef Pr(Text, Profile):\n prob = 1\n for i in range(len(Text)):\n prob *= Profile[Text[i]][i]\n return prob\n\ndef CountWithPseudocounts(Motifs): # Count Parallel Motifs Content (get Median)\n count = {} # initializing the count dictionary\n k = len(Motifs[0]); t = len(Motifs);\n for symbol in \"ACGT\":\n count[symbol] = []\n count[symbol] = list(np.ones(k,dtype = 'int'))\n for i in range(t):\n for j in range(k):\n symbol = Motifs[i][j]\n count[symbol][j] += 1\n return count, k\n\nimport math as m\ndef ProfileWithPseudocounts(Motifs):\n count, k = CountWithPseudocounts(Motifs)\n num_seq = len(Motifs)+4; entropy = 0;\n for i in range(k):\n for j in 'ACGT':\n count[j][i] = float((float(count[j][i])/float(num_seq)))\n f = max(count[j][i] for j in 'ACGT')\n entropy += -f*m.log(f)\n return count, entropy\n\n\ndef ProfileMostProbableKmer(Text, k, Profile):\n probs = []; topprobs_seq = [];\n for i in range(len(Text)-k+1):\n probs.append(Pr(Text[i:i+k],Profile))\n #print(probs)\n for j in range(len(probs)):\n if probs[j] == max(probs):\n topprobs_seq=Text[j:j+k]\n #print(max(probs))\n #topprob_index = probs.index(topprob)\n if max(probs) == 0:\n topprobs_seq = Text[0:k]\n return topprobs_seq\n\ndef Motifs(Profile, Dna,k):\n motifs = []\n for i in range(len(Dna)):\n mot = ProfileMostProbableKmer(Dna[i],k,Profile);\n motifs.append(mot)\n return motifs\n\n#### N is the number of reiteration\ndef RandomizedMotifSearch(Dna, k_iter, N):\n k_bestmotifs = []; k_scores = []; k_entropy = [];\n for k in range(2, k_iter):\n t = len(Dna); M = RandomMotifs(Dna, k, t); BestMotifs = M\n for i in range(N):\n Motifprofile, entropy = ProfileWithPseudocounts(M)\n #print(Profile)\n M = Motifs(Motifprofile, Dna,k);\n this_score = Score(M)\n if this_score < Score(BestMotifs):\n BestMotifs = M\n BestP, Bestentropy = Motifprofile, entropy\n k_bestmotifs.append(BestMotifs)\n k_scores.append(this_score / k)\n k_entropy.append(Bestentropy / k)\n return k_bestmotifs, k_scores, k_entropy\n\n################ Gibb's\ndef GreedyMotifSearchWithPseudocounts(Dna, k_iter):\n k_bestmotifs = []; k_scores = []; k_entropy = [];\n for k in range(2, k_iter):\n t = len(Dna); BestMotifs = []; loop_scores = [];\n for i in range(0, len(Dna)):\n BestMotifs.append(Dna[i][0:k])\n\n for i in range(len(Dna[0]) - k + 1):\n Motifs = []\n Motifs.append(Dna[0][i:i + k])\n # print(Motifs)\n for j in range(1, len(Dna)):\n P, entropy = ProfileWithPseudocounts(Motifs[0:j])\n Motifs.append(ProfileMostProbableKmer(Dna[j], k, P))\n # print(Motifs)\n this_score = Score(Motifs)\n if this_score < Score(BestMotifs):\n BestMotifs = Motifs\n loop_scores.append(this_score)\n BestP, entropy = P, entropy\n k_bestmotifs.append(BestMotifs)\n k_scores.append(loop_scores[-1]/k)\n k_entropy.append(entropy/k)\n return k_bestmotifs, k_scores, k_entropy\n\nDna = ['CGCCCCTCTCGGGGGTGTTCAGTAAACGGCCA','GGGCGAGGTATGTGTAAGTGCCAAGGTGCCAG',\n 'TAGTACCGAGACCGAAAGAAGTATACAGGCGT','TAGATCAAGTTTCAGGTGCACGTCGGTGAACC',\n 'AATCCACCAGCTCCACGTGCAATGTTGGCCTA']\n\n\nimport ast\ndef entry_processor(Dna_entry, k_entry, N_entry): ### take .entry as input\n Dna_disp = str(Dna_entry.get());\n seq = ast.literal_eval(Dna_disp); # seq = [n.strip() for n in seq_list];\n k = int(k_entry.get());\n if not N_entry.get(): N = 100;\n else: N = int(N_entry.get());\n return [seq, k, N]\n\n############################################### GUI\ndef display_motif_Random():\n [seq, k, N] = entry_processor(Dna_entry, k_entry,N_entry);\n k_bestmotifs, k_scores, k_entropy = RandomizedMotifSearch(seq,k,N)\n T.insert(END, 'Motifs:\\n '+str(k_bestmotifs)+ '\\n\\nScores:\\n '+str(k_scores)+\n '\\n\\nEntropy:\\n '+str(k_entropy)+'\\n')\n Status_done()\n\ndef display_motif_Gibbs():\n [seq, k, N] = entry_processor(Dna_entry, k_entry,N_entry);\n k_bestmotifs, k_scores, k_entropy = GibbsSampler(seq, k, N)\n T.insert(END, 'Motifs:\\n '+str(k_bestmotifs)+ '\\n\\nScores:\\n '+str(k_scores)+\n '\\n\\nEntropy:\\n '+str(k_entropy)+'\\n')\n Status_done()\n\ndef display_motif_Greedy():\n seq, k,_ = entry_processor(Dna_entry, k_entry,N_entry);\n k_bestmotifs, k_scores, k_entropy = GreedyMotifSearchWithPseudocounts(seq, k)\n T.insert(END, 'Motifs:\\n '+str(k_bestmotifs)+ '\\n\\nScores:\\n '+str(k_scores)+\n '\\n\\nEntropy:\\n '+str(k_entropy)+'\\n')\n Status_done()\n\n###################################################### GUI\n##################### Entry\nfrom tkinter import *\nroot = Tk()\nroot.geometry(\"800x700\"); root.title('Holy Moti');\nroot.iconbitmap(r\"C:\\Users\\mailb\\PycharmProjects\\Motif Search Function\\apta_index_tn_13c_icon.ico\")\nLabel(root, text= \"Sequence: (Format: List)\").grid(row=0); Dna_entry = Entry(root);\nDna_entry.bind(\"\");Dna_entry.grid(row = 0, column = 1);\n\nLabel(root, text= \"Target Motif Length\").grid(row=1);k_entry = Entry(root);\nk_entry.bind(\"\"); k_entry.grid(row = 1, column = 1);\n\nLabel(root, text= \"No. of Reiteration (optional)\").grid(row=2); N_entry = Entry(root);\nN_entry.bind(\"\"); N_entry.grid(row = 2, column = 1);\n\n##################### Buttons\nframe1 = Frame(root); frame1.grid(row = 4, column = 0);\ncompute_button1 = Button(frame1, text = 'Randomized\\nMotif Search', width = 15, height = 2, fg = 'blue',\n command = lambda:Status_running(1));\ncompute_button1.pack(side = LEFT);\n\nframe2 = Frame(root); frame2.grid(row = 4, column = 1);\ncompute_button2 = Button(frame2, text = 'Gibb''s Sampling\\nMotif Search', width = 15, height = 2, fg = 'green',\n command = lambda:Status_running(2));\ncompute_button2.pack()\n\nframe3 = Frame(root); frame3.grid(row = 4, column = 2);\ncompute_button3 = Button(frame3, text = 'Greedy\\nMotif Search', width = 15, height = 2, fg = 'purple',\n command = lambda:Status_running(3));\ncompute_button3.pack()\n\ndef reset():\n T.delete('1.0', END); Status_done();\n\nreset_button = Button(root, text = 'Reset Space', width = 15, height = 2, fg = 'black',\n command = reset).grid(row = 5, column = 2);\nexit_button = Button(root, text = 'Exit', width = 15, height = 2, fg = 'red',\n command = exit).grid(row = 5, column = 1);\n\nlabel_status = Label(text = 'Status: ');label_status.grid(row = 6, column = 1);\n\nT = Text(root, height=30, width=99)\nT.grid(row = 7, column = 0, columnspan=3, rowspan=2, padx=2, pady=3)\n\ndef Status_running(number):\n label_status.config(text = 'Searching for the bottom of your patience...')\n if number == 1 : display_motif_Random()\n if number == 2 : display_motif_Gibbs()\n if number == 3: display_motif_Greedy()\n\ndef Status_done():\n label_status.config(text = 'Status: Done! I''m ready.')\n\nroot.mainloop()","sub_path":"Motif_Search_GUI/Randomized Motif Search.py","file_name":"Randomized Motif Search.py","file_ext":"py","file_size_in_byte":7966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"302919224","text":"from os import getenv\nfrom twisted.internet import defer, reactor, task\n\nfrom cafe.logging import LoggedObject\nfrom cafe.twisted import async_sleep\nfrom consul.base import ConsulException\nfrom consul.twisted import Consul\n\nCONSUL_HOST = getenv('CONSUL_HOST', '127.0.0.1')\nCONSUL_PORT = int(getenv('CONSUL_PORT', '8500'))\nCONSUL_TOKEN = getenv('CONSUL_TOKEN', None)\nCONSUL_SCHEME = getenv('CONSUL_SCHEME', 'http')\nCONSUL_DC = getenv('CONSUL_DC', None)\nCONSUL_VERIFY = bool(getenv('CONSUL_VERIFY', 'True'))\n\n\nclass SessionedConsulAgent(LoggedObject, object):\n GLOBAL_RETRY_DELAY_SECONDS = int(getenv('CONSUL_GLOBAL_RETRY_DELAY_SECONDS', 10))\n SESSION_TTL_SECONDS = int(getenv('CONSUL_SESSION_TTL_SECONDS', '75'))\n SESSION_HEARTBEAT_SECONDS = int(getenv('CONSUL_SESSION_HEARTBEAT_SECONDS', '75'))\n SESSION_LOCK_DELAY_SECONDS = int(getenv('CONSUL_SESSION_LOCK_DELAY_SECONDS', '15'))\n SESSION_CREATE_RETRY_DELAY_SECONDS = GLOBAL_RETRY_DELAY_SECONDS\n\n def __init__(self, name, behavior='delete', ttl=None, heartbeat_interval=None, lock_delay=None, host=CONSUL_HOST,\n port=CONSUL_PORT, token=CONSUL_TOKEN, scheme=CONSUL_SCHEME, dc=CONSUL_DC, verify=CONSUL_VERIFY,\n **kwargs):\n \"\"\"\n :type behavior: str\n :param behavior: consul session behavior (release, delete)\n :type ttl: int\n :param ttl: time to live for the session before it is invalidated\n :param name: session name to use\n :type name: str\n :param heartbeat_interval: interval (in seconds) in which a session\n should be renewed, this value is also used as the session ttl.\n :type heartbeat_interval: str\n :type lock_delay: int\n :param lock_delay: consul lock delay to use for sessions\n \"\"\"\n assert behavior in ('release', 'delete')\n self.name = name\n self.ttl = ttl or self.SESSION_TTL_SECONDS\n self.heartbeat_interval = heartbeat_interval or self.SESSION_HEARTBEAT_SECONDS\n self.lock_delay = lock_delay or self.SESSION_LOCK_DELAY_SECONDS\n if 0 > self.lock_delay > 60:\n self.logger.debug('invalid lock-delay=%s specified, using defaults', self.lock_delay)\n self.lock_delay = 15\n self.consul = Consul(host=host, port=port, token=token, scheme=scheme, dc=dc, verify=verify, **kwargs)\n self.session = None\n self.heartbeat = task.LoopingCall(self.session_renew)\n reactor.callLater(0, self.session_create)\n self.start()\n reactor.addSystemEventTrigger('before', 'shutdown', self.stop)\n reactor.addSystemEventTrigger('before', 'shutdown', self.session_destroy)\n\n @property\n def agent(self):\n return self.consul\n\n def start(self):\n \"\"\"\n Start this instance.\n \"\"\"\n self.logger.trace('starting consul agent')\n\n def stop(self):\n \"\"\"\n Execute clean-up tasks.\n \"\"\"\n self.logger.trace('stopping consul agent')\n\n @property\n def ready(self):\n \"\"\"Check if a session has been established with consul.\"\"\"\n return self.session is not None\n\n @defer.inlineCallbacks\n def wait_for_ready(self, attempts=None, interval=None):\n \"\"\"\n :param attempts: number of attempts before giving up, if None there is\n no giving up.\n :type attempts: int or None\n :param interval: interval (in seconds), by default the create retry interval is used\n :type interval: int or None\n \"\"\"\n interval = interval if interval is not None else self.SESSION_CREATE_RETRY_DELAY_SECONDS\n attempt = 0\n while not self.ready and (attempts is None or attempt <= attempts):\n attempt += 1\n self.logger.debug('attempt=%s interval=%ss waiting for session to established', attempt, interval)\n yield async_sleep(interval)\n\n @defer.inlineCallbacks\n def session_create(self, retry=True):\n \"\"\"\n Create a session, and set the internal `session_id` property. If an\n exception is encountered during creation, the operation will be\n reattempted again at half the ttl of the session itself if `retry` is\n `True`.\n\n :param retry: retry later if creation fails\n :type retry: bool\n \"\"\"\n try:\n self.logger.trace('attempting to create a new session')\n self.session = yield self.consul.session.create(\n self.name, behavior='delete', ttl=self.ttl, lock_delay=self.lock_delay)\n self.logger.info('name=%s session=%s created', self.name, self.session)\n\n if not self.heartbeat.running:\n reactor.callLater(0, self.heartbeat.start, interval=self.heartbeat_interval)\n except ConsulException as e:\n self.logger.warning(\n 'session=%s creation failed, retrying reason=%s',\n self.session, e.message)\n if retry:\n # try again in SESSION_CREATE_RETRY_DELAY_SECONDS\n reactor.callLater(self.SESSION_CREATE_RETRY_DELAY_SECONDS, self.session_create)\n\n @defer.inlineCallbacks\n def session_renew(self):\n \"\"\"Renew session if one is active, else do nothing.\"\"\"\n try:\n if self.session is not None:\n self.logger.trace('name=%s session=%s renewing session', self.name, self.session)\n yield self.consul.session.renew(self.session)\n except ConsulException as e:\n self.logger.warning(\n 'session=%s renewal attempt failed reason=%s',\n self.session, e.message\n )\n\n @defer.inlineCallbacks\n def session_destroy(self):\n \"\"\"Destroy a session if one is active, else do nothing.\"\"\"\n try:\n if self.session is not None:\n if self.heartbeat.running:\n self.logger.trace('name=%s session=%s stopping heartbeat', self.name, self.session)\n self.heartbeat.stop()\n\n self.logger.trace('name=%s session=%s destroying session', self.name, self.session)\n yield self.consul.session.destroy(self.session)\n self.logger.info('name=%s session=%s destroyed session', self.name, self.session)\n self.session = None\n except ConsulException as e:\n self.logger.warning(\n 'session=%s destruction attempt failed reason=%s',\n self.session, e.message\n )\n\n @classmethod\n def create_lock_key(cls, *args):\n \"\"\"Helper method to create a valid key provider components as args\"\"\"\n return '/'.join(args)\n\n @defer.inlineCallbacks\n def _lock(self, action, key, value=None):\n \"\"\"\n Internal method to acquire/release a lock\n\n :type key: str\n :type value: str\n \"\"\"\n assert action in ('acquire', 'release')\n self.logger.debug(\n 'lock=%s action=%s session=%s value=%s',\n key, action, self.session, value\n )\n if not self.ready:\n self.logger.trace(\n 'lock=%s action=%s failed as consul agent is not ready',\n key, action\n )\n result = False\n else:\n result = yield self.consul.kv.put(\n key=key, value=value, **{action: self.session})\n self.logger.info('lock=%s action=%s result=%s', key, action, result)\n defer.returnValue(result)\n\n @defer.inlineCallbacks\n def acquire_lock(self, key, value=''):\n \"\"\"\n Acquire a lock with a provided value.\n\n :type key: str\n :type value: str\n \"\"\"\n result = yield self._lock(action='acquire', key=key, value=value)\n defer.returnValue(result)\n\n @defer.inlineCallbacks\n def release_lock(self, key, value='', delete=False):\n \"\"\"\n Release a lock with a provided value.\n\n :type key: str\n :type value: str\n :type delete: bool\n \"\"\"\n result = yield self._lock(action='release', key=key, value=value)\n if result and delete:\n try:\n self.logger.trace('key=%s deleting as lock is released', key)\n yield self.consul.kv.delete(key=key)\n except ConsulException as e:\n self.logger.warning(\n 'key=%s failed to delete reason=%s', key, e.message)\n defer.returnValue(result)\n\n @defer.inlineCallbacks\n def wait_for_lock(self, key, value='', attempts=None):\n \"\"\"\n Wait till a lock is acquired. If attempts is None, wait for ever.\n\n :type key: str\n :type value: str\n :type attempts: None or int\n :rtype: bool\n \"\"\"\n index = None\n result = False\n yield self.wait_for_ready()\n while not result and (attempts is None or attempts >= 0):\n self.logger.debug(\n 'lock=%s waiting for lock; %s attempts left',\n key, attempts if attempts is not None else 'infinite')\n result = yield self.acquire_lock(key=key, value=value)\n if not result:\n index, _ = yield self.agent.kv.get(key=key, index=index)\n if attempts is not None:\n attempts -= 1\n defer.returnValue(result)\n\n\nclass DistributedConsulAgent(SessionedConsulAgent):\n ELECTION_EXPIRY = int(getenv('CONSUL_ELECTION_EXPIRY', SessionedConsulAgent.SESSION_HEARTBEAT_SECONDS))\n ELECTION_RETRY = int(getenv('CONSUL_ELECTION_RETRY', SessionedConsulAgent.SESSION_CREATE_RETRY_DELAY_SECONDS))\n\n def __init__(self, name, behavior='delete', ttl=None, heartbeat_interval=None, lock_delay=None, host=CONSUL_HOST,\n port=CONSUL_PORT, token=CONSUL_TOKEN, scheme=CONSUL_SCHEME, dc=CONSUL_DC, verify=CONSUL_VERIFY,\n **kwargs):\n super(DistributedConsulAgent, self).__init__(\n name, behavior=behavior, ttl=ttl, heartbeat_interval=heartbeat_interval, lock_delay=lock_delay,\n host=host, port=port, token=token, scheme=scheme, dc=dc, verify=verify, **kwargs\n )\n self._leader = None\n self.is_leader = False\n self._abstain = False\n self.leader_key = 'service/{}/leader'.format(name)\n reactor.callLater(0, self.update_leader)\n\n @property\n def leader(self):\n \"\"\"Current leader data\"\"\"\n return self._leader\n\n @leader.setter\n def leader(self, value):\n self._leader = value\n if value is None:\n # immediate retry if we are the leader\n reactor.callLater(0, self.acquire_leadership)\n\n @defer.inlineCallbacks\n def update_leader(self, index=None):\n try:\n index, data = yield self.agent.kv.get(key=self.leader_key, index=index)\n if data is not None and hasattr(data, 'get'):\n self.leader = data.get('Value', None)\n else:\n # the key does not exist, we are using 'delete' behaviour\n self.leader = None\n self.logger.trace('name=%s session=%s leader=%s', self.name, self.session, self.leader)\n except ConsulException as e:\n self.logger.error(\n 'leader update failed, retrying later exception=%s message=%s', e.__class__.__name__, e.message)\n yield async_sleep(self.SESSION_CREATE_RETRY_DELAY_SECONDS)\n reactor.callLater(0, self.update_leader, index=index)\n\n @property\n def candidate_data(self):\n \"\"\"\n Data to use when applying for leadership.\n\n :rtype: str\n \"\"\"\n return self.session\n\n @defer.inlineCallbacks\n def acquire_leadership(self):\n \"\"\"\n Try to acquire leadership.\n\n :rtype: bool\n \"\"\"\n if self.session is None:\n self.logger.trace('name=%s session not ready, retrying later', self.name)\n reactor.callLater(self.ELECTION_RETRY, self.acquire_leadership)\n elif self._abstain:\n self.logger.trace('name=%s session=%s currently abstaining from elections, skipping', self.name,\n self.session)\n elif self.leader is not None:\n self.logger.trace('name=%s leader exists, skipping', self.name)\n else:\n value = self.candidate_data\n self.logger.trace('name=%s session=%s can i haz leadership', self.name, self.session)\n try:\n self.is_leader = yield self.acquire_lock(key=self.leader_key, value=value)\n if self.is_leader:\n self.logger.info('name=%s session=%s acquired leadership', self.name, self.session)\n else:\n # handle consul lock-delay safe guard, retry a bit later\n reactor.callLater(self.ELECTION_RETRY, self.acquire_leadership)\n self.logger.trace('name=%s session=%s acquired_leadership=%s', self.name, self.session, self.is_leader)\n except ConsulException as e:\n self.logger.trace('name=%s session=%s acquiring leadership attempt failed reason=%s', self.name,\n self.session, e.message)\n defer.returnValue(self.is_leader)\n\n @defer.inlineCallbacks\n def relinquish_leadership(self, abstain=False):\n \"\"\"\n :param abstain: abstain from next election till a new leader is elected,\n WARNING: be sure you know what you are doing, this can lead to potential deadlocks.\n :type abstain: bool\n \"\"\"\n try:\n self.logger.info('name=%s session=%s relinquishing leadership', self.name, self.session)\n self._abstain = abstain\n yield self.release_lock(key=self.leader_key)\n if abstain:\n self.logger.debug('name=%s session=%s waiting for next leader', self.name, self.session)\n yield self.wait_for_leader()\n finally:\n self._abstain = False\n\n @defer.inlineCallbacks\n def wait_for_leader(self, attempts=None, interval=None):\n \"\"\"\n :param attempts: number of attempts before giving up, if None there is\n no giving up.\n :type attempts: int or None\n :param interval: interval (in seconds), by default the election retry interval is used\n :type interval: int or None\n \"\"\"\n yield self.wait_for_ready()\n interval = interval if interval is not None else self.ELECTION_RETRY\n attempt = 0\n while self.leader is None and (attempts is None or attempt <= attempts):\n attempt += 1\n self.logger.debug('attempt=%s interval=%ss waiting for leader to be elected', attempt, interval)\n yield async_sleep(interval)\n\n @defer.inlineCallbacks\n def wait_for_leadership(self):\n yield self.wait_for_leader()\n while not self.is_leader:\n yield async_sleep(self.ELECTION_EXPIRY)\n","sub_path":"cafe/consul/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":14889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"177735978","text":"import pygame, eightbit, re\n\n#TODO: Add radio and checkboxes.\n#TODO: Add arrow key manouverable button sets.\n\ndef focusable(cls):\n cls.is_focusable = True\n return cls\n\nclass Widget(pygame.Rect):\n current_widget_id = 0\n def __init__(self, game, left, top, width, height):\n super(Widget, self).__init__(left, top, width, height)\n Widget.current_widget_id += 1\n self._widget_id = Widget.current_widget_id\n self.hovering = False\n self.focused = False\n self._full_surface = pygame.Surface(self.size)\n self._surfaces = self.populate_surfaces(game)\n\n def populate_surfaces(self, gane):\n return [self._full_surface.copy()]\n\n def get_surface(self, game):\n return self._surfaces[0]\n\n def on_click(self, game, pos):\n pass\n\n def on_enter(self, game, pos):\n pass\n\n def on_leave(self, game, pos):\n pass\n\n def on_key(self, game, key):\n pass\n\nclass Button(Widget):\n def __init__(self, game, left, top, width, height, text, text_colour=eightbit.BLACK, action=None, center_x=False, center_y=False):\n self._text = text\n self._action = action\n self._text_surface = game.get_font(20).render(self._text, 1, text_colour)\n super(Button, self).__init__(game, left-(width/2 if center_x else 0), top-(height/2 if center_y else 0), width, height)\n\n def on_click(self, game, pos):\n if self._action != None:\n self._action()\n\n def populate_surfaces(self, game):\n normal = self._full_surface.copy()\n normal.fill(eightbit.WHITE)\n normal.blit(self._text_surface, (self.width/2-self._text_surface.get_width()/2, self.height/2-self._text_surface.get_height()/2))\n hover = self._full_surface.copy()\n hover.fill(eightbit.GREY)\n hover.blit(self._text_surface, (self.width/2-self._text_surface.get_width()/2, self.height/2-self._text_surface.get_height()/2))\n return [normal, hover]\n\n def get_surface(self, game):\n if self.hovering:\n return self._surfaces[1]\n return self._surfaces[0]\n\nclass EightbitButton(Button):\n def __init__(self, game, left, top, text, action=None, padding_x=10, padding_y=5, center_x=False, center_y=False):\n self._padding_x = padding_x\n self._padding_y = padding_y\n size = game.get_font(20).size(text)\n width = size[0]+padding_x*2 + 5\n height = size[1]+padding_y*2 + 5\n super(EightbitButton, self).__init__(game, left, top, width, height, text, eightbit.WHITE, action, center_x, center_y)\n\n def populate_surfaces(self, game):\n normal = self._full_surface.copy()\n normal.set_colorkey(eightbit.WHITE)\n normal.fill(eightbit.WHITE)\n pygame.draw.rect(normal, eightbit.BLACK, pygame.Rect(0, 0, self.width - 5, self.height - 5))\n pygame.draw.rect(normal, eightbit.BLACK, pygame.Rect(3, self.height - 2, self.width, 2))\n pygame.draw.rect(normal, eightbit.BLACK, pygame.Rect(self.width - 2, 3, 2, self.height))\n normal.blit(self._text_surface, (self._padding_x, self._padding_y))\n hover = self._full_surface.copy()\n hover.set_colorkey(eightbit.WHITE)\n hover.fill(eightbit.WHITE)\n pygame.draw.rect(hover, eightbit.BLACK, pygame.Rect(5, 5, self.width - 5, self.height - 5))\n hover.blit(self._text_surface, (self._padding_x + 5, self._padding_y + 5))\n return [normal, hover]\n\n@focusable\nclass Textbox(Widget):\n def __init__(self, game, left, top, max_length, text=\"\", padding_x=10, padding_y=5, center_x=False, center_y=False):\n self._max_length = max_length\n self._cursor_pos = len(text)\n self.set_text(game, text)\n self._padding_x = padding_x\n self._padding_y = padding_y\n self._count = 0\n size = game.get_font(20).size(\"W\"*max_length)\n width = size[0] + padding_x * 2\n height = size[1] + padding_y * 2\n super(Textbox, self).__init__(game, left-(width/2 if center_x else 0), top-(height/2 if center_y else 0), width, height)\n\n def get_surface(self, game):\n self._count += 1\n surface = self._surfaces[0].copy()\n surface.blit(self._text_surface, (self._padding_x, self.height/2-self._text_surface.get_height()/2))\n if self.focused and self._count % 60 < 45:\n pygame.draw.rect(surface, eightbit.BLACK, pygame.Rect(game.get_font(20).size(self.get_text()[:self._cursor_pos])[0] + self._padding_x, self._padding_y, 2, self.height-self._padding_y*2))\n return surface\n\n def populate_surfaces(self, game):\n normal = self._full_surface.copy()\n normal.fill(eightbit.WHITE)\n return [normal]\n\n def set_text(self, game, text, cursor=0):\n if len(text) <= self._max_length:\n self._text = text\n self._text_surface = game.get_font(20).render(self._text, 1, eightbit.BLACK)\n self._cursor_pos += cursor\n\n def get_text(self):\n return self._text\n\n def remove_char(self, game, index, cursor=0):\n text = self.get_text()\n self.set_text(game, text[:index-1] + text[index:], cursor)\n\n def add_char(self, game, index, char, cursor=0):\n text = self.get_text()\n self.set_text(game, text[:index] + char + text[index:], cursor)\n\n def on_key(self, game, key):\n if len(pygame.key.name(key)) == 1 and re.match(r\"[a-z0-9]\", pygame.key.name(key)) != None:\n char = pygame.key.name(key)\n caps = pygame.key.get_mods() & pygame.KMOD_CAPS\n shift = pygame.key.get_mods() & pygame.KMOD_SHIFT\n if (caps and not shift) or (shift and not caps):\n char = char.upper()\n self.add_char(game, self._cursor_pos, char, 1)\n elif key == pygame.K_LEFT and self._cursor_pos > 0:\n self._cursor_pos -= 1\n elif key == pygame.K_RIGHT and self._cursor_pos < len(self.get_text()):\n self._cursor_pos += 1\n elif key == pygame.K_BACKSPACE and self._cursor_pos > 0:\n self.remove_char(game, self._cursor_pos, -1)\n elif key == pygame.K_DELETE and self._cursor_pos < len(self.get_text()):\n self.remove_char(game, self._cursor_pos+1)\n elif key == pygame.K_SPACE:\n self.add_char(game, self._cursor_pos, \" \", 1)\n elif key == pygame.K_HOME:\n self._cursor_pos = 0\n elif key == pygame.K_END:\n self._cursor_pos = len(self.get_text())\n\n\nclass EightbitTextbox(Textbox):\n def __init__(self, game, left, top, max_length, text=\"\", padding_x=10, padding_y=5, center_x=False, center_y=False):\n super(EightbitTextbox, self).__init__(game, left, top, max_length, text, padding_x, padding_y, center_x, center_y)\n\n def populate_surfaces(self, game):\n normal = self._full_surface.copy()\n normal.set_colorkey(eightbit.WHITE)\n normal.fill(eightbit.BLACK)\n pygame.draw.rect(normal, eightbit.WHITE, pygame.Rect(2, 2, self.width - 4, self.height - 4))\n return [normal]\n","sub_path":"eightbit/Widget.py","file_name":"Widget.py","file_ext":"py","file_size_in_byte":7027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"182602621","text":"from django.conf.urls import patterns, include, url\nimport views\nfrom django.contrib import admin\nadmin.autodiscover()\n\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'SceneMaker.views.home', name='home'),\n url(r'^$', views.index),\n url(r'login/^$', views.login),\n url(r'logout/^$', views.logout),\n url(r'signup/^$', views.signup),\n url(r'^admin/', include(admin.site.urls)),\n url(r'^api/', include('API.urls', namespace='API')),\n)\n\nif not settings.PRODUCTION:\n\turlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n\turlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)","sub_path":"SceneMaker/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"17716542","text":"#!/usr/bin/env python3\n#\n# Copyright 2021 Graviti. Licensed under MIT License.\n#\n\n\"\"\"mixin classes for local file and remote file.\"\"\"\n\nimport os\nfrom hashlib import sha1\nfrom http.client import HTTPResponse\nfrom string import printable\nfrom typing import Any, Callable, Dict, Optional, Union\nfrom urllib.error import HTTPError\nfrom urllib.parse import quote, urljoin\nfrom urllib.request import pathname2url, urlopen\n\nfrom _io import BufferedReader\n\nfrom tensorbay.utility.repr import ReprMixin\n\n\nclass URL:\n \"\"\"URL is a class used to get and update the url.\n\n Arguments:\n url: The url.\n updater: A function used to update the url.\n\n \"\"\"\n\n def __init__(self, url: str, updater: Callable[[], Optional[str]]) -> None:\n self._updater = updater\n self._getter: Callable[..., str] = lambda: url\n\n @classmethod\n def from_getter(cls, getter: Callable[..., str], updater: Callable[[], Optional[str]]) -> \"URL\":\n \"\"\"Create a URL instance from the given getter and updater.\n\n Arguments:\n getter: The url getter of the file.\n updater: The updater of the url.\n\n Returns:\n The URL instance which stores the url and the updater.\n\n \"\"\"\n obj: \"URL\" = object.__new__(cls)\n obj._getter = getter\n obj._updater = updater\n return obj\n\n def update(self) -> None:\n \"\"\"Update the url.\"\"\"\n url = self._updater()\n if url is not None:\n self._getter = lambda: url # type: ignore[assignment, return-value]\n\n def get(self) -> str:\n \"\"\"Get the url of the file.\n\n Returns:\n The url.\n\n \"\"\"\n return self._getter()\n\n\nclass FileMixin(ReprMixin):\n \"\"\"FileMixin is a mixin class to mixin file related methods for local file.\n\n Arguments:\n local_path: The file local path.\n\n Attributes:\n path: The file local path.\n\n \"\"\"\n\n _checksum: str\n\n _repr_maxlevel = 3\n _BUFFER_SIZE = 65536\n\n def __init__(self, local_path: str) -> None:\n self.path = local_path\n\n def _repr_head(self) -> str:\n return f'{self.__class__.__name__}(\"{self.path}\")'\n\n def _get_callback_body(self) -> Dict[str, Any]:\n return {\"checksum\": self.get_checksum(), \"fileSize\": os.path.getsize(self.path)}\n\n def get_checksum(self) -> str:\n \"\"\"Get and cache the sha1 checksum of the local data.\n\n Returns:\n The sha1 checksum of the local data.\n\n \"\"\"\n if not hasattr(self, \"_checksum\"):\n sha1_object = sha1()\n with open(self.path, \"rb\") as fp:\n while True:\n data = fp.read(self._BUFFER_SIZE)\n if not data:\n break\n sha1_object.update(data)\n\n self._checksum = sha1_object.hexdigest()\n\n return self._checksum\n\n def get_url(self) -> str:\n \"\"\"Return the url of the local data file.\n\n Returns:\n The url of the local data.\n\n \"\"\"\n return urljoin(\"file:\", pathname2url(os.path.abspath(self.path)))\n\n def open(self) -> BufferedReader:\n \"\"\"Return the binary file pointer of this file.\n\n The local file pointer will be obtained by build-in ``open()``.\n\n Returns:\n The local file pointer for this data.\n\n \"\"\"\n return open(self.path, \"rb\")\n\n\nclass RemoteFileMixin(ReprMixin):\n \"\"\"RemoteFileMixin is a mixin class to mixin file related methods for remote file.\n\n Arguments:\n local_path: The file local path.\n url: The URL instance used to get and update url.\n cache_path: The path to store the cache.\n\n Attributes:\n path: The file local path.\n\n \"\"\"\n\n _repr_maxlevel = 3\n\n def __init__(\n self,\n remote_path: str,\n *,\n url: Optional[URL] = None,\n cache_path: str = \"\",\n ) -> None:\n self.path = remote_path\n self.url = url\n self.cache_path = os.path.join(cache_path, remote_path) if cache_path else \"\"\n\n def _repr_head(self) -> str:\n return f'{self.__class__.__name__}(\"{self.path}\")'\n\n def _urlopen(self) -> HTTPResponse:\n\n if not self.url:\n raise ValueError(f\"The file cannot open because {self._repr_head()} has no url\")\n\n try:\n return urlopen( # type: ignore[no-any-return]\n quote(self.url.get(), safe=printable), timeout=2\n )\n except HTTPError as error:\n if error.code == 403:\n self.url.update()\n return urlopen(quote(self.url.get(), safe=printable)) # type: ignore[no-any-return]\n raise\n\n def open(self) -> Union[HTTPResponse, BufferedReader]:\n \"\"\"Return the binary file pointer of this file.\n\n The remote file pointer will be obtained by ``urllib.request.urlopen()``.\n\n Returns:\n The remote file pointer for this data.\n\n \"\"\"\n cache_path = self.cache_path\n if not cache_path:\n return self._urlopen()\n\n if not os.path.exists(cache_path):\n dirname = os.path.dirname(cache_path)\n if not os.path.exists(dirname):\n os.makedirs(dirname)\n\n with self._urlopen() as fp:\n with open(cache_path, \"wb\") as cache:\n cache.write(fp.read())\n\n return open(cache_path, \"rb\")\n","sub_path":"tensorbay/utility/file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":5412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"235911227","text":"import pygame\nfrom pygame.sprite import Sprite\n\n\nclass Bullet(Sprite):\n \"\"\" \"\"\"\n\n def __init__(self, myset, screen, ship):\n \"\"\" 继承父类 初始化子弹的位置,颜色,速度 \"\"\"\n super().__init__()\n self.screen = screen\n self.rect = pygame.Rect(0, 0, myset.bullet_width, myset.bullet_height)\n self.rect.centery = ship.rect.centery\n self.rect.right = ship.rect.right\n self.x = float(self.rect.x)\n\n self.color = myset.bullet_color\n self.speed = myset.bullet_speed\n\n def update(self):\n #移动子弹\n self.x += self.speed\n self.rect.x = self.x\n\n def draw_bullet(self):\n # 画子弹\n pygame.draw.rect(self.screen, self.color, self.rect)\n","sub_path":"mygame/ship_bullet.py","file_name":"ship_bullet.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"620757654","text":"import urllib.request, http.client, json, time, datetime\nimport datetime\nimport pymongo\nimport time\nimport tushare as ts\n\nclient = pymongo.MongoClient(\"mongodb://localhost:27017/\")\ndaylinedb = client[\"daylinedb\"]\ncollist = daylinedb.list_collection_names()\ndate_list = [\"20201107\", \"20201108\", \"20201109\", \"20201110\", \"20201111\", \"20201112\", \"20201113\", \"20201114\", \"20201115\", \"20201116\", \"20201117\", \"20201118\", \"20201119\", \"20201120\", \"20201121\", \"20201122\", \"20201123\", \"20201124\", \"20201125\", \"20201126\", \"20201127\", \"20201128\", \"20201129\", \"20201130\", ]\npro = ts.pro_api(token=\"df36b05825c5f945cdd1b566f85f69d6db45e597765a0bdc9f616f44\")\nstart_date = (datetime.datetime.now()+datetime.timedelta(days=-365)).strftime(\"%Y%m%d\")\n# end_date = datetime.datetime.now().strftime(\"%Y%m%d\")\n# daily_data = pro.daily(trade_date=datetime.datetime.now().strftime(\"%Y%m%d\"))\nfor end_date in date_list:\n\tdaily_data = pro.daily(trade_date=end_date).to_dict(orient='records')\n\ttime.sleep(1)\n\t# index_data = pro.index_daily(ts_code='000300.Sh', start_date=start_date, end_date=end_date).to_dict(orient='records')\n\tif daily_data:\n\t\tfor stock in daily_data:\n\t\t\tprint(stock)\n\t\t\tstock_dict = {\n\t\t\t\t\"symbol\": stock[\"ts_code\"][0:6],\n\t\t\t\t\"exchange\": stock[\"ts_code\"][7:].lower(),\n\t\t\t\t\"date\": stock[\"trade_date\"],\n\t\t\t\t\"open\": stock[\"open\"],\n\t\t\t\t\"close\": stock[\"close\"],\n\t\t\t\t\"high\": stock[\"high\"],\n\t\t\t\t\"low\": stock[\"low\"],\n\t\t\t\t\"pre_close\": stock[\"pre_close\"],\n\t\t\t\t\"change\": stock[\"change\"],\n\t\t\t\t\"chg\": stock[\"pct_chg\"],\n\t\t\t\t\"volume\": stock[\"vol\"],\n\t\t\t\t\"amount\": stock[\"amount\"],\n\t\t\t}\n\t\t\tdaylinedb[stock[\"ts_code\"][0:6]].insert_one(stock_dict)\n# print(index_data)\t\n# for stock in collist:\n\t# if stock == \"000651\":\n\t\t# query = {\n\t\t\t# \"date\": {\n\t\t\t\t# \"$gte\": start_date,\n\t\t\t# }\n\t\t# }\n\t\t# data_list = list(daylinedb[stock].find(query))\n\t\t# index_data = index_data[-(len(data_list)+1): -1]\n\t\t# for l in list(data_list):\n\t\t\t# print(index_data[list(data_list).index(l)])\n\n\t","sub_path":"gjsicence/update_daily_data.py","file_name":"update_daily_data.py","file_ext":"py","file_size_in_byte":1945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"314904049","text":"# encoding: utf8\nimport turtle\nfrom snake import Snake\n\n\ndef main():\n snake = Snake(move_interval_seconds=0.1)\n snake.start()\n screen = turtle.Screen()\n screen.onscreenclick(build_screen_click_fun(snake))\n screen.title(\"crazy turtle\")\n screen.listen()\n screen.mainloop()\n\n\ndef build_screen_click_fun(snake):\n def on_screen_click(x, y):\n print('点击坐标 x:%d, y:%d' % (x, y))\n snake.head_to_position(x, y)\n return on_screen_click\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"168230644","text":"n = int(input(\"Podaj liczbe wyrazow ciagu Fibonacciego: \"))\r\ndef fibonacci(n):\r\n pwyrazy = (0, 1) \r\n a, b = pwyrazy \r\n print(a, end=\" \")\r\n while n > 1:\r\n print (b, end=\" \")\r\n a, b = b, a + b \r\n n -= 1\r\nprint(fibonacci(n))\r\n","sub_path":"6.py","file_name":"6.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"487792807","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nimport datetime as dat\nfrom selenium.webdriver.common.keys import Keys\nimport time\n\n\nURL = 'http://ec2-54-212-56-191.us-west-2.compute.amazonaws.com/now/'\n#URL = 'https://google.com'\ntry:\n\n response_code = requests.get(URL).status_code\n if response_code==200:\n print(\"the \" +URL+ \" is OK and working with status code \" + str(response_code))\n driver = webdriver.Chrome('./chromedriver')\n driver.get(URL)\n html = driver.page_source\n soup = BeautifulSoup(html, 'html.parser')\n results = soup.p.string\n localtime = dat.datetime.now()\n current_time = localtime.strftime(\"%H:%M:%S\")\n py_time = dat.datetime.strptime(current_time,\"%H:%M:%S\")\n server_time = dat.datetime.strptime(results,\"%H:%M:%S\")\n if py_time == server_time:\n print(\"The clock of the server and the python machine is in sync\")\n print(\"the python time is \" + current_time)\n print(\"the server time is \" + results)\n else:\n print(\"The clock of the server and the python machine is NOT in sync\")\n print(\"the python machine time is \" + current_time)\n print(\"the server time is \" + results)\n driver.close()\n else:\n print(\"the \" +URL+ \" is NOT OK as it is responding with status \" +str(response_code) )\nexcept requests.ConnectionError as c:\n print(\"The URL is not responding it is NOT OKAY .... \" + str(c))\nexcept AttributeError as a:\n print(\"the URL \" +URL+ \" is not intended to be used for the script \")\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"115722293","text":"import pytest \nimport session9\nfrom session9 import *\n\nfrom faker import Faker\nfake = Faker()\n\nfrom decimal import Decimal\n\n\nfaker_profile_dict_keys = fake.profile().keys()\n\nfake_profile_namedtuple = convert_dictionary_to_namedtuple(generate_random_profile(1),profile)[0]\nfake_profile_namedtuple_fields = fake_profile_namedtuple._fields\n\ndef test_profile_fields_available():\n ''' test for all keys in Faker dictionary matches with fields profile namedtuple''' \n\n #check faker keys in profile fields\n for key in faker_profile_dict_keys:\n assert True == (key in fake_profile_namedtuple_fields) # hasattr(fake_profile_namedtuple,key)\n #check profile fields in faker keys\n for field in fake_profile_namedtuple_fields:\n assert True == (field in faker_profile_dict_keys)\n\ndef test_profile_fields_not_empty():\n ''' test none of the fields in Faker profile is empty''' \n for field in fake_profile_namedtuple_fields:\n assert None != getattr(fake_profile_namedtuple,field)\n\ndef test_profile_doc_string_not_empty():\n ''' test none of the doc string in profile is empty'''\n assert len(profile.__doc__) > 0\n assert len(profile.name.__doc__) > 0\n assert len(profile.birthdate.__doc__) > 0\n assert len(profile.sex.__doc__) > 0\n assert len(profile.blood_group.__doc__) > 0\n assert len(profile.ssn.__doc__) > 0\n assert len(profile.username.__doc__) > 0\n assert len(profile.website.__doc__) > 0\n assert len(profile.mail.__doc__) > 0\n assert len(profile.address.__doc__) > 0\n assert len(profile.residence.__doc__) > 0\n assert len(profile.current_location.__doc__) > 0\n assert len(profile.company.__doc__) > 0\n assert len(profile.job.__doc__) > 0\n\n\ndef test_profile_generation():\n '''test number of profiles created is equal to count value'''\n assert 10 == len(generate_random_profile(10))\n assert 50 == len(generate_random_profile(50))\n assert 100 == len(generate_random_profile(100))\n\ndef test_validate_datatype_of_count_generate_random_profile():\n '''validate the datatype of count is int'''\n with pytest.raises(TypeError, match=r\".*'count' must be int not float.*\"):\n generate_random_profile(10.0)\n with pytest.raises(TypeError, match=r\".*'count' must be int not str.*\"):\n generate_random_profile(\"hello\")\n with pytest.raises(TypeError, match=r\".*'count' must be int not list.*\"):\n generate_random_profile([1,2,3])\n\ndef test_convert_dictionary_to_namedtuple():\n '''test if datatype of converted list is profile'''\n profile_list = convert_dictionary_to_namedtuple(generate_random_profile(10),profile)\n for profile_ in profile_list:\n assert 'profile' == profile_.__class__.__name__\n\n\ndef test_get_age():\n '''test get_age function'''\n assert \"1 year/s, 0 month/s, 1 day/s\" == get_age(366)\n assert \"0 year/s, 11 month/s, 30 day/s\" == get_age(364)\n assert \"1 year/s, 1 month/s, 1 day/s\" == get_age(396)\n \ndef test_validate_datatype_of_days_get_age():\n '''validate the datatype of days is int'''\n with pytest.raises(TypeError, match=r\".*'days' must be int not float.*\"):\n get_age(10.0)\n with pytest.raises(TypeError, match=r\".*'days' must be int not str.*\"):\n get_age(\"hello\")\n with pytest.raises(TypeError, match=r\".*'days' must be int not list.*\"):\n get_age([1,2,3])\n\ndef test_demograph():\n '''test the demograph calculation'''\n fake_profiles_dict = ({'address': '9089 Nichols Lodge\\nNorth Anthonystad, ND 17725',\n 'birthdate': datetime.date(1941, 4, 13),\n 'blood_group': 'AB-',\n 'company': 'Hardin, Smith and Melendez',\n 'current_location': (Decimal('72.700640'), Decimal('-8.379374')),\n 'job': \"Barrister's clerk\",\n 'mail': 'william44@hotmail.com',\n 'name': 'Heather Torres',\n 'residence': '884 Julia Roads Suite 037\\nEvansland, NV 26477',\n 'sex': 'F',\n 'ssn': '163-49-0337',\n 'username': 'tyler59',\n 'website': ['http://vance.com/', 'https://www.simmons.biz/']},\n {'address': '828 Todd Squares\\nTimothybury, FL 10394',\n 'birthdate': datetime.date(2012, 9, 15),\n 'blood_group': 'AB+',\n 'company': 'Smith, Perez and Edwards',\n 'current_location': (Decimal('32.9266245'), Decimal('-136.106601')),\n 'job': 'Company secretary',\n 'mail': 'susanjones@yahoo.com',\n 'name': 'Karen Macias',\n 'residence': '267 Marsh Prairie\\nPort Tracyburgh, MT 29152',\n 'sex': 'F',\n 'ssn': '179-94-6474',\n 'username': 'wesley55',\n 'website': ['https://www.pruitt.com/']},\n {'address': '33750 Weaver Ferry Apt. 525\\nNorth Christopher, MI 31898',\n 'birthdate': datetime.date(1955, 8, 25),\n 'blood_group': 'AB-',\n 'company': 'Garcia-Lopez',\n 'current_location': (Decimal('50.4030935'), Decimal('177.608880')),\n 'job': 'Education administrator',\n 'mail': 'qford@hotmail.com',\n 'name': 'Deborah Barnett',\n 'residence': '804 Boyle Ridge\\nHarrisshire, NC 15335',\n 'sex': 'F',\n 'ssn': '303-06-5199',\n 'username': 'zhudson',\n 'website': ['https://www.moore.net/', 'https://www.williams.com/']},\n {'address': '50331 Sherman Glen Suite 159\\nWest Thomas, OR 60511',\n 'birthdate': datetime.date(2019, 10, 8),\n 'blood_group': 'B+',\n 'company': 'Owens, Chung and Gonzales',\n 'current_location': (Decimal('-57.925414'), Decimal('-179.664195')),\n 'job': 'Psychologist, occupational',\n 'mail': 'anthony08@yahoo.com',\n 'name': 'Robert Hughes',\n 'residence': '709 Ashlee Track\\nNew Juanmouth, ID 11645',\n 'sex': 'M',\n 'ssn': '508-52-7990',\n 'username': 'williamstony',\n 'website': ['http://www.hamilton.com/',\n 'http://mason.org/',\n 'https://serrano-atkins.net/']})\n\n fake_profiles_namedtuple = convert_dictionary_to_namedtuple( fake_profiles_dict ,profile)\n\n assert demograph(fake_profiles_dict,'dict') == demograph(fake_profiles_namedtuple,'namedtuple') == \" largest bloodgroup : B+ \\n mean current_location : (Decimal('24.526236'), Decimal('-36.6353225')) \\n oldest person age : 80 year/s, 3 month/s, 1 day/s \\n average age : 39 year/s, 2 month/s, 5 day/s \"\n\nfake_profile_dictionary_10_000 = generate_random_profile(10_000)\nfake_profile_namedtuple_10_000 = convert_dictionary_to_namedtuple(fake_profile_dictionary_10_000,profile)\n\n\ndef test_dict_namedtuple_performance():\n '''test to compare the performance of dictonary and namedtuple'''\n\n start = perf_counter()\n for _ in range(1000):\n demograph(fake_profile_namedtuple_10_000,\"namedtuple\")\n end = perf_counter()\n namedtuple_elapsed = (end - start)\n\n start = perf_counter()\n for _ in range(1000):\n demograph(fake_profile_dictionary_10_000,\"dict\")\n end = perf_counter()\n dict_elapsed = (end - start) \n\n assert dict_elapsed > namedtuple_elapsed\n\n\n\ndef test_stock_fields_not_empty():\n ''' test none of the fields in stock namedtuple is empty''' \n stock_ = generate_random_stock(1)[0] \n for field in stock._fields:\n assert None != getattr(stock_,field)\n\ndef test_stock_doc_string_not_empty():\n ''' test none of the doc string in stock is empty'''\n assert len(stock.__doc__) > 0\n assert len(stock.name.__doc__) > 0\n assert len(stock.symbol.__doc__) > 0\n assert len(stock.open.__doc__) > 0\n assert len(stock.high.__doc__) > 0\n assert len(stock.close.__doc__) > 0\n\ndef test_stock_generation():\n '''test number of stocks created is equal to count value'''\n assert 10 == len(generate_random_stock(10))\n assert 50 == len(generate_random_stock(50))\n assert 100 == len(generate_random_stock(100))\n\ndef test_validate_datatype_of_count_generate_random_stock():\n '''validate the datatype of count is int'''\n with pytest.raises(TypeError, match=r\".*'count' must be int not float.*\"):\n generate_random_stock(10.0)\n with pytest.raises(TypeError, match=r\".*'count' must be int not str.*\"):\n generate_random_stock(\"hello\")\n with pytest.raises(TypeError, match=r\".*'count' must be int not list.*\"):\n generate_random_stock([1,2,3])\n\ndef test_stock_open_high_close_values():\n '''test to make sure high is less than or equal to open or close'''\n stocks = generate_random_stock(10)\n for stock_ in stocks:\n assert stock_.high >= stock_.open\n assert stock_.high >= stock_.close\n\ndef test_calculate_stock_market():\n '''test stock market open, high, close is correct'''\n stocks = [stock(name='Bowman Group', symbol='BG', open=6200.56439626876, high=9429.488513790375, close=8912.184713785548), \n stock(name='Hicks and Sons', symbol='HS', open=4827.56386679894, high=4877.329115630371, close=1364.542280443182), \n stock(name='Jennings-Johnson', symbol='JJ', open=10181.883950151056, high=10181.883950151056, close=9889.247048809815), \n stock(name='Walker Inc', symbol='WI', open=10102.229791515016, high=17387.077644208843, close=17387.077644208843), \n stock(name='Kirk, Allen and Reed', symbol='KAR', open=9433.821824140465, high=16454.845186010243, close=9582.261252321166), \n stock(name='Schroeder-Warren', symbol='SW', open=389.3936343844695, high=464.74240037497253, close=99.93211909588699), \n stock(name='Hall and Sons', symbol='HS', open=7291.483996717891, high=14263.850820678063, close=7026.577643208964), \n stock(name='Young Ltd', symbol='YL', open=7521.418099415024, high=12027.760925745906, close=5520.979539997164), \n stock(name='Shaw, Zavala and Cox', symbol='SZC', open=5205.886273339603, high=8083.736771352835, close=8083.736771352835), \n stock(name='Chavez-Lopez', symbol='CL', open=8146.022559933936, high=16165.100685136455, close=5601.16989194355)]\n\n assert calculate_stock_market(stocks) == \"Open index : 69300.26839266515 \\nHigh index : 109335.81601307912 \\nClose index : 73467.70890516693 \\n\"\n\n","sub_path":"9_Named_Tuples/test_session9.py","file_name":"test_session9.py","file_ext":"py","file_size_in_byte":9729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"570187257","text":"import datetime as dt \n\ntday = dt.date.today()\n# print(tday.weekday())\n# print(tday.isoweekday())\n\ntdelta = dt.timedelta(days=7)\n\n# print(tday - tdelta)\n\nbday = dt.date(2020, 1, 31)\n\ntil_bday = bday - tday\n# print(til_bday)\n\n# t = dt.time(9, 30, 45, 100000)\n# print(t)\n\n# dt_mtn = dt.datetime.now(tz=pytz.timezone('US/Mountain'))\n# print(dt_mtn)\ndatestr = tday.strftime('%B %d, %Y')\n\ndtnew = dt.datetime.strptime(datestr, '%B %d, %Y')\nprint(dtnew)","sub_path":"test/sundazentime.py","file_name":"sundazentime.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"46769638","text":"#!/usr/bin/env python\n\nimport math\nfrom flexbe_core import EventState, Logger\nimport rospy\nimport copy\nfrom std_msgs.msg import UInt8\n\nfrom sensor_msgs.msg import PointCloud2, PointCloud\nfrom sensor_msgs import point_cloud2\nimport numpy as np\nfrom scipy.linalg import lstsq\nfrom gpd.msg import CloudIndexed\nfrom std_msgs.msg import Header, Int64\nfrom geometry_msgs.msg import Point, Pose, PoseStamped, Point32, Quaternion\nfrom sara_msgs.msg import Entity, Entities\nfrom tf import TransformListener\nfrom gpd.msg import GraspConfigList\nfrom tf.transformations import quaternion_from_euler, euler_from_quaternion\n\n\nfrom visualization_msgs.msg import Marker\nfrom visualization_msgs.msg import MarkerArray\n\n\nclass GetGraspFromEntity(EventState):\n '''\n State taking an entity and returning the best grasp based on the pointcloud entity\n @author Jeffrey Cousineau\n @license Apache2.0\n\n ># Entity object entity to grasp\n #> GraspingPose object pose to grasp the given entity\n -- ApproachDistance\tfloat\tdistance from object at which the gripper shall approach\n -- DistanceScoringMultiplier\tfloat\thow much a meter distance affects the score (Higher = closer poses)\n -- OrientationScoringMultiplier\tfloat\thow much radians difference from ideal pose affects the score (Higher = more correctly orientated poses)\n -- GraspScoringMultiplier\tfloat\thow much scores from gpd affects the final score (Higher = more weight in final score from gpd)\n \n <= done grasp was found and returned\n <= failed grasp was not found\n '''\n\n def graspCallback(self, msg):\n self.graspList = msg.grasps\n\n def __init__(self, approachDistance, distanceScoringMultiplier, orientationScoringMultiplier,\n graspScoringMultiplier):\n super(GetGraspFromEntity, self).__init__(outcomes=['done', 'failed'], input_keys=['Entity'],\n output_keys=['ApproachPose', 'GraspingPose'])\n self.approachDistance = approachDistance\n self.distanceScoringMultiplier = distanceScoringMultiplier\n self.orientationScoringMultiplier = orientationScoringMultiplier\n self.graspScoringMultiplier = graspScoringMultiplier\n self.graspList = None\n self.grasps_sub = rospy.Subscriber('/detect_grasps/clustered_grasps', GraspConfigList, self.graspCallback)\n\n self.listener = TransformListener(20)\n self.idealRoll = 0.0\n self.idealPitch = 0.0\n self.idealYaw = 0.07 # 4 degrees to the right relatively to the robot POV\n self.maxgraspScore = 0.0\n\n self.pub = rospy.Publisher('cloud_indexed', CloudIndexed, queue_size=1)\n self.marker_pub = rospy.Publisher('grasp_pose', PoseStamped, queue_size=1)\n self.marker_pub_app = rospy.Publisher('approach_pose', PoseStamped, queue_size=1)\n\n def execute(self, userdata):\n\n if userdata.Entity.pointcloud.header.frame_id == \"\":\n grasp, approach = self.getGraspWithoutPointcloud(userdata.Entity)\n else:\n grasp, approach = self.getGraspFromPointcloud(userdata.Entity)\n\n # return the chosen poses\n userdata.GraspingPose = grasp\n userdata.ApproachPose = approach\n\n\n # Creates markers for the chosen pose\n stamped = PoseStamped()\n stamped.header.frame_id = \"base_link\"\n stamped.header.stamp = rospy.Time.now()\n stamped.pose = grasp\n self.marker_pub.publish(stamped)\n stamped.pose = approach\n self.marker_pub_app.publish(stamped)\n return 'done'\n\n def graspToPose(self, grasp):\n pose = Pose()\n pose.position = grasp.top\n\n yaw = math.atan2(grasp.approach.y, grasp.approach.x)\n distXY = (grasp.approach.x**2 + grasp.approach.y**2)**0.5\n pitch = -math.atan2(grasp.approach.z, distXY)\n\n approach = np.array([grasp.approach.x, grasp.approach.y, grasp.approach.z])\n approach /= (approach ** 2).sum() ** 0.5 # Get the unit vector\n binormal = np.array([grasp.binormal.x, grasp.binormal.y, grasp.binormal.z])\n binormal /= (binormal ** 2).sum() ** 0.5 # Get the unit vector\n\n binormal_ref_x = np.cross(np.array([0, 0, 1]), approach)\n binormal_ref_y = np.cross(binormal_ref_x, approach)\n roll = math.atan2(np.vdot(approach, binormal_ref_y), np.vdot(approach, binormal_ref_x)) * math.pi / 2\n\n # Transformation to quaternion for a Pose\n quat = quaternion_from_euler(roll, pitch, yaw, axes='sxyz')\n pose.orientation.x = quat[0]\n pose.orientation.y = quat[1]\n pose.orientation.z = quat[2]\n pose.orientation.w = quat[3]\n\n return pose\n\n def getGraspFromPointcloud(self, entity):\n\n Logger.loginfo(\"Selected entity : \" + str(entity.ID))\n Logger.loginfo(\n \"Current position : (\" + str(entity.position.x) + \", \" + str(\n entity.position.y) + \", \" + str(\n entity.position.x) + \")\")\n\n # Convert to Pointcloud and change frame of reference to base)link\n pointCloud = PointCloud()\n pointCloud.header = entity.pointcloud.header\n for p in point_cloud2.read_points(entity.pointcloud):\n point = Point32()\n point.x, point.y, point.z = [p[0], p[1], p[2]]\n pointCloud.points.append(point)\n pointCloud.header.stamp = rospy.Time.now() - rospy.Duration(1)\n self.listener.waitForTransform(pointCloud.header.frame_id, \"/base_link\", rospy.Time(0), rospy.Duration(10))\n pointCloud = self.listener.transformPointCloud(\"/base_link\", pointCloud)\n\n cloud = []\n for p in pointCloud.points:\n cloud.append([p.x, p.y, p.z])\n\n Logger.loginfo(\"Cloud size : \" + str(len(cloud)))\n\n # if len(cloud) > 0:\n cloud = np.asarray(cloud)\n X = cloud\n A = np.c_[X[:, 0], X[:, 1], np.ones(X.shape[0])]\n C, _, _, _ = lstsq(A, X[:, 2])\n a, b, c, d = C[0], C[1], -1., C[2] # coefficients of the form: a*x + b*y + c*z + d = 0.\n dist = ((a * X[:, 0] + b * X[:, 1] + d) - X[:, 2]) ** 2\n err = dist.sum()\n idx = np.where(dist > 0.01)\n\n msg = CloudIndexed()\n header = Header()\n header.frame_id = \"/base_link\"\n header.stamp = rospy.Time.now()\n msg.cloud_sources.cloud = point_cloud2.create_cloud_xyz32(header, cloud.tolist())\n msg.cloud_sources.view_points.append(Point(0, -0.5, 1.5))\n for i in xrange(cloud.shape[0]):\n msg.cloud_sources.camera_source.append(Int64(0))\n for i in idx[0]:\n msg.indices.append(Int64(i))\n # s = raw_input('Hit [ENTER] to publish')\n self.pub.publish(msg)\n\n i = 0\n\n ################################\n # Temporary setting a timeout\n while self.graspList == None:\n i = i + 1\n rospy.sleep(1)\n if i > 20:\n return self.getGraspWithoutPointcloud(entity)\n\n bestScore = 0\n bestGrasp = None\n # Normalisation des scores de grasp\n for grasp in self.graspList:\n if grasp.score.data > self.maxgraspScore:\n self.maxgraspScore = grasp.score.data\n\n for grasp in self.graspList:\n\n # Poses with a negative approach gets a negative multiplier\n if grasp.approach.z < 0: # Approche par le haut\n # poseScore = self.calculateGraspScore(pose)\n ref = [0.577350269, 0.577350269, -0.577350269]\n app = [grasp.approach.x, grasp.approach.y, grasp.approach.z]\n poseScore = np.dot(app, ref)\n rospy.loginfo(\"Total pose score (Positive approach): %s\", str(poseScore))\n\n if bestScore < poseScore:\n bestScore = poseScore\n bestGrasp = grasp\n\n if bestGrasp is not None:\n pose = self.graspToPose(bestGrasp)\n\n # Generate approach pose\n approach_pose = Pose()\n applength = np.linalg.norm([bestGrasp.approach.x, bestGrasp.approach.y, bestGrasp.approach.z])\n approach_pose.position.x = pose.position.x - bestGrasp.approach.x / applength * self.approachDistance\n approach_pose.position.y = pose.position.y - bestGrasp.approach.y / applength * self.approachDistance\n approach_pose.position.z = pose.position.z - bestGrasp.approach.z / applength * self.approachDistance\n approach_pose.orientation = pose.orientation\n\n return pose, approach_pose\n\n return self.getGraspWithoutPointcloud(entity)\n\n def getGraspWithoutPointcloud(self, entity):\n # verifie si on recoit une pose ou un point\n grasp = Pose()\n grasp.position = entity.position\n gripperX = 0\n gripperY = -0.5\n\n # calcul des angles\n yaw = math.atan2((grasp.position.y - gripperY), (grasp.position.x - gripperX))\n dist = ((grasp.position.y - gripperY) ** 2 + (grasp.position.x - gripperX) ** 2) ** 0.5\n pitch = 0\n\n # calcul du quaternion\n quat = quaternion_from_euler(0, pitch, yaw)\n self.quat = Quaternion()\n self.quat.x = quat[0]\n self.quat.y = quat[1]\n self.quat.z = quat[2]\n self.quat.w = quat[3]\n grasp.orientation = self.quat\n\n # calcul du vecteur dapproche avec les points\n dX = (gripperX - grasp.position.x)\n dY = (gripperY - grasp.position.y)\n length = (dX ** 2 + dY ** 2) ** 0.5\n dX *= self.approachDistance / length\n dY *= self.approachDistance / length\n\n # applique le vecteur dapproche\n approach = Pose()\n approach.position.x = grasp.position.x+dX\n approach.position.y = grasp.position.y+dY\n approach.position.z = grasp.position.z\n approach.orientation = self.quat\n\n return grasp, approach\n","sub_path":"sara_flexbe_states/src/sara_flexbe_states/GetGraspFromEntity.py","file_name":"GetGraspFromEntity.py","file_ext":"py","file_size_in_byte":9903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"402626408","text":"from datetime import datetime, timedelta\nfrom time import sleep\nimport quandl\nimport numpy as np\nimport pandas as pd\n\nimport requests\nimport json\n\n#quandl key#\nquandl.ApiConfig.api_key = 'Key'\n\n\ndef get_date_str(N):\n return str((datetime.now() + timedelta(days=N)).date())\n\n\n##quick check to see if the last available data was yesterday\ndef get_data(security, start_date, end_date):\n return quandl.get(\"WIKI/{}.11\".format(security), start_date=start_date, end_date=end_date)\n\n\ndef moving_average_df(ma, data):\n return pd.DataFrame(data['Adj. Close'].rolling(window=ma, center=False).mean().dropna())\n\n\ndef inner_join(df1, df2):\n return pd.concat([df1, df2], axis=1, join='inner')\n\n\ndef greater_crossover_columns(df, col1, col2):\n greater = []\n for s, l in zip(df.ix[:, col1], df.ix[:, col2]):\n if s > l:\n greater.append('Yes')\n else:\n greater.append('No')\n df['greater'] = greater\n\n crossover = []\n for a, b in zip(df.shift(1).greater, df.greater):\n if a == b:\n crossover.append('No')\n else:\n crossover.append('Yes')\n crossover[0] = 'No'\n df['crossover'] = crossover\n\n\ndef buy_sell_column(df):\n buy_sell = []\n for a, b in zip(df.greater, df.crossover):\n if a == 'No' and b == 'Yes':\n buy_sell.append('Sell')\n elif a == 'Yes' and b == 'Yes':\n buy_sell.append('Buy')\n else:\n buy_sell.append('Hold')\n df['buy_sell'] = buy_sell\n","sub_path":"mean_reversion.py","file_name":"mean_reversion.py","file_ext":"py","file_size_in_byte":1492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"517396155","text":"import speech_recognition as sr\r\nimport pygame as pg\r\nimport sqlite3\r\nfrom gtts import gTTS\r\nr = sr.Recognizer()\r\nm = sr.Microphone()\r\nc = 0\r\nch = 'y'\r\ntext2 = \"Do you want to continue? ( yes or no )\"\r\npg.mixer.init()\r\ndef play_music(music_file, volume=1.0):\r\n pg.mixer.music.set_volume(volume)\r\n pg.mixer.music.load(music_file)\r\n print(\"Music file {} loaded!\".format(music_file))\r\n clock = pg.time.Clock()\r\n pg.mixer.music.play()\r\n while pg.mixer.music.get_busy():\r\n clock.tick(30)\r\n #try:\r\n #except pg.error:\r\n #print(\"File {} not found! ({})\".format(music_file, pg.get_error()))\r\n return\r\ntry:\r\n print(\"A moment of silence, please...\")\r\n with m as source: r.adjust_for_ambient_noise(source)\r\n print(\"Set minimum energy threshold to {}\".format(r.energy_threshold))\r\n while (ch == 'y' or ch =='Y'):\r\n c = c + 1\r\n print(\"Please, say Patient name\")\r\n with m as source: audio = r.listen(source)\r\n print(\"Got it! Now to recognize it...\")\r\n try:\r\n value1 = r.recognize_google(audio)\r\n if str is bytes:\r\n print(u\"You said {}\".format(value1).encode(\"utf-8\"))\r\n else:\r\n print(\"You said {}\".format(value1))\r\n except sr.UnknownValueError:\r\n print(\"Oops! Didn't catch that\")\r\n except sr.RequestError as e:\r\n print(\"Uh oh! Couldn't request results from Google Speech Recognition service; {0}\".format(e))\r\n conn = sqlite3.connect('test.db')\r\n data = conn.execute(\"select * from vnist1 where Pname = '\" + value1 + \"'\")\r\n text =''\r\n if(value1 == 'quit'):\r\n text = \"bye\"\r\n print (text)\r\n speech = gTTS(text,'en')\r\n file = \"a\" + str(c) + \"gir.mp3\"\r\n speech.save(file)\r\n music_file = file\r\n volume = 0.8\r\n play_music(music_file, volume)\r\n break;\r\n for row in data:\r\n text = \"Patient name is \" + row[1] + \". The ward number is \" + str(row[3]) + \". The room number is \" + str(row[4])\r\n print (text)\r\n speech = gTTS(text,'en')\r\n file = \"a\" + str(c) + \"gir.mp3\"\r\n speech.save(file)\r\n\r\n music_file = file\r\n volume = 0.8\r\n play_music(music_file, volume)\r\n print(\"Do you want to know details of other patient:(y/n):\")\r\n ch = input()\r\n\r\nexcept KeyboardInterrupt:\r\n pass","sub_path":"finalVnist1.py","file_name":"finalVnist1.py","file_ext":"py","file_size_in_byte":2439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"570013980","text":"\"\"\"SQLAlchemy backend implementation.\"\"\"\n\nimport sys\n\nfrom oslo_config import cfg\nfrom oslo_db import options as db_options\nfrom oslo_db.sqlalchemy import session\nfrom oslo_db.sqlalchemy import utils as db_utils\nfrom oslo_log import log\n\nimport sqlalchemy.orm.exc as sa_exc\nfrom sqlalchemy.orm import with_polymorphic\n\nfrom craton.inventory import exceptions\nfrom craton.inventory.db.sqlalchemy import models\n\n\nCONF = cfg.CONF\n\nLOG = log.getLogger(__name__)\n\n\n_FACADE = None\n\n_DEFAULT_SQL_CONNECTION = 'sqlite://'\ndb_options.set_defaults(cfg.CONF,\n connection=_DEFAULT_SQL_CONNECTION)\n\n\ndef _create_facade_lazily():\n global _FACADE\n if _FACADE is None:\n _FACADE = session.EngineFacade.from_config(cfg.CONF)\n return _FACADE\n\n\ndef get_engine():\n facade = _create_facade_lazily()\n return facade.get_engine()\n\n\ndef get_session(**kwargs):\n facade = _create_facade_lazily()\n return facade.get_session(**kwargs)\n\n\ndef get_backend():\n \"\"\"The backend is this module itself.\"\"\"\n return sys.modules[__name__]\n\n\ndef is_admin_context(context):\n \"\"\"Check if this request had admin context.\"\"\"\n # FIXME(sulo): fix after we have Users table\n return True\n\n\ndef require_admin_context(f):\n \"\"\"Decorator that ensures admin request context.\"\"\"\n\n def wrapper(*args, **kwargs):\n if not is_admin_context(args[0]):\n raise exceptions.AdminRequired()\n return f(*args, **kwargs)\n return wrapper\n\n\ndef model_query(context, model, *args, **kwargs):\n \"\"\"Query helper that accounts for context's `read_deleted` field.\n :param context: context to query under\n :param model: model to query. Must be a subclass of ModelBase.\n :param session: if present, the session to use\n :param project_only: if present and context is user-type, then restrict\n query to match the context's project_id.\n \"\"\"\n session = kwargs.get('session') or get_session()\n project_only = kwargs.get('project_only')\n kwargs = dict()\n\n if project_only and not context.is_admin:\n kwargs['project_id'] = context.tenant\n\n return db_utils.model_query(\n model=model, session=session, args=args, **kwargs)\n\n\n###################\n# TODO(sulo): add filter on project_id and deleted fields\n\ndef cells_get_all(context, region):\n \"\"\"Get all cells.\"\"\"\n query = model_query(context, models.Cell, project_only=True)\n if region is not None:\n query = query.filter_by(region_id=region)\n\n try:\n return query.all()\n except sa_exc.NoResultFound:\n raise exceptions.NotFound()\n except Exception as err:\n raise exceptions.UnknownException(message=err)\n\n\ndef cells_get_by_name(context, region_id, cell_id):\n \"\"\"Get cell details given for a given cell in a region.\"\"\"\n try:\n query = model_query(context, models.Cell).\\\n filter_by(region_id=region_id).\\\n filter_by(name=cell_id)\n return query.one()\n except sa_exc.NoResultFound:\n raise exceptions.NotFound()\n\n\ndef cells_get_by_id(context, region_id, cell_id):\n \"\"\"Get cell details given for a given cell in a region.\"\"\"\n try:\n query = model_query(context, models.Cell).\\\n filter_by(region_id=region_id).\\\n filter_by(id=cell_id)\n return query.one()\n except sa_exc.NoResultFound:\n raise exceptions.NotFound()\n\n\ndef cells_create(context, values):\n \"\"\"Create a new cell.\"\"\"\n session = get_session()\n cell = models.Cell()\n with session.begin():\n cell.update(values)\n cell.save(session)\n return cell\n\n\ndef cells_update(context, cell_id, values):\n \"\"\"Update an existing cell.\"\"\"\n session = get_session()\n with session.begin():\n query = model_query(context, models.Cell, session=session,\n project_only=True)\n query = query.filter_by(id=cell_id)\n try:\n cell_ref = query.with_lockmode('update').one()\n except Exception:\n raise\n\n cell_ref.update(values)\n cell_ref.save(session)\n return cell_ref\n\n\ndef cells_delete(context, cell_id):\n \"\"\"Delete an existing cell.\"\"\"\n session = get_session()\n with session.begin():\n query = model_query(context, models.Cell, session=session,\n project_only=True)\n query = query.filter_by(id=cell_id)\n query.delete()\n\n\ndef cells_data_update(context, cell_id, data):\n \"\"\"Update existing cells variables or create when\n its not present.\n \"\"\"\n session = get_session()\n with session.begin():\n query = model_query(context, models.Cell, session=session,\n project_only=True)\n query = query.filter_by(id=cell_id)\n\n try:\n cell_ref = query.with_lockmode('update').one()\n except sa_exc.NoResultFound:\n # cell does not exist so cant do this\n raise\n\n for key in data:\n cell_ref.variables[key] = data[key]\n\n return cell_ref\n\n\ndef cells_data_delete(context, cell_id, data):\n \"\"\"Delete the existing key (variable) from cells data.\"\"\"\n session = get_session()\n with session.begin():\n query = model_query(context, models.Cell, session=session,\n project_only=True)\n query = query.filter_by(id=cell_id)\n\n try:\n cell_ref = query.with_lockmode('update').one()\n except sa_exc.NoResultFound:\n # cell does not exist so cant do this\n raise\n\n for key in data:\n try:\n del cell_ref.variables[data[key]]\n except KeyError:\n # This key does not exist so just ignore\n pass\n\n return cell_ref\n\n\ndef regions_get_all(context):\n \"\"\"Get all available regions.\"\"\"\n query = model_query(context, models.Region, project_only=True)\n try:\n return query.all()\n except sa_exc.NoResultFound:\n raise exceptions.NotFound()\n\n\ndef regions_get_by_name(context, name):\n \"\"\"Get cell detail for the region with given name.\"\"\"\n query = model_query(context, models.Region, project_only=True)\n query = query.filter_by(name=name)\n try:\n return query.one()\n except sa_exc.NoResultFound:\n raise exceptions.NotFound()\n\n\ndef regions_get_by_id(context, region_id):\n \"\"\"Get cell detail for the region with given id.\"\"\"\n query = model_query(context, models.Region, project_only=True)\n query = query.filter_by(id=region_id)\n try:\n return query.one()\n except sa_exc.NoResultFound:\n raise exceptions.NotFound()\n\n\ndef regions_create(context, values):\n \"\"\"Create a new region.\"\"\"\n session = get_session()\n region = models.Region()\n with session.begin():\n region.update(values)\n region.save(session)\n return region\n\n\ndef regions_update(context, region_id, values):\n \"\"\"Update an existing region.\"\"\"\n # We dont have anything to update right now\n pass\n\n\ndef regions_delete(context, region_id):\n \"\"\"Delete an existing region.\"\"\"\n session = get_session()\n with session.begin():\n query = model_query(context, models.Region, session=session,\n project_only=True)\n query = query.filter_by(id=region_id)\n query.delete()\n return\n\n\ndef regions_data_update(context, region_id, data):\n \"\"\"\n Update existing region variables or create when its not present.\n \"\"\"\n session = get_session()\n with session.begin():\n query = model_query(context, models.Region, session=session,\n project_only=True)\n query = query.filter_by(id=region_id)\n\n try:\n region_ref = query.with_lockmode('update').one()\n except sa_exc.NoResultFound:\n # region does not exist so cant do this\n raise\n\n for key in data:\n region_ref.variables[key] = data[key]\n\n return region_ref\n\n\ndef regions_data_delete(context, region_id, data):\n \"\"\"Delete the existing key (variable) from region data.\"\"\"\n session = get_session()\n with session.begin():\n query = model_query(context, models.Region, session=session,\n project_only=True)\n query = query.filter_by(id=region_id)\n\n try:\n region_ref = query.with_lockmode('update').one()\n except sa_exc.NoResultFound:\n # region does not exist so cant do this\n raise\n\n for key in data:\n try:\n del region_ref.variables[data[key]]\n except KeyError:\n # This key does not exist so just ignore\n pass\n\n return region_ref\n\n\ndef hosts_get_by_region(context, region_id, filters):\n \"\"\"Get all hosts for this region.\n\n :param region_id: ID for the region\n :param filters: filters wich contains differnt keys/values to match.\n Supported filters are by name, ip_address, id and cell_id.\n \"\"\"\n host_devices = with_polymorphic(models.Device, [models.Host])\n query = model_query(context, host_devices, project_only=True)\n query = query.filter_by(region_id=region_id)\n\n if \"name\" in filters:\n query = query.filter_by(name=filters[\"name\"])\n if \"ip_address\" in filters:\n query = query.filter_by(ip_address=filters[\"ip_address\"])\n if \"id\" in filters:\n query = query.filter_by(id=filters[\"id\"])\n if \"cell\" in filters:\n query = query.filter_by(cell_id=filters[\"cell\"])\n\n try:\n result = query.all()\n except sa_exc.NoResultFound:\n raise exceptions.NotFound()\n except Exception as err:\n raise exceptions.UnknownException(message=err)\n return result\n\n\ndef hosts_get_by_id(context, host_id):\n \"\"\"Get details for the host with given id.\"\"\"\n host_devices = with_polymorphic(models.Device, '*')\n query = model_query(context, host_devices, project_only=True).\\\n filter_by(id=host_id)\n try:\n result = query.one()\n LOG.info(\"Result by host id %s\" % result)\n except sa_exc.NoResultFound:\n LOG.error(\"No result found for host with id %s\" % host_id)\n raise exceptions.NotFound()\n except Exception as err:\n raise exceptions.UnknownException(message=err)\n return result\n\n\ndef hosts_create(context, values):\n \"\"\"Create a new host.\"\"\"\n session = get_session()\n host = models.Host()\n with session.begin():\n host.update(values)\n host.save(session)\n return host\n\n\ndef hosts_update(context, host_id, values):\n \"\"\"Update an existing host.\"\"\"\n return None\n\n\ndef hosts_delete(context, host_id):\n \"\"\"Delete an existing host.\"\"\"\n session = get_session()\n with session.begin():\n host_devices = with_polymorphic(models.Device, '*')\n query = model_query(context, host_devices, session=session,\n project_only=True)\n query = query.filter_by(id=host_id)\n query.delete()\n return\n\n\ndef hosts_data_update(context, host_id, data):\n \"\"\"\n Update existing host variables or create when its not present.\n \"\"\"\n session = get_session()\n with session.begin():\n host_devices = with_polymorphic(models.Device, '*')\n query = model_query(context, host_devices, session=session,\n project_only=True)\n query = query.filter_by(id=host_id)\n\n try:\n host_ref = query.with_lockmode('update').one()\n except sa_exc.NoResultFound:\n raise exceptions.NotFound()\n\n for key in data:\n host_ref.variables[key] = data[key]\n\n return host_ref\n\n\ndef hosts_data_delete(context, host_id, data):\n \"\"\"Delete the existing key (variable) from region data.\"\"\"\n session = get_session()\n with session.begin():\n host_devices = with_polymorphic(models.Device, '*')\n query = model_query(context, host_devices, session=session,\n project_only=True)\n query = query.filter_by(id=host_id)\n\n try:\n host_ref = query.with_lockmode('update').one()\n except sa_exc.NoResultFound:\n raise exceptions.NotFound()\n\n for key in data:\n try:\n del host_ref.variables[data[key]]\n except KeyError:\n pass\n\n return host_ref\n","sub_path":"craton/inventory/db/sqlalchemy/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":12304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"278141383","text":"# Matthew Fischer\n# Project 1\n\nnums = [1,2,3,4,5]\n\nfrontProduct = [0,0,0,0,0]\nbackProduct = [0,0,0,0,0]\n\n# array frontward product\nfor i in range(0,len(nums)):\n sum = 1\n for j in range(0,i+1):\n sum *= nums[j]\n frontProduct[i] = sum\n\n# array backward product\nfor i in range(len(nums)-1,-1,-1):\n sum = 1\n for j in range(len(nums)-1,i-1,-1):\n sum *= nums[j]\n backProduct[i] = sum \n \n# new array of products\nproductArr = [1,1,1,1,1]\nfor i in range(0,len(productArr)):\n #left marker\n if i > 0:\n productArr[i] *= frontProduct[i-1]\n # right marker\n if i < 4:\n productArr[i] *= backProduct[i+1]\n\nprint(frontProduct)\nprint(backProduct)\nprint(\"Product except position\")\nprint(productArr)\n\n#------OutPut--------\n#PS C:\\Users\\Matthew Fischer\\Documents\\Python\\Python> & C:/Python27/python.exe \"c:/Users/Matthew Fischer/Documents/Python/CS240/Program#1.py\"\n#Product except position\n#[120, 60, 40, 30, 24]\n#PS C:\\Users\\Matthew Fischer\\Documents\\Python\\Python>\n#--------------------","sub_path":"Program#1.py","file_name":"Program#1.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"273397597","text":"#!/env/python\n\nclass Expense:\n def __init__(self, name, amount, subj_justified, obj_justified):\n self.name = name # Name\n self.when = when # date, and time if appropriate. I will have to look into datetime to sort out formats.\n self.amount = amount # tuple of float amount + str currency\n self.subj_justified = subj_justified # Was it a justified expense\n self.obj_justified = obj_justified # Blanka decides if it was justified\n self.extra = extra # extra attributes. I don't yet know if this is necessary ie. if these can be determined by a call comparable to [B]ooks.keys(), it isn't.\n def display(self):\n print(str(self.name))\n \n# The display section will have to be rewritten to account for those tags and contexts which are not lists etc., and to add commas for those which are.\n\n\n\nwrite = Goal(\"Write works of fiction\", seniority = 20, relative_placement = 1, consistency = 1)\n\nfit = Goal(\"Get and maintain a high-level of fitness\", seniority = 20, consistency = 0.2)\n\nprint(\"\\n\")\nwrite.display()\nprint(\"\\n\")\nfit.display()\n\ngoal_attributes = {}\n\n\"\"\"\n\nbook_items = {\"cost\": {\"help\": \"a tuple containing an int or float followed by a string containing the currency\", \"form\":\n[\"int\", \"float\"]}, \"intlnk\": {\"help\": \"a dictionary object containing internal links and, optionally, tags\", \"form\": \"dict\"}} # what is the name for the items?\n\n\"\"\"\n","sub_path":"Code/Blanka/Classes_expenses.py","file_name":"Classes_expenses.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"304215605","text":"#!/usr/bin/env python\n\nimport base\nimport readers\ntry:\n import numpy as np\nexcept:\n import mynumpy as np\nimport os.path\nimport sys\n\nif len(sys.argv) < 3:\n base.Logger.log(\"Usage is %s configuration topology [output] [fixcm]\" % sys.argv[0], base.Logger.CRITICAL)\n sys.exit()\n\nif len(sys.argv) > 3:\n output = sys.argv[3]\nelse: output = sys.argv[1] + \".xyz\"\n\nfixcm = False\nif len(sys.argv) > 4:\n if sys.argv[4] == \"fixcm\":\n fixcm = True\n\nl = readers.LorenzoReader(sys.argv[1], sys.argv[2])\ns = l.get_system()\nappend = False\nniter = 1\nwhile s:\n base.Logger.log(\"Working on conf %i...\" % niter, base.Logger.INFO)\n\n # set center of mass to strand 0\n if fixcm:\n base.Logger.log(\"setting centre of mass to strand 0\", base.Logger.INFO)\n centre_of_mass = np.array([0.,0.,0.])\n n_nucleotides = 0\n for nucleotide in s._strands[0]._nucleotides:\n centre_of_mass += nucleotide.cm_pos\n n_nucleotides += 1\n centre_of_mass /= float(n_nucleotides)\n ## Split into single frame ## Added by ZYC @ 2017-05-25 13.52.36\n\n for strand in s._strands:\n strand.translate (-centre_of_mass)\n\n s.print_vmd_xyz_output(output, append=append, same_colors=True, visibility = \"caca.vis\")\n s = l.get_system()\n append = True\n niter += 1\n\n\nif niter < 2:\n base.Logger.log (\"Dind't do anything...\")\nelse:\n base.Logger.log(\"Output printed on '%s'\" % output, base.Logger.INFO)\n\n","sub_path":"UTILS/traj2xyz.py","file_name":"traj2xyz.py","file_ext":"py","file_size_in_byte":1467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"612660367","text":"# Copyright 2019-2021 Siemens AG\n# SPDX-License-Identifier: MIT\n\nimport json\nimport time\nimport logging\n\nfrom tenacity import retry, retry_if_exception_type, stop_after_attempt, TryAgain\nfrom fossology.obj import Upload, Summary, Licenses, get_options\nfrom fossology.exceptions import AuthorizationError, FossologyApiError\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\n\nclass Uploads:\n \"\"\"Class dedicated to all \"uploads\" related endpoints\"\"\"\n\n # Retry until the unpack agent is finished\n @retry(retry=retry_if_exception_type(TryAgain), stop=stop_after_attempt(10))\n def detail_upload(\n self, upload_id: int, group: str = None, wait_time: int = 0\n ) -> Upload:\n \"\"\"Get detailled information about an upload\n\n API Endpoint: GET /uploads/{id}\n\n Get information about a given upload. If the upload is not ready wait another ``wait_time`` seconds or look at\n the ``Retry-After`` to determine how long the wait period shall be.\n\n If ``wait_time`` is 0, the time interval specified by the ``Retry-After`` header is used.\n\n The function stops trying after **10 attempts**.\n\n :Examples:\n\n >>> # Wait up to 20 minutes until the upload is ready\n >>> long_upload = detail_upload(1, 120)\n\n >>> # Wait up to 5 minutes until the upload is ready\n >>> long_upload = detail_upload(1, 30)\n\n :param upload_id: the id of the upload\n :param group: the group the upload shall belong to\n :param wait_time: use a customized upload wait time instead of Retry-After (in seconds, default: 0)\n :type upload_id: int\n :type group: string\n :type wait_time: int\n :return: the upload data\n :rtype: Upload\n :raises FossologyApiError: if the REST call failed\n :raises AuthorizationError: if the user can't access the group\n \"\"\"\n headers = {}\n if group:\n headers[\"groupName\"] = group\n response = self.session.get(f\"{self.api}/uploads/{upload_id}\", headers=headers)\n\n if response.status_code == 200:\n logger.debug(f\"Got details for upload {upload_id}\")\n return Upload.from_json(response.json())\n\n elif response.status_code == 403:\n description = f\"Getting details for upload {upload_id} {get_options(group)}not authorized\"\n raise AuthorizationError(description, response)\n\n elif response.status_code == 503:\n if not wait_time:\n wait_time = response.headers[\"Retry-After\"]\n logger.debug(\n f\"Retry GET upload {upload_id} after {wait_time} seconds: {response.json()['message']}\"\n )\n time.sleep(int(wait_time))\n raise TryAgain\n\n else:\n description = f\"Error while getting details for upload {upload_id}\"\n raise FossologyApiError(description, response)\n\n def upload_file( # noqa: C901\n self,\n folder,\n file=None,\n vcs=None,\n url=None,\n description=None,\n access_level=None,\n ignore_scm=False,\n group=None,\n wait_time=0,\n ):\n \"\"\"Upload a package to FOSSology\n\n API Endpoint: POST /uploads\n\n Perform a file, VCS or URL upload and get information about the upload using :func:`~fossology.uploads.Uploads.detail_upload` and passing the ``wait_time`` argument.\n\n See description of :func:`~fossology.uploads.Uploads.detail_upload` to configure how long the client shall wait for the upload to be ready.\n\n :Example for a file upload:\n\n >>> from fossology import Fossology\n >>> from fossology.obj import AccessLevel\n >>> foss = Fossology(FOSS_URL, FOSS_TOKEN, username)\n >>> my_upload = foss.upload_file(\n foss.rootFolder,\n file=\"my-package.zip\",\n description=\"My product package\",\n access_level=AccessLevel.PUBLIC,\n )\n\n :Example for a VCS upload:\n\n >>> vcs = {\n \"vcsType\": \"git\",\n \"vcsUrl\": \"https://github.com/fossology/fossology-python\",\n \"vcsName\": \"fossology-python-github-master\",\n \"vcsUsername\": \"\",\n \"vcsPassword\": \"\",\n }\n >>> vcs_upload = foss.upload_file(\n foss.rootFolder,\n vcs=vcs,\n description=\"Upload from VCS\",\n access_level=AccessLevel.PUBLIC,\n )\n\n :Example for a URL upload:\n\n >>> url = {\n \"url\": \"https://github.com/fossology/fossology-python/archive/master.zip\",\n \"name\": \"fossology-python-master.zip\",\n \"accept\": \"zip\",\n \"reject\": \"\",\n \"maxRecursionDepth\": \"1\",\n }\n >>> url_upload = foss.upload_file(\n foss.rootFolder,\n url=url,\n description=\"Upload from URL\",\n access_level=AccessLevel.PUBLIC,\n )\n\n :param folder: the upload Fossology folder\n :param file: the local path of the file to be uploaded\n :param vcs: the VCS specification to upload from an online repository\n :param url: the URL specification to upload from a url\n :param description: description of the upload (default: None)\n :param access_level: access permissions of the upload (default: protected)\n :param ignore_scm: ignore SCM files (Git, SVN, TFS) (default: True)\n :param group: the group name to chose while uploading the file (default: None)\n :param wait_time: use a customized upload wait time instead of Retry-After (in seconds, default: 0)\n :type folder: Folder\n :type file: string\n :type vcs: dict()\n :type url: dict()\n :type description: string\n :type access_level: AccessLevel\n :type ignore_scm: boolean\n :type group: string\n :type wait_time: int\n :return: the upload data\n :rtype: Upload\n :raises FossologyApiError: if the REST call failed\n :raises AuthorizationError: if the user can't access the group\n \"\"\"\n headers = {\"folderId\": str(folder.id)}\n if description:\n headers[\"uploadDescription\"] = description\n if access_level:\n headers[\"public\"] = access_level.value\n if ignore_scm:\n headers[\"ignoreScm\"] = \"false\"\n if group:\n headers[\"groupName\"] = group\n\n if file:\n headers[\"uploadType\"] = \"server\"\n with open(file, \"rb\") as fp:\n files = {\"fileInput\": fp}\n response = self.session.post(\n f\"{self.api}/uploads\", files=files, headers=headers\n )\n elif vcs or url:\n if vcs:\n headers[\"uploadType\"] = \"vcs\"\n data = json.dumps(vcs)\n else:\n headers[\"uploadType\"] = \"url\"\n data = json.dumps(url)\n headers[\"Content-Type\"] = \"application/json\"\n response = self.session.post(\n f\"{self.api}/uploads\", data=data, headers=headers\n )\n else:\n logger.info(\n \"Neither VCS, or Url or filename option given, not uploading anything\"\n )\n return\n\n if file:\n source = f\"{file}\"\n elif vcs:\n source = vcs.get(\"vcsName\")\n else:\n source = url.get(\"name\")\n\n if response.status_code == 201:\n try:\n upload = self.detail_upload(response.json()[\"message\"], wait_time)\n logger.info(\n f\"Upload {upload.uploadname} ({upload.hash.size}) \"\n f\"has been uploaded on {upload.uploaddate}\"\n )\n return upload\n except TryAgain:\n description = f\"Upload of {source} failed\"\n raise FossologyApiError(description, response)\n\n elif response.status_code == 403:\n description = (\n f\"Upload of {source} {get_options(group, folder)}not authorized\"\n )\n raise AuthorizationError(description, response)\n\n else:\n description = f\"Upload {description} could not be performed\"\n raise FossologyApiError(description, response)\n\n @retry(retry=retry_if_exception_type(TryAgain), stop=stop_after_attempt(3))\n def upload_summary(self, upload, group=None):\n \"\"\"Get clearing information about an upload\n\n API Endpoint: GET /uploads/{id}/summary\n\n :param upload: the upload to gather data from\n :param group: the group name to chose while accessing an upload (default: None)\n :type: Upload\n :type group: string\n :return: the upload summary data\n :rtype: Summary\n :raises FossologyApiError: if the REST call failed\n :raises AuthorizationError: if the user can't access the group\n \"\"\"\n headers = {}\n if group:\n headers[\"groupName\"] = group\n response = self.session.get(\n f\"{self.api}/uploads/{upload.id}/summary\", headers=headers\n )\n\n if response.status_code == 200:\n return Summary.from_json(response.json())\n\n elif response.status_code == 403:\n description = f\"Getting summary of upload {upload.id} {get_options(group)}not authorized\"\n raise AuthorizationError(description, response)\n\n elif response.status_code == 503:\n logger.debug(\n f\"Unpack agent for {upload.uploadname} (id={upload.id}) didn't start yet\"\n )\n time.sleep(3)\n raise TryAgain\n else:\n description = f\"No summary for upload {upload.uploadname} (id={upload.id})\"\n raise FossologyApiError(description, response)\n\n @retry(retry=retry_if_exception_type(TryAgain), stop=stop_after_attempt(3))\n def upload_licenses(self, upload, group: str = None, agent=None, containers=False):\n \"\"\"Get clearing information about an upload\n\n API Endpoint: GET /uploads/{id}/licenses\n\n The response does not generate Python objects yet, the plain JSON data is simply returned.\n\n :param upload: the upload to gather data from\n :param agent: the license agents to use (e.g. \"nomos,monk,ninka,ojo,reportImport\", default: \"nomos\")\n :param containers: wether to show containers or not (default: False)\n :param group: the group name to chose while accessing the upload (default: None)\n :type upload: Upload\n :type agent: string\n :type containers: boolean\n :type group: string\n :return: the list of licenses findings for the specified agent\n :rtype: list of Licenses\n :raises FossologyApiError: if the REST call failed\n :raises AuthorizationError: if the user can't access the group\n \"\"\"\n headers = {}\n params = {}\n headers = {}\n if group:\n headers[\"groupName\"] = group\n if agent:\n params[\"agent\"] = agent\n else:\n params[\"agent\"] = agent = \"nomos\"\n if containers:\n params[\"containers\"] = \"true\"\n if group:\n headers[\"groupName\"] = group\n\n response = self.session.get(\n f\"{self.api}/uploads/{upload.id}/licenses\", params=params, headers=headers\n )\n\n if response.status_code == 200:\n all_licenses = []\n scanned_files = response.json()\n for file_with_findings in scanned_files:\n file_licenses = Licenses.from_json(file_with_findings)\n all_licenses.append(file_licenses)\n return all_licenses\n\n elif response.status_code == 403:\n description = f\"Getting license for upload {upload.id} {get_options(group)}not authorized\"\n raise AuthorizationError(description, response)\n\n elif response.status_code == 412:\n description = f\"Unable to get licenses from {agent} for {upload.uploadname} (id={upload.id})\"\n raise FossologyApiError(description, response)\n\n elif response.status_code == 503:\n logger.debug(\n f\"Unpack agent for {upload.uploadname} (id={upload.id}) didn't start yet\"\n )\n time.sleep(3)\n raise TryAgain\n\n else:\n description = f\"No licenses for upload {upload.uploadname} (id={upload.id})\"\n raise FossologyApiError(description, response)\n\n def delete_upload(self, upload, group=None):\n \"\"\"Delete an upload\n\n API Endpoint: DELETE /uploads/{id}\n\n :param upload: the upload to be deleted\n :param group: the group name to chose while deleting the upload (default: None)\n :type upload: Upload\n :type group: string\n :raises FossologyApiError: if the REST call failed\n :raises AuthorizationError: if the user can't access the group\n \"\"\"\n headers = {}\n if group:\n headers[\"groupName\"] = group\n response = self.session.delete(\n f\"{self.api}/uploads/{upload.id}\", headers=headers\n )\n\n if response.status_code == 202:\n logger.info(f\"Upload {upload.id} has been scheduled for deletion\")\n\n elif response.status_code == 403:\n description = (\n f\"Deleting upload {upload.id} {get_options(group)}not authorized\"\n )\n raise AuthorizationError(description, response)\n\n else:\n description = f\"Unable to delete upload {upload.id}\"\n raise FossologyApiError(description, response)\n\n def list_uploads(\n self, folder=None, group=None, recursive=True, page_size=20, page=1\n ):\n \"\"\"Get all uploads available to the registered user\n\n API Endpoint: GET /uploads\n\n :param folder: only list uploads from the given folder\n :param group: list uploads from a specific group (not only your own uploads) (default: None)\n :param recursive: wether to list uploads from children folders or not (default: True)\n :param page_size: limit the number of uploads per page (default: 20)\n :param page: the number of the page to fetch uploads from (default: 1)\n :type folder: Folder\n :type group: string\n :type recursive: boolean\n :type page_size: int\n :type page: int\n :return: a list of uploads\n :rtype: list of Upload\n :raises FossologyApiError: if the REST call failed\n :raises AuthorizationError: if the user can't access the group\n \"\"\"\n params = {}\n headers = {\"limit\": str(page_size), \"page\": str(page)}\n if group:\n headers[\"groupName\"] = group\n if folder:\n params[\"folderId\"] = folder.id\n if not recursive:\n params[\"recursive\"] = \"false\"\n\n response = self.session.get(\n f\"{self.api}/uploads\", headers=headers, params=params\n )\n\n if response.status_code == 200:\n uploads_list = list()\n for upload in response.json():\n uploads_list.append(Upload.from_json(upload))\n logger.info(\n f\"Retrieved page {page} of uploads, {response.headers.get('X-TOTAL-PAGES', 'Unknown')} pages are in total available\"\n )\n return uploads_list\n\n elif response.status_code == 403:\n description = (\n f\"Retrieving list of uploads {get_options(group, folder)}not authorized\"\n )\n raise AuthorizationError(description, response)\n\n else:\n description = \"Unable to retrieve the list of uploads\"\n raise FossologyApiError(description, response)\n\n def move_upload(self, upload, folder, group=None):\n \"\"\"Move an upload to another folder\n\n API Endpoint: PATCH /uploads/{id}\n\n :param upload: the Upload to be copied in another folder\n :param folder: the destination Folder\n :param group: the group name to chose while changing the upload (default: None)\n :type upload: Upload\n :type folder: Folder\n :type group: string\n :raises FossologyApiError: if the REST call failed\n :raises AuthorizationError: if the user can't access the group or folder\n \"\"\"\n headers = {\"folderId\": str(folder.id)}\n if group:\n headers[\"groupName\"] = group\n response = self.session.patch(\n f\"{self.api}/uploads/{upload.id}\", headers=headers\n )\n\n if response.status_code == 202:\n logger.info(f\"Upload {upload.uploadname} has been moved to {folder.name}\")\n\n elif response.status_code == 403:\n description = (\n f\"Moving upload {upload.id} {get_options(group, folder)}not authorized\"\n )\n raise AuthorizationError(description, response)\n\n else:\n description = f\"Unable to move upload {upload.uploadname} to {folder.name}\"\n raise FossologyApiError(description, response)\n\n def copy_upload(self, upload, folder):\n \"\"\"Copy an upload in another folder\n\n API Endpoint: PUT /uploads/{id}\n\n :param upload: the Upload to be copied in another folder\n :param folder: the destination Folder\n :type upload: Upload\n :type folder: Folder\n :raises FossologyApiError: if the REST call failed\n \"\"\"\n headers = {\"folderId\": str(folder.id)}\n response = self.session.put(f\"{self.api}/uploads/{upload.id}\", headers=headers)\n\n if response.status_code == 202:\n logger.info(f\"Upload {upload.uploadname} has been copied to {folder.name}\")\n\n elif response.status_code == 403:\n description = f\"Copy upload {upload.id} {get_options(folder)}not authorized\"\n raise AuthorizationError(description, response)\n\n else:\n description = f\"Unable to copy upload {upload.uploadname} to {folder.name}\"\n raise FossologyApiError(description, response)\n","sub_path":"fossology/uploads.py","file_name":"uploads.py","file_ext":"py","file_size_in_byte":18176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"520249458","text":"import pyperclip, detectEnglish, transpositionDecrypt\n\ndef main():\n filename = input('input the filename to be hacked:')\n inputFile = open(filename)\n myMessage = inputFile.read()\n inputFile.close()\n\n hackedMessage = hackTransposition(myMessage)\n\n if hackedMessage == None:\n print('Fail to hack encryption')\n\n else:\n print(hackedMessage[:200])\n outputFile = open(\"%s.decrypt.txt\" % (filename) , 'w')\n outputFile.write(hackedMessage)\n outputFile.flush()\n outputFile.close()\n\ndef hackTransposition(message):\n print('hacking...')\n\n for key in range(1,len(message)):\n print('Tryint key #%s...' % (key))\n\n decryptText = transpositionDecrypt.decryptMessage(key, message)\n\n if detectEnglish.isEnglish(decryptText):\n print()\n print('possible encryption hack:')\n print('Key %s: %s' % (key, decryptText[:100]))\n print()\n print('Enter D for done, or just Press Enter to continue hacking:')\n response = input('>')\n\n # strip is to remove whitespace in a string \n if response.strip().upper().startswith('D'):\n return decryptText\n\n return None\n\nif __name__ == '__main__':\n main()\n","sub_path":"cryptography/jiaocheng/transpositionHacker.py","file_name":"transpositionHacker.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"36434261","text":"import itchat\nimport re\nimport time\nfrom DecryptLogin import login\nfrom playsound import playsound\n\n'''微博监控'''\n\n\nclass MessageHandler:\n def handleMessage(message):\n print(message)\n\n\nclass wbMonitor():\n def __init__(self, username, password, time_interval=30, handler=MessageHandler(), **kwargs):\n _, self.session = login.Login().weibo(username, password, 'scanqr')\n self.headers = {\n 'Accept': 'application/json, text/plain, */*',\n 'Accept-Encoding': 'gzip, deflate, br',\n 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',\n 'Connection': 'keep-alive',\n 'Host': 'm.weibo.cn',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'\n }\n self.api_url = 'https://m.weibo.cn/api/container/getIndex?uid={}&luicode=10000011&lfid=231093_-_selffollowed&type=uid&value={}&containerid={}'\n self.format_profile_url = 'https://m.weibo.cn/u/{}?uid={}&luicode=10000011&lfid=231093_-_selffollowed'\n self.time_interval = time_interval\n self.handler = handler\n\n '''开始监控'''\n\n def start(self, user_id=None):\n if not user_id:\n followed = self.getFollowed()\n print('未指定想要监控的用户ID, 您关注的用户有:\\n(是否想选择其中一位进行监控?)')\n print('-' * 40)\n for idx, each in enumerate(sorted(followed.keys())):\n print('[%d]. %s' % (idx + 1, each))\n print('-' * 40)\n while True:\n user_choice = input('请选择您想要监控的用户编号(例如1):')\n try:\n profile_url = followed[sorted(followed.keys())[int(user_choice) - 1]]\n user_id = re.findall(r'uid=(\\d+)&', profile_url)[0]\n break\n except:\n print('您的输入有误, 请重新输入.')\n else:\n profile_url = self.format_profile_url.format(user_id, user_id)\n self.monitor(user_id, profile_url)\n\n '''监控用户主页'''\n\n def monitor(self, user_id, profile_url):\n user_name, containerid = self.getContainerid(user_id, profile_url)\n res = self.session.get(self.api_url.format(user_id, user_id, containerid))\n weibo_ids = []\n cards = res.json()['data']['cards']\n for card in cards:\n if card['card_type'] == 9:\n weibo_ids.append(str(card['mblog']['id']))\n while True:\n result = self.checkUpdate(user_id, profile_url, weibo_ids)\n if len(result) == 0:\n print(\"empty update array\\n\")\n time.sleep(60)\n else:\n weibo_ids = result\n time.sleep(self.time_interval)\n\n '''检查用户是否有新的微博'''\n\n def checkUpdate(self, user_id, profile_url, weibo_ids):\n try:\n user_name, containerid = self.getContainerid(user_id, profile_url)\n if containerid == -1:\n return []\n res = self.session.get(self.api_url.format(user_id, user_id, containerid))\n resJson = res.json();\n if \"data\" in resJson:\n data = res.json()['data']\n if \"cards\" in data:\n cards = res.json()['data']['cards']\n flag = False\n for card in cards:\n if card['card_type'] == 9:\n if str(card['mblog']['id']) not in weibo_ids:\n flag = True\n weibo_ids.append(str(card['mblog']['id']))\n print(str(time.strftime('%Y-%m-%d %H:%M:%S',\n time.localtime(time.time()))) + ': 用户<%s>发布了新微博' % user_name)\n pics = []\n if card['mblog'].get('pics'):\n for i in card['mblog']['pics']:\n pics.append(i['url'])\n pics = '||'.join(pics)\n message = ('[时间]: %s\\n[来源]: %s\\n[原文作者]: %s\\n[内容]: %s\\n[图片链接]: %s\\n' %\n (card['mblog']['created_at'], card['mblog']['source'],\n card['mblog']['user']['screen_name'], card['mblog']['text'], pics))\n self.handler.handleMessage(message)\n else:\n print(\"not contains cards\\n\")\n print(res.text + \"\\n\")\n else:\n print(\"not contains data\\n\")\n print(res.text + \"\\n\")\n return []\n if not flag:\n print(\n str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))) + ': 用户<%s>未发布新微博' % user_name)\n return weibo_ids\n except Exception as e:\n print(e)\n print(\"异常\")\n return []\n\n '''获取containerid'''\n\n def getContainerid(self, user_id, profile_url):\n self.session.get(profile_url)\n containerid = re.findall(r'fid%3D(\\d+)%26', str(self.session.cookies))[0]\n res = self.session.get(self.api_url.format(user_id, user_id, containerid))\n user_name = self.decode(re.findall(r'\"screen_name\":\"(.*?)\"', res.text)[0])\n # print(\"res:\" + res.text)\n data = res.json()['data']\n if \"tabsInfo\" in data:\n for i in res.json()['data']['tabsInfo']['tabs']:\n if i['tab_type'] == 'weibo':\n containerid = i['containerid']\n else:\n containerid = -1\n print(\"not contains tabsInfo\\n\")\n print(res.text + \"\\n\")\n return user_name, containerid\n\n '''获取关注列表'''\n\n def getFollowed(self):\n data = {}\n page = 0\n while True:\n page += 1\n res = self.session.get(\n 'https://m.weibo.cn/api/container/getIndex?containerid=231093_-_selffollowed&page={}'.format(page),\n headers=self.headers)\n profile_urls = re.findall(r'\"profile_url\":\"(.*?)\"', res.text)\n screen_names = re.findall(r'\"screen_name\":\"(.*?)\"', res.text)\n if len(profile_urls) == 0:\n break\n for screen_name, profile_url in zip(screen_names, profile_urls):\n data[self.decode(screen_name)] = profile_url.replace('\\\\', '')\n return data\n\n '''解码'''\n\n def decode(self, content):\n return content.encode('latin-1').decode('unicode_escape')\n\n\nclass WeChatHandler(MessageHandler):\n def __init__(self, open=0, roomName=\"wu2198\"):\n self.open = open\n self.chatRoom = None\n self.roomName = roomName\n print(\"wechat open:\" + str(open))\n if open == 1:\n itchat.auto_login(hotReload=True)\n rooms = itchat.search_chatrooms(name=roomName)\n if len(rooms) == 0:\n print(\"no chat room named:\" + roomName)\n else:\n self.chatRoom = rooms[0]\n\n def handleMessage(self, message):\n print(message)\n playsound(\"sound.mp3\")\n if self.chatRoom:\n self.chatRoom.send(message)\n\n\n'''run'''\nif __name__ == '__main__':\n import argparse\n\n parser = argparse.ArgumentParser(description=\"微博监控\")\n parser.add_argument('-u', dest='username', help='用户名')\n parser.add_argument('-p', dest='password', help='密码')\n parser.add_argument('-i', dest='id', help='待监控用户id')\n parser.add_argument('-t', dest='time_interval', default=30, type=int, help='监控的时间间隔')\n parser.add_argument('-wechat', dest='open_wechat', default=False, type=int)\n parser.add_argument('-roomName', dest='room_name', default=\"wu2198\")\n args = parser.parse_args()\n if args.username and args.password:\n messageHandler = WeChatHandler(open=args.open_wechat, roomName=args.room_name)\n wb = wbMonitor(username=args.username, password=args.password, time_interval=args.time_interval,\n handler=messageHandler)\n wb.start(args.id)\n","sub_path":"WeiboMonitor.py","file_name":"WeiboMonitor.py","file_ext":"py","file_size_in_byte":8350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"295694413","text":"# -*- coding: utf-8 -*-\nfrom odoo import models, fields, api,exceptions,tools,_\nfrom odoo.exceptions import UserError\ndef return_form_action(self):\n return {\n 'type': 'ir.actions.act_window',\n 'res_model': 'setaction.setaction',\n 'view_mode': 'form',\n 'view_type': 'form',\n 'res_id': self.id,\n# 'context':{'active_model':self.model, 'function_key': self.function_key},\n 'views': [(False, 'form')],\n 'target': 'new',\n }\ndef return_form_action_decorator(func):\n def wrapper(*args,**kargs):\n self = args[0]\n# default_loai_record = self._context\n# print ('**********default_loai_record,', default_loai_record)\n# print ('**********default_loai_record,', default_loai_record.get('default_loai_record'))\n# if default_loai_record.get('default_loai_record') != u'Công Việc':\n# raise UserError(u'Không phải công việc không sử dụng chức năng multi này')\n func(*args,**kargs)\n return return_form_action(self)\n return wrapper\n\nclass Setaction(models.TransientModel):\n _inherit = \"setaction.setaction\"\n @api.multi\n @return_form_action_decorator\n def multi_confirmed(self):\n active_ids = self._context.get('active_ids')\n self.choosed_object_qty = len(active_ids)\n if active_ids:\n affected_count = 0\n for r in self.env['cvi'].browse(active_ids):\n if r.state in ['draft'] and not r.cam_sua:\n affected_count +=1\n r.state = 'confirmed'\n self.affected_object_qty = affected_count\n else:\n raise UserError (u'Bạn chưa chọn dòng nào')\n return return_form_action(self)\n \n @api.multi\n @return_form_action_decorator\n def multi_approved(self):\n active_ids = self._context.get('active_ids')\n self.choosed_object_qty = len(active_ids)\n if active_ids:\n affected_count = 0\n for r in self.env['cvi'].browse(active_ids):\n if r.is_sep and r.state in ['confirmed']:\n affected_count +=1\n r.state = 'approved'\n else:\n raise UserError (u'Bạn không phải là lãnh đạo của nhân viên tạo record này hoặc trạng thái chưa phải là confirm')\n self.affected_object_qty = affected_count\n else:\n raise UserError (u'Bạn chưa chọn dòng nào')\n return return_form_action(self)\n @api.multi\n @return_form_action_decorator\n def multi_draft(self):\n active_ids = self._context.get('active_ids')\n self.choosed_object_qty = len(active_ids)\n if active_ids:\n affected_count = 0\n for r in self.env['cvi'].browse(active_ids):\n state = r.state\n if (state in ['mark_delete','confirmed'] and not r.cam_sua_do_diff_user) or (state =='approved' and r.is_sep) :\n affected_count +=1\n r.state = 'draft'\n self.affected_object_qty = affected_count\n else:\n raise UserError (u'Bạn chưa chọn dòng nào')\n# return return_form_action(self)\n @api.multi\n @return_form_action_decorator\n def multi_mark_delete(self):\n active_ids = self._context.get('active_ids')\n self.choosed_object_qty = len(active_ids)\n if active_ids:\n affected_count = 0\n for r in self.env['cvi'].browse(active_ids):\n state = r.state\n if state in ['draft'] and not r.cam_sua_do_diff_user:\n affected_count +=1\n r.state = 'mark_delete'\n self.affected_object_qty = affected_count\n else:\n raise UserError (u'Bạn chưa chọn dòng nào')\n# return return_form_action(self)\n \n# @api.multi\n# def multi_mark_delete(self):\n# active_ids = self._context.get('active_ids')\n# if active_ids:\n# cvis = self.env['cvi'].browse(active_ids)\n# cvis.write({'state':'mark_delete'})\n# else:\n# raise UserError (u'Bạn chưa chọn dòng nào')\n \n ","sub_path":"dai_tgg/models/setaction_dai_tgg.py","file_name":"setaction_dai_tgg.py","file_ext":"py","file_size_in_byte":4313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"59041683","text":"\"\"\"\nThis module implements \"quick sort\" algorithm to sort an array.\n\"\"\"\n\n\ndef getPivot(array):\n array_length = len(array)\n\n if array_length == 0:\n return None\n elif array_length < 5:\n return array[0]\n\n first_element = array[0]\n last_element = array[array_length - 1]\n middle_element = array[array_length // 2]\n\n if first_element <= middle_element <= last_element or last_element <= middle_element <= first_element:\n return middle_element\n elif middle_element <= last_element <= first_element or first_element <= last_element <= middle_element:\n return last_element\n elif last_element <= first_element <= middle_element or middle_element <= first_element <= last_element:\n return first_element\n\n\ndef quickSort(array):\n \"\"\"\n Sort incoming array in ascending order with quick-sort algorithm.\n\n :param array:\n :return array:\n \"\"\"\n array_length = len(array)\n\n if array_length <= 1:\n return array\n\n if array_length == 2:\n if array[0] > array[1]:\n array[0], array[1] = array[1], array[0]\n return array\n\n pivot = getPivot(array)\n\n lessThanPivot = []\n equalPivot = []\n moreThanPivot = []\n\n for element in array:\n if element < pivot:\n lessThanPivot.append(element)\n elif element == pivot:\n equalPivot.append(element)\n elif element > pivot:\n moreThanPivot.append(element)\n\n return quickSort(lessThanPivot) + equalPivot + quickSort(moreThanPivot)\n\n\nif __name__ == '__main__':\n from array_manager import print_array, generate_array\n\n array = generate_array(array_size=100, is_unique=True)\n print_array(array, f'Array [{len(array)}]')\n array = quickSort(array)\n print_array(array, f'Sorted array [{len(array)}]')\n","sub_path":"quick_sort.py","file_name":"quick_sort.py","file_ext":"py","file_size_in_byte":1804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"542726768","text":"#using default argumnets\ndef info( name, age = 25 ):\n #here I gave 25 as default parameter \n print (\"Name: \", name)\n print (\"Age \", age)\n return;\n# Now you can call printinfo function\nprint(\" Enter your name: \")\nname=str(input())\nage=str(input(\"Enter your age\"))\ninfo( name,age )\ninfo( name)\n#I didn't give age here so i shows 25\n","sub_path":"default_arguments.py","file_name":"default_arguments.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"144035151","text":"from PyQt5 import QtCore, QtGui, QtWidgets\r\nfrom Employee_war_card import Empl\r\nimport MySQLdb as mysql\r\n\r\nclass In_Re_management(object):\r\n def show_Users(self):\r\n self.window = QtWidgets.QMainWindow()\r\n self.ui = Empl()\r\n self.ui.setupUi(self.window)\r\n self.window.show()\r\n def setupUi(self, MainWindow):\r\n MainWindow.setObjectName(\"MainWindow\")\r\n MainWindow.resize(790, 262)\r\n self.centralwidget = QtWidgets.QWidget(MainWindow)\r\n self.centralwidget.setObjectName(\"centralwidget\")\r\n self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)\r\n self.lineEdit.setGeometry(QtCore.QRect(20, 50, 31, 21))\r\n self.lineEdit.setObjectName(\"lineEdit\")\r\n self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)\r\n self.lineEdit_2.setGeometry(QtCore.QRect(70, 50, 101, 20))\r\n self.lineEdit_2.setObjectName(\"lineEdit_2\")\r\n self.lineEdit_3 = QtWidgets.QLineEdit(self.centralwidget)\r\n self.lineEdit_3.setGeometry(QtCore.QRect(180, 50, 81, 20))\r\n self.lineEdit_3.setObjectName(\"lineEdit_3\")\r\n self.lineEdit_4 = QtWidgets.QLineEdit(self.centralwidget)\r\n self.lineEdit_4.setGeometry(QtCore.QRect(270, 50, 81, 20))\r\n self.lineEdit_4.setObjectName(\"lineEdit_4\")\r\n self.lineEdit_5 = QtWidgets.QLineEdit(self.centralwidget)\r\n self.lineEdit_5.setGeometry(QtCore.QRect(360, 50, 151, 20))\r\n self.lineEdit_5.setObjectName(\"lineEdit_5\")\r\n self.lineEdit_6 = QtWidgets.QLineEdit(self.centralwidget)\r\n self.lineEdit_6.setGeometry(QtCore.QRect(520, 50, 91, 20))\r\n self.lineEdit_6.setObjectName(\"lineEdit_6\")\r\n self.lineEdit_7 = QtWidgets.QLineEdit(self.centralwidget)\r\n self.lineEdit_7.setGeometry(QtCore.QRect(620, 50, 71, 20))\r\n self.lineEdit_7.setObjectName(\"lineEdit_7\")\r\n self.label = QtWidgets.QLabel(self.centralwidget)\r\n self.label.setGeometry(QtCore.QRect(20, 30, 47, 13))\r\n font = QtGui.QFont()\r\n font.setPointSize(12)\r\n self.label.setFont(font)\r\n self.label.setObjectName(\"label\")\r\n self.label_2 = QtWidgets.QLabel(self.centralwidget)\r\n self.label_2.setGeometry(QtCore.QRect(100, 30, 47, 13))\r\n font = QtGui.QFont()\r\n font.setPointSize(12)\r\n self.label_2.setFont(font)\r\n self.label_2.setObjectName(\"label_2\")\r\n self.label_3 = QtWidgets.QLabel(self.centralwidget)\r\n self.label_3.setGeometry(QtCore.QRect(170, 30, 121, 20))\r\n font = QtGui.QFont()\r\n font.setPointSize(9)\r\n self.label_3.setFont(font)\r\n self.label_3.setObjectName(\"label_3\")\r\n self.label_4 = QtWidgets.QLabel(self.centralwidget)\r\n self.label_4.setGeometry(QtCore.QRect(270, 30, 91, 20))\r\n font = QtGui.QFont()\r\n font.setPointSize(9)\r\n self.label_4.setFont(font)\r\n self.label_4.setObjectName(\"label_4\")\r\n self.label_5 = QtWidgets.QLabel(self.centralwidget)\r\n self.label_5.setGeometry(QtCore.QRect(420, 30, 47, 13))\r\n font = QtGui.QFont()\r\n font.setPointSize(12)\r\n self.label_5.setFont(font)\r\n self.label_5.setObjectName(\"label_5\")\r\n self.label_6 = QtWidgets.QLabel(self.centralwidget)\r\n self.label_6.setGeometry(QtCore.QRect(530, 20, 81, 31))\r\n font = QtGui.QFont()\r\n font.setPointSize(12)\r\n self.label_6.setFont(font)\r\n self.label_6.setObjectName(\"label_6\")\r\n self.label_7 = QtWidgets.QLabel(self.centralwidget)\r\n self.label_7.setGeometry(QtCore.QRect(630, 20, 51, 31))\r\n font = QtGui.QFont()\r\n font.setPointSize(12)\r\n self.label_7.setFont(font)\r\n self.label_7.setObjectName(\"label_7\")\r\n font = QtGui.QFont()\r\n font.setPointSize(9)\r\n self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget)\r\n self.pushButton_4.setGeometry(QtCore.QRect(300, 130, 161, 51))\r\n self.pushButton_4.setObjectName(\"pushButton_4\")\r\n self.pushButton_4.clicked.connect(self.show_Users)\r\n self.widget = QtWidgets.QWidget(self.centralwidget)\r\n self.widget.setGeometry(QtCore.QRect(190, 80, 381, 41))\r\n self.widget.setObjectName(\"widget\")\r\n self.horizontalLayout = QtWidgets.QHBoxLayout(self.widget)\r\n self.horizontalLayout.setContentsMargins(0, 0, 0, 0)\r\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\r\n self.horizontalLayout_2 = QtWidgets.QHBoxLayout()\r\n self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\")\r\n self.pushButton = QtWidgets.QPushButton(self.widget)\r\n self.pushButton.setObjectName(\"pushButton\")\r\n self.pushButton.clicked.connect(self.change)\r\n self.horizontalLayout_2.addWidget(self.pushButton)\r\n self.pushButton_2 = QtWidgets.QPushButton(self.widget)\r\n self.pushButton_2.setObjectName(\"pushButton_2\")\r\n self.pushButton_2.clicked.connect(self.add)\r\n self.horizontalLayout_2.addWidget(self.pushButton_2)\r\n self.pushButton_5 = QtWidgets.QPushButton(self.widget)\r\n self.pushButton_5.setObjectName(\"pushButton\")\r\n self.pushButton_5.clicked.connect(self.change)\r\n self.horizontalLayout_2.addWidget(self.pushButton_5)\r\n self.pushButton_6 = QtWidgets.QPushButton(self.widget)\r\n self.pushButton_6.setObjectName(\"pushButton\")\r\n self.pushButton_6.clicked.connect(self.change)\r\n self.horizontalLayout_2.addWidget(self.pushButton_6)\r\n self.pushButton_7 = QtWidgets.QPushButton(self.widget)\r\n self.pushButton_7.setObjectName(\"pushButton\")\r\n self.pushButton_7.clicked.connect(self.change)\r\n self.horizontalLayout_2.addWidget(self.pushButton_7)\r\n self.pushButton_8 = QtWidgets.QPushButton(self.widget)\r\n self.pushButton_8.setObjectName(\"pushButton\")\r\n self.pushButton_8.clicked.connect(self.change)\r\n self.horizontalLayout_2.addWidget(self.pushButton_8)\r\n self.pushButton_3 = QtWidgets.QPushButton(self.widget)\r\n self.pushButton_3.setObjectName(\"pushButton_3\")\r\n self.pushButton_3.clicked.connect(self.dels)\r\n self.horizontalLayout_2.addWidget(self.pushButton_3)\r\n self.horizontalLayout.addLayout(self.horizontalLayout_2)\r\n MainWindow.setCentralWidget(self.centralwidget)\r\n self.menubar = QtWidgets.QMenuBar(MainWindow)\r\n self.menubar.setGeometry(QtCore.QRect(0, 0, 790, 21))\r\n self.menubar.setObjectName(\"menubar\")\r\n MainWindow.setMenuBar(self.menubar)\r\n self.statusbar = QtWidgets.QStatusBar(MainWindow)\r\n self.statusbar.setObjectName(\"statusbar\")\r\n MainWindow.setStatusBar(self.statusbar)\r\n\r\n self.retranslateUi(MainWindow)\r\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\r\n\r\n\r\n def retranslateUi(self, MainWindow):\r\n _translate = QtCore.QCoreApplication.translate\r\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"MainWindow\"))\r\n self.label.setText(_translate(\"MainWindow\", \"Warehouse_number\"))\r\n self.label_2.setText(_translate(\"MainWindow\", \"Date\"))\r\n self.label_3.setText(_translate(\"MainWindow\", \"Name_of_inventory\"))\r\n self.label_4.setText(_translate(\"MainWindow\", \"Number_of_inventory_items\"))\r\n self.label_5.setText(_translate(\"MainWindow\", \"Firstname\"))\r\n self.label_6.setText(_translate(\"MainWindow\", \"Lastname\"))\r\n self.label_7.setText(_translate(\"MainWindow\", \"Position\"))\r\n self.pushButton_4.setText(_translate(\"MainWindow\", \"Get_invoice_data\"))\r\n self.pushButton.setText(_translate(\"MainWindow\", \"Update_invoice_data\"))\r\n self.pushButton_2.setText(_translate(\"MainWindow\", \"Add_invoice_data\"))\r\n self.pushButton_3.setText(_translate(\"MainWindow\", \"Delete_invoice_data\"))\r\n self.pushButton_5.setText(_translate(\"MainWindow\", \"Get_receipt_data\"))\r\n self.pushButton_6.setText(_translate(\"MainWindow\", \"Update_receipt_data\"))\r\n self.pushButton_7.setText(_translate(\"MainWindow\", \"Add_receipt_data\"))\r\n self.pushButton_8.setText(_translate(\"MainWindow\", \"Delete_receipt_data\"))\r\n\r\n def change(self):\r\n\r\n try:\r\n Warehouse_num = int(self.lineEdit.text())\r\n date = self.lineEdit_2.text()\r\n Name_of_inventory = self.lineEdit_3.text()\r\n Number_of_inventory_items = int(self.lineEdit_4.text())\r\n Firstname = self.lineEdit_6.text()\r\n Lastname = self.lineEdit_7.text()\r\n Position = self.lineEdit_5.text()\r\n except:\r\n return\r\n\r\n try:\r\n db = mysql.connect(host=\"localhost\", user=\"root\", passwd=\"root\", db=\"lab4\")\r\n cur = db.cursor()\r\n ch1=\"\"\"UPDATE Warehouse_registration_card SET date = %s, Name_of_inventory = %s, Number_of_inventory_items = %s, Position = %s, Firstname = %s, Lastname = %s, Division_Division_num = %s WHERE user_id = %s\"\"\"\r\n ch2=(date, Name_of_inventory, Number_of_inventory_items, Position, Firstname, Lastname, Warehouse_num )\r\n cur.execute(ch1, ch2)\r\n db.commit()\r\n cur.close()\r\n finally:\r\n db.close()\r\n\r\n def add(self):\r\n\r\n try:\r\n Warehouse_num = int(self.lineEdit.text())\r\n date = self.lineEdit_2.text()\r\n Name_of_inventory = self.lineEdit_3.text()\r\n Number_of_inventory_items = int(self.lineEdit_4.text())\r\n Firstname = self.lineEdit_6.text()\r\n Lastname = self.lineEdit_7.text()\r\n Position = self.lineEdit_5.text()\r\n except:\r\n return\r\n db = mysql.connect(host=\"localhost\", user=\"root\", passwd=\"root\", db=\"lab4\")\r\n cur = db.cursor()\r\n cur.execute('insert into Warehouse_registration_card values(%s, %s, %s, %s, %s, %s, %s, %s)', \\\r\n (int(Warehouse_num), date, Name_of_inventory,Number_of_inventory_items, Position, Firstname, Lastname,))\r\n db.commit()\r\n cur.close()\r\n db.close()\r\n\r\n def dels(self):\r\n\r\n\r\n db = mysql.connect(host=\"localhost\", user=\"root\", passwd=\"root\", db=\"lab4\")\r\n cur = db.cursor()\r\n try:\r\n Warehouse_num = int(self.lineEdit.text())\r\n except:\r\n return\r\n cur.execute(\"DELETE FROM Warehouse_registration_card WHERE Warehouse_num = %s\",(int(Warehouse_num),))\r\n db.commit()\r\n cur.close()\r\n db.close()\r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n import sys\r\n app = QtWidgets.QApplication(sys.argv)\r\n MainWindow = QtWidgets.QMainWindow()\r\n ui = In_Re_management()\r\n ui.setupUi(MainWindow)\r\n MainWindow.show()\r\n sys.exit(app.exec_())\r\n","sub_path":"In_Re_management.py","file_name":"In_Re_management.py","file_ext":"py","file_size_in_byte":10685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"264422028","text":"import sys, os\nimport numpy as np\nimport csv\nfrom scipy import spatial\nimport matplotlib.pyplot as plt\n\n\ndef usage():\n print(\"Usage: python plot_cosine.py feats.csv model dataset layer [tl, tr, c, bl, br] min=auto, max=auto\")\n sys.exit(0)\n\ndef cosine_sim(A, B):\n return np.dot(A, B) / (np.linalg.norm(A) * np.linalg.norm(B))\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 6 and len(sys.argv) != 8:\n usage()\n\n if sys.argv[5] not in ['tl', 'tr', 'c', 'bl', 'br']:\n usage()\n\n csvfile = sys.argv[1]\n model = sys.argv[2]\n dataset = sys.argv[3]\n layer = sys.argv[4]\n comp = sys.argv[5]\n\n with open(csvfile, 'r') as f:\n reader = csv.reader(f)\n all_feats = np.array(list(reader))\n\n max_r = 0\n max_c = 0\n for row in all_feats:\n name = row[0]\n r = int(name.split('_')[0])\n c = int(name.split('_')[1])\n if r > max_r:\n max_r = r\n if c > max_c:\n max_c = c\n\n all_vects = all_feats[:,1:]\n feat_len = len(all_vects[0])\n\n feat_array = np.zeros((max_r+1, max_c+1, feat_len))\n cs_array = np.zeros((max_r+1, max_c+1))\n \n PROB = False\n COSINE = False\n if feat_len == 1:\n PROB = True\n else:\n COSINE = True\n\n if COSINE:\n for row in all_feats:\n name = row[0]\n feat = np.array(row[1:]).astype(float)\n r = int(name.split('_')[0])\n c = int(name.split('_')[1])\n feat_array[r,c] = feat\n\n if comp == 'tl':\n compvect = feat_array[0, 0]\n elif comp == 'tr':\n compvect = feat_array[0, max_c]\n elif comp == 'c':\n compvect = feat_array[max_r // 2, max_c // 2]\n elif comp == 'bl':\n compvect = feat_array[max_r, 0]\n elif comp == 'br':\n compvect = feat_array[max_r, max_c]\n\n for i in range(max_r+1):\n for j in range(max_c+1):\n cs_array[i,j] = cosine_sim(compvect, feat_array[i,j])\n\n elif PROB:\n for row in all_feats:\n name = row[0]\n feat = float(row[1])\n r = int(name.split('_')[0])\n c = int(name.split('_')[1])\n cs_array[r,c] = feat\n\n print(\"min:\", np.min(cs_array))\n print(\"max:\", np.max(cs_array))\n\n fig, ax = plt.subplots()\n pos = ax.imshow(cs_array, cmap='hot')\n\n if COSINE:\n ax.set_title('Cosine Similarity of Shifted Object Features\\n{} {} on {}, comp. to {}'.format(model, layer, dataset, comp))\n if PROB:\n ax.set_title('Correct Class Prob. of Shifted Object Features\\n {} on {}'.format(model, dataset))\n\n ax.set_xlabel('Horizontal Shift in Pixels')\n ax.set_ylabel('Vertical Shift in Pixels')\n if len(sys.argv) == 8:\n cmap_min = float(sys.argv[6])\n cmap_max = float(sys.argv[7])\n pos.set_clim(cmap_min, cmap_max)\n\n fig.colorbar(pos)\n plt.savefig('{}-{}-{}-{}-plot.png'.format(model, layer, dataset, comp))\n\n # save out csv for d3\n\n csv_export = []\n for i in range(cs_array.shape[0]):\n for j in range(cs_array.shape[1]):\n val = cs_array[i, j]\n csv_export.append([i, j, val])\n\n with open('{}-{}-{}-{}-d3.csv'.format(model, layer, dataset, comp), 'w') as f:\n writer = csv.writer(f)\n writer.writerow([\"y\", \"x\", \"val\"])\n writer.writerows(csv_export)\n\n","sub_path":"plotting/plot_cosine_png.py","file_name":"plot_cosine_png.py","file_ext":"py","file_size_in_byte":3368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"174582431","text":"import numpy as np\nfrom numpy import *\nimport math\n\n\nclass LR:\n def __init__(self):\n self.learning_rate = 0.1\n self.theta = ones((33, 1))\n self.prediction = []\n self.train_data = []\n self.load_date()\n\n def load_date(self):\n f = open('./data/trainSet.csv', 'r')\n f.readline()\n print('loading data...')\n for line in f.readlines():\n line_arr = line.strip('\\n').split(',')\n line_arr = [float(i) for i in line_arr]\n line_arr.insert(0, 1)\n self.prediction.append(line_arr.pop())\n # print(line_arr)\n self.train_data.append(line_arr)\n f.close()\n self.train_data = np.array(self.train_data)\n\n index_max = np.max(self.train_data, axis=0)\n index_min = np.min(self.train_data, axis=0)\n print(index_max)\n print(index_min)\n\n for i in range(1, 33):\n for j in range(len(self.train_data)):\n self.train_data[j][i] = (self.train_data[j][i] - index_min[i])/(index_max[i] - index_min[i])\n\n def sigmoid(self, inX):\n return 1.0 / (1 + exp(-inX))\n\n def train(self):\n dataMat = mat(self.train_data)\n lableMat = mat(self.prediction)\n m,n = shape(dataMat)\n for i in range(10):\n h = self.sigmoid(dataMat*self.theta)\n error = lableMat - h\n self.theta = self.theta + self.learning_rate*dataMat.transpose()*error\n print('current accuracy: ', self.accuracy_train_set())\n\n def accuracy_train_set(self):\n result = []\n acc = 0\n for i in self.train_data:\n line = np.array(i)\n pre = np.sum(line*self.theta)\n if pre >= 0:\n result.append(1.0)\n else:\n result.append(0.0)\n print(result)\n for i in range(len(self.prediction)):\n if self.prediction[i] == result[i]:\n acc += 1\n return acc/len(self.prediction)\n\n\ndef main():\n lr = LR()\n lr.train()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"LogicRegression/LR.py","file_name":"LR.py","file_ext":"py","file_size_in_byte":2088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"444523193","text":"#from psychopy import * #import all libraries from PsychoPy\nimport math\nimport numpy as np\nfrom matplotlib.pyplot import plot,show,hist,subplots,tight_layout,savefig,ion\nfrom matplotlib import rc\nimport pylab\nfrom random import randrange,choice,shuffle\nimport sys\nimport os\n\n\n# TRIAL TYPES\nCTRL=0\nCW=2\nCCW=1\n\nIN=3\nOUT=4\n\ncodes = [\"CTRL\",\"CW\", \"CCW\", \"IN\",\"OUT\"]\n\n#delta of proximity\ndelta_t=[8,12,16]\n\n#rings\nR1=8\ndr=np.round(R1*math.sin(delta_t[1]/180.0*math.pi),1)\nR2=R1+dr\nR3=R1+2*dr\n\nRs=[R1,R2,R3]\n\ndelays = [[0],[3]]\nri=30\nrf=60\n\n\nCM=['Blue','Green', 'Grey', 'Orange', 'Purple', 'Red', 'Cyan']\n\ndef validate(trials):\n # atrials=np.array(trials)\n # T1 = map(cal_quadrant,a[:,3])\n # T2 = map(cal_quadrant,a[:,5])\n # T3 = map(cal_quadrant,a[:,7])\n\n return True\n\ndef calc_quadrant(angle):\n return int(angle) / 90 + 1\n\ndef oposite(quadrant):\n op=(quadrant+2)%4\n return (4 if op < 1 else op)\n\ndef genPos(quadrant):\n Q=(quadrant-1)*90\n angle=randrange(ri,rf,1)+Q\n return np.mod(angle,360)\n\ndef genCCW(quadrant,R,delta):\n ring1=R\n probe=genPos(quadrant)\n neigh=probe-delta\n ring2=choice(Rs)\n return [ring1,probe,ring1,neigh]\n \ndef genCW(quadrant,R,delta):\n ring1=R\n probe=genPos(quadrant)\n neigh=probe+delta\n ring2=choice(Rs)\n return [ring1,probe,ring1,neigh]\n \ndef genIO(quadrant,R_1,R_2):\n probe=genPos(quadrant)\n ring=choice(Rs)\n return [R_1,probe,R_2,probe]\n\ndef genIO2(quadrant):\n probe=genPos(quadrant)\n ring=choice([R1,R2])\n return [R2,probe,R1,probe]\n\ndef genRand(quadrant):\n Q=[q for q in [1,2,3,4] if q != quadrant]\n far1=genPos(quadrant)\n ring1=genR()\n\n q,Q=choicePop(Q)\n far2=genPos(q)\n ring2=genR()\n\n q,_=choicePop(Q)\n far3=genPos(q)\n ring3=genR()\n return [ring1,far1,ring2,far2]\n\ndef genR():\n r=randrange(Rs[0],Rs[2])\n r_d=randrange(1,9)/10.0\n return r+r_d\n\ndef choicePop(list):\n c=choice(list)\n i=0\n for n in list:\n if n == c: \n new_list = list[0:i]+list[i+1:]\n i+=1\n return (c,new_list)\n\ndef genCtr(quadrant,R):\n ring1=R\n probe=genPos(quadrant)\n return [ring1,probe,-1,-1]\n \nif __name__ == \"__main__\":\n \n valid=False\n trials=[]\n while(not valid):\n valid = validate(trials)\n for d in delays:\n for q in range(1,4+1):\n\n # IN TRIALS\n trials.append(d+[IN]+genIO(q,Rs[0],Rs[1])) # dr1\n trials.append(d+[IN]+genIO(q,Rs[1],Rs[2])) # dr2\n trials.append(d+[IN]+genIO(q,Rs[0],Rs[2])) # dr3\n\n # OUT TRIALS\n trials.append(d+[OUT]+genIO(q,Rs[1],Rs[0])) # dr1\n trials.append(d+[OUT]+genIO(q,Rs[2],Rs[1])) # dr2\n trials.append(d+[OUT]+genIO(q,Rs[2],Rs[0])) # dr3\n \n # CW/CCW\n gens=[genCW,genCCW]*3\n types=[CW,CCW]*3\n idx = [0,1]*3\n\n # R1\n i,idx = choicePop(idx)\n trials.append(d+[types[i]]+gens[i](q,Rs[0],delta_t[0])) # R1 dt1\n\n i,idx = choicePop(idx)\n trials.append(d+[types[i]]+gens[i](q,Rs[0],delta_t[1])) # R1 dr2\n \n i,idx = choicePop(idx)\n trials.append(d+[types[i]]+gens[i](q,Rs[0],delta_t[2])) # R1 dr2\n\n # R3\n i,idx = choicePop(idx)\n trials.append(d+[types[i]]+gens[i](q,Rs[2],delta_t[0])) # R1 dt1\n\n i,idx = choicePop(idx)\n trials.append(d+[types[i]]+gens[i](q,Rs[2],delta_t[1])) # R1 dr2\n \n i,idx = choicePop(idx)\n trials.append(d+[types[i]]+gens[i](q,Rs[2],delta_t[2])) # R1 dr2\n\n # Controls\n trials.append(d+[CTRL]+genCtr(q,Rs[0]))\n trials.append(d+[CTRL]+genCtr(q,Rs[1]))\n trials.append(d+[CTRL]+genCtr(q,Rs[2]))\n\n shuffle(trials)\n shuffle(trials)\n\n \n\n atrials=np.array(trials)\n\n font = {'family' : 'normal',\n 'weight' : 'bold',\n 'size' : 8}\n\n rc('font', **font)\n\n\n f,ax=subplots(3,2)\n i=0\n for j in [atrials[:,1]==k for k in [CTRL, CW, CCW, IN, OUT]]:\n axi = ax[i/2,np.mod(i,2)]\n a = atrials[j,3]\n b = atrials[j,5]\n points = list(a)+list(b[b != 1])\n if atrials[j,1][0] == CTRL:\n points = list(a)\n axi.hist(points,360,color=CM[i])\n axi.set_title(codes[i]+\": \"+str(len(points)/2))\n i+=1\n\n points = list(atrials[:,3])+list(atrials[:,5])\n axi = ax[i/2,np.mod(i,2)]\n axi.hist(points,360,color='k')\n axi.set_title(\"All: \"+str(len(points)/2))\n tight_layout()\n\n pdir = \"subjects_trials\"\n subj = sys.argv[1]\n \n if os.path.exists(pdir+\"/\"+subj):\n n=1\n while os.path.exists(pdir+\"/\"+subj+str(n)): \n n+=1\n subj=subj+\"_\"+str(n)\n\n\n if not os.path.isdir(pdir+\"/\"+subj):\n os.makedirs(pdir+\"/\"+subj)\n\n savefig(pdir+\"/\"+subj+\"/\"+'trials.png',dpi=500)\n\n # 3 blocks trials\n file1 = open(pdir+\"/\"+subj+\"/\"+\"stim1.txt\",'w')\n file2 = open(pdir+\"/\"+subj+\"/\"+\"stim2.txt\",'w')\n file3 = open(pdir+\"/\"+subj+\"/\"+\"stim3.txt\",'w')\n\n trials1 = trials[0:len(trials)/3]\n trials2 = trials[len(trials)/3:2*len(trials)/3]\n trials3 = trials[2*len(trials)/3:len(trials)]\n\n file1.write(\"DELAY\\tTYPE\\tR1\\tT1\\tR2\\tT2\\n\")\n while len(trials1):\n t=trials1.pop()\n file1.write('\\t'.join(map(str, t))+\"\\n\")\n\n file2.write(\"DELAY\\tTYPE\\tR1\\tT1\\tR2\\tT2\\n\")\n while len(trials2):\n t=trials2.pop()\n file2.write('\\t'.join(map(str, t))+\"\\n\")\n\n file3.write(\"DELAY\\tTYPE\\tR1\\tT1\\tR2\\tT2\\n\")\n while len(trials3):\n t=trials3.pop()\n file3.write('\\t'.join(map(str, t))+\"\\n\")\n \n\n\n\n\n \n","sub_path":"generate_input2.py","file_name":"generate_input2.py","file_ext":"py","file_size_in_byte":5666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"475111813","text":"import torch\nimport torch.nn as nn\nfrom torch import optim\nfrom tensorboardX import SummaryWriter\n\nfrom tqdm import tqdm\nimport numpy as np\nimport logging\nfrom evaluate import eval_func, re_rank, euclidean_dist\n\nfrom utils import AverageMeter, calculate_acc\nimport os.path as osp\nimport os\n\nfrom utils.lr_scheduler import WarmupMultiStepLR\n\nfrom torch.optim import SGD\n# ?\nfrom optimizers import make_optimizer, make_optimizer_partial\ntry:\n from apex import amp\n from apex.parallel import DistributedDataParallel as DDP\n import apex\nexcept:\n pass\n\n# TODO: add config in defaults.py\nclass BaseTrainer(object):\n def __init__(self, cfg, model, train_dl, val_dl,\n loss_func, num_query, num_gpus):\n self.cfg = cfg\n self.model = model\n self.train_dl = train_dl\n self.val_dl = val_dl\n self.loss_func = loss_func\n self.num_query = num_query\n\n self.loss_avg = AverageMeter()\n self.acc_avg = AverageMeter()\n self.train_epoch = 1\n self.batch_cnt = 0\n\n self.logger = logging.getLogger('reid_baseline.train')\n self.log_period = cfg.SOLVER.LOG_PERIOD\n self.checkpoint_period = cfg.SOLVER.CHECKPOINT_PERIOD\n self.eval_period = cfg.SOLVER.EVAL_PERIOD\n self.output_dir = cfg.OUTPUT_DIR\n self.device = cfg.MODEL.DEVICE\n self.epochs = cfg.SOLVER.MAX_EPOCHS\n\n if cfg.SOLVER.TENSORBOARD.USE:\n summary_dir = os.path.join(cfg.OUTPUT_DIR,'summaries/')\n os.makedirs(summary_dir,exist_ok=True)\n self.summary_writer = SummaryWriter(log_dir=summary_dir)\n self.current_iteration = 0\n\n self.model.cuda()\n self.logger.info(self.model)\n\n\n if cfg.SOLVER.FIX_BACKBONE:\n\n print('==>fix backbone')\n param_list = []\n for k,v in self.model.named_parameters():\n if 'reduction_' not in k and 'fc_id_' not in k:\n v.requires_grad=False\n else:\n param_list.append(v)\n print(k)\n self.optim = make_optimizer_partial(param_list,opt=self.cfg.SOLVER.OPTIMIZER_NAME,lr=cfg.SOLVER.BASE_LR,weight_decay=self.cfg.SOLVER.WEIGHT_DECAY,momentum=cfg.SOLVER.MOMENTUM)\n\n else:\n self.optim = make_optimizer(self.model,opt=self.cfg.SOLVER.OPTIMIZER_NAME,lr=cfg.SOLVER.BASE_LR,weight_decay=self.cfg.SOLVER.WEIGHT_DECAY,momentum=cfg.SOLVER.MOMENTUM)\n self.scheduler = WarmupMultiStepLR(self.optim, cfg.SOLVER.STEPS, cfg.SOLVER.GAMMA, cfg.SOLVER.WARMUP_FACTOR,cfg.SOLVER.WARMUP_EPOCH, cfg.SOLVER.WARMUP_METHOD)\n self.logger.info(self.optim)\n\n # ? may be changed corresponding to the original one\n if cfg.MODEL.PRETRAIN_PATH != '':\n self.logger.info('Loading pretrained weights from {}'.format(cfg.MODEL.PRETRAIN_PATH))\n param_dict = torch.load(cfg.MODEL.PRETRAIN_PATH)\n\n start_with_module = False\n for k in param_dict.keys():\n if k.startswith('module.'):\n start_with_module = True\n break\n if start_with_module:\n param_dict = {k[7:] : v for k, v in param_dict.items() }\n\n print('ignore_param:')\n print([k for k, v in param_dict.items() if k not in self.model.state_dict() or self.model.state_dict()[k].size() != v.size()])\n print('unload_param:')\n print([k for k, v in self.model.state_dict().items() if k not in param_dict.keys() or param_dict[k].size() != v.size()] )\n\n param_dict = {k: v for k, v in param_dict.items() if k in self.model.state_dict() and self.model.state_dict()[k].size() == v.size()}\n for i in param_dict:\n self.model.state_dict()[i].copy_(param_dict[i])\n # for k,v in self.model.named_parameters():\n # if 'reduction_' not in k:\n # print(v.requires_grad)#理想状态下,所有值都是False\n return\n\n def handle_new_batch(self):\n if self.current_iteration % self.cfg.SOLVER.TENSORBOARD.LOG_PERIOD == 0:\n if self.summary_writer:\n self.summary_writer.add_scalar('Train/lr',self.scheduler.get_lr()[0],self.current_iteration)\n self.summary_writer.add_scalar('Train/loss',self.loss_avg.avg,self.current_iteration)\n self.summary_writer.add_scalar('Train/acc',self.acc_avg.avg,self.current_iteration)\n self.acc_avg.reset()\n\n\n self.batch_cnt += 1\n self.current_iteration += 1\n if self.batch_cnt % self.cfg.SOLVER.LOG_PERIOD == 0:\n self.logger.info('Epoch[{}] Iteration[{}/{}] Loss: {:.3f},'\n 'Acc: {:.3f}, Base Lr: {:.2e}'\n .format(self.train_epoch, self.batch_cnt,\n len(self.train_dl), self.loss_avg.avg,\n self.acc_avg.avg, self.scheduler.get_lr()[0]))\n\n def handle_new_epoch(self):\n\n self.batch_cnt = 1\n\n lr = self.scheduler.get_lr()[0]\n self.logger.info('Epoch {} done'.format(self.train_epoch))\n self.logger.info('-' * 20)\n\n torch.save(self.model.state_dict(), osp.join(self.output_dir,\n self.cfg.MODEL.NAME + '_epoch_last.pth'))\n torch.save(self.optim.state_dict(), osp.join(self.output_dir,\n self.cfg.MODEL.NAME + '_epoch_last_optim.pth'))\n\n if self.train_epoch > self.cfg.SOLVER.START_SAVE_EPOCH and self.train_epoch % self.checkpoint_period == 0:\n self.save()\n if (self.train_epoch > 0 and self.train_epoch % self.eval_period == 0) or self.train_epoch == 50 :\n self.evaluate()\n pass\n self.scheduler.step()\n self.train_epoch += 1\n\n def step(self, batch):\n self.model.train()\n self.optim.zero_grad()\n img, target = batch\n img, target = img.cuda(), target.cuda()\n # !! WARNINIG: USE_COS\n if self.cfg.MODEL.USE_COS:\n outputs = self.model(img,target)\n else:\n outputs = self.model(img)\n if self.cfg.MODEL.NAME in [\"cosinemgn\",\"cosinemgn2d\"]:\n loss,tpl,pce,gce = self.loss_func(outputs, target,in_detail=True)\n\n if self.current_iteration % self.cfg.SOLVER.TENSORBOARD.LOG_PERIOD == 0:\n if self.summary_writer:\n self.summary_writer.add_scalar('Train/tpl',tpl,self.current_iteration)\n self.summary_writer.add_scalar('Train/gce',gce,self.current_iteration)\n self.summary_writer.add_scalar('Train/pce',pce,self.current_iteration)\n else:\n loss,tpl,ce = self.loss_func(outputs, target,in_detail=True)\n\n if self.current_iteration % self.cfg.SOLVER.TENSORBOARD.LOG_PERIOD == 0:\n if self.summary_writer:\n self.summary_writer.add_scalar('Train/tpl',tpl,self.current_iteration)\n self.summary_writer.add_scalar('Train/ce',ce,self.current_iteration)\n\n loss.backward()\n self.optim.step()\n\n # acc = (score.max(1)[1] == target).float().mean()\n acc = calculate_acc(self.cfg, outputs, target)\n\n self.loss_avg.update(loss.cpu().item())\n self.acc_avg.update(acc.cpu().item())\n\n return self.loss_avg.avg, self.acc_avg.avg\n\n def evaluate(self):\n self.model.eval()\n num_query = self.num_query\n feats, pids, camids = [], [], []\n with torch.no_grad():\n for batch in tqdm(self.val_dl, total=len(self.val_dl),\n leave=False):\n data, pid, camid, _ = batch\n data = data.cuda()\n\n # ff = torch.FloatTensor(data.size(0), 2048).zero_()\n # for i in range(2):\n # if i == 1:\n # data = data.index_select(3, torch.arange(data.size(3) - 1, -1, -1).long().to('cuda'))\n # outputs = self.model(data)\n # f = outputs.data.cpu()\n # ff = ff + f\n\n ff = self.model(data).data.cpu()\n fnorm = torch.norm(ff, p=2, dim=1, keepdim=True)\n ff = ff.div(fnorm.expand_as(ff))\n\n feats.append(ff)\n pids.append(pid)\n camids.append(camid)\n feats = torch.cat(feats, dim=0)\n pids = torch.cat(pids, dim=0)\n camids = torch.cat(camids, dim=0)\n # ?\n if self.cfg.TEST.RANDOMPERM <=0 :\n query_feat = feats[:num_query]\n query_pid = pids[:num_query]\n query_camid = camids[:num_query]\n\n gallery_feat = feats[num_query:]\n gallery_pid = pids[num_query:]\n gallery_camid = camids[num_query:]\n\n distmat = euclidean_dist(query_feat, gallery_feat)\n\n\n cmc, mAP, _ = eval_func(distmat.numpy(), query_pid.numpy(), gallery_pid.numpy(),\n query_camid.numpy(), gallery_camid.numpy(),\n )\n else:\n cmc = 0\n mAP = 0\n seed = torch.random.get_rng_state()\n torch.manual_seed(0)\n for i in range(self.cfg.TEST.RANDOMPERM):\n index = torch.randperm(feats.size()[0])\n # print(index[:10])\n query_feat = feats[index][:num_query]\n query_pid = pids[index][:num_query]\n query_camid = camids[index][:num_query]\n\n gallery_feat = feats[index][num_query:]\n gallery_pid = pids[index][num_query:]\n gallery_camid = camids[index][num_query:]\n\n distmat = euclidean_dist(query_feat, gallery_feat)\n\n _cmc, _mAP, _ = eval_func(distmat.numpy(), query_pid.numpy(), gallery_pid.numpy(),\n query_camid.numpy(), gallery_camid.numpy(),\n )\n cmc += _cmc/self.cfg.TEST.RANDOMPERM\n mAP += _mAP/self.cfg.TEST.RANDOMPERM\n torch.random.set_rng_state(seed)\n\n self.logger.info('Validation Result:')\n self.logger.info('mAP: {:.2%}'.format(mAP))\n for r in self.cfg.TEST.CMC:\n self.logger.info('CMC Rank-{}: {:.2%}'.format(r, cmc[r - 1]))\n\n self.logger.info('average of mAP and rank1: {:.2%}'.format((mAP+cmc[0])/2.0))\n self.logger.info('-' * 20)\n\n if self.summary_writer:\n self.summary_writer.add_scalar('Valid/rank1',cmc[0],self.train_epoch)\n self.summary_writer.add_scalar('Valid/mAP',mAP,self.train_epoch)\n self.summary_writer.add_scalar('Valid/rank1_mAP',(mAP+cmc[0])/2.0,self.train_epoch)\n\n\n def save(self):\n torch.save(self.model.state_dict(), osp.join(self.output_dir,\n self.cfg.MODEL.NAME + '_epoch' + str(self.train_epoch) + '.pth'))\n torch.save(self.optim.state_dict(), osp.join(self.output_dir,\n self.cfg.MODEL.NAME + '_epoch' + str(\n self.train_epoch) + '_optim.pth'))\n","sub_path":"engine/base_trainer.py","file_name":"base_trainer.py","file_ext":"py","file_size_in_byte":11313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"491874280","text":"\n\"\"\"\nhttps://www.tensorflow.org/tutorials/keras/save_and_restore_models\n\"\"\"\nfrom __future__ import absolute_import, division, print_function\n\nimport os\n\nimport tensorflow as tf\nfrom tensorflow import keras\n\n# Returns a short sequential model\ndef create_model():\n model = tf.keras.models.Sequential([\n keras.layers.Dense(512, activation=tf.nn.relu, input_shape=(784,)),\n keras.layers.Dropout(0.2),\n keras.layers.Dense(10, activation=tf.nn.softmax)\n ])\n \n model.compile(optimizer=tf.keras.optimizers.Adam(), \n loss=tf.keras.losses.sparse_categorical_crossentropy,\n metrics=['accuracy'])\n \nreturn model\n\nif __name__ == '__main__':\n\n (train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data()\n\n train_labels = train_labels[:1000]\n test_labels = test_labels[:1000]\n\n train_images = train_images[:1000].reshape(-1, 28 * 28) / 255.0\n test_images = test_images[:1000].reshape(-1, 28 * 28) / 255.0\n # Create a basic model instance\n model = create_model()\n model.summary()\n\n","sub_path":"lab/TensorFlow_MNIST.py","file_name":"TensorFlow_MNIST.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"445336682","text":"example_dictionary = {'Kaly': [12, \"jum\"], 'boi': [22, 'black'],\n 'jane': [21, 'redhed'], 'BOBBythepimp': [86, \"black\"]}\n\nprint(example_dictionary['BOBBythepimp'])\n\nexample_dictionary[\"jim\"] = 77\n\nprint(\"Jim is %s\" % (example_dictionary[\"jim\"]))\n\ndel example_dictionary[\"jim\"]\n\nprint(example_dictionary['BOBBythepimp'][1])\n\nNumber\n1 is Biology\nNumber\n2 is Calculus\nAB / BC\nNumber\n3 is Chemistry\nNumber\n4 is Chinese\nNumber\n5 is Comparative\nGov\nNumber\n6 is Computer\nScience\nA\nNumber\n7 is Computer\nScience\nPrinciples\nNumber\n8 is English\nLanguage\nNumber\n9 is English\nLiterature\nNumber\n10 is Environmental\nScience\nNumber\n11 is European\nHistory\nNumber\n12 is French\nNumber\n13 is Human\nGeography\nNumber\n14 is Japanese\nNumber\n15 is Latin\nNumber\n16 is Macroeconomics\nNumber\n17 is Microeconomics\nNumber\n18 is Music\nTheory\nNumber\n19 is Physics\n1\nNumber\n20 is Physics\n2\nNumber\n21 is Physics\nC - E / M\nNumber\n22 is Physics\nC - Mechanics\nNumber\n23 is Psychology\nNumber\n24 is Seminar\nNumber\n25 is Spanish\nLanguage\nNumber\n26 is Spanish\nLiterature\nNumber\n27 is Statistics\nNumber\n28 is Studio\nArt\nNumber\n29 is US\nGovernment and Politics\nNumber\n30 is US\nHistory\nNumber\n31 is World\nHistory\n","sub_path":"dictionaries.py","file_name":"dictionaries.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"353607236","text":"import sys\nimport pygame\nfrom pygame.gfxdraw import aacircle as circ\nfrom pygame.gfxdraw import filled_circle as fcirc\nimport numpy as np\nfrom time import sleep\nimport matplotlib.pyplot as plt\n\n\n\n#Rezolucija\nXsize = 1000\nYsize = 960\n\n#Konstante\ng = 9.80\nm = 50\nL = 100 # pixeli\nPocetniKut = 1.2\ntirkizna = [84,255,159]\npurple = [131,111,255]\n\n#Poziv pygame\npygame.init()\n#Otvaranje prozora\nscreen = pygame.display.set_mode((Xsize,Ysize))\n\n\n# Funkcija za crtanje krugova\ndef draw_circ(screen, location, R, color):\n Sx = int(location[0])\n Sy = int(location[1])\n fcirc(screen, Sx, Sy, R, color)\n circ(screen, Sx, Sy, R, color)\n if Sx + R > Xsize:\n fcirc(screen, Sx-Xsize, Sy, R, color)\n circ(screen, Sx-Xsize, Sy , R, color)\n if Sx - R < 0:\n fcirc(screen, Sx+Xsize, Sy , R, color)\n circ(screen, Sx+Xsize, Sy , R, color)\n\ndef Kugla2(x,y):\n pygame.draw.line(screen, purple, (x,350),(x,y), 3)\n # pygame.draw.circle(screen, white,(x,y), 20, 0)\n draw_circ (screen, (x,y),20,tirkizna)\n\ndef Kugla2_pokret(x,y):\n theta = PocetniKut*np.cos((g/L)**(1/2)*t)\n\n pygame.draw.line(screen, purple, (x,350), [(L * np.sin(theta))+460,(L * np.cos(theta)+400)], 3)\n # pygame.draw.circle(screen, white,(x,y), 20, 0)\n draw_circ (screen, [(L * np.sin(theta))+x,(L * np.cos(theta)+400)],20,tirkizna)\n\n\n\nright = True\nt = 0\nrunning = True\n\nv1=0\n\nA = (L* 0.0264)-((L* 0.0264)*np.cos(PocetniKut)) # Max vrijednost\n#T = (2*np.pi())*np.sqrt((L*0.0264)/g) # Amplituda\n\n\n\n\nKugla2(460,550)\n\nwhile running:\n\n event = pygame.event.poll()\n if event.type == pygame.QUIT:\n running = False\n\n screen.fill(pygame.Color(84,84,84))\n\n theta = PocetniKut*np.cos((g/L)**(1/2)*t)\n A = (L* 0.0264)-((L* 0.0264)*np.cos(theta))\n print(theta)\n sleep(0.01)\n\n\n\n #Kugla2(460,550)\n\n pygame.draw.line(screen,[255,250,250],(350,350),(600,350),5)\n\n if right:\n pygame.draw.line(screen, purple, (500,350), [(L * np.sin(theta))+500,(L * np.cos(theta)+400)], 3)\n draw_circ (screen, [(L * np.sin(theta))+500,(L * np.cos(theta)+400)],20,tirkizna)\n Kugla2(460,(400+L)) # Stacionarna kugla 2\n v1 = 0\n v1 += (np.sqrt(g/(L*0.0264)*A*np.sin(theta)))\n v2=v1\n Eukup = m*g*A+((m*(v1**2))/2)\n # print(Eukup,\" \",m*g*A,\" \",(m*v1**2)/2)\n\n\n\n else:\n Kugla2_pokret(460,550)\n pygame.draw.line(screen, purple, (500,350), (500,(400+L)), 3)\n draw_circ (screen, (500,(400+L)),20,tirkizna)\n v2-= (np.sqrt(g/(L*0.0264)*A*np.sin(theta)))\n Eukup = m*g*A+((m*(v2**2))/2)\n # print(Eukup,\" \",m*g*A,\" \",(m*v2**2)/2)\n\n\n\n\n\n # Kad pendulum dode do theta = 0 prebaci se na lijevi\n if theta <= 0:\n right = False # Return\n else:\n right = True\n\n t += 0.01\n\n\n pygame.display.flip()\n # sleep(60)\n\n\n\n\nxos = np.array([0,t,0,1])\nyos = np.sin(xos)\nplt.plot(xos,yos)\nplt.show()\n\n# kolicina_gibanja_nakon = m1*v1 + m2*v2\n# kolicina_gibanja_prije\n","sub_path":"ovo.py","file_name":"ovo.py","file_ext":"py","file_size_in_byte":2978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"402848488","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Nov 16 20:28:45 2018\n\n@author: snickerdoodles\n\nThis class provides the framework for sampling methods to inherit from. It contains\nall of the attributes for the probability model supplied by the user.\n\nAttributes\n----------\nmodel_distributions: dict\n wrappers for pytorch distributions to use in calculating the likelihood\n \nmodel: list of dictionaries\n each element in the list represents a single random variable in the probability\n model supplied. For more information, see the function create_model()\n \ndata: dictionary\n represents the observed values for several variables. The keys of the data dictionary\n match up with the `Name` field of the corresponding model dictionary\n \nExample\n-------\n > model = [[\"X\",\"gaussian\",[0,1]],\n [\"Y\",\"gaussian\",[\"X\",1]]]\n > Model(model)\n\"\"\"\n\nimport torch\nimport torch.distributions\n\n\nclass Model: \n model_distributions = {\"gaussian\":torch.distributions.Normal,\n \"exponential\":torch.distributions.Exponential,\n \"uniform\":torch.distributions.Uniform,\n \"gamma\":torch.distributions.Gamma,\n \"beta\":torch.distributions.Beta,\n \"dirichlet\":torch.distributions.Dirichlet,\n \"multinomial\":torch.distributions.Multinomial,\n \"mvgaussian\":torch.distributions.MultivariateNormal,\n \"bernoulli\":torch.distributions.Bernoulli,\n \"binomial\":torch.distributions.Binomial,\n \"poisson\":torch.distributions.Poisson,\n }\n\n def __init__(self, models):\n \"\"\"\n Params\n ------\n models: list of lists\n each nested list represents a single random variable. The first element of the \n nested list is the random variable's name, the second is its distribution,\n the third are its parameters, and the fourth optional element is the dimensionality of the distribution, in the case of multivariate variables.\n\n \"\"\"\n self.model = [self.__create_model(model) for model in models]\n self.data = {}\n \n def __create_model(self,model):\n \"\"\"\n Returns a dictionary representation of a random variable, to be used in the model field. `Name` refers to the random variable name, `Distribution` refers to its distribution, `Parameters` refer to the parameters of the distribution, `Observed` refers to whether the variable is observed or not, `Continuous` refers to the continuity of the distribution, and `Dimension` refers to the dimensionality of the variable.\n \n Params\n ------\n model: list\n A single input list corresponding to a random variable.\n \n \"\"\"\n out = {}\n out[\"Name\"] = model[0]\n out[\"Distribution\"] = Model.model_distributions[model[1]]\n out[\"Parameters\"] = [self.strip_quotations(str(parameter)) for parameter in model[2]]\n out[\"Observed\"] = False\n out[\"Continuous\"] = self.is_continuous(model[1])\n try:\n out[\"Dimension\"] = model[3]\n except IndexError:\n out[\"Dimension\"] = 1\n return out\n \n def strip_quotations(self,expression):\n \"\"\"\n Strips any redundant quotations from the string\n \"\"\"\n return expression.replace(\"'\",\"\")\n \n \n def log_likelihood(self, state, compute_grad = False):\n \"\"\"\n Given observations, compute the joint log likelihood of the observations\n \n Params\n ------\n state: dictionary\n dictionary of observed values, indexed by the name of the corresponding variable.\n \n Returns\n -------\n torch.tensor\n \n Examples\n ------\n > log_likelihood({\"X\":5,\"Y\":2})\n \"\"\"\n state = {**state, **self.data} #Combine the current parameter values with the observed data\n log_prob = torch.tensor(0.)\n for model in self.model:\n #Substitute in the state parameter values, and evaluate the corresponding expression\n args = [eval(key,state) for key in model[\"Parameters\"]]\n value = state[model[\"Name\"]]\n try:\n log_prob += model[\"Distribution\"](*args).log_prob(value).sum()\n except Exception:\n log_prob += -99999999\n return log_prob\n \n def is_continuous(self, dist_name):\n \"\"\"\n Calculates whether the given distribution is continuous or not\n \n Params\n -----\n dist_name: string\n \"\"\"\n return dist_name in [\"gaussian\",\"exponential\",\"beta\",\"gamma\",\"uniform\",\"mvgaussian\"]\n\n def random_init(self):\n \"\"\"\n Generates a random initial sample, by first initializing the priors, and then\n initializing the other random variables conditioned on the priors\n \n Returns\n -------\n dictionary\n \"\"\"\n parameters_init = {}\n for model in self.model:\n if model[\"Observed\"]:\n continue\n args = [torch.tensor(eval(key,{\"__builtins__\":None},parameters_init),dtype=torch.float) for key in model[\"Parameters\"]]\n init = model[\"Distribution\"](*args).sample()\n init.requires_grad = True\n parameters_init[model[\"Name\"]] = init\n return parameters_init\n \n def observe(self, data):\n for variable in data:\n for model in self.model:\n if variable == model[\"Name\"]:\n model[\"Observed\"] = True\n self.data = data\n","sub_path":"src/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"412828285","text":"from database import SupervisedDataBase, Environment\nfrom logger import ProgressBar\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\n\nclass VanillaLSTM(nn.Module):\n\n def __init__(self, features, hidden_size, lstmlayers):\n super().__init__()\n self.features = features\n self.featureslen = len(features)\n self.hidden_size = hidden_size\n self.lstmlayers = lstmlayers\n\n self.lstm = nn.LSTM(input_size=self.featureslen, hidden_size=hidden_size, batch_first=True, num_layers=lstmlayers, dropout=0.5)\n self.fc = nn.Linear(in_features=self.featureslen, out_features=3)\n\n def forward(self, t):\n\n t, (hn, cn) = self.lstm(t)\n\n #get the last cell output\n t = t[:,-1,:]\n\n #fc layer with sigmoid activation\n t = self.fc(t)\n\n return t\n\n def inspect(self, symbol, pause=0.001, stepper=False, loops=1):\n \"\"\"\n lets the network run in an environment and plots it\n \"\"\"\n #setup variables\n done = False\n\n #setup the environment\n env = Environment(1000, symbol, features=self.features)\n o = env.reset()\n\n #setup the logger\n logger = pd.DataFrame()\n logger['close'] = env.ta_data['close'][env.episode_index:env.episode_index+env.windowsize].copy().reset_index(drop=True)\n logger['close_copy'] = env.scaled_data['close'][env.episode_index:env.episode_index+env.windowsize].copy().reset_index(drop=True)\n logger['hold'] = np.nan\n logger['buy'] = np.nan\n logger['sell'] = np.nan\n logger.reset_index(drop=True, inplace=True)\n\n #setup the plotting\n fig, ax = plt.subplots()\n ax2 = ax.twinx()\n fig.show()\n\n #mainloop\n torch.set_grad_enabled(False)\n for i in range(loops):\n while not done:\n\n #get the prediction from the model\n tensor = torch.tensor(o, dtype=torch.float32)\n tensor = tensor.unsqueeze(dim=0)\n prediction = self.forward(tensor)\n prediction = F.softmax(prediction, dim=1)\n maxindex = torch.argmax(prediction).item()\n \n #update the logger\n if maxindex == 0:\n logger['hold'].iloc[-1] = logger['close'].iloc[-1]\n elif maxindex == 1:\n logger['buy'].iloc[-1] = logger['close'].iloc[-1]\n elif maxindex == 2:\n logger['sell'].iloc[-1] = logger['close'].iloc[-1]\n\n #plotting\n df = pd.DataFrame(o)\n ax.cla()\n ax2.cla()\n ax.plot(df[0])\n ax.plot(logger['close_copy'], color='red', linestyle='--')\n ax2.plot(logger['close'], color='purple')\n ax2.plot(logger['hold'], color='gray', marker='o')\n ax2.plot(logger['buy'], color='green', marker='o')\n ax2.plot(logger['sell'], color='red', marker='o')\n fig.canvas.draw()\n plt.pause(pause)\n\n #update the environment\n o, r, done = env.step(1)\n\n #update the logger\n logger.drop(inplace=True, index=0)\n appender = pd.DataFrame({\n 'close': [env.ta_data['close'][env.episode_index+env.windowsize-1].copy()],\n 'close_copy' : [env.scaled_data['close'][env.episode_index+env.windowsize-1].copy()],\n 'hold': [None],\n 'buy': [None],\n 'sell': [None]\n })\n logger = logger.append(appender, ignore_index=True)\n logger.reset_index(drop=True, inplace=True)\n\n if stepper:\n input()\n\n torch.set_grad_enabled(True)\n\n def train(self, databasepath, epochs, batchsize, balance=True, learningrate=0.001, terminallogger=True, saving=True):\n \"\"\"\n trains the network\n \"\"\"\n\n #setup the dataset\n data = SupervisedDataBase.from_database(databasepath)\n\n #setup the optimizer\n optimizer = optim.Adam(self.parameters(), lr=learningrate)\n \n #mainloop\n addloss = 0\n addacc = 0\n for i in range(epochs):\n\n #get the batches\n trainX, trainY, testX, testY = data.getbatches(batchsize=batchsize, features=self.features, balance_traindata=balance)\n\n #setup the progressbar\n bar = ProgressBar(f'Epoch {i}', maximum=trainX.shape[0]) if terminallogger else 0\n\n #train the network\n torch.set_grad_enabled(True)\n addloss = 0.0\n for i, element in enumerate(trainX):\n samples = torch.tensor(element, dtype=torch.float32)\n labels = torch.tensor(trainY[i], dtype=torch.int64)\n predictions = self.forward(samples)\n loss = F.cross_entropy(predictions, labels)\n addloss += loss.item()\n loss.backward()\n optimizer.step()\n\n if terminallogger:\n bar.step(addloss/(i+1))\n\n #evaluate the network\n torch.set_grad_enabled(False)\n addloss = 0.0\n addacc = 0.0\n for i, element in enumerate(testX):\n samples = torch.tensor(element, dtype=torch.float32)\n labels = torch.tensor(testY[i], dtype=torch.int64)\n prediction = self.forward(samples)\n loss = F.cross_entropy(prediction, labels)\n addloss += loss.item()\n addacc += self.calc_accuracy(prediction, labels)\n\n if terminallogger:\n bar.lastcall(addacc/testX.shape[0], addloss/testX.shape[0])\n bar.finish()\n\n if saving:\n torch.save(self, f'./models/VanillaLSTM_{self.featureslen}_{self.lstmlayers}_{self.hidden_size}')\n\n return addloss/testX.shape[0], addacc/testX.shape[0]\n\n @staticmethod\n def calc_accuracy(predictions, labels):\n predictions = F.softmax(predictions, dim=1)\n maxindex = predictions.argmax(dim=1)\n\n score = 0\n for i, element in enumerate(maxindex):\n if element == labels[i]:\n score += 1\n \n return score/predictions.shape[0]","sub_path":"utils/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"634993561","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('introduction', views.introduction, name='introduction'),\n path('daily', views.daily, name='daily'),\n path('daily///', views.daily_detail, name='daily_detail'),\n path('daily//',views.photo, name='photo'),\n path('posts', views.posts, name='posts'),\n path('post_list', views.post_list, name='post_list'),\n path('post//', views.post_detail, name='post_detail'),\n]","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"184628589","text":"#!/usr/bin/python\n# -*- coding:utf8 -*-\n\nimport re\nimport os.path\nfrom collections import defaultdict\n\nfrom api import plugin\nimport sshclient\n\n\nWEIGHT = 3\nFile_name = os.path.basename(os.path.abspath(__file__))\nPlugin_name = re.search(\"(\\w+)\\.py\", File_name).group(1)\n\n\nclass Table(object):\n\n\n def __init__(self, data):\n\n data = data.split('\\n')\n self.data = [ i.split() for i in data]\n\n def get_value(self, key):\n\n Index = self.data[2].index(key)\n\n return self.data[3][Index]\n\n\nclass Agent(plugin.plugin):\n\n def __init__(self, host, user, passwd):\n\n self.ssh = sshclient.SSHClient(host, user, passwd)\n\n\n def _get_data(self):\n\n current_usag = self.ssh.excute(\"mpstat 2 1\")[1].read()\n avg_usag = self.ssh.excute(\"mpstat\")[1].read()\n self.ssh.close()\n Current_Table = Table(current_usag)\n Avg_Table = Table(avg_usag)\n current = Current_Table.get_value(\"%usr\")\n avg = Avg_Table.get_value(\"%usr\")\n\n return current, avg\n\n def _struct_data(self):\n\n levels = ['debug','info','warn','error','critical']\n result = defaultdict(list)\n for lv in levels:\n result[lv]\n current, avg = self._get_data()\n if float(current) > 80.0 :\n msg = \"CPU 当前使用率超过80%, 当前为%s%%\"%current\n msg += \",开机以来的平均使用率为%s\"%avg\n result[\"warn\"].append(msg)\n else:\n msg = \"CPU 当前使用率为%s%%\"%current\n msg += \",开机以来的平均使用率为%s%%\"%avg\n result['info'].append(msg)\n\n return result\n\n def report(self):\n\n result = dict()\n data = self._struct_data()\n result.setdefault(Plugin_name, data)\n\n return result\n\ndef test():\n\n agent = Agent(\"172.16.0.61\", \"root\", \"hermeshermes\")\n agent.report()\n\n\nif __name__ == \"__main__\":\n\n test()\n\n\n\n\n\n\n\n\n","sub_path":"plugins/cpu.py","file_name":"cpu.py","file_ext":"py","file_size_in_byte":1928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"194710227","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n.. currentmodule:: test_cli\n.. moduleauthor:: zaro0508 \n\nThis is the test module for the project's command-line interface (CLI)\nmodule.\n\"\"\"\n# fmt: off\n\nimport yaml\nimport jccli.cli as cli\nfrom jccli import __version__\n# fmt: on\nfrom click.testing import CliRunner, Result\nfrom mock import MagicMock, patch, sentinel\nfrom jccli.jc_api_v2 import JumpcloudApiV2\n\nclass TestCli:\n\n def setup_method(self, test_method):\n pass\n\n\n def teardown_method(self, test_method):\n pass\n\n\n def test_version_displays_library_version(self):\n \"\"\"\n Arrange/Act: Run the `version` subcommand.\n Assert: The output matches the library version.\n \"\"\"\n runner: CliRunner = CliRunner()\n result: Result = runner.invoke(cli.cli, [\"version\"])\n assert (\n __version__ in result.output.strip()\n ), \"Version number should match library version.\"\n\n\n def test_verbose_output(self):\n \"\"\"\n Arrange/Act: Run the `version` subcommand with the '-v' flag.\n Assert: The output indicates verbose logging is enabled.\n \"\"\"\n runner: CliRunner = CliRunner()\n result: Result = runner.invoke(cli.cli, [\"-v\", \"version\"])\n assert (\n \"Verbose\" in result.output.strip()\n ), \"Verbose logging should be indicated in output.\"\n\n\n def test_create_group_with_invalid_type(self):\n runner: CliRunner = CliRunner()\n result: Result = runner.invoke(cli.cli, [\"create-group\", \"-n\", \"foo\", \"-t\", \"bar\"])\n assert (\n \"invalid choice\" in result.output.strip()\n ), \"Invalid choice should be indicated in output.\"\n\n @patch.object(JumpcloudApiV2,'create_group')\n def test_create_group_type_user(self, mock_create_group):\n response = [\n {\n 'id': '5dc3248445886d6c72b9614c',\n 'name': 'foo',\n 'type': 'user_group'\n }\n ]\n mock_create_group.return_value = response\n runner: CliRunner = CliRunner()\n result: Result = runner.invoke(cli.cli, [\"create-group\", \"-n\", \"foo\", \"-t\", \"user\"])\n assert (\n yaml.safe_load(result.output) == response\n ), \"Invalid response in output.\"\n\n @patch.object(JumpcloudApiV2,'create_group')\n def test_create_group_type_system(self, mock_create_group):\n response = [\n {\n 'id': '5dc3248445886d6c72b9614c',\n 'name': 'foo',\n 'type': 'system_group'\n }\n ]\n mock_create_group.return_value = response\n runner: CliRunner = CliRunner()\n result: Result = runner.invoke(cli.cli, [\"create-group\", \"-n\", \"foo\", \"-t\", \"system\"])\n assert (\n yaml.safe_load(result.output) == response\n ), \"Invalid response in output.\"\n\n @patch.object(JumpcloudApiV2,'delete_group')\n def test_delete_group(self, mock_create_group):\n response = None\n mock_create_group.return_value = response\n runner: CliRunner = CliRunner()\n result: Result = runner.invoke(cli.cli, [\"delete-group\", \"-n\", \"foo\"])\n assert (\n result.output.strip() == \"Jumpcloud group deleted\"\n ), \"Invalid response in output.\"\n","sub_path":"tests/test_cli.py","file_name":"test_cli.py","file_ext":"py","file_size_in_byte":3285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"120537486","text":"import json\n\n\nclass Config(object):\n \"\"\"\n Represents configuration loaded from a given file\n \"\"\"\n def __init__(self, path=None):\n \"\"\"\n Initializes configuration and loaded data from file if path is given\n\n :param path: path to the configuration file\n :type path: str\n \"\"\"\n self.config = {}\n if path is not None:\n self.loadFromFile(path)\n\n def loadFromFile(self, path):\n \"\"\"\n Loads configuration data from file to which path is given\n\n :param path: path to the configuration file\n :type path: str\n :return: returns None\n \"\"\"\n f = open(path, 'r')\n self.config = json.loads(f.read())\n f.close()\n\n def get(self, name, defaultValue=None):\n \"\"\"\n Gets configuration value located under the given name\n\n :param name: Name of configuration value\n :param defaultValue: Default value returned \\\n when needed value is undefined\n :type name: str\n :type defaultValue: None\n :return: returns configuration value or None if it's undefined\n \"\"\"\n if name in self.config:\n return self.config[name]\n else:\n return defaultValue\n","sub_path":"src/Config.py","file_name":"Config.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"296421128","text":"import os\n\npath = os.path.dirname(__file__)\nfile = open(os.path.join(path,'input_18_1.txt'), 'r')\ninput = file.readlines()\n\ntext = '''.#.#...|#.\n.....#|##|\n.|..|...#.\n..|#.....#\n#.#|||#|#|\n...#.||...\n.|....|...\n||...#|.#|\n|.||||..|.\n...#.|..|.'''\n#input = text.split('\\n')\n\nEmpty = 0\nTrees = 1\nLumber = 2\n\nclass Forest:\n def __init__(self, width, height):\n self.width = width\n self.height = height\n self.fields = [[Empty for x in range(width)] for y in range(height)]\n \n def __repr__(self):\n ret = ''\n for line in self.fields:\n lret = ''\n for x in line:\n if x == Empty:\n lret += '.'\n elif x == Trees:\n lret += '|'\n elif x == Lumber:\n lret += '#'\n lret += '\\n'\n ret += lret\n return ret\n\n def addField(self, x, y, field):\n if field == '.':\n return\n elif field == '#':\n self.fields[y][x] = Lumber\n elif field == '|':\n self.fields[y][x] = Trees\n else:\n print(field)\n \n def getAdjacencies(self, x, y):\n ret = []\n if y > 0:\n ret.append(self.fields[y-1][x])\n if x > 0:\n ret.append(self.fields[y-1][x-1])\n if x < self.width-1:\n ret.append(self.fields[y-1][x+1])\n if y < self.height-1:\n ret.append(self.fields[y+1][x])\n if x > 0:\n ret.append(self.fields[y+1][x-1])\n if x < self.width-1:\n ret.append(self.fields[y+1][x+1])\n if x > 0:\n ret.append(self.fields[y][x-1])\n if x < self.width-1:\n ret.append(self.fields[y][x+1])\n return ret\n \n def getCounts(self, adj):\n counts = [0,0,0]\n for a in adj:\n counts[a] += 1\n return counts\n \n def simulate(self):\n newfield = [[Empty for x in range(self.width)] for y in range(self.height)]\n for y in range(self.height):\n for x in range(self.width):\n field = self.fields[y][x]\n counts = self.getCounts(self.getAdjacencies(x, y))\n if field == Empty:\n if counts[Trees] >= 3:\n newfield[y][x] = Trees\n else:\n newfield[y][x] = Empty\n if field == Trees:\n if counts[Lumber] >= 3:\n newfield[y][x] = Lumber\n else:\n newfield[y][x] = Trees\n if field == Lumber:\n if counts[Lumber] >= 1 and counts[Trees] >= 1:\n newfield[y][x] = Lumber\n else:\n newfield[y][x] = Empty\n self.fields = newfield\n \n def countResources(self):\n trees = 0\n lumber = 0\n for y in range(self.height):\n for x in range(self.width):\n if self.fields[y][x] == Trees:\n trees += 1\n if self.fields[y][x] == Lumber:\n lumber += 1\n return trees, lumber\n\nf = Forest(50, 50)\n\nfor y in range(len(input)):\n line = input[y]\n for x in range(len(line)):\n f.addField(x, y, line[x])\n\nfor x in range(10):\n print(f)\n f.simulate()\nprint(f)\n \nt,l = f.countResources()\nprint(t, l, t*l)\n\n\n","sub_path":"18_1.py","file_name":"18_1.py","file_ext":"py","file_size_in_byte":3140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"363541272","text":"import tkinter as tk\nfrom tkinter.filedialog import askopenfilename\nimport shutil\nimport os\nimport sys\nfrom PIL import Image, ImageTk\n\n##load = Image.open('/home/deepanshu/Desktop/new_test/PlantDiseaseDetection/test/test/7b29fda8-5d5a-4158-827d-9941is')\n\ndef analysis(img):\n load = Image.open(img)\n\n import cv2 # working with, mainly resizing, images\n import numpy as np # dealing with arrays\n import os # dealing with directories\n from random import shuffle # mixing up or currently ordered data that might lead our network astray in training.\n from tqdm import \\\n tqdm # a nice pretty percentage bar for tasks. Thanks to viewer Daniel BA1/4hler for this suggestion\n verify_dir = '/home/deepanshu/Desktop/Hack_BPIT/hack_bpit/new_test/PlantDiseaseDetection/testpicture'\n IMG_SIZE = 50\n LR = 1e-3\n MODEL_NAME = 'healthyvsunhealthy-{}-{}.model'.format(LR, '2conv-basic')\n\n def process_verify_data():\n verifying_data = []\n for img in tqdm(os.listdir(verify_dir)):\n path = os.path.join(verify_dir, img)\n img_num = img.split('.')[0]\n img = cv2.imread(path, cv2.IMREAD_COLOR)\n img = cv2.resize(img, (IMG_SIZE, IMG_SIZE))\n verifying_data.append([np.array(img), img_num])\n np.save('verify_data.npy', verifying_data)\n return verifying_data\n\n verify_data = process_verify_data()\n #verify_data = np.load('verify_data.npy')\n\n import tflearn\n from tflearn.layers.conv import conv_2d, max_pool_2d\n from tflearn.layers.core import input_data, dropout, fully_connected\n from tflearn.layers.estimator import regression\n import tensorflow as tf\n tf.reset_default_graph()\n\n convnet = input_data(shape=[None, IMG_SIZE, IMG_SIZE, 3], name='input')\n\n convnet = conv_2d(convnet, 32, 3, activation='relu')\n convnet = max_pool_2d(convnet, 3)\n\n convnet = conv_2d(convnet, 64, 3, activation='relu')\n convnet = max_pool_2d(convnet, 3)\n\n convnet = conv_2d(convnet, 128, 3, activation='relu')\n convnet = max_pool_2d(convnet, 3)\n\n convnet = conv_2d(convnet, 32, 3, activation='relu')\n convnet = max_pool_2d(convnet, 3)\n\n convnet = conv_2d(convnet, 64, 3, activation='relu')\n convnet = max_pool_2d(convnet, 3)\n\n convnet = fully_connected(convnet, 1024, activation='relu')\n convnet = dropout(convnet, 0.8)\n\n convnet = fully_connected(convnet, 4, activation='softmax')\n convnet = regression(convnet, optimizer='adam', learning_rate=LR, loss='categorical_crossentropy', name='targets')\n\n model = tflearn.DNN(convnet, tensorboard_dir='log')\n\n if os.path.exists('{}.meta'.format(MODEL_NAME)):\n model.load(MODEL_NAME)\n print('model loaded!')\n\n\n for num, data in enumerate(verify_data):\n\n img_num = data[1]\n img_data = data[0]\n\n \n orig = img_data\n data = img_data.reshape(IMG_SIZE, IMG_SIZE, 3)\n # model_out = model.predict([data])[0]\n model_out = model.predict([data])[0]\n\n if np.argmax(model_out) == 0:\n return 'Healthy Leaf'\n elif np.argmax(model_out) == 1:\n return 'Bacterial Leaf'\n elif np.argmax(model_out) == 2:\n return 'Virus Infected Leaf'\n elif np.argmax(model_out) == 3:\n return 'Leaf is Late BLight'\n\n","sub_path":"hack_bpit/apply.py","file_name":"apply.py","file_ext":"py","file_size_in_byte":3315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"60589141","text":"#!/usr/bin/env python\nimport rospy\nimport sys\nimport Queue\nimport traceback\nimport math\nimport time\nimport numpy as np\nimport std_msgs.msg\nfrom std_msgs.msg import String\nfrom std_msgs.msg import Int8\nfrom geometry_msgs.msg import Twist\nfrom geometry_msgs.msg import TransformStamped\nfrom geometry_msgs.msg import PoseStamped\nfrom dronet_tello.msg import FlightData\nfrom dronet_tello.msg import HeadedBool \nfrom dronet_tello.msg import HeadedString\nimport rosgraph.impl.graph as rig\nfrom PredatorEnum import MachineState, MissionState, UserState, UserCommand, WarningState, CommandState, VelocityState\n\n#take in form of x1,x2,x3,x4...\ngoal_x = sys.argv[1]\ngoal_y = sys.argv[2]\ngoal_z = sys.argv[3]\ninterpolation_x = []\ninterpolation_y = []\ninterpolation_z = []\ncurr_x = 0\ncurr_y = 0\ncurr_z = 0\ncurr_angle = 0\nhome_x = -200\nhome_y = -200\nthreshold = 0.1\npublishing = True\nkill = False\nsweeping = False\npossible_target_detected = False\nold_height = 0\nbattery_percentage = 100\nbattery_low = False\nuser_input = str(UserCommand.Default)\nignore_map = {'x':[], 'y':[], 'z':[]}\nbaseline_hover_threshold = 10\nhover_threshold = baseline_hover_threshold\nignore = False\nmachine_state = MachineState.Default\ncommand_state = CommandState.Default\nmission_state = MissionState.Default\nwarning_state = WarningState.Default\n\ndef process_sysargs():\n\tglobal goal_x, goal_y, goal_z, interpolation_x, interpolation_y, interpolation_z, curr_x, curr_y, curr_z\n\tgoal_x = goal_x.split(\",\")\n\tgoal_y = goal_y.split(\",\")\n\tgoal_z = goal_z.split(\",\")\n\tfor i in range(0,len(goal_x)):\n\t\tgoal_x[i] = float(goal_x[i])\n\t\tgoal_y[i] = float(goal_y[i])\n\t\tgoal_z[i] = float(goal_z[i])\n\t# pick closer goal, make first entry in interpolations\n\tdistance_1 = math.sqrt((curr_x-goal_x[0])**2+(curr_y-goal_y[0])**2+(curr_z-goal_z[0])**2)\n\tdistance_2 = math.sqrt((curr_x-goal_x[1])**2+(curr_y-goal_y[1])**2+(curr_z-goal_z[1])**2)\n\tif(distance_1 < distance_2):\n\t\tprint(goal_x[0])\n\t\tprint(len(interpolation_x))\n\t\tinterpolation_x.append(goal_x[0])\n\t\tinterpolation_y.append(goal_y[0])\n\t\tinterpolation_z.append(goal_z[0])\n\telse:\n\t\tinterpolation_x.append(goal_x[1])\n\t\tinterpolation_y.append(goal_y[1])\n\t\tinterpolation_z.append(goal_z[1])\n\t\tgoal_x[1] = goal_x[0]\n\t\tgoal_y[1] = goal_y[0]\n\t\tgoal_z[1] = goal_z[0]\n\t\tgoal_x[0] = interpolation_x[0]\n\t\tgoal_y[0] = interpolation_y[0]\n\t\tgoal_z[0] = interpolation_z[0]\n\tinterpolate(0.1)\n\n\n# Traverses between xy coordinates starting at nearest point\ndef interpolate(increment_z):\n\tglobal goal_x, goal_y, goal_z, interpolation_x, interpolation_y, interpolation_z\n\tindex = 2\n\tfor i in frange(goal_z[0], goal_z[1], increment_z):\n\t\tinterpolation_z.append(i)\n\t\tif(index % 2 == 0 or i == goal_x[1]):\n\t\t\tinterpolation_x.append(goal_x[1])\n\t\t\tinterpolation_y.append(goal_y[1])\n\t\telse:\n\t\t\tinterpolation_x.append(goal_x[0])\n\t\t\tinterpolation_y.append(goal_y[0])\n\t\tindex += 1\n\tif(interpolation_x[len(interpolation_x)-1] != goal_x[1]):\n\t\t# need one more traverse\n\t\tinterpolation_x.append(goal_x[1])\n\t\tinterpolation_y.append(goal_y[1])\n\t\tinterpolation_z.append(goal_z[1])\n\n\ndef frange(start, stop, step):\n\ti = start\n\tif(stop < start):\n\t\tstep = -step\n\t\twhile i > stop:\n\t\t\tyield round(i,2)\n\t\t\ti = float(i + step)\n\telse:\n\t\twhile i < stop:\n\t\t\tyield round(i,2)\n\t\t\ti = float(i + step)\n\n\ndef vicon_data(msg):\n\tglobal curr_x, curr_y, curr_z, curr_angle\n\tglobal home_x, home_y\n\tglobal publishing\n\tcurr_x = msg.transform.translation.x\n\tcurr_y = msg.transform.translation.y\n\tcurr_z = msg.transform.translation.z\n\t# quaternions to radians\n\tsiny_cosp = +2.0 * (msg.transform.rotation.w * msg.transform.rotation.z + msg.transform.rotation.x * msg.transform.rotation.y);\n\tcosy_cosp = +1.0 - 2.0 * (msg.transform.rotation.y * msg.transform.rotation.y + msg.transform.rotation.z * msg.transform.rotation.z); \n\tcurr_angle = math.atan2(siny_cosp, cosy_cosp);\n\tpublishing = True\n\tif(curr_z < 0.05):\n\t\thome_x = msg.transform.translation.x\n\t\thome_y = msg.transform.translation.y\n\n\ndef process_flight_data(msg):\n\tglobal sweeping, battery_percentage, battery_low, warning_state\n\t# height == VPS data\n\tbattery_percentage = msg.battery_percentage\n\tbattery_low = bool(msg.battery_low)\n\tif(battery_low == True):\n\t\twarning_state = WarningState.LowBattery\n\ndef process_visp_auto_tracker_status(msg):\n\tglobal possible_target_detected, ignore, machine_state, command_state\n\t#if (data.data >= 3 and not ignore):\n\tif(command_state != CommandState.Manual or machine_state != MachineState.Manual):\n\t\tif (msg.data == 3 or msg.data == 5 and not ignore):\n\t\t\tpossible_target_detected = True\n\n\ndef process_user_input(msg):\n\tglobal user_input, hover_threshold, kill, machine_state, command_state, warning_state, mission_state\n\tuser_input = str(msg.data)\n\tif(\"Land\" in user_input):\n\t\tkill=True\n\telif(\"KeepHovering\" in user_input):\n\t\thover_threshold += 5\n\telif(\"Manual\" in user_input):\n\t\tprint(\"Machine in manual mode.\")\n\t\tmachine_state = MachineState.Manual\n\t\tcommand_state = CommandState.Manual\n\telif(\"Auto\" in user_input):\n\t\tif(warning_state == WarningState.NoVicon):\n\t\t\tprint(\"No Vicon connectivity: cannot assume autonomous control\")\n\t\t\tmachine_state = MachineState.Manual\n\t\t\tcommand_state = CommandState.Manual\n\t\telse:\n\t\t\tmachine_state = MachineState.Default\n\t\t\tcommand_state = CommandState.Auto\n\t\t\twarning_state = WarningState.Default\n\n\ndef process_visp_position(msg):\n\tglobal target_position_x, target_position_y, target_position_z, target_position_angle\n\tglobal curr_x, curr_y, curr_z\n\ttarget_position_x = msg.pose.position.x\n\ttarget_position_y = msg.pose.position.y\n\ttarget_position_z = msg.pose.position.z\n\t# quaternions to radians\n\tsiny_cosp = +2.0 * (msg.pose.orientation.w * msg.pose.orientation.z + msg.pose.orientation.x * msg.pose.orientation.y);\n\tcosy_cosp = +1.0 - 2.0 * (msg.pose.orientation.y * msg.pose.orientation.y + msg.pose.orientation.z * msg.pose.orientation.z); \n\ttarget_position_angle = math.atan2(siny_cosp, cosy_cosp);\n\n\ndef determine_velocity_enum(vel):\n\tvelocity = math.sqrt(vel.linear.x**2 + vel.linear.y**2 + vel.linear.z**2)\n\tif(velocity < 0.3):\n\t\treturn VelocityState.Slow\n\telif(velocity < 0.67):\n\t\treturn VelocityState.Medium\n\telse:\n\t\treturn VelocityState.Fast\n\n\ndef percent_mission_completed(goal_counter):\n\tglobal goal_x, goal_y, interpolation_x, interpolation_y, interpolation_z\n\ttotal_distance = 0.0\n\tfor i in range(0, len(interpolation_x)):\n\t\ttotal_distance += math.sqrt((interpolation_x[i] - curr_x)**2 + (interpolation_y[i] - curr_y)**2 + (interpolation_z[i] - curr_z)**2)\n\ttravelled_distance = 0.0\n\tfor i in range(0, goal_counter+1):\n\t\ttravelled_distance += math.sqrt((interpolation_x[i] - curr_x)**2 + (interpolation_y[i] - curr_y)**2 + (interpolation_z[i] - curr_z)**2)\n\treturn \"{0:.0%}\".format(travelled_distance/total_distance)\n\n\ndef sliding_window(arr, elem):\n\tnew_arr = arr[1:len(arr)]\n\tnew_arr = np.append(new_arr, elem)\n\treturn new_arr\n\n\ndef main():\n\tglobal goal_x, goal_y, interpolation_x, interpolation_y, interpolation_z, home_x, home_y\n\tglobal threshold, hover_threshold\n\tglobal curr_x, curr_y, curr_z, curr_angle\n\tglobal publishing, kill, sweeping, possible_target_detected\n\tglobal user_input, ignore_map, ignore\n\tglobal machine_state, command_state, mission_state, warning_state\n\tglobal target_position_x, target_position_y, target_position_z, target_position_angle\n\n\tprocess_sysargs()\n\n\trospy.init_node(\"sweep\", anonymous=True)\n\tvelocity_publisher = rospy.Publisher(\"/velocity\", Twist, queue_size=1)\n\tmachine_state_publisher = rospy.Publisher(\"/machine_state\", HeadedString, queue_size=1)\n\tmission_state_publisher = rospy.Publisher(\"/mission_state\", HeadedString, queue_size=1)\n\twarning_state_publisher = rospy.Publisher(\"/warning_state\", HeadedString, queue_size=1)\n\tcommand_state_publisher = rospy.Publisher(\"/command_state\", HeadedString, queue_size=1)\n\tvelocity_state_publisher = rospy.Publisher(\"/velocity_state\", HeadedString, queue_size=1)\n\tposition_subscriber = rospy.Subscriber(\"/vicon/TELLO/TELLO\", TransformStamped, vicon_data, queue_size=10)\n\tinput_subscriber = rospy.Subscriber(\"/user_input\", HeadedString, process_user_input, queue_size=1)\n\tflight_data_subscriber = rospy.Subscriber(\"/flight_data\", FlightData, process_flight_data, queue_size=5)\n\tvisp_auto_tracker_status_subscriber = rospy.Subscriber(\"/visp_auto_tracker/status\", Int8, process_visp_auto_tracker_status, queue_size=5)\n\tuser_input_subscriber = rospy.Subscriber(\"/user_input\", HeadedString, process_user_input, queue_size=1)\n\tvisp_position_subscriber = rospy.Subscriber(\"/visp_auto_tracker/object_position\", PoseStamped, process_visp_position, queue_size=1)\n\n\t#nodemap_file = open(os.path.basename(__file__), \"w\")\n\t#nodemap_file.write(rig.topic_node('/velocity'))\n\n\tvel = Twist()\n\tvel.linear.x = 0\n\tvel.angular.z = 0\n\t\n\tset_rate = 20\n\tdt = 1.0/set_rate\n\trate = rospy.Rate(set_rate)\n\n\tintegral = 0\n\tprevious_error = 0\n\tz_integral = 0\n\tz_previous_error = 0\n\tang_previous_error = 0\n\tang_integral = 0\n\tsweep_threshold = 0.25\n\n\t# Defaults: Kp = 0.045; Ki = 0.08; Kd = 0.075\n\t# Super-slow debug mode: Kp = 0.03; Ki = 0.003; Kd = 0.006\n\tKp = 0.27 # 0.41 not good for goal near wall -- overshoot 0.41\n\tKi = 0.00075\n\tKd = 0.01\n\tKp_fast = 0.41; Ki_fast = 0.003; Kd_fast = 0.01\n\tKp_reg = 0.41; Ki_reg = 0.003; Kd_reg = 0.01;\n#\tKp_slow = 0.07; Ki_slow = 0.003; Kd_slow = 0.006;\n#\tKp_slow = 0.0025; Ki_slow = 0.003; Kd_slow = 0.001; #suuuuuuper slow\n\tKp_slow = 0.2; Ki_slow = 0.003; Kd_slow = 0.0075;\n\tpublishing_count = 0\n\thover_count = 0\n\tgoal_counter = 0\n\thome_not_set = True\n\t# ignore_threshold:\t0.65 for QR codes of approx. 18cm width (standard letter paper)\n\t#\t\t\t??? for QR codes of approx. (10x17\" A4 paper)\n\tignore_threshold = 0.065 # 0.1\n\tangle_facing_sweep_area = math.atan2(goal_y[0]-goal_y[1], goal_x[0]-goal_x[1]) + math.pi/2.0\n\tmachine_state = MachineState.Default\n\tignore = False\n\tpublishing_record = np.ones(50, dtype=bool)\n\tlook_closer_count = 0\n\texit_count = 0\n\tbackup_count = 0\n\tif(\"Vicon\" in str(warning_state)):\n\t\twarning_state = str(WarningState.Default)\n\tmission_state = MissionState.Default\n\n\twhile not rospy.is_shutdown():\n\n\t\t#3D Euclidean distance\n\t\tdistance_to_goal = math.sqrt((interpolation_x[goal_counter] - curr_x)**2 + (interpolation_y[goal_counter] - curr_y)**2)\n\t\tz_distance_to_goal = interpolation_z[goal_counter] - curr_z\n\t\tif(home_x != -200 and home_not_set):\n\t\t\tinterpolation_x.append(home_x)\n\t\t\tinterpolation_y.append(home_y)\n\t\t\tinterpolation_z.append(0)\n\t\t\thome_not_set = False\n\t\tprint(\"\")\n\t\tpercent_mission = percent_mission_completed(goal_counter)\n\t\tprint(\"ignore: \"+str(ignore))\n\t\tprint(\"kill: \"+str(kill))\n\t\tprint(\"% mission completed: \"+ percent_mission)\n\t\tprint(\"waypoints visited: \"+str(goal_counter)+\"/\"+str(len(interpolation_x)-1))\n\t\tprint(\"interpolation_x: \"+str(interpolation_x))\n\t\tprint(\"interpolation_y: \"+str(interpolation_y))\n\t\tprint(\"interpolation_z: \"+str(interpolation_z))\n\t\tprint(\"home: \"+str(home_x)+\",\"+str(home_y))\n\t\tprint(\"curr_x, curr_y, curr_z: \"+str(curr_x)+\", \"+str(curr_y)+\", \"+str(curr_z))\n\t\tprint(\"curr_angle: \"+str(math.degrees(curr_angle)))\n\t\t#print(\"goal_x: \"+str(goal_x))\n\t\t#print(\"goal_y: \"+str(goal_y))\n\t\t#print(\"\"+str(math.degrees(angle_facing_sweep_area)))\n\t\tangle_to_goal = math.atan2(interpolation_y[goal_counter]-curr_y, interpolation_x[goal_counter]-curr_x) - curr_angle\n\t\traw_angle_to_goal = math.atan2(interpolation_y[goal_counter]-curr_y, interpolation_x[goal_counter]-curr_x)\n\t\tdesired_angle = math.atan2(goal_y[1]-goal_y[0], goal_x[1]-goal_x[0]) + math.radians(90)\n\n\t\t# Returned to base or user-requested land\n\t\tif(kill):\n\t\t\t# send land cmd then exit\n\t\t\tif(\"Land\" in user_input):\n\t\t\t\tstrmsg = \"User requested land\"\n\t\t\t\tmission_state = MissionState.Abort\n\t\t\t\twarning_state = WarningState.AbortingMission\n\t\t\telse:\n\t\t\t\tstrmsg = \"Returned to base; landing\"\n\t\t\t\tmission_state = MissionState.Complete\n\t\t\t\t#warning_state = WarningState.Default\n\t\t\tmachine_state = MachineState.Landing\n\t\t\tprint(strmsg)\n\t\t\tvel.linear.x = 0\n\t\t\tvel.linear.y = 0\n\t\t\tvel.linear.z = -200\n\t\t\tvelocity_publisher.publish(vel)\n\t\t\tvelocity_publisher.publish(vel)\n\t\t\tvelocity_publisher.publish(vel)\n\t\t\tvelocity_publisher.publish(vel)\n\t\t\tvelocity_publisher.publish(vel)\n\t\t\th = std_msgs.msg.Header()\n\t\t\th.stamp = rospy.Time.now()\n\t\t\theaded_str_msg = HeadedString()\n\t\t\theaded_str_msg.header = h\n\t\t\theaded_str_msg.data = str(machine_state)\n\t\t\tmachine_state_publisher.publish(headed_str_msg)\n\t\t\theaded_str_msg.data = str(mission_state)\n\t\t\tmission_state_publisher.publish(headed_str_msg)\n\t\t\theaded_str_msg.data = str(warning_state)\n\t\t\tmission_state_publisher.publish(headed_str_msg)\n\t\t\texit_count+= 1\n\t\t\tif(exit_count > 5):\n\t\t\t\texit()\n\t\t\tcontinue\n\n\t\t# in manual control mode\n\t\tif(machine_state == str(MachineState.Manual) and str(command_state) == CommandState.Auto and not kill):\n\t\t\th = std_msgs.msg.Header()\n\t\t\th.stamp = rospy.Time.now()\n\t\t\theaded_str_msg = HeadedString()\n\t\t\theaded_str_msg.header = h\n\t\t\theaded_str_msg.data = str(machine_state)\n\t\t\tmachine_state_publisher.publish(headed_str_msg)\n\t\t\theaded_str_msg.data = str(MissionState.InProgress)\n\t\t\tmission_state_publisher.publish(headed_str_msg)\n\t\t\theaded_str_msg.data = str(CommandState.Manual)\n\t\t\tcommand_state_publisher.publish(headed_str_msg)\n\t\t\tcontinue\n\t\telse:\n\t\t\tcommand_state = CommandState.Auto\n\t\t\th = std_msgs.msg.Header()\n\t\t\th.stamp = rospy.Time.now()\n\t\t\theaded_str_msg = HeadedString()\n\t\t\theaded_str_msg.header = h\n\t\t\theaded_str_msg.data = str(command_state)\n\t\t\tcommand_state_publisher.publish(headed_str_msg)\n\n\t\t# Check if current spot has been seen & adjudicated\n\t\tfor i in range(0,len(ignore_map['x'])):\n\t\t\tif math.sqrt((curr_x - ignore_map['x'][i])**2+(curr_y - ignore_map['y'][i])**2+(curr_z - ignore_map['z'][i])**2) < ignore_threshold:\n\t\t\t\tignore = True\n\t\t\telse:\n\t\t\t\tignore = False\n\n\t\t# check for lapse in vicon data\n\t\tpublishing_record = sliding_window(publishing_record, publishing)\n\t\tprint(\"publishingrecord over 1/2 false: \"+str(publishing_record.tolist().count(False) > len(publishing_record)/3.0))\n\t\tif(not publishing and machine_state != MachineState.Manual):\n\t\t\tpublishing_count += 1\n\t\telse:\n\t\t\tpublishing_count = 0\n\t\tif(publishing_count > 5 and machine_state != MachineState.Manual and machine_state != MachineState.Hovering):\n\t\t\tvel.linear.x = 0\n\t\t\tvel.linear.y = 0\n\t\t\tvel.linear.z = 0\n\t\t\twarning_state = str(WarningState.NoVicon)\n\t\t\tmachine_state = str(MachineState.Hovering)\n\t\t\tmission_state = str(MissionState.Suspended)\n\t\t\tprint(str(WarningState.NoVicon))\n\t\t\tprint(str(MachineState.Hovering))\n\t\t\tprint(str(mission_state))\n\t\t\th = std_msgs.msg.Header()\n\t\t\th.stamp = rospy.Time.now()\n\t\t\theaded_str_msg = HeadedString()\n\t\t\theaded_str_msg.header = h\n\t\t\theaded_str_msg.data = str(MachineState.Hovering)\n\t\t\tmachine_state_publisher.publish(headed_str_msg)\n\t\t\theaded_str_msg.data = str(WarningState.NoVicon)\n\t\t\twarning_state_publisher.publish(headed_str_msg)\n\t\t\theaded_str_msg.data = str(mission_state)\n\t\t\tmachine_state_publisher.publish(headed_str_msg)\n\t\t\tvelocity_publisher.publish(vel)\n\t\t\tcontinue\n\t\telif(publishing_record.tolist().count(False) > len(publishing_record)/2.0 and machine_state != MachineState.Manual):\n\t\t\twarning_state = str(WarningState.LosingVicon)\n\t\t\tmachine_state = str(MachineState.LosingVicon)\n\t\t\t#print(machine_state)\n\t\t\t#print(str(WarningState.LosingVicon))\n\t\t\th = std_msgs.msg.Header()\n\t\t\th.stamp = rospy.Time.now()\n\t\t\theaded_str_msg = HeadedString()\n\t\t\theaded_str_msg.header = h\n\t\t\theaded_str_msg.data = machine_state\n\t\t\tmachine_state_publisher.publish(headed_str_msg)\n\t\t\theaded_str_msg.data = str(warning_state)\n\t\t\twarning_state_publisher.publish(headed_str_msg)\n\t\t\t#if(\"Default\" in user_input):\n\t\t\t#\tmission_state = MissionState.WaitingForUser\n\t\t\t#\theaded_str_msg.data = str(mission_state)\n\t\t\t#\tmission_state_publisher.publish(headed_str_msg)\n\n\t\t#Finished sweep\n\t\telif (distance_to_goal < sweep_threshold and z_distance_to_goal < sweep_threshold and interpolation_x[goal_counter] == goal_x[1] and interpolation_x[goal_counter] == goal_y[1] and interpolation_z[goal_counter] == goal_z[1] and machine_state != MachineState.Manual):\n\t\t\tvel.linear.x = 0\n\t\t\tvel.linear.y = 0\n\t\t\thover_count += dt\n\t\t\t#query user for options: Sweep again? Inspect specific point? Go home?\n\t\t\tstrmsg = str(MachineState.FinishedBehavior)\n\t\t\tmachine_state = MachineState.FinishedBehavior\n\t\t\tmission_state = MissionState.FinishedBehavior\n\t\t\tif(hover_count > 10 and goal_counter < len(goal_x)-1):\n\t\t\t\thover_count = 0\n\t\t\t\tintegral = 0\n\t\t\t\tprevious_error = 0\n\t\t\t\tang_previous_error = 0\n\t\t\t\tang_integral = 0\n\t\t\t\tgoal_counter +=1\n\t\t\t#print(strmsg)\n\t\t\t#velocity_publisher.publish(vel)\n\t\t\t#machine_state_publisher.publish(str(machine_state))\n\t\t\t#mission_state_publisher.publish(str(mission_state))\n\t\t\tKp = Kp_reg; Ki = Ki_reg; Kd = Kd_reg\n\n\t\t#arrived back to home base\n\t\telif(distance_to_goal < sweep_threshold and z_distance_to_goal < sweep_threshold and abs(interpolation_x[goal_counter] - home_x) < sweep_threshold and abs(interpolation_y[goal_counter] - home_y) < sweep_threshold and machine_state != MachineState.Manual):\n\t\t\tvel.linear.x = 0\n\t\t\tvel.linear.y = 0\n\t\t\tmachine_state = MachineState.Hovering\n\t\t\tmission_state = MissionState.Complete\n\t\t\tif(hover_count > 2):\n\t\t\t\tvel.linear.z = -200\n\t\t\t\tvelocity_publisher.publish(vel)\n\t\t\t\tstrmsg = \"Returned to home base\"\n\t\t\t\tmachine_state = MachineState.Landing\n\t\t\t\tmission_state = MissionState.Complete\n\t\t\t\t#machine_state_publisher.publish(str(machine_state))\n\t\t\telif(hover_count > 2 and goal_counter == len(goal_x)-1):\n\t\t\t\texit()\n\t\t\t#print(strmsg)\n\t\t\t#print(machine_state)\n\t\t\t#print(mission_state)\n\t\t\t#velocity_publisher.publish(vel)\n\t\t\t#machine_state_publisher.publish(strmsg)\n\t\t\thover_count += dt\n\t\t\t\n\t\t#reached sweeping area\n\t\telif (distance_to_goal < sweep_threshold and goal_counter == 0 and machine_state != MachineState.Manual):\n\t\t\tvel.linear.x = 0\n\t\t\tvel.linear.y = 0\n\t\t\tvel.linear.z = 0\n\t\t\tstrmsg = \"SWEEP AREA REACHED\"\n\t\t\tmachine_state = MachineState.Sweeping\n\t\t\tif(hover_count > 5 and goal_counter == 0):\n\t\t\t\tgoal_counter += 1\n\t\t\t\thover_count = 0\n\t\t\t#print(strmsg)\n\t\t\t#velocity_publisher.publish(vel)\n\t\t\t#machine_state_publisher.publish(str(machine_state))\n\t\t\thover_count += dt\n\t\t\tintegral = 0\n\t\t\tprevious_error = 0\n\t\t\tz_integral = 0\n\t\t\tz_previous_error = 0\n\t\t\tang_previous_error = 0\n\t\t\tang_integral = 0\n\t\t\tKp = Kp_slow; Ki = Ki_slow; Kd = Kd_slow;\n\n\t\t#reached an interpolated goal\n\t\telif (distance_to_goal < sweep_threshold and z_distance_to_goal < sweep_threshold and \"LookCloser\" not in user_input): # and machine_state != MachineState.Manual):\n\t\t\tif(hover_count < 1 and goal_counter < len(interpolation_x)-1):\n\t\t\t\tvel.linear.x = 0\n\t\t\t\tvel.linear.y = 0\n\t\t\t\tvel.linear.z = 0\n\t\t\t\tstrmsg = \"SWEEPING; REACHED INTERPOLATION POINT\"\n\t\t\t#elif(hover_count >= 1 and goal_counter < len(interpolation_x)-1):\n\t\t\telse:\n\t\t\t\tvel.linear.x = 0\n\t\t\t\tvel.linear.y = 0\n\t\t\t\tvel.linear.z = 0\n\t\t\t\tstrmsg = \"SWEEPING; LEAVING INTERPOLATION POINT\"\n\t\t\t\thover_count = 0\n\t\t\t\tintegral = 0\n\t\t\t\tprevious_error = 0\n\t\t\t\tz_integral = 0\n\t\t\t\tz_previous_error = 0\n\t\t\t\tang_previous_error = 0\n\t\t\t\tang_integral = 0\n\t\t\t\tgoal_counter += 1\n\t\t\t#print(strmsg)\n\t\t\tmachine_state = MachineState.Sweeping\n\t\t\tmission_state = MissionState.InsideSweepArea\n\t\t\thover_count += dt\n\t\t\t#velocity_publisher.publish(vel)\n\t\t\t#machine_state_publisher.publish(str(machine_state))\n\t\t\t#mission_state_publisher.publish(str(mission_state))\n\n\t\telif(machine_state != MachineState.Manual):\n\t\t\tif(possible_target_detected and goal_counter < len(interpolation_x)-1 and goal_counter > 0 and not ignore):\n\t\t\t\t#query user for options: Sweep again? Inspect specific point? Go home?\n\t\t\t\tvel.linear.x = 0\n\t\t\t\tvel.linear.y = 0\n\t\t\t\tvel.linear.z = 0\n\t\t\t\tprevious_error = 0\n\t\t\t\tintegral = 0\n\t\t\t\tz_previous_error = 0\n\t\t\t\tz_integral = 0\n\t\t\t\thover_count += dt\n\t\t\t\tif(\"LookCloser\" not in user_input):\n\t\t\t\t\tmachine_state = MachineState.PossibleTargetDetected\n\t\t\t\t\tmission_state = MissionState.PossibleTargetDetected\n\t\t\t\t\tstrmsg = str(MachineState.PossibleTargetDetected)\n\t\t\t\t#print(\"hover_count: \"+str(hover_count))\n\t\t\t\t# look closer auto\n\t\t\t\tif(\"LookCloser\" in user_input):\n\t\t\t\t\tif(look_closer_count < 2.25):\n\t\t\t\t\t\thover_count = 0\n\t\t\t\t\t\tvel.linear.x = 0.15\n\t\t\t\t\t\tvel.linear.y = 0 \n\t\t\t\t\t\tlook_closer_count += dt\n\t\t\t\t\telif(hover_count < 5):\n\t\t\t\t\t\tvel.linear.x = 0\n\t\t\t\t\t\tvel.linear.y = 0\n\t\t\t\t\telse:\n\t\t\t\t\t\tvel.linear.x = -0.15\n\t\t\t\t\t\tvel.linear.y = 0\n\t\t\t\t\t\thover_count = 0\n\t\t\t\t\t\tlook_closer_count = 0\n\t\t\t\t#elif(\"RequestAutoControl\" in user_input and \"Vicon\" in str(warning_state)):\n\t\t\t\t#\tif(backup_count < 3):\n\t\t\t\t#\t\tvel.linear.x = -0.15\n\t\t\t\t#\t\tvel.linear.y = 0\n\t\t\t\t#\t\tbackup_count += dt\n\t\t\t\t#\telse:\n\t\t\t\t#\t\thover_count = 0\n\t\t\t\t#\t\tlook_closer_count = 0\n\t\t\t\t#\t\tbackup_count = 0\n\t\t\t\telif(hover_count > hover_threshold or \"KeepSweeping\" in user_input):\n\t\t\t\t\t#goal_counter = len(interpolation_x)-1\n\t\t\t\t\t#possible_target_detected = False\n\t\t\t\t\tignore = True\n\t\t\t\t\tignore_map['x'].append(curr_x)\n\t\t\t\t\tignore_map['y'].append(curr_y)\n\t\t\t\t\tignore_map['z'].append(curr_z)\n\t\t\t\telif('ReturnHome' in user_input):\n\t\t\t\t\thover_count = 0\n\t\t\t\t\thover_threshold = baseline_hover_threshold\n\t\t\t\t\tgoal_counter = len(interpolation_x)-1\n\t\t\t\telse:\n\t\t\t\t\thover_count = 0\n\t\t\t\t\thover_threshold = baseline_hover_threshold\n\t\t\t\t\tpossible_target_detected = False\n\t\t\telse:\n\t\t\t\tif(goal_counter == 0):\n\t\t\t\t\tstrmsg = \"APPROACHING SWEEP AREA\"\n\t\t\t\t\tmachine_state = MachineState.OutsideSweepArea\n\t\t\t\t\tmission_state = MissionState.OutsideSweepArea\n\n\t\t\t\telif(goal_counter == len(interpolation_x)-1):\n\t\t\t\t\tstrmsg = \"LEAVING SWEEP AREA\"\n\t\t\t\t\tKp = Kp_reg; Ki = Ki_reg; Kd = Kd_reg;\n\t\t\t\t\tmachine_state = MachineState.FinishedBehavior\n\t\t\t\t\tmission_state = MissionState.OutsideSweepArea\n\n\t\t\t\telse:\n\t\t\t\t\tstrmsg = \"SWEEPING\"\n\t\t\t\t\tKp = Kp_slow; Ki = Ki_slow; Kd = Kd_slow;\n\t\t\t\t\tmachine_state = MachineState.Sweeping\n\t\t\t\t\tmission_state = MissionState.InsideSweepArea\n\n\t\t\t\terror = distance_to_goal\n\t\t\t\tderivative = (error - previous_error) / dt\n\t\t\t\tintegral = integral + (error * dt)\n\t\t\t\tw = Kp*error + Ki*integral + Kd*derivative\n\t\t\t\tprevious_error = error\n\n\t\t\t\tz_error = z_distance_to_goal\n\t\t\t\tz_derivative = (z_error - z_previous_error) / dt\n\t\t\t\tz_integral = z_integral + (z_error * dt)\n\t\t\t\tz_w = Kp * z_error + Ki * z_integral + Kd * z_derivative\n\t\t\t\tz_previous_error = z_error\n\n\t\t\t\t#ang_error = math.atan2(math.sin(curr_angle-desired_angle), math.cos(curr_angle-desired_angle)) # math.atan2(math.sin(raw_angle_to_goal - curr_angle), math.cos(raw_angle_to_goal - curr_angle))\n\t\t\t\t#ang_derivative = (ang_error - ang_previous_error) / dt\n\t\t\t\t#ang_integral = z_integral + (ang_error * dt)\n\t\t\t\t#ang_w = Kp * ang_error + Ki * ang_integral + Kd * ang_derivative\n\t\t\t\t#ang_w = math.atan2(math.sin(ang_w), math.cos(ang_w))\n\t\t\t\t#ang_previous_error = ang_error\n\n\t\t\t\t#ang_w = ang_error #* 0.25\n\t\t\t\t#if(ang_w > 1):\n\t\t\t\t#\tang_w = 1\n\t\t\t\t#elif(ang_w < -1):\n\t\t\t\t#\tang_w = -1\n\t\t\t\t#elif(abs(math.atan2(math.sin(desired_angle-curr_angle), math.cos(desired_angle-curr_angle))) < math.radians(15)):\n\t\t\t\t#\tang_w = 0\n\n\t\t\t\tvel.linear.x = math.cos(angle_to_goal) * w\n\t\t\t\t#negative sin due to how Tello interprets roll (right = pos)\n\t\t\t\tvel.linear.y = -math.sin(angle_to_goal) * w\n\t\t\t\tvel.linear.z = z_w * 5.5\n\t\t\t\tvel.angular.z = 0 # ang_w\n\t\t\t\n\t\t\t\t# max tello speed is +-1\n\t\t\t\tif(vel.linear.y > 1):\n\t\t\t\t\tvel.linear.y = 1\n\t\t\t\tif(vel.linear.y < -1):\n\t\t\t\t\tvel.linear.y = -1\n\t\t\t\tif(vel.linear.x > 1):\n\t\t\t\t\tvel.linear.x = 1\n\t\t\t\tif(vel.linear.x < -1):\n\t\t\t\t\tvel.linear.x = -1\n\t\t\t\tif(vel.linear.z > 1):\n\t\t\t\t\tvel.linear.z = 1\n\t\t\t\tif(vel.linear.z < -1):\n\t\t\t\t\tvel.linear.z = -1\n\n\t\tprint(\"vel.x, vel.y, vel.z: \"+ str(vel.linear.x)+\", \"+ str(vel.linear.y)+\", \"+ str(vel.linear.z))\n\t\t#print(\"vel.ang.z: \"+str(vel.angular.z))\n\t\t#print(\"Kp, Ki, Kd: \"+str(Kp)+\" \"+str(Ki)+\" \"+str(Kd))\n\t\t#print(\"desired_angle: \"+str(math.degrees(desired_angle)))\n\t\t#print(\"angle_error: \"+str(math.atan2(math.sin(desired_angle-curr_angle), math.cos(desired_angle-curr_angle))))\n\t\tprint(strmsg)\n\t\tprint(str(machine_state))\n\t\tprint(str(mission_state))\n\t\tprint(str(warning_state))\n\t\tprint(str(user_input))\n\t\tprint(str(command_state))\n\t\tvel_enum = determine_velocity_enum(vel)\n\t\tprint(str(vel_enum))\n\t\th = std_msgs.msg.Header()\n\t\th.stamp = rospy.Time.now()\n\t\theaded_str_msg = HeadedString()\n\t\theaded_str_msg.header = h\n\t\theaded_str_msg.data = str(machine_state)\n\t\tmachine_state_publisher.publish(headed_str_msg)\n\t\theaded_str_msg.data = str(mission_state)\n\t\tmission_state_publisher.publish(headed_str_msg)\n\t\theaded_str_msg.data = str(warning_state)\n\t\twarning_state_publisher.publish(headed_str_msg)\n\t\theaded_str_msg.data = str(command_state)\n\t\tcommand_state_publisher.publish(headed_str_msg)\n\t\t#determine velocity state\n\n\t\theaded_str_msg.data = str(vel_enum)\n\t\tvelocity_state_publisher.publish()\n\t\tvelocity_publisher.publish(vel)\t\n\t\tpublishing = False\n\t\twarning_state = WarningState.Default\n\t\trate.sleep()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/predator/scripts/sweep_for_target.py","file_name":"sweep_for_target.py","file_ext":"py","file_size_in_byte":24678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"498693395","text":"#!/usr/bin/env python\n# coding: utf-8\n\nfrom swisscom_ai.research_keyphrase.embeddings.emb_distrib_local import EmbeddingDistributorLocal\nfrom swisscom_ai.research_keyphrase.model.input_representation import InputTextObj\nfrom swisscom_ai.research_keyphrase.model.method import MMRPhrase\nfrom swisscom_ai.research_keyphrase.preprocessing.postagging import PosTaggingStanford\nfrom swisscom_ai.research_keyphrase.util.fileIO import read_file\nimport os\nimport numpy as np\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom flair.embeddings import WordEmbeddings, FlairEmbeddings, DocumentPoolEmbeddings, Sentence\nfrom flair.embeddings import WordEmbeddings, FlairEmbeddings, DocumentLSTMEmbeddings\nfrom flair.embeddings import BertEmbeddings\n\n\n\n# initialize the word embeddings\nglove_embedding = WordEmbeddings('glove')\nflair_embedding_forward = FlairEmbeddings('news-forward')\nflair_embedding_backward = FlairEmbeddings('news-backward')\nFT_embedding = WordEmbeddings('en')\nbert_embedding = BertEmbeddings('bert-large-uncased')\n\n\n# initialize the document embeddings\ndocument_embeddings = DocumentPoolEmbeddings([glove_embedding])\n\n\n# load pos tagger\ndef load_local_pos_tagger(lang):\n assert (lang in ['en', 'de', 'fr']), \"Only english 'en', german 'de' and french 'fr' are handled\"\n #jar_path = config_parser.get('STANFORDTAGGER', 'jar_path')\n stanford_ner_dir = './stanford-postagger-full-2018-10-16/'\n model_directory_path= './stanford-postagger-full-2018-10-16/models/'\n jar_path= stanford_ner_dir + 'stanford-postagger.jar'\n\n return PosTaggingStanford(jar_path, model_directory_path, lang=lang)\n\n\n\n# Maximal Marginal Relevance Similarity Calculation\ndef _MMR(candidates, X, doc_embedd, beta, N):\n \"\"\"\n Core method using Maximal Marginal Relevance in charge to return the top-N candidates\n :param embdistrib: embdistrib: embedding distributor see @EmbeddingDistributor\n :param text_obj: Input text representation see @InputTextObj\n :param candidates: list of candidates (string)\n :param X: numpy array with the embedding of each candidate in each row\n :param beta: hyperparameter beta for MMR (control tradeoff between informativeness and diversity)\n :param N: number of candidates to extract\n :param use_filtered: if true filter the text by keeping only candidate word before computing the doc embedding\n :return: A tuple with 3 elements :\n 1)list of the top-N candidates (or less if there are not enough candidates) (list of string)\n 2)list of associated relevance scores (list of float)\n 3)list containing for each keyphrase a list of alias (list of list of string)\n \"\"\"\n\n N = min(N, len(candidates))\n doc_sim = cosine_similarity(X, doc_embedd)\n\n doc_sim_norm = doc_sim/np.max(doc_sim)\n doc_sim_norm = 0.5 + (doc_sim_norm - np.average(doc_sim_norm)) / np.std(doc_sim_norm)\n\n sim_between = cosine_similarity(X)\n np.fill_diagonal(sim_between, np.NaN)\n\n sim_between_norm = sim_between/np.nanmax(sim_between, axis=0)\n sim_between_norm = 0.5 + (sim_between_norm - np.nanmean(sim_between_norm, axis=0)) / np.nanstd(sim_between_norm, axis=0)\n\n selected_candidates = []\n unselected_candidates = [c for c in range(len(candidates))]\n\n j = np.argmax(doc_sim)\n selected_candidates.append(j)\n unselected_candidates.remove(j)\n\n for _ in range(N - 1):\n selec_array = np.array(selected_candidates)\n unselec_array = np.array(unselected_candidates)\n\n distance_to_doc = doc_sim_norm[unselec_array, :]\n dist_between = sim_between_norm[unselec_array][:, selec_array]\n if dist_between.ndim == 1:\n dist_between = dist_between[:, np.newaxis]\n j = np.argmax(beta * distance_to_doc - (1 - beta) * np.max(dist_between, axis=1).reshape(-1, 1))\n item_idx = unselected_candidates[j]\n selected_candidates.append(item_idx)\n unselected_candidates.remove(item_idx)\n return selected_candidates\n \n\n\n# Evaluation\nimport argparse\nfrom configparser import ConfigParser\nfrom swisscom_ai.research_keyphrase.model.extractor import extract_candidates, extract_sent_candidates\npos_tagger = load_local_pos_tagger('en')\ncount = 0\ntp = 0\nr = 0\np = 0\nF = 0\nfor file in os.listdir(\"./Dataset/Hulth2003/Test/\"):\n # select only 200 text samples to test\n if(count == 100): break\n if file.endswith(\".abstr\"):\n print('Processing: ',file)\n path = os.path.join(\"./Dataset/Hulth2003/Test/\", file)\n f=open(path,'r').read()\n f = f.replace(\"\\n\", \" \")\n f = f.replace(\"\\t\", \" \")\n raw_text = f\n #print(raw_text)\n tagged = pos_tagger.pos_tag_raw_text(raw_text)\n text_obj = InputTextObj(tagged, 'en')\n # List of candidates based on PosTag rules\n candidates = np.array(extract_candidates(text_obj)) \n # Remove Duplicates\n candidates = list(set(candidates))\n #print(candidates)\n tagged = text_obj.filtered_pos_tagged\n tokenized_doc_text = ' '.join(token[0].lower() for sent in tagged for token in sent)\n #print(tokenized_doc_text)\n document = Sentence(tokenized_doc_text)\n #print(document)\n document_embeddings.embed(document)\n doc = document.get_embedding()\n #print(doc)\n #print(doc.shape)\n score = []\n for x in candidates:\n sentence = Sentence(x)\n document_embeddings.embed(sentence)\n res = sentence.get_embedding()\n temp = res.numpy()\n score.append(temp[0])\n doc = doc.numpy()\n score = np.asarray(score)\n #print(score)\n #print(score.shape)\n # result contains index of the top 15 candidate keyphrases\n result = _MMR(candidates, score, doc, 1, 15)\n #print(result)\n pred_kp = []\n for i in range(len(result)):\n pred_kp.append(candidates[result[i]].lower())\n print('predicted keyphrases: ', pred_kp)\n f2=open(\"./Dataset/Hulth2003/Test/\" + file[:-6]+\".uncontr\",'r').read()\n f2 = f2.replace(\"\\n\", \"\")\n f2 = f2.replace(\"\\t\", \" \")\n f2 = f2.split('; ')\n actual_kp = f2\n for x in actual_kp:\n x_lower = x.lower()\n if raw_text.find(x_lower) == -1:\n actual_kp.remove(x)\n for x in actual_kp:\n x = x.lower()\n actual_kp = list(set(actual_kp))\n print('actual keyphrases: ',actual_kp)\n intersect = list(set(pred_kp).intersection(actual_kp))\n tp = tp + len(intersect)\n #print(intersect)\n #print(tp)\n r = r + len(pred_kp)\n #print(r)\n p = p + len(actual_kp)\n #print(p)\n count = count + 1\n \nprecision = tp / p\nrecall = tp / r\nF = 2*precision*recall / (precision + recall)\nprint(precision)\nprint(recall)\nprint(F)\n\n\n","sub_path":"Glove.py","file_name":"Glove.py","file_ext":"py","file_size_in_byte":6830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"317428163","text":"from collections import OrderedDict\nfrom typing import Union, List, cast, Optional\n\nfrom mypy.checker import TypeChecker\nfrom mypy.nodes import StrExpr, TypeInfo\nfrom mypy.plugin import MethodContext, CheckerPluginInterface\nfrom mypy.types import Type, Instance, AnyType, TypeOfAny\n\nfrom mypy_django_plugin import helpers\nfrom mypy_django_plugin.lookups import resolve_lookup, RelatedModelNode, LookupException\n\n\ndef extract_proper_type_for_values_and_values_list(method_name: str, ctx: MethodContext) -> Type:\n api = cast(TypeChecker, ctx.api)\n\n object_type = ctx.type\n if not isinstance(object_type, Instance):\n return ctx.default_return_type\n\n ret = ctx.default_return_type\n\n any_type = AnyType(TypeOfAny.implementation_artifact)\n fields_arg_expr = ctx.args[ctx.callee_arg_names.index('fields')]\n\n model_arg: Union[AnyType, Type] = ret.args[0] if len(ret.args) > 0 else any_type\n\n column_names: List[Optional[str]] = []\n column_types: OrderedDict[str, Type] = OrderedDict()\n\n fill_column_types = True\n\n if len(fields_arg_expr) == 0:\n # values_list/values with no args is not yet supported, so default to Any types for field types\n # It should in the future include all model fields, \"extra\" fields and \"annotated\" fields\n fill_column_types = False\n\n if isinstance(model_arg, Instance):\n model_type_info = model_arg.type\n else:\n model_type_info = None\n\n # Figure out each field name passed to fields\n has_dynamic_column_names = False\n for field_expr in fields_arg_expr:\n if isinstance(field_expr, StrExpr):\n field_name = field_expr.value\n column_names.append(field_name)\n # Default to any type\n column_types[field_name] = any_type\n\n if model_type_info:\n resolved_lookup_type = resolve_values_lookup(ctx.api, model_type_info, field_name)\n if resolved_lookup_type is not None:\n column_types[field_name] = resolved_lookup_type\n else:\n # Dynamic field names are partially supported for values_list, but not values\n column_names.append(None)\n has_dynamic_column_names = True\n\n if method_name == 'values_list':\n flat = helpers.parse_bool(helpers.get_argument_by_name(ctx, 'flat'))\n named = helpers.parse_bool(helpers.get_argument_by_name(ctx, 'named'))\n\n if named and flat:\n api.fail(\"'flat' and 'named' can't be used together.\", ctx.context)\n return ret\n elif named:\n if fill_column_types and not has_dynamic_column_names:\n row_arg = helpers.make_named_tuple(api, fields=column_types, name=\"Row\")\n else:\n row_arg = helpers.make_named_tuple(api, fields=OrderedDict(), name=\"Row\")\n elif flat:\n if len(ctx.args[0]) > 1:\n api.fail(\"'flat' is not valid when values_list is called with more than one field.\", ctx.context)\n return ret\n if fill_column_types and not has_dynamic_column_names:\n # Grab first element\n row_arg = column_types[column_names[0]]\n else:\n row_arg = any_type\n else:\n if fill_column_types:\n args = [\n # Fallback to Any if the column name is unknown (e.g. dynamic)\n column_types.get(column_name, any_type) if column_name is not None else any_type\n for column_name in column_names\n ]\n else:\n args = [any_type]\n row_arg = helpers.make_tuple(api, fields=args)\n elif method_name == 'values':\n expression_arg_names = ctx.arg_names[ctx.callee_arg_names.index('expressions')]\n for expression_name in expression_arg_names:\n # Arbitrary additional annotation expressions are supported, but they all have type Any for now\n column_names.append(expression_name)\n column_types[expression_name] = any_type\n\n if fill_column_types and not has_dynamic_column_names:\n row_arg = helpers.make_typeddict(api, fields=column_types, required_keys=set())\n else:\n return ctx.default_return_type\n else:\n raise Exception(f\"extract_proper_type_for_values_list doesn't support method {method_name}\")\n\n new_type_args = [model_arg, row_arg]\n return helpers.reparametrize_instance(ret, new_type_args)\n\n\ndef resolve_values_lookup(api: CheckerPluginInterface, model_type_info: TypeInfo, lookup: str) -> Optional[Type]:\n \"\"\"Resolves a values/values_list lookup if possible, to a Type.\"\"\"\n try:\n nodes = resolve_lookup(api, model_type_info, lookup)\n except LookupException:\n nodes = []\n\n if not nodes:\n return None\n\n make_optional = False\n\n for node in nodes:\n if isinstance(node, RelatedModelNode) and node.is_nullable:\n # All lookups following a relation which is nullable should be optional\n make_optional = True\n\n node = nodes[-1]\n\n node_type = node.typ\n if isinstance(node, RelatedModelNode):\n # Related models used in values/values_list get resolved to the primary key of the related model.\n # So, we lookup the pk of that model.\n pk_lookup_nodes = resolve_lookup(api, node_type.type, \"pk\")\n if not pk_lookup_nodes:\n return None\n node_type = pk_lookup_nodes[0].typ\n if make_optional:\n return helpers.make_optional(node_type)\n else:\n return node_type\n","sub_path":"keywords_generator_server/venv/lib/python3.6/site-packages/mypy_django_plugin/transformers/queryset.py","file_name":"queryset.py","file_ext":"py","file_size_in_byte":5577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"193085432","text":"from PIL import Image, ImageTk\nfrom Tkinter import Tk, Frame, Label\n\nclass Example(Frame):\n def __init__(self, parent):\n Frame.__init__(self, parent)\n self.parent = parent\n self.initUI()\n\n def initUI(self):\n self.parent.title(\"Title\")\n self.img = Image.open(\"./img/tatras.jpg\")\n tatras = ImageTk.PhotoImage(self.img)\n label = Label(self, image=tatras)\n\n # Reference must be stored\n label.image = tatras\n\n label.pack()\n self.pack()\n\n def setGeometry(self):\n w, h = self.img.size\n self.parent.geometry(\"{}x{}+300+300\".format(w,h))\n\ndef main():\n root = Tk()\n ex = Example(root)\n ex.setGeometry()\n root.mainloop()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Tutorials/Tkinter/label.py","file_name":"label.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"408161528","text":"import datetime\n\nfrom dateutil.relativedelta import relativedelta\n\nfrom django.core.management.base import BaseCommand, CommandError\nfrom django.db.models import Q\n\nfrom notifications.models import ProjectExpiredNotifications\n\nfrom userinput.models import Project, RUBIONUser\n\nfrom website.models import EMailText\n\nclass Command(BaseCommand):\n help = 'Sends an notification mail to users whose projects are about to run out.'\n\n def __init__(self, *args, **kwargs):\n self.today = datetime.datetime.today()\n self.next_month = self.today + relativedelta(months = +1)\n self.two_weeks_ago = self.today + relativedelta(weeks=-2)\n self.one_weeks_ago = self.today + relativedelta(weeks=-1)\n super(Command, self).__init__(*args, **kwargs)\n \n def add_arguments(self, parser):\n # Named (optional) arguments\n parser.add_argument(\n '--list',\n action='store_true',\n help='Lists the projects on STDOUT',\n )\n\n \n def handle(self, *args, **options):\n recently_send = ProjectExpiredNotifications.objects.filter(mail__sent_at__gt = self.one_weeks_ago)\n ids = []\n for rs in recently_send.all():\n ids.append(rs.id)\n projects_soon = Project.objects.filter(\n expire_at__gt = self.today, expire_at__lt = self.next_month, locked = False\n ).exclude(id__in = ids)\n projects_expired = Project.objects.filter(expire_at__lte = self.today, locked = False)\n \n if options['list']:\n self.list_projects(\"Expired projects\", projects_expired)\n self.list_projects(\"Projects expiring soon\", projects_soon)\n\n else:\n for project in projects_expired:\n if self.needs_to_be_sent( project ):\n self.send_expired_mail( project )\n\n for project in projects_soon:\n if self.needs_to_be_sent( project ):\n self.send_will_soon_expire_mail( project )\n\n\n def send_expired_mail( self, project ):\n mail = EMailText.objects.get(identifier = 'warning.project.expired')\n self.send_mail(mail, project)\n \n \n def send_will_soon_expire_mail( self, project ):\n mail = EMailText.objects.get(identifier = 'warning.project.will_expire')\n self.send_mail(mail, project)\n\n def send_mail( self, mail, project ):\n contacts = self.get_contacts( project.get_workgroup() )\n to = []\n languages = []\n for contact in contacts:\n to.append(contact.email)\n if contact.preferred_language is not None:\n languages.append(contact.preferred_language)\n\n languages = list(set(languages)) # removes duplicates\n if len(languages) == 1:\n languages = languages[0]\n else:\n languages = None\n \n sent_mail = mail.send(\n to, {\n 'contacts' : contacts,\n 'project_de' : project.title_de,\n 'project_en' : project.title,\n 'expires' : project.expire_at\n },\n lang = languages \n )\n noti = ProjectExpiredNotifications(\n project=project, mail = sent_mail\n ).save()\n \n def needs_to_be_sent( self, project ):\n notifications = ProjectExpiredNotifications.objects.filter(project = project).order_by('-mail__sent_at')\n try:\n last = notifications[0]\n except IndexError:\n return True\n\n if last.mail.sent_at < self.two_weeks_ago:\n return True\n\n return False\n \n\n \n def list_projects(self, title, projects):\n self.stdout.write(\"\\n{}:\".format(title))\n self.stdout.write(\"--------------------------------------------------\")\n for project in projects:\n wg = project.get_workgroup()\n self.stdout.write(\"\\n{}: {}\".format(str(project.expire_at),str(project)))\n self.stdout.write(\"Group: {}\".format(wg))\n self.stdout.write(\"Head of group: {}\".format(wg.get_head()))\n self.stdout.write(\"Contacts:\")\n for con in self.get_contacts(wg).all():\n self.stdout.write(\" - {} <{}>\".format(con.full_name(), con.email))\n\n self.stdout.write(\"Needs to be sent: {}\".format(self.needs_to_be_sent(project)))\n\n def get_contacts(self, wg):\n return RUBIONUser.objects.live().descendant_of(wg).filter(\n Q(is_leader = True) | Q(may_create_projects = True)\n )\n \n \n \n","sub_path":"userinput/management/commands/warn_projects.py","file_name":"warn_projects.py","file_ext":"py","file_size_in_byte":4600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"510474892","text":"\"\"\"\nPerceptually uniform colourmaps for geosciences\n\nPackaging of colourmaps created by Fabio Crameri http://www.fabiocrameri.ch/colourmaps.php\n\nCreated by Callum Rollo\n2020-05-06\n\"\"\"\n\nimport numpy as np\nfrom pathlib import Path\nfrom matplotlib.colors import LinearSegmentedColormap\nimport matplotlib.pyplot as plt\nimport os\n# Find the colormap text files and make a list of the paths\ntext_file_folder = os.path.join(os.path.dirname(__file__), 'cmaps')\npaths = list(Path(text_file_folder).glob('*.txt'))\ncrameri_cmaps = dict()\ncrameri_cmaps_r = dict()\ncrameri_cmaps_s = dict()\nfor cmap_path in paths:\n # Name of colour map taken from text file\n cmap_name = os.path.split(cmap_path)[1][:-4]\n cm_data = np.loadtxt(str(cmap_path))\n # Make a linear segmented colour map\n if cmap_name[-1] == 'S':\n crameri_cmaps_s[cmap_name] = LinearSegmentedColormap.from_list(cmap_name, cm_data)\n continue\n crameri_cmaps[cmap_name] = LinearSegmentedColormap.from_list(cmap_name, cm_data)\n # reverse the colour map and add this to the dictionary crameri_cmaps_r, mpt fpr categorical maps\n crameri_cmaps_r[cmap_name + '_r'] = LinearSegmentedColormap.from_list(cmap_name + '_r', cm_data[::-1, :])\n\n\ndef show_cmaps():\n \"\"\"\n A rough function for a quick plot of the colourmaps. Nowhere near as pretty as the original\n see http://www.fabiocrameri.ch/colourmaps.php\n :return:\n \"\"\"\n x = np.linspace(0, 100, 100)[None, :]\n fig, axs = plt.subplots(int(np.ceil(len(crameri_cmaps) / 7)), 7, figsize=(22, 10))\n fig.subplots_adjust(hspace=.8, wspace=.08)\n axs = axs.ravel()\n for ax in axs:\n ax.axis('off')\n for c, cmap_selected in enumerate(sorted(crameri_cmaps.keys())):\n colourmap = crameri_cmaps[cmap_selected]\n axs[c].pcolor(x, cmap=colourmap)\n axs[c].text(5, -0.3, cmap_selected, fontsize=26)\n\n\n# So colourmaps can be called in other programs\nlocals().update(crameri_cmaps)\nlocals().update(crameri_cmaps_r)\nlocals().update(crameri_cmaps_s)\n","sub_path":"cmcrameri/cm.py","file_name":"cm.py","file_ext":"py","file_size_in_byte":2010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"64692943","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n__author__ = 'ipetrash'\n\n\nimport datetime as DT\nimport functools\nimport html\nimport logging\nimport sys\nfrom pathlib import Path\nfrom typing import Union, Optional\n\nfrom telegram import Update, ReplyKeyboardMarkup, InlineKeyboardMarkup, InlineKeyboardButton\nfrom telegram.ext import MessageHandler, CommandHandler, CallbackContext, Filters\nfrom telegram.ext.filters import MergedFilter\n\nimport db\nfrom config import HELP_TEXT, ADMIN_USERNAME, TEXT_BUTTON_MORE, DIR_COMICS\nfrom parsers import bash_im\n\n\ndef get_logger(file_name: str, dir_name='logs'):\n dir_name = Path(dir_name).resolve()\n dir_name.mkdir(parents=True, exist_ok=True)\n\n file_name = str(dir_name / Path(file_name).resolve().name) + '.log'\n\n log = logging.getLogger(__name__)\n log.setLevel(logging.DEBUG)\n\n formatter = logging.Formatter('[%(asctime)s] %(filename)s[LINE:%(lineno)d] %(levelname)-8s %(message)s')\n\n fh = logging.FileHandler(file_name, encoding='utf-8')\n fh.setLevel(logging.DEBUG)\n\n ch = logging.StreamHandler(stream=sys.stdout)\n ch.setLevel(logging.DEBUG)\n\n fh.setFormatter(formatter)\n ch.setFormatter(formatter)\n\n log.addHandler(fh)\n log.addHandler(ch)\n\n return log\n\n\ndef has_admin_filter(filter_handler) -> bool:\n if filter_handler is FILTER_BY_ADMIN:\n return True\n\n if isinstance(filter_handler, MergedFilter):\n return any([\n has_admin_filter(filter_handler.base_filter),\n has_admin_filter(filter_handler.and_filter),\n has_admin_filter(filter_handler.or_filter),\n ])\n\n return False\n\n\ndef get_doc(obj) -> Optional[str]:\n if not obj or not obj.__doc__:\n return\n\n items = []\n for line in obj.__doc__.splitlines():\n if line.startswith(' '):\n line = line[4:]\n\n items.append(line)\n\n return '\\n'.join(items).strip()\n\n\nREPLY_KEYBOARD_MARKUP = ReplyKeyboardMarkup(\n [[TEXT_BUTTON_MORE]], resize_keyboard=True\n)\n\nFILTER_BY_ADMIN = Filters.user(username=ADMIN_USERNAME)\n\nBUTTON_HELP_COMMON = InlineKeyboardButton('⬅️ Общие команды', callback_data='help_common')\nBUTTON_HELP_ADMIN = InlineKeyboardButton('Команды админа ➡️', callback_data='help_admin')\n\nCOMMON_COMMANDS = []\nADMIN_COMMANDS = []\n\nlog = get_logger(Path(__file__).resolve().parent.name)\n\n\ndef fill_commands_for_help(dispatcher):\n for commands in dispatcher.handlers.values():\n for command in commands:\n if not isinstance(command, (CommandHandler, MessageHandler)):\n continue\n\n help_command = get_doc(command.callback)\n if not help_command:\n continue\n\n if has_admin_filter(command.filters):\n if help_command not in ADMIN_COMMANDS:\n ADMIN_COMMANDS.append(help_command)\n else:\n if help_command not in COMMON_COMMANDS:\n COMMON_COMMANDS.append(help_command)\n\n\ndef log_func(log: logging.Logger):\n def actual_decorator(func):\n @functools.wraps(func)\n def wrapper(update: Update, context: CallbackContext):\n if update:\n chat_id = user_id = first_name = last_name = username = language_code = None\n\n if update.effective_chat:\n chat_id = update.effective_chat.id\n\n if update.effective_user:\n user_id = update.effective_user.id\n first_name = update.effective_user.first_name\n last_name = update.effective_user.last_name\n username = update.effective_user.username\n language_code = update.effective_user.language_code\n\n try:\n message = update.effective_message.text\n except:\n message = ''\n\n try:\n query_data = update.callback_query.data\n\n # Содержит текущий текст сообщения, под которым была inline-кнопка\n # Нет смысла логировать этот текст\n message = ''\n except:\n query_data = ''\n\n msg = f'[chat_id={chat_id}, user_id={user_id}, ' \\\n f'first_name={first_name!r}, last_name={last_name!r}, ' \\\n f'username={username!r}, language_code={language_code}, ' \\\n f'message={message!r}, query_data={query_data!r}]'\n msg = func.__name__ + msg\n\n log.debug(msg)\n\n return func(update, context)\n\n return wrapper\n return actual_decorator\n\n\ndef update_quote(quote_id: int, update: Update = None, context: CallbackContext = None):\n need_reply = update and context\n\n quote_bashim = bash_im.Quote.parse_from(quote_id)\n if not quote_bashim:\n text = f'Цитаты #{quote_id} на сайте нет'\n log.info(text)\n need_reply and reply_error(text, update, context)\n return\n\n quote_db: db.Quote = db.Quote.get_or_none(quote_id)\n if not quote_db:\n log.info(f'Цитаты #{quote_id} в базе нет, будет создание цитаты')\n\n # При отсутствии, цитата будет добавлена в базу\n db.Quote.get_from(quote_bashim)\n\n # Сразу же пробуем скачать комиксы\n quote_bashim.download_comics(DIR_COMICS)\n\n text = f'Цитата #{quote_id} добавлена в базу'\n log.info(text)\n need_reply and reply_info(text, update, context)\n\n else:\n # TODO: Поддержать проверку и добавление новых комиксов\n modified_list = []\n\n if quote_db.text != quote_bashim.text:\n quote_db.text = quote_bashim.text\n modified_list.append('текст')\n\n if modified_list:\n quote_db.modification_date = DT.date.today()\n quote_db.save()\n\n text = f'Цитата #{quote_id} обновлена ({\", \".join(modified_list)})'\n log.info(text)\n need_reply and reply_info(text, update, context)\n\n else:\n text = f'Нет изменений в цитате #{quote_id}'\n log.info(text)\n need_reply and reply_info(text, update, context)\n\n\ndef get_html_message(quote: Union[bash_im.Quote, db.Quote]) -> str:\n text = html.escape(quote.text)\n footer = f\"\"\"{quote.date_str} | #{quote.id}\"\"\"\n return f'{text}\\n\\n{footer}'\n\n\ndef reply_help(update: Update, context: CallbackContext):\n query = update.callback_query\n message = update.effective_message\n query_data = None\n\n # Если функция вызвана из CallbackQueryHandler\n if query:\n query.answer()\n query_data = query.data\n\n username = update.effective_user.username\n is_admin = username == ADMIN_USERNAME[1:]\n\n show_common_help = True\n if query_data:\n show_common_help = query_data.endswith('common')\n\n text_common = HELP_TEXT + '\\n\\n' + '\\n\\n'.join(COMMON_COMMANDS)\n text_admin = '\\n\\n'.join(ADMIN_COMMANDS)\n\n if is_admin:\n text = text_common if show_common_help else text_admin\n next_button = BUTTON_HELP_ADMIN if show_common_help else BUTTON_HELP_COMMON\n reply_markup = InlineKeyboardMarkup.from_button(next_button)\n else:\n text = text_common\n reply_markup = REPLY_KEYBOARD_MARKUP\n\n if query:\n message.edit_text(text, reply_markup=reply_markup)\n else:\n message.reply_text(text, reply_markup=reply_markup)\n\n\ndef reply_error(text: str, update: Update, context: CallbackContext):\n update.effective_message.reply_text(\n '⚠ ' + text\n )\n\n\ndef reply_info(text: str, update: Update, context: CallbackContext):\n update.effective_message.reply_text(\n 'ℹ️ ' + text\n )\n\n\ndef reply_quote(\n quote: Union[bash_im.Quote, db.Quote],\n update: Update,\n context: CallbackContext,\n reply_markup: ReplyKeyboardMarkup = None\n):\n # Отправка цитаты и отключение link preview -- чтобы по ссылке не генерировалась превью\n update.effective_message.reply_html(\n get_html_message(quote),\n disable_web_page_preview=True,\n reply_markup=reply_markup\n )\n","sub_path":"common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":8513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"395527337","text":"# coding=utf-8\nimport sys,os\nbase_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsys.path.append(base_dir)\nimport requests\nimport json\nclass RunMain:\n def send_get(self, url, data):\n res = requests.get(url=url, params=data).json()\n return res\n\n def send_post(self, url, data):\n res = requests.post(url=url, data=data).json()\n return res\n\n def run_main(self,url,method,data=None):\n res = None\n if method == 'GET':\n res = self.send_get(url, data)\n else:\n res = self.send_post(url, data)\n return res\n\nif __name__ == '__main__':\n url = 'http://dealerapp.bmw.com.cn/api/dealer/user/login'\n data = {\n 'phone':'18800009631',\n 'pin':'0000',\n 'deviceCode':'888888',\n 'clientOsType':'2',\n 'clientVersion':'1.1.0'\n }\n\n res = RunMain().run_main(url,'GET',data)\n print(res)","sub_path":"AFS_api/base/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"483463154","text":"import sys\nimport time\nfrom typing import Iterable\n\n\ndef compute_fuel(x: int) -> int:\n y = max(0, ((x // 3) - 2))\n return y + compute_fuel(y) if y > 0 else y\n\n\ndef solve(input_iter: Iterable[str]) -> int:\n modules = [int(line.strip()) for line in input_iter]\n return sum(compute_fuel(module) for module in modules)\n\n\ndef run_tests():\n tests = [\n [\"12\"],\n [\"14\"],\n [\"1969\"],\n [\"100756\"],\n ]\n\n answers = [\n 2,\n 2,\n 966,\n 50346,\n ]\n\n for i, (test, answer) in enumerate(zip(tests, answers), start=1):\n print('Running test: {}/{}'.format(i, len(tests)))\n start = time.time()\n computed = solve(test)\n end = time.time()\n assert computed == answer, (test, answer, computed)\n print('OK. Took {:.2f}'.format(end - start))\n\n\nif __name__ == '__main__':\n run_tests()\n print(solve(sys.stdin))\n","sub_path":"2019/solutions/day1_part2.py","file_name":"day1_part2.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"18589488","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport datetime\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('admin', '0008_auto_20170620_0903'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='GiftTheme',\n fields=[\n ('id', models.AutoField(verbose_name='ID', auto_created=True, serialize=False, primary_key=True)),\n ('title', models.CharField(max_length=12, verbose_name='主题名称')),\n ('theme_pic', models.CharField(max_length=128, verbose_name='封面图片')),\n ('title_color', models.CharField(max_length=7, verbose_name='主题字体颜色', default='#FB966E')),\n ('category_index', models.IntegerField(max_length=5, verbose_name='所属分类')),\n ('create_time', models.DateField(max_length=128, verbose_name='创建日期', default=datetime.datetime.now)),\n ('status', models.CharField(max_length=1, verbose_name='状态', default='0')),\n ],\n options={\n 'verbose_name': '基础数据-主题',\n 'verbose_name_plural': '基础数据-主题',\n 'db_table': 'gift_theme',\n },\n ),\n migrations.CreateModel(\n name='GiftThemeItem',\n fields=[\n ('id', models.AutoField(verbose_name='ID', auto_created=True, serialize=False, primary_key=True)),\n ('card_id', models.CharField(max_length=32, verbose_name='微信返回ID', blank=True, null=True)),\n ('title', models.CharField(max_length=12, verbose_name='名称')),\n ('theme', models.ForeignKey(to='admin.GiftTheme')),\n ],\n options={\n 'verbose_name': '基础数据-主题-item',\n 'verbose_name_plural': '基础数据-主题-item',\n 'db_table': 'gift_theme_item',\n },\n ),\n migrations.CreateModel(\n name='GiftThemePicItem',\n fields=[\n ('id', models.AutoField(verbose_name='ID', auto_created=True, serialize=False, primary_key=True)),\n ('background_pic', models.CharField(max_length=128, verbose_name='背景图片')),\n ('msg', models.CharField(max_length=32, verbose_name='默认祝福语')),\n ('theme', models.ForeignKey(to='admin.GiftTheme')),\n ],\n options={\n 'verbose_name': '基础数据-分类-picItem',\n 'verbose_name_plural': '基础数据-分类-picItem',\n 'db_table': 'gift_category_pic_item',\n },\n ),\n ]\n","sub_path":"apps/admin/migrations/0009_gifttheme_giftthemeitem_giftthemepicitem.py","file_name":"0009_gifttheme_giftthemeitem_giftthemepicitem.py","file_ext":"py","file_size_in_byte":2726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"463116508","text":"\nORIGDIR = \"ff-orig/mozilla-24.0esr\"\nDEVDIR = \"ff-dev/mozilla-24.0esr\"\nPATCHDIR = \"patch/mozilla-24.0esr\"\nIGNORE_BINARY = True\nEXCLUSIONS = [\n '_virtualenv',\n 'confdefs.h',\n '*.pytmp',\n 'obj-*',\n 'dist',\n '*.pyc',\n '*.jar',\n '.hg*',\n '*.so',\n 'configure',\n 'configure.in',\n '*.a',\n 'Linux_All_DBG.OBJ',\n '*.o',\n '*.swp',\n '*.swo',\n 'ipc',\n 'TestDeadlockDetector*',\n 'test_deadlock_detector',\n 'idl-parser',\n '.mozconfig*',\n '.project',\n 'jprof-log',\n 'imacros.c.out*',\n 'build-debug',\n 'PKG-INFO',\n 'mozbase',\n 'python',\n 'mozinfo.json',\n '*.mk',\n # Below here, we exclude to allow comparison of a compiled js/src\n # directory to an uncompiled one.\n '.deps',\n 'system_wrappers_js',\n 'Makefile',\n 'config.cache',\n 'config.log',\n 'config.status',\n 'host_*',\n 'js-conf*',\n '*.a',\n '*.a.desc',\n 'nsinstall',\n 'expandlibs_config.py',\n 'jsapi-tests',\n 'jsauto*',\n '*.out.h',\n 'unallmakefiles',\n '*gdb.py',\n 'intl',\n 'symverscript',\n 'selfhosted.js',\n 'backend.RecursiveMakeBackend.built.pp',\n]\n\n","sub_path":"util/patchconfig24.0esr.py","file_name":"patchconfig24.0esr.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"329428140","text":"from bs4 import BeautifulSoup\nimport asyncio\nimport aiohttp\nimport time\nimport re\nfrom selenium import webdriver\nsem=asyncio.Semaphore(200)\n\ndef getHref():\n with open('link.txt') as f:\n for site in f:\n link=site.strip()\n url = 'https://www.baidu.com/s?wd=site:' +link\n print(url)\n web = webdriver.Chrome()\n web.get(url=url)\n try:\n while web.find_element_by_partial_link_text('下一页'):\n web.find_element_by_partial_link_text('下一页').click()\n time.sleep(1)\n Text = web.page_source\n soup = BeautifulSoup(Text, 'lxml')\n res = soup.select('div > h3 > a')\n with open('url.txt', 'a') as f:\n for i in res:\n f.write(i.get('href') + '\\n')\n except:\n time.sleep(1)\n web.close()\n continue\n\n\nasync def main(loop):\n with open('url.txt') as g:\n result=[loop.create_task(getio(s.strip()))for s in g]\n await asyncio.wait(result)\n\nasync def getio(url):\n async with sem:\n async with aiohttp.ClientSession() as ssion:\n try:\n async with ssion.get(url=url,timeout=2) as reson:\n\n if reson.status==200:\n Text=await reson.text()\n pattern = re.compile(u'[1-9]\\d{5}(?:19|20)\\d\\d(?:0[1-9]|1[012])(?:0[1-9]|[12]\\d|3[01])\\d{4}')\n if pattern.search(Text) != None :\n print(\"存在\")\n resss=pattern.search(Text)\n print(resss)\n relt_text=open('result.txt','a')\n relt_text.write(url.strip()+'\\t'+str(resss)+'\\n')\n else:\n print('不存在')\n else:\n pass\n except:\n pass\n\n\nif __name__ == '__main__':\n # getHref()\n # time.sleep(2)\n loop=asyncio.get_event_loop()\n loop.run_until_complete(main(loop))\n loop.close()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"64516354","text":"import os\nimport urllib2\n\nfrom PIL import Image\n\n\ndef get_python_image(filename):\n \"\"\" Get a python logo image for this example \"\"\"\n if not os.path.exists(filename):\n response = urllib2.urlopen(\n 'http://www.python.org/community/logos/python-logo.png')\n f = open(filename, 'w')\n f.write(response.read())\n f.close()\n\nif __name__ == '__main__':\n get_python_image(\"python.png\")\n im = Image.open(\"python.png\")\n im2=im.resize((200,200),Image.ANTIALIAS)\n im2.save(\"python.png\",'PNG')","sub_path":"src/monitorperf/reportmaker/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"265067129","text":"from difflib import SequenceMatcher\nimport sys\nimport math\nimport struct\nimport time\nimport csv\n\n\nclass obj:\n\tdef __init__(self, name):\n\t\tself.name = name\n\t\tself.who = None\n\t\tself.where = None \n\t\tself.what = None \n\t\tself.why = None \n\t\tself.when = None \n\t\tself.whispers = None \n\n\tdef get_ans(self, qst):\n\t\tqst = qst.lower()\n\t\tans = \"\"\n\t\tif \"who\" in qst:\n\t\t\tans = self.who\n\t\telif \"where\" in qst:\n\t\t\tans = self.where\n\t\telif \"what\" in qst:\n\t\t\tans = self.what\n\t\telif \"why\" in qst:\n\t\t\tans = self.why\n\t\telif \"when\" in qst:\n\t\t\tans= self.when\n\t\telse:\n\t\t\tans = self.whispers\n\t\treturn ans\n\nobjects = []\ndef initialize_everything():\n\tcatobj = obj(name='the cat')\n\tcatobj.who='Hyun Jung Jun an art student at Northwestern University'\n\tcatobj.what = \"The cat is a flashe linen thread piece. Flashe is a vinyl-based which can be used to create paintings on various mediums such as linen and thread.\"\n\tcatobj.where = 'The cat was created in Evanston IL'\n\tcatobj.why = 'For a thesis project'\n\tcatobj.when = 'This was created in 2019'\n\tcruxobj = obj(name = 'the crucifixion')\n\tcruxobj.who= 'Naddo Ceccarelli'\n\tcruxobj.what = 'The crucifixion is a Tempera and gold on panel gold leaf is gilded onto the wood panel before inscription and detailing'\n\tcruxobj.where = 'It was created in Siena Ital'\n\tcruxobj.why = 'The crucfixion is a depiction of Christs death used in many Churches. These panel works were typically used in reliquaries'\n\tcruxobj.when = 'The crucifixion was created in the 14th century circa 1350-1359'\n\tobjects.append(catobj)\n\tobjects.append(cruxobj)\n\t\t\n\n\ndef create_answer():\n\tquestion=open(\"question.txt\",\"r\").read()\n\tansw = \"I don't understand\"\n\tfor elem in objects:\n\t\tif elem.name in question:\n\t\t\tprint(elem.name)\n\t\t\tansw = elem.get_ans(question)\n\tf=open(\"answer.txt\",\"w\")\n\tf.write(str(answ))\n\n\ninitialize_everything()\ncreate_answer()","sub_path":"src/walexa.py","file_name":"walexa.py","file_ext":"py","file_size_in_byte":1844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"337997816","text":"from django.shortcuts import render\nfrom django.http import HttpResponse, JsonResponse, HttpResponseForbidden\nfrom django.template.response import TemplateResponse\nfrom django.contrib.auth.decorators import login_required\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view\nfrom rest_framework.decorators import renderer_classes\nfrom rest_framework.response import Response\nfrom rest_framework.renderers import JSONRenderer\nfrom server.models import Module, ModuleVersion, Workflow, WfModule, ParameterSpec, ParameterVal\nfrom server.serializers import WorkflowSerializer, WorkflowSerializerLite\nfrom server.execute import execute_wfmodule\n\n\n# ---- Workflows list page ----\n@login_required\ndef workflows2(request):\n return TemplateResponse(request, 'workflows.html', {})\n\n# ---- Workflow ----\n\n\n# List all workflows, or create a new workflow.\n@api_view(['GET', 'POST'])\n@renderer_classes((JSONRenderer,))\ndef workflow_list(request, format=None):\n if request.method == 'GET':\n workflows = Workflow.objects.filter(owner=request.user)\n serializer = WorkflowSerializerLite(workflows, many=True)\n return Response(serializer.data)\n\n elif request.method == 'POST':\n serializer = WorkflowSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save(owner=request.user)\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n# Retrieve, update or delete a workflow instance.\n@api_view(['GET', 'PATCH', 'DELETE'])\n@renderer_classes((JSONRenderer,))\ndef workflow_detail(request, pk, format=None):\n try:\n workflow = Workflow.objects.get(pk=pk)\n except Workflow.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n if not workflow.user_authorized(request.user):\n return HttpResponseForbidden()\n\n if request.method == 'GET':\n serializer = WorkflowSerializer(workflow)\n return Response(serializer.data)\n\n # We use PATCH to set the order of the modules when the user drags.\n elif request.method == 'PATCH':\n for record in request.data:\n wfm = workflow.wf_modules.get(pk=record['id'])\n wfm.order = record['order']\n wfm.save()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n elif request.method == 'DELETE':\n workflow.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\n# Invoked when user pressess add_module button\n@api_view(['PUT'])\n@renderer_classes((JSONRenderer,))\ndef workflow_addmodule(request, pk, format=None):\n try:\n workflow = Workflow.objects.get(pk=pk)\n except Workflow.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n if not workflow.user_authorized(request.user):\n return HttpResponseForbidden()\n\n try:\n moduleID = request.data['moduleID']\n insertBefore = int(request.data['insertBefore'])\n module = Module.objects.get(pk=moduleID)\n #For now, we always get the last version of a module – the ModuleVersion object is ordered by the\n # last_update_time, so retrieving the 0th element will return the latest version.\n #In future versions, we'll need to be cleverer here (but only marginally so): we should always add the\n #latest version of a workflow, and if the users want to use a previous version, they should be able to rollback\n #using the module UI, and not from the \"Add Module\" UI. This will require API changes.\n module_version = ModuleVersion.objects.filter(module=module)[0]\n except Module.DoesNotExist:\n return Response(status=status.HTTP_400_BAD_REQUEST)\n\n # create new WfModule in the right place\n # this also makes wfm.order sequential, which is not strictly necessary but kinda nice\n pos = 0\n for wfm in WfModule.objects.filter(workflow=workflow):\n if pos == insertBefore:\n pos += 1\n if wfm.order != pos:\n wfm.order = pos\n wfm.save()\n pos +=1\n\n newwfm = WfModule.objects.create(workflow=workflow, module_version=module_version, order=insertBefore)\n newwfm.create_default_parameters()\n\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n","sub_path":"server/views/workflows.py","file_name":"workflows.py","file_ext":"py","file_size_in_byte":4297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"71406896","text":"import cv2\n\nfrom ..contour_filter import contour_filter\nfrom ...math_ import geometry\nfrom ...helpers_.types import RangedNumber\n\n\n@contour_filter\ndef polygon_filter(contour_list, side_amount=6, min_angle_ratio: RangedNumber(0, 1) = 0.7,\n min_area_ratio: RangedNumber(0, 1) = 0.7, min_len_ratio: RangedNumber(0, 1) = 0.7,\n approximation_coefficient: RangedNumber(0, 1) = 0.02):\n \"\"\"\n A filter that Detects regular polygon of n-sides sides\n :param contour_list: the list of contours to be filtered\n :param side_amount: the amount of sides the wanted polygon has.\n :param min_angle_ratio: the minimum ratio between the each angle and the average angle and the average angle and the\n target angle of a shape of side_amount\n :param min_area_ratio: The minimum ratio between the contour's area and the target area\n :param min_len_ratio: The minimum ratio between the length of each side and the average length and\n between the average length.\n :param approximation_coefficient: the coefficient for the function cv2.approxPolyDP.\n :return: the list of contours (numpy ndarrays) that passed the filter and are regular polygon\n \"\"\"\n if side_amount < 3:\n raise ValueError(\"A polygon must have at least 3 sides\")\n output = []\n ratios = []\n output_append = output.append\n ratio_append = ratios.append\n for current_contour in contour_list:\n vertices, lengths, angles = geometry.contour_lengths_and_angles(current_contour, approximation_coefficient)\n if len(vertices) == side_amount:\n target_angle = geometry.regular_polygon_angle(side_amount)\n average_length = round(sum(lengths) / float(len(lengths)), 3)\n average_angle = round(sum(angles) / float(len(lengths)), 3)\n for length in lengths:\n if 1 - ((((length - average_length) ** 2) ** 0.5) / average_length) < min_len_ratio:\n break\n else:\n for angle in angles:\n if 1 - ((((angle - average_angle) ** 2) ** 0.5) / average_angle) < min_angle_ratio:\n break\n else:\n if not 1 - ((((target_angle - average_angle) ** 2) ** 0.5) / target_angle) < min_angle_ratio:\n ratios = cv2.contourArea(current_contour) / geometry.polygon_area(average_length, side_amount)\n if min_area_ratio <= ratios <= 1 / min_area_ratio:\n ratio_append(ratios)\n output_append(current_contour)\n return output, ratios\n","sub_path":"ovl/contour_filters_/shape_filters/polygon_filter.py","file_name":"polygon_filter.py","file_ext":"py","file_size_in_byte":2661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"192364597","text":"import sys\r\nimport os\r\n\r\nthisdir = os.getcwd()\r\npattern = \".wav\"\r\nnewName = \"file\"\r\n\r\ndef main():\r\n\tif len(sys.argv) > 1:\r\n\t\tif sys.argv[1] == '?':\r\n\t\t\tprint(\"arg1 = new name\")\r\n\t\t\tprint(\"arg2 = extention\")\r\n\t\t\treturn\r\n\t\telse:\t\t\t\r\n\t\t\tnewName = sys.argv[1]\r\n\telse:\r\n\t\tnewName = \"file\"\r\n\tif len(sys.argv) > 2:\r\n\t\tpattern = sys.argv[2]\r\n\telse:\r\n\t\tpattern = \".wav\"\t\t\t\t\t\r\n\r\n\tfileList = [x for x in os.listdir(thisdir) if x.endswith(pattern)]\t\r\n\tnumberList = [\"%.2d\" % i for i in range(len(fileList))]\r\n\t\r\n\ti = 0\r\n\tfor selections in fileList:\r\n\t\tif selections != '':\r\n\t\t\tos.rename(thisdir + \"\\\\\" + selections, thisdir + \"\\\\\" + newName + \"_\" + numberList[i] + pattern)\r\n\t\t\ti +=1\t\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n \r\n","sub_path":"batchRename.py","file_name":"batchRename.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"160566926","text":"from validators.validator_schemas import post_schema\nfrom validators.data_validator import validate_data\n\nimport django\ndjango.setup()\nfrom Agro.models import Post, User\n\n\nfrom dao.post import dao_create_post, dao_delete_data_info, dao_update_post\n\n\ndef create_post(user_id, data):\n try:\n user = User.objects.get(id=user_id)\n data = validate_data(post_schema, data)\n is_user_created = dao_create_post(data, user_id)\n if is_user_created:\n return {'message': 'Post created'}\n return {'message': 'user not created'}\n\n except User.DoesNotExist:\n return {'message': 'User Not exists'}\n\n\ndef update_post(post_id, request_data, user_id):\n try:\n post = Post.objects.get(id=post_id, is_deleted=False)\n user = User.objects.get(id=user_id)\n if post.user == user:\n if validate_data(post_schema, request_data):\n is_data_info_deleted = dao_delete_data_info(post)\n if is_data_info_deleted:\n is_post_updated = dao_update_post(request_data, post)\n if is_post_updated:\n return {'message': 'updated'}\n return {'message': 'not updated'}\n return {'message': 'invalid user'}\n except Post.DoesNotExist:\n return {'message': 'post not exist'}\n except User.DoesNotExist:\n return {'message': 'User not exist'}\n\n\ndef delete_post(post_id, user_id):\n try:\n user_post = Post.objects.get(id=post_id)\n user = User.objects.get(id=user_id)\n if user_post.user == user:\n is_post_deleted = dao_delete_data_info(user_post)\n if is_post_deleted:\n user_post.is_deleted = True\n user_post.save()\n return {'message': 'post deleted'}\n return {'message': 'Post not deleted'}\n\n except Post.DoesNotExist:\n return {'message': 'post not exist'}\n except User.DoesNotExist:\n return {'message': 'post not exist'}\n","sub_path":"app/service_apis_handler/create_post.py","file_name":"create_post.py","file_ext":"py","file_size_in_byte":2072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"576166920","text":"import math\nimport random\nimport numpy\nimport matplot.lib.pyplot as plit\ndef fitness(x):\n return math.sin((math.pi * x)/256)\n\ndef gen_pop(N):\n pop=[]\n for i in range(N):\n pop.append(random.randrange(0,255))\n return pop\ndef acumular(v):\n res = []\n acum = 0\n for i in v:\n res.append(i + acum)\n acum = res[-1]\n return res\n \ndef random_select(pop,f):\n fit = map(f,pop)\n soma = sum(fit)\n norm = map(lambda x: x/soma,fit)\n acm = acumular(norm)\n r = random.random()\n \n for i in range(len(acm)):\n if r < acm[i]:\n break\n return pop[i]\n\ndef reproduzir(x, y):\n bx = format(x, '08b')\n by = format(y, '08b')\n c = random.randint(0, len(bx)-1)\n return int(bx[0:c] + by[c:len(by)],2)\ndef mutar(x):\n bx = format(x ,'08b')\n r = random.randrange(0, len(bx))\n x = x ^ (1 << r)\n return x\n\ndef argmax(V):\n maior = 0\n for i in range(1,len(V)):\n if V[i] > V[maior]:\n maior = i\n return maior\n\ndef genetico(pop_inicial, f, n_iter, tx_mutacao):\n pop = pop_inicial\n max_fits = []\n med_fits = []\n fit = map(f, pop)\n mais_fit = pop[argmax(fit)]\n melhor_solucao = 0\n for gen in range(n_iter):\n p_nova = []\n for i in range(len(pop_inicial)):\n x = random_select(pop, f)\n y = random_select(pop, f)\n novo = reproduzir(x, y)\n r = random.randrange(0, 100)\n if r < tx_mutacao:\n novo = mutar(novo)\n p_nova.append(novo)\n pop = p_nova\n fit = map(f, pop)\n max_fits.append(max(fit))\n med_fits.append(sum(fit) / len(fit))\n mais_fit = pop[argmax(fit)]\n if f(mais_fit) > f(melhor_solucao):\n melhor_solucao = mais_fit\n \n fit = map(f, pop)\n mais_fit = argmax(fit)\n \n plt.figure()\n plt.plot(max_fits, label='Fitness maximo')\n plt.plot(med_fits, label='Fitness medio')\n plt.legend()\n plt.ylabel('Fitness')\n plt.xlabel('Geracoes')\n plt.show()\n \n return pop[mais_fit], fit[mais_fit], pop, melhor_solucao\n \npop_inicial = [17, 20, 59, 79, 204, 197, 213, 44, 254, 0]\nmais_fit, mf_valor, pop_final, melhor = genetico(pop_inicial, fitness, 100, 5)\nprint(mais_fit, mf_valor)\nprint(pop_final)\nprint(melhor, fitness(melhor))\n#random_select(pop_inicial, fitness)\n\n\n","sub_path":"Genetico.py","file_name":"Genetico.py","file_ext":"py","file_size_in_byte":2364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"405380902","text":"\"\"\"\nlos loops se utilizan para iterar sobre una secuencia dada.\nEn cada iteración, la variable definida en el ciclo for se asignará\nal siguiente valor en la lista.\nEl tipo de range representa una secuencia de números inmutable\nhttps://docs.python.org/3/library/stdtypes.html#typesseq-range\n\"\"\"\n\nfor i in range(5): # range(5) retorna 0, 1, 2, 3, 4\n print(i)\n\nprimes = [2, 3, 5, 7]\n\nfor prime in primes:\n print(prime)\n","sub_path":"lesson6/task1/for_loop.py","file_name":"for_loop.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"511682215","text":"\"\"\"This module contains functionality for all the sampling methods supported in UQpy.\"\"\"\nimport sys\nimport copy\nimport numpy as np\nfrom scipy.spatial.distance import pdist\nimport scipy.stats as sp\nimport UQpy\nimport random\nfrom UQpy.PDFs import *\nimport warnings\n\n\ndef init_sm(data):\n ################################################################################################################\n # Add available sampling methods Here\n valid_methods = ['mcs', 'lhs', 'mcmc', 'pss', 'sts', 'SuS']\n\n ################################################################################################################\n # Check if requested method is available\n\n if 'method' in data:\n if data['method'] not in valid_methods:\n raise NotImplementedError(\"method - %s not available\" % data['method'])\n else:\n raise NotImplementedError(\"No sampling method was provided\")\n\n ################################################################################################################\n # Monte Carlo simulation block.\n # Mandatory properties(4): 1. Number of parameters, 2. distribution, 3. distribution parameters 4. Number of samples\n # Optional properties(0):\n\n if data['method'] == 'mcs':\n\n # Mandatory\n if 'number of samples' not in data:\n data['number of samples'] = None\n if 'distribution type' not in data:\n raise NotImplementedError(\"Distributions not defined. Exit code\")\n if 'distribution parameters' not in data:\n raise NotImplementedError(\"Distribution parameters not provided. Exit code\")\n if 'number of parameters' not in data:\n data['number of parameters'] = None\n\n ################################################################################################################\n # Latin Hypercube simulation block.\n # Mandatory properties(4): 1. Number of parameters, 2. distribution, 3. distribution parameters 4. Number of samples\n # Optional properties(3): 1. Criterion, 2. Metric, 3. Iterations\n\n if data['method'] == 'lhs':\n # Mandatory\n if 'number of parameters' not in data:\n data['number of parameters'] = None\n if 'number of samples' not in data:\n data['number of samples'] = None\n if 'distribution type' not in data:\n raise NotImplementedError(\"Exit code: Distributions not defined.\")\n if 'distribution parameters' not in data:\n raise NotImplementedError(\"Exit code: Distribution parameters not defined.\")\n\n # Optional\n if 'criterion' not in data:\n data['criterion'] = None\n if 'distance' not in data:\n data['distance'] = None\n if 'iterations' not in data:\n data['iterations'] = None\n\n ####################################################################################################################\n # Markov Chain Monte Carlo simulation block.\n # Mandatory properties(4): 1. target distribution, 2. target distribution parameters, 3. Number of samples,\n # 4. Number of parameters\n # Optional properties(5): 1. Proposal distribution, 2. proposal width, 3. Seed, 4. jump samples (avoid burn-in),\n # 5. algorithm\n\n if data['method'] == 'mcmc':\n # Mandatory\n if 'number of parameters' not in data:\n raise NotImplementedError('Exit code: Number of parameters not defined.')\n if 'target distribution type' not in data:\n raise NotImplementedError(\"Exit code: Target distribution type not defined.\")\n if 'target distribution parameters' not in data:\n raise NotImplementedError(\"Exit code: Target distribution parameters not defined.\")\n if 'number of samples' not in data:\n raise NotImplementedError('Exit code: Number of samples not defined.')\n # Optional\n if 'seed' not in data:\n data['seed'] = None\n if 'jump' not in data:\n data['jump'] = None\n if 'proposal distribution type' not in data:\n data['proposal distribution type'] = None\n #else:\n # if data['proposal distribution type'] not in ['Uniform', 'Normal']:\n # raise ValueError('Exit code: Unrecognized type of proposal distribution type. Supported distributions: '\n # 'Uniform, '\n # 'Normal.')\n\n if 'proposal distribution width' not in data:\n data['proposal distribution width'] = None\n if 'algorithm' not in data:\n data['algorithm'] = None\n\n ################################################################################################################\n # Partially stratified sampling block.\n # Mandatory properties (4): 1. distribution, 2. distribution parameters, 3. design, 4. strata\n # Optional properties(1): 1. Number of parameters\n\n if data['method'] == 'pss':\n\n # Mandatory\n if 'distribution type' not in data:\n raise NotImplementedError(\"Exit code: Distributions not defined.\")\n elif 'distribution parameters' not in data:\n raise NotImplementedError(\"Exit code: distribution parameters not defined.\")\n if 'design' not in data:\n raise NotImplementedError(\"Exit code: pss design not defined.\")\n if 'strata' not in data:\n raise NotImplementedError(\"Exit code: pss strata not defined.\")\n\n # Optional\n if 'number of parameters' not in data:\n data['number of parameters'] = None\n\n ################################################################################################################\n # Stratified sampling block.\n # Mandatory properties(3): 1. distribution, 2. distribution parameters, 3. design\n # Optional properties(1): 1. Number of parameters\n\n if data['method'] == 'sts':\n # Mandatory\n if 'distribution type' not in data:\n raise NotImplementedError(\"Exit code: Distributions not defined.\")\n elif 'distribution parameters' not in data:\n raise NotImplementedError(\"Exit code: distribution parameters not defined.\")\n if 'design' not in data:\n raise NotImplementedError(\"Exit code: sts design not defined.\")\n\n # Optional\n if 'number of parameters' not in data:\n data['number of parameters'] = None\n\n ####################################################################################################################\n # Stochastic reduced order model block\n # Mandatory properties(2): 1. moments, 2. error function weights\n # Optional properties(2): 1.properties to match, 2. sample weights\n\n if 'SROM' in data and data['SROM'] is True:\n # Mandatory\n if 'moments' not in data:\n raise NotImplementedError(\"Exit code: Moments not provided.\")\n if 'error function weights' not in data:\n raise NotImplementedError(\"Exit code: Error function weights not provided.\")\n\n # Optional\n if 'properties to match' not in data:\n data['properties to match'] = None\n if 'sample weights' not in data:\n data['sample weights'] = None\n\n ####################################################################################################################\n # Check any NEW METHOD HERE\n #\n #\n\n\n########################################################################################################################\n########################################################################################################################\n########################################################################################################################\n\n\ndef run_sm(data):\n ################################################################################################################\n # Run Monte Carlo simulation\n if data['method'] == 'mcs':\n print(\"\\nRunning %k \\n\", data['method'])\n rvs = MCS(dimension=data['number of parameters'], pdf_type=data['distribution type'],\n pdf_params=data['distribution parameters'],\n nsamples=data['number of samples'])\n\n ################################################################################################################\n # Run Latin Hypercube sampling\n elif data['method'] == 'lhs':\n print(\"\\nRunning %k \\n\", data['method'])\n rvs = LHS(dimension=data['number of parameters'], pdf_type=data['distribution type'],\n pdf_params=data['distribution parameters'],\n nsamples=data['number of samples'], lhs_metric=data['distance'],\n lhs_iter=data['iterations'], lhs_criterion=data['criterion'])\n\n ################################################################################################################\n # Run partially stratified sampling\n elif data['method'] == 'pss':\n print(\"\\nRunning %k \\n\", data['method'])\n rvs = PSS(dimension=data['number of parameters'], pdf_type=data['distribution type'],\n pdf_params=data['distribution parameters'],\n pss_design=data['design'], pss_strata=data['strata'])\n\n ################################################################################################################\n # Run STS sampling\n\n elif data['method'] == 'sts':\n print(\"\\nRunning %k \\n\", data['method'])\n rvs = STS(dimension=data['number of parameters'], pdf_type=data['distribution type'],\n pdf_params=data['distribution parameters'], sts_design=data['design'])\n\n ################################################################################################################\n # Run Markov Chain Monte Carlo sampling\n\n elif data['method'] == 'mcmc':\n print(\"\\nRunning %k \\n\", data['method'])\n rvs = MCMC(dimension=data['number of parameters'], pdf_target_type=data['target distribution type'],\n algorithm=data['algorithm'], pdf_proposal_type=data['proposal distribution type'],\n pdf_proposal_scale=data['proposal distribution width'],\n pdf_target_params=data['target distribution parameters'], seed=data['seed'],\n jump=data['jump'], nsamples=data['number of samples'])\n\n ################################################################################################################\n # Run SROM to the samples\n\n if 'SROM' in data and data['SROM'] == 'Yes':\n print(\"\\nImplementing SROM to samples\")\n rvs = SROM(samples=rvs.samples, pdf_type=data['distribution type'], moments=data['moments'],\n weights_errors=data['error function weights'], weights_function=data['sample weights'],\n properties=data['properties to match'], pdf_params=data['distribution parameters'])\n\n ################################################################################################################\n # Run ANY NEW METHOD HERE\n\n return rvs\n\n########################################################################################################################\n########################################################################################################################\n# Stochastic reduced order model\n########################################################################################################################\n\nclass SROM:\n\n # TODO: Mohit - Write the documentation for the class\n\n def __init__(self, samples=None, pdf_type=None, moments=None, weights_errors=None,\n weights_function=None, properties=None, pdf_params=None):\n \"\"\"\n :param samples:\n :type\n :param pdf_type:\n :type\n :param moments:\n :type\n\n :param weights_errors:\n :type\n\n :param weights_function:\n :type weights_function: list\n\n :param properties:\n :type properties:\n\n :param pdf_params: list\n :type pdf_params: list\n \"\"\"\n\n # TODO: Mohit - Add error checks\n\n self.samples = samples\n self.pdf_type = pdf_type\n self.moments = moments\n self.weights_errors = weights_errors\n self.weight_function = weights_function\n self.properties = properties\n self.pdf_params = pdf_params\n self.dimension = len(self.pdf_type)\n self.nsamples = samples.shape[0]\n self.init_srom()\n weights = self.run_srom()\n print(weights.shape)\n self.samples = np.concatenate([self.samples, weights.reshape(weights.shape[0], 1)], axis=1)\n\n def run_srom(self):\n from scipy import optimize\n\n def f(p_, samples, w, mar, n, d, m, alpha, para):\n e1 = 0.\n e2 = 0.\n e22 = 0.\n e3 = 0.\n samples = np.matrix(samples)\n p_ = np.transpose(np.matrix(p_))\n com = np.append(samples, p_, 1)\n for j in range(d):\n srt = com[np.argsort(com[:, j].flatten())]\n s = srt[0, :, j]\n a = srt[0, :, d]\n A = np.cumsum(a)\n marginal = pdf(mar[j])\n for i in range(n):\n e1 = + w[i, j] * (A[0, i] - marginal(s[0, i], para[j])) ** 2\n\n e2 = + ((1 / w[i + 1, j]) ** 2) * (np.sum(np.transpose(p_) * samples[:, j]) - m[0, j]) ** 2\n e22 = + ((1 / w[i + 2, j]) ** 2) * (\n np.sum(np.array(p_) * (np.array(samples[:, j]) * np.array(samples[:, j]))) - m[1, j]) ** 2\n\n return alpha[0] * e1 + alpha[1] * (e2 + e22) + alpha[2] * e3\n\n def constraint(x):\n return np.sum(x) - 1\n\n def constraint2(y):\n n = np.size(y)\n return np.ones(n) - y\n\n def constraint3(z):\n n = np.size(z)\n return z - np.zeros(n)\n\n cons = ({'type': 'eq', 'fun': constraint}, {'type': 'ineq', 'fun': constraint2},\n {'type': 'ineq', 'fun': constraint3})\n\n p_ = optimize.minimize(f, np.zeros(self.nsamples),\n args=(self.samples, self.weight_function, self.pdf_type, self.nsamples, self.dimension,\n self.moments, self.weights_errors, self.pdf_params),\n constraints=cons, method='SLSQP')\n\n return p_.x\n\n def init_srom(self):\n\n self.moments = np.array(self.moments)\n self.weights_errors = np.array(self.weights_errors).astype(np.float64)\n\n if self.samples is None:\n raise NotImplementedError('Samples not provided for SROM')\n\n if self.properties is None:\n self.properties = [1, 1, 0]\n\n if self.weight_function is None or len(self.weight_function) == 0:\n temp_weights_function = np.ones(shape=(self.samples.shape[0], self.dimension))\n print(temp_weights_function)\n self.weight_function = np.concatenate([temp_weights_function, self.moments], axis=0)\n\n\n########################################################################################################################\n########################################################################################################################\n# Monte Carlo simulation\n########################################################################################################################\n\nclass MCS:\n \"\"\"\n A class used to perform brute force Monte Carlo design of experiment (MCS).\n SamplesU01 belong in hypercube [0, 1]^n while samples belong to the parameter space\n\n :param dimension: Number of parameters\n :type dimension: int\n\n :param nsamples: Number of samples to be generated\n :type nsamples: int\n\n :param pdf_type: Type of distributions\n :type pdf_type: list\n\n :param pdf_params: Distribution parameters\n :type pdf_params: list\n\n \"\"\"\n\n def __init__(self, dimension=None, pdf_type=None, pdf_params=None, nsamples=None):\n\n self.dimension = dimension\n self.nsamples = nsamples\n self.pdf_type = pdf_type\n self.pdf_params = pdf_params\n self.init_mcs()\n self.samplesU01, self.samples = self.run_mcs()\n\n def run_mcs(self):\n\n samples = np.random.rand(self.nsamples, self.dimension)\n samples_u_to_x = inv_cdf(samples, self.pdf_type, self.pdf_params)\n return samples, samples_u_to_x\n\n ################################################################################################################\n # Initialize Monte Carlo simulation.\n # Necessary parameters: 1. Probability distribution, 2. Probability distribution parameters 3. Number of samples\n # Optional: dimension, names of random variables\n\n def init_mcs(self):\n if self.nsamples is None:\n raise NotImplementedError(\"Exit code: Number of samples not defined.\")\n if self.pdf_type is None:\n raise NotImplementedError(\"Exit code: Distributions not defined.\")\n else:\n for i in self.pdf_type:\n if i not in ['Uniform', 'Normal', 'Lognormal', 'Weibull', 'Beta', 'Exponential', 'Gamma']:\n raise NotImplementedError(\"Exit code: Unrecognized type of distribution.\"\n \"Supported distributions: 'Uniform', 'Normal', 'Lognormal', \"\n \"'Weibull', 'Beta', 'Exponential', 'Gamma'. \")\n if self.pdf_params is None:\n raise NotImplementedError(\"Exit code: Distribution parameters not defined.\")\n\n if self.dimension is None:\n if len(self.pdf_type) != len(self.pdf_params):\n raise NotImplementedError(\"Exit code: Incompatible dimensions.\")\n else:\n self.dimension = len(self.pdf_type)\n else:\n import itertools\n from itertools import chain\n\n if len(self.pdf_type) == 1 and len(self.pdf_params) == self.dimension:\n self.pdf_type = list(itertools.repeat(self.pdf_type, self.dimension))\n self.pdf_type = list(chain.from_iterable(self.pdf_type))\n elif len(self.pdf_params) == 1 and len(self.pdf_type) == self.dimension:\n self.pdf_params = list(itertools.repeat(self.pdf_params, self.dimension))\n self.pdf_params = list(chain.from_iterable(self.pdf_params))\n elif len(self.pdf_params) == 1 and len(self.pdf_type) == 1:\n self.pdf_params = list(itertools.repeat(self.pdf_params, self.dimension))\n self.pdf_type = list(itertools.repeat(self.pdf_type, self.dimension))\n self.pdf_type = list(chain.from_iterable(self.pdf_type))\n self.pdf_params = list(chain.from_iterable(self.pdf_params))\n elif len(self.pdf_type) != len(self.pdf_params):\n raise NotImplementedError(\"Exit code: Incompatible dimensions\")\n\n\n########################################################################################################################\n########################################################################################################################\n# Latin hypercube sampling (LHS)\n########################################################################################################################\n\nclass LHS:\n \"\"\"\n A class that creates a Latin Hypercube Design for experiments.\n SamplesU01 belong in hypercube [0, 1]^n while samples belong to the parameter space\n\n :param pdf_type: Distribution of the parameters\n :type pdf_type: list\n\n :param pdf_params: Distribution parameters\n :type pdf_params: list\n\n :param lhs_criterion: The criterion for generating sample points\n Options:\n 1. random - completely random \\n\n 2. centered - points only at the centre \\n\n 3. maximin - maximising the minimum distance between points \\n\n 4. correlate - minimizing the correlation between the points \\n\n :type lhs_criterion: str\n\n :param lhs_iter: The number of iteration to run. Only for maximin, correlate and criterion\n :type lhs_iter: int\n\n :param lhs_metric: The distance metric to use. Supported metrics are\n 'braycurtis', 'canberra', 'chebyshev', 'cityblock', 'correlation', 'cosine', 'dice', \\n\n 'euclidean', 'hamming', 'jaccard', 'kulsinski', 'mahalanobis', 'matching', 'minkowski', \\n\n 'rogerstanimoto', 'russellrao', 'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean', \\n\n 'yule'.\n :type lhs_metric: str\n\n \"\"\"\n\n def __init__(self, dimension=None, pdf_type=None, pdf_params=None, lhs_criterion=None, lhs_metric=None,\n lhs_iter=None, nsamples=None):\n\n self.dimension = dimension\n self.nsamples = nsamples\n self.pdf_type = pdf_type\n self.pdf_params = pdf_params\n self.lhs_criterion = lhs_criterion\n self.lhs_metric = lhs_metric\n self.lhs_iter = lhs_iter\n self.init_lhs()\n self.samplesU01, self.samples = self.run_lhs()\n\n def run_lhs(self):\n\n print('Running LHS for ' + str(self.lhs_iter) + ' iterations')\n\n cut = np.linspace(0, 1, self.nsamples + 1)\n a = cut[:self.nsamples]\n b = cut[1:self.nsamples + 1]\n\n if self.lhs_criterion == 'random':\n samples = self._random(a, b)\n samples_u_to_x = inv_cdf(samples, self.pdf_type, self.pdf_params)\n return samples, samples_u_to_x\n elif self.lhs_criterion == 'centered':\n samples = self._centered(a, b)\n samples_u_to_x = inv_cdf(samples, self.pdf_type, self.pdf_params)\n return samples, samples_u_to_x\n elif self.lhs_criterion == 'maximin':\n samples = self._max_min(a, b)\n samples_u_to_x = inv_cdf(samples, self.pdf_type, self.pdf_params)\n return samples, samples_u_to_x\n elif self.lhs_criterion == 'correlate':\n samples = self._correlate(a, b)\n samples_u_to_x = inv_cdf(samples, self.pdf_type, self.pdf_params)\n return samples, samples_u_to_x\n\n def _random(self, a, b):\n \"\"\"\n :return: The samples points for the random LHS design\n\n \"\"\"\n u = np.random.rand(self.nsamples, self.dimension)\n samples = np.zeros_like(u)\n\n for i in range(self.dimension):\n samples[:, i] = u[:, i] * (b - a) + a\n\n for j in range(self.dimension):\n order = np.random.permutation(self.nsamples)\n samples[:, j] = samples[order, j]\n\n return samples\n\n def _centered(self, a, b):\n\n samples = np.zeros([self.nsamples, self.dimension])\n centers = (a + b) / 2\n\n for i in range(self.dimension):\n samples[:, i] = np.random.permutation(centers)\n\n return samples\n\n def _max_min(self, a, b):\n\n max_min_dist = 0\n samples = self._random(a, b)\n for _ in range(self.lhs_iter):\n samples_try = self._random(a, b)\n d = pdist(samples_try, metric=self.lhs_metric)\n if max_min_dist < np.min(d):\n max_min_dist = np.min(d)\n samples = copy.deepcopy(samples_try)\n\n print('Achieved max_min distance of ', max_min_dist)\n\n return samples\n\n def _correlate(self, a, b):\n\n min_corr = np.inf\n samples = self._random(a, b)\n for _ in range(self.lhs_iter):\n samples_try = self._random(a, b)\n R = np.corrcoef(np.transpose(samples_try))\n np.fill_diagonal(R, 1)\n R1 = R[R != 1]\n if np.max(np.abs(R1)) < min_corr:\n min_corr = np.max(np.abs(R1))\n samples = copy.deepcopy(samples_try)\n print('Achieved minimum correlation of ', min_corr)\n return samples\n\n ################################################################################################################\n # Latin hypercube checks.\n # Necessary parameters: 1. Probability distribution, 2. Probability distribution parameters\n # Optional: number of samples (default 100), criterion, metric, iterations\n\n def init_lhs(self):\n\n if self.nsamples is None:\n raise NotImplementedError(\"Exit code: Number of samples not defined.\")\n if self.pdf_type is None:\n raise NotImplementedError(\"Exit code: Distributions not defined.\")\n else:\n for i in self.pdf_type:\n if i not in ['Uniform', 'Normal', 'Lognormal', 'Weibull', 'Beta', 'Exponential', 'Gamma']:\n raise NotImplementedError(\"Exit code: Unrecognized type of distribution.\"\n \"Supported distributions: 'Uniform', 'Normal', 'Lognormal', 'Weibull', \"\n \"'Beta', 'Exponential', 'Gamma'.\")\n if self.pdf_params is None:\n raise NotImplementedError(\"Exit code: Distribution parameters not defined.\")\n if self.dimension is None:\n if len(self.pdf_type) != len(self.pdf_params):\n raise NotImplementedError(\"Exit code: Incompatible dimensions.\")\n else:\n self.dimension = len(self.pdf_type)\n else:\n import itertools\n from itertools import chain\n\n if len(self.pdf_type) == 1 and len(self.pdf_params) == self.dimension:\n self.pdf_type = list(itertools.repeat(self.pdf_type, self.dimension))\n self.pdf_type = list(chain.from_iterable(self.pdf_type))\n elif len(self.pdf_params) == 1 and len(self.pdf_type) == self.dimension:\n self.pdf_params = list(itertools.repeat(self.pdf_params, self.dimension))\n self.pdf_params = list(chain.from_iterable(self.pdf_params))\n elif len(self.pdf_params) == 1 and len(self.pdf_type) == 1:\n self.pdf_params = list(itertools.repeat(self.pdf_params, self.dimension))\n self.pdf_type = list(itertools.repeat(self.pdf_type, self.dimension))\n self.pdf_type = list(chain.from_iterable(self.pdf_type))\n self.pdf_params = list(chain.from_iterable(self.pdf_params))\n elif len(self.pdf_type) != len(self.pdf_params):\n raise NotImplementedError(\"Exit code: Incompatible dimensions.\")\n\n if self.lhs_criterion is None:\n self.lhs_criterion = 'random'\n else:\n if self.lhs_criterion not in ['random', 'centered', 'maximin', 'correlate']:\n raise NotImplementedError(\"Exit code: Supported lhs criteria: 'random', 'centered', 'maximin', \"\n \"'correlate'\")\n\n if self.lhs_metric is None:\n self.lhs_metric = 'euclidean'\n else:\n if self.lhs_metric not in ['braycurtis', 'canberra', 'chebyshev', 'cityblock', 'correlation', 'cosine',\n 'dice', 'euclidean', 'hamming', 'jaccard', 'kulsinski', 'mahalanobis',\n 'matching', 'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean',\n 'sokalmichener', 'sokalsneath', 'sqeuclidean']:\n raise NotImplementedError(\"Exit code: Supported lhs distances: 'braycurtis', 'canberra', 'chebyshev', \"\n \"'cityblock',\"\n \" 'correlation', 'cosine','dice', 'euclidean', 'hamming', 'jaccard', \"\n \"'kulsinski', 'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto',\"\n \"'russellrao', 'seuclidean','sokalmichener', 'sokalsneath', 'sqeuclidean'\")\n\n if self.lhs_iter is None or self.lhs_iter == 0:\n self.lhs_iter = 1000\n elif self.lhs_iter is not None:\n self.lhs_iter = int(self.lhs_iter)\n\n########################################################################################################################\n########################################################################################################################\n# Partially Stratified Sampling (PSS)\n########################################################################################################################\n\nclass PSS:\n \"\"\"\n This class generates a partially stratified sample set on U(0,1) as described in:\n Shields, M.D. and Zhang, J. \"The generalization of Latin hypercube sampling\" Reliability Engineering and\n System Safety. 148: 96-108\n\n :param pss_design: Vector defining the subdomains to be used.\n Example: 5D problem with 2x2D + 1x1D subdomains using pss_design = [2,2,1]. \\n\n Note: The sum of the values in the pss_design vector equals the dimension of the problem.\n :param pss_strata: Vector defining how each dimension should be stratified.\n Example: 5D problem with 2x2D + 1x1D subdomains with 625 samples using\n pss_pss_stratum = [25,25,625].\\n\n Note: pss_pss_stratum(i)^pss_design(i) = number of samples (for all i)\n :return: pss_samples: Generated samples Array (nSamples x nRVs)\n :type pss_design: list\n :type pss_strata: list\n\n Created by: Jiaxin Zhang\n Last modified: 24/01/2018 by D.G. Giovanis\n\n \"\"\"\n\n # TODO: Jiaxin - Add documentation to this subclass\n # TODO: the pss_design = [[1,4], [2,5], [3]] - then reorder the sequence of RVs\n # TODO: Add the sample check and pss_design check in the beginning\n # TODO: Create a list that contains all element info - parent structure\n\n def __init__(self, dimension=None, pdf_type=None, pdf_params=None, pss_design=None, pss_strata=None):\n\n self.pdf_type = pdf_type\n self.pdf_params = pdf_params\n self.pss_design = pss_design\n self.pss_strata = pss_strata\n self.dimension = dimension\n self.init_pss()\n self.nsamples = self.pss_strata[0] ** self.pss_design[0]\n self.samplesU01, self.samples = self.run_pss()\n\n def run_pss(self):\n samples = np.zeros((self.nsamples, self.dimension))\n samples_u_to_x = np.zeros((self.nsamples, self.dimension))\n col = 0\n for i in range(len(self.pss_design)):\n n_stratum = self.pss_strata[i] * np.ones(self.pss_design[i], dtype=np.int)\n sts = STS(pdf_type=self.pdf_type, pdf_params=self.pdf_params, sts_design=n_stratum, pss_=True)\n index = list(range(col, col + self.pss_design[i]))\n samples[:, index] = sts.samplesU01\n samples_u_to_x[:, index] = sts.samples\n arr = np.arange(self.nsamples).reshape((self.nsamples, 1))\n samples[:, index] = samples[np.random.permutation(arr), index]\n samples_u_to_x[:, index] = samples_u_to_x[np.random.permutation(arr), index]\n col = col + self.pss_design[i]\n\n return samples, samples_u_to_x\n\n ################################################################################################################\n # Partially Stratified sampling (PSS) checks.\n # Necessary parameters: 1. pdf, 2. pdf parameters 3. pss design 4. pss strata\n # Optional:\n\n def init_pss(self):\n\n if self.pdf_type is None:\n raise NotImplementedError(\"Exit code: Distribution not defined.\")\n else:\n for i in self.pdf_type:\n if i not in ['Uniform', 'Normal', 'Lognormal', 'Weibull', 'Beta', 'Exponential', 'Gamma']:\n raise NotImplementedError(\"Exit code: Unrecognized type of distribution.\"\n \"Supported distributions: 'Uniform', 'Normal', 'Lognormal', 'Weibull', \"\n \"'Beta', 'Exponential', 'Gamma'. \")\n if self.pdf_params is None:\n raise NotImplementedError(\"Exit code: Distribution parameters not defined.\")\n\n if self.pss_design is None:\n raise NotImplementedError(\"Exit code: pss design not defined.\")\n elif self.pss_strata is None:\n raise NotImplementedError(\"Exit code: pss strata not defined.\")\n else:\n if len(self.pss_design) != len(self.pss_strata):\n raise ValueError('Exit code: \"pss design\" and \"pss strata\" must be the same length.')\n\n sample_check = np.zeros((len(self.pss_strata), len(self.pss_design)))\n for i in range(len(self.pss_strata)):\n for j in range(len(self.pss_design)):\n sample_check[i, j] = self.pss_strata[i] ** self.pss_design[j]\n\n if np.max(sample_check) != np.min(sample_check):\n raise ValueError('Exit code: All dimensions must have the same number of samples/strata.')\n\n if self.dimension is None:\n self.dimension = np.sum(self.pss_design)\n else:\n if self.dimension != np.sum(self.pss_design):\n raise NotImplementedError(\"Exit code: Incompatible dimensions.\")\n\n import itertools\n from itertools import chain\n\n if len(self.pdf_type) == 1 and len(self.pdf_params) == self.dimension:\n self.pdf_type = list(itertools.repeat(self.pdf_type, self.dimension))\n self.pdf_type = list(chain.from_iterable(self.pdf_type))\n elif len(self.pdf_params) == 1 and len(self.pdf_type) == self.dimension:\n self.pdf_params = list(itertools.repeat(self.pdf_params, self.dimension))\n self.pdf_params = list(chain.from_iterable(self.pdf_params))\n elif len(self.pdf_params) == 1 and len(self.pdf_type) == 1:\n self.pdf_params = list(itertools.repeat(self.pdf_params, self.dimension))\n self.pdf_type = list(itertools.repeat(self.pdf_type, self.dimension))\n self.pdf_type = list(chain.from_iterable(self.pdf_type))\n self.pdf_params = list(chain.from_iterable(self.pdf_params))\n elif len(self.pdf_type) != len(self.pdf_params):\n raise NotImplementedError(\"Exit code: Incompatible dimensions.\")\n\n\n########################################################################################################################\n########################################################################################################################\n# Stratified Sampling (sts)\n########################################################################################################################\n\nclass STS:\n # TODO: MDS - Add documentation to this subclass\n \"\"\"\n :param dimension:\n :param pdf_type:\n :param pdf_params:\n :param sts_design:\n :param pss_:\n \"\"\"\n\n def __init__(self, dimension=None, pdf_type=None, pdf_params=None, sts_design=None, pss_=None):\n\n self.dimension = dimension\n self.pdf_type = pdf_type\n self.pdf_params = pdf_params\n self.sts_design = sts_design\n if pss_ is None:\n self.init_sts()\n strata = Strata(nstrata=self.sts_design)\n self.origins = strata.origins\n self.widths = strata.widths\n self.weights = strata.weights\n self.samplesU01, self.samples = self.run_sts()\n\n def run_sts(self):\n samples = np.empty([self.origins.shape[0], self.origins.shape[1]], dtype=np.float32)\n for i in range(0, self.origins.shape[0]):\n for j in range(0, self.origins.shape[1]):\n samples[i, j] = np.random.uniform(self.origins[i, j], self.origins[i, j] + self.widths[i, j])\n samples_u_to_x = inv_cdf(samples, self.pdf_type, self.pdf_params)\n return samples, samples_u_to_x\n\n def init_sts(self):\n\n if self.pdf_type is None:\n raise NotImplementedError(\"Exit code: Distribution not defined.\")\n else:\n for i in self.pdf_type:\n if i not in ['Uniform', 'Normal', 'Lognormal', 'Weibull', 'Beta', 'Exponential', 'Gamma']:\n raise NotImplementedError(\"Exit code: Unrecognized type of distribution.\"\n \"Supported distributions: 'Uniform', 'Normal', 'Lognormal', 'Weibull', \"\n \"'Beta', 'Exponential', 'Gamma'. \")\n if self.pdf_params is None:\n raise NotImplementedError(\"Exit code: Distribution parameters not defined.\")\n\n if self.sts_design is None:\n raise NotImplementedError(\"Exit code: sts design not defined.\")\n\n if self.dimension is None:\n self.dimension = len(self.sts_design)\n else:\n if self.dimension != len(self.sts_design):\n raise NotImplementedError(\"Exit code: Incompatible dimensions.\")\n\n import itertools\n from itertools import chain\n\n if len(self.pdf_type) == 1 and len(self.pdf_params) == self.dimension:\n self.pdf_type = list(itertools.repeat(self.pdf_type, self.dimension))\n self.pdf_type = list(chain.from_iterable(self.pdf_type))\n elif len(self.pdf_params) == 1 and len(self.pdf_type) == self.dimension:\n self.pdf_params = list(itertools.repeat(self.pdf_params, self.dimension))\n self.pdf_params = list(chain.from_iterable(self.pdf_params))\n elif len(self.pdf_params) == 1 and len(self.pdf_type) == 1:\n self.pdf_params = list(itertools.repeat(self.pdf_params, self.dimension))\n self.pdf_type = list(itertools.repeat(self.pdf_type, self.dimension))\n self.pdf_type = list(chain.from_iterable(self.pdf_type))\n self.pdf_params = list(chain.from_iterable(self.pdf_params))\n elif len(self.pdf_type) != len(self.pdf_params):\n raise NotImplementedError(\"Exit code: Incompatible dimensions.\")\n\n # TODO: Create a list that contains all element info - parent structure\n # e.g. SS_samples = [STS[j] for j in range(0,nsamples)]\n # hstack\n\n\n########################################################################################################################\n########################################################################################################################\n# Class Strata\n########################################################################################################################\n\n\nclass Strata:\n \"\"\"\n Define a rectilinear stratification of the n-dimensional unit hypercube with N strata.\n\n :param nstrata: array-like\n An array of dimension 1 x n defining the number of strata in each of the n dimensions\n Creates an equal stratification with strata widths equal to 1/nstrata\n The total number of strata, N, is the product of the terms of nstrata\n Example -\n nstrata = [2, 3, 2] creates a 3d stratification with:\n 2 strata in dimension 0 with stratum widths 1/2\n 3 strata in dimension 1 with stratum widths 1/3\n 2 strata in dimension 2 with stratum widths 1/2\n\n :param input_file: string\n File path to input file specifying stratum origins and stratum widths\n\n :param origins: array-like\n An array of dimension N x n specifying the origins of all strata\n The origins of the strata are the coordinates of the stratum orthotope nearest the global origin\n Example - A 2D stratification with 2 strata in each dimension\n origins = [[0, 0]\n [0, 0.5]\n [0.5, 0]\n [0.5, 0.5]]\n\n :param widths: array-like\n An array of dimension N x n specifying the widths of all strata in each dimension\n Example - A 2D stratification with 2 strata in each dimension\n widths = [[0.5, 0.5]\n [0.5, 0.5]\n [0.5, 0.5]\n [0.5, 0.5]]\n\n \"\"\"\n\n def __init__(self, nstrata=None, input_file=None, origins=None, widths=None):\n\n \"\"\"\n Class defines a rectilinear stratification of the n-dimensional unit hypercube with N strata\n\n :param nstrata: array-like\n An array of dimension 1 x n defining the number of strata in each of the n dimensions\n Creates an equal stratification with strata widths equal to 1/nstrata\n The total number of strata, N, is the product of the terms of nstrata\n Example -\n nstrata = [2, 3, 2] creates a 3d stratification with:\n 2 strata in dimension 0 with stratum widths 1/2\n 3 strata in dimension 1 with stratum widths 1/3\n 2 strata in dimension 2 with stratum widths 1/2\n\n :param input_file: string\n File path to input file specifying stratum origins and stratum widths\n See documentation ######## for input file format\n\n :param origins: array-like\n An array of dimension N x n specifying the origins of all strata\n The origins of the strata are the coordinates of the stratum orthotope nearest the global origin\n Example - A 2D stratification with 2 strata in each dimension\n origins = [[0, 0]\n [0, 0.5]\n [0.5, 0]\n [0.5, 0.5]]\n\n :param widths: array-like\n An array of dimension N x n specifying the widths of all strata in each dimension\n Example - A 2D stratification with 2 strata in each dimension\n widths = [[0.5, 0.5]\n [0.5, 0.5]\n [0.5, 0.5]\n [0.5, 0.5]]\n\n Created by: Michael D. Shields\n Last modified: 11/4/2017\n Last modified by: Michael D. Shields\n\n \"\"\"\n\n self.input_file = input_file\n self.nstrata = nstrata\n self.origins = origins\n self.widths = widths\n\n if self.nstrata is None:\n if self.input_file is None:\n if self.widths is None or self.origins is None:\n sys.exit('Error: The strata are not fully defined. Must provide [nstrata], '\n 'input file, or [origins] and [widths]')\n\n else:\n # Read the strata from the specified input file\n # See documentation for input file formatting\n array_tmp = np.loadtxt(input_file)\n self.origins = array_tmp[:, 0:array_tmp.shape[1] // 2]\n self.width = array_tmp[:, array_tmp.shape[1] // 2:]\n\n # Check to see that the strata are space-filling\n space_fill = np.sum(np.prod(self.width, 1))\n if 1 - space_fill > 1e-5:\n sys.exit('Error: The stratum design is not space-filling.')\n if 1 - space_fill < -1e-5:\n sys.exit('Error: The stratum design is over-filling.')\n\n # TODO: MDS - Add a check for disjointness of strata\n # Check to see that the strata are disjoint\n # ncorners = 2**self.strata.shape[1]\n # for i in range(0,len(self.strata)):\n # for j in range(0,ncorners):\n\n else:\n # Use nstrata to assign the origin and widths of a specified rectilinear stratification.\n self.origins = np.divide(self.fullfact(self.nstrata), self.nstrata)\n self.widths = np.divide(np.ones(self.origins.shape), self.nstrata)\n self.weights = np.prod(self.widths, axis=1)\n\n def fullfact(self, levels):\n\n # TODO: MDS - Acknowledge the source here.\n \"\"\"\n Create a general full-factorial design\n\n Parameters\n ----------\n levels : array-like\n An array of integers that indicate the number of levels of each input\n design factor.\n\n Returns\n -------\n mat : 2d-array\n The design matrix with coded levels 0 to k-1 for a k-level factor\n\n Example\n -------\n ::\n\n >>> fullfact([2, 4, 3])\n array([[ 0., 0., 0.],\n [ 1., 0., 0.],\n [ 0., 1., 0.],\n [ 1., 1., 0.],\n [ 0., 2., 0.],\n [ 1., 2., 0.],\n [ 0., 3., 0.],\n [ 1., 3., 0.],\n [ 0., 0., 1.],\n [ 1., 0., 1.],\n [ 0., 1., 1.],\n [ 1., 1., 1.],\n [ 0., 2., 1.],\n [ 1., 2., 1.],\n [ 0., 3., 1.],\n [ 1., 3., 1.],\n [ 0., 0., 2.],\n [ 1., 0., 2.],\n [ 0., 1., 2.],\n [ 1., 1., 2.],\n [ 0., 2., 2.],\n [ 1., 2., 2.],\n [ 0., 3., 2.],\n [ 1., 3., 2.]])\n\n \"\"\"\n n = len(levels) # number of factors\n nb_lines = np.prod(levels) # number of trial conditions\n H = np.zeros((nb_lines, n))\n\n level_repeat = 1\n range_repeat = np.prod(levels)\n for i in range(n):\n range_repeat //= levels[i]\n lvl = []\n for j in range(levels[i]):\n lvl += [j] * level_repeat\n rng = lvl * range_repeat\n level_repeat *= levels[i]\n H[:, i] = rng\n\n return H\n\n\n########################################################################################################################\n########################################################################################################################\n# Markov Chain Monte Carlo (MCMC)\n########################################################################################################################\n\n\nclass MCMC:\n\n \"\"\"Generate samples from an arbitrary probability density function using Markov Chain Monte Carlo.\n\n This class generates samples from arbitrary distribution using Metropolis-Hastings(MH),\n Modified Metropolis-Hastings, of Affine Invariant Ensembler Sampler with stretch moves.\n\n References:\n S.-K. Au and J. L. Beck, “Estimation of small failure probabilities in high dimensions by subset simulation,”\n Probabilistic Eng. Mech., vol. 16, no. 4, pp. 263–277, Oct. 2001.\n J. Goodman and J. Weare, “Ensemble samplers with affine invariance,” Commun. Appl. Math. Comput. Sci., vol. 5,\n no. 1, pp. 65–80, 2010.\n\n Input:\n :param dimension: A scalar value defining the dimension of target density function.\n Default: 1\n :type dimension: int\n\n :param pdf_proposal_type: Type of proposed density function.\n Options:\n 'Normal' : Normal proposal density\n 'Uniform' : Uniform proposal density\n Default: 'Uniform'\n If dimension > 1 and algorithm = 'MMH', this may be input as a list to assign different proposal\n densities to each dimension. Example pdf_proposal_type = ['Normal','Uniform'].\n If dimesion > 1, algorithm = 'MMH' and this is input as a string, the proposal densities for all\n dimensions are set equal to the assigned proposal type.\n :type pdf_proposal_type: str or str list\n\n :param pdf_proposal_scale: Scale of the proposal distribution\n If algorithm == 'MH' or 'MMH'\n For pdf_proposal_type = 'Uniform'\n Proposal is Uniform in [x-pdf_proposal_scale/2, x+pdf_proposal_scale/2]\n For pdf_proposal_type = 'Normal'\n Proposal is Normal with standard deviation equal to pdf_proposal_scale\n If algorithm == 'Stretch'\n pdf_proposal_scale sets the scale of the stretch density\n g(z) = 1/sqrt(z) for z in [1/pdf_proposal_scale, pdf_proposal_scale]\n Default value: dimension x 1 list of ones\n :type pdf_proposal_scale: float or float list\n If dimension > 1, this may be defined as float or float list\n If input as float, pdf_proposal_scale is assigned to all dimensions\n If input as float list, each element is assigned to the corresponding dimension\n\n :param pdf_target_type: Type of target density function for acceptance/rejection in MMH. Not used for MH or Stretch.\n Options:\n 'marginal_pdf': Check acceptance/rejection for a candidate in MMH using the marginal pdf\n For independent variables only\n 'joint_pdf': Check acceptance/rejection for a candidate in MMH using the joint pdf\n Default: 'marginal_pdf'\n :type pdf_target_type: str\n\n :param pdf_target: Target density function from which to draw random samples\n The target joint probability density must be a function, or list of functions, or a string.\n If type == 'str'\n The assigned string must refer to a custom pdf defined in the file custom_pdf.py in the working\n directory\n If type == function\n The function must be defined in the python script calling MCMC\n If dimension > 1, the input to pdf_target is a list of size [dimensions x 1]\n Default: Multivariate normal distribution having zero mean and unit standard deviation\n :type pdf_target: function, function list, or str\n\n :param pdf_target_params: Parameters of the target pdf\n :type pdf_target_params: list\n\n :param algorithm: Algorithm used to generate random samples.\n Options:\n 'MH': Metropolis Hastings Algorithm\n 'MMH': Component-wise Modified Metropolis Hastings Algorithm\n 'Stretch': Affine Invariant Ensemble MCMC with stretch moves\n Default: 'MMH'\n :type algorithm: str\n\n :param jump: Number of samples between accepted states of the Markov chain.\n Default value: 1 (Accepts every state)\n :type: jump: int\n\n :param nsamples: Number of samples to generate\n No Default Value: nsamples must be prescribed\n :type nsamples: int\n\n :param seed: Seed of the Markov chain(s)\n For 'MH' and 'MMH', this is a single point, defined as a numpy array of dimension (1 x dimension)\n For 'Stretch', this is a numpy array of dimension N x dimension, where N is the ensemble size\n Default:\n For 'MH' and 'MMH': zeros(1 x dimension)\n For 'Stretch': No default, this must be specified.\n :type seed: float list\n\n\n Output:\n :return: MCMC.samples:\n\n :rtype: MCMC.samples: numpy array\n \"\"\"\n\n # Authors: Mohit Chauhan, Dimitris Giovanis, Michael D. Shields\n # Updated: 4/26/18 by Michael D. Shields\n\n def __init__(self, dimension=None, pdf_proposal_type=None, pdf_proposal_scale=None, pdf_target_type=None,\n pdf_target=None, pdf_target_params=None, algorithm=None, jump=None, nsamples=None, seed=None):\n\n self.pdf_proposal_type = pdf_proposal_type\n self.pdf_proposal_scale = pdf_proposal_scale\n self.pdf_target_type = pdf_target_type\n self.pdf_target = pdf_target\n self.pdf_target_params = pdf_target_params\n self.algorithm = algorithm\n self.jump = jump\n self.nsamples = nsamples\n self.dimension = dimension\n self.seed = seed\n self.init_mcmc()\n if self.algorithm is 'Stretch':\n self.ensemble_size = len(self.seed)\n self.samples = self.run_mcmc()\n\n #TODO Add burn-in\n\n def run_mcmc(self):\n rejects = 0\n\n # Defining an array to store the generated samples\n samples = np.zeros([self.nsamples * self.jump, self.dimension])\n\n ################################################################################################################\n # Classical Metropolis-Hastings Algorithm with symmetric proposal density\n if self.algorithm == 'MH':\n\n # TODO: from np.random import multivariate_normal\n\n samples[0, :] = self.seed\n\n pdf_ = self.pdf_target[0]\n\n for i in range(self.nsamples * self.jump - 1):\n if self.pdf_proposal_type[0] == 'Normal':\n if self.dimension == 1:\n candidate = np.random.normal(samples[i, :], np.array(self.pdf_proposal_scale))\n else:\n if i == 0:\n self.pdf_proposal_scale = np.diag(np.array(self.pdf_proposal_scale))\n candidate = np.random.multivariate_normal(samples[i, :], np.array(self.pdf_proposal_scale))\n\n elif self.pdf_proposal_type == 'Uniform':\n\n candidate = np.random.uniform(low=samples[i, :] - np.array(self.pdf_proposal_scale) / 2,\n high=samples[i, :] + np.array(self.pdf_proposal_scale) / 2,\n size=self.dimension)\n\n p_proposal = pdf_(candidate, self.pdf_target_params)\n p_current = pdf_(samples[i, :], self.pdf_target_params)\n p_accept = p_proposal / p_current\n\n accept = np.random.random() < p_accept\n\n if accept:\n samples[i + 1, :] = candidate\n else:\n samples[i + 1, :] = samples[i, :]\n rejects += 1\n\n ################################################################################################################\n # Modified Metropolis-Hastings Algorithm with symmetric proposal density\n elif self.algorithm == 'MMH':\n\n samples[0, :] = self.seed[0]\n\n if self.pdf_target_type == 'marginal_pdf':\n for i in range(self.nsamples * self.jump - 1):\n for j in range(self.dimension):\n\n pdf_ = self.pdf_target[j]\n\n if self.pdf_proposal_type[j] == 'Normal':\n candidate = np.random.normal(samples[i, j], self.pdf_proposal_scale[j])\n\n elif self.pdf_proposal_type[j] == 'Uniform':\n candidate = np.random.uniform(low=samples[i, j] - self.pdf_proposal_scale[j] / 2,\n high=samples[i, j] + self.pdf_proposal_scale[j] / 2, size=1)\n\n p_proposal = pdf_(candidate, self.pdf_target_params)\n p_current = pdf_(samples[i, j], self.pdf_target_params)\n p_accept = p_proposal / p_current\n\n accept = np.random.random() < p_accept\n\n if accept:\n samples[i + 1, j] = candidate\n else:\n samples[i + 1, j] = samples[i, j]\n\n elif self.pdf_target_type == 'joint_pdf':\n pdf_ = self.pdf_target[0]\n # current = np.zeros(self.dimension)\n for i in range(self.nsamples * self.jump - 1):\n candidate = list(samples[i, :])\n # if i==0:\n # current = self.seed\n # else:\n # current = samples[i-1,:]\n current = list(samples[i, :])\n for j in range(self.dimension):\n if self.pdf_proposal_type[j] == 'Normal':\n candidate[j] = np.random.normal(samples[i, j], self.pdf_proposal_scale[j])\n\n elif self.pdf_proposal_type[j] == 'Uniform':\n candidate[j] = np.random.uniform(low=samples[i, j] - self.pdf_proposal_scale[j] / 2,\n high=samples[i, j] + self.pdf_proposal_scale[j] / 2,\n size=1)\n\n p_proposal = pdf_(candidate, self.pdf_target_params)\n p_current = pdf_(current, self.pdf_target_params)\n p_accept = p_proposal / p_current\n\n accept = np.random.random() < p_accept\n\n if accept:\n current[j] = candidate[j]\n else:\n candidate[j] = current[j]\n\n samples[i + 1, :] = current\n\n ################################################################################################################\n # Affine Invariant Ensemble Sampler with stretch moves\n # Reference: Goodman, J. and Weare, J., (2010) \"Ensemble samplers with affine invariance.\" Communications in\n # applied mathematics and computational science. 5: 65-80.\n\n elif self.algorithm == 'Stretch':\n\n samples[0:self.ensemble_size, :] = self.seed\n\n pdf_ = self.pdf_target[0]\n\n for i in range(self.ensemble_size-1,self.nsamples * self.jump - 1):\n complementary_ensemble = samples[i-self.ensemble_size+2:i+1,:]\n S = random.choice(complementary_ensemble)\n s = (1+(self.pdf_proposal_scale[0]-1)*random.random())**2/self.pdf_proposal_scale[0]\n candidate = S+s*(samples[i-self.ensemble_size+1,:]-S)\n\n p_proposal = pdf_(candidate, self.pdf_target_params)\n p_current = pdf_(samples[i-self.ensemble_size+1, :], self.pdf_target_params)\n p_accept = s**(self.dimension-1)*p_proposal/p_current\n\n accept = np.random.random() < p_accept\n\n if accept:\n samples[i + 1, :] = candidate\n else:\n samples[i + 1, :] = samples[i-self.ensemble_size+1, :]\n\n ################################################################################################################\n # Return the samples\n\n if self.algorithm is 'MMH' or self.algorithm is 'MH':\n return samples[0:self.nsamples * self.jump:self.jump]\n else:\n output = np.zeros((self.nsamples,self.dimension))\n j = 0\n for i in range(self.jump*self.ensemble_size-self.ensemble_size, samples.shape[0],\n self.jump*self.ensemble_size):\n output[j:j+self.ensemble_size,:] = samples[i:i+self.ensemble_size,:]\n j = j+self.ensemble_size\n return output\n\n # TODO: Add Gibbs Sampler\n # TODO: Add Affine Invariant with walk moves\n\n ####################################################################################################################\n # Check to ensure consistency of the user input and assign defaults\n def init_mcmc(self):\n\n if self.dimension is None:\n self.dimension = 1\n\n # Check nsamples\n if self.nsamples is None:\n raise NotImplementedError('Exit code: Number of samples not defined.')\n \n # Check seed\n if self.seed is None:\n self.seed = np.zeros(self.dimension)\n if self.algorithm is not 'Stretch':\n if self.seed.__len__() != self.dimension:\n raise NotImplementedError(\"Exit code: Incompatible dimensions in 'seed'.\")\n else:\n if self.seed.shape[0] < 3:\n raise NotImplementedError(\"Exit code: Ensemble size must be > 2.\")\n\n # Check jump\n if self.jump is None:\n self.jump = 1\n\n # Check pdf_proposal_type\n if self.pdf_proposal_type is None:\n self.pdf_proposal_type = 'Uniform'\n # If pdf_proposal_type is entered as a string, make it a list\n if type(self.pdf_proposal_type).__name__=='str':\n self.pdf_proposal_type = [self.pdf_proposal_type]\n for i in self.pdf_proposal_type:\n if i not in ['Uniform', 'Normal']:\n raise ValueError('Exit code: Unrecognized type for proposal distribution. Supported distributions: '\n 'Uniform, '\n 'Normal.')\n if self.algorithm is 'MH' and len(self.pdf_proposal_type)!=1:\n raise ValueError('Exit code: MH algorithm can only take one proposal distribution.')\n elif len(self.pdf_proposal_type)!=self.dimension:\n if len(self.pdf_proposal_type) == 1:\n self.pdf_proposal_type = self.pdf_proposal_type * self.dimension\n else:\n raise NotImplementedError(\"Exit code: Incompatible dimensions in 'pdf_proposal_type'.\")\n\n # Check pdf_proposal_scale\n if self.pdf_proposal_scale is None:\n self.pdf_proposal_scale = 1\n if type(self.pdf_proposal_scale).__name__ != 'list':\n self.pdf_proposal_scale = [self.pdf_proposal_scale]\n if len(self.pdf_proposal_scale) != self.dimension:\n if len(self.pdf_proposal_scale) == 1:\n self.pdf_proposal_scale = self.pdf_proposal_scale * self.dimension\n else:\n raise NotImplementedError(\"Exit code: Incompatible dimensions in 'pdf_proposal_scale'.\")\n\n # Check pdf_target_type\n if self.algorithm is 'MMH' and self.pdf_target_type is None:\n self.pdf_target_type = 'marginal_pdf'\n if self.pdf_target_type not in ['joint_pdf', 'marginal_pdf']:\n raise ValueError('Exit code: Unrecognized type for target distribution. Supported distributions: '\n 'joint_pdf, '\n 'marginal_pdf.')\n\n # Check algorithm\n if self.algorithm is None:\n self.algorithm = 'MMH'\n else:\n if self.algorithm not in ['MH', 'MMH', 'Stretch']:\n raise NotImplementedError('Exit code: Unrecognized MCMC algorithm. Supported algorithms: '\n 'Metropolis-Hastings (MH), '\n 'Modified Metropolis-Hastings (MMH), '\n 'Affine Invariant Ensemble with Stretch Moves (Stretch).')\n\n # Check pdf_target\n if type(self.pdf_target).__name__ == 'str':\n self.pdf_target = pdf(self.pdf_target)\n if self.pdf_target is None and self.algorithm is 'MMH':\n if self.dimension == 1 or self.pdf_target_type is 'marginal_pdf':\n def target(x):\n return sp.norm.pdf(x)\n if self.dimension == 1:\n self.pdf_target = [target]\n else:\n self.pdf_target = [target] * self.dimension\n else:\n def target(x):\n return sp.multivariate_normal.pdf(x,mean=np.zeros(self.dimension),cov=np.eye(self.dimension))\n self.pdf_target = [target]\n elif self.pdf_target is None:\n if self.dimension == 1:\n def target(x):\n return sp.norm.pdf(x)\n self.pdf_target = [target]\n else:\n def target(x):\n return sp.multivariate_normal.pdf(x,mean=np.zeros(self.dimension),cov=np.eye(self.dimension))\n self.pdf_target = [target]\n elif type(self.pdf_target).__name__ != 'list':\n self.pdf_target = [self.pdf_target]\n\n # Check pdf_target_params\n if self.pdf_target_params is None:\n self.pdf_target_params = []\n if type(self.pdf_target_params).__name__!='list':\n self.pdf_target_params = [self.pdf_target_params]\n\n\n\n########################################################################################################################\n########################################################################################################################\n# ADD ANY NEW METHOD HERE\n########################################################################################################################\n","sub_path":"build/lib/UQpy/SampleMethods.py","file_name":"SampleMethods.py","file_ext":"py","file_size_in_byte":65044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"213884672","text":"import sys\nfrom pySQL import *\nimport json\nimport os\n\nclass node(object):\n\tdef __init__(self, row, star = False):\n\t\t\"\"\"\n\t\tinitializes node object\n\t\targ: row of SQL query data\n\t\t\"\"\"\n\t\tself.id = row['id']\n\t\tself.jitid = row['jitid']\n\t\tself.name = row['name']\n\t\tself.adjacencies = []\n\t\tself.value = row['value']\n\t\tself.pid = None\n\t\tself.jit = None\n\t\tself.dct = {}\n\t\tself.is_star(star)\n\tdef __repr__(self):\n\t\treturn self.name\n\t\treturn self.pid\n\tdef is_star(self,star):\n\t\tif star:\n\t\t\tself.pid = 000\n\t\t\tself.adjacencies.append(self.pid)\n\tdef add_child(self,n):\n\t\t\"\"\"\n\t\tadds child to adjacencies list\n\t\t\"\"\"\n\t\tself.adjacencies.append(n.jitid)\n\t\tn.pid = self.id\t\t\t\n\tdef is_parent(self):\n\t\t\"\"\"\n\t\tchecks if node has children\n\t\treturns boolean\n\t\t\"\"\"\n\t\tif get_childs_by_pid(self.id):\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\tdef generate_JSON(self):\n\t\t\"\"\"\n\t\tgenerates JSON structure\n\t\treturns JSON structure\n\t\t\"\"\"\n\t\tself.dct = {\n\t\t'jitid':self.jitid,\n\t\t'name': self.name,\n\t\t'data':{'value':self.value},\n\t\t'adjacencies':self.adjacencies\n\t\t}\n\t\tself.jit = json.dumps(self.dct)\n\ndef create_star(jitid):\n\t\"\"\"\n\tcreates star/company\n\targs: requires companies jitID\n\treturn: list of all nodes in system\n\t\"\"\"\n\trow = get_node_by_jitid(jitid)\n\tn = node(row, star = True)\n\tsystem = [n]\n\tif n.is_parent():\n\t\tsystem.extend(create_system(n))\n\treturn system\n\t\ndef create_system(parent):\n\t\"\"\"\n\tcreates childs of parent node recursively\n\targs: node object\n\treturns list of all children node for given parent node\n\t\"\"\"\n\tsystem = []\n\tchild_list = get_childs_by_pid(parent.id)\n\tfor childs in child_list:\n\t\trow = get_node_by_id(childs['chid'])\n\t\tp = node(row)\n\t\tparent.add_child(p)\n\t\tsystem.append(p)\n\t\tif p.is_parent():\n\t\t\tsystem.extend(create_system(p))\n\t\telse:\n\t\t\tcontinue\n\treturn system\n\ndef create_universe(companies):\n\tuniverse =[]\n\tfor jitid in companies:\n\t\tsystem = create_star(jitid)\n\t\tuniverse.append(system)\n\treturn universe\n\ndef create_JSON(systems):\n\tfor nodes in systems:\n\t\tif nodes.pid == 000:\n\t\t\tind = systems.index(nodes)\n\t\t\tfName = systems[ind].name + \".json\"\n\t\t\tbreak\n\tfp = open(fName, 'w')\n\tfor nodes in systems:\n\t\tnodes.generate_JSON()\n\t\tjson.dump(nodes.dct,fp)\n\t\tfp.write('\\n')\n\tfp.close()\n\ndef write_json(universe):\n\tfor systems in universe:\n\t\tcreate_JSON(systems)\n\ndef main(companies):\n\t\"\"\"\n\truns all functions\n\targs: list of jitids where jitid is ticker symbol of company\n\tprints json structure of node\n\t\"\"\"\n\tif type(companies) != list:\n\t\tcompanies = [companies]\n\tuniverse = create_universe(companies)\t\n\twrite_json(universe)\n\t\nif __name__ == \"__main__\":\n\tmain(sys.argv[1])\n","sub_path":"backend/pyJit (1) 2.py","file_name":"pyJit (1) 2.py","file_ext":"py","file_size_in_byte":2562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"486314267","text":"\n#sensor name to retrieve\n#log file start and stop time to match to sensors you are retrieving\n#to me it looks like kat_store is running on a SAST timezone\ndef sensor_data_pvsn(sensor, timestart, timestop):\n import requests \n sensors_url = 'http://portal.mkat.karoo.kat.ac.za/katstore/api/query'\n\n sample_params = {'sensor':sensor, \n 'start_time':timestart.strftime('%s'), \n 'end_time': timestop.strftime('%s'),\n 'include_value_time': True}\n\n #Debug\n #print(sample_params)\n try:\n resp = requests.get(sensors_url, sample_params)\n except Exception as exc:\n print('Something failed: {}'.format(exc))\n if resp.status_code == 200:\n sample_results = resp.json()\n #Debug\n #print(resp.json())\n timestampv=[sample['value_time'] for sample in sample_results['data']]\n timestamps=[sample['sample_time'] for sample in sample_results['data']]\n samples=[sample['value'] for sample in sample_results['data']]\n else:\n print(\"Request returned with a status code {}\".format(resp.status_code))\n print(resp)\n return(timestampv,timestamps,samples)\n \n","sub_path":"cam_sensors.py","file_name":"cam_sensors.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"540893194","text":"import re\nimport math\n\nMT_NORMAL = 0\nMT_RAPID = 1\n\ngcRegex = re.compile(\"[-]?\\d+[.]?\\d*\")\t\n\ndef get_float(which, pstr):\n\ttry:\n\t\treturn float(gcRegex.findall(pstr.split(which)[1])[0])\n\texcept ValueError:\n\t\treturn 0.0\n\texcept IndexError:\n\t\treturn 0.0\n\ndef drawArc(cx, cy, cz, rad, angstart, angend, cw, numsegments):\n\tpts = []\n\tif cw:\n\t\tsign = -1\n\t\tangdist = angstart - angend\n\t\twhile angdist <= 0:\n\t\t\tangdist += 2*math.pi\n\telse:\n\t\tsign = 1\n\t\tangdist = angend - angstart\n\t\twhile angdist <= 0:\n\t\t\tangdist += 2*math.pi\n\t\t\t\n\tsegs = int(math.degrees(angdist)/4)\n\tif segs < numsegments:\n\t\tsegs = numsegments\n\t\t\n\tfor i in range(segs+1): \n\t\ttheta = angstart + sign * (angdist * (float(i) / float(segs)))\n\t\twhile theta < 0:\n\t\t\ttheta += 2*math.pi\n\n\t\tdx = rad * math.cos(theta)\n\t\tdy = rad * math.sin(theta) \n\n\t\tpts.append([cx + dx, cy + dy, cz]) \n\t\t\n\treturn pts\n\ndef setQuadrant(sa, dx, dy):\n\ta = math.degrees(sa)\n\tif dy >= 0:\n\t\twhile a < 0.0:\n\t\t\ta += 180\n\t\twhile a > 180:\n\t\t\ta -= 180\n\telse:\n\t\twhile a < 180:\n\t\t\ta += 180\n\t\twhile a > 360:\n\t\t\ta -= 180\n\t\t\n\tif dx <= 0:\n\t\twhile a > 270:\n\t\t\ta -= 180\n\t\twhile a < 90:\n\t\t\ta += 180\n\telse:\n\t\twhile a > 450:\n\t\t\ta -= 180\n\t\twhile a < 270:\n\t\t\ta += 180\n\t\tif a >= 360:\n\t\t\ta -= 360\n\t\n\treturn math.radians(a)\n\n\nclass GParseErrorSyntax(Exception):\n\tpass\n\nclass GParseErrorNoCommand(Exception):\n\tpass\n\n\nclass GParseErrorNumberFormat(Exception):\n\tpass\n\nclass gShifter:\n\treXparam = re.compile('(.*X *)(-{0,1}\\d*\\.\\d+)(.*)')\n\treYparam = re.compile('(.*Y *)(-{0,1}\\d*\\.\\d+)(.*)')\n\n\tdef __init__(self, dx, dy):\n\t\tself.dx = dx\n\t\tself.dy = dy\n\t\t\n\tdef shift(self, gline):\n\t\tif self.dx != 0:\n\t\t\tgline = self.shiftX(gline)\n\t\tif self.dy != 0:\n\t\t\tgline = self.shiftY(gline)\n\t\treturn gline\n\t\n\tdef getFormat(self, sval):\n\t\tc = sval.split(\".\")\n\t\tif len(c) != 2:\n\t\t\tprint(\"length not 2 (%s)\" % sval)\n\t\t\treturn \"%-.2f\"\n\t\t\n\t\tl = len(c[1])\n\t\tfmt = \"%\" + (\"-0.%df\" % l)\n\t\treturn fmt\n\t\n\tdef shiftX(self, gline):\n\t\tr = gShifter.reXparam.match(gline)\n\t\tif r is None:\n\t\t\treturn gline\n\t\t\n\t\ttry:\n\t\t\tsval = r.group(2)\n\t\t\tval = float(sval)\n\t\texcept:\n\t\t\tprint(\"unable to parse X value out of (%s) - leaving unchanged\" % gline)\n\t\t\treturn gline\n\t\t\n\t\tnewsval = self.getFormat(sval) % (val + self.dx)\n\t\t\n\t\tnewg = r.group(1) + newsval + r.group(3)\n\t\treturn newg\n\t\n\tdef shiftY(self, gline):\n\t\tr = gShifter.reYparam.match(gline)\n\t\tif r is None:\n\t\t\treturn gline\n\t\t\n\t\ttry:\n\t\t\tsval = r.group(2)\n\t\t\tval = float(sval)\n\t\texcept:\n\t\t\tprint(\"unable to parse y value out of (%s) - leaving unchanged\" % gline)\n\t\t\treturn gline\n\t\t\n\t\tnewsval = self.getFormat(sval) % (val + self.dy)\n\t\t\n\t\tnewg = r.group(1) + newsval + r.group(3)\n\t\treturn newg\n\t\t\n\nclass gMirror:\n\treXparam = re.compile('(.*X *)(-{0,1}\\d*\\.\\d+)(.*)')\n\treYparam = re.compile('(.*Y *)(-{0,1}\\d*\\.\\d+)(.*)')\n\n\tdef __init__(self):\n\t\tpass\n\t\t\n\tdef getFormat(self, sval):\n\t\tc = sval.split(\".\")\n\t\tif len(c) != 2:\n\t\t\tprint(\"length not 2 (%s)\" % sval)\n\t\t\treturn \"%-.2f\"\n\t\t\n\t\tl = len(c[1])\n\t\tfmt = \"%\" + (\"-0.%df\" % l)\n\t\treturn fmt\n\t\n\tdef mirrorY(self, gline):\n\t\tr = gMirror.reXparam.match(gline)\n\t\tif r is None:\n\t\t\treturn gline\n\t\t\n\t\ttry:\n\t\t\tsval = r.group(2)\n\t\t\tval = float(sval)\n\t\texcept:\n\t\t\tprint(\"unable to parse X value out of (%s) - leaving unchanged\" % gline)\n\t\t\treturn gline\n\t\t\n\t\tnewsval = self.getFormat(sval) % -val\n\t\t\n\t\tnewg = r.group(1) + newsval + r.group(3)\n\t\treturn newg\n\t\n\tdef mirrorX(self, gline):\n\t\tr = gMirror.reYparam.match(gline)\n\t\tif r is None:\n\t\t\treturn gline\n\t\t\n\t\ttry:\n\t\t\tsval = r.group(2)\n\t\t\tval = float(sval)\n\t\texcept:\n\t\t\tprint(\"unable to parse y value out of (%s) - leaving unchanged\" % gline)\n\t\t\treturn gline\n\t\t\n\t\tnewsval = self.getFormat(sval) % -val\t\n\t\t\t\n\t\tnewg = r.group(1) + newsval + r.group(3)\n\t\treturn newg\n\t\t\n\nclass gParser:\n\tgcmd = re.compile('^([GMT]\\d+)(.*)')\n\tgparm = re.compile('^([XYZFIJKS] *-{0,1}\\d*\\.{0,1}\\d+)(.*)')\n\n\tdef __init__(self):\n\t\tself.lastCmd = None\n\n\tdef parseGLine(self, gline):\n\t\tgl = gline.strip().upper()\n\t\tif '(' in gl:\n\t\t\tgl = gl.split('(', 1)[0]\n\n\t\tif ';' in gl:\n\t\t\tgl = gl.split(';', 1)[0]\n\n\t\tif '%' in gl:\n\t\t\tgl = gl.split('%', 1)[0]\n\n\t\tif len(gl) == 0:\n\t\t\treturn None, None\n\n\t\tr = gParser.gcmd.match(gl)\n\t\tif r is None:\n\t\t\tif self.lastCmd is None:\n\t\t\t\traise GParseErrorNoCommand\n\t\t\telse:\n\t\t\t\tcmd = self.lastCmd\n\t\t\t\tremaining = gl\n\t\telse:\n\t\t\tcmd = r.group(1)\n\t\t\ttry:\n\t\t\t\tremaining = r.group(2).strip()\n\t\t\texcept IndexError:\n\t\t\t\tremaining = \"\"\n\n\t\t\tif cmd in [\"G1\", \"G01\", \"G0\", \"G00\"]:\n\t\t\t\tself.lastCmd = cmd\n\n\t\tparms = {}\n\t\twhile remaining != \"\":\n\t\t\tr = gParser.gparm.match(remaining)\n\t\t\tif r is None:\n\t\t\t\traise GParseErrorSyntax\n\t\t\telse:\n\t\t\t\tprm = r.group(1)\n\t\t\t\ttag = prm[0]\n\t\t\t\tprm = prm[1:]\n\t\t\t\ttry:\n\t\t\t\t\tparms[tag] = float(prm)\n\t\t\t\texcept ValueError:\n\t\t\t\t\traise GParseErrorNumberFormat\n\n\t\t\t\ttry:\n\t\t\t\t\tremaining = r.group(2).strip()\n\t\t\t\texcept IndexError:\n\t\t\t\t\tremaining = \"\"\n\n\t\treturn cmd, parms\t\n\t\n\t\nclass CNC:\n\tdef __init__(self):\n\t\tself.curX = 0\n\t\tself.curY = 0\n\t\tself.curZ = 0\n\t\tself.curI = 0\n\t\tself.curJ = 0\n\t\tself.curK = 0\n\n\t\tself.points = [(0, 0, 0, MT_NORMAL, 0)]\n\t\t\n\t\tself.relative = False\n\t\tself.metric = True\t\n\t\t\n\t\tself.lastCmd = \"G1\"\n\t\t\n\t\tself.gp = gParser()\n\n\t\tself.dispatch = {\n\t\t\t\"G0\": self.moveFast,\n\t\t\t\"G1\": self.moveSlow,\n\t\t\t\"G2\": self.arcCW,\n\t\t\t\"G3\": self.arcCCW,\n\t\t\t\"G20\": self.setInches,\n\t\t\t\"G21\": self.setMillimeters,\n\t\t\t\"G28\": self.home,\n\t\t\t\"G90\": self.setAbsolute,\n\t\t\t\"G91\": self.setRelative,\n\t\t\t\"G92\": self.axisReset,\n\t\t\t}\n\t\t\n\tdef execute(self, gline, lx):\n\t\tself.currentlx = lx\n\t\tcmd, params = self.gp.parseGLine(gline)\n\t\tif cmd is None:\n\t\t\treturn\n\t\tif cmd not in self.dispatch:\n\t\t\treturn\n\t\n\t\tself.dispatch[cmd](params)\n\t\t\n\tdef moveFast(self, parms):\n\t\tself.lastCmd = \"G0\"\n\t\tself.move(parms, MT_RAPID)\n\t\t\n\tdef moveSlow(self, parms):\n\t\tself.lastCmd = \"G1\"\n\t\tself.move(parms, MT_NORMAL)\n\t\t\n\tdef move(self, parms, moveType):\n\t\tself.checkCoords(parms)\t\t\n\t\tself.recordPoint(self.curX, self.curY, self.curZ, moveType)\n\t\t\n\tdef arcCW(self, params):\n\t\tself.arc(params, True)\n\t\t\n\tdef arcCCW(self, params):\n\t\tself.arc(params, False)\n\t\t\n\tdef arc(self, params, cw):\n\t\tx = self.curX\n\t\ty = self.curY\n\t\tz = self.curZ\n\t\tself.checkCoords(params)\n\t\t\n\t\tcx = x + self.curI\n\t\tcy = y + self.curJ\n\t\tcz = z + self.curK\n\n\t\t# calculate radius, start and end angles\n\t\tdx = x - cx\n\t\tdy = y - cy\n\t\tif dy == 0:\n\t\t\tstartang = math.radians(0)\n\t\telif dx == 0:\n\t\t\tstartang = math.radians(90)\n\t\telse:\n\t\t\tstartang = math.atan(dy/dx)\n\t\t\t\n\t\tstartang = setQuadrant(startang, dx, dy)\n\t\trad = math.sqrt(dx*dx+dy*dy)\n\t\t\n\t\tdx = self.curX - cx\n\t\tdy = self.curY - cy\n\t\tif dy == 0:\n\t\t\tendang = math.radians(0)\n\t\telif dx == 0:\n\t\t\tendang = math.radians(90)\n\t\telse:\n\t\t\tendang = math.atan(dy/dx)\n\t\tendang = setQuadrant(endang, dx, dy)\n\n\t\tpts = drawArc(cx, cy, cz, rad, startang, endang, cw, 20)\n\t\tfor p in pts:\n\t\t\tself.recordPoint(p[0], p[1], p[2], MT_NORMAL)\n\t\n\tdef recordPoint(self, px, py, pz, mtype):\n\t\tself.points.append((px, py, pz, mtype, self.currentlx))\n\t\t\n\tdef getPoints(self):\n\t\treturn self.points\n\t\t\n\tdef setInches(self, _):\n\t\tself.metric = False\n\n\tdef setMillimeters(self, _):\n\t\tself.metric = True\n\n\tdef home(self, parms):\n\t\tnaxes = 0\n\t\tif 'X' in parms.keys():\n\t\t\tself.curX = 0\n\t\t\tnaxes += 1\n\t\tif 'Y' in parms.keys():\n\t\t\tself.curY = 0\n\t\t\tnaxes += 1\n\t\tif 'Z' in parms.keys():\n\t\t\tself.curZ = 0\n\t\t\tnaxes += 1\n\t\t\t\n\t\tif naxes == 0:\n\t\t\tself.curX = 0\n\t\t\tself.curY = 0\n\t\t\tself.curZ = 0\n\t\t\t\n\t\tself.recordPoint(self.curX, self.curY, self.curZ, MT_NORMAL)\n\n\tdef setAbsolute(self, *_):\n\t\tself.relative = False\n\n\tdef setRelative(self, *_):\n\t\tself.relative = True\n\t\t\n\tdef axisReset(self, parms, _):\n\t\tif 'X' in parms.keys():\n\t\t\tself.curX = float(parms['X'])\n\t\tif 'Y' in parms.keys():\n\t\t\tself.curY = float(parms['Y'])\n\t\tif 'Z' in parms.keys():\n\t\t\tself.curZ = float(parms['Z'])\n\t\n\tdef checkCoords(self, parms):\n\t\tif self.relative:\n\t\t\tif 'X' in parms.keys():\n\t\t\t\tself.curX += float(parms[\"X\"])\n\t\t\tif 'Y' in parms.keys():\n\t\t\t\tself.curY += float(parms[\"Y\"])\n\t\t\tif 'Z' in parms.keys():\n\t\t\t\tself.curZ += float(parms[\"Z\"])\n\t\telse:\n\t\t\tif 'X' in parms.keys():\n\t\t\t\tself.curX = float(parms[\"X\"])\n\t\t\tif 'Y' in parms.keys():\n\t\t\t\tself.curY = float(parms[\"Y\"])\n\t\t\tif 'Z' in parms.keys():\n\t\t\t\tself.curZ = float(parms[\"Z\"])\n\n\t\tself.curI = 0.0\n\t\tself.curJ = 0.0\n\t\tself.curK = 0.0\n\t\tif 'I' in parms.keys():\n\t\t\tself.curI = float(parms[\"I\"])\n\t\tif 'J' in parms.keys():\n\t\t\tself.curJ = float(parms[\"J\"])\n\t\tif 'K' in parms.keys():\n\t\t\tself.curK = float(parms[\"K\"])\n\n\n","sub_path":"monitor/cnc.py","file_name":"cnc.py","file_ext":"py","file_size_in_byte":8306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"439371337","text":"import requests\nfrom multiprocessing import Process\nimport json\nfrom queue import Queue\nimport time\n\nclass XiaomiSpider(object):\n def __init__(self):\n self.url='http://app.mi.com/categotyAllListApi?page={}&categoryId=5&pageSize=30'\n self.headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36'}\n #创建队列\n self.q=Queue()\n self.i=0\n \n #URL入队列\n def url_in(self):\n for page in range(11):\n #入队列\n self.q.put(self.url.format(str(page)))\n \n \n #进程事件函数:获取队列中的URL,发请求解析处理数据\n def get_data(self):\n #获取url,做解析\n while True:\n if self.q.empty():\n break\n else:\n url=self.q.get()\n html=requests.get(url,headers=self.headers\n ).text\n html=json.loads(html)\n for app in html['data']:\n app_name=app['displayName']\n app_url=app['packageName']\n self.i+=1\n app_dict={'应用名称':app_name,\n '应用链接':app_url}\n \n print(app_dict)\n \n def main(self):\n #入队列\n self.url_in()\n #创建多个进程并启动进程\n t_list=[]\n for i in range(2):\n t=Process(target=self.get_data)\n t_list.append(t)\n t.start()\n #回收进程\n for i in t_list:\n i.join()\n print(self.i)\n \nif __name__=='__main__':\n start=time.time()\n spider=XiaomiSpider()\n spider.main()\n end=time.time()\n print(end-start)\n","sub_path":"爬虫项目/小米应用商店(多进程).py","file_name":"小米应用商店(多进程).py","file_ext":"py","file_size_in_byte":1847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"96031283","text":"# A recursive implementation of Binary Search\ndef recBinarySearch(target, theValues, first, last):\n # If the sequence of values cannot be subdivided further,\n # we are done\n if last <= first: # BASE CASE #1\n return False\n\n\n else:\n # Find the midpoint of the sequence\n mid = (first + last) // 2\n # Does the element at the midpoint contain the target?\n if theValues[mid] == target:\n return True # BASE CASE #2\n # or does the target precede the element at the midpoint?\n elif target < theValues[mid]:\n return recBinarySearch(target, theValues, first, mid - 1)\n # or does the target follows the element at the midpoint?\n else:\n return recBinarySearch(target ,theValues , mid + 1, last)\n\n\nprint(recBinarySearch(5,[1,2,3,4,5,6,7,8,9],0 ,8))\n","sub_path":"Week 7/Practical/Q2.py","file_name":"Q2.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"50087631","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 27 17:13:27 2020\n\n@author: mbulut\n\"\"\"\n\n\n\n\n#1. kutuphaneler\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n\n\n\n#2.1. Veri Yukleme\n\nveriler = pd.read_csv('veriler.csv')\n\n#pd.read_csv(\"veriler.csv\")\n\n#veri on isleme\n\nboy = veriler[['boy']]#test\n\nprint(boy)\n\nboykilo = veriler[['boy','kilo']]\n\nprint(boykilo)\n\n#eksik veriler\n\nfrom sklearn.impute import SimpleImputer\n\nimputer= SimpleImputer(missing_values=np.nan, strategy='mean') \n\nYas = veriler.iloc[:,1:4].values\nprint(Yas)\n\nimputer = imputer.fit(Yas[:,1:4])\n\nYas[:,1:4] = imputer.transform(Yas[:,1:4])\nprint(Yas)\n\n\n\n#encoder: Kategorik -> Numeric\n\nulke = veriler.iloc[:,0:1].values\nprint(ulke)\n\nfrom sklearn.preprocessing import LabelEncoder\nle = LabelEncoder()\n\nulke[:,0] = le.fit_transform(ulke[:,0])\nprint(ulke)\n\n\n\nfrom sklearn.preprocessing import OneHotEncoder\nohe = OneHotEncoder(categories='auto')\nulke=ohe.fit_transform(ulke).toarray()\nprint(ulke)\n\n\n#encoder: Kategorik -> Numeric (cinsiyet)\n\nc = veriler.iloc[:,-1:].values\nprint(c)\n\nfrom sklearn.preprocessing import LabelEncoder\nle = LabelEncoder()\n\nc[:,0] = le.fit_transform(c[:,0])\nprint(c)\n\n\n\nfrom sklearn.preprocessing import OneHotEncoder\nohe = OneHotEncoder(categories='auto')\nc=ohe.fit_transform(c).toarray()\nprint(c)\n\n\n\n#numpy dizileri dataframe donusumu\n\nsonuc = pd.DataFrame(data = ulke, index = range(22), columns=['fr','tr','us'] )\nprint(sonuc)\n\n\n\nsonuc2 =pd.DataFrame(data = Yas, index = range(22), columns = ['boy','kilo','yas'])\nprint(sonuc2)\n\n\n\ncinsiyet = veriler.iloc[:,-1].values\nprint(cinsiyet)\n\n\n\nsonuc3 = pd.DataFrame(data = c[:,:1] , index=range(22), columns=['cinsiyet'])\nprint(sonuc3)\n\n\n\n#dataframe birlestirme islemi\n\ns=pd.concat([sonuc,sonuc2],axis=1)\nprint(s)\n\n\n\ns2= pd.concat([s,sonuc3],axis=1)\nprint(s2)\n\n\n\n#verilerin egitim ve test icin bolunmesi\n\nfrom sklearn.model_selection import train_test_split\n\nx_train, x_test,y_train,y_test = train_test_split(s,sonuc3,test_size=0.33, random_state=0)\n\n\n#verilerin olceklenmesi\n\"\"\"\nfrom sklearn.preprocessing import StandardScaler\n\nsc = StandardScaler()\n\nX_train = sc.fit_transform(x_train)\n\nX_test = sc.fit_transform(x_test)\n\n\"\"\"\nfrom sklearn.linear_model import LinearRegression\nregressor=LinearRegression()\nregressor.fit(x_train,y_train)\n\ny_pred=regressor.predict(x_test)\n\n\n#HADİ BUNU BOY İÇİN YAPALIM. BOY \"Y\" DEĞERİ OLACAK\nboy=s2.iloc[:,3:4].values\nsol=s2.iloc[:,:3]\nsag=s2.iloc[:,4:]\n\nveri=pd.concat([sol,sag],axis=1)\n\nx_train, x_test,y_train,y_test = train_test_split(veri,boy,test_size=0.33, random_state=0)\n\nr2=LinearRegression()\nr2.fit(x_train,y_train)\n\ny_pred=r2.predict(x_test)\n\n\nimport statsmodels.api as sm\n\nX=np.append(arr=np.ones((22,1)).astype(int),values=veri,axis=1)\nX_l=veri.iloc[:,[0,1,2,3,4,5]].values\nprint(X)\nprint(X_l)\nr_ols=sm.OLS(endog=boy,exog=X_l).fit()\n\n#print(r_ols.summary())\n\n\n\n\n\n\n\n\n\n\n","sub_path":"2- Doğrusal Regresyon/2-Çoklu Doğrusal Regresyon/2-Geri Eleme/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"458817526","text":"from os.path import join\n\nfrom setuptools import Extension, find_packages, setup\n\n\ndef get_long_description():\n with open('README.rst') as fp:\n return fp.read()\n\n\ndef get_ext_modules():\n base = 'ufpeg/booster'\n sources = ['ufpegbooster.cpp']\n depends = ['node.hpp', 'context.hpp', 'instructions.hpp', 'vm.hpp']\n booster = Extension(\n 'ufpeg.booster',\n sources=[join(base, src) for src in sources],\n depends=[join(base, dep) for dep in depends],\n )\n return [booster]\n\n\nsetup(\n name='ufpeg',\n version='0.1.0',\n description='UFPEG: An ultra fast parser for Python using PEG',\n long_description=get_long_description(),\n url='https://github.com/eb08a167/ufpeg',\n author='Andrew Kiyko',\n author_email='eb08a167@gmail.com',\n license='MIT',\n classifiers=[\n 'Programming Language :: C',\n 'Programming Language :: Python :: 3',\n 'Intended Audience :: Developers',\n ],\n packages=find_packages(),\n ext_modules=get_ext_modules(),\n python_requires='>=3.3',\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"285042912","text":"#\n# Copyright 2017 by Delphix\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#\n# This class has been automatically generated from:\n# /delphix-network-latency-test.json\n#\n# Do not edit this file manually!\n#\n\nfrom delphixpy.v1_9_0.web.vo.NetworkTest import NetworkTest\nfrom delphixpy.v1_9_0 import factory\nfrom delphixpy.v1_9_0 import common\n\nclass __Undef(object):\n def __repr__(self):\n return \"undef\"\n\n_UNDEFINED = __Undef()\n\nclass NetworkLatencyTest(NetworkTest):\n \"\"\"\n *(extends* :py:class:`v1_9_0.web.vo.NetworkTest` *)* Round-trip latency\n tests to a target system.\n \"\"\"\n def __init__(self, undef_enabled=True):\n super(NetworkLatencyTest, self).__init__()\n self._type = (\"NetworkLatencyTest\", True)\n self._loss = (self.__undef__, True)\n self._parameters = (self.__undef__, True)\n self._average = (self.__undef__, True)\n self._maximum = (self.__undef__, True)\n self._minimum = (self.__undef__, True)\n self._stddev = (self.__undef__, True)\n\n API_VERSION = \"1.9.0\"\n\n @classmethod\n def from_dict(cls, data, dirty=False, undef_enabled=True):\n obj = super(NetworkLatencyTest, cls).from_dict(data, dirty, undef_enabled)\n obj._loss = (data.get(\"loss\", obj.__undef__), dirty)\n if obj._loss[0] is not None and obj._loss[0] is not obj.__undef__:\n assert isinstance(obj._loss[0], int), (\"Expected one of [u'integer'], but got %s\" % type(obj._loss[0]))\n common.validate_format(obj._loss[0], \"None\", None, None)\n if \"parameters\" in data and data[\"parameters\"] is not None:\n obj._parameters = (factory.create_object(data[\"parameters\"], \"NetworkLatencyTestParameters\"), dirty)\n factory.validate_type(obj._parameters[0], \"NetworkLatencyTestParameters\")\n else:\n obj._parameters = (obj.__undef__, dirty)\n obj._average = (data.get(\"average\", obj.__undef__), dirty)\n if obj._average[0] is not None and obj._average[0] is not obj.__undef__:\n assert isinstance(obj._average[0], int), (\"Expected one of [u'integer'], but got %s\" % type(obj._average[0]))\n common.validate_format(obj._average[0], \"None\", None, None)\n obj._maximum = (data.get(\"maximum\", obj.__undef__), dirty)\n if obj._maximum[0] is not None and obj._maximum[0] is not obj.__undef__:\n assert isinstance(obj._maximum[0], int), (\"Expected one of [u'integer'], but got %s\" % type(obj._maximum[0]))\n common.validate_format(obj._maximum[0], \"None\", None, None)\n obj._minimum = (data.get(\"minimum\", obj.__undef__), dirty)\n if obj._minimum[0] is not None and obj._minimum[0] is not obj.__undef__:\n assert isinstance(obj._minimum[0], int), (\"Expected one of [u'integer'], but got %s\" % type(obj._minimum[0]))\n common.validate_format(obj._minimum[0], \"None\", None, None)\n obj._stddev = (data.get(\"stddev\", obj.__undef__), dirty)\n if obj._stddev[0] is not None and obj._stddev[0] is not obj.__undef__:\n assert isinstance(obj._stddev[0], int), (\"Expected one of [u'integer'], but got %s\" % type(obj._stddev[0]))\n common.validate_format(obj._stddev[0], \"None\", None, None)\n return obj\n\n def to_dict(self, dirty=False):\n dct = super(NetworkLatencyTest, self).to_dict(dirty)\n\n def dictify(obj):\n if isinstance(obj, list):\n return [dictify(o) for o in obj]\n elif hasattr(obj, \"to_dict\"):\n return obj.to_dict()\n else:\n return obj\n if \"loss\" == \"type\" or (self.loss is not self.__undef__ and not (dirty and not self._loss[1])):\n dct[\"loss\"] = dictify(self.loss)\n if \"parameters\" == \"type\" or (self.parameters is not self.__undef__ and not (dirty and not self._parameters[1])):\n dct[\"parameters\"] = dictify(self.parameters)\n if \"average\" == \"type\" or (self.average is not self.__undef__ and not (dirty and not self._average[1])):\n dct[\"average\"] = dictify(self.average)\n if \"maximum\" == \"type\" or (self.maximum is not self.__undef__ and not (dirty and not self._maximum[1])):\n dct[\"maximum\"] = dictify(self.maximum)\n if \"minimum\" == \"type\" or (self.minimum is not self.__undef__ and not (dirty and not self._minimum[1])):\n dct[\"minimum\"] = dictify(self.minimum)\n if \"stddev\" == \"type\" or (self.stddev is not self.__undef__ and not (dirty and not self._stddev[1])):\n dct[\"stddev\"] = dictify(self.stddev)\n return dct\n\n def dirty(self):\n return self.from_dict(self.to_dict(dirty=False), dirty=True)\n\n def force_dirty(self):\n self._loss = (self._loss[0], True)\n self._parameters = (self._parameters[0], True)\n self._average = (self._average[0], True)\n self._maximum = (self._maximum[0], True)\n self._minimum = (self._minimum[0], True)\n self._stddev = (self._stddev[0], True)\n\n def is_dirty(self):\n return any([self._loss[1], self._parameters[1], self._average[1], self._maximum[1], self._minimum[1], self._stddev[1]])\n\n def __eq__(self, other):\n if other is None:\n return False\n if not isinstance(other, NetworkLatencyTest):\n return False\n return super(NetworkLatencyTest, self).__eq__(other) and \\\n self.loss == other.loss and \\\n self.parameters == other.parameters and \\\n self.average == other.average and \\\n self.maximum == other.maximum and \\\n self.minimum == other.minimum and \\\n self.stddev == other.stddev\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n def __repr__(self):\n return common.generate_repr_string(self)\n\n @property\n def loss(self):\n \"\"\"\n Percentage of requests or replies lost.\n\n :rtype: ``int``\n \"\"\"\n return self._loss[0]\n\n @loss.setter\n def loss(self, value):\n self._loss = (value, True)\n\n @property\n def parameters(self):\n \"\"\"\n The parameters used to execute the test.\n\n :rtype: :py:class:`v1_9_0.web.vo.NetworkLatencyTestParameters`\n \"\"\"\n return self._parameters[0]\n\n @parameters.setter\n def parameters(self, value):\n self._parameters = (value, True)\n\n @property\n def average(self):\n \"\"\"\n Average measured round-trip time (usec).\n\n :rtype: ``int``\n \"\"\"\n return self._average[0]\n\n @average.setter\n def average(self, value):\n self._average = (value, True)\n\n @property\n def maximum(self):\n \"\"\"\n Maximum measured round-trip time (usec).\n\n :rtype: ``int``\n \"\"\"\n return self._maximum[0]\n\n @maximum.setter\n def maximum(self, value):\n self._maximum = (value, True)\n\n @property\n def minimum(self):\n \"\"\"\n Minimum measured round-trip time (usec).\n\n :rtype: ``int``\n \"\"\"\n return self._minimum[0]\n\n @minimum.setter\n def minimum(self, value):\n self._minimum = (value, True)\n\n @property\n def stddev(self):\n \"\"\"\n Standard deviation (usec).\n\n :rtype: ``int``\n \"\"\"\n return self._stddev[0]\n\n @stddev.setter\n def stddev(self, value):\n self._stddev = (value, True)\n\n","sub_path":"src/main/resources/delphixpy/v1_9_0/web/vo/NetworkLatencyTest.py","file_name":"NetworkLatencyTest.py","file_ext":"py","file_size_in_byte":7889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"149035603","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# Copyright: (c) 2018, Mikhail Yohman (@FragmentedPacket) \n# Copyright: (c) 2018, David Gomez (@amb1s1) \n# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\n\nfrom __future__ import absolute_import, division, print_function\n__metaclass__ = type\n\nANSIBLE_METADATA = {'metadata_version': '1.1',\n 'status': ['preview'],\n 'supported_by': 'community'}\n\nDOCUMENTATION = r'''\n---\nmodule: netbox_device\nshort_description: Create, update or delete devices within Netbox\ndescription:\n - Creates, updates or removes devices from Netbox\nnotes:\n - Tags should be defined as a YAML list\n - This should be ran with connection C(local) and hosts C(localhost)\nauthor:\n - Mikhail Yohman (@FragmentedPacket)\n - David Gomez (@amb1s1)\nrequirements:\n - pynetbox\nversion_added: '2.8'\noptions:\n netbox_url:\n description:\n - URL of the Netbox instance resolvable by Ansible control host\n required: true\n netbox_token:\n description:\n - The token created within Netbox to authorize API access\n required: true\n data:\n description:\n - Defines the device configuration\n suboptions:\n name:\n description:\n - The name of the device\n required: true\n device_type:\n description:\n - Required if I(state=present) and the device does not exist yet\n device_role:\n description:\n - Required if I(state=present) and the device does not exist yet\n tenant:\n description:\n - The tenant that the device will be assigned to\n platform:\n description:\n - The platform of the device\n serial:\n description:\n - Serial number of the device\n asset_tag:\n description:\n - Asset tag that is associated to the device\n site:\n description:\n - Required if I(state=present) and the device does not exist yet\n rack:\n description:\n - The name of the rack to assign the device to\n position:\n description:\n - The position of the device in the rack defined above\n face:\n description:\n - Required if I(rack) is defined\n status:\n description:\n - The status of the device\n choices:\n - Active\n - Offline\n - Planned\n - Staged\n - Failed\n - Inventory\n cluster:\n description:\n - Cluster that the device will be assigned to\n comments:\n description:\n - Comments that may include additional information in regards to the device\n tags:\n description:\n - Any tags that the device may need to be associated with\n custom_fields:\n description:\n - must exist in Netbox\n required: true\n state:\n description:\n - Use C(present) or C(absent) for adding or removing.\n choices: [ absent, present ]\n default: present\n validate_certs:\n description:\n - If C(no), SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates.\n default: 'yes'\n type: bool\n'''\n\nEXAMPLES = r'''\n- name: \"Test Netbox modules\"\n connection: local\n hosts: localhost\n gather_facts: False\n\n tasks:\n - name: Create device within Netbox with only required information\n netbox_device:\n netbox_url: http://netbox.local\n netbox_token: thisIsMyToken\n data:\n name: Test Device\n device_type: C9410R\n device_role: Core Switch\n site: Main\n state: present\n\n - name: Delete device within netbox\n netbox_device:\n netbox_url: http://netbox.local\n netbox_token: thisIsMyToken\n data:\n name: Test Device\n state: absent\n\n - name: Create device with tags\n netbox_device:\n netbox_url: http://netbox.local\n netbox_token: thisIsMyToken\n data:\n name: Another Test Device\n device_type: C9410R\n device_role: Core Switch\n site: Main\n tags:\n - Schnozzberry\n state: present\n\n - name: Update the rack and position of an existing device\n netbox_device:\n netbox_url: http://netbox.local\n netbox_token: thisIsMyToken\n data:\n name: Test Device\n rack: Test Rack\n position: 10\n face: Front\n state: present\n'''\n\nRETURN = r'''\ndevice:\n description: Serialized object as created or already existent within Netbox\n returned: success (when I(state=present))\n type: dict\nmsg:\n description: Message indicating failure or info about what has been achieved\n returned: always\n type: str\n'''\n\nimport json\nimport traceback\n\nfrom ansible.module_utils.basic import AnsibleModule, missing_required_lib\nfrom ansible.module_utils.net_tools.netbox.netbox_utils import (\n find_ids,\n normalize_data,\n create_netbox_object,\n delete_netbox_object,\n update_netbox_object,\n DEVICE_STATUS,\n FACE_ID\n)\n\nPYNETBOX_IMP_ERR = None\ntry:\n import pynetbox\n HAS_PYNETBOX = True\nexcept ImportError:\n PYNETBOX_IMP_ERR = traceback.format_exc()\n HAS_PYNETBOX = False\n\n\ndef main():\n '''\n Main entry point for module execution\n '''\n argument_spec = dict(\n netbox_url=dict(type=\"str\", required=True),\n netbox_token=dict(type=\"str\", required=True, no_log=True),\n data=dict(type=\"dict\", required=True),\n state=dict(required=False, default='present', choices=['present', 'absent']),\n validate_certs=dict(type=\"bool\", default=True)\n )\n\n global module\n module = AnsibleModule(argument_spec=argument_spec,\n supports_check_mode=True)\n\n # Fail module if pynetbox is not installed\n if not HAS_PYNETBOX:\n module.fail_json(msg=missing_required_lib('pynetbox'), exception=PYNETBOX_IMP_ERR)\n\n # Fail if device name is not given\n if not module.params[\"data\"].get(\"name\"):\n module.fail_json(msg=\"missing device name\")\n\n # Assign variables to be used with module\n app = 'dcim'\n endpoint = 'devices'\n url = module.params[\"netbox_url\"]\n token = module.params[\"netbox_token\"]\n data = module.params[\"data\"]\n state = module.params[\"state\"]\n validate_certs = module.params[\"validate_certs\"]\n\n # Attempt to create Netbox API object\n try:\n nb = pynetbox.api(url, token=token, ssl_verify=validate_certs)\n except Exception:\n module.fail_json(msg=\"Failed to establish connection to Netbox API\")\n try:\n nb_app = getattr(nb, app)\n except AttributeError:\n module.fail_json(msg=\"Incorrect application specified: %s\" % (app))\n\n nb_endpoint = getattr(nb_app, endpoint)\n norm_data = normalize_data(data)\n try:\n if 'present' in state:\n result = ensure_device_present(nb, nb_endpoint, norm_data)\n else:\n result = ensure_device_absent(nb_endpoint, norm_data)\n return module.exit_json(**result)\n except pynetbox.RequestError as e:\n return module.fail_json(msg=json.loads(e.error))\n except ValueError as e:\n return module.fail_json(msg=str(e))\n\n\ndef _find_ids(nb, data):\n if data.get(\"status\"):\n data[\"status\"] = DEVICE_STATUS.get(data[\"status\"].lower())\n if data.get(\"face\"):\n data[\"face\"] = FACE_ID.get(data[\"face\"].lower())\n return find_ids(nb, data)\n\n\ndef ensure_device_present(nb, nb_endpoint, normalized_data):\n '''\n :returns dict(device, msg, changed, diff): dictionary resulting of the request,\n where `device` is the serialized device fetched or newly created in\n Netbox\n '''\n data = _find_ids(nb, normalized_data)\n nb_device = nb_endpoint.get(name=data[\"name\"])\n result = {}\n if not nb_device:\n device, diff = create_netbox_object(nb_endpoint, data, module.check_mode)\n msg = \"Device %s created\" % (data[\"name\"])\n changed = True\n result[\"diff\"] = diff\n else:\n device, diff = update_netbox_object(nb_device, data, module.check_mode)\n if device is False:\n module.fail_json(\n msg=\"Request failed, couldn't update device: %s\" % data[\"name\"]\n )\n if diff:\n msg = \"Device %s updated\" % (data[\"name\"])\n changed = True\n result[\"diff\"] = diff\n else:\n msg = \"Device %s already exists\" % (data[\"name\"])\n changed = False\n result.update({\"device\": device, \"changed\": changed, \"msg\": msg})\n return result\n\n\ndef ensure_device_absent(nb_endpoint, data):\n '''\n :returns dict(msg, changed, diff)\n '''\n nb_device = nb_endpoint.get(name=data[\"name\"])\n result = {}\n if nb_device:\n dummy, diff = delete_netbox_object(nb_device, module.check_mode)\n msg = 'Device %s deleted' % (data[\"name\"])\n changed = True\n result[\"diff\"] = diff\n else:\n msg = 'Device %s already absent' % (data[\"name\"])\n changed = False\n\n result.update({\"changed\": changed, \"msg\": msg})\n return result\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"env/lib/python3.9/site-packages/ansible/modules/net_tools/netbox/netbox_device.py","file_name":"netbox_device.py","file_ext":"py","file_size_in_byte":9236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"443940202","text":"import urllib.request\nimport re\n\nurl = \"http://shakespeare.mit.edu/hamlet/hamlet.1.4.html\"\nencoding = \"utf-8\"\nproxy = {\"http\": \"http://prxy.ex.media.osaka-cu.ac.jp:10080\",\n \"https\": \"http://prxy.ex.media.osaka-cu.ac.jp:10080\"}\nalphabet = {}\n\n\ndef count(key):\n if key in alphabet:\n alphabet[key] += 1\n else:\n alphabet[key] = 1\n\n\nwith urllib.request.FancyURLopener(proxy).open(url) as page:\n for raw_line in page:\n line = raw_line.decode(encoding)\n match = re.search(r\".*\", line)\n if match:\n fixed_line_first = re.sub(r\".*\", \"\", line)\n fixed_line_second = re.sub(r\".*\", \"\", fixed_line_first)\n fixed_line = fixed_line_second.replace(\"-\", \" \")\n words = fixed_line.lower().split()\n for word in words:\n if word[0] == word[len(word)-1]:\n count(word[0])\n\nfor letter in sorted(alphabet):\n print(f\"{letter}: {alphabet[letter]}\")\n","sub_path":"11/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"424719330","text":"#!/usr/local/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n\npython_report_hourly_app_king3_OrgId.py 跑单独机构加强版本3 再次优化小时报表 封装了小时报表对象类以及将取自动递增流水方法提取到工具db_utils文件中,集成监听所有的print到log日志的封装类\n指定单机构-小时报表-计算写入数���库oracle的报表脚本\n版本说明:1:跑所有机构的小时报表;2:逻辑变更-【周期内工况使用量(本期期末数-上期期末数)】【周期内标况使用量(本期期末数-上期期末数)】 3:整体脚本代码结构变更\nVersion: 1.0\nAuthor: LC\nDateTime: 2019年5月10日09:48:17\nUpdateTime: 2020年4月9日14:08:36\n一加壹博客最Top-一起共创1+1>2的力量!~LC\nLC博客url: http://oneplusone.top/index.html\nLC博客url: http://oneplusone.vip/index.html\n一加壹.SNS LC - 又一个SNS社区: http://sns.oneplusone.vip\n赞助一加壹博客最Top-LC万能收款码支持-支付宝、微信、QQ\nhttp://lc.oneplusone.vip/donateMeByLC.html\n\n\"\"\"\nimport time\nimport datetime\nimport calendar\nimport os\nimport sys\nimport cx_Oracle\nimport operator\nfrom python_report_hourly_model import ReportHourlyModel # 导入小时报表对象类\nfrom db_utils import get_sys_serial_no # 导入获取流水号方法\nfrom print_msg_to_log_model import PrintLogger\n\n# 改变系统环境编码为简体中文utf-8-为了让oracle查询出的中文不乱码\nos.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'\n\n\n# 定义类 MyOracle\nclass MyOracle:\n SHOW_SQL = True\n\n def __init__(self, host='192.168.0.7', port=1521, user='SCOTT', password='Lmt123456',\n sid='LMTPlat'): # 注意###里改为自己所需要的ip\n self.host = host\n self.port = port\n self.user = user\n self.password = password\n self.sid = sid\n\n # 连接数据库\n def get_con(self):\n try:\n dsn_tns = cx_Oracle.makedsn(self.host, self.port, self.sid)\n # 如果是Oracle 12c 数据库需要替换sid 为service_name\n dsn_tns = dsn_tns.replace('SID', 'SERVICE_NAME')\n conn = cx_Oracle.connect(self.user, self.password, dsn_tns)\n return conn\n except Exception as e:\n print(\"Exception Error:%s\" % e)\n finally:\n pass\n\n # 查询所有\n def select_all(self, sql):\n try:\n con = self.get_con()\n # print con\n cur = con.cursor()\n cur.execute(sql)\n fc = cur.fetchall()\n return fc\n except Exception as e:\n print(\"Exception Error:%s\" % e)\n finally:\n cur.close()\n con.close()\n\n # 自定义查询 一个参数可用\n def select_by_where(self, sql, data):\n try:\n con = self.get_con()\n # print(con)\n d = (data,)\n cur = con.cursor()\n cur.execute(sql, d)\n fc = cur.fetchall()\n # if len(fc) > 0:\n # for e in range(len(fc)):\n # print(fc[e])\n return fc\n except Exception as e:\n print(\"Exception Error:%s\" % e)\n finally:\n cur.close()\n con.close()\n\n # 自定义查询 带多个参数\n def select_by_where_many_params(self, sql, params):\n try:\n con = self.get_con()\n # print(con)\n for d in params:\n cur = con.cursor()\n cur.execute(sql, d)\n fc = cur.fetchall()\n pass\n return fc\n except Exception as e:\n print(\"Exception Error:%s\" % e)\n finally:\n cur.close()\n con.close()\n\n # 自定义查询 带多个参数 返回字典样式列表\n def select_by_where_many_params_dict(self, sql, params):\n try:\n con = self.get_con()\n # print(con)\n for d in params:\n cur = con.cursor()\n cur.execute(sql, d)\n cur.rowfactory = self.makedict(cur)\n fc = cur.fetchall()\n return fc\n except Exception as e:\n print(\"Exception Error:%s\" % e)\n finally:\n cur.close()\n con.close()\n\n # 带参数 执行自定义sql语句\n def dml_by_where(self, sql, params):\n try:\n con = self.get_con()\n cur = con.cursor()\n\n for d in params:\n if self.SHOW_SQL:\n print('执行sql:[{}],参数:[{}]'.format(sql, d))\n cur.execute(sql, d)\n\n con.commit()\n\n except Exception as e:\n con.rollback()\n print(\"Exception Error:%s\" % e)\n finally:\n cur.close()\n con.close()\n\n # 不带参数的更新方法\n def dml_nowhere(self, sql):\n try:\n con = self.get_con()\n cur = con.cursor()\n count = cur.execute(sql)\n con.commit()\n return count\n except Exception as e:\n con.rollback()\n print(\"Exception Error:%s\" % e)\n finally:\n cur.close()\n con.close()\n\n # 数据库查询返回字典\n def makedict(self, cursor):\n cols = [d[0] for d in cursor.description]\n\n def createrow(*args):\n return dict(zip(cols, args))\n\n return createrow\n\n\n# 公共方法\n\n\n# 获取间隔n天时间的最小时间(0点)和最大时间(23点59分59秒)-datetime.timedelta(days=1)可以处理天,datetime.timedelta(weeks=1)也可以处理周等\n# @param n,types,isFormat; n代表几天,可以正值(n天后),可以负值(n天前),0代表今天 ;\n# types取值有max和min,max代表输出当前时间最大时间,min代表输出当前时间最小时间;\n# isFormat是否格式化输出,布尔值为True,格式化输出str类型时间,为False,不格式化输出,直接返回datetime类型时间。\n# @return 符合要求的datetime格式日期\n# 使用示例:\n# print(to_n_datetime_max_min_time(2,\"max\", False))-2019-03-09 23:59:59.999999\n# print(to_n_datetime_max_min_time(0,\"min\", False))-2019-03-07 00:00:00\n# print(to_n_datetime_max_min_time(-1,\"min\", False))-2019-03-06 00:00:00\n# print(to_n_datetime_max_min_time(-5, \"max\", True))-2019-03-02 23:59:59\ndef to_n_datetime_max_min_time(n, types, is_format):\n if types == \"max\":\n return_time = datetime.datetime.combine(datetime.date.today() + datetime.timedelta(days=n), datetime.time.max)\n elif types == \"min\":\n return_time = datetime.datetime.combine(datetime.date.today() + datetime.timedelta(days=n), datetime.time.min)\n if (is_format):\n return_time = return_time.strftime('%Y-%m-%d %H:%M:%S')\n return return_time\n\n\n# 获取间隔n个小时时间的最小时间(0点)和最大时间(23点59分59秒)-datetime.timedelta(days=1)可以处理天,datetime.timedelta(weeks=1)也可以处理周等\n# @param n,h,types,isFormat; n代表几天,可以正值(n天后),可以负值(n天前),0代表今天 ;\n# h代表几小时,可以正值(h小时后),可以负值(h小时前),0代表当前小时 ;\n# types取值有max和min,max代表输出当前时间最大时间,min代表输出当前时间最小时间;\n# isFormat是否格式化输出,布尔值为True,格式化输出str类型时间,为False,不格式化输出,直接返回datetime类型时间。\n# @return 符合要求的datetime格式日期\n# 使用示例:\ndef to_get_hour_first_last_minutes_datetime_max_min_time(n, h, types, is_format):\n if types == \"max\":\n return_time = datetime.datetime.combine(datetime.date.today() + datetime.timedelta(days=n), datetime.time.max) + datetime.timedelta(hours=h)\n elif types == \"min\":\n return_time = datetime.datetime.combine(datetime.date.today() + datetime.timedelta(days=n), datetime.time.min)\n if (is_format):\n return_time = return_time.strftime('%Y-%m-%d %H:%M:%S')\n return return_time\n\n\n# 获取间隔n个小时时间的最小时间(0点)和最大时间(23点59分59秒)-datetime.timedelta(days=1)可以处理天,datetime.timedelta(weeks=1)也可以处理周等\n# @param n,h,types,isFormat; n代表几天,可以正值(n天后),可以负值(n天前),0代表今天 ;\n# h代表几小时,可以正值(h小时后),可以负值(h小时前),0代表当前小时 ;\n# types取值有max和min,max代表输出当前时间+1h的最小时间,min代表输出当前时间最小时间;\n# isFormat是否格式化输出,布尔值为True,格式化输出str类型时间,为False,不格式化输出,直接返回datetime类型时间。\n# @return 符合要求的datetime格式日期\n# 使用示例:\ndef to_get_hour_first_last_minutes_datetime_max_min_time_ver_2(n, h, types, is_format):\n if types == \"max\":\n return_time = datetime.datetime.combine(datetime.date.today() + datetime.timedelta(days=n), datetime.time.min) + datetime.timedelta(hours=h+24)\n elif types == \"min\":\n return_time = datetime.datetime.combine(datetime.date.today() + datetime.timedelta(days=n), datetime.time.min)\n if (is_format):\n return_time = return_time.strftime('%Y-%m-%d %H:%M:%S')\n return return_time\n\n\n# 获取间隔n个小时时间的最小时间(0点)和最大时间(23点59分59秒)-datetime.timedelta(days=1)可以处理天,datetime.timedelta(weeks=1)也可以处理周等 凌晨1点数据计算专属方法\n# @param n,h,types,isFormat; n代表几天,可以正值(n天后),可以负值(n天前),0代表今天 ;\n# h代表几小时,可以正值(h小时后),可以负值(h小时前),0代表当前小时 ;\n# types取值有max和min,max代表输出当前时间最大时间,min代表输出当前时间最小时间;\n# isFormat是否格式化输出,布尔值为True,格式化输出str类型时间,为False,不格式化输出,直接返回datetime类型时间。\n# @return 符合要求的datetime格式日期\n# 使用示例:\ndef to_get_hour_first_last_minutes_datetime_max_min_time2(n, h, types, is_format):\n if types == \"max\":\n return_time = datetime.datetime.combine(datetime.date.today() + datetime.timedelta(days=n), datetime.time.max) + datetime.timedelta(hours=h)\n elif types == \"min\":\n return_time = datetime.datetime.combine(datetime.date.today() + datetime.timedelta(days=n), datetime.time.min)\n elif types == \"min2\":\n return_time = datetime.datetime.combine(datetime.date.today() + datetime.timedelta(days=n), datetime.time.min) + datetime.timedelta(hours=h)\n if (is_format):\n return_time = return_time.strftime('%Y-%m-%d %H:%M:%S')\n return return_time\n\n\n# 从oracle数据库SCADA_FLMETER_DATA读取所有符合条件的数据\n# 带参数查询\n# @param org_id 要查询机构号\n# @param days 0代表今天 +n代表n天后 -n代表n天前\n# @return 处理结果 True成功 False失败\ndef select_sfd_by_where(org_id, days):\n sql = \"select * from SCADA_FLMETER_DATA where SFD_ORG_ID= :orgid and INSTANT_TIME between :minTime AND :maxTime \"\n yesterday_min = to_n_datetime_max_min_time(days, \"min\", False)\n yesterday_max = to_n_datetime_max_min_time(days, \"max\", False)\n data = [{\"orgid\": org_id, \"minTime\": yesterday_min, \"maxTime\": yesterday_max}]\n fc = db.select_by_where_many_params_dict(sql, data)\n print(\"总共抄表数据:\", len(fc))\n # for row in fc:\n # print(row)\n return fc, data\n\n\n# 从oracle数据库SCADA_FLMETER_DATA读取所有符合条件的数据\n# 带参数查询\n# @param org_id 要查询机构号\n# @param days 天数 代表几天,可以正值(n天后),可以负值(n天前),0代表今天\n# @param hours 0代表当前小时 +n代表n小时后 -n代表n小时前\n# @return 处理结果 True成功 False失败\ndef select_sfd_by_where_for_hourly(org_id, days, hours):\n sql = \"select * from SCADA_FLMETER_DATA where SFD_ORG_ID= :orgid and INSTANT_TIME between :minTime AND :maxTime \"\n yesterday_min = to_get_hour_first_last_minutes_datetime_max_min_time(days, hours, \"min\", False)\n yesterday_max = to_get_hour_first_last_minutes_datetime_max_min_time(days, hours, \"max\", False)\n data = [{\"orgid\": org_id, \"minTime\": yesterday_min, \"maxTime\": yesterday_max}]\n fc = db.select_by_where_many_params_dict(sql, data)\n print(\"总共抄表数据:\", len(fc))\n # for row in fc:\n # print(row)\n return fc, data\n\n\n# 从oracle数据库SCADA_FLMETER_DATA读取所有符合条件的数据\n# 带参数查询\n# @param org_id 要查询机构号\n# @param days 天数 代表几天,可以正值(n天后),可以负值(n天前),0代表今天\n# @param hours 0代表当前小时 +n代表n小时后 -n代表n小时前\n# @return 处理结果 True成功 False失败\ndef select_sfd_by_where_for_hourly_ver_2(org_id, days, hours):\n sql = \"select * from SCADA_FLMETER_DATA where SFD_ORG_ID= :orgid and INSTANT_TIME between :minTime AND :maxTime \"\n yesterday_min = to_get_hour_first_last_minutes_datetime_max_min_time_ver_2(days, hours, \"min\", False)\n yesterday_max = to_get_hour_first_last_minutes_datetime_max_min_time_ver_2(days, hours, \"max\", False)\n data = [{\"orgid\": org_id, \"minTime\": yesterday_min, \"maxTime\": yesterday_max}]\n fc = db.select_by_where_many_params_dict(sql, data)\n print(\"总共抄表数据:\", len(fc))\n # for row in fc:\n # print(row)\n return fc, data\n\n\n# 从oracle数据库SCADA_FLMETER_DATA读取所有符合条件的数据\n# 带参数查询\n# @param org_id 要查询机构号\n# @param days 天数 代表几天,可以正值(n天后),可以负值(n天前),0代表今天\n# @param hours 0代表当前小时 +n代表n小时后 -n代表n小时前\n# @return 处理结果 True成功 False失败\ndef select_sfd_by_where_for_hourly_ver_2_pro(org_id, days, hours):\n sql = \"select * from SCADA_FLMETER_DATA where SFD_ORG_ID= :orgid and INSTANT_TIME between :minTime AND :maxTime \"\n yesterday_min = to_get_hour_first_last_minutes_datetime_max_min_time_ver_2(days, hours - 1, \"max\", False)\n yesterday_max = to_get_hour_first_last_minutes_datetime_max_min_time_ver_2(days, hours, \"max\", False)\n data = [{\"orgid\": org_id, \"minTime\": yesterday_min, \"maxTime\": yesterday_max}]\n fc = db.select_by_where_many_params_dict(sql, data)\n print(\"总共抄表数据:\", len(fc))\n # for row in fc:\n # print(row)\n return fc, data\n\n\n# 从oracle数据库SCADA_FLMETER_DATA读取所有符合条件的数据 凌晨1点数据计算专属方法\n# 带参数查询\n# @param org_id 要查询机构号\n# @param days 天数 代表几天,可以正值(n天后),可以负值(n天前),0代表今天\n# @param hours 0代表当前小时 +n代表n小时后 -n代表n小时前\n# @return 处理结果 True成功 False失败\ndef select_sfd_by_where_for_hourly2(org_id, days, hours):\n sql = \"select * from SCADA_FLMETER_DATA where SFD_ORG_ID= :orgid and INSTANT_TIME between :minTime AND :maxTime \"\n yesterday_min_max = to_get_hour_first_last_minutes_datetime_max_min_time2(days, hours, \"min\", False)\n yesterday_max_min = to_get_hour_first_last_minutes_datetime_max_min_time2(days, hours+23, \"min2\", False)\n data = [{\"orgid\": org_id, \"minTime\": yesterday_max_min, \"maxTime\": yesterday_min_max}]\n fc = db.select_by_where_many_params_dict(sql, data)\n print(\"总共抄表数据:\", len(fc))\n # for row in fc:\n # print(row)\n return fc, data\n\n\n# 处理好数据写入oracle\n# @param 日报表对象report_daily_model-主键【srd_org_id 机构号,srd_id 记录ID 】其他字段\n# @return 处理结果 True成功 False失败\ndef ok_processing_data_insert_into_oracle(report_daily_model, *args, **kwargs):\n print(report_daily_model.flmeter_no)\n fc = select_scada_report_daily_is_null_or_not(report_daily_model.srd_org_id, report_daily_model.flmeter_no,report_daily_model.year,report_daily_model.month, report_daily_model.day)\n print(\"总列表长度:\", len(fc))\n if len(fc) == 0: # 如果为0 代表无数据 先生成一条\n insert_scada_report_daily(report_daily_model)\n pass\n else: # 如果不为0 则根据SRD_ORG_ID,SRD_ID直接删除此条数据 再新增一条\n ok_srd_id = fc[0]['SRD_ID']\n del_scada_report_daily(report_daily_model.srd_org_id, ok_srd_id)\n insert_scada_report_daily(report_daily_model)\n pass\n # print(args) # (1, 2, 3, '123')\n # print(kwargs)\n print(report_daily_model.flmeter_no+\"处理好数据已写入oracle\")\n pass\n return True\n\n\n# 处理好数据写入oracle for 小时报表\n# @param 小时报表对象report_hourly_model-主键【srh_org_id 机构号, srh_id 记录ID 】其他字段\n# @return 处理结果 True成功 False失败\ndef ok_processing_data_insert_into_oracle_for_hourly(report_hourly_model, *args, **kwargs):\n print(report_hourly_model.flmeter_no)\n fc = select_scada_report_hourly_is_null_or_not(report_hourly_model.srh_org_id, report_hourly_model.flmeter_no, report_hourly_model.year, report_hourly_model.month, report_hourly_model.day, report_hourly_model.hour)\n print(\"总列表长度:\", len(fc))\n if len(fc) == 0: # 如果为0 代表无数据 先生成一条\n insert_scada_report_hourly(report_hourly_model)\n pass\n else: # 如果不为0 则根据SRD_ORG_ID,SRD_ID直接删除此条数据 再新增一条\n ok_srh_id = fc[0]['SRH_ID']\n del_scada_report_hourly(report_hourly_model.srh_org_id, ok_srh_id)\n insert_scada_report_hourly(report_hourly_model)\n pass\n # print(args) # (1, 2, 3, '123')\n # print(kwargs)\n print(report_hourly_model.flmeter_no+\"处理好数据已写入oracle\")\n pass\n return True\n\n\n# 查询SCADA_REPORT_DAILY表中 此当前年月日数据 是否存在 不存在 新增 存在的话 删除 再新增\n# @param srd_org_id 机构号\n# @param flmeter_no 流量计编号\n# @param year 年\n# @param month 月\n# @param day 日\n# @return 返回查询出的数据list\ndef select_scada_report_daily_is_null_or_not(srd_org_id, flmeter_no, year, month, day):\n sql = \"select * from SCADA_REPORT_DAILY where SRD_ORG_ID= :srd_org_id and FLMETER_NO= :flmeter_no and YEAR = :year and MONTH = :month and DAY = :day\"\n data = [{\"srd_org_id\": srd_org_id, \"flmeter_no\": flmeter_no, \"year\": year, \"month\": month, \"day\": day}]\n fc = db.select_by_where_many_params_dict(sql, data)\n return fc\n\n\n# 查询SCADA_REPORT_HOURLY表中 此当前年月日数据 是否存在 不存在 新增 存在的话 删除 再新增\n# @param srh_org_id 机构号\n# @param flmeter_no 流量计编号\n# @param year 年\n# @param month 月\n# @param day 日\n# @param hour 小时\n# @return 返回查询出的数据list\ndef select_scada_report_hourly_is_null_or_not(srh_org_id, flmeter_no, year, month, day, hour):\n sql = \"select * from SCADA_REPORT_HOURLY where SRH_ORG_ID= :srh_org_id and FLMETER_NO= :flmeter_no and YEAR = :year and MONTH = :month and DAY = :day and HOUR = :hour\"\n data = [{\"srh_org_id\": srh_org_id, \"flmeter_no\": flmeter_no, \"year\": year, \"month\": month, \"day\": day, \"hour\": hour}]\n fc = db.select_by_where_many_params_dict(sql, data)\n return fc\n\n\n# 新增SCADA_REPORT_DAILY\n# @param report_daily_model 日报表对象类\n# @return null 插入成功或失败\ndef insert_scada_report_daily(report_daily_model):\n insert_sql = \"INSERT INTO SCADA_REPORT_DAILY (SRD_ORG_ID,SRD_ID, RTU_NO,FLMETER_NO,CUSTOMER_NO,\" \\\n \"REPORT_TIME,YEAR,MONTH,DAY, HOUR,\" \\\n \"STD_SUM,WORK_SUM,STD_FLOW,WORK_FLOW,TEMPERATURE,\" \\\n \"PRESSURE,PRICE,USE_VOLUME_WORK, USE_VOLUME_STD,USE_MONEY,\" \\\n \"SUM_TOTAL_VOLUME,SUM_TOTAL_MONEY,TOTAL_BUY_VOLUME,TOTAL_BUY_MONEY,REMAIN_MONEY,\" \\\n \"REMAIN_VOLUME,FM_STATE,FM_STATE_MSG,RTU_STATE,RTU_STATE_MSG,VALVE_STATE,VALVE_STATE_MSG,POWER_VOLTAGE,\" \\\n \"BATTERY_VOLTAGE,BATTERY_LEVEL,PRESS_IN,PRESS_OUT,TEMP_IN,\" \\\n \"TEMP_OUT,RSSI, SRD_STATUS ) \" \\\n \"VALUES\" \\\n \"(:srd_org_id,:srd_id, :rtu_no,:flmeter_no,:customer_no,\" \\\n \":report_time,:year,:month,:day, :hour,\" \\\n \":std_sum,:work_sum,:std_flow,:work_flow,:temperature,\" \\\n \":pressure,:price,:use_volume_work, :use_volume_std,:use_money,\" \\\n \":sum_total_volume,:sum_total_money,:total_buy_volume,:total_buy_money,:remain_money,\" \\\n \":remain_volume,:fm_state,:fm_state_msg,:rtu_state,:rtu_state_msg,:valve_state,:valve_state_msg,:power_voltage,\" \\\n \":battery_voltage,:battery_level,:press_in,:press_out,:temp_in,\" \\\n \":temp_out,:rssi, :srd_status)\"\n data = [{\"srd_org_id\": report_daily_model.srd_org_id, \"srd_id\": report_daily_model.srd_id, \"rtu_no\": report_daily_model.rtu_no, \"flmeter_no\": report_daily_model.flmeter_no,\"customer_no\": report_daily_model.customer_no,\n \"report_time\": report_daily_model.report_time, \"year\": report_daily_model.year, \"month\": report_daily_model.month, \"day\": report_daily_model.day, \"hour\": report_daily_model.hour,\n \"std_sum\": report_daily_model.std_sum, \"work_sum\": report_daily_model.work_sum, \"std_flow\": report_daily_model.std_flow, \"work_flow\": report_daily_model.work_flow, \"temperature\": report_daily_model.temperature,\n \"pressure\": report_daily_model.pressure, \"price\": report_daily_model.price, \"use_volume_work\": report_daily_model.use_volume_work, \"use_volume_std\": report_daily_model.use_volume_std, \"use_money\": report_daily_model.use_money,\n \"sum_total_volume\": report_daily_model.sum_total_volume, \"sum_total_money\": report_daily_model.sum_total_money, \"total_buy_volume\": report_daily_model.total_buy_volume, \"total_buy_money\": report_daily_model.total_buy_money, \"remain_money\": report_daily_model.remain_money,\n \"remain_volume\": report_daily_model.remain_volume, \"fm_state\": report_daily_model.fm_state,\"fm_state_msg\": report_daily_model.fm_state_msg, \"rtu_state\": report_daily_model.rtu_state,\"rtu_state_msg\": report_daily_model.rtu_state_msg, \"valve_state\": report_daily_model.valve_state, \"valve_state_msg\": report_daily_model.valve_state_msg, \"power_voltage\": report_daily_model.power_voltage,\n \"battery_voltage\": report_daily_model.battery_voltage, \"battery_level\": report_daily_model.battery_level, \"press_in\": report_daily_model.press_in, \"press_out\": report_daily_model.press_out, \"temp_in\": report_daily_model.temp_in,\n \"temp_out\": report_daily_model.temp_out, \"rssi\": report_daily_model.rssi, \"srd_status\": report_daily_model.srd_status}]\n db.dml_by_where(insert_sql, data) # ok\n print('insert_scada_report_daily ok')\n\n\n# 新增SCADA_REPORT_HOURLY\n# @param report_hourly_model 小时报表对象类\n# @return null 插入成功或失败\ndef insert_scada_report_hourly(report_hourly_model):\n insert_sql = \"INSERT INTO SCADA_REPORT_HOURLY (SRH_ORG_ID,SRH_ID, RTU_NO,FLMETER_NO,CUSTOMER_NO,\" \\\n \"REPORT_TIME,YEAR,MONTH,DAY, HOUR,\" \\\n \"STD_SUM,WORK_SUM,STD_FLOW,WORK_FLOW,TEMPERATURE,\" \\\n \"PRESSURE,PRICE,USE_VOLUME_WORK, USE_VOLUME_STD,USE_MONEY,\" \\\n \"SUM_TOTAL_VOLUME,SUM_TOTAL_MONEY,TOTAL_BUY_VOLUME,TOTAL_BUY_MONEY,REMAIN_MONEY,\" \\\n \"REMAIN_VOLUME,FM_STATE,FM_STATE_MSG,RTU_STATE,RTU_STATE_MSG,VALVE_STATE,VALVE_STATE_MSG,POWER_VOLTAGE,\" \\\n \"BATTERY_VOLTAGE,BATTERY_LEVEL,PRESS_IN,PRESS_OUT,TEMP_IN,\" \\\n \"TEMP_OUT,RSSI, SRH_STATUS ) \" \\\n \"VALUES\" \\\n \"(:srh_org_id,:srh_id, :rtu_no,:flmeter_no,:customer_no,\" \\\n \":report_time,:year,:month,:day, :hour,\" \\\n \":std_sum,:work_sum,:std_flow,:work_flow,:temperature,\" \\\n \":pressure,:price,:use_volume_work, :use_volume_std,:use_money,\" \\\n \":sum_total_volume,:sum_total_money,:total_buy_volume,:total_buy_money,:remain_money,\" \\\n \":remain_volume,:fm_state,:fm_state_msg,:rtu_state,:rtu_state_msg,:valve_state,:valve_state_msg,:power_voltage,\" \\\n \":battery_voltage,:battery_level,:press_in,:press_out,:temp_in,\" \\\n \":temp_out,:rssi, :srh_status)\"\n data = [{\"srh_org_id\": report_hourly_model.srh_org_id, \"srh_id\": report_hourly_model.srh_id, \"rtu_no\": report_hourly_model.rtu_no, \"flmeter_no\": report_hourly_model.flmeter_no,\"customer_no\": report_hourly_model.customer_no,\n \"report_time\": report_hourly_model.report_time, \"year\": report_hourly_model.year, \"month\": report_hourly_model.month, \"day\": report_hourly_model.day, \"hour\": report_hourly_model.hour,\n \"std_sum\": report_hourly_model.std_sum, \"work_sum\": report_hourly_model.work_sum, \"std_flow\": report_hourly_model.std_flow, \"work_flow\": report_hourly_model.work_flow, \"temperature\": report_hourly_model.temperature,\n \"pressure\": report_hourly_model.pressure, \"price\": report_hourly_model.price, \"use_volume_work\": report_hourly_model.use_volume_work, \"use_volume_std\": report_hourly_model.use_volume_std, \"use_money\": report_hourly_model.use_money,\n \"sum_total_volume\": report_hourly_model.sum_total_volume, \"sum_total_money\": report_hourly_model.sum_total_money, \"total_buy_volume\": report_hourly_model.total_buy_volume, \"total_buy_money\": report_hourly_model.total_buy_money, \"remain_money\": report_hourly_model.remain_money,\n \"remain_volume\": report_hourly_model.remain_volume, \"fm_state\": report_hourly_model.fm_state,\"fm_state_msg\": report_hourly_model.fm_state_msg, \"rtu_state\": report_hourly_model.rtu_state,\"rtu_state_msg\": report_hourly_model.rtu_state_msg, \"valve_state\": report_hourly_model.valve_state, \"valve_state_msg\": report_hourly_model.valve_state_msg, \"power_voltage\": report_hourly_model.power_voltage,\n \"battery_voltage\": report_hourly_model.battery_voltage, \"battery_level\": report_hourly_model.battery_level, \"press_in\": report_hourly_model.press_in, \"press_out\": report_hourly_model.press_out, \"temp_in\": report_hourly_model.temp_in,\n \"temp_out\": report_hourly_model.temp_out, \"rssi\": report_hourly_model.rssi, \"srh_status\": report_hourly_model.srh_status}]\n db.dml_by_where(insert_sql, data) # ok\n print('insert_scada_report_hourly ok')\n\n\n# 删除SCADA_REPORT_DAILY 带条件参数 删除数据\n# @param srd_org_id 机构号\n# @param srd_id 记录id\n# @return null 删除成功或失败\ndef del_scada_report_daily(srd_org_id, srd_id):\n sql = \"delete from SCADA_REPORT_DAILY where SRD_ORG_ID = :1 and SRD_ID=:2\"\n data = [(srd_org_id, srd_id)]\n db.dml_by_where(sql, data)\n print('del_by_where ok')\n\n\n# 删除SCADA_REPORT_HOURLY 带条件参数 删除数据\n# @param srh_org_id 机构号\n# @param srh_id 记录id\n# @return null 删除成功或失败\ndef del_scada_report_hourly(srh_org_id, srh_id):\n sql = \"delete from SCADA_REPORT_HOURLY where SRH_ORG_ID = :1 and SRH_ID=:2\"\n data = [(srh_org_id, srh_id)]\n db.dml_by_where(sql, data)\n print('del_by_where del_scada_report_hourly ok')\n\n\n# 获取所有需要跑脚本的机构信息\n# 字段:ORG_REPORT_GENERATE 是否计算生成报表:0不生成,1生成\ndef get_all_org_id_for_run_py_command_script_from_select_db():\n sql = \"select * from ORGANIZATION where ORG_REPORT_GENERATE= :org_report_generate\"\n data = [{\"org_report_generate\": \"1\"}]\n fc = db.select_by_where_many_params_dict(sql, data)\n return fc\n\n\n# 周期内平均值计算方法\n# @param data_list 计算的字典列表 key 对应的键\n# @return 处理之后的周期内平均值-返回四舍五入-再处理成str类型返回\ndef get_average_period(data_list, key):\n count_nums = 0\n total_size = len(data_list)\n for x in data_list:\n if x[key] is not None:\n if is_number(x[key]):\n if float(x[key]) < 0:\n x[key] = 0\n count_nums += float(x[key])\n else:\n count_nums += 0\n else:\n count_nums += 0\n ok_value = count_nums // total_size\n return str(round(ok_value, 2)) # 返回四舍五入\n\n\n# 数据处理-主逻辑处理-主要函数方法\n# @param data_for_processing 要处理的原数据\n# @param last_data_for_processing 要处理的原数据-上一次的\n# @param org_id 机构号\n# @param 字典传参 query_datetime 查询操作的日期\n# @return 处理结果 True成功 False失败\ndef data_processing(data_for_processing, last_data_for_processing, org_id, **kwargs):\n rm_repeat_sfd_data_list = [] # 用于临时存放已删除重复的字典数据\n last_rm_repeat_sfd_data_list = [] # 用于临时存放已删除重复的字典数据 上一天的 上一次的\n\n flmeter_no_set = set() # set是一个无序且不重复的元素集合-注意在创建空集合的时候只能使用s=set(),因为s={}创建的是空字典\n for x in data_for_processing:\n flmeter_no_set.add(x['FLMETER_NO'])\n print('不同的表计号共有个数:', len(flmeter_no_set)) # 19\n\n print('根据表计号,进行数据的再次筛选,处理,写入数据库')\n print('----------------------------------------------------------------------------------------')\n\n # 根据表计号,进行数据的再次筛选,处理,写入数据库\n flmeter_no_set_copy = flmeter_no_set.copy()\n for fno in flmeter_no_set:\n print(fno)\n # 以下为处理逻辑\n # 首先根据表计号,在原字典数据【data_for_processing】中筛选出所有此表计的数据\n for xx in data_for_processing:\n if xx['FLMETER_NO'] == fno:\n rm_repeat_sfd_data_list.append(xx)\n # print(rm_repeat_sfd_data_list)\n\n # 在查询当天的上一天数据中 for循环\n for xx in last_data_for_processing:\n if xx['FLMETER_NO'] == fno:\n last_rm_repeat_sfd_data_list.append(xx)\n # print(rm_repeat_sfd_data_list)\n\n\n print(\"此查询区间,当前编号下总共抄表记录:\", len(rm_repeat_sfd_data_list))\n print(\"此查询区间,上一天当前编号下总共抄表记录:\", len(last_rm_repeat_sfd_data_list))\n\n # 此表计数据字典列表 排序 按照采集时间INSTANT_TIME排序 默认升序 如果要降序排序,可以指定reverse=True\n sorted_rm_repeat_sfd_data_list = sorted(rm_repeat_sfd_data_list, key=operator.itemgetter('INSTANT_TIME'), reverse=False)\n\n # 上一天总抄表记录 排序 按照采集时间INSTANT_TIME排序 默认升序 如果要降序排序,可以指定reverse=True\n last_sorted_rm_repeat_sfd_data_list = []\n if len(last_rm_repeat_sfd_data_list) > 0:\n last_sorted_rm_repeat_sfd_data_list = sorted(last_rm_repeat_sfd_data_list, key=operator.itemgetter('INSTANT_TIME'), reverse=False)\n\n # 排序完成之后,具体字段补充\n\n # 新建一个小时报表类,用于接收收据\n rdm = ReportHourlyModel()\n\n # 机构号\n rdm.srh_org_id = sorted_rm_repeat_sfd_data_list[0]['SFD_ORG_ID']\n\n # 记录id srd_id 移到line385\n\n # RTU编号\n rdm.rtu_no = sorted_rm_repeat_sfd_data_list[0]['RTU_NO']\n # 流量计编号\n rdm.flmeter_no = sorted_rm_repeat_sfd_data_list[0]['FLMETER_NO']\n # 客户编号\n rdm.customer_no = sorted_rm_repeat_sfd_data_list[0]['CUSTOMER_NO']\n\n # 得到当前时间datetime\n now_datetime = datetime.datetime.today()\n # print(now_datetime.year, now_datetime.month, now_datetime.day, now_datetime.hour, now_datetime.minute,now_datetime.second) # 2019 3 8 12 52 10\n\n # 报表时间 年 月 日 时\n rdm.report_time = now_datetime\n\n # 将查询时间的年月日 分别赋值到对应字段\n # 处理年\n rdm.year = str(kwargs['query_datetime'].year)\n # 处理月\n # print(len(str(rdm.month)))\n # 如果月份小于10 补零 让9变为09月\n if len(str(kwargs['query_datetime'].month)) < 2:\n rdm.month = \"0\" + str(kwargs['query_datetime'].month)\n else:\n rdm.month = str(kwargs['query_datetime'].month)\n # 处理日\n # print(len(str(rdm.day)))\n # 如果日小于10 补零 让9变为09日\n if len(str(kwargs['query_datetime'].day)) < 2:\n rdm.day = \"0\" + str(kwargs['query_datetime'].day)\n else:\n rdm.day = str(kwargs['query_datetime'].day)\n\n # 处理小时 处理了 小时报表需要用到\n # print(len(str(rdm.hour)))\n # 如果小时小于10 补零 让9变为09小时\n if len(str(kwargs['query_datetime'].hour + 1)) < 2:\n rdm.hour = \"0\" + str(kwargs['query_datetime'].hour + 1)\n else:\n rdm.hour = str(kwargs['query_datetime'].hour + 1)\n\n # 记录ID-取自动递增流水号\n ssn_org_id = org_id # 传入过来的org_id\n ssn_key_name = \"SCADA_REPORT_HOURLY\" # 如需修改为其他表的递增流水,请自行修改\n ok_srd_id = get_sys_serial_no(db, ssn_org_id, ssn_key_name, rdm.year, rdm.month) # 导入获取流水号方法\n print(ok_srd_id)\n rdm.srh_id = ssn_org_id + rdm.year + rdm.month + ok_srd_id\n\n # 标况总量(期末数)\n rdm.std_sum = sorted_rm_repeat_sfd_data_list[len(sorted_rm_repeat_sfd_data_list) - 1]['STD_SUM'] # 默认升序,列表最后一个元素,值最大\n # 工况总量(期末数)\n rdm.work_sum = sorted_rm_repeat_sfd_data_list[len(sorted_rm_repeat_sfd_data_list) - 1]['WORK_SUM'] # 默认升序,列表最后一个元素,值最大\n # 标况流量(周期内平均值)\n rdm.std_flow = get_average_period(sorted_rm_repeat_sfd_data_list, \"STD_FLOW\") # 使用周期内平均值计算方法 计算平均值\n # 工况流量(周期内平均值)\n rdm.work_flow = get_average_period(sorted_rm_repeat_sfd_data_list, \"WORK_FLOW\")\n # 温度(周期内平均值)\n rdm.temperature = get_average_period(sorted_rm_repeat_sfd_data_list, \"TEMPERATURE\")\n\n # 压力(周期内平均值)\n rdm.pressure = get_average_period(sorted_rm_repeat_sfd_data_list, \"PRESSURE\")\n # 单价(期末数)\n rdm.price = sorted_rm_repeat_sfd_data_list[len(sorted_rm_repeat_sfd_data_list) - 1]['PRICE']\n # 周期内工况使用量(周期内期末数-期初数)\n max_work_sum = sorted_rm_repeat_sfd_data_list[len(sorted_rm_repeat_sfd_data_list) - 1]['WORK_SUM']\n min_work_sum = sorted_rm_repeat_sfd_data_list[0]['WORK_SUM']\n if max_work_sum is None:\n max_work_sum = str(0)\n if min_work_sum is None:\n min_work_sum = str(0)\n if len(last_rm_repeat_sfd_data_list) > 0: # (本期期末数-上期期末数)\n last_max_work_sum = last_sorted_rm_repeat_sfd_data_list[len(last_rm_repeat_sfd_data_list) - 1]['WORK_SUM']\n if last_max_work_sum is None:\n last_max_work_sum = str(0)\n rdm.use_volume_work = str(round(float(max_work_sum) - float(last_max_work_sum), 2))\n else: # (本周期内期末数-本周期内期初数)\n rdm.use_volume_work = str(round(float(max_work_sum) - float(min_work_sum), 2))\n if float(rdm.use_volume_work) < 0: # 如果use_volume_work计算出来小于0,则直接置为0\n rdm.use_volume_work = str(0)\n print(rdm.flmeter_no, \"☆ use_volume_work <0 置为0\")\n\n # 周期内标况使用量(周期内期末数 - 期初数)\n max_std_sum = sorted_rm_repeat_sfd_data_list[len(sorted_rm_repeat_sfd_data_list) - 1]['SUM_TOTAL'] # 默认升序,列表最后一个元素,值最大\n min_std_sum = sorted_rm_repeat_sfd_data_list[0]['SUM_TOTAL'] # 默认升序,列表第一个元素,值最小\n if max_std_sum is None:\n max_std_sum = str(0)\n if min_std_sum is None:\n min_std_sum = str(0)\n if len(last_rm_repeat_sfd_data_list) > 0: # (本期期末数-上期期末数)\n if last_sorted_rm_repeat_sfd_data_list[len(last_rm_repeat_sfd_data_list) - 1]['SUM_TOTAL'] is None:\n last_sorted_rm_repeat_sfd_data_list[len(last_rm_repeat_sfd_data_list) - 1]['SUM_TOTAL'] = str(0)\n rdm.use_volume_std = str(round(float(max_std_sum) - float(last_sorted_rm_repeat_sfd_data_list[len(last_rm_repeat_sfd_data_list) - 1]['SUM_TOTAL']), 2))\n else: # 周期内标况使用量(周期内期末数-期初数)\n rdm.use_volume_std = str(round(float(max_std_sum) - float(min_std_sum), 2))\n if float(rdm.use_volume_std) < 0: # 如果use_volume_std计算出来小于0,则直接置为0\n rdm.use_volume_std = str(0)\n print(rdm.flmeter_no, \"☆ use_volume_std <0 置为0\")\n\n # 周期内使用额(单价(期末数)* 周期内标况使用量)结果四舍五入\n # print(rdm.use_volume_std,rdm.price)\n if rdm.price is None:\n rdm.price = str(0)\n rdm.use_money = str(round((float(rdm.use_volume_std) * float(rdm.price)), 2))\n\n # 总累积使用量(期末数)\n rdm.sum_total_volume = sorted_rm_repeat_sfd_data_list[len(sorted_rm_repeat_sfd_data_list) - 1]['SUM_TOTAL']\n if rdm.sum_total_volume is None:\n rdm.sum_total_volume = str(0)\n print(rdm.flmeter_no, \"☆ sum_total_volume is None 置为0\")\n # 累购气量(期末数)\n rdm.total_buy_volume = sorted_rm_repeat_sfd_data_list[len(sorted_rm_repeat_sfd_data_list) - 1]['TOTAL_BUY_VOLUME']\n # 累购金额(期末数)\n rdm.total_buy_money = sorted_rm_repeat_sfd_data_list[len(sorted_rm_repeat_sfd_data_list) - 1]['TOTAL_BUY_MONEY']\n # 剩余金额(期末数)\n rdm.remain_money = sorted_rm_repeat_sfd_data_list[len(sorted_rm_repeat_sfd_data_list) - 1]['REMAIN_MONEY']\n # 总累计使用金额(期末累购金额-期末剩余金额)\n if rdm.total_buy_money is None: # total_buy_money为None的话 置为0查询计算\n rdm.total_buy_money = str(0)\n if rdm.remain_money is None: # remain_money为None的话 置为0查询计算\n rdm.remain_money = str(0)\n rdm.sum_total_money = float(rdm.total_buy_money) - float(rdm.remain_money)\n if rdm.sum_total_money < 0: # 如果sum_total_money计算出来小于0,则直接置为0\n rdm.sum_total_money = str(0)\n print(rdm.flmeter_no, \"☆ sum_total_money <0 置为0\")\n\n # 剩余数量(期末数)\n rdm.remain_volume = sorted_rm_repeat_sfd_data_list[len(sorted_rm_repeat_sfd_data_list) - 1]['REMAIN_VOLUME']\n # 流量计(表)状态(期末数)\n rdm.fm_state = sorted_rm_repeat_sfd_data_list[len(sorted_rm_repeat_sfd_data_list) - 1]['FM_STATE']\n # 表状态解析(按位解析)(期末数)\n rdm.fm_state_msg = sorted_rm_repeat_sfd_data_list[len(sorted_rm_repeat_sfd_data_list) - 1]['FM_STATE_MSG']\n # RTU状态(期末数)\n rdm.rtu_state = sorted_rm_repeat_sfd_data_list[len(sorted_rm_repeat_sfd_data_list) - 1]['RTU_STATE']\n # RTU状态解析(按字节解析)(期末数)\n rdm.rtu_state_msg = sorted_rm_repeat_sfd_data_list[len(sorted_rm_repeat_sfd_data_list) - 1]['RTU_STATE_MSG']\n # 阀门控制器状态(期末数)\n rdm.valve_state = sorted_rm_repeat_sfd_data_list[len(sorted_rm_repeat_sfd_data_list) - 1]['VALVE_STATE']\n # 阀门控制器状态解析(期末数)\n rdm.valve_state_msg = sorted_rm_repeat_sfd_data_list[len(sorted_rm_repeat_sfd_data_list) - 1]['VALVE_STATE_MSG']\n # 供电电压(周期内平均值)\n rdm.power_voltage = sorted_rm_repeat_sfd_data_list[len(sorted_rm_repeat_sfd_data_list) - 1]['POWER_VOLTAGE']\n\n # 电池电压(期末数)\n rdm.battery_voltage = sorted_rm_repeat_sfd_data_list[len(sorted_rm_repeat_sfd_data_list) - 1]['BATTERY_VOLTAGE']\n # 电池电量(期末数)\n rdm.battery_level = sorted_rm_repeat_sfd_data_list[len(sorted_rm_repeat_sfd_data_list) - 1]['BATTERY_LEVEL']\n # 入口压力(周期内平均值)\n rdm.press_in = get_average_period(sorted_rm_repeat_sfd_data_list, \"PRESSURE\")\n # 出口压力(周期内平均值)\n rdm.press_out = get_average_period(sorted_rm_repeat_sfd_data_list, \"PRESSURE\")\n # 入口温度(周期内平均值)\n rdm.temp_in = get_average_period(sorted_rm_repeat_sfd_data_list, \"TEMPERATURE\")\n\n # 出口温度(周期内平均值)\n rdm.temp_out = get_average_period(sorted_rm_repeat_sfd_data_list, \"TEMPERATURE\")\n # 信号强度(平均值)\n rdm.rssi = get_average_period(sorted_rm_repeat_sfd_data_list, \"RSSI\")\n # 删除标识符 1正常,9不正常已删除 默认置为1\n rdm.srh_status = \"1\"\n\n # print(sorted_rm_repeat_sfd_data_list)\n # print(len(sorted_rm_repeat_sfd_data_list), sorted_rm_repeat_sfd_data_list[0]['FLMETER_NO'], max_std_sum,min_std_sum, ok_std_sum)\n # print('----------------------------------------------------------------------------------------')\n\n # 写入数据库\n is_success = ok_processing_data_insert_into_oracle_for_hourly(rdm) # 将完善好数据的小时报表对象rdm-(其实该是rhm)传入\n print('----------------------------------------------------------------------------------------')\n\n # 处理数据完毕 清除临时使用数据\n flmeter_no_set_copy.remove(fno)\n rm_repeat_sfd_data_list.clear()\n last_rm_repeat_sfd_data_list.clear()\n pass\n return True\n\n\n# 判断\"字符串\"是否为数字\n# @param s 要检测的字符串\n# @return 处理结果 True是数字 False不是数字\ndef is_number(s):\n try:\n float(s)\n return True\n except ValueError:\n pass\n\n try:\n import unicodedata\n unicodedata.numeric(s)\n return True\n except (TypeError, ValueError):\n pass\n\n return False\n\n\n# main方法\n# @param db 数据库实例\n# @param org_id 机构号\n# @param days 天数\n# @param hours 小时数\n# @return main方法运行处理结果 执行完毕即可\ndef main(db, org_id, days, hours):\n\n print(\"I am main()\")\n\n # 记录ID - 取自动递增流水号\n # 设置机构号(传参接收过来了 )和序列号名称代码位置\n # com/lc/demo/pythonReportDemo/reportDailyKingDemo/python_report_daily_app_king2.py:419\n\n if hours == -23: # 凌晨1点的数据\n # 设置查询的机构,要查询哪一小时 【select_sfd_by_where_for_hourly 改为 select_sfd_by_where_for_hourly_ver_2】\n return_data, params_data = select_sfd_by_where_for_hourly_ver_2(org_id, days, hours) # @param org_id 要查询机构号 @param days 代表几天,可以正值(n天后),可以负值(n天前),0代表今天; hours 0代表小时 +n代表n小时后 -n代表n小时前 默认为-1 跑1小时前的数据\n\n # 查询当天的上一天数据 凌晨1点数据计算专属方法\n print(\"下面是查询当前小时的上一小时数据-总共抄表数据\")\n last_return_data, last_params_data = select_sfd_by_where_for_hourly2(org_id, days, hours - 1)\n\n pass\n else:\n # 设置查询的机构,要查询哪一小时 由方法【select_sfd_by_where_for_hourly 改为 select_sfd_by_where_for_hourly_ver_2 再改为 select_sfd_by_where_for_hourly_ver_2_pro】\n return_data, params_data = select_sfd_by_where_for_hourly_ver_2_pro(org_id, days, hours) # @param org_id 要查询机构号 @param days 代表几天,可以正值(n天后),可以负值(n天前),0代表今天; hours 0代表小时 +n代表n小时后 -n代表n小时前 默认为-1 跑1小时前的数据\n\n # 查询当天的上一天数据\n print(\"下面是查询当前小时的上一小时数据-总共抄表数据\")\n # 由【select_sfd_by_where_for_hourly 改为 select_sfd_by_where_for_hourly_ver_2 再改为 select_sfd_by_where_for_hourly_ver_2_pro】\n last_return_data, last_params_data = select_sfd_by_where_for_hourly_ver_2_pro(org_id, days, hours - 1)\n\n # print(return_data)\n # print(len(return_data))\n\n # 接下来开始处理查询出数据\n if len(return_data) > 0:\n print(params_data[0]['orgid'], [params_data[0]['minTime'].strftime('%Y-%m-%d %H:%M:%S'),params_data[0]['maxTime'].strftime('%Y-%m-%d %H:%M:%S')], \"开始进行计算小时报表数据处理\")\n is_ok = data_processing(return_data, last_return_data, params_data[0]['orgid'],query_datetime=last_params_data[0]['maxTime']) # 数据处理函数,处理小时报表 , 小时报表数据计算,写入数据库操作\n if is_ok:\n print(params_data[0]['orgid'],\"data_processing is ok\")\n print('----------------------------------------------------------------------------------------')\n pass\n else:\n print(params_data[0]['orgid'], [params_data[0]['minTime'].strftime('%Y-%m-%d %H:%M:%S'),params_data[0]['maxTime'].strftime('%Y-%m-%d %H:%M:%S')], \"期间无抄表数据,请等待重新计算小时报表\")\n print(\"----------------------------------------------------------------------------------------\")\n pass\n\n\nif __name__ == '__main__':\n\n # sys.stdout = PrintLogger('python_report_hourly_app_king3_OrgId.py.log') # 监听所有的print到log日志 封装类 如不需要打印所有输出print的log日志,隐掉这段即可\n\n print(\"============================================================================================================================================================分隔符\")\n\n db = MyOracle() # MyOracle()类实例化\n\n # 程序运行时间计算\n begin_time = None # 接收程序运行开始时间\n end_time = None # 接收程序运行结束时间\n begin_time = datetime.datetime.now()\n # print(\"程序运行开始时间:\", begin_time)\n\n begin_time_clock = None # 接收程序运行开始时间\n end_time_clock = None # 接收程序运行结束时间\n begin_time_clock = time.clock()\n # print(\"程序运行开始time.clock():\", begin_time_clock)\n\n # 查询出所有需要跑脚本的机构id\n org_list = get_all_org_id_for_run_py_command_script_from_select_db() # 查询出所有需要跑脚本的机构id\n\n # 循环 org_list @param db实例 @param org_id 要查询机构号 @param days 代表几天,可以正值(n天后),可以负值(n天前),0代表今天 ;hours 0代表当前小时 +n代表n小时后 -n代表n小时前 默认为-1 跑一小时前的数据\n # # if x['ORG_ID'] == '0027':\n # for x in org_list:\n # print(\"此机构:\", x['ORG_ID'])\n # for hours_temp in range(-23, 1, +1):\n # main(db, x['ORG_ID'], -1, hours_temp) # 传入的机构,设置要查询哪一天哪一小时!运行main方法,将db带过去,机构id,-1,-0 => -1跑昨天的数据!-0代表昨天0-24点数据,用于下面的操作!\n\n # 单跑某一个机构时 例如 0030\n for hours_temp in range(-23, 1, +1):\n main(db, '0039', -1, hours_temp)\n\n print(\"all done-指定单机构-小时报表整个处理流程完成\")\n print(\"----------------------------------------------------------------------------------------\")\n end_time = datetime.datetime.now()\n print(\"程序运行开始时间\", begin_time)\n print(\"程序运行结束时间:\", end_time)\n print(\"整个程序运行总时间:\", (end_time - begin_time).seconds, \"秒\") # (end_time - begin_time).microseconds, \"微秒 \"1秒 = 10的6次方微秒\n\n print(\"----------------------------------------------------------------------------------------\")\n end_time_clock = time.clock()\n print(\"程序运行开始time.clock():\", begin_time_clock)\n print(\"程序运行结束time.clock():\", end_time_clock)\n print(\"整个程序运行总时间time.clock()差:\", (end_time_clock - begin_time_clock), \"秒\")\n print(\"----------------------------------------------------------------------------------------\")","sub_path":"com/lc/demo/pythonReportDemo/reportHourlyKingDemo/python_report_hourly_app_king3_OrgId.py","file_name":"python_report_hourly_app_king3_OrgId.py","file_ext":"py","file_size_in_byte":48260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"56314138","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Sep 16 09:37:58 2013\n\n@author: jinpeng\n\"\"\"\n\nimport unittest\nfrom sklearn import datasets\nfrom epac.map_reduce.reducers import Reducer\nfrom epac import Methods\nfrom sklearn.metrics import precision_recall_fscore_support\n\n\n## 1) Design your classifier\n## ===========================================================================\nclass MySVC:\n def __init__(self, C=1.0):\n self.C = C\n\n def transform(self, X, y):\n from sklearn.svm import SVC\n svc = SVC(C=self.C)\n svc.fit(X, y)\n # \"transform\" should return a dictionary\n return {\"y/pred\": svc.predict(X), \"y\": y}\n\n\n## 2) Design your reducer which compute, precision, recall, f1_score, etc.\n## ===========================================================================\nclass MyReducer(Reducer):\n def reduce(self, result):\n pred_list = []\n # iterate all the results of each classifier\n # then you can design you own reducer!\n for res in result:\n precision, recall, f1_score, support = \\\n precision_recall_fscore_support(res['y'], res['y/pred'])\n pred_list.append({res['key']: recall})\n return pred_list\n\n\nclass TestDumpClass(unittest.TestCase):\n def test_mysvc_reducer(self):\n ## 1) Build dataset\n ## ===================================================================\n X, y = datasets.make_classification(n_samples=12,\n n_features=10,\n n_informative=2,\n random_state=1)\n\n ## 2) run with Methods\n ## ===================================================================\n my_svc1 = MySVC(C=1.0)\n my_svc2 = MySVC(C=2.0)\n\n two_svc_single = Methods(my_svc1, my_svc2)\n two_svc_local = Methods(my_svc1, my_svc2)\n two_svc_swf = Methods(my_svc1, my_svc2)\n\n two_svc_single.reducer = MyReducer()\n two_svc_local.reducer = MyReducer()\n two_svc_swf.reducer = MyReducer()\n\n for leaf in two_svc_single.walk_leaves():\n print(leaf.get_key())\n for leaf in two_svc_local.walk_leaves():\n print(leaf.get_key())\n for leaf in two_svc_swf.walk_leaves():\n print(leaf.get_key())\n\n # top-down process to call transform\n two_svc_single.run(X=X, y=y)\n # buttom-up process to compute scores\n res_single = two_svc_single.reduce()\n\n ### You can get below results:\n ### ==================================================================\n ### [{'MySVC(C=1.0)': array([ 1., 1.])}, {'MySVC(C=2.0)': array([ 1., 1.])}]\n\n ### 3) Run using local multi-processes\n ### ==================================================================\n from epac.map_reduce.engine import LocalEngine\n local_engine = LocalEngine(two_svc_local, num_processes=2)\n two_svc_local = local_engine.run(**dict(X=X, y=y))\n res_local = two_svc_local.reduce()\n\n ### 4) Run using soma-workflow\n ### ==================================================================\n from epac.map_reduce.engine import SomaWorkflowEngine\n sfw_engine = SomaWorkflowEngine(tree_root=two_svc_swf,\n num_processes=2)\n two_svc_swf = sfw_engine.run(**dict(X=X, y=y))\n res_swf = two_svc_swf.reduce()\n if not repr(res_swf) == repr(res_local):\n raise ValueError(\"Cannot dump class definition\")\n if not repr(res_swf) == repr(res_single):\n raise ValueError(\"Cannot dump class definition\")\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"epac/tests/test_dump_class_definition_sfw.py","file_name":"test_dump_class_definition_sfw.py","file_ext":"py","file_size_in_byte":3736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"636113939","text":"import argparse\nimport d3rlpy\nfrom d3rlpy.metrics import dynamics_observation_prediction_error_scorer\nfrom d3rlpy.metrics import dynamics_reward_prediction_error_scorer\nfrom sklearn.model_selection import train_test_split\n\nPARAMETER_TABLE = {\n 'halfcheetah-random-v0': (5, 0.5),\n 'hopper-random-v0': (5, 1),\n 'walker2d-random-v0': (1, 1),\n 'halfcheetah-medium-v0': (1, 1),\n 'hopper-medium-v0': (5, 5),\n 'walker2d-medium-v0': (5, 5),\n 'halfcheetah-medium-replay-v0': (5, 1),\n 'hopper-medium-replay-v0': (5, 1),\n 'walker2d-medium-replay-v0': (1, 1),\n 'halfcheetah-medium-expert-v0': (5, 1),\n 'hopper-medium-expert-v0': (5, 1),\n 'walker2d-medium-expert-v0': (1, 2)\n}\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--dataset', type=str, default='hopper-medium-v0')\n parser.add_argument('--seed', type=int, default=1)\n parser.add_argument('--gpu', type=int)\n args = parser.parse_args()\n\n # create dataset without masks\n dataset, env = d3rlpy.datasets.get_dataset(args.dataset)\n\n # fix seed\n d3rlpy.seed(args.seed)\n env.seed(args.seed)\n\n _, test_episodes = train_test_split(dataset, test_size=0.2)\n\n # prepare dynamics model\n dynamics_encoder = d3rlpy.models.encoders.VectorEncoderFactory(\n hidden_units=[200, 200, 200, 200],\n activation='swish',\n )\n dynamics_optim = d3rlpy.models.optimizers.AdamFactory(weight_decay=2.5e-5)\n dynamics = d3rlpy.dynamics.ProbabilisticEnsembleDynamics(\n encoder_factory=dynamics_encoder,\n optim_factory=dynamics_optim,\n learning_rate=1e-3,\n n_ensembles=5,\n use_gpu=args.gpu,\n )\n\n # train dynamics model\n dynamics.fit(dataset.episodes,\n eval_episodes=test_episodes,\n n_steps=100000,\n scorers={\n \"obs_error\": dynamics_observation_prediction_error_scorer,\n \"rew_error\": dynamics_reward_prediction_error_scorer,\n })\n\n if args.dataset in PARAMETER_TABLE:\n rollout_horizon, lam = PARAMETER_TABLE[args.dataset]\n else:\n rollout_horizon, lam = 5, 1\n\n # prepare combo\n mopo = d3rlpy.algos.MOPO(dynamics=dynamics,\n rollout_horizon=rollout_horizon,\n lam=lam,\n use_gpu=args.gpu)\n\n # train combo\n mopo.fit(dataset.episodes,\n eval_episodes=test_episodes,\n n_steps=500000,\n n_steps_per_epoch=1000,\n save_interval=10,\n scorers={\n \"environment\": d3rlpy.metrics.evaluate_on_environment(env),\n 'value_scale': d3rlpy.metrics.average_value_estimation_scorer\n },\n experiment_name=f\"MOPO_{args.dataset}_{args.seed}\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"reproductions/offline/mopo.py","file_name":"mopo.py","file_ext":"py","file_size_in_byte":2862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"330063469","text":"#! /usr/bin/python3\nfrom vpython import *\nfrom math import sin, cos\nimport argparse\nimport matplotlib.pyplot as plt \n\n\ndef set_scene(data):\n \"\"\"\n Set Vpython Scene\n :param: data: list of the data for the projectile motion\n \"\"\"\n scene.title = \"Assignment 5: Projectile motion\"\n scene.width = 800\n scene.heigth = 600\n scene.caption = \"\"\"Right button drag or Ctrl-drag to rotate \"camera\" to view scene.\n To zoom, drag with middle button or Alt/Option depressed, or use scroll wheel.\n On a two-button mouse, middle is left + right.\n Touch screen: pinch/extend to zoom, swipe or two-finger rotate.\"\"\"\n scene.forward = vector(0, -.3, -1)\n scene.x = -1\n # Set background: floor, table, etc\n scene.background = color.white\n scene.center = vector(10,data['init_height'],0)\n num = 0\n if data['init_height'] > 4:\n num = 2\n else:\n num = 0\n floor = box(pos=vector(35,0,0), length=75, width = 3, height = 0.5, color=color.magenta)\n table = box(pos=vector(0, data['init_height'] / 2 ,0), length=5, width = 2, height = data['init_height'] - num, color=color.blue)\n \n\ndef motion_no_drag(data):\n \"\"\"\n Create animation for projectile motion with no dragging force\n :param: data: list of the data for the projectile motion\n \"\"\"\n ball_nd = sphere(pos=vector(0, data['init_height'], 0),\n radius=1, color=color.cyan, make_trail=True)\n # Follow the movement of the ball\n scene.camera.follow(ball_nd)\n # Set initial velocity & position\n \n ball_nd.velocity = vector(data['init_velocity'] * cos(data['theta'] * pi / 180),\n data['init_velocity'] * sin(data['theta'] * pi / 180), 0)\n \n data[\"init_vel_x\"] = data['init_velocity'] * cos(data['theta'] * pi / 180)\n data[\"init_vel_y\"] = data['init_velocity'] * sin(data['theta'] * pi / 180)\n \n #floor = box(pos = (0,0,0), size = (100, 0.25, 10))\n t = 0\n g = vector(0, data['gravity'], 0)\n \n data['pos_x'] = 0\n x1 = []\n y1 = []\n \n # Animate\n mass = data['ball_mass'] * g\n fBallg = (mass / data['ball_mass']) * data[\"deltat\"]\n while ball_nd.pos.y > 0:\n rate(100) # refresh rate \n \n ball_nd.velocity = ball_nd.velocity + fBallg\n ball_nd.pos = ball_nd.pos + ball_nd.velocity * data[\"deltat\"]\n \n t = t + data[\"deltat\"] #update the time\n \n x1.append(ball_nd.pos.x)\n y1.append(ball_nd.pos.y)\n\n data[\"x1\"] = x1\n data[\"y1\"] = y1\n\n\ndef motion_drag(data):\n \"\"\"\n Create animation for projectile motion with no dragging force\n :param: data: list of the data for the projectile motion\n \"\"\"\n ball_ar = sphere(pos=vector(0, data['init_height']+ 0.5, 0),\n radius=1, color=color.yellow, make_trail=True)\n\n # Follow the movement of the ball\n scene.camera.follow(ball_ar)\n\n t = 0\n AR_x = -1/2 * data['rho'] * data[\"init_vel_x\"] * data['Cd']\n AR_y = -1/2 * data['rho'] * data[\"init_vel_y\"] * data['Cd']\n \n g = vector(AR_x, data['gravity'] + AR_y, 0)\n \n ball_ar.velocity = vector(data[\"init_vel_x\"], data[\"init_vel_y\"], 0)\n x_ar = []\n y_ar = []\n \n while ball_ar.pos.y > 0:\n \n rate(100) # refresh rate \n mass_ar = data['ball_mass']* g\n ball_ar.velocity = ball_ar.velocity + ( mass_ar/data['ball_mass']) * data[\"deltat\"]\n ball_ar.pos = ball_ar.pos + ball_ar.velocity * data[\"deltat\"]\n \n t = t + data[\"deltat\"] #update the time\n \n #get points for plotting\n x_ar.append(ball_ar.pos.x)\n y_ar.append(ball_ar.pos.y)\n\n data[\"x_ar\"] = x_ar\n data[\"y_ar\"] = y_ar\n\n \ndef plot_data(data):\n \"\"\"\n Create plot for the information from the two projectile motion.\n :param: data: list of the data for the projectile motion\n \"\"\"\n fig=plt.figure()\n fig.suptitle('Plot with and without Air resistance')\n plt.subplot(2,1,1) #Plot of the drag motion\n plt.title(\"Drag projectile motion\")\n #plt.xlabel(\"x (m)\")\n plt.ylabel(\"y (m)\")\n plt.plot(data[\"x_ar\"],data[\"y_ar\"])\n\n plt.subplot(2,1,2) #Plot of the none drag motion\n plt.title(\"No drag projectile motion\")\n plt.xlabel(\"x (m)\")\n plt.ylabel(\"y (m)\")\n plt.plot(data[\"x1\"],data[\"y1\"])\n plt.show()\n \n\ndef main():\n \"\"\"\n \"Main\" Function\n \"\"\"\n # 1) Parse the arguments\n parser = argparse.ArgumentParser(description=\"Description for my parser\", add_help=False)\n parser.add_argument(\"-v\", \"--velocity\", action=\"store\", type=float, required=True, help=\"The velocity of the object is required\")\n parser.add_argument(\"-a\", \"--angle\", action=\"store\", type=float, required=True, help=\"The angle of the object is required\")\n parser.add_argument(\"-h\", \"--height\", required=False, type=float, default= 1.2, help=\"The height of the object is not required. Default is set to 1.2 meters.\" )\n parser.add_argument(\"--help\", action='help')\n args = parser.parse_args()\n\n int_vel = 0\n angles = 0\n int_height = 0\n \n if args.velocity:\n int_vel = args.velocity\n if args.angle:\n angles = args.angle\n if args.height:\n int_height = args.height\n\n # Set Variables\n data = {} # empty dictionary for all data and variables\n data['init_height'] = int_height # y-axis\n data['init_velocity'] = int_vel # m/s\n data['theta'] = angles # degrees\n\t\n # Constants\n data['rho'] = 1.225 # kg/m^3\n data['Cd'] = 0.5 # coefficient friction\n data['deltat'] = 0.005\n data['gravity'] = -9.8 # m/s^2\n\n data['ball_mass'] = 0.145 # kg\n data['ball_radius'] = 0.075 # meters\n data['ball_area'] = pi * data['ball_radius']**2\n data['alpha'] = data['rho'] * data['Cd'] * data['ball_area'] / 2.0\n data['beta'] = data['alpha'] / data['ball_mass']\n\t\n # Set Scene\n set_scene(data)\n # 2) No Drag Animation\n motion_no_drag(data)\n # 3) Drag Animation\n motion_drag(data)\n # 4) Plot Information: extra credit\n plot_data(data)\n\n\nif __name__ == \"__main__\":\n main()\n exit(0)\n","sub_path":"lab5/lab5.py","file_name":"lab5.py","file_ext":"py","file_size_in_byte":6094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"238514881","text":"import scrapy\nimport datetime\nfrom ..items import *\nimport re\nfrom lxml import etree\nfrom ..items import ZhuqiuSpiderItem\n\nclass LeisuSpiderSpider(scrapy.Spider):\n name = 'leisu_spider'\n # allowed_domains = ['aaaa']\n start_urls = ['https://data.leisu.com/zuqiu-8437']\n\n def parse(self, response):\n item_list = []\n for i in range(1,8):\n item = {}\n match1 = response.xpath('//div[@class=\"left-list\"]/div[{}]'.format(i)).extract()[0]\n match2 = response.xpath('//div[@class=\"left-list\"]/div[{}]'.format(i)).extract()[0]\n resp = etree.HTML(match1)\n match_item_top = resp.xpath('//div[@class=\"title\"]/span/text()')[0]\n if i == 1:\n list_k = []\n res = etree.HTML(match1)\n res = res.xpath('//div/div[3]') #获得热门赛事的div列表\n item_content = {}\n match_item = res.xpath('/div/div[@class=\"title\"]/span/text()')\n target_url_list = res.xpath('/div/div/ul[@class=\"fd-list\"]/li/a/@href')\n target_name_list = res.xpath('/div/div/ul[@class=\"fd-list\"]/li/a/span/text()')\n item_content[match_item] = dict(zip(target_name_list,target_url_list))\n list_k.append(item_content)\n else:\n list_k = []\n res = etree.HTML(match1)\n res = res.xpath('//div[@class=\"children\"]') # 获得热门赛事的div列表\n for r in res:\n item_content = {}\n res = etree.HTML(etree.tostring(r, encoding='utf-8').decode())\n match_item = res.xpath('/div/div[@class=\"title\"]/span/text()')\n target_url_list = res.xpath('/div/div/ul[@class=\"fd-list\"]/li/a/@href')\n target_name_list = res.xpath('/div/div/ul[@class=\"fd-list\"]/li/a/span/text()')\n item_content[match_item] = dict(zip(target_name_list, target_url_list))\n list_k.append(item_content)\n\n item[match_item_top] = list_k\n yield item\n\n\n\n\n\n\n\n\n # remen_urls = response.xpath(\"/html/body/div[1]/div[2]/div/div/div[1]/div/div[1]/div[3]/ul/li/a/@href\").extract()\n # guoji_urls = urls = response.xpath(\"/html/body/div[1]/div[2]/div/div/div[1]/div/div[2]/div[2]/ul/li/a/@href\").extract()\n # shatan_urls = response.xpath(\"/html/body/div[1]/div[2]/div/div/div[1]/div/div[2]/div[3]/ul/li/a/@href\").extract()\n # ou_zhou_urls = response.xpath(\"/html/body/div[1]/div[2]/div/div/div[1]/div/div[3]/div[2]/ul/li/a/@href\").extract()\n # England = response.xpath(\"/html/body/div[1]/div[2]/div/div/div[1]/div/div[3]/div[3]/ul/li/a/@href\").extract()\n","sub_path":"sports/football/ti_spider_before/ti_spider/spiders/leisu_database_spider.py","file_name":"leisu_database_spider.py","file_ext":"py","file_size_in_byte":2734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"388732511","text":"from operator import pos\nimport re\nfrom flask import Flask, render_template,request,session,redirect\n\nfrom flask_sqlalchemy import SQLAlchemy\nfrom datetime import date, datetime\n#from flask_mail import Mail\nimport math\nfrom werkzeug.utils import secure_filename\nimport os\n\nimport json\nimport pymysql\npymysql.install_as_MySQLdb()\n\n\n\nwith open('config.json','r') as c:\n params=json.load(c)[\"params\"]\nlocal_server=True\napp=Flask(__name__)\napp.secret_key='super-secret-key'\n\n#to send email\n# app.config.update(\n# MALI_SERVER='smtp.gmail.com',\n# MAIL_PORT='465',\n# MAIL_USE_SSL=True,\n# MAIL_USERNAME=params['gmail_user'],\n# MAIN_PASSWORD=params['gmail_pass']\n# )\n# mail=Mail(app)\n\n\n# uploading for file\napp.config['UPLOAD_FOLDER']=params['upload_location']\n\n\n\n\nif(local_server):\n app.config['SQLALCHEMY_DATABASE_URI'] = params['local_uri']\nelse:\n app.config['SQLALCHEMY_DATABASE_URI'] = params['prod_uri']\n\ndb=SQLAlchemy(app)\n\n\nclass Contacts(db.Model):\n name = db.Column(db.String, nullable=False)\n email = db.Column(db.String, nullable=False)\n phone = db.Column(db.String, nullable=False)\n message= db.Column(db.String, nullable=False)\n date = db.Column(db.String, nullable=True)\n sno = db.Column(db.Integer, primary_key=True)\n\n\nclass Posts(db.Model):\n sno = db.Column(db.Integer, primary_key=True)\n title = db.Column(db.String, nullable=False)\n content = db.Column(db.String, nullable=False)\n date = db.Column(db.String, nullable=True)\n slug = db.Column(db.Integer, primary_key=True)\n\n@app.route(\"/\")\ndef home():\n #pagination logic\n posts=Posts.query.filter_by().all()\n last=math.ceil(len(posts)/int(params['no_of_posts']))\n #posts=posts[]\n\n page=request.args.get('page')\n if(not str(page).isnumeric()):\n page=1\n page=int(page)\n post= posts[(page-1)*int(params['no_of_posts']):(page-1)*int(params['no_of_posts'])+ int(params['no_of_posts'])]\n if(page==1):\n prev=\"#\"\n next=\"/?page=\"+str(page+1)\n elif(page==last):\n prev=\"/?page=\"+str(page-1)\n next=\"#\"\n else:\n prev=\"/?page=\"+str(page-1)\n next=\"/?page=\"+str(page+1)\n\n posts = Posts.query.filter_by().all()\n return render_template('index.html',params=params,posts=post,prev=prev,next=next)\n\n@app.route(\"/about\")\ndef about():\n return render_template('public/about.html',params=params)\n\n@app.route(\"/contact\", methods=['GET','POST'])\ndef contact():\n if(request.method=='POST'):\n name=request.form.get('name')\n email=request.form.get('email')\n phone=request.form.get('phone')\n message=request.form.get('message')\n\n entry=Contacts(name=name,email=email,phone=phone,message=message, date=datetime.now())\n\n db.session.add(entry)\n db.session.commit()\n\n #to send email\n #mail.send_message('New Message from '+name,sender=email,recipients=[params['gmail_user']],body=message+\"\\n\"+phone)\n\n\n return render_template('public/contact.html',params=params)\n\n@app.route(\"/post/\",methods=['GET'])\ndef post_route(post_slug):\n post=Posts.query.filter_by(slug=post_slug).first()\n return render_template('public/post.html',params=params,post=post)\n\n\n# admin part\n@app.route(\"/dashboard\",methods=['GET','POST'])\ndef dashboard():\n if ('user' in session and session['user']==params['admin_user']):\n posts=Posts.query.all()\n return render_template('admin/dashboard.html',params=params,posts=posts)\n if request.method=='POST':\n username=request.form.get('uname')\n password=request.form.get('pass')\n if(username==params['admin_user'] and password==params['admin_password']):\n session['user']=username\n posts=Posts.query.all()\n return render_template('admin/dashboard.html',params=params,posts=posts)\n\n return render_template('admin/login.html',params=params)\n\n@app.route(\"/edit/\",methods=['GET','POST'])\ndef edit(sno):\n if ('user' in session and session['user']==params['admin_user']):\n if(request.method=='POST'):\n box_title=request.form.get('title')\n box_slug=request.form.get('slug')\n box_content=request.form.get('content')\n date=datetime.now()\n\n if(sno!='0'):\n # post=Posts(title=box_title,content=box_content,date=date,slug=box_slug)\n # db.session.add(post)\n # db.session.commit()\n # else:\n post=Posts.query.filter_by(sno=sno).first()\n post.title=box_title\n post.slug=box_slug\n post.content=box_content\n post.date=date\n db.session.commit()\n return redirect('/dashboard')\n post=Posts.query.filter_by(sno=sno).first()\n return render_template('admin/edit.html',params=params,post=post)\n\n@app.route(\"/add/\",methods=['GET','POST'])\ndef add(sno):\n if ('user' in session and session['user']==params['admin_user']):\n if(request.method=='POST'):\n box_title=request.form.get('title')\n box_slug=request.form.get('slug')\n box_content=request.form.get('content')\n date=datetime.now()\n\n if(sno=='0'):\n post=Posts(title=box_title,content=box_content,date=date,slug=box_slug)\n db.session.add(post)\n db.session.commit()\n return redirect('/dashboard')\n return render_template('admin/add.html',params=params,sno=sno)\n\n\n@app.route(\"/upload\",methods=['POST','GET'])\ndef upload():\n if ('user' in session and session['user']==params['admin_user']):\n if(request.method=='POST'):\n f=request.files['file']\n f.save(os.path.join(app.config['UPLOAD_FOLDER'],secure_filename(f.filename)))\n return \"Updated Successfully\"\n\n@app.route(\"/logout\")\ndef logout():\n session.pop('user')\n return redirect('/dashboard')\n\n@app.route(\"/delete/\",methods=['GET','POST'])\ndef delete(sno):\n if ('user' in session and session['user']==params['admin_user']):\n post=Posts.query.filter_by(sno=sno).first()\n db.session.delete(post)\n db.session.commit()\n return redirect('/dashboard')\n\n\n\n\napp.run(debug=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"479122085","text":"'''\nTesting of git_irepository\nRUN TEST:\n python -m unittest test_git_interface.py -v\n'''\n\nimport unittest\nfrom git_irepository import iGitHub\n\n\nclass TestGitHub(unittest.TestCase):\n\n def test_git_obj_creation(self):\n \"\"\"test_create_git_obj\"\"\"\n auth_key = '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'\n org = 'vikash-org'\n result = iGitHub(org, auth_key)\n self.assertTrue(result != None)\n\n\n","sub_path":"src/test_git_interface.py","file_name":"test_git_interface.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"153614434","text":"\nclass ServerModel(object):\n def __init__(self, id, port, game, hostname, clientnum, maxclientnum, map, gametype):\n self.id = id\n self.port = port\n self.game = game\n self.hostname = hostname\n self.clientnum = clientnum\n self.maxclientnum = maxclientnum\n self.map = map\n self.gametype = gametype\n\n def __repr__(self):\n return ''.format(id=self.id)\n","sub_path":"Master/master/models/servermodel.py","file_name":"servermodel.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"238245217","text":"import urlparse\nimport ldap\n\nfrom django.contrib.auth import REDIRECT_FIELD_NAME, logout\nfrom django.contrib.auth.decorators import (login_required as\n _login_required)\nfrom django.contrib.auth.views import redirect_to_login\n\nimport commonware.log\nfrom statsd import statsd\n\nfrom larper import UserSession, get_assertion, store_assertion\n\n\nlog = commonware.log.getLogger('m.browserid')\n\n\ndef _redirect(request, login_url, redirect_field_name):\n \"\"\"Redirects the request based on parameters.\"\"\"\n path = request.build_absolute_uri()\n # If the login url is the same scheme and net location then just\n # use the path as the \"next\" url.\n login_scheme, login_netloc = urlparse.urlparse(login_url or\n settings.LOGIN_URL)[:2]\n current_scheme, current_netloc = urlparse.urlparse(path)[:2]\n if ((not login_scheme or login_scheme == current_scheme) and\n (not login_netloc or login_netloc == current_netloc)):\n path = request.get_full_path()\n log.debug('Clearing user session')\n logout(request)\n return redirect_to_login(path, login_url, redirect_field_name) \n\ndef login_required(function=None,\n redirect_field_name=REDIRECT_FIELD_NAME,\n login_url='/'):\n \"\"\"BrowserID sepcific login_required decorator.\n\n Decorator for views that checks that the user is logged in, redirecting\n to the log-in page if necessary.\n\n If the user's session timesout, sasl_interactive_bind\n will fail with a generic error. This is wrapped in a\n ldap.OTHER exception.\n \"\"\"\n def decorator(view_func):\n def _view(request, *args, **kwargs):\n (asst_hsh, assertion) = get_assertion(request)\n if not asst_hsh or not assertion:\n log.info(\"No assertion in session\")\n return _redirect(request, login_url, redirect_field_name)\n\n try:\n directory = UserSession(request)\n (registered, unique_id) = directory.registered_user()\n except ldap.OTHER:\n statsd.incr('browserid.session_timedout')\n log.info(\"Backend session timed out, clearing session assertion\")\n return _redirect(request, login_url, redirect_field_name)\n return view_func(request, *args, **kwargs)\n return _view\n\n if function:\n return decorator(function)\n else:\n return decorator\n","sub_path":"apps/browserid/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":2490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"615782941","text":"import time \nimport datetime\n# # t1=time.time()\n# # print(t1)\n# # time.sleep(10)\n# t2=time.time()\n\n# print(time.ctime(t2))\n# print(t2-t1)\n\nt=time.time()\nprint(time.ctime())\nresult = time.localtime()\nprint(result)\n# print(\"result:\", result)\n# print(\"\\nyear:\", result.tm_year)\n# print(\"tm_hour:\", result.tm_hour)\n\n# print(datetime.datetime.now())\ntime.sleep(10)\nprint(time.ctime(t))","sub_path":"advanced_python/time_module/prog1.py","file_name":"prog1.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"183005786","text":"from __future__ import absolute_import\nimport struct\n\nimport pytest\n\nfrom tchannel import messages\nfrom tchannel.messages.common import PROTOCOL_VERSION\nfrom tchannel.io import BytesIO\n\n\ndef make_short_bytes(value):\n \"\"\"Convert value into a big-endian unsigned int.\"\"\"\n return struct.pack('>H', value)\n\n\n@pytest.fixture\ndef init_request_message():\n return BytesIO(\n make_short_bytes(0x02) + # version 2\n make_short_bytes(0) # 0 headers\n )\n\n\n@pytest.fixture\ndef call_request_bytes():\n return bytearray([\n 0x00, # flags:1\n 0x00, 0x00, 0x04, 0x00, # ttl:4\n\n # tracing:24\n 0x00, 0x01, 0x02, 0x03, # span_id:8\n 0x04, 0x05, 0x06, 0x07, #\n 0x08, 0x09, 0x0a, 0x0b, # parent_id:8\n 0x0c, 0x0d, 0x0e, 0x0f, #\n 0x10, 0x11, 0x12, 0x13, # trace_id:8\n 0x14, 0x15, 0x16, 0x17, #\n 0x01, # traceflags:1\n\n 0x06, # service~1\n 0x61, 0x70, 0x61, 0x63, # ...\n 0x68, 0x65, # ...\n 0x01, # nh:1\n 0x03, 0x6b, 0x65, 0x79, # (hk~1 hv~1){nh}\n 0x03, 0x76, 0x61, 0x6c, # ...\n 0x00, # csumtype:1 (csum:4){0,1}\n 0x00, 0x02, 0x6f, 0x6e, # arg1~2\n 0x00, 0x02, 0x74, 0x6f, # arg2~2\n 0x00, 0x02, 0x74, 0x65 # arg3~2\n ])\n\n\n@pytest.fixture\ndef init_request_with_headers():\n header_name = b'test_header'\n header_value = b'something'\n header_buffer = (\n make_short_bytes(len(header_name)) +\n header_name +\n make_short_bytes(len(header_value)) +\n header_value\n )\n return BytesIO(\n make_short_bytes(PROTOCOL_VERSION) +\n make_short_bytes(1) +\n header_buffer\n )\n\n\ndef test_message_type_applies():\n \"\"\"Verify message_type propagates.\"\"\"\n assert messages.InitRequestMessage().message_type > 0\n\n\ndef test_init_request(init_request_message):\n \"\"\"Verify we can get an init request message to parse.\"\"\"\n message = messages.init_req_rw.read(init_request_message)\n assert message.version == 2\n assert message.headers == {}\n\n\ndef test_init_request_with_headers(init_request_with_headers):\n message = messages.init_req_rw.read(init_request_with_headers)\n assert message.version == 2\n assert message.headers['test_header'] == 'something'\n\n\ndef test_valid_ping_request():\n \"\"\"Verify we don't barf on 0-length bodies.\"\"\"\n assert (\n messages.ping_req_rw.read(BytesIO()) == messages.PingRequestMessage()\n )\n\n\n@pytest.mark.parametrize('message_class, message_rw, attrs', [\n (messages.InitRequestMessage, messages.init_req_rw, {\n 'headers': {'one': '2'}\n }),\n (messages.InitResponseMessage, messages.init_res_rw, {'headers': {}}),\n (messages.PingRequestMessage, messages.ping_req_rw, {}),\n (messages.PingResponseMessage, messages.ping_res_rw, {}),\n (messages.ErrorMessage, messages.error_rw, {\n 'code': 1,\n 'message': 'hi',\n 'original_message_id': 1,\n }),\n (messages.CallRequestMessage, messages.call_req_rw, {\n 'flags': 0,\n 'ttl': 1,\n 'tracing': messages.Tracing(0, 0, 0, 0),\n 'service': 'kodenom',\n 'headers': {},\n 'checksum': (messages.ChecksumType.none, 0),\n 'arg_1': None,\n 'arg_2': None,\n 'arg_3': None,\n }),\n (messages.CallRequestMessage, messages.call_req_rw, {\n 'flags': 0x01,\n 'ttl': 1,\n 'tracing': messages.Tracing(0, 0, 0, 1),\n 'service': 'with_checksum',\n 'headers': {},\n 'checksum': (messages.ChecksumType.crc32, 3),\n 'arg_1': b'hi',\n 'arg_2': b'\\x00',\n 'arg_3': None,\n }),\n (messages.CallResponseMessage, messages.call_res_rw, {\n 'flags': 1,\n 'code': 1,\n 'tracing': messages.Tracing(0, 0, 0, 1),\n 'headers': {},\n 'checksum': (messages.ChecksumType.crc32, 1),\n 'arg_1': None,\n 'arg_2': None,\n 'arg_3': None,\n }),\n])\ndef test_roundtrip_message(message_class, message_rw, attrs):\n \"\"\"Verify all message types serialize and deserialize properly.\"\"\"\n message = message_class(**attrs)\n buff = message_rw.write(message, BytesIO()).getvalue()\n assert message == message_rw.read(BytesIO(buff))\n\n\n@pytest.mark.parametrize('message_rw, byte_stream', [\n (messages.error_rw, bytearray([\n 0, 0, 0, 0, 1, 0, 2\n ] + list('hi')))\n])\ndef test_parse_message(message_rw, byte_stream):\n \"\"\"Verify all messages parse properly.\"\"\"\n message_rw.read(BytesIO(byte_stream))\n\n\ndef test_error_message_name():\n \"\"\"Smoke test the error dictionary.\"\"\"\n error = messages.ErrorMessage()\n error.code = 0x03\n assert error.error_name() == 'busy'\n\n\ndef test_call_req_parse(call_request_bytes):\n msg = messages.call_req_rw.read(BytesIO(call_request_bytes))\n\n assert msg.flags == 0\n assert msg.ttl == 1024\n\n assert msg.tracing == messages.Tracing(\n span_id=283686952306183,\n parent_id=579005069656919567,\n trace_id=1157726452361532951,\n traceflags=1\n )\n\n assert msg.service == 'apache'\n assert msg.headers == {'key': 'val'}\n assert msg.checksum == (messages.ChecksumType.none, None)\n\n assert msg.arg_1 == b'on'\n assert msg.arg_2 == b'to'\n assert msg.arg_3 == b'te'\n\n\ndef test_call_res_parse():\n buff = bytearray([\n 0x00, # flags:1\n 0x00, # code:1\n\n # tracing:24\n 0x00, 0x01, 0x02, 0x03, # span_id:8\n 0x04, 0x05, 0x06, 0x07, #\n 0x08, 0x09, 0x0a, 0x0b, # parent_id:8\n 0x0c, 0x0d, 0x0e, 0x0f, #\n 0x10, 0x11, 0x12, 0x13, # trace_id:8\n 0x14, 0x15, 0x16, 0x17, #\n 0x01, # traceflags:1\n\n 0x01, # nh:1\n 0x03, 0x6b, 0x65, 0x79, # (hk~1 hv~1){nh}\n 0x03, 0x76, 0x61, 0x6c, # ...\n 0x00, # csumtype:1 (csum:4){0,1}\n 0x00, 0x02, 0x6f, 0x6e, # arg1~2\n 0x00, 0x02, 0x74, 0x6f, # arg2~2\n 0x00, 0x02, 0x74, 0x65 # arg3~2\n ])\n\n msg = messages.call_res_rw.read(BytesIO(buff))\n\n assert msg.flags == 0\n assert msg.code == 0\n\n assert msg.tracing == messages.Tracing(\n span_id=283686952306183,\n parent_id=579005069656919567,\n trace_id=1157726452361532951,\n traceflags=1\n )\n\n assert msg.headers == {'key': 'val'}\n assert msg.checksum == (messages.ChecksumType.none, None)\n\n assert msg.arg_1 == b'on'\n assert msg.arg_2 == b'to'\n assert msg.arg_3 == b'te'\n\n\ndef test_equality_check_against_none(init_request_with_headers):\n assert (messages.InitRequestMessage() == None) is False\n","sub_path":"python/tests/test_messages.py","file_name":"test_messages.py","file_ext":"py","file_size_in_byte":6717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"543822297","text":"import re\nimport os\nimport numpy as np\nfrom scipy.io import netcdf_file\n\n\nclass AbinitOutput:\n def __init__(self, filename='abinit.out'):\n\n self.filename = filename\n rf = open(self.filename)\n self.data = rf.read()\n\n def reload(self):\n rf = open(self.filename)\n self.data = rf.read()\n\n def get_energetics(self):\n\n ret = re.findall('ETOT\\s*([\\d]+)\\s*([\\.E\\d\\-\\+]+)\\s*([\\.E\\d\\-\\+]+)\\s*([\\.E\\d\\-\\+]+)\\s*([\\.E\\d\\-\\+]+)\\n',\n self.data)\n if not ret:\n return None\n else:\n ret = [[float(x) for x in y] for y in ret]\n ret = np.array(ret)\n energetics = {'iter': list(ret[:, 0]),\n 'etot': list(ret[:, 1]),\n 'deltaEh': list(ret[:, 2]),\n 'residm': list(ret[:, 3]),\n 'nres2': list(ret[:, 4])}\n return energetics\n\n def get_occupation_matrix(self):\n\n occ_block = re.findall(r\"=== For Atom[\\s\\w\\d\\-\\.,=>:]*\\n \\n \\n\", self.data)\n if not occ_block:\n return None\n occs = re.findall('Occupation matrix for spin[\\s\\d\\w]*([\\s\\d\\-\\.]*)', occ_block[0])\n atoms = [int(x) for x in re.findall('For Atom([\\s\\w\\d]*)', occ_block[0])]\n spins = [int(x) for x in re.findall('Occupation matrix for spin([\\s\\w\\d]*\\n)', occ_block[0])]\n\n ret = []\n n = len(occs)\n if 2 * len(atoms) == len(spins) and len(spins) == n:\n for i in range(n):\n atom = atoms[(i + 1) / 2 + (i + 1) % 2 - 1]\n spin = spins[i]\n occ_matrix = [float(x) for x in occs[i].strip().split()]\n ret.append({'atom': atom, 'spin': spin, 'occ_matrix': occ_matrix})\n return ret\n\n def get_dmatpawu(self):\n om = self.get_occupation_matrix()\n min_atom = min([x['atom'] for x in om])\n max_atom = max([x['atom'] for x in om])\n ret = []\n for i in range(min_atom, max_atom + 1):\n for iom in om:\n if iom['atom'] == i and iom['spin'] == 1:\n ret.append(iom['occ_matrix'])\n return np.array(ret)\n\n @staticmethod\n def read_output_netcdf(filename):\n return netcdf2dict(filename)\n\n\ndef netcdf2dict(filename):\n \"\"\"\n Read a NetCDF file and create a python dictionary with\n numbers or lists for each variable\n\n Args:\n filename:\n NetCDF filename\n \"\"\"\n if not os.path.isfile(filename):\n print('ERROR: No such file: ', filename)\n return None\n ret = {}\n netcdfile = netcdf_file(filename, 'r', mmap=False)\n for ii in netcdfile.variables.keys():\n ret[ii] = netcdfile.variables[ii][:]\n netcdfile.close()\n\n for i in ret:\n if ret[i].dtype == np.dtype('>f8'):\n ret[i] = [round(x, 11) for x in ret[i].flatten()]\n elif ret[i].dtype == np.dtype('>i4'):\n ret[i] = [int(x) for x in ret[i].flatten()]\n\n for i in ret:\n if len(ret[i]) == 1:\n ret[i] = ret[i][0]\n\n return ret\n","sub_path":"pychemia/code/abinit/output.py","file_name":"output.py","file_ext":"py","file_size_in_byte":3084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"327164914","text":"from flask import Flask, Blueprint, render_template\nfrom admin.second import second\n\napp = Flask(__name__)\napp.register_blueprint(second, url_prefix=\"/admin\")\n\n\n@app.route(\"/home\")\n@app.route(\"/\")\ndef home():\n return render_template(\"index.html\")\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","sub_path":"Flask Tutorial #10 - Blueprints & Using Multiple Python Files/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"224368498","text":"\"\"\" Extracts frames from a video and stores triplets for network consumption \"\"\"\n\nfrom absl import app\nfrom absl import flags\nimport numpy as np\nimport cv2\nfrom collections import deque\nfrom os import path\n\nflags.DEFINE_string('input_file', None, 'Input video file')\nflags.DEFINE_string('output_dir', None, 'Directory to store predictions.')\nflags.DEFINE_integer('img_height', 128, 'Input frame height.')\nflags.DEFINE_integer('img_width', 416, 'Input frame width.')\n\nFLAGS = flags.FLAGS\nflags.mark_flag_as_required('input_file')\nflags.mark_flag_as_required('output_dir')\n\n\ndef main(_):\n cap = cv2.VideoCapture(FLAGS.input_file)\n queue = deque(maxlen=3)\n ctr = 0\n while cap.isOpened():\n _, frame = cap.read()\n frame = cv2.resize(frame, (FLAGS.img_width, FLAGS.img_height))\n queue.append(frame)\n if len(queue) == 3:\n triplet = np.zeros((FLAGS.img_height, FLAGS.img_width * 3, 3), dtype=np.uint8)\n for i in range(3):\n img = queue[i]\n min_x = i*FLAGS.img_width\n max_x = min_x + FLAGS.img_width\n triplet[:, min_x:max_x, :] = img\n filename = path.join(FLAGS.output_dir, 'triplet_%08d.png' % ctr)\n cv2.imwrite(filename, triplet)\n ctr += 1\n queue.popleft()\n cap.release()\n\nif __name__ == '__main__':\n app.run(main)","sub_path":"depth_from_video_in_the_wild/transform_video.py","file_name":"transform_video.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"129550981","text":"# -*- coding: utf-8 -*-\nfrom __future__ import print_function, division\nimport logging\nimport numpy as np\nimport random\nimport torch\nfrom torch.optim import lr_scheduler\nfrom pymic.loss.seg.util import get_soft_label\nfrom pymic.loss.seg.util import reshape_prediction_and_ground_truth\nfrom pymic.loss.seg.util import get_classwise_dice\nfrom pymic.loss.seg.dice import DiceLoss\nfrom pymic.net_run.weak_sup import WSLSegAgent\nfrom pymic.util.ramps import get_rampup_ratio\n\nclass WSLDMPLS(WSLSegAgent):\n \"\"\"\n Weakly supervised segmentation based on Dynamically Mixed Pseudo Labels Supervision.\n\n * Reference: Xiangde Luo, Minhao Hu, Wenjun Liao, Shuwei Zhai, Tao Song, Guotai Wang,\n Shaoting Zhang. ScribblScribble-Supervised Medical Image Segmentation via \n Dual-Branch Network and Dynamically Mixed Pseudo Labels Supervision.\n `MICCAI 2022. `_ \n \n :param config: (dict) A dictionary containing the configuration.\n :param stage: (str) One of the stage in `train` (default), `inference` or `test`. \n\n .. note::\n\n In the configuration dictionary, in addition to the four sections (`dataset`,\n `network`, `training` and `inference`) used in fully supervised learning, an \n extra section `weakly_supervised_learning` is needed. See :doc:`usage.wsl` for details.\n \"\"\"\n def __init__(self, config, stage = 'train'):\n net_type = config['network']['net_type']\n if net_type not in ['UNet2D_DualBranch', 'UNet3D_DualBranch']:\n raise ValueError(\"\"\"For WSL_DMPLS, a dual branch network is expected. \\\n It only supports UNet2D_DualBranch and UNet3D_DualBranch currently.\"\"\")\n super(WSLDMPLS, self).__init__(config, stage)\n\n def training(self):\n class_num = self.config['network']['class_num']\n iter_valid = self.config['training']['iter_valid']\n wsl_cfg = self.config['weakly_supervised_learning']\n iter_max = self.config['training']['iter_max']\n rampup_start = wsl_cfg.get('rampup_start', 0)\n rampup_end = wsl_cfg.get('rampup_end', iter_max)\n train_loss = 0\n train_loss_sup = 0\n train_loss_reg = 0\n train_dice_list = []\n self.net.train()\n for it in range(iter_valid):\n try:\n data = next(self.trainIter)\n except StopIteration:\n self.trainIter = iter(self.train_loader)\n data = next(self.trainIter)\n \n # get the inputs\n inputs = self.convert_tensor_type(data['image'])\n y = self.convert_tensor_type(data['label_prob']) \n \n inputs, y = inputs.to(self.device), y.to(self.device)\n \n # zero the parameter gradients\n self.optimizer.zero_grad()\n \n # forward + backward + optimize\n outputs1, outputs2 = self.net(inputs)\n loss_sup1 = self.get_loss_value(data, outputs1, y) \n loss_sup2 = self.get_loss_value(data, outputs2, y) \n loss_sup = 0.5 * (loss_sup1 + loss_sup2)\n\n # get pseudo label with dynamical mix\n outputs_soft1 = torch.softmax(outputs1, dim=1)\n outputs_soft2 = torch.softmax(outputs2, dim=1)\n beta = random.random()\n pseudo_lab = beta*outputs_soft1.detach() + (1.0-beta)*outputs_soft2.detach()\n pseudo_lab = torch.argmax(pseudo_lab, dim = 1, keepdim = True)\n pseudo_lab = get_soft_label(pseudo_lab, class_num, self.tensor_type)\n \n # calculate the pseudo label supervision loss\n loss_calculator = DiceLoss()\n loss_dict1 = {\"prediction\":outputs1, 'ground_truth':pseudo_lab}\n loss_dict2 = {\"prediction\":outputs2, 'ground_truth':pseudo_lab}\n loss_reg = 0.5 * (loss_calculator(loss_dict1) + loss_calculator(loss_dict2))\n \n rampup_ratio = get_rampup_ratio(self.glob_it, rampup_start, rampup_end, \"sigmoid\")\n regular_w = wsl_cfg.get('regularize_w', 0.1) * rampup_ratio\n loss = loss_sup + regular_w*loss_reg\n\n loss.backward()\n self.optimizer.step()\n \n train_loss = train_loss + loss.item()\n train_loss_sup = train_loss_sup + loss_sup.item()\n train_loss_reg = train_loss_reg + loss_reg.item() \n # get dice evaluation for each class in annotated images\n if(isinstance(outputs1, tuple) or isinstance(outputs1, list)):\n outputs1 = outputs1[0] \n p_argmax = torch.argmax(outputs1, dim = 1, keepdim = True)\n p_soft = get_soft_label(p_argmax, class_num, self.tensor_type)\n p_soft, y = reshape_prediction_and_ground_truth(p_soft, y) \n dice_list = get_classwise_dice(p_soft, y)\n train_dice_list.append(dice_list.cpu().numpy())\n train_avg_loss = train_loss / iter_valid\n train_avg_loss_sup = train_loss_sup / iter_valid\n train_avg_loss_reg = train_loss_reg / iter_valid\n train_cls_dice = np.asarray(train_dice_list).mean(axis = 0)\n train_avg_dice = train_cls_dice[1:].mean()\n\n train_scalers = {'loss': train_avg_loss, 'loss_sup':train_avg_loss_sup,\n 'loss_reg':train_avg_loss_reg, 'regular_w':regular_w,\n 'avg_fg_dice':train_avg_dice, 'class_dice': train_cls_dice}\n\n return train_scalers\n ","sub_path":"pymic/net_run/weak_sup/wsl_dmpls.py","file_name":"wsl_dmpls.py","file_ext":"py","file_size_in_byte":5481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"167639904","text":"import csv\nimport cv2\nimport numpy as np\nfrom keras.models import Sequential\nfrom keras.layers import Flatten, Dense, Dropout, Lambda, Cropping2D\nimport sys\nimport argparse\nimport os\nfrom keras.layers.convolutional import Convolution2D\nfrom keras.optimizers import adam\nimport json\nfrom keras.callbacks import TensorBoard\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau\nimport logging\nimport math\nimport random\nfrom keras import backend as k\nfrom sklearn.utils import shuffle\nfrom imblearn.under_sampling import RandomUnderSampler\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\ntfl = logging.getLogger('tensorflow')\ntfl.setLevel(logging.ERROR)\n\n\ndef parse_args(arguments):\n \"\"\"\n Parses arguments given at the command line.\n :param arguments: Arguments given at the command line\n :return: Dict of variables parsed from the arguments\n \"\"\"\n parser = argparse.ArgumentParser(description=\"Trains a behavioral cloning model from a given training file set.\")\n parser.add_argument('-c', '--configuration', help=\"File path configuration file\", required=True,\n dest='config')\n parser.add_argument('-l', '--logdir', help=\"Tensorboard log directory\", dest='log_dir', required=True)\n\n return vars(parser.parse_args(arguments))\n\n\ndef load_config(config_name):\n \"\"\"\n Loads a .json configuration file\n :param config_name: Path for the configuration file.\n :return: A dict containing the loaded configuration values.\n \"\"\"\n with open(config_name) as config_file:\n configuration = json.load(config_file)\n return configuration\n\n\ndef get_file_list(dir_path):\n \"\"\"\n Get list of log files.\n :param dir_path: File path for .csv log file.\n :return: List of file paths of driving log files to open.\n \"\"\"\n file_list = []\n for root, dirs, files in os.walk(dir_path):\n [file_list.append(os.path.join(root, file)) for file in files if file.endswith('.csv')]\n return file_list\n\n\ndef get_log_lines(path):\n \"\"\"\n Gets list of records from driving log.\n :param path: Input path for driving log.\n :return: List of driving log records.\n \"\"\"\n log_lines = []\n with open(path) as csvfile:\n reader = csv.reader(csvfile)\n for line in reader:\n log_lines.append(line)\n return log_lines\n\n\ndef get_path_replacement(path, new_root):\n \"\"\"\n Changes absolute file path name for an image noted in the log file to a new 'root'\n if directory was moved after recording.\n :param path: File path for an image.\n :param old_root: Original root to be replaced.\n :param new_root: New file root to be included.\n :return: Modified filepath.\n \"\"\"\n file_tokens = path.split('/')\n end_tokens = file_tokens[-3:]\n end_tokens.insert(0, new_root)\n return '/'.join(end_tokens)\n\n\ndef get_image_and_measurement(line, old_root=None, new_root=None):\n \"\"\"\n Gets images and measurements from a log file line.\n :param line: Line record from a log file.\n :param old_root: If changing image file paths, original root of the path.\n :param new_root: If changing image file paths, replacement root of the file path.\n :return: Center image, left image, right image, and steering measurement.\n \"\"\"\n center_image_path = line[0]\n left_image_path = line[1]\n right_image_path = line[2]\n\n if new_root and old_root:\n center_image_path = get_path_replacement(center_image_path, new_root)\n left_image_path = get_path_replacement(left_image_path, new_root)\n right_image_path = get_path_replacement(right_image_path, new_root)\n center_image = cv2.imread(center_image_path)\n left_image = cv2.imread(left_image_path)\n right_image = cv2.imread(right_image_path)\n measurement = float(line[3])\n\n return center_image, left_image, right_image, measurement\n\n\ndef create_model(units=1, loss_function='mse', input_shape=(160, 320, 3),\n gpus=1, learning_rate=0.001, dropout=0.25):\n \"\"\"\n Creates and compiles Convolutional Neural Network model to learn steering angle from images.\n Implemented from Bojarski, M. et al, NVIDIA, \"End to End Learning for Self-Driving\n Cars\", 2016 - https://arxiv.org/pdf/1604.07316v1.pdf, and this was noted by\n David Silver during the Udacity Self-Driving Car Nanodegree walkthrough for\n the behavioral cloning project.\n Before convolutional layers, the model normalizes and then crops the images.\n :param units: How many units to include in output layer (since this is a regression model,\n this value will always be 1.\n :param loss_function: Loss function to use in the model.\n :param input_shape: Input shape of images\n :param gpus: Number of GPUs to use, if training on a GPU with multiple cards.\n :param learning_rate: Learning rate to start with in the model.\n :param dropout: Percentage of records to dropout after convolutions.\n :return:\n \"\"\"\n # NVIDIA Example\n conv_model = Sequential()\n conv_model.add(Lambda(lambda x: (x / 255.0) - 0.5, input_shape=input_shape))\n conv_model.add(Cropping2D(cropping=((70,25),(0,0))))\n conv_model.add(Convolution2D(24, 5, 5, subsample=(2, 2), activation='relu'))\n conv_model.add(Convolution2D(36, 5, 5, subsample=(2, 2), activation='relu'))\n conv_model.add(Convolution2D(48, 5, 5, subsample=(2, 2), activation='relu'))\n conv_model.add(Convolution2D(64, 3, 3, activation='relu'))\n conv_model.add(Convolution2D(64, 3, 3, activation='relu'))\n conv_model.add(Dropout(dropout))\n conv_model.add(Flatten())\n conv_model.add(Dense(100, activation='relu'))\n conv_model.add(Dense(50, activation='relu'))\n conv_model.add(Dense(10, activation='relu'))\n conv_model.add(Dense(units))\n\n opt = adam(lr=learning_rate)\n\n if gpus <= 1:\n conv_model.compile(loss=loss_function, optimizer=opt, metrics=['accuracy'])\n else:\n gpu_list = []\n [gpu_list.append('gpu(%d)' % i) for i in range(gpus)]\n conv_model.compile(loss=loss_function, optimizer=opt, metrics=['accuracy'],\n context=gpu_list)\n return conv_model\n\n\ndef augment_brightness_camera_images(image):\n \"\"\"\n Note: Cited from blog post https://chatbotslife.com/using-augmentation-to-mimic-human-driving-496b569760a9,\n which was a recommended reading by my Udacity mentor, Rahul. Function used to augment my dataset to\n improve model performance.\n :param image: Image file opened by OpenCV\n :return: Randomly brightened variation of the input image.\n \"\"\"\n image1 = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)\n image1 = np.array(image1, dtype=np.float64)\n random_bright = .5 + np.random.uniform()\n image1[:, :, 2] = image1[:, :, 2] * random_bright\n image1[:, :, 2][image1[:, :, 2] > 255] = 255\n image1 = np.array(image1, dtype=np.uint8)\n image1 = cv2.cvtColor(image1, cv2.COLOR_HSV2RGB)\n return image1\n\n\ndef adjust_side_images(measurement_value, adjustment_offset, side):\n \"\"\"\n Implementation of usage of left and right images to simulate edge correction,\n as suggested in blog post by Vivek Yadav,\n https://chatbotslife.com/using-augmentation-to-mimic-human-driving-496b569760a9,\n as suggested reading by my Udacity mentor, Rahul. Function used to augment my dataset to improve\n model performance.\n :param measurement_value: Steering measurement value.\n :param adjustment_offset: Amount to offset side images by.\n :param side: Image position to determine offset side.\n :return: Adjusted measurement value.\n \"\"\"\n if side == 'left':\n return measurement_value + adjustment_offset\n elif side == 'right':\n return measurement_value - adjustment_offset\n elif side == 'center':\n return measurement_value\n\n\ndef shift_image_position(image, steering_angle, translation_range):\n \"\"\"\n Note: Cited from blog post https://chatbotslife.com/using-augmentation-to-mimic-human-driving-496b569760a9,\n which was a recommended reading by my Udacity mentor, Rahul. Function used to augment my dataset to\n improve model performance.\n :param image: Input image to shift.\n :param steering_angle: Input steering angle\n :param translation_range: Range to translate the image.\n :return: translated_image, translated_steering_angle\n \"\"\"\n translation_x = translation_range * np.random.uniform() - translation_range / 2\n translated_steering_angle = steering_angle + translation_x / translation_range * 2 * .2\n translation_y = 40 * np.random.uniform() - 40 / 2\n translation_m = np.float32([[1, 0, translation_x], [0, 1, translation_y]])\n rows = image.shape[0]\n cols = image.shape[1]\n translated_image = cv2.warpAffine(image, translation_m, (cols, rows))\n\n return translated_image, translated_steering_angle\n\n\ndef add_random_shadow(image):\n \"\"\"\n Adding a random shadow mask to the image.\n Note: Cited from blog post https://chatbotslife.com/using-augmentation-to-mimic-human-driving-496b569760a9,\n which was a recommended reading by my Udacity mentor, Rahul. Function used to augment my dataset to\n improve model performance.\n :param image: Image to add a shadow too.\n :return: Image with a random shadow added.\n \"\"\"\n top_y = 320 * np.random.uniform()\n top_x = 0\n bot_x = 160\n bot_y = 320 * np.random.uniform()\n image_hls = cv2.cvtColor(image, cv2.COLOR_RGB2HLS)\n shadow_mask = 0 * image_hls[:, :, 1]\n x_m = np.mgrid[0:image.shape[0], 0:image.shape[1]][0]\n y_m = np.mgrid[0:image.shape[0], 0:image.shape[1]][1]\n\n shadow_mask[((x_m - top_x) * (bot_y - top_y) - (bot_x - top_x) * (y_m - top_y) >= 0)] = 1\n if np.random.randint(2) == 1:\n random_bright = .5\n cond1 = shadow_mask == 1\n cond0 = shadow_mask == 0\n if np.random.randint(2) == 1:\n image_hls[:, :, 1][cond1] = image_hls[:, :, 1][cond1] * random_bright\n else:\n image_hls[:, :, 1][cond0] = image_hls[:, :, 1][cond0] * random_bright\n\n image = cv2.cvtColor(image_hls, cv2.COLOR_HLS2RGB)\n\n return image\n\n\ndef flip_image_and_measurement(image, measurement):\n \"\"\"\n Flips image so it looks as though it was made going from the opposite direction.\n\n Note: Implementation of usage of left and right images to simulate edge correction,\n as suggested in blog post by Vivek Yadav,\n https://chatbotslife.com/using-augmentation-to-mimic-human-driving-496b569760a9,\n as suggested reading by my Udacity mentor, Rahul. Function used to augment my dataset to improve\n model performance.\n :param image: Image to be flipped\n :param measurement: Measurement to be flipped\n :return: Flipped image and measurement.\n \"\"\"\n return cv2.flip(image, 1), measurement * -1\n\n\ndef crop_image(image, horizon_divisor, hood_pixels, crop_height, crop_width):\n \"\"\"\n Note: Cited and refactored from blog post\n https://chatbotslife.com/using-augmentation-to-mimic-human-driving-496b569760a9,\n which was a recommended reading by my Udacity mentor, Rahul. Function used to augment\n my dataset to improve model performance.\n :param image: Image to be cropped.\n :param horizon_divisor: Divisor to find the top 1/xth of the image to crop unneeded information above the horizon.\n :param hood_pixels: Number of pixels to crop out of the bottom of the image to eliminate unneeded information about the hood.\n :param crop_height: Height to resize the image to after eliminating horizon and hood.\n :param crop_width: Width to resize the image to after eliminating horizon and hood.\n :return: Cropped image.\n \"\"\"\n shape = image.shape\n image = image[math.floor(shape[0] / horizon_divisor):shape[0] - hood_pixels, 0:shape[1]]\n image = cv2.resize(image, (crop_width, crop_height))\n\n return image\n\n\ndef full_augment_image(image, position, measurement, side_adjustment, shift_offset=0.004):\n \"\"\"\n Takes an image array, it's position, it's measurement, the side adjustment value, and\n the translation offset desired and provides one copy of the original image plus all\n seven augmentation functions.\n :param image: Input image array.\n :param position: Position of the camera (Center, left or right)\n :param measurement: Steering angle measurement.\n :param shift_offset: Amount to offset translation.\n :return: Augmented images list, augmented measurements list. There should be 8.\n \"\"\"\n aug_images = []\n aug_measurements = []\n\n measurement = adjust_side_images(measurement, side_adjustment, position)\n\n bright = augment_brightness_camera_images(image)\n shadow = add_random_shadow(image)\n flipped, flipped_mmt = flip_image_and_measurement(image, measurement)\n\n aug_images.append(image)\n aug_measurements.append(measurement)\n aug_images.append(bright)\n aug_measurements.append(measurement)\n aug_images.append(shadow)\n aug_measurements.append(measurement)\n aug_images.append(flipped)\n aug_measurements.append(flipped_mmt)\n\n translated, shift_mmt = shift_image_position(image, measurement, shift_offset)\n bright_shifted, bright_shift_mmt = shift_image_position(bright, measurement, shift_offset)\n shadow_shifted, shadow_shift_mmt = shift_image_position(shadow, measurement, shift_offset)\n flipped_shifted, flipped_shift_mmt = shift_image_position(flipped, flipped_mmt, shift_offset)\n\n aug_images.append(translated)\n aug_measurements.append(shift_mmt)\n\n aug_images.append(bright_shifted)\n aug_measurements.append(bright_shift_mmt)\n\n aug_images.append(shadow_shifted)\n aug_measurements.append(shadow_shift_mmt)\n\n aug_images.append(flipped_shifted)\n aug_measurements.append(flipped_shift_mmt)\n\n return aug_images, aug_measurements\n\n\ndef shuffle_lines(shuffle_lines):\n \"\"\"\n Shuffles log record lines.\n :param shuffle_lines: Log record lines to be shuffled.\n :return: Shuffled lines\n \"\"\"\n return_lines = []\n\n index_list = range(len(shuffle_lines))\n shuffled_indexes = random.sample(index_list, len(index_list))\n\n for i in shuffled_indexes:\n return_lines.append(shuffle_lines[i])\n\n return return_lines\n\n\ndef generate_full_augment_from_lines(lines, old_root, new_root, side_adjustment, batch_size=32):\n \"\"\"\n Generator to generated full complement of augmented images from log line records.\n Batch size is divided by 8 to account for the 8 different images returned from\n the image augmentation function (assuming using 32, 64, 128, 256, etc. as acceptable\n batch size values).\n\n Splits lines into batches, opens images and gets measurement from the lines,\n augments each image (and updates the respective measurement accordingly),\n and converts the resulting lists of images and measurements to numpy arrays\n and yields them.\n :param lines: Log lines to augment.\n :param batch_size: Batch size for model run.\n :return: Augmented images and measurements yielded for model training.\n \"\"\"\n num_lines = len(lines)\n batch_size = int(batch_size//8)\n while 1:\n for offset in range(0, num_lines, batch_size):\n batch_lines = lines[offset:offset+batch_size]\n\n images = []\n measurements = []\n\n for batch_line in batch_lines:\n center, left, right, measurement = get_image_and_measurement(batch_line,\n old_root,\n new_root)\n\n for position in ['center','left','right']:\n if position == 'center':\n current_image = center\n elif position == 'left':\n current_image = left\n else:\n current_image = right\n\n augmented_images, augmented_measurements = full_augment_image(current_image,\n position,\n measurement,\n side_adjustment)\n\n for index in range(len(augmented_measurements)):\n images.append(augmented_images[index])\n measurements.append(augmented_measurements[index])\n\n X = np.array(images)\n y = np.array(measurements)\n\n yield shuffle(X, y)\n\n\ndef get_measurement_list(lines, measurement_position=3):\n \"\"\"\n Gets only the measurements from the lines.\n :param lines: Log record lines.\n :return: List of measurement values from the input log record lines.\n \"\"\"\n measurement_list = [float(line[measurement_position]) for line in lines]\n logger.info(\"Measurement average: \" + str(np.mean(measurement_list)))\n return measurement_list\n\n\ndef classify_measurements(measurements, low=-.1, high=.1):\n \"\"\"\n Obtain class values based on the values of the input measurements.\n This is then used to downsample dominant value ranges.\n :param measurements: Steering angle measurements for the all log lines.\n :param low: Lower bound of class range.\n :param high: Upper bound of class range.\n :return: List of class for each measurement- 1 if within specified range,\n 0 if not within that range.\n \"\"\"\n classes = []\n for value in measurements:\n if value >= low and value <= high:\n classes.append(1)\n else:\n classes.append(0)\n logger.info(\"1 classes: \" + str(len([x for x in classes if x == 1])))\n return classes\n\n\ndef get_binary_downsample_indexes(measurements, classes):\n \"\"\"\n Gets a specified ratio and uses that to determine indexes\n to keep by undersampling the measurements according to class\n ratios. Undersampling utilizes the imbalanced-learn package's\n RandomUnderSampler.\n :param measurements: Steering angle measurements.\n :param classes: Classes of 1's or 0's pertaining to a dominant range.\n :return: Indexes for line records to keep as a result of undersampling.\n \"\"\"\n ratio = get_binary_downsample_ratio(classes)\n logger.info(ratio)\n rus = RandomUnderSampler(ratio=ratio, return_indices=True)\n mmt_array = np.array(measurements).reshape(-1, 1)\n _, _, indexes = rus.fit_sample(mmt_array, classes)\n return indexes\n\n\ndef get_binary_downsample_ratio(classes, pct_keep_dominant=.9):\n \"\"\"\n Calculates the downsampling ratio to pass to the imbalanced-learn\n RandomUnderSampler object. If 1's are not greater than 0's, return\n the ratio of the class counts as-is. If the number of 1's is greater\n than the number of zeros, return the full length of the zero class and\n multiply the 1's class by the percentage to keep of the dominant class.\n :param classes: List of zeros or ones labeling the measurements\n :return: Ratio dict to pass to the imbalanced-learrn RandomUnderSampler.\n \"\"\"\n zeros = len([item for item in classes if item == 0])\n ones = len([item for item in classes if item == 1])\n if zeros >= ones:\n return {0: zeros, 1: ones}\n else:\n return {0: zeros, 1: int(ones*pct_keep_dominant)}\n\n\ndef binary_downsample_lines(lines):\n \"\"\"\n Downsample dominant measurements by applying a binary indicator as to\n whether lines' particular measurements fall into a particular range, and\n then reducing records from the dominant class.\n :param lines: Log record lines\n :return: Log record lines, downsampled to remove some lines from the dominant range.\n \"\"\"\n measurements = get_measurement_list(lines)\n classes = classify_measurements(measurements)\n logger.info('Len_Set_Classes: ' + str(len(set(classes))))\n if len(set(classes)) == 1:\n return lines\n else:\n indexes = get_binary_downsample_indexes(measurements, classes)\n return [lines[index] for index in indexes]\n\n\nif __name__ == '__main__':\n\n # Set TensorFlow logging so it isn't so verbose.\n os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\n # Load the necessary parameters\n args = parse_args(sys.argv[1:])\n config = load_config(args['config'])\n\n # Load data\n logger.info(\"Getting log lines...\")\n log_paths = get_file_list(config['input_path'])\n lines = []\n\n for path in log_paths:\n [lines.append(line) for line in get_log_lines(path)]\n logger.info(\"Number of lines: \" + str(len(lines)))\n\n # Downsample the lines to better balance out the 0-value measurements\n lines = binary_downsample_lines(lines)\n logger.info(\"Number of lines after downsampling: \" + str(len(lines)))\n\n # Shuffle the data once\n lines = shuffle_lines(lines)\n logger.info(\"Number of lines after shuffle: \" + str(len(lines)))\n\n\n # Train/Test Split\n validation_index = int(len(lines) * config['test_size'])\n\n lines_test = lines[-validation_index:]\n lines_train = lines[:-validation_index]\n logger.info(\"Validation set of length \" + str(len(lines_test)))\n logger.info(\"Training set of length \" + str(len(lines_train)))\n\n # Create and compile the model\n model = create_model(config['units'], gpus=config['gpus'], learning_rate=config['learning_rate'],\n dropout=config['dropout_percentage'])\n\n # Set up checkpointing callback. Keep only the best checkpoints as the model improves.\n ckpt_path = config['checkpoint_path'] + \"/augment_NVIDIA_{epoch:02d}_{val_acc:.2f}.hdf5\"\n checkpointer = ModelCheckpoint(ckpt_path, verbose=1, save_best_only=True)\n\n # Set up early stopping callback, to stop training if the validation loss hasn't\n # improved after 7 epochs.\n early_stopper = EarlyStopping(monitor='val_loss', patience=7)\n\n # Set up learning rate reducing callback, to decrease the learning rate\n # if the validation loss plateaus for 4 epochs.\n lr_reducer = ReduceLROnPlateau(monitor='val_loss', factor=.1, patience=4, min_lr=0.00000001)\n\n # Establish tensorboard callback, if configuration specified that Tensorboard should be used.\n # Add all callbacks to a list.\n if config[\"use_tensorboard\"] == \"True\":\n if not os.path.exists(args['log_dir']):\n os.makedirs(args['log_dir'])\n tensorboard = TensorBoard(log_dir=args['log_dir'], histogram_freq=1, write_images=True)\n\n callbacks = [checkpointer, early_stopper, lr_reducer, tensorboard]\n else:\n callbacks = [checkpointer, early_stopper, lr_reducer]\n\n # Train the model, using training and validation generators to feed in images and measurements.\n logger.info(\"Training the model...\")\n\n train_generator = generate_full_augment_from_lines(lines_train, config['old_image_root'],\n config['new_image_root'],\n config['side_adjustment'], config['batch_size'])\n\n validation_generator = generate_full_augment_from_lines(lines_test, config['old_image_root'],\n config['new_image_root'],\n config['side_adjustment'], config['batch_size'])\n\n model.fit_generator(train_generator, samples_per_epoch=len(lines_train), nb_epoch=config['epochs'],\n validation_data=validation_generator, nb_val_samples=len(lines_test), callbacks=callbacks,\n nb_worker=3, nb_val_worker=2)\n\n # Save out the final results of the model.\n if config['output_path'].endswith('.h5'):\n model.save(config['output_path'])\n else:\n model.save(config['output_path'] + '.h5')\n\n # Clear the tensorflow session to try to surpress one minor warning that appears,\n # and end the program run.\n k.clear_session()\n sys.exit(0)\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":23822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"163807566","text":"import multiprocessing\nimport os\nimport subprocess\n\nfrom joblib import Parallel, delayed\n\n\ndef make_all_simdirs(basedir, restarts):\n \"\"\"\n Create the dummy simulation directories according to the given restarts value.\n\n Parameters\n ----------\n basedir : str\n The base directory that will contain all dummy simulation directories.\n restarts : int\n The amount of the simulation that will be repeated.\n\n Returns\n -------\n list(str)\n A list of dummy simulation directories.\n \"\"\"\n\n simdirs = [os.path.join(basedir, \"sim{}\".format(restart)) for restart in range(restarts)]\n cmds = [\" \".join([\"mkdir\", simdir]) for simdir in simdirs]\n\n for cmd in cmds:\n os.system(cmd)\n\n return simdirs\n\n\ndef remove_all_simdirs(basedir, restarts):\n \"\"\"\n Remove the created dummy simulation directories and all the files which they contains.\n\n Parameters\n ----------\n basedir : str\n The base directory that will contain all dummy simulation directories.\n restarts : int\n The amount of the simulation that will be repeated.\n \"\"\"\n\n simdirs = [os.path.join(basedir, \"sim{}\".format(restart)) for restart in range(restarts)]\n cmds = [\" \".join([\"rm -rf\", simdir]) for simdir in simdirs]\n\n for cmd in cmds:\n os.system(cmd)\n\n\ndef run_single_sim(simulator, config_path, network_path, output_dir=\".\"):\n \"\"\"\n Run the simulation once according to the given config_path and network_path.\n Then, the result of the simulation is outputted to the output_dir.\n\n Parameters\n ----------\n simulator : str\n The path of the simulator executor \"./sim\"\n config_path : str\n The path of input \"config.xml\" file for the simulator.\n network_path : str, optional\n The path of input \"network.xml\" file for the simulator.\n output_dir : str, optional\n The directory of the simulation result which is stored, by default \".\"\n \"\"\"\n\n outfile = open(output_dir + \"/log\", \"w\")\n\n config_path = \"--configPath=\" + config_path\n network_path = \"--networkPath=\" + network_path\n output_dir = \"--outputDir=\" + output_dir\n\n args = (simulator, config_path, network_path, output_dir)\n try:\n subprocess.run(args, stdout=outfile, check=True)\n except subprocess.CalledProcessError:\n print(\"ERROR:\", args)\n\n\ndef run_parallel_multiple_sims(simdirs, simulator, config_path, network_path,\n num_cores=multiprocessing.cpu_count()):\n \"\"\"\n Run the simulation parallely.\n\n Parameters\n ----------\n simdirs : list(str)\n The list of dummy simulation directories.\n simulator : str\n The path of the simulator executor \"./sim\"\n config_path : str\n The path of input \"config.xml\" file for the simulator.\n network_path : str, optional\n The path of input \"network.xml\" file for the simulator.\n num_cores : int, optional\n The number of parallel threads to parallel the simulation process,\n by default multiprocessing.cpu_count()\n \"\"\"\n\n Parallel(n_jobs=num_cores)(delayed(run_single_sim)\n (simulator, config_path, network_path, simdir) for simdir in simdirs)\n","sub_path":"ratatoskr_tools/simulation/simulation.py","file_name":"simulation.py","file_ext":"py","file_size_in_byte":3209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"116951644","text":"import fcntl\nimport os\nimport requests\nimport urlparse\n\nimport goodeggs_parser\n\n\nclass PathQueue(object):\n\n def __init__(self, queue_directory_path):\n self.queue_directory_path = queue_directory_path\n\n def _ordered_listdir(self):\n file_names = os.listdir(self.queue_directory_path)\n\n def get_mtime(file_name):\n file_path = os.path.join(self.queue_directory_path, file_name)\n stat_results = os.stat(file_path)\n return stat_results.st_mtime\n\n return sorted(file_names, key=get_mtime)\n\n def pop(self):\n file_names = self._ordered_listdir()\n for file_name in file_names:\n file_path = os.path.join(self.queue_directory_path, file_name)\n try:\n open_mode = os.O_RDWR | os.O_CREAT | os.O_TRUNC\n fd = os.open(file_path, open_mode)\n try:\n fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)\n except (IOError, OSError):\n os.close(fd)\n else:\n os.close(fd)\n return file_name.replace('__', '/')\n except OSError:\n pass\n return None\n\n def push(self, path):\n file_name = path.replace('/', '__')\n file_path = os.path.join(self.queue_directory_path, file_name)\n with open(file_path, 'a'):\n os.utime(file_path, None)\n\n def acknowledge(self, path):\n file_name = path.replace('/', '__')\n file_path = os.path.join(self.queue_directory_path, file_name)\n os.remove(file_path)\n\n\nclass FileResults(object):\n\n def __init__(self, result_directory_path):\n self.results = []\n file_names = os.listdir(result_directory_path)\n for file_name in file_names:\n file_path = os.path.join(result_directory_path, file_name)\n url_pathname = file_name.replace('__', '/')\n self.results.append(\n {'file_path': file_path, 'url_pathname': url_pathname})\n\n\ndef crawl(queue_path, result_path, callback=None):\n path_queue = PathQueue(queue_path)\n\n while True:\n path = path_queue.pop()\n if not path:\n break\n url = urlparse.urljoin('https://www.goodeggs.com', path)\n result = requests.get(url)\n result_file_path = os.path.join(result_path, path.replace('/', '__'))\n with open(result_file_path, 'w') as result_file:\n result_file.write(result.text.encode('utf-8'))\n parser = goodeggs_parser.ItemGridParser(result.text)\n for product_path in parser.product_id_to_product_path.values():\n file_name = product_path.replace('/', '__')\n result_file_path = os.path.join(result_path, file_name)\n if not os.path.isfile(result_file_path):\n path_queue.push(product_path)\n\n path_queue.acknowledge(path)\n if callback and not callback(url):\n break\n","sub_path":"goodeggs_crawler.py","file_name":"goodeggs_crawler.py","file_ext":"py","file_size_in_byte":2645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"600583018","text":"#! /usr/bin/env python\n\n\"\"\"\nThis pipeline does the following:\n-> Combine DNA and RNA variants from mpileup, mutseq, strelka pipeline etc,\n-> Summarize variants by gene and variant level,\n-> Rerun samtools mpileup at default setting for all variant positions,\n-> Parse mpileup results to get base count info,\n-> Combining base count info for tumour-normal pairs if applicable,\n-> Adjust tumour base count according to tumour content,\n-> Perform Fisher Exact test to determine p value,\n-> Annotate variant in summary with base counts and cosmic,\n-> Indicate the caller(s) for each variant.\n\"\"\"\n\n\nimport os, stat, os.path, time, datetime, subprocess\nimport re, sys, glob, argparse, csv, shutil, fileinput\nfrom pprint import pprint\nfrom itertools import islice\nimport operator\nimport ConfigParser\nfrom collections import defaultdict\nfrom settings import SUM_SNV_HEADER\n\n\nfrom jinja2 import Environment, FileSystemLoader\nimport logging\nimport colorlog\n\nlogger = colorlog.getLogger()\nlogger.setLevel(logging.DEBUG)\nhandler = logging.StreamHandler()\nhandler.setLevel(logging.DEBUG)\nhandler.setFormatter(\n colorlog.ColoredFormatter('%(log_color)s%(levelname)s:%(name)s:%(message)s'))\nlogger.addHandler(handler)\n\n\ndef get_files(bam_vcf_files):\n \"\"\" \n Dictionary: {patient -> {status -> {file_identifier -> file_path}}} \n \"\"\"\n patient_files = dict()\n with open(bam_vcf_files, 'r') as fh:\n records = csv.DictReader(fh, delimiter='\\t')\n headers = records.fieldnames\n for line in records:\n patient = line['patient']\n status = line['status']\n try:\n patient_files[patient][status].append(line)\n except KeyError:\n if patient not in patient_files:\n patient_files[patient] = {}\n if status not in patient_files[patient]:\n patient_files[patient][status] = line\n return patient_files\n\n\ndef example_display(n, iterable):\n \"\"\" \n Return first n items of the iterable as a list! \n \"\"\"\n return list(islice(iterable, n))\n\n\ndef group_readable(file_path):\n m = os.stat(file_path).st_mode\n #other_execute = bool(m & 0001)\n #other_write = bool(m & 0002)\n #other_read = bool(m & 0004)\n group_read = bool(m & stat.S_IRGRP)\n return group_read\n\n\ndef check_files(files):\n missing_files = []\n for file in files:\n short_name = file.split(\"/\")[-1]\n if os.path.exists(file):\n readable = group_readable(file)\n if readable:\n logger.info(\"%s: OK\" % short_name)\n else:\n missing_files.append(file)\n if missing_files:\n logger.error(\"ERROR: The following files missing\")\n for file in missing_files:\n logger.info(\"Missing %s\" % file)\n sys.exit()\n\n\ndef delete_files_by_extension(extension):\n files = [ f for f in os.listdir(\".\") if f.endswith(tuple(extension))]\n for f in files:\n os.remove(f)\n\n\ndef delete_files(files):\n for f in files:\n os.remove(f)\n\n\ndef run_fisher_exact_test(Rscript_path,r_script):\n p = subprocess.Popen('%s/Rscript %s' % (Rscript_path,r_script), shell=True, stdout=subprocess.PIPE)\n output, err = p.communicate()\n #logger.info(output)\n\n\ndef count_ref_alt_bases(snp_list, base_count_file, af_file):\n \"\"\" Generate allele frequency dict to append af info to summary file \"\"\"\n snps = dict()\n for snp in snp_list:\n sl = snp.rstrip().split(':')\n chr = sl[0]\n pos = sl[1]\n ref = sl[2]\n alt = sl[3]\n key = \":\".join([chr, pos, ref])\n if key not in snps:\n snps[key] = [alt]\n else:\n snps[key].append(alt)\n # parse mpileup output to make af dict\n afs = dict()\n logger.info(\"Parsing mpileup file: %s!\" % base_count_file)\n with open (base_count_file) as fh:\n for line in fh:\n sl = line.strip().split('\\t')\n pos_ref = sl[0].split(\":\")\n chr = pos_ref[0]\n pos = pos_ref[1]\n ref = pos_ref[2]\n snp = sl[0]\n cov = sl[1]\n a, c, g, t, n = sl[2], sl[3], sl[4], sl[5], sl[6]\n d = {\"A\":a, \"C\":c, \"G\":g, \"T\":t, \"N\":n}\n ref_count = d[ref]\n d.pop(ref, None)\n alts = snps[snp]\n for alt in alts:\n alt_count = d[alt]\n adj_cov = int(alt_count)+int(ref_count)\n if (adj_cov != 0):\n af = str(\"{:.2f}\".format(float(alt_count)/adj_cov))\n else:\n af = str(\"{:.2f}\".format(float(alt_count)/int(cov)))\n value = \":\".join([alt, cov, ref_count, alt_count, af])\n try:\n afs[snp].append(value)\n except KeyError:\n afs[snp] = [value]\n # logger.info(afs)\n with open(af_file, 'wb') as opf:\n writer = csv.writer(opf, delimiter='\\t')\n for snp in afs:\n sp_snp = snp.split(':')\n for af in afs[snp]:\n sp_af = af.split(':')\n content = sp_snp + sp_af\n writer.writerow(content)\n return afs\n\n\ndef parse_snv_vcf(vcf_file, caller, impacts, gene_pats, gene_variants,\n snv_pos, snv_list, patient_status):\n logger.info(\"Parsing %s, Variant caller is: %s! \" %\n (vcf_file.split(\"/\")[-1], caller))\n with open(vcf_file, 'r') as fh:\n ## Following line is useful for testing the script\n #fh = [next(fh) for x in xrange(350)]\n for line in fh:\n if (not line.startswith(\"#\")):\n sl = line.strip().split(\"\\t\")\n Info = sl[7]\n if (not Info.startswith(\"INDEL\") and\n \"EFF=\" in Info and\n any(x in Info for x in impacts)):\n splitInfo = Info.split(\";\")\n # get gmaf value\n try:\n gmaf = [j for j in splitInfo if\n j.startswith(\"GMAF=\")][0].split(\"=\")[1]\n except:\n gmaf = \"gmaf_unknown\"\n transcripts = [i for i in splitInfo if\n i.startswith(\"EFF=\")][0].split(\"=\")[1].split(\",\")\n rs_cos_id = sl[2]\n chr, start, ref = sl[0], sl[1], sl[3]\n alts = sl[4].split(\",\")\n snv_pos.append(\"\\t\".join([chr, start]))\n for alt in alts:\n snv = \":\".join([chr, start, ref, alt])\n snv_list.append(snv)\n snp_id_tmp = rs_cos_id.split(\";\")[0]\n if snp_id_tmp.startswith(\"rs\"):\n snp_id = snp_id_tmp\n else:\n snp_id = \"novel_snp\"\n try:\n cosmic_id = rs_cos_id.split(\";\")[1]\n except:\n if snp_id_tmp.startswith(\"COS\"):\n cosmic_id = snp_id_tmp\n else:\n cosmic_id = \"not_in_cosmic64\"\n selected_transcripts = [k for k in transcripts\n if any(x in k for x in impacts)]\n # pick the first transcript to get the gene name\n trans_details = selected_transcripts[0]\n gene = trans_details.split(\"|\")[5]\n if (gene == \"\"):\n gene = \"INTERGENIC\"\n # make gene -> patient dict to count how many patients\n # have variant in this gene\n try:\n gene_pats[gene].append(patient_status)\n except:\n gene_pats[gene] = [patient_status]\n details = \":\".join([snp_id, cosmic_id, gmaf, trans_details, caller])\n # put all relevant info into a triple nested dictionary:\n # gene -> snv -> patient -> details\n try:\n gene_variants[gene][snv][patient_status].append(details)\n except:\n gene_variants[gene][snv][patient_status] = [details]\n return [gene_pats, gene_variants, snv_pos, snv_list]\n\n\ndef summarize_snvs(patient_files, sum_header_wn_tmp, hm_sum_wn_tmp, hm_impacts):\n \"\"\"\n Generate triple nested dictionary for each\n Combine all the SNV positions from each pileline and patient status for pileup\n Positions = mpileup + strelka + primary + relaspe\n Get snp list for all patients\n Summarize all SNVs with high or moderate or low or modifier impact\n Annotate as if a SNV in mpileup or/and strelka\n pool all snv positions from various vcf files: single, paired, mutseq, strelka\n if a variant exists in one tissue, time point, check all samples from the same patient\n \"\"\"\n tree = lambda: defaultdict(tree)\n hm_variants_dict = tree()\n hm_gene_dict = dict()\n patient_snv = dict()\n patient_callers = dict()\n snv_pos_files = []\n for patient in patient_files:\n logger.info(\"Parsing all vcf files related to: %s\" % patient)\n snv_pos_file = \".\".join([patient, \"vcf.snp.pos\"])\n snv_pos_files.append(snv_pos_file)\n snv_pos = []\n snv_list = []\n for status in patient_files[patient]:\n if (\"normal\" not in status):\n status_vcfs = patient_files[patient][status]\n logger.info(\"Parsing vcf files related to: %s, %s\" %\n (patient, status))\n patient_status = \"_\".join([patient, status])\n for key in status_vcfs:\n caller = key.replace('_vcf', '').replace('_snv', '')\n vcf = status_vcfs[key]\n if 'vcf' in key and 'indel' not in key and vcf != 'NA':\n # print(caller, vcf)\n try:\n patient_callers[patient_status].append(caller)\n except KeyError:\n patient_callers[patient_status] = [caller]\n two_dicts = parse_snv_vcf(vcf, caller, hm_impacts,\n hm_gene_dict, hm_variants_dict,\n snv_pos, snv_list, patient_status)\n hm_gene_dict = two_dicts[0]\n hm_variants_dict = two_dicts[1]\n snv_pos = two_dicts[2]\n snv_list = two_dicts[3]\n snv_pos = list(set(snv_pos))\n snv_list = list(set(snv_list))\n patient_snv[patient] = snv_list\n with open(snv_pos_file, 'w') as pos_writer:\n for snv_coord in sorted(snv_pos):\n pos_writer.write(snv_coord)\n pos_writer.write(\"\\n\")\n #logger.info(\"Example patient snv dict are: \\n\")\n # n_items = example_display(2, patient_snv.iteritems())\n # logger.info(n_items)\n write_summary(hm_variants_dict, hm_gene_dict, hm_sum_wn_tmp,\n sum_header_wn_tmp, patient_callers, patient_files)\n return [patient_snv, snv_pos_files]\n\n\ndef write_summary(variants_dict, gene_dict, summary_file,\n sum_header_wn_tmp, patient_callers, patient_files):\n writer = open(summary_file, 'w')\n writer.write(\"\\t\".join(sum_header_wn_tmp))\n writer.write(\"\\n\")\n logger.info(\"Writing variants_dict into summary file: %s\" % summary_file)\n for gene in variants_dict:\n short_patient = [i.split(\"_\")[0] for i in gene_dict[gene]]\n num_patients_gene_level = len(list(set(short_patient)))\n numsnvs = len(variants_dict[gene].keys())\n for snv in variants_dict[gene]:\n patient_statuses_snv_level = list(set([i for i in\n variants_dict[gene][snv].keys()]))\n patients_snv_level = [i.split(\"_\")[0] for\n i in patient_statuses_snv_level]\n num_patients_snv_level = len(patients_snv_level)\n snv_details = []\n # logger.info(\"patients_snv_level are: %s\" % patients_snv_level)\n # all patient status combinations\n all_patient_statuses = []\n for pat in patients_snv_level:\n for sta in patient_files[pat]:\n if not re.search(r'normal', sta, re.M|re.I):\n all_patient_statuses.append( \"_\".join([pat, sta]))\n all_patient_statuses = list(set(all_patient_statuses))\n # print('bbbbbbbbb')\n patient_statuses_not_called = list(set(all_patient_statuses)-\n set(patient_statuses_snv_level))\n # logger.info(\"all_patient_statuses is %s, %s, %s, %s\" %\n # (gene, all_patient_statuses, patient_statuses_snv_level,\n # patient_statuses_not_called))\n for patient in variants_dict[gene][snv]:\n chr, start, ref, alt = snv.split(':')\n # anno_details: rs8473:COSM1128106:0.4748:NON_SYNONYMOUS_\n # CODING(MODERATE|MISSENSE|Aaa/Gaa|K2857E|2896|MKI67|protein_\n # coding|CODING|ENST00000368653|13|1):pileup\n anno_details_all = variants_dict[gene][snv][patient]\n callers = [i.split(\":\")[-1] for i in anno_details_all]\n anno_details = list(set(anno_details_all))[0].split(\":\")\n rs_id = anno_details[0]\n cosmic_id = anno_details[1]\n gmaf = anno_details[2]\n snp_eff = anno_details[3]\n # see if variant called by both mpileup and strelka etc\n callers_run = patient_callers[patient]\n (in_paired_mpileup,\n in_mutseq, in_strelka,\n in_DNA_single_mpileup,\n in_RNA_single_mpileup) = determine_callers(callers_run, callers)\n content = \"\\t\".join([gene, str(num_patients_gene_level),\n str(numsnvs), chr, start, ref, alt,\n str(num_patients_snv_level), patient,\n rs_id, gmaf, cosmic_id, snp_eff,\n in_DNA_single_mpileup, in_paired_mpileup,\n in_mutseq, in_strelka, in_RNA_single_mpileup])\n writer.write(content)\n writer.write(\"\\n\")\n # include variant for all statuses as long it is called in status\n for patient_status in patient_statuses_not_called:\n # patient = patient_status\n callers_run = patient_callers[patient_status]\n callers = []\n (in_paired_mpileup,\n in_mutseq, in_strelka,\n in_DNA_single_mpileup,\n in_RNA_single_mpileup) = determine_callers(callers_run, callers)\n content = '\\t'.join([gene, str(num_patients_gene_level),\n str(numsnvs), chr, start, ref, alt,\n str(num_patients_snv_level), patient_status,\n rs_id, gmaf, cosmic_id, snp_eff,\n in_DNA_single_mpileup, in_paired_mpileup,\n in_mutseq, in_strelka, in_RNA_single_mpileup])\n writer.write(content)\n writer.write(\"\\n\")\n\n\ndef determine_callers(callers_run, snv_callers):\n # callers_run are callers that have run for a patient_status bam\n # snv_callers are the callers reporting this snv\n in_paired_mpileup = \"not_in_paired_mpileup\"\n in_mutseq = \"not_in_mutseq\"\n in_strelka = \"not_in_strelka\"\n in_DNA_single_mpileup = \"not_in_DNA_single_mpileup\"\n in_RNA_single_mpileup = \"not_in_RNA_single_mpileup\"\n if 'strelka' in callers_run:\n if 'strelka' in snv_callers:\n in_strelka = \"in_strelka\"\n else:\n # print 'ooooooooooo', callers_run, snv_callers\n in_strelka = \"strelka_not_run\"\n if 'paired_mpileup' in callers_run:\n if 'paired_mpileup' in snv_callers:\n in_paired_mpileup = 'in_paired_mpileup'\n else:\n in_paired_mpileup = 'paired_mpileup_not_run'\n if 'DNA_single' in callers_run:\n if 'DNA_single' in snv_callers:\n in_DNA_single_mpileup = 'in_DNA_single_mpileup'\n else:\n in_DNA_single_mpileup = 'DNA_single_mpileup_not_run'\n if 'RNA_single' in callers_run:\n if 'RNA_single' in snv_callers:\n in_RNA_single_mpileup = 'in_RNA_single_mpileup'\n else:\n in_RNA_single_mpileup = 'RNA_single_mpileup_not_run'\n if 'mutseq' in callers_run:\n if 'mutseq' in snv_callers:\n in_mutseq = 'in_mutseq'\n else:\n in_mutseq = 'mutseq_not_run'\n return (in_paired_mpileup, in_mutseq, in_strelka,\n in_DNA_single_mpileup, in_RNA_single_mpileup)\n\n\ndef calculate_af (cov, refC, altC):\n # ref + alt <= cov because low qaulity bases filtered\n adj_cov = int(refC) + int(altC)\n if (adj_cov != 0):\n af = \"{:.2f}\".format(float(altC)/adj_cov)\n elif (int(cov) != 0):\n af = \"{:.2f}\".format(float(altC)/int(cov))\n else:\n af = 0.00\n return af\n\n\ndef summarize_indels(patient_files, sum_header_wn_tmp,\n hm_sum_wn_tmp, hm_impacts):\n tree = lambda: defaultdict(tree)\n hm_variants_dict = tree() \n hm_gene_dict = dict()\n hm_indel_dict = dict()\n patient_callers = dict()\n modifier_indel_dict = dict()\n for patient in patient_files:\n logger.info(\"Parsing vcf files related to %s\" % patient)\n for status in patient_files[patient]:\n if (\"normal\" not in status):\n status_vcfs = patient_files[patient][status]\n logger.info(\"Parsing vcf related to %s %s\" %\n (patient, status))\n strelka_indel_vcf = status_vcfs['strelka_indel_vcf']\n DNA_single_vcf = status_vcfs['DNA_single_vcf']\n RNA_single_vcf = status_vcfs['RNA_single_vcf']\n paired_mpileup_vcf = status_vcfs['paired_mpileup_vcf']\n #mutseq does not have indel result\n # mutseq_snv_vcf = status_vcfs['mutseq_snv_vcf']\n patient_status = \"_\".join([patient, status])\n patient_status = \"_\".join([patient, status])\n for key in status_vcfs:\n # do not parse mutseq or strelka snv vcfs\n caller = key.replace('_vcf', '').replace('_indel', '')\n vcf = status_vcfs[key]\n if 'vcf' in key and 'strelka_indel' in key and vcf != 'NA':\n try:\n patient_callers[patient_status].append(caller)\n except KeyError:\n patient_callers[patient_status] = [caller]\n two_dicts = parse_strelka_indel(vcf, caller, hm_impacts,\n hm_gene_dict, hm_variants_dict,\n patient_status)\n hm_gene_dict, hm_variants_dict = two_dicts\n elif ('vcf' in key and 'strelka' not in key and\n 'mutseq' not in key and 'snv' not in key and\n vcf != 'NA'):\n try:\n patient_callers[patient_status].append(caller)\n except KeyError:\n patient_callers[patient_status] = [caller]\n two_dicts = parse_mpileup_indel(vcf, caller, hm_impacts,\n hm_gene_dict, hm_variants_dict,\n patient_status)\n hm_gene_dict, hm_variants_dict = two_dicts\n write_indel_summary(hm_variants_dict, hm_gene_dict, hm_sum_wn_tmp,\n sum_header_wn_tmp, patient_callers, patient_files)\n\n\ndef parse_mpileup_indel(vcf_file, caller, impacts,\n gene_patients, gene_variants, patient_status):\n logger.info(\"%s variant caller is: %s! \" % (vcf_file.split(\"/\")[-1], caller))\n with open(vcf_file, 'r') as fh:\n # Following line is useful for testing the script\n # pileup header 153 lines\n # fh = [next(fh) for x in xrange(200)]\n for line in fh:\n if not line.startswith(\"#\"):\n sl = line.strip().split(\"\\t\")\n Info = sl[7]\n if (Info.startswith(\"INDEL\") and\n \"EFF=\" in Info and\n any(x in Info for x in impacts)):\n #logger.info(Info, impacts)\n splitInfo = Info.split(\";\")\n cov = [i for i in splitInfo if\n i.startswith(\"DP=\")][0].split(\"=\")[1]\n refC_altC = [i for i in splitInfo if\n i.startswith(\"DP4=\")][0].split(\"=\")[1].split(\",\")\n tmp_refC = refC_altC[0:2]\n tmp_altC = refC_altC[2:]\n refC = sum(int(i) for i in tmp_refC)\n altC = sum(int(i) for i in tmp_altC)\n af = calculate_af (cov, refC, altC)\n mpileup_cov = [cov, str(refC), str(altC), str(af)]\n strelka_cov = [\"na\", \"na\", \"na\", \"na\", \"na\", \"na\", \"na\", \"na\"]\n cov_info = \"\\t\".join(mpileup_cov + strelka_cov)\n try:\n gmaf = [j for j in splitInfo if\n j.startswith(\"GMAF=\")][0].split(\"=\")[1]\n except:\n gmaf = \"gmaf_unknown\"\n transcripts = [i for i in splitInfo if\n i.startswith(\"EFF=\")][0].split(\"=\")[1].split(\",\")\n rs_cos_id = sl[2]\n chromosome, start, ref = sl[0], sl[1], sl[3]\n alts = sl[4].split(\",\")\n for alt in alts:\n indel = \":\".join([chromosome, start, ref, alt])\n snp_id_tmp = rs_cos_id.split(\";\")[0]\n if snp_id_tmp.startswith(\"rs\"):\n snp_id = snp_id_tmp\n else:\n snp_id = \"novel_snp\"\n try:\n cosmic_id = rs_cos_id.split(\";\")[1]\n except:\n if snp_id_tmp.startswith(\"COS\"):\n cosmic_id = snp_id_tmp\n else:\n cosmic_id = \"not_in_cosmic64\"\n selected_transcripts = [k for k in transcripts if\n any(x in k for x in impacts)]\n # pick the first transcript to get the gene name\n trans_details = selected_transcripts[0]\n gene = trans_details.split(\"|\")[5]\n if (gene == \"\"):\n gene = \"INTERGENIC\"\n # make gene -> patient dict to count\n # how many patients have variant in this gene\n try:\n gene_patients[gene].append(patient_status)\n except:\n gene_patients[gene] = [patient_status]\n details = \":\".join([snp_id, cosmic_id, gmaf,\n trans_details, cov_info, caller])\n # put all relevant info into a triple nested dictionary:\n # gene -> snv -> patient -> details\n try:\n gene_variants[gene][indel][patient_status].append(details)\n except:\n gene_variants[gene][indel][patient_status] = [details]\n return [gene_patients, gene_variants]\n\n\ndef parse_strelka_indel(vcf_file, caller, impacts, gene_pats,\n gene_variants, patient_status):\n logger.info(\"%s variant caller is: %s!\" % (vcf_file.split(\"/\")[-1], caller))\n with open(vcf_file, 'r') as fh:\n # Following line is useful for testing the script\n # strelka header lines 324\n # fh = [next(fh) for x in xrange(300)]\n for line in fh:\n if (not line.startswith(\"#\")):\n sl = line.strip().split(\"\\t\")\n Info = sl[7]\n if (\"EFF=\" in Info) and any(x in Info for x in impacts):\n # use tier1 counts, which is with mapping quality >40\n normal_info = sl[9].split(\":\")\n tumor_info = sl[10].split(\":\")\n splitInfo = Info.split(\";\")\n nor_cov = normal_info[0]\n nor_refC = normal_info[2].split(\",\")[0]\n nor_indelC = normal_info[3].split(\",\")[0]\n tum_cov = tumor_info[0]\n tum_refC = tumor_info[2].split(\",\")[0]\n tum_indelC = tumor_info[3].split(\",\")[0]\n #nor_adj_cov = int(nor_refC) + int(nor_indelC)\n #tum_adj_cov = int(tum_refC) + int(tum_indelC)\n nor_af = calculate_af (nor_cov, nor_refC, nor_indelC)\n tum_af = calculate_af (tum_cov, tum_refC, tum_indelC)\n mpileup_cov = [\"na\", \"na\", \"na\", \"na\"]\n strelka_cov = [nor_cov, nor_refC, nor_indelC,\n str(nor_af), tum_cov, tum_refC,\n tum_indelC, str(tum_af)]\n cov_info = \"\\t\".join(mpileup_cov + strelka_cov)\n try:\n gmaf = [j for j in splitInfo if\n j.startswith(\"GMAF=\")][0].split(\"=\")[1]\n except:\n gmaf = \"gmaf_unknown\"\n transcripts = [i for i in splitInfo if\n i.startswith(\"EFF=\")][0].split(\"=\")[1].split(\",\")\n rs_cos_id = sl[2]\n chr, start, ref = sl[0], sl[1], sl[3]\n alts = sl[4].split(\",\")\n for alt in alts:\n indel = \":\".join([chr, start, ref, alt])\n snp_id_tmp = rs_cos_id.split(\";\")[0]\n if snp_id_tmp.startswith(\"rs\"):\n snp_id = snp_id_tmp\n else:\n snp_id = \"novel_snp\"\n try:\n cosmic_id = rs_cos_id.split(\";\")[1]\n except:\n if snp_id_tmp.startswith(\"COS\"):\n cosmic_id = snp_id_tmp\n else:\n cosmic_id = \"not_in_cosmic64\"\n selected_transcripts = [k for k in transcripts\n if any(x in k for x in impacts)]\n trans_details = selected_transcripts[0]\n gene = trans_details.split(\"|\")[5]\n if (gene == \"\"):\n gene = \"INTERGENIC\"\n try:\n gene_pats[gene].append(patient_status)\n except:\n gene_pats[gene] = [patient_status]\n details = \":\".join([snp_id, cosmic_id, gmaf,\n trans_details, cov_info, caller])\n try:\n gene_variants[gene][indel][patient_status].append(details)\n except:\n gene_variants[gene][indel][patient_status] = [details]\n return [gene_pats, gene_variants]\n\n\n\ndef write_indel_summary(variants_dict, gene_dict, summary_file,\n sum_header_wn_tmp, patient_callers, patient_files):\n writer = open(summary_file, 'w')\n writer.write(\"\\t\".join(sum_header_wn_tmp))\n writer.write(\"\\n\")\n logger.info(\"Writing variants_dict into %s\" % summary_file)\n for gene in variants_dict:\n short_patient = [i.split(\"_\")[0] for i in gene_dict[gene]]\n num_patients_gene_level = len(list(set(short_patient)))\n numSNVs = len(variants_dict[gene].keys())\n for snv in variants_dict[gene]:\n patients_snv_level = [i.split(\"_\")[0] for i in\n variants_dict[gene][snv]]\n num_patients_SNV_level = len(list(set(patients_snv_level)))\n snv_details = []\n for patient in variants_dict[gene][snv]:\n # snv_details: 10:64927823:C:G\n chr, start, ref, alt = snv.split(\":\")\n # #anno_details: rs8473:COSM1128106:0.4748:NON_SYNONYMOUS_\n # CODING(MODERATE|MISSENSE|Aaa/Gaa|K2857E|2896|MKI67|protein_\n # coding|CODING|ENST00000368653|13|1):pileup\n anno_details_all = variants_dict[gene][snv][patient]\n if (\"strelka\" in anno_details_all):\n anno_details = [i for i in anno_details_all\n if \"strelka\" in i][0].split(\":\")\n else:\n callers = [i.split(\":\")[-1] for i in anno_details_all]\n # pick highest ref+alt if called both in DNA and RNA\n multi_cov = [i.split(':')[4] for i in anno_details_all]\n multi_ref_alt= [int(i.split('\\t')[1]) +\n int(i.split('\\t')[2])\n for i in multi_cov]\n index, value = max(enumerate(multi_ref_alt),\n key=operator.itemgetter(1))\n anno_details = anno_details_all[index].split(':')\n (rs_id, cosmic_id, gmaf,\n snp_eff, cov_info ) = anno_details[0:5]\n # see if variant called by both mpileup and strelka\n callers_run = patient_callers[patient]\n (in_paired_mpileup,\n in_mutseq, in_strelka,\n in_DNA_single_mpileup,\n in_RNA_single_mpileup) = determine_callers(callers_run,\n callers)\n content = \"\\t\".join([gene, str(num_patients_gene_level),\n str(numSNVs), chr, start, ref, alt,\n str(num_patients_SNV_level), patient,\n rs_id, gmaf, cosmic_id, snp_eff,\n in_DNA_single_mpileup,\n in_paired_mpileup,\n in_strelka, in_RNA_single_mpileup,\n cov_info])\n\n writer.write(content)\n writer.write(\"\\n\")\n\n\ndef adjust_allele_frequency(type, com_af_files,patient_files):\n tc_key = \"_\".join([type, \"tc\"])\n for file in com_af_files:\n file = file.strip()\n sp_f = re.split('[.]',file)\n patient =sp_f[0]\n status = sp_f[1]\n pat_status = \"_\".join([patient, status])\n af_aj_file = file + \".adjusted\"\n writer = csv.writer(open(af_aj_file, 'wb'),delimiter='\\t')\n with open (file) as handle:\n for line in handle:\n sl = line.rstrip().split('\\t')\n n_totC = int(sl[4])\n n_refC = int(sl[5])\n n_altC = int(sl[6])\n t_totC = int(sl[9])\n t_refC = int(sl[10])\n t_altC = int(sl[11])\n n_af = float(sl[7])\n t_af = float(sl[12])\n # skip adjustment for second low frequency allele\n tlow_totC = t_refC + t_altC\n tc_tmp = patient_files[patient][status][tc_key]\n if ( n_totC > 0 and t_totC > 0 and\n (tlow_totC > 0.7*t_totC) and\n (\"unknow\" not in tc_tmp) ):\n nlz_factor = float(float(t_totC)/n_totC)\n tc = float(int(tc_tmp)/100.0)\n n_nlz_refC = n_refC*nlz_factor\n n_nlz_altC = n_altC*nlz_factor\n t_aj_ref = float(t_refC-n_nlz_refC*(1-tc))/tc\n t_aj_alt = float(t_altC-n_nlz_altC*(1-tc))/tc\n if (t_aj_ref >= 0 and t_aj_alt >= 0):\n t_aj_tot = t_aj_ref + t_aj_alt\n if t_aj_tot != 0:\n t_aj_af = t_aj_alt/t_aj_tot\n if t_aj_af >= 1:\n t_aj_af =1\n elif t_aj_af<0:\n t_aj_af = 0\n else:\n t_aj_tot, t_aj_ref = t_totC, t_refC\n t_aj_alt, t_aj_af = t_altC, t_af\n elif (t_aj_ref < 0 and t_aj_alt >= 0):\n t_aj_alt = t_aj_alt - t_aj_ref\n t_aj_ref = 0\n t_aj_tot = t_aj_ref + t_aj_alt\n if t_aj_tot != 0:\n t_aj_af = t_aj_alt/t_aj_tot\n if t_aj_af >= 1:\n t_aj_af =1\n elif t_aj_af < 0:\n t_aj_af = 0\n else:\n t_aj_tot, t_aj_ref = t_totC, t_refC\n t_aj_alt, t_aj_af = t_altC, t_af\n elif (t_aj_ref >= 0 and t_aj_alt < 0):\n t_aj_ref = t_aj_ref - t_aj_alt\n t_aj_alt = 0\n t_aj_tot = t_aj_ref + t_aj_alt\n if t_aj_tot != 0:\n t_aj_af = t_aj_alt/t_aj_tot\n if t_aj_af >= 1:\n t_aj_af = 1\n elif t_aj_af < 0:\n t_aj_af = 0\n else:\n t_aj_tot, t_aj_ref = t_totC, t_refC\n t_aj_alt, t_aj_af = t_altC, t_af\n else:\n t_aj_tot, t_aj_ref = t_totC, t_refC\n t_aj_alt, t_aj_af = t_altC, t_af\n try:\n tc = float(int(tc_tmp)/100.0)\n except:\n tc = \"tc_unknown\"\n t_aj_tot = \"{:.1f}\".format( float(t_aj_tot) )\n t_aj_ref = \"{:.1f}\".format( float(t_aj_ref) )\n t_aj_alt = \"{:.1f}\".format( float(t_aj_alt) )\n t_aj_af = \"{:.2f}\".format( float(t_aj_af) )\n writer.writerow([sl[0],sl[1],sl[2],sl[3],\n sl[4],sl[5],sl[6],sl[7],sl[8],\n t_totC, t_refC, t_altC, t_af,\n t_aj_tot,t_aj_ref,t_aj_alt,t_aj_af,tc])\n logger.info(\"Finishing af adjustment for: %s\" % (pat_status))\n\n\ndef make_patient_wn_af_dict(af_files):\n patient_af_dict = dict()\n for file in af_files:\n if (file != \"NA\"):\n patient = \"_\".join(re.split('[.]', file)[:2])\n with open(file) as f:\n next( f )\n for line in f:\n sl = [i.strip() for i in line.rstrip().split('\\t')]\n chr, pos, ref, alt = sl[1], sl[2], sl[3], sl[4]\n key = \"_\".join([patient, chr, pos, ref, alt])\n n_cov, n_ref, n_alt, n_af = sl[5], sl[6], sl[7], sl[8]\n t_cov, t_ref, t_alt, t_af = sl[10], sl[11], sl[12], sl[13]\n n_af = \"{:.2f}\".format( float(n_af) )\n t_af = \"{:.2f}\".format( float(t_af) )\n ajt_cov, ajt_ref, ajt_alt, ajt_af = sl[14], sl[15], sl[16], sl[17]\n ajt_cov = \"{:.1f}\".format( float(ajt_cov) )\n ajt_ref = \"{:.1f}\".format( float(ajt_ref) )\n ajt_alt = \"{:.1f}\".format( float(ajt_alt) )\n ajt_af = \"{:.2f}\".format( float(ajt_af) )\n p_value, tc = sl[19], sl[18]\n value = \",\".join([n_cov, n_ref, n_alt, n_af,\n t_cov, t_ref, t_alt, t_af,\n ajt_cov, ajt_ref, ajt_alt, ajt_af,\n p_value])\n try:\n patient_af_dict[key].append(value)\n except KeyError:\n patient_af_dict[key] = [value]\n return patient_af_dict\n\n\ndef make_patient_non_af_dict(af_files):\n patient_af_dict = dict()\n for file in af_files:\n if (file != \"NA\"):\n patient = \"_\".join(re.split('[.]', file)[:2])\n with open(file) as f:\n for line in f:\n sl = [i.strip() for i in line.rstrip().split('\\t')]\n chr, pos, ref, alt = sl[0], sl[1], sl[2], sl[3]\n key = \"_\".join([patient, chr, pos, ref, alt])\n t_cov, t_ref, t_alt, t_af = sl[4], sl[5], sl[6], sl[7]\n value = \",\".join([t_cov, t_ref, t_alt, t_af])\n try:\n patient_af_dict[key].append(value)\n except KeyError:\n patient_af_dict[key] = [value]\n return patient_af_dict\n\n\ndef qsub_scripts(scripts):\n \"\"\" qsub scripts \"\"\"\n wkdir = os.getcwd()\n for script in scripts:\n p = subprocess.Popen('ssh m0001 \\\"cd %s; qsub %s\\\"' %\n (wkdir, script), shell=True,\n stdout=subprocess.PIPE)\n output, err = p.communicate()\n\n\ndef parse_pileup_output(patient_files, patient_snv_wn, patient_snv_non):\n af_files = dict()\n com_af_files = dict()\n af_dicts = dict()\n data_types = [\"DNA\", \"RNA\"]\n for type in data_types:\n af_files[type] = []\n com_af_files[type] = []\n af_dicts[type] = dict()\n for patient in patient_files:\n if (\"normal\" in patient_files[patient]):\n snp_list = patient_snv_wn[patient]\n else:\n snp_list = patient_snv_non[patient]\n # get base count and af for all samples of a patient\n for status in patient_files[patient]:\n bam_types = dict()\n DNA_bam = patient_files[patient][status]['DNA_bam']\n RNA_bam = patient_files[patient][status]['RNA_bam']\n bam_types[\"DNA\"] = DNA_bam\n bam_types[\"RNA\"] = RNA_bam\n for type in bam_types:\n if (bam_types[type] != \"NA\"):\n #for type in data_types:\n base_count_file = \".\".join([patient, status,\n type, \"pileup.AFcounts\"])\n af_file = \".\".join([patient, status,\n type, \"pileup.AFcounts.af\"])\n af_files[type].append( af_file )\n # variant bp count dict for primary, relapse, and normal\n af_dict = count_ref_alt_bases(snp_list,\n base_count_file,\n af_file)\n # '5:131892979:G': ['G:88:1:1:0.01']\n try:\n #logger.info(patient, status)\n af_dicts[type][patient][status] = af_dict\n except KeyError:\n if patient not in af_dicts[type]:\n af_dicts[type][patient] = {}\n if status not in af_dicts[type][patient]:\n af_dicts[type][patient][status] = af_dict\n nor_bams = dict()\n if (\"normal\" in patient_files[patient]):\n nor_bams[\"DNA\"] = patient_files[patient][\"normal\"]['DNA_bam']\n nor_bams[\"RNA\"] = patient_files[patient][\"normal\"]['RNA_bam']\n else:\n nor_bams[\"DNA\"] = \"NA\"\n nor_bams[\"RNA\"] = \"NA\"\n for type in nor_bams:\n if (nor_bams[type] != \"NA\"):\n n_af_dict = af_dicts[type][patient][\"normal\"]\n for status in patient_files[patient]:\n # if tumor bam exist\n bam_key = \"_\".join([type, \"bam\"])\n t_bam = patient_files[patient][status][bam_key]\n if (not status == \"normal\") and (t_bam != \"NA\"):\n logger.info(\"merging %s %s %s with its normal!\" %\n (patient, status, type))\n com_af_file = \".\".join([patient, status,\n type, \"af.combined\"])\n com_af_files[type].append(com_af_file)\n t_af_dict = af_dicts[type][patient][status]\n with open(com_af_file, 'wb') as opf:\n writer = csv.writer(opf, delimiter='\\t')\n #logger.info(\"snp_list is: \", snp_list)\n for snp in snp_list:\n sp_snp = snp.split(':')\n chr, start, ref = sp_snp[0], sp_snp[1], sp_snp[2]\n alt = sp_snp[3]\n af_key = \":\".join([chr, start, ref])\n if (\"no_matched_normal\" not in n_af_dict):\n try:\n normal_afs = n_af_dict[af_key]\n normal_af = [i for i in normal_afs\n if i[0] == alt][0].split(\":\")\n except KeyError:\n normal_af = [\"N\", \"0\", \"0\", \"0\", \"0\"]\n else:\n alt_tag = \"_\".join([\"no\", type, \"normal\"])\n normal_af = [alt_tag, \"0\", \"0\", \"0\", \"0\"]\n n_totC, n_refC, n_altC, n_af = normal_af[1:5]\n try:\n tumour_afs = t_af_dict[af_key]\n tumour_af = [i for i in tumour_afs if\n i[0] == alt][0].split(\":\")\n except KeyError:\n tumour_af = [\"N\", \"0\", \"0\", \"0\", \"0\"]\n t_totC, t_refC, t_altC, t_af = tumour_af[1:5]\n t_alt = tumour_af[0]\n writer.writerow([chr, start, ref, alt,\n n_totC, n_refC, n_altC, n_af,\n t_alt,\n t_totC, t_refC, t_altC, t_af])\n else:\n n_af_dict = dict()\n n_af_dict[\"no_matched_normal\"] = \"True\"\n logger.info(\"no %s %s normal bam, merging not required!\" %\n (patient, type))\n return com_af_files\n\n\ndef detect_cluster_job_status(completeion_file_list):\n completed = False\n for file in completeion_file_list:\n if (os.path.exists(file)):\n completed = True\n else:\n completed = False\n break\n return completed\n\n\ndef detect_cluster_jobs(complete_stamps):\n \"\"\" detect if job on cluster finised \"\"\"\n job_status = False\n logger.info(\"Waiting for cluster jobs to finish!\\n\")\n while (not job_status):\n time.sleep(10)\n job_status = detect_cluster_job_status(complete_stamps)\n logger.info(\"All cluster jobs finished? %s\\n\" % job_status)\n\n\ndef make_pileup_scripts(patient_files):\n \"\"\" genearate pileup scripts, which also parses pileup results! \"\"\"\n pileup_scripts = []\n pileup_stamps = []\n for patient in patient_files:\n for status in patient_files[patient]:\n snv_positions = \".\".join([patient, \"vcf.snp.pos\"])\n DNA_bam = patient_files[patient][status]['DNA_bam']\n RNA_bam = patient_files[patient][status]['RNA_bam']\n if (DNA_bam != 'NA'):\n script = make_script(patient, status, 'DNA',\n snv_positions, DNA_bam)\n pileup_scripts.append(script)\n pileup_stamp = \"_\".join([patient, status, 'DNA',\n \"pileup.complete\"])\n pileup_stamps.append( pileup_stamp )\n if (RNA_bam != 'NA'):\n script = make_script(patient, status, 'RNA',\n snv_positions, RNA_bam)\n pileup_scripts.append(script)\n pileup_stamp = \"_\".join([patient, status, 'RNA',\n \"pileup.complete\"])\n pileup_stamps.append( pileup_stamp )\n\n return [pileup_scripts, pileup_stamps]\n\n\ndef make_script(patient, status, data,\n mpileup_positions, bam_file):\n name = \".\".join([patient, status, data])\n pileup_script = \".\".join([name, \"pileup.sh\"])\n mpileup_output = \".\".join([name, \"pileup\"])\n mpileup_AFcounts = \".\".join([name, \"pileup.AFcounts\"])\n mpileup_stamp = \".\".join([name, \"_pileup.complete\"])\n # patient_status = \"_\".join([patient, status, data])\n log_file = \"variant_summary.log\"\n jinja2_env = Environment(loader=FileSystemLoader([os.getcwd()]),\n trim_blocks=True)\n template = jinja2_env.get_template('template.sh')\n with open(pileup_script, 'wb') as opf:\n content = template.render(mpileup_output = mpileup_output,\n mpileup_AFcounts = mpileup_AFcounts,\n mpileup_stamp = mpileup_stamp,\n log_file = log_file,\n mpileup_positions = mpileup_positions,\n bam_file = bam_file,\n patient_status = name)\n opf.write(content)\n logger.info('templated {0}'.format(pileup_script))\n return pileup_script\n\n\ndef make_af_dict(patient_files):\n \"\"\"\n Reading in af files for all patients and making af_dicts:\n {'DNA': [{'Axxxxx_unknown_10_100148176_A_G': ['2,0,2,1.00,2,0,2,1.00,2.0,0.0,2.0,1.00,1.000'],\n 'Axxxxx_unknown_X_99657566_G_T': ['4,2,2,0.50,4,2,2,0.50,4.0,2.0,2.0,0.50,1.000'],\n 'Axxxxx_unknown_X_99941705_T_C': ['5,0,5,1.00,5,0,5,1.00,5.0,0.0,5.0,1.00,1.000']},\n {}],\n 'RNA': [{},\n {'Axxxxx_unknown_10_100148176_A_G': ['2,0,2,1.00'],\n 'Axxxxx_unknown_X_99941705_T_C': ['5,0,5,1.00']}]}\n \"\"\"\n AFcounts_afs_wn = dict()\n af_dicts = dict()\n types = [\"DNA\", \"RNA\"]\n for type in types:\n bam_key = \"_\".join([type, \"bam\"])\n affs_wn = []\n affs_non = []\n af_dicts[type] = []\n AFcounts_afs_wn[type] = []\n for patient in patient_files:\n # see if DNA or RNA normal BAMs available\n if (\"normal\" in patient_files[patient]):\n nor_bam = patient_files[patient][\"normal\"][bam_key]\n else:\n nor_bam = \"NA\"\n if (nor_bam != \"NA\" ):\n logger.info(\"%s has %s normal bam!\" % (patient, type))\n for status in patient_files[patient]:\n #bam = patient_files[patient][status][bam_key]\n if (not status == \"normal\"): #and (bam != \"NA\"):\n aff = \".\".join([patient, status,\n type, \"af.combined.adjusted.fisher\"])\n affs_wn.append(aff)\n AFcounts_af = \".\".join([patient, status,\n type, \"pileup.AFcounts.af\"])\n AFcounts_afs_wn[type].append( AFcounts_af )\n elif (nor_bam == \"NA\"):\n logger.info(\"%s does not have %s normal bam!\" % (patient, type))\n for status in patient_files[patient]:\n bam = patient_files[patient][status][bam_key]\n #if (bam != \"NA\"):\n if (not status == \"normal\") and (bam != \"NA\"):\n aff = \".\".join([patient, status,\n type, \"pileup.AFcounts.af\"])\n affs_non.append( aff )\n logger.info(\"%s no normal af files are: %s\" % (type, affs_non))\n logger.info(\"%s with normal af files are: %s\" % (type, affs_wn))\n af_non_dict = make_patient_non_af_dict( affs_non )\n #'PASWLN_Primary_3_50879176_A_T': ['18,14,4,0.22']\n af_wn_dict = make_patient_wn_af_dict( affs_wn )\n #'PASWAJ_Relapse_8_116635942_C_T': ['96,55,41,0.43,116,61,55,0.47,116.0,61.0,55.0,0.47,0.579,Unknown']\n af_dicts[type] = [af_wn_dict, af_non_dict]\n return [af_dicts, AFcounts_afs_wn]\n\n\ndef add_af_anno_for_unpaired(snv_sum, snv_sum_tmp,\n DNA_af_wn_dict, RNA_af_wn_dict,\n DNA_af_non_dict, RNA_af_non_dict,\n patient_files, sum_header):\n with open(snv_sum, 'wb') as csvfile:\n writer = csv.writer(csvfile, delimiter='\\t')\n writer.writerow(sum_header)\n no_coverage = [\"0\", \"0\", \"0\", \"0\"]\n no_bam = [\"na\", \"na\", \"na\", \"na\"]\n with open(snv_sum_tmp, 'r') as snv_fh:\n records = csv.DictReader(snv_fh, delimiter='\\t')\n header = records.fieldnames\n for line in records:\n line_content = [line[i] for i in header ]\n sl = line['patient_ID'].split(\"_\")\n patient = sl[0]\n status = '_'.join(sl[1:])\n DNA_bam = patient_files[patient][status]['DNA_bam']\n RNA_bam = patient_files[patient][status]['RNA_bam']\n DNA_tc = patient_files[patient][status]['DNA_tc']\n RNA_tc = patient_files[patient][status]['RNA_tc']\n variant = \"_\".join([patient_id, chr, pos, ref, alt])\n variant = \"_\".join([line['patient_ID'],\n line['chromosome'],\n line['position'],\n line['ref_base'],\n line['alt_base']])\n # DNA af info\n try:\n DNA_af = DNA_af_non_dict[variant][0].split(',')\n except KeyError:\n if (DNA_bam == \"NA\"):\n DNA_af = no_bam\n else:\n DNA_af = no_coverage \n # RNA af info\n try:\n RNA_af = RNA_af_non_dict[variant][0].split(',')\n except KeyError:\n if (RNA_bam == \"NA\"):\n RNA_af = no_bam\n else:\n RNA_af = no_coverage\n final_content = line_content + DNA_af + [DNA_tc] + RNA_af + [RNA_tc]\n writer.writerow(final_content)\n\n\ndef add_af_anno_for_paired(snv_sum, snv_sum_tmp,\n DNA_af_wn_dict, RNA_af_wn_dict,\n DNA_af_non_dict, RNA_af_non_dict,\n patient_files, sum_header):\n no_bam = [\"na\", \"na\", \"na\", \"na\" ,\"na\", \"na\", \"na\",\n \"na\", \"na\", \"na\", \"na\", \"na\", \"na\"]\n no_coverage = [\"0\", \"0\", \"0\", \"0\" ,\"0\", \"0\", \"0\",\n \"0\", \"0\", \"0\", \"0\", \"0\", \"0\"]\n nas = [\"na\", \"na\", \"na\", \"na\"]\n zeros = [\"0\", \"0\", \"0\", \"0\"]\n with open(snv_sum, 'wb') as csvfile:\n writer = csv.writer(csvfile, delimiter='\\t')\n writer.writerow(sum_header)\n with open(snv_sum_tmp, 'r') as snv_fh:\n records = csv.DictReader(snv_fh, delimiter='\\t')\n header = records.fieldnames\n for line in records:\n line_content = [line[i] for i in header ]\n sl = line['patient_ID'].split(\"_\")\n patient = sl[0]\n status = '_'.join(sl[1:])\n n_DNA_bam = patient_files[patient]['normal']['DNA_bam']\n n_RNA_bam = patient_files[patient]['normal']['RNA_bam']\n DNA_bam = patient_files[patient][status]['DNA_bam']\n RNA_bam = patient_files[patient][status]['RNA_bam']\n DNA_tc = patient_files[patient][status]['DNA_tc']\n RNA_tc = patient_files[patient][status]['RNA_tc']\n variant = \"_\".join([line['patient_ID'],\n line['chromosome'],\n line['position'],\n line['ref_base'],\n line['alt_base']])\n # DNA af info\n if (n_DNA_bam != \"NA\"):\n try:\n DNA_af = DNA_af_wn_dict[variant][0].split(',')\n except KeyError:\n if (DNA_bam != \"NA\"):\n DNA_af = no_coverage\n else:\n DNA_af = no_bam\n elif (n_DNA_bam == \"NA\"):\n try:\n DNA_af_tmp = DNA_af_non_dict[variant][0].split(',')\n DNA_af = nas + DNA_af_tmp + nas + [\"na\"]\n except KeyError:\n if (DNA_bam != \"NA\"):\n DNA_af = nas + zeros + nas + [\"na\"]\n else:\n DNA_af = no_bam\n # RNA af info\n if (n_RNA_bam != \"NA\"):\n try:\n RNA_af = RNA_af_wn_dict[variant][0].split(',')\n except KeyError:\n RNA_af = no_coverage\n elif (n_RNA_bam == \"NA\"):\n try:\n RNA_af_tmp = RNA_af_non_dict[variant][0].split(',')\n RNA_af = nas + RNA_af_tmp + nas + [\"na\"]\n except KeyError:\n if (RNA_bam != \"NA\"):\n RNA_af = nas + zeros + nas + [\"na\"]\n else:\n RNA_af = no_bam\n final_content = line_content + DNA_af + [DNA_tc] + RNA_af + [RNA_tc]\n writer.writerow(final_content)\n\n\ndef group_patients(patient_files):\n patient_files_wn = dict()\n patient_files_non = dict()\n for patient in patient_files:\n tmp_dict = patient_files[patient]\n if (\"normal\" in patient_files[patient]):\n patient_files_wn[patient] = tmp_dict\n else:\n patient_files_non[patient] = tmp_dict\n return [patient_files_wn, patient_files_non]\n\n\ndef check_file_permission(patient_files):\n strelka_snv_vcfs = []\n strelka_indel_vcfs = []\n DNA_bams = []\n paired_mpileup_vcfs = []\n mutseq_snv_vcfs = []\n DNA_single_vcfs = []\n RNA_single_vcfs = []\n RNA_bams = []\n for patient in patient_files:\n for status in patient_files[patient]:\n strelka_snv_vcf = patient_files[patient][status]['strelka_snv_vcf']\n strelka_indel_vcf = patient_files[patient][status]['strelka_indel_vcf']\n DNA_single_vcf = patient_files[patient][status]['DNA_single_vcf']\n paired_mpileup_vcf = patient_files[patient][status]['paired_mpileup_vcf']\n mutseq_snv_vcf = patient_files[patient][status]['mutseq_snv_vcf']\n DNA_bam = patient_files[patient][status]['DNA_bam']\n RNA_bam = patient_files[patient][status]['RNA_bam']\n RNA_single_vcf = patient_files[patient][status]['RNA_single_vcf']\n if (strelka_snv_vcf != \"NA\"):\n strelka_snv_vcfs.append(strelka_snv_vcf)\n if (strelka_indel_vcf != \"NA\"):\n strelka_indel_vcfs.append(strelka_indel_vcf)\n if (DNA_single_vcf != \"NA\"):\n DNA_single_vcfs.append(DNA_single_vcf)\n if (RNA_single_vcf != \"NA\"):\n RNA_single_vcfs.append(RNA_single_vcf)\n if (paired_mpileup_vcf != \"NA\"):\n paired_mpileup_vcfs.append(paired_mpileup_vcf)\n if (mutseq_snv_vcf != \"NA\"):\n mutseq_snv_vcfs.append(mutseq_snv_vcf)\n if (DNA_bam != \"NA\"):\n DNA_bams.append(DNA_bam)\n if (RNA_bam != \"NA\"):\n RNA_bams.append(RNA_bam)\n logger.info(\"Checking strelka snv vcf fileis permissions!\")\n check_files(strelka_snv_vcfs)\n logger.info(\"Checking strelka indel vcf fileis permissions!\")\n check_files(strelka_indel_vcfs)\n logger.info(\"Checking paired_mpileup vcf file permissions!\")\n check_files(paired_mpileup_vcfs)\n logger.info(\"Checking single_mpileup vcf file permissions!\")\n check_files(DNA_single_vcfs)\n check_files(RNA_single_vcfs)\n logger.info(\"Checking bam file permissions!\")\n check_files(DNA_bams)\n logger.info(\"Checking mutseq snv vcf file permissions!\")\n check_files(mutseq_snv_vcfs)\n logger.info(\"Checking RNA_bam file permissions!\")\n check_files(RNA_bams)\n\n\n\ndef __main__():\n parser = argparse.ArgumentParser(description='Summarize variants at both gene and variant level')\n parser.add_argument('-d','--data_type', required=True,\n help='specify data type as wgs or spc')\n parser.add_argument('-i','--input_file', required=True,\n help='specify input file, which tells vcf, bam paths')\n args = vars(parser.parse_args())\n logger.debug('some debug message')\n logger.info('some info message')\n logger.warning('some warning message')\n logger.error('some error message')\n logger.critical('some critical message')\n logger.info(\"Gene summary scripts starts at: %s\\n\" % datetime.datetime.now())\n input_file = args['input_file']\n # impact_types as annotated by snpeff\n impact_types = [\"HIGH\", \"MODERATE\"]\n # use this R path when running qsub or locally\n Rscript_path = \"/gsc/software/linux-x86_64-centos6/R-3.1.1/bin\"\n r_script = \"fisherExactTest.r\"\n # snv and indel summaries for patient with or without normal\n hm_snv_sum_wn = \"high_moderate_SNV_summary_with_normal.txt\"\n hm_snv_sum_wn_tmp = \".\".join([hm_snv_sum_wn, \"tmp\"])\n hm_snv_sum_non = \"high_moderate_SNV_summary_no_normal.txt\"\n hm_snv_sum_non_tmp = \".\".join([hm_snv_sum_non, \"tmp\"])\n hm_indel_sum_wn = \"high_moderate_INDEL_summary_with_normal.txt\"\n hm_indel_sum_non = \"high_moderate_INDEL_summary_no_normal.txt\"\n sum_snv_header = SUM_SNV_HEADER\n\n sum_snv_header_non = (sum_snv_header +\n [\"t_DNA_cov\", \"t_DNA_RefC\", \"t_DNA_AltC\", \"t_DNA_AF\",\n \"DNA_tc\", \"t_RNA_cov\", \"t_RNA_RefC\", \"t_RNA_AltC\",\n \"t_RNA_AF\", \"RNA_tc\"])\n sum_snv_header_wn = (sum_snv_header +\n [\"n_DNA_cov\", \"n_DNA_RefC\", \"n_DNA_AltC\", \"n_DNA_AF\",\n \"t_DNA_cov\", \"t_DNA_RefC\", \"t_DNA_AltC\", \"t_DNA_AF\",\n \"adj_t_DNA_cov\", \"adj_t_DNA_RefC\", \"adj_t_DNA_AltC\",\n \"adj_t_DNA_AF\", \"DNA_fisher_pvalue\", \"DNA_tc\",\n \"n_RNA_cov\", \"n_RNA_RefC\", \"n_RNA_AltC\", \"n_RNA_AF\",\n \"t_RNA_cov\", \"t_RNA_RefC\", \"t_RNA_AltC\", \"t_RNA_AF\",\n \"adj_t_RNA_cov\", \"adj_t_RNA_RefC\", \"adj_t_RNA_AltC\",\n \"adj_t_RNA_AF\", \"RNA_fisher_pvalue\", \"RNA_tc\"])\n sum_indel_header = [\"gene\", \"num_patients_gene_level\", \"num_INDELs_gene_level\",\n \"chromosome\", \"position\", \"ref_base\", \"alt_base\",\n \"num_patients_INDEL_level\", \"patient_ID\", \"snp_ID\", \"gmaf\",\n \"cosmic64_ID\", \"snpeff_details\", \"in_DNA_single_mpileup\",\n \"in_paired_mpileup\", \"in_strelka\", \"pileup_cov\",\n \"pileup_RefC\", \"pileup_AltC\", \"pileup_AF\",\n \"strelka_n_Cov\", \"strelka_n_RefC\", \"strelka_n_AltC\",\n \"strelka_n_AF\", \"strelka_t_Cov\", \"strelka_t_RefC\",\n \"strelka_t_AltC\", \"strelka_t_AF\"]\n logger.info(\"Removing completion stamps to initialize the pipeline!\")\n extension = ['intersect.complete', 'pileup.complete']\n delete_files_by_extension(extension)\n logger.info(\"Variant input file is: %s\" % (input_file))\n logger.info(\"Generating patient_files dictionary!\")\n patient_files = get_files(input_file)\n out_dict = group_patients(patient_files)\n patient_files_wn = out_dict[0]\n patient_files_non = out_dict[1]\n logger.info(\"Patients with matched normal are:\\n\")\n logger.info((patient_files_wn))\n logger.info(\"Patients without matched normal are:\\n\")\n logger.info((patient_files_non))\n logger.info(\"Checking bam, vcf file permissions!\")\n check_file_permission(patient_files)\n if args['data_type'] == 'wgs':\n logger.info(\"Summarizing indels for tumours with matching normals!\")\n summarize_indels(patient_files_wn,\n sum_indel_header,\n hm_indel_sum_wn,\n impact_types)\n logger.info(\"Summarizing indels for tumours without normals!\")\n summarize_indels(patient_files_non,\n sum_indel_header,\n hm_indel_sum_non,\n impact_types)\n logger.info(\"Summarizing snvs for tumours with matching normals!\")\n (patient_snv_wn,\n pos_files_wn) = summarize_snvs(patient_files_wn,\n sum_snv_header,\n hm_snv_sum_wn_tmp,\n impact_types)\n logger.info(\"Summarizing snvs for tumours without matching_normal!\")\n (patient_snv_non,\n pos_files_non) = summarize_snvs(patient_files_non,\n sum_snv_header,\n hm_snv_sum_non_tmp,\n impact_types)\n logger.info(\"Generating mpileup scripts!\")\n (pileup_scripts,\n pileup_complete_stamps) = make_pileup_scripts(patient_files)\n logger.info(\"Qsub mpileup scripts!\")\n qsub_scripts(pileup_scripts)\n logger.info(\"Detecting if pileup jobs on cluster finised!\")\n detect_cluster_jobs(pileup_complete_stamps)\n logger.info(\"Deleting intermediate files!\")\n #delete_files(pileup_scripts)\n #delete_files (pos_files_non)\n #delete_files (pos_files_wn)\n logger.info(\"Parsing pileup output to get base counts!\")\n com_af_files = parse_pileup_output(patient_files,\n patient_snv_wn,\n patient_snv_non)\n logger.info(\"Adjusting tumour base count by tumour content!\")\n for type in com_af_files:\n adjust_allele_frequency(type,\n com_af_files[type],\n patient_files)\n logger.info(\"Performing Fisher Exact Test for tumour/normal pairs!\")\n run_fisher_exact_test(Rscript_path, r_script)\n logger.info(\"Deleting intermediate files!\" )\n extension=['combined.adjusted', 'combined', '.pileup.log']\n #delete_files_by_extension(extension)\n logger.info(\"Figuring out if DNA and/or RNA bams available!\\n\")\n logger.info(\"Reading in DNA and RNA af files and making af dictionary!\")\n af_out = make_af_dict(patient_files)\n DNA_af_wn_dict = af_out[0][\"DNA\"][0]\n DNA_af_non_dict = af_out[0][\"DNA\"][1]\n RNA_af_wn_dict = af_out[0][\"RNA\"][0]\n RNA_af_non_dict = af_out[0][\"RNA\"][1]\n DNA_AFcounts_afs_wn = af_out[1][\"DNA\"]\n RNA_AFcounts_afs_wn = af_out[1][\"RNA\"]\n logger.info(\"Deleting AFcounts.af files!\")\n #delete_files(AFcounts_afs_wn)\n if pairing_status == 'unpaired':\n logger.info(\"Combining snv_non summary, af, and annotation results!\")\n add_af_anno_for_unpaired(hm_snv_sum_non,\n hm_snv_sum_non_tmp,\n DNA_af_wn_dict,\n RNA_af_wn_dict,\n DNA_af_non_dict,\n RNA_af_non_dict,\n patient_files,\n sum_snv_header_non)\n \n elif pairing_status == 'paired':\n logger.info(\"Combining snv_wn summary, af, and annotation results!\")\n add_af_anno_for_paired(hm_snv_sum_wn,\n hm_snv_sum_wn_tmp,\n DNA_af_wn_dict,\n RNA_af_wn_dict,\n DNA_af_non_dict,\n RNA_af_non_dict,\n patient_files,\n sum_snv_header_wn)\n logger.info(\"Deleting intermediate files!\")\n extension=['adjusted.fisher', '.vcf', 'AFcounts.af']\n #delete_files_by_extension(extension)\n logger.info(\"Summarization scripts finished on: %s\" %\n datetime.datetime.now())\n\n\nif __name__ == '__main__':\n __main__()\n\n","sub_path":"summarize_variants.py","file_name":"summarize_variants.py","file_ext":"py","file_size_in_byte":65895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"504617014","text":"import re\na=open(\"wtf.txt\",\"r\")\ni=0\np0=[]\nwhile i!=1:\n b=a.readline()\n# print(b)\n try:\n p=re.sub(r'\\(.+$','',re.search(r\"^.+( - )\",b).group(0))\n if p!=\"\":\n print (p)\n p0.append(p)\n else:\n i=1\n break\n except:\n break\na.close()\nb=open(\"MainIndexWithIdenticalKeywords.txt\",\"w+\")\nfor p1 in p0:\n b.write(p1+\"\\n\")\nb.close()\n","sub_path":"GeneralUsageLister/wtf.py","file_name":"wtf.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"357707209","text":"# Python Object-oriented programming\nclass Employee:\n\n def __init__(self, first_name, last_name, pay):\n self.first_name = first_name\n self.last_name = last_name\n self.pay = pay\n self.email = first_name + '.' + last_name +'@company.com'\n\n def fullName(self):\n return '{}, {}'.format(self.first_name, self.last_name)\n\n\nperson1 = Employee('ivan', 'richard', 50000)\nprint(person1.fullName())\n\n\n\n\n\n\n","sub_path":"classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"531120350","text":"\n# coding: utf-8\n\n# In[4]:\n\n\nfrom __future__ import print_function\n\nimport numpy as np\nimport keras\nimport gc\nfrom itertools import izip\nfrom sklearn.cross_validation import train_test_split\nimport tensorflow as tf\nfrom keras.models import load_model\nfrom keras.models import Model\nfrom keras.callbacks import TensorBoard\nfrom keras.layers import Input, merge, Convolution2D, MaxPooling2D, UpSampling2D, BatchNormalization, Activation, SpatialDropout2D\nfrom keras.optimizers import Adam\nfrom keras.optimizers import SGD\nfrom keras.layers import concatenate\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler, ReduceLROnPlateau\nfrom keras import backend as K\nfrom keras.callbacks import EarlyStopping\nfrom keras.layers.convolutional import Conv2D, MaxPooling2D\nfrom keras.callbacks import Callback\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom sklearn.metrics import confusion_matrix, f1_score, fbeta_score, precision_score, recall_score\n\nworking_path = \"/home/felix/output/luna/subset0/\"\nfinal_set_path='../finalset/'\n\n\nK.set_image_dim_ordering('tf') #Using Tensorflow\n\nimg_cols = 512\nimg_rows = 512\n\n\n\n\nsmooth = 1.\n\n\n\ndef dice_coef(y_true, y_pred):\n \n y_true_f = K.flatten(y_true)\n y_pred_f = K.flatten(y_pred)\n intersection = K.sum(y_true_f * y_pred_f)\n return (2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth)\n\ndef dice_coef_np(y_true,y_pred):\n \n y_true_f = y_true.flatten()\n y_pred_f = y_pred.flatten()\n intersection = np.sum(y_true_f * y_pred_f)\n return (2. * intersection + smooth) / (np.sum(y_true_f) + np.sum(y_pred_f) + smooth)\n\ndef dice_coef_loss(y_true, y_pred):\n \n return -dice_coef(y_true, y_pred)\n\ndef f1_score(y_true, y_pred):\n\n # Count positive samples.\n c1 = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n c2 = K.sum(K.round(K.clip(y_pred, 0, 1)))\n c3 = K.sum(K.round(K.clip(y_true, 0, 1)))\n\n # If there are no true samples, fix the F1 score at 0.\n if c3 == 0:\n return 0\n\n # How many selected items are relevant?\n precision = c1 / (c2+ K.epsilon())\n\n # How many relevant items are selected?\n recall = c1 / (c3+ K.epsilon())\n\n # Calculate f1_score\n f1_score = 2 * (precision * recall) /((precision + recall)+ K.epsilon())\n return f1_score\n\n\ndef precision(y_true, y_pred):\n\n # Count positive samples.\n c1 = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n c2 = K.sum(K.round(K.clip(y_pred, 0, 1)))\n c3 = K.sum(K.round(K.clip(y_true, 0, 1)))\n\n # If there are no true samples, fix the F1 score at 0.\n if c3 == 0:\n return 0\n\n # How many selected items are relevant?\n precision = c1 / (c2+ K.epsilon())\n\n return precision\n\n\ndef recall(y_true, y_pred):\n\n # Count positive samples.\n c1 = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n c3 = K.sum(K.round(K.clip(y_true, 0, 1)))\n\n # If there are no true samples, fix the F1 score at 0.\n if c3 == 0:\n return 0\n\n recall = c1 / (c3+ K.epsilon())\n\n return recall\n\n\ndef get_model():\n inputs = Input((img_rows, img_cols,1))\n conv1 = BatchNormalization()(inputs)\n conv1 = Convolution2D(32, 3, 3,activation='relu',init='lecun_uniform', border_mode='same')(conv1)\n conv1 = BatchNormalization(axis=-1)(conv1)\n conv1 = Convolution2D(32, 3, 3,activation='relu',init='lecun_uniform', border_mode='same')(conv1) \n conv1 = BatchNormalization(axis=-1)(conv1)\n pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)\n\n conv2 = Convolution2D(64, 3, 3,init='lecun_uniform', border_mode='same')(pool1)\n conv2 = BatchNormalization(axis=-1)(conv2)\n conv2 = Convolution2D(64, 3, 3,activation='relu',init='lecun_uniform', border_mode='same')(conv2)\n conv2 = BatchNormalization(axis=-1)(conv2)\n pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)\n\n conv3 = Convolution2D(128, 3, 3,activation='relu',init='lecun_uniform', border_mode='same')(pool2)\n conv3 = BatchNormalization(axis=-1)(conv3)\n conv3 = Convolution2D(128, 3, 3,activation='relu',init='lecun_uniform', border_mode='same')(conv3)\n conv3 = BatchNormalization(axis=-1)(conv3)\n pool3 = MaxPooling2D(pool_size=(2, 2))(conv3)\n\n conv4 = Convolution2D(256, 3, 3,activation='relu',init='lecun_uniform', border_mode='same')(pool3)\n conv4 = BatchNormalization(axis=-1)(conv4)\n conv4 = Convolution2D(256, 3, 3,activation='relu',init='lecun_uniform', border_mode='same')(conv4)\n conv4 = BatchNormalization(axis=-1)(conv4)\n pool4 = MaxPooling2D(pool_size=(2, 2))(conv4)\n \n\n conv5 = Convolution2D(512, 3, 3,activation='relu',init='lecun_uniform', border_mode='same')(pool4)\n conv5 = BatchNormalization(axis=-1)(conv5)\n conv5 = Convolution2D(512, 3, 3, activation='relu',init='lecun_uniform', border_mode='same')(conv5)\n conv5 = BatchNormalization(axis=-1)(conv5)\n \n \n up6 = merge([UpSampling2D(size=(2, 2))(conv5), conv4], mode='concat', concat_axis=3)\n conv6 = SpatialDropout2D(0.4, noise_shape=None, seed=None)(up6)\n conv6 = Convolution2D(256, 3, 3,activation='relu',init='lecun_uniform', border_mode='same')(up6)\n conv6 = Convolution2D(256, 3, 3,activation='relu',init='lecun_uniform', border_mode='same')(conv6)\n\n \n up7 = merge([UpSampling2D(size=(2, 2))(conv6), conv3], mode='concat', concat_axis=3)\n conv7 = SpatialDropout2D(0.4, noise_shape=None, seed=None)(up7)\n conv7 = Convolution2D(128, 3, 3,activation='relu',init='lecun_uniform', border_mode='same')(up7)\n conv7 = Convolution2D(128, 3, 3,activation='relu',init='lecun_uniform', border_mode='same')(conv7)\n\n \n up8 = merge([UpSampling2D(size=(2, 2))(conv7), conv2], mode='concat', concat_axis=3)\n conv8 = SpatialDropout2D(0.4, noise_shape=None, seed=None)(up8)\n conv8 = Convolution2D(64, 3, 3,activation='relu',init='lecun_uniform', border_mode='same')(up8)\n conv8 = Convolution2D(64, 3, 3,activation='relu',init='lecun_uniform', border_mode='same')(conv8) \n\n\n \n up9 = merge([UpSampling2D(size=(2, 2))(conv8), conv1], mode='concat', concat_axis=3)\n conv9 = SpatialDropout2D(0.4, noise_shape=None, seed=None)(up9)\n conv9 = Convolution2D(32, 3, 3,activation='relu',init='lecun_uniform', border_mode='same')(up9) \n conv9 = Convolution2D(32, 3, 3, activation='relu',init='lecun_uniform', border_mode='same')(conv9)\n\n\n conv10 = Convolution2D(1, 1, 1, activation='sigmoid')(conv9)\n print('Conv10: ')\n print(conv10.shape)\n\n model = Model(input=inputs, output=conv10)\n model.compile(optimizer=Adam(lr=1.0e-5), loss=dice_coef_loss, metrics=[dice_coef, 'accuracy', precision, recall, f1_score])\n return model\n\ndef initial_load_data():\n print('-'*30)\n \n print('Loading and preprocessing train data...')\n print('-'*30)\n working_path = \"/home/felix/output/luna/subset0/\"\n #Loading traning data from subset 0 to 9\n imgs_train=np.load(working_path+\"trainImages.npy\").astype(np.float32)\n imgs_mask_train=np.load(working_path+\"trainMasks.npy\").astype(np.float32)\n print(imgs_mask_train.shape)\n for x in range(1,10):\n working_path=\"/home/felix/output/luna/subset%d/\"% (x,)\n imgs_train_temp = np.load(working_path+\"trainImages.npy\").astype(np.float32)\n imgs_train=np.append(imgs_train,imgs_train_temp, axis=0)\n imgs_mask_train_temp = np.load(working_path+\"trainMasks.npy\").astype(np.float32)\n imgs_mask_train=np.append(imgs_mask_train,imgs_mask_train_temp, axis=0)\n \n #Train and test data were initially split after preprocessing\n #Due to apparent differences between train and testa data, a final normalization \n # step was conducted --> this is why they are being merged again\n \n for x in range(10):\n working_path=\"/home/felix/output/luna/subset%d/\"% (x,)\n imgs_temp= np.load(working_path+\"testImages.npy\").astype(np.float32)\n imgs_train=np.append(imgs_train,imgs_temp, axis=0)\n imgs_mask_temp = np.load(working_path+\"testMasks.npy\").astype(np.float32)\n imgs_mask_train=np.append(imgs_mask_train,imgs_mask_temp, axis=0)\n \n mean = np.mean(imgs_train) # mean for data centering\n std = np.std(imgs_train) # std for data normalization\n\n imgs_train -= mean \n imgs_train /= std\n \n #Splitting training data into training data and test data\n imgs_train, imgs_test,imgs_mask_train,imgs_mask_test_true = train_test_split(imgs_train, imgs_mask_train, test_size=0.15, random_state=42)\n \n np.save('imagesTest.npy', imgs_test)\n np.save('masksTest.npy', imgs_mask_test_true)\n np.save('imagesTrain.npy', imgs_train)\n np.save('masksTrain.npy', imgs_mask_train)\n \n \n \n print('Train images:')\n print(len(imgs_train))\n print('Train masks:')\n print (len(imgs_mask_train))\n print('Test images:')\n print(len(imgs_test))\n print('Test masks:')\n print (len(imgs_mask_test_true))\n\n \n return imgs_train, imgs_mask_train,imgs_test, imgs_mask_test_true\n\ndef load_training_data():\n \n \n imgs_train=np.load('imagesTrain.npy')\n imgs_mask_train=np.load('masksTrain.npy')\n #Splitting training data into training data and validation data\n imgs_train, imgs_val,imgs_mask_train,imgs_mask_val = train_test_split(imgs_train, imgs_mask_train, test_size=0.33, random_state=42)\n \n print('Train images:')\n print(len(imgs_train))\n print('Train masks:')\n print (len(imgs_mask_train))\n print('Validation images:')\n print(len(imgs_val))\n print('Validation masks:')\n print(len(imgs_mask_val))\n\n \n \n return imgs_train,imgs_mask_train, imgs_val, imgs_mask_val\n\n \ndef train(use_existing):\n \n imgs_train,imgs_mask_train, imgs_val, imgs_mask_val=load_training_data()\n \n \n \n #Augmenting training images and masks\n # create two instances with the same arguments\n # create dictionary with the input augmentation values\n data_gen_args = dict(\n \n rotation_range=30,\n width_shift_range=0,\n height_shift_range=0,\n zoom_range=0, \n horizontal_flip=True,\n vertical_flip = True)\n ## use this method with both images and masks\n imgs_train_datagen = ImageDataGenerator(**data_gen_args)\n #No alterations for validation set\n imgs_val_datagen= ImageDataGenerator()\n \n masks_train_datagen = ImageDataGenerator(**data_gen_args)\n \n #no alterations for validation set\n imgs_mask_val_datagen=ImageDataGenerator()\n\n # Provide the same seed and keyword arguments to the fit and flow methods\n seed = 1\n ## fit the augmentation model to the images and masks with the same seed\n print('datagen fit...')\n imgs_train_datagen.fit(imgs_train, augment=True, seed=seed)\n masks_train_datagen.fit(imgs_mask_train, augment=True, seed=seed)\n #imgs_val_datagen.fit(imgs_val, augment=False)\n #imgs_mask_val_datagen.fit(imgs_mask_val, augment=False)\n print('datagen fit done.')\n ## set the parameters for the data to come from (images)\n batch_size=2\n imgs_train_generator = imgs_train_datagen.flow(\n imgs_train,\n batch_size=batch_size,\n shuffle=True,\n seed=seed)\n ## set the parameters for the data to come from (masks)\n masks_train_generator= masks_train_datagen.flow(\n imgs_mask_train,\n batch_size=batch_size,\n shuffle=True,\n seed=seed)\n \n imgs_val_generator = imgs_val_datagen.flow(\n imgs_val,\n batch_size=batch_size,\n shuffle=True,\n seed=seed)\n #set the parameters for the data to come from (masks)\n masks_val_generator = imgs_mask_val_datagen.flow(\n imgs_mask_val,\n batch_size=batch_size,\n shuffle=True,\n seed=seed)\n\n # combine generators into one which yields images and masks\n #train_generator = zip(imgs_train_generator, masks_train_generator)\n train_generator=izip(imgs_train_generator, masks_train_generator)\n #val_generator = zip(imgs_val_generator, masks_val_generator)\n val_generator=izip(imgs_val_generator, masks_val_generator)\n \n print('-'*30)\n print('Creating and compiling model...')\n print('-'*30)\n #Clearing Session infos, to clear GPU from stale models\n K.clear_session()\n hist=None\n model=None\n gc.collect()\n model = get_model()\n init_weights=model.get_weights()\n \n \n \n # Saving model and weights to unet.h5 at checkpoints\n model_checkpoint = ModelCheckpoint('unet.h5', monitor='val_loss', save_best_only=True)\n #\n #Using existed model and weights if said so\n if use_existing:\n model=load_model('./unet.h5',custom_objects={'dice_coef_loss': dice_coef_loss, 'dice_coef':dice_coef, 'precision':precision, 'f1_score':f1_score, 'recall': recall, 'dice_coef_np':dice_coef_np}) \n print('model and weights loaded.')\n \n \n \n print('Fitting model...')\n #Early Stop when Validation does not decrease anymore\n #early_stopping = EarlyStopping(monitor='val_loss', patience=3)\n \n #Reduce learning rate by a certain factor when learning stagnates\n reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2,\n patience=6, min_lr=0.001)\n \n tbCallBack= keras.callbacks.TensorBoard(log_dir='./logs/logfinal', histogram_freq=0, batch_size=2, write_graph=True, write_grads=False, write_images=False, embeddings_freq=0, embeddings_layer_names=None, embeddings_metadata=None)\n \n steps_per_epoch=len(imgs_train)\n validation_steps=len(imgs_val)\n hist=model.fit_generator(train_generator,\n steps_per_epoch=steps_per_epoch,\n validation_data=val_generator,\n validation_steps=validation_steps,\n epochs=120,verbose=1,callbacks=[model_checkpoint, tbCallBack, reduce_lr])\n \n #Resetting weights, so no stale models would linger in GPU memory\n model.set_weights(init_weights)\n '''\n tbCallBack= keras.callbacks.TensorBoard(log_dir='./logs', histogram_freq=0, batch_size=2, write_graph=True, write_grads=False, write_images=False, embeddings_freq=0, embeddings_layer_names=None, embeddings_metadata=None)\n hist=model.fit_generator(train_generator, steps_per_epoch=2000, epochs=50)\n model.fit(imgs_train, imgs_mask_train,validation_split=0.1, batch_size=2, epochs=10, verbose=1, shuffle=True,\n callbacks=[model_checkpoint, tbCallBack])\n '''\n print(hist.history)\n \n\n \ndef predict():\n # loading best weights from training session\n \n model=load_model('./unet.h5',custom_objects={'dice_coef_loss': dice_coef_loss, 'dice_coef':dice_coef, 'precision':precision, 'f1_score':f1_score, 'recall': recall, 'dice_coef_np':dice_coef_np}) \n print('model and weights loaded.')\n \n print('Predicting masks on test data...')\n imgs_test=np.load('imagesTest.npy')\n imgs_mask_test_true=np.load('masksTest.npy')\n num_test = len(imgs_test)\n print('Test images: %d',num_test)\n imgs_mask_test = np.ndarray([num_test,512,512,1],dtype=np.float32)\n for i in range(num_test):\n imgs_mask_test[i] = model.predict([imgs_test[i:i+1]], verbose=0)[0]\n print('PredMask: ')\n print(imgs_mask_test.shape)\n np.save('masksTestPredicted.npy', imgs_mask_test)\n \n \n mean = 0.0\n\n for i in range(num_test):\n \n # Channel last\n # mean+=dice_coef_np(imgs_mask_test_true[i,0], imgs_mask_test[i,0])\n mean+=dice_coef_np(imgs_mask_test_true[i], imgs_mask_test[i]) \n \n \n mean/=num_test\n print(\"Mean Dice Coeff : \",mean)\n\nif __name__ == '__main__':\n for x in range(1):\n #initial_load_data()\n #train(False)\n predict()\n \n \n\n\n# In[1]:\n\n\n\n\n","sub_path":"Unet_Segment_wAugm.py","file_name":"Unet_Segment_wAugm.py","file_ext":"py","file_size_in_byte":15718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"465986461","text":"from PIL import Image\nfrom tqdm import tqdm\nimport numpy as np\n\nimport os\nimport argparse\n\ndef to_monochrome(tri):\n \"\"\"Utility to convert libraw 3 channel raw into single channel\n\n Input: Libraw image as numpy array, size (H, W, 3)\n Input Pattern:\n R Channel (0):\n R 0 R 0 R\n 0 0 0 0 0\n R 0 R 0 R\n 0 0 0 0 0\n R 0 R 0 R\n\n G Chennel (1):\n 0 G 0 G 0\n G 0 G 0 G\n 0 G 0 G 0\n G 0 G 0 G\n 0 G 0 G 0\n\n B Chennel (2):\n B' 0 B' 0 B'\n 0 B 0 B 0\n B' 0 B' 0 B'\n 0 B 0 B 0\n B' 0 B' 0 B'\n\n Output: Image squeezed into single channel, size (H, W)\n Bayer pattern:\n R G R G R\n G B G B G\n R G R G R\n G B G B G\n R G R G R\n \"\"\"\n # monochromatic\n mo = np.zeros((tri.shape[0], tri.shape[1])).astype(\"uint8\")\n\n # sqeeze\n mo[0::2,0::2] = tri[0::2, 0::2, 0] #R\n mo[1::2,0::2] = tri[1::2, 0::2, 1] #G1\n mo[0::2,1::2] = tri[0::2, 1::2, 1] #G1\n b = tri[1::2, 1::2, 2] > tri[0::2, 0::2, 2]\n mo[1::2,1::2] = np.multiply(tri[1::2, 1::2, 2], b) + np.multiply(tri[0::2, 0::2, 2], 1-b) #max(B,B')\n\n # mo = np.sum(tri, axis = 2)\n assert len(mo.shape) == 2, \"Output is not monochromatic\"\n return mo\n\ndef get_image_list(li):\n \"\"\"Utility to get all image from txt file\n\n Input: text file with all images to convert, each file path has one line.\n Output: a python list of file paths\n \"\"\"\n with open(li) as f:\n filenames = f.readlines()\n\n filenames = [x.strip() for x in filenames]\n return filenames\n\ndef main(args):\n\n f = args.file\n o = args.output\n\n if not os.path.exists(o):\n os.mkdir(o)\n\n fl = []\n if f.split(\".\")[-1] == \"txt\":\n fl = get_image_list(f)\n else:\n fl.append(f)\n\n for img in tqdm(fl):\n i = np.array(Image.open(img))\n i = to_monochrome(i).astype(\"uint8\")\n fn = img.split(\"/\")[-1]\n Image.fromarray(i).save(o+fn)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description = \"Utility to batch pack libraw trichromatic mosaics\")\n\n parser.add_argument(\"file\", help = \"If text file, get all files in the text list, separated by return.\")\n parser.add_argument(\"--output\", \"-o\", help = \"Output location\", default = \"./mono/\")\n\n args = parser.parse_args()\n\n main(args)\n","sub_path":"data/utils/to_mono.py","file_name":"to_mono.py","file_ext":"py","file_size_in_byte":2363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"405283153","text":"from parse import compile\nfrom copy import copy, deepcopy\nfrom collections import defaultdict, Counter, deque\nfrom blist import *\nimport itertools\nimport math\nimport sys\n# sys.setrecursionlimit(10000)\n\ns = ''\ntiles = {}\nwhile s != 'done':\n s = input()\n tile = int(s.strip(':').split(' ')[1])\n s = input()\n grid = []\n while s != '' and s != 'done':\n grid.append(list(s))\n s = input()\n tiles[tile] = grid\n \ndef rotate1(grid, times=1):\n if times > 1:\n grid = rotate1(grid, times - 1)\n n,m = len(grid), len(grid[0])\n newgrid = deepcopy(grid)\n for i in range(n):\n for j in range(m):\n newi = j\n newj = m - i - 1\n newgrid[newi][newj] = grid[i][j] \n return newgrid\n \ndef rotate2(grid):\n return rotate1(grid, 2)\n \ndef rotate3(grid):\n return rotate1(grid, 3)\n \ndef flip_vert(grid):\n n,m = len(grid), len(grid[0])\n newgrid = deepcopy(grid)\n for i in range(n):\n for j in range(m):\n newi = n - i - 1\n newj = j\n newgrid[newi][newj] = grid[i][j]\n return newgrid\n \ndef flip_hor(grid):\n n,m = len(grid), len(grid[0])\n newgrid = deepcopy(grid)\n for i in range(n):\n for j in range(m):\n c = grid[i][j]\n newi = i\n newj = m - j - 1\n newgrid[newi][newj] = c \n return newgrid\n \ndef flip_both(grid):\n return flip_hor(flip_vert(grid))\n \nrots = [\n ('rot_none', lambda x: x),\n ('rot1', rotate1),\n ('rot2', rotate2),\n ('rot3', rotate3)\n]\n \nflips = [\n ('flip_none', lambda x: x), \n ('fliph', flip_hor), \n ('flipv', flip_vert), \n ('flip_both', flip_both)\n]\n\ndef unique_op_pairs():\n op_results = {}\n # determine which pairs of ops result in the same value\n test_grid = [\n [str(i*len(grid[i]) + j) for j in range(len(grid[i]))] \n for i in range(len(grid))\n ]\n for (r,rf) in rots:\n for (f,ff) in flips:\n res = rf(ff(test_grid))\n s = ''\n for i in res:\n s += ','.join(i)\n if s not in op_results:\n op_results[s] = ((r,rf), (f,ff))\n return set([op_results[k] for k in op_results])\n\nop_pairs = unique_op_pairs()\n \ndef right_edge(grid):\n str = ''\n n,m = len(grid), len(grid[0])\n for i in range(n):\n str += grid[i][m-1]\n return str\n \ndef left_edge(grid):\n str = ''\n n,m = len(grid), len(grid[0])\n for i in range(n):\n str += grid[i][0]\n return str\n \ndef top_edge(grid):\n return ''.join(grid[0])\n \ndef bottom_edge(grid):\n return ''.join(grid[len(grid)-1])\n \nedges = [('right', right_edge, left_edge), \n('left', left_edge, right_edge), ('top', top_edge, bottom_edge),\n('bottom', bottom_edge, top_edge)]\n\ndef match_edge(g1, g2):\n # determine which edges of g1, g2 matches to\n matches = []\n for (e, f1, f2) in edges:\n if f1(g1) == f2(g2):\n matches.append(e)\n return matches\n\n# in is 12x12\npremade_grids = {}\nadj = defaultdict(list)\nfor kk, t1 in enumerate(tiles):\n g1 = tiles[t1]\n print('Checking tile {}: {} of {}'.format(t1, kk + 1, len(tiles)))\n for t2 in tiles:\n if t2 == t1:\n continue\n g2 = tiles[t2]\n for ((r1, r1func),(f1,f1func)) in op_pairs:\n g1op = '{},{}'.format(r1,f1)\n if (t1, g1op) in premade_grids:\n newg1 = premade_grids[(t1, g1op)]\n else:\n newg1 = r1func(f1func(g1))\n premade_grids[(t1, g1op)] = newg1\n for ((r, rfunc), (f, ffunc)) in op_pairs:\n g2op = '{},{}'.format(r,f)\n if (t2, g2op) in premade_grids:\n newg2 = premade_grids[(t2, g2op)]\n else:\n newg2 = rfunc(ffunc(g2))\n premade_grids[(t2, g2op)] = newg2\n matches = match_edge(newg1, newg2)\n for m in matches:\n adj[(t1, g1op)].append(((t2, g2op), m))\n \ndef side_move(i, j, side):\n if side == 'top':\n return (i -1, j)\n if side == 'bottom':\n return (i+1, j)\n if side == 'right':\n return (i, j + 1)\n if side == 'left':\n return (i, j - 1)\n print('somethings wrong')\n exit()\n \ndef valid(i, j, grid):\n if i >= 0 and i < len(grid):\n if j >= 0 and j < len(grid[i]):\n return True\n return False\n \ndef fits(t, op, i, j, grid):\n if grid[i][j] is not None:\n return False\n sides = ['bottom', 'top', 'left', 'right']\n for side in sides:\n i2,j2 = side_move(i, j, side)\n if valid(i2,j2,grid):\n if grid[i2][j2] is not None:\n t2,op2 = grid[i2][j2]\n if ((t2,op2), side) not in adj[(t,op)]:\n return False\n return True\n\nSIDES = int(math.sqrt(len(tiles)))\nGRID = [[None for i in range(SIDES)] for j in range(SIDES)]\n\ndef solve(t, op, i=0, j=0, unused=set([t for t in tiles])):\n if not fits(t, op, i, j, GRID):\n return None\n depth = SIDES * i + j + 1\n if depth % SIDES == 0:\n rleft = SIDES * SIDES - depth\n print('.'*depth + ' '*rleft + '|')\n \n GRID[i][j] = (t, op)\n unused.remove(t)\n if len(unused) == 0:\n return GRID\n for k in adj:\n (t2,op2) = k\n if t2 not in unused:\n continue\n newj = (j + 1) % SIDES\n newi = i if newj > 0 else i + 1\n ret = solve(t2,op2,newi,newj,unused)\n if ret is not None:\n return ret\n\n GRID[i][j] = None\n unused.add(t)\n return None\n \ndef four_corners(grid):\n n,m = len(grid), len(grid[0])\n a,b,c,d = grid[0][0][0], grid[0][m-1][0], grid[n-1][m-1][0], grid[n-1][0][0]\n return (a*b*c*d, [a,b,c,d])\n \ndef print_grid(metagrid):\n for k in premade_grids:\n n,m = len(premade_grids[k]), len(premade_grids[k][0])\n break\n for row in metagrid:\n for i in range(1,n-1):\n fullrow = ''\n for k in row:\n grid = premade_grids[k]\n fullrow += ''.join(grid[i][1:m-1])\n print(fullrow) \n \nfor k in adj:\n t,op = k\n ret = solve(t,op)\n if ret is not None:\n print('grid is {}'.format(ret))\n print('four corners: {}'.format(four_corners(GRID)))\n print_grid(GRID)\n exit()\n \n \n\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n # hello","sub_path":"2020/day21/solveclean.py","file_name":"solveclean.py","file_ext":"py","file_size_in_byte":6488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"568925383","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom eudplib import *\n\nchkt = GetChkTokenized()\nUNIx = bytearray(chkt.getsection(\"UNIx\"))\n\n\ndef main():\n DoActions([\n # 스카웃 디텍터 추가\n SetMemory(0x664198, Add, 32768),\n # 머신 샵의 Spider Mines 버튼 액션을 Unknown Tech35로\n SetMemory(0x5186F0, Add, 2097152),\n # Unknown Tech35를 Spider Mines처럼 수정\n\t\tSetMemory(0x656234, SetTo, 6553600),\n\t\tSetMemory(0x65628C, SetTo, 6553600),\n\t\tSetMemory(0x6562E4, SetTo, 20710618),\n\t\tSetMemory(0x6563C4, SetTo, 1),\n\t\tSetMemory(0x65641C, SetTo, 78643200),\n\t\tSetMemory(0x656474, SetTo, 15925613),\n\t\tSetMemory(0x6564A8, SetTo, 16843520),\n\t\tSetMemory(0x6564D4, SetTo, 65793),\n ])\n # 히드라리스크 체력을 75로 하향, 방어력을 1로 상향.\n SetUnitSettings(\"Zerg Hydralisk\", \"hit points\", 75)\n SetUnitSettings(\"Zerg Hydralisk\", \"armor points\", 1)\n\n global chkt, UNIx\n chkt.setsection(\"UNIx\", UNIx)\n\n\ndef SetUnitSettings(unit, data, value):\n global UNIx\n UNIx_data = {\n # data: (offset, size)\n \"use default settings\": (0, 1),\n \"hit points\": (1, 4),\n \"shield points\": (5, 2),\n \"armor points\": (7, 1),\n \"build time\": (8, 2),\n \"mineral cost\": (10, 2),\n \"gas cost\": (12, 2),\n \"string number\": (14, 2),\n }\n UNIx_keys = UNIx_data.keys()\n if data in (\"hit points\", \"shield points\"):\n value = value * 256\n unit = EncodeUnit(unit)\n assert data in UNIx_data, \"%s is not an Unit Settings.\" % (data)\n UNIx[unit] = 0\n offset, size = UNIx_data[data]\n index = 228 * offset + unit * size\n i2bn = {\n 1: i2b1,\n 2: i2b2,\n 4: i2b4,\n }\n UNIx[index:index + size] = i2bn[size](value)\n","sub_path":"source/initialization.py","file_name":"initialization.py","file_ext":"py","file_size_in_byte":1824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"491280774","text":"# coding=utf-8\n# Copyright 2020 The Trax Authors.\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\"\"\"Tests for trax.layers.research.efficient_attention.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as onp\nfrom tensorflow import test\nfrom trax.layers import attention\nfrom trax.layers import base\nfrom trax.layers.research import efficient_attention\nfrom trax.shapes import ShapeDtype\n\n\nclass EfficientAttentionTest(test.TestCase):\n\n def test_memory_efficient_causal_attention(self):\n qkv_shape = ShapeDtype((3, 32, 8))\n input_signature = (qkv_shape, qkv_shape, qkv_shape)\n layer = efficient_attention.MemoryEfficientCausalAttention(\n loop_stride=16, dropout=0.1, mode='train')\n final_shape = base.check_shape_agreement(layer, input_signature)\n self.assertEqual((3, 32, 8), final_shape)\n\n def test_time_bin_causal_attention_bin_length(self):\n qkv_shape = ShapeDtype((3, 57, 8))\n input_signature = (qkv_shape, qkv_shape, qkv_shape)\n layer = efficient_attention.TimeBinCausalAttention(\n bin_length=16, dropout=0.1, mode='train')\n final_shape = base.check_shape_agreement(layer, input_signature)\n self.assertEqual((3, 57, 8), final_shape)\n\n def test_time_bin_causal_attention_n_bins(self):\n qkv_shape = ShapeDtype((3, 57, 8))\n input_signature = (qkv_shape, qkv_shape, qkv_shape)\n layer = efficient_attention.TimeBinCausalAttention(\n n_bins=4, dropout=0.1, mode='train')\n final_shape = base.check_shape_agreement(layer, input_signature)\n self.assertEqual((3, 57, 8), final_shape)\n\n def test_time_bin_and_dot_product_causal_attention_are_consistent(self):\n dot_product_layer = attention.DotProductCausalAttention(\n dropout=0.0, mode='train')\n time_bin_layer = efficient_attention.TimeBinCausalAttention(\n bin_length=4, dropout=0.0, mode='train')\n\n # Exactly 2 bins.\n input_shape = (3, 8, 8)\n inputs = [onp.random.uniform(size=input_shape) for _ in range(3)]\n\n dot_product_output = dot_product_layer(inputs)\n time_bin_output = time_bin_layer(inputs)\n onp.testing.assert_array_almost_equal(dot_product_output, time_bin_output)\n\n def test_lsh_causal_attention_fast_inference(self):\n qkv_shape = ShapeDtype((3, 1, 8))\n input_signature = (qkv_shape, qkv_shape, qkv_shape)\n layer = efficient_attention.LSHCausalAttention(\n n_bins=4, dropout=0.0, max_len_for_inference=128, mode='predict')\n final_shape = base.check_shape_agreement(layer, input_signature)\n self.assertEqual((3, 1, 8), final_shape)\n\n\nif __name__ == '__main__':\n test.main()\n","sub_path":"trax/layers/research/efficient_attention_test.py","file_name":"efficient_attention_test.py","file_ext":"py","file_size_in_byte":3140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"547682845","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd\nimport seaborn as sns\n\ntitanic=sns.load_dataset('titanic')\ntitanic\n\n\n# In[2]:\n\n\ntitanic.info()\n\n\n# In[3]:\n\n\ntitanic.dtypes\n\n\n# ## Q7. 연령대별 사망자수 0~10/11~20/.../70~80 ->남/녀 사망자수\n\n# In[6]:\n\n\nage0=titanic[(titanic['age']>=0)&(titanic['age']<10)]\nage1=titanic[(titanic['age']>=10)&(titanic['age']<20)]\nage2=titanic[(titanic['age']>=20)&(titanic['age']<30)]\nage3=titanic[(titanic['age']>=30)&(titanic['age']<40)]\nage4=titanic[(titanic['age']>=40)&(titanic['age']<50)]\nage5=titanic[(titanic['age']>=50)&(titanic['age']<60)]\nage6=titanic[(titanic['age']>=60)&(titanic['age']<70)]\nage7=titanic[(titanic['age']>=70)&(titanic['age']<80)]\nage8=titanic[(titanic['age']>=80)&(titanic['age']<90)]\n\nprint('10대 미만 사망자수 :',len(age0['survived']==0))\nprint('10대 사망자수 :',len(age1['survived']==0))\nprint('20대 사망자수 :',len(age2['survived']==0))\nprint('30대 사망자수 :',len(age3['survived']==0))\nprint('40대 사망자수 :',len(age4['survived']==0))\nprint('50대 사망자수 :',len(age5['survived']==0))\nprint('60대 사망자수 :',len(age6['survived']==0))\nprint('70대 사망자수 :',len(age7['survived']==0))\nprint('80대 사망자수 :',len(age8['survived']==0))\n\n\n# In[4]:\n\n\nprint('**titanic호 연령대별 성별에 따른 사망자 수**',end='\\n\\n')\ngrAge=[]\ngrAgeIndex=['0~9','10~19','20~29','30~39','40~49','50~59','60~69','70~79','80~89']\nfor i in range(len(grAgeIndex)):\n if i < 7 :\n grAge.append(titanic[titanic['age']//10==i])\n print('%5s세 그룹 여성 사망자 수 : %3d명'\n %(grAgeIndex[i],grAge[i].groupby(['sex','survived'])['survived'].count()[0]))\n print('%5s세 그룹 남성 사망자 수 : %3d명'\n %(grAgeIndex[i],grAge[i].groupby(['sex','survived'])['survived'].count()[2]))\n print('-'*35)\n elif i==7:\n grAge.append(titanic[titanic['age']//10==i])\n print('%5s세 그룹 남성 사망자 수 : %3d명'\n %(grAgeIndex[i],grAge[i].groupby(['sex','survived'])['survived'].count()[0]))\n print('-'*35)\n else:\n print('%5s세 그룹 남성 사망자 수 : %3d명'\n %(grAgeIndex[i],0))\n\n","sub_path":"21.06.08/Pandas09_21_titanic03_송예지.py","file_name":"Pandas09_21_titanic03_송예지.py","file_ext":"py","file_size_in_byte":2222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"551357492","text":"\"\"\"\n*******************************************************\n * Copyright (C) 2017 MindsDB Inc. \n *\n * This file is part of MindsDB Server.\n *\n * MindsDB Server can not be copied and/or distributed without the express\n * permission of MindsDB Inc\n *******************************************************\n\"\"\"\n\nfrom mindsdb.libs.constants import (DEFAULT_CAPABILITIES,\n DEFAULT_COALLITION_ID,\n FILLER_FOR_WIRESHARK_DUMP,\n SERVER_STATUS_AUTOCOMMIT)\nfrom mindsdb.libs.helpers.logging import logging\nfrom mindsdb.proxies.mysql.data_types.mysql_datum import Datum\nfrom mindsdb.mindsdb_server.proxies.mysql.data_types.mysql_packet import Packet\n\n\nclass HandshakePacket(Packet):\n\n '''\n Implementation based on:\n https://mariadb.com/kb/en/library/1-connecting-connecting/#initial-handshake-packet\n '''\n\n def setup(self):\n\n self.protocol_version = Datum('int<1>', 10)\n self.server_version = Datum('string', '5.7.1-MindsDB-1.0')\n self.connection_id = Datum('int<4>', self.proxy.connection_id)\n self.scramble_1st_part = Datum('string<8>', self.proxy.salt[:8])\n self.reserved_byte = Datum('string<1>', '')\n self.server_capabilities_1st_part = Datum(\n 'int<2>', DEFAULT_CAPABILITIES)\n self.server_default_collation = Datum('int<1>', DEFAULT_COALLITION_ID)\n self.status_flags = Datum('int<2>', SERVER_STATUS_AUTOCOMMIT)\n self.server_capabilities_2nd_part = Datum(\n 'int<2>', DEFAULT_CAPABILITIES >> 16)\n self.wireshark_filler = Datum('int<1>', FILLER_FOR_WIRESHARK_DUMP)\n self.reserved_filler1 = Datum('string<6>', '')\n self.reserved_filler2 = Datum('string<4>', '')\n self.scramble_2nd_part = Datum('string', self.proxy.salt[8:])\n self.null_close = Datum('string', 'mysql_native_password')\n\n @property\n def body(self):\n\n order = [\n 'protocol_version',\n 'server_version',\n 'connection_id',\n 'scramble_1st_part',\n 'reserved_byte',\n 'server_capabilities_1st_part',\n 'server_default_collation',\n 'status_flags',\n 'server_capabilities_2nd_part',\n 'wireshark_filler',\n 'reserved_filler1',\n 'reserved_filler2',\n 'scramble_2nd_part',\n 'null_close'\n ]\n string = b''\n for key in order:\n string += getattr(self, key).toStringPacket()\n\n self.setBody(string)\n return self._body\n\n @staticmethod\n def test():\n import pprint\n logging.basicConfig(level=10)\n pprint.pprint(str(HandshakePacket().getPacketString()))\n\n\n# only run the test if this file is called from debugger\nif __name__ == \"__main__\":\n HandshakePacket.test()\n","sub_path":"mindsdb/proxies/mysql/data_types/mysql_packets/handshake_packet.py","file_name":"handshake_packet.py","file_ext":"py","file_size_in_byte":2912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"273172712","text":"\"\"\"affaire_attribution\n\nRevision ID: 72499d23d034\nRevises: b8e660727760\nCreate Date: 2021-10-27 15:12:22.123281\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '72499d23d034'\ndown_revision = 'b8e660727760'\nbranch_labels = None\ndepends_on = None\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('affaire', sa.Column('attribution', sa.Text(), nullable=True))\n # ### end Alembic commands ###\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('affaire', 'attribution')\n # ### end Alembic commands ###\n","sub_path":"back/infolica/alembic/versions/20211027_72499d23d034.py","file_name":"20211027_72499d23d034.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"64443975","text":"#\n# @lc app=leetcode id=36 lang=python3\n#\n# [36] Valid Sudoku\n#\n\n# @lc code=start\nclass Solution:\n # def isValidSudoku(self, board: List[List[str]]) -> bool:\n # for i in range(9):\n # row, col, sub = set(), set(), set()\n # for j in range(9):\n # sub_i = i // 3 * 3 + j // 3\n # sub_j = i % 3 * 3 + j % 3\n # if board[i][j] in row or board[j][i] in col or board[sub_i][sub_j] in sub:\n # return False\n # else:\n # if board[i][j] != '.':\n # row.add(board[i][j])\n # if board[j][i] != '.':\n # col.add(board[j][i])\n # if board[sub_i][sub_j] != '.':\n # sub.add(board[sub_i][sub_j])\n # return True\n\n def isValidSudoku(self, board):\n seen = sum(([(c, i), (j, c), (i//3, j//3, c)]\n for i, row in enumerate(board)\n for j, c in enumerate(row)\n if c != '.'), [])\n return len(seen) == len(set(seen))\n\n# @lc code=end\n\n","sub_path":"36.valid-sudoku.py","file_name":"36.valid-sudoku.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"186287165","text":"from flask import request, redirect\nfrom urlparse import parse_qsl, urlparse, urlunparse\nimport hashlib\nfrom traffgroup.core.model.security import Account\nfrom traffgroup.core.X.xflask import capp\nfrom traffgroup.x.util import url_append\n\n\n\n\nremoved_fields = [\"username\", \"password\", \"password_again\", \"email\", \"email_again\", \"signature\", \"failure\", \"success\", \n \"agreed\", \"user_type\", \"recaptcha_challenge_field\", \"recaptcha_response_field\"]\n\nsecret = \"asdgSGGSdfsg\"\n\n# redirect next account types to home page\nACC_TYPES_HOMEPAGE = {\n Account.Type.FINANCIAL_MANAGER: 'finance/payout_requests/'\n}\n\n\nclass CallbackException(RuntimeError):\n pass\n\ndef cb_return(err_code=None, account_type=None, **kwargs):\n \n try:\n signature = request.values['signature']\n failure_url = request.values['failure']\n success_url = request.values['success']\n except KeyError as e:\n raise CallbackException(\"Field missing: \" + e.message)\n \n if signature != hashlib.sha224(success_url + failure_url + secret).hexdigest():\n raise CallbackException(\"Signature mismatch [%s + %s + %s] [%s] != [%s]\" % (success_url, failure_url, secret, signature, hashlib.sha224(success_url + failure_url + secret).hexdigest()) )\n \n if err_code:\n path = failure_url\n else:\n path = success_url\n\n # account homepage path\n if account_type and account_type in ACC_TYPES_HOMEPAGE:\n capp.logger.info(path)\n url_parts = urlparse(path)\n path = urlunparse([url_parts[0], url_parts[1], ACC_TYPES_HOMEPAGE[account_type],\n url_parts[3], url_parts[4], url_parts[5]])\n\n query_dict = {}\n query_dict.update(request.values.items())\n \n \n if \"?\" in path:\n args = path.split(\"?\")[-1:]\n params = parse_qsl(args[0])\n query_dict.update(params)\n\n if err_code:\n query_dict = {\"error\" : err_code}\n\n query_dict.update(kwargs)\n\n filtered = ['username','email','icq','wmr','subs_num','traffic_type']\n for f in filtered:\n query_dict.pop(f, None)\n\n\n str_query_dict = {}\n for k, v in query_dict.iteritems():\n str_query_dict.update([(k, v)])\n \n for k in removed_fields:\n str_query_dict.pop(k, None)\n \n return redirect(url_append(path, str_query_dict), 302)\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n ","sub_path":"traffgroup/accounts/lib/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"152883227","text":"from django.db import models\n\nfrom django.core.exceptions import ValidationError\nfrom datetime import datetime\n\nfrom django.contrib.auth.models import User\n\n\nclass Movie(models.Model):\n title = models.CharField(max_length=20, null=False)\n director = models.CharField(max_length=40, null=True)\n description = models.TextField(max_length=250, null=True)\n release_year = models.IntegerField(null=False)\n image_url = models.URLField(null=True)\n length = models.PositiveIntegerField(null=False) # time in minutes\n\n def clean(self):\n if self.title == \"\":\n raise ValidationError(\"Title cannot be empty\")\n\n def save(self, *args, **kwargs):\n self.clean()\n super(Movie, self).save(*args, **kwargs)\n\n\nclass Auditorium(models.Model):\n number = models.IntegerField(primary_key=True)\n rows = models.IntegerField(null=False, default=5) # number of rows in auditorium\n seats = models.IntegerField(null=False, default=8) # number of seats in a row\n\n\nclass Showtime(models.Model):\n movie = models.ForeignKey(Movie, on_delete=models.CASCADE)\n auditorium = models.ForeignKey(Auditorium)\n date = models.DateTimeField(default=datetime.now)\n\n\nclass ReservationNumber(models.Model):\n pass\n\n\nclass Reservation(models.Model):\n showtime = models.ForeignKey(Showtime)\n user = models.ForeignKey(User, unique=False, null=False)\n seat_number = models.IntegerField(null=False) # min_value=1, max_value=showtime.auditorium.seats)\n seat_row = models.IntegerField(null=False) # min_value=1, max_value=showtime.auditorium.rows)\n reservation_number = models.ForeignKey(ReservationNumber, default=1)\n\n def save(self, *args, **kwargs):\n if 1 <= self.seat_number <= self.showtime.auditorium.seats and 1 <= self.seat_row <= self.showtime.auditorium.rows:\n super(Reservation, self).save(*args, **kwargs)\n\n\nclass Ticket(models.Model):\n reservation = models.ForeignKey(Reservation)\n user = models.ForeignKey(User, unique=False, null=False)\n date = models.DateTimeField()\n\n MONTHS = (\n (1, 'styczeń'),\n (2, 'luty'),\n (3, 'marzec'),\n (4, 'kwiecień'),\n (5, 'maj'),\n (6, 'czerwiec'),\n (7, 'lipiec'),\n (8, 'sierpień'),\n (9, 'wrzesień'),\n (10, 'pażdziernik'),\n (11, 'listopad'),\n (12, 'grudzień')\n )\n","sub_path":"cinema/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"6520955","text":"from core.helpers import all, get_pref\nfrom core.logger import Logger\nfrom pts.action_manager import ActionManager\nfrom sync.sync_base import SyncBase\n\nfrom plex import Plex\nfrom plex_metadata import Library\n\n\nlog = Logger('sync.pull')\n\n\nclass Base(SyncBase):\n task = 'pull'\n\n @classmethod\n def get_missing(cls, t_items, is_collected=True):\n return dict([\n (t_item.pk, t_item) for t_item in t_items.itervalues()\n if (not is_collected or t_item.is_collected) and\n cls.is_missing(t_item)\n ])\n\n @classmethod\n def is_missing(cls, t_item):\n is_local = getattr(t_item, 'is_local', False)\n\n if not hasattr(t_item, 'is_collected'):\n return not is_local\n\n return getattr(t_item, 'is_collected') and not is_local\n\n def watch(self, p_items, t_item):\n if type(p_items) is not list:\n p_items = [p_items]\n\n if not t_item.is_watched:\n return True\n\n for p_item in p_items:\n # Ignore already seen movies\n if p_item.seen:\n continue\n\n # Scrobble item\n Plex['library'].scrobble(p_item.rating_key)\n\n # Mark item as added in `pts.action_manager`\n ActionManager.update_history(p_item.rating_key, 'add', 'add')\n\n return True\n\n\n def rate(self, p_items, t_item):\n if type(p_items) is not list:\n p_items = [p_items]\n\n if t_item.rating is None:\n return True\n\n t_rating = t_item.rating.value\n\n for p_item in p_items:\n # Ignore already rated episodes\n if p_item.user_rating == t_rating:\n continue\n\n if p_item.user_rating is None or self.rate_conflict(p_item, t_item):\n Plex['library'].rate(p_item.rating_key, t_rating)\n\n return True\n\n def rate_conflict(self, p_item, t_item):\n status = self.get_status()\n\n # First run, overwrite with trakt rating\n if status.last_success is None:\n return True\n\n resolution = get_pref('sync_ratings_conflict')\n\n if resolution == 'trakt':\n return True\n\n if resolution == 'latest':\n # If trakt rating was created after the last sync, update plex rating\n if t_item.rating.timestamp > status.last_success:\n return True\n\n log.info(\n 'Conflict when updating rating for item %s (plex: %s, trakt: %s), trakt rating will be changed on next push.',\n p_item.rating_key, p_item.user_rating, t_item.rating.value\n )\n\n return False\n\n\nclass Episode(Base):\n key = 'episode'\n auto_run = False\n\n def run(self, p_episodes, t_episodes):\n if p_episodes is None:\n return False\n\n enabled_funcs = self.get_enabled_functions()\n\n for key, t_episode in t_episodes.iteritems():\n if key is None or key not in p_episodes:\n continue\n\n # Mark episode as 'local'\n t_episode.is_local = True\n\n # TODO check result\n self.trigger(enabled_funcs, p_episode=p_episodes[key], t_episode=t_episode)\n\n return True\n\n def run_watched(self, p_episode, t_episode):\n return self.watch(p_episode, t_episode)\n\n def run_ratings(self, p_episode, t_episode):\n return self.rate(p_episode, t_episode)\n\n\nclass Season(Base):\n key = 'season'\n auto_run = False\n children = [Episode]\n\n def run(self, p_seasons, t_seasons):\n if p_seasons is None:\n return False\n\n for key, p_season in p_seasons.iteritems():\n t_season = t_seasons.get(key)\n\n if t_season:\n # Mark season as 'local'\n t_season.is_local = True\n\n self.child('episode').run(\n p_episodes=p_season,\n t_episodes=t_season.episodes if t_season else {}\n )\n\n\nclass Show(Base):\n key = 'show'\n children = [Season]\n\n def run(self, section=None):\n self.check_stopping()\n\n enabled_funcs = self.get_enabled_functions()\n if not enabled_funcs:\n log.info('There are no functions enabled, skipping pull.show')\n return True\n\n p_shows = self.plex.library('show')\n self.save('last_library', p_shows, source='plex')\n\n if p_shows is None:\n log.warn('Unable to retrieve shows library from plex')\n return False\n\n # Fetch library, and only get ratings and collection if enabled\n t_shows, t_shows_table = self.trakt.merged('shows', ratings='ratings' in enabled_funcs, collected=True)\n self.save('last_library', t_shows_table, source='trakt')\n\n if t_shows is None:\n log.warn('Unable to construct merged library from trakt')\n return False\n\n self.emit('started', len(t_shows_table))\n\n for x, (key, t_show) in enumerate(t_shows_table.iteritems()):\n self.check_stopping()\n self.emit('progress', x + 1)\n\n if key is None or key not in p_shows or not t_show.seasons:\n continue\n\n log.debug('Processing \"%s\" [%s]', t_show.title, key)\n\n t_show.is_local = True\n\n # Trigger show functions\n self.trigger(enabled_funcs, p_shows=p_shows[key], t_show=t_show)\n\n # Run through each matched show and run episode functions\n for p_show in p_shows[key]:\n self.child('season').run(\n p_seasons=Library.episodes(p_show.rating_key, p_show, flat=False),\n t_seasons=t_show.seasons if t_show else {}\n )\n\n self.emit('finished')\n self.check_stopping()\n\n # Trigger plex missing show/episode discovery\n self.discover_missing(t_shows)\n\n log.info('Finished pulling shows from trakt')\n return True\n\n def discover_missing(self, t_shows):\n # Ensure collection cleaning is enabled\n if not Prefs['sync_clean_collection']:\n return\n\n log.info('Searching for shows/episodes that are missing from plex')\n\n for key, t_show in t_shows.iteritems():\n # Ignore show if there are no collected episodes on trakt\n if all([not e.is_collected for (_, e) in t_show.episodes()]):\n continue\n\n show = t_show.to_identifier()\n\n if self.is_missing(t_show):\n # Entire show is missing\n log.debug('Unable to find \"%s\" [%s] in plex', t_show.title, key)\n\n self.store('missing.shows', show)\n continue\n\n # Create 'seasons' list\n if 'seasons' not in show:\n show['seasons'] = []\n\n for sk, t_season in t_show.seasons.iteritems():\n # Ignore season if there are no collected episodes on trakt\n if all([not e.is_collected for e in t_season.episodes.values()]):\n continue\n\n i_season = {'number': sk}\n\n if self.is_missing(t_season):\n # Entire season is missing\n log.debug('Unable to find S%02d of \"%s\" [%s] in plex', sk, t_show.title, key)\n\n show['seasons'].append(i_season)\n continue\n\n # Create 'episodes' list\n if 'episodes' not in i_season:\n i_season['episodes'] = []\n\n for ek, t_episode in t_season.episodes.iteritems():\n if not self.is_missing(t_episode):\n continue\n\n log.debug('Unable to find S%02dE%02d of \"%s\" [%s] in plex', sk, ek, t_show.title, key)\n\n # Append episode to season dict\n i_season['episodes'].append({'number': ek})\n\n if not i_season['episodes']:\n # Couldn't find any missing episodes in this season\n continue\n\n # Append season to show dict\n show['seasons'].append(i_season)\n\n if not show['seasons']:\n # Couldn't find any missing seasons/episodes\n continue\n\n self.store('missing.shows', show)\n\n log.info('Discovered %s show(s) with missing items', len(self.retrieve('missing.shows')))\n\n def run_ratings(self, p_shows, t_show):\n return self.rate(p_shows, t_show)\n\n\nclass Movie(Base):\n key = 'movie'\n\n def run(self, section=None):\n self.check_stopping()\n\n enabled_funcs = self.get_enabled_functions()\n if not enabled_funcs:\n log.info('There are no functions enabled, skipping pull.movie')\n return True\n\n p_movies = self.plex.library('movie')\n self.save('last_library', p_movies, source='plex')\n\n if p_movies is None:\n log.warn('Unable to retrieve movies library from plex')\n return False\n\n # Fetch library, and only get ratings and collection if enabled\n t_movies, t_movies_table = self.trakt.merged('movies', ratings='ratings' in enabled_funcs, collected=True)\n self.save('last_library', t_movies_table, source='trakt')\n\n if t_movies is None:\n log.warn('Unable to construct merged library from trakt')\n return False\n\n self.emit('started', len(t_movies_table))\n\n for x, (key, t_movie) in enumerate(t_movies_table.iteritems()):\n self.check_stopping()\n self.emit('progress', x + 1)\n\n if key is None or key not in p_movies:\n continue\n\n log.debug('Processing \"%s\" [%s]', t_movie.title, key)\n t_movie.is_local = True\n\n # TODO check result\n self.trigger(enabled_funcs, p_movies=p_movies[key], t_movie=t_movie)\n\n self.emit('finished')\n self.check_stopping()\n\n # Trigger plex missing movie discovery\n self.discover_missing(t_movies)\n\n log.info('Finished pulling movies from trakt')\n return True\n\n def discover_missing(self, t_movies):\n # Ensure collection cleaning is enabled\n if not Prefs['sync_clean_collection']:\n return\n\n log.info('Searching for movies that are missing from plex')\n\n # Find collected movies that are missing from Plex\n t_collection_missing = self.get_missing(t_movies)\n\n for key, t_movie in t_collection_missing.iteritems():\n log.debug('Unable to find \"%s\" [%s] in plex', t_movie.title, key)\n\n self.store('missing.movies', t_movie.to_identifier())\n\n log.info('Discovered %s missing movie(s)', len(self.retrieve('missing.movies')))\n\n def run_watched(self, p_movies, t_movie):\n return self.watch(p_movies, t_movie)\n\n def run_ratings(self, p_movies, t_movie):\n return self.rate(p_movies, t_movie)\n\n\nclass Pull(Base):\n key = 'pull'\n title = 'Pull'\n children = [Show, Movie]\n threaded = True\n","sub_path":"Trakttv.bundle/Contents/Code/sync/pull.py","file_name":"pull.py","file_ext":"py","file_size_in_byte":10965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"27363588","text":"__author__ = 'Scott'\n\n\ndef ask_ok(prompt, retries=4, complaint='Yes or no, please!'):\n while True:\n ok = input(prompt)\n if ok in ('y', 'ye', 'yes'):\n return True\n if ok in ('n', 'no', 'nop', 'nope'):\n return False\n retries -= 1\n if retries < 0:\n raise OSError('uncooperative user')\n print(complaint)\n\n\ndef cheeseshop(kind, *arguments, **keywords):\n print(\"-- Do you have any\", kind, \"?\")\n print(\"-- I'm sorry, we're all out of\", kind)\n for arg in arguments:\n print(arg)\n print(\"-\" * 40)\n keys = sorted(keywords.keys())\n for kw in keys:\n print(kw, \":\", keywords[kw])\n\n\ndef write_multiple_items(file, separator, *args):\n \"\"\"Write arbitrary number of arguments to file, separated by separator.\"\"\"\n f = open(file, 'w')\n f.write(separator.join(args))\n\n\ndef concat(*args, sep=\"/\"):\n \"\"\"Join arbitrary number of arguments with '/' separator.\"\"\"\n return sep.join(args)\n\n\nif __name__ == \"__main__\":\n # ask_ok('Is python fun?: ')\n cheeseshop(\"Limburger\", \"It's very runny, sir.\",\n \"It's really very, VERY runny, sir\",\n shopkeeper=\"Michael Palin\",\n client=\"John Cleese\",\n sketch=\"Cheese Shop Sketch\")\n write_multiple_items('/Users/Scott/multiple_write_function_file', '&', 'arg1', 'arg2', 'arg3')\n print(concat('arg1', 'arg2', 'arg3'))","sub_path":"args.py","file_name":"args.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"117626617","text":"import discord\nimport random\nimport typing\nimport string\nfrom discord.ext import commands\nfrom synth.utils import errors\n\nclass Fun(commands.Cog):\n def __init__(self, bot: commands.Bot):\n self.bot = bot\n\n def emojify(self, text: str, seperator: str = \"\"):\n l = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\"]\n result = [\"\\u200b\"]\n for char in text.lower():\n if char != \" \":\n if not char.isdigit():\n if char in string.ascii_letters:\n result.append(f\":regional_indicator_{char}:\")\n else:\n result.append(char)\n else:\n result.append(f\":{l[int(char)]}:\")\n else:\n result.append(\" \")\n else:\n return seperator.join(result)\n\n def mock(self, text: str):\n result = str()\n for char in text:\n value = random.choice([True, False])\n if value:\n result += char.upper()\n else:\n result += char.lower()\n else:\n return result\n\n def b(self, text: str):\n return text.replace(\"b\", \"🅱️\").replace(\"B\", \"🅱️\")\n\n @commands.command(name=\"emojify\")\n async def _emojify(self, ctx: commands.Context, *, text: typing.Union[discord.Message, str]):\n \"\"\"Represent your text with emojis\"\"\"\n if isinstance(text, discord.Message):\n if not text.embeds:\n await ctx.send(self.emojify(text.clean_content))\n else:\n if text.embeds[0].description:\n await ctx.send(discord.utils.escape_mentions(self.emojify(text.embeds[0].description)))\n else:\n await ctx.error(description=\"Embed does not have a description.\")\n else:\n await ctx.send(self.emojify(text))\n\n @commands.command(name=\"mock\")\n async def _mock(self, ctx: commands.Context, *, text: typing.Union[discord.Message, str]):\n \"\"\"Mock a text or message\"\"\"\n if isinstance(text, discord.Message):\n if not text.embeds:\n await ctx.send(self.mock(text.clean_content))\n else:\n if text.embeds[0].description:\n await ctx.send(discord.utils.escape_mentions(self.mock(text.embeds[0].description)))\n else:\n await ctx.error(description=\"Embed does not have a description.\")\n else:\n await ctx.send(self.mock(text))\n\n @commands.command(name=\"b\")\n async def _b(self, ctx: commands.Context, *, text: typing.Union[discord.Message, str]):\n \"\"\"🅱️\"\"\"\n if isinstance(text, discord.Message):\n if not text.embeds:\n await ctx.send(self.b(text.clean_content))\n else:\n if text.embeds[0].description:\n await ctx.send(discord.utils.escape_mentions(self.b(text.embeds[0].description)))\n else:\n await ctx.error(description=\"Embed does not have a description.\")\n else:\n await ctx.send(self.b(text))\n\n @commands.group(name=\"random\", invoke_without_command=True)\n async def _random(self, ctx: commands.Context):\n \"\"\"Various selection of random things\"\"\"\n await ctx.send_help(ctx.command)\n\n @_random.command(name=\"choice\")\n async def random_choice(self, ctx: commands.Context, *choices: commands.clean_content):\n if len(choices) < 2:\n return await ctx.error(description=\"Not enough choices to pick from.\")\n\n await ctx.send(random.choice(choices))\n\n @_random.command(name=\"image\")\n async def random_image(self, ctx: commands.Context, tag: str):\n image = await self.bot.api.ksoft.random_image(tag)\n embed = discord.Embed(color=self.bot.colors.neutral, title=image.tag.title())\n embed.set_image(url=image.url)\n embed.set_footer(text=f\"Data provided by the ksoft.si api\")\n\n await ctx.send(embed=embed)\n\n @_random.command(name=\"meme\")\n async def random_meme(self, ctx: commands.Context):\n meme = await self.bot.api.ksoft.random_meme()\n embed = discord.Embed(color=self.bot.colors.neutral)\n embed.set_author(name=meme.title, url=meme.source)\n embed.set_image(url=meme.image_url)\n embed.set_footer(text=f\"{meme.upvotes} 👍 | {meme.downvotes} 👎 | {meme.comments} 💬 | Data provided by the ksoft.si api\")\n\n await ctx.send(embed=embed)\n\n @_random.command(name=\"wikihow\")\n async def random_wikihow(self, ctx: commands.Context):\n wikihow = await self.bot.api.ksoft.random_wikihow()\n embed = discord.Embed(color=self.bot.colors.neutral)\n embed.set_author(name=wikihow.title, url=wikihow.article_url)\n embed.set_image(url=wikihow.url)\n embed.set_footer(text=f\"Data provided by the ksoft.si api\")\n\n await ctx.send(embed=embed)\n\n @_random.command(name=\"aww\")\n async def random_aww(self, ctx: commands.Context):\n aww = await self.bot.api.ksoft.random_aww()\n embed = discord.Embed(color=self.bot.colors.neutral)\n embed.set_author(name=aww.title, url=aww.source)\n embed.set_image(url=aww.image_url)\n embed.set_footer(text=f\"{aww.upvotes} 👍 | {aww.downvotes} 👎 | {aww.comments} 💬 | Data provided by the ksoft.si api\")\n\n await ctx.send(embed=embed)\n\n\ndef setup(bot):\n bot.add_cog(Fun(bot))","sub_path":"synth/modules/fun.py","file_name":"fun.py","file_ext":"py","file_size_in_byte":5502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"629577544","text":"# -*- coding: utf-8 -*-\nimport math\n\nfrom openerp.osv import fields, osv\nfrom openerp.tools.translate import _\n\nclass res_partner(osv.osv):\n _inherit = \"res.partner\"\n _columns = {\n 'wf_doublet_ids': fields.one2many('res.partner', 'wf_doublet_id', 'Doublets'),\n 'wf_doublet_id': fields.many2one('res.partner', 'Doublet of'),\n }\n\n def wf_onchange_address(self, cr, uid, ids, last_name, zip, country_id=False, ref=None, city=None, street=None, context=None):\n res = {}\n if country_id:\n country = self.pool.get('res.country').browse(cr,uid,country_id)\n if country.wf_default_lang:\n res['value'] = {'lang': country.wf_default_lang}\n \n if country_id and zip and last_name:\n name = \"%s %s\" % (last_name.lower(), zip)\n partner_ids = self.search(cr,uid, ['|',('name','ilike', name), ('last_name','=', last_name), ('zip', '=', zip), ('city', '=', city),('street', '=', street),('country_id', '=', country_id),('ref', '!=', ref)], order='name', context=context)\n warning = {}\n doublets = []\n if partner_ids:\n for partner in partner_ids:\n doublets.append((4,partner))\n\n message = _('There are %s other Partner(s) with same Country, ZIP and Last_name shown in field doublets' %(len(partner_ids)))\n warning = { 'title': _('Info'), 'message': message }\n if 'value' in res:\n res['value'].update({'wf_doublet_ids': doublets, 'warning':warning})\n else:\n res['value'] = {'wf_doublet_ids': doublets, 'warning':warning}\n return res\n\nres_partner()","sub_path":"wf_partner_doublets/wf_partner.py","file_name":"wf_partner.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"152759516","text":"#!/usr/bin/env python\n#\n# __COPYRIGHT__\n#\n# Permission is hereby granted, free of charge, to any person obtaining\n# a copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so, subject to\n# the following conditions:\n#\n# The above copyright notice and this permission notice shall be included\n# in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY\n# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#\n\n__revision__ = \"__FILE__ __REVISION__ __DATE__ __DEVELOPER__\"\n\nimport os\n\nimport TestSCons\n\ntest = TestSCons.TestSCons()\n\nnot_executable = test.workpath(\"not_executable\")\n\ntest.write(not_executable, \"\\n\")\n\ntest.write(\"f3.in\", \"\\n\")\n\ntest.write('SConstruct', r\"\"\"\nbld = Builder(action = '%s $SOURCES $TARGET')\nenv = Environment(BUILDERS = { 'bld' : bld })\nenv.bld(target = 'f3', source = 'f3.in')\n\"\"\" % test.workdir.replace('\\\\', '\\\\\\\\'))\n\ntest.run(arguments='.',\n stdout = test.wrap_stdout(\"%s f3.in f3\\n\" % test.workdir, error=1),\n stderr = None,\n status = 2)\n\nbad_command = \"\"\"\\\nBad command or file name\n\"\"\"\n\nunrecognized = \"\"\"\\\n'.+' is not recognized as an internal or external command,\noperable program or batch file.\nscons: \\\\*\\\\*\\\\* \\\\[%s\\\\] Error 1\n\"\"\"\n\nunspecified = \"\"\"\\\nThe name specified is not recognized as an\ninternal or external command, operable program or batch file.\nscons: \\\\*\\\\*\\\\* \\\\[%s\\\\] Error 1\n\"\"\"\n\ncannot_execute = \"\"\"\\\n(sh: )*.+: cannot execute(( -)? \\\\[?Is a directory\\\\]?)?\nscons: \\\\*\\\\*\\\\* \\\\[%s\\\\] Error %s\n\"\"\"\n\npermission_denied = \"\"\"\\\n.+: (p|P)ermission denied\nscons: \\\\*\\\\*\\\\* \\\\[%s\\\\] Error %s\n\"\"\"\n\nis_a_directory = \"\"\"\\\n.+: (i|I)s a directory\nscons: \\\\*\\\\*\\\\* \\\\[%s\\\\] Error %s\n\"\"\"\n\nkonnte_nicht_gefunden_werden = \"\"\"\\\nDer Befehl \".+\" ist entweder falsch geschrieben oder\nkonnte nicht gefunden werden.\nscons: \\\\*\\\\*\\\\* \\\\[%s\\\\] Error %s\n\"\"\"\n\ntest.description_set(\"Incorrect STDERR:\\n%s\\n\" % test.stderr())\nif os.name == 'nt':\n errs = [\n bad_command,\n unrecognized % 'f3',\n konnte_nicht_gefunden_werden % ('f3', 1),\n unspecified % 'f3'\n ]\nelse:\n errs = [\n cannot_execute % ('f3', 126),\n is_a_directory % ('f3', 126),\n permission_denied % ('f3', 126),\n ]\n\ntest.must_contain_any_line(test.stderr(), errs, find=TestSCons.search_re)\n\ntest.pass_test()\n\n# Local Variables:\n# tab-width:4\n# indent-tabs-mode:nil\n# End:\n# vim: set expandtab tabstop=4 shiftwidth=4:\n","sub_path":"test/Errors/execute-a-directory.py","file_name":"execute-a-directory.py","file_ext":"py","file_size_in_byte":3078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"629198044","text":"import json\nimport requests\noctopus_server_uri = 'https://your.octopus.app/api'\noctopus_api_key = 'API-YOURAPIKEY'\nheaders = {'X-Octopus-ApiKey': octopus_api_key}\nspace_name = 'Default'\naccount = {\n 'Id': None,\n 'AccountType': 'AzureServicePrincipal',\n 'AzureEnvironment': '',\n 'SubscriptionNumber': 'Subscription GUID', # replace with valid GUID\n 'Password': {\n 'HasValue': True,\n 'NewValue': 'App registration secret' # replace with valid secret\n },\n 'TenantId': 'Tenant GUID', # replace with valid GUID\n 'ClientId': 'Client GUID', # replace with valid GUID\n 'ActiveDirectoryEndpointBaseUri': '',\n 'ResourceManagementEndpointBaseUri': '',\n 'Name': 'Azure Account Name', # replace with preferred name\n 'Description': 'Azure Account Description', # replace with preferred description\n 'TenantedDeploymentParticipation': 'Untenanted',\n 'TenantTags': [],\n 'TenantIds': [],\n 'EnvironmentIds': []\n}\nuri = '{0}/spaces/all'.format(octopus_server_uri)\nresponse = requests.get(uri, headers=headers)\nresponse.raise_for_status()\nspaces = json.loads(response.content.decode('utf-8'))\nspace = next((x for x in spaces if x['Name'] == space_name), None)\nuri = '{0}/{1}/accounts'.format(octopus_server_uri, space['Id'])\nresponse = requests.post(uri, headers=headers, json=account)\nresponse.raise_for_status()","sub_path":"REST/python/Accounts/create-azure-service-principal.py","file_name":"create-azure-service-principal.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"285224356","text":"\"\"\"\nImplement strStr().\n\nReturn the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.\n\"\"\"\nimport unittest\n\n\ndef strStr(needle, haystack):\n \"\"\"\n :type haystack: str\n :type needle: str\n :rtype: int\n \"\"\"\n if len(needle) == 0 or len(haystack) == 0:\n return 0\n if len(needle) > len(haystack):\n return -1\n first_index = -1\n needle_length = len(needle)\n for i in range(len(haystack) - needle_length + 1):\n curr_word = haystack[i:i + needle_length]\n if curr_word == needle:\n first_index = i\n return i\n return first_index\n\n\nclass TestStrStr(unittest.TestCase):\n def test_1(self):\n self.assertEquals(strStr(\"ll\", \"hello\"), 2)\n\n def test_2(self):\n self.assertEquals(strStr(\"bba\", \"aaaaa\"), -1)\n\n def test_3(self):\n self.assertEquals(strStr(\"\", \"\"), 0)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"strStr.py","file_name":"strStr.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"143008925","text":"# %load q04_count/build.py\n# Default Imports\nfrom greyatomlib.python_getting_started.q01_read_data.build import read_data\ndata = read_data()\n\n# Your Solution Here\ndef deliveries_count(data=data):\n # Your code here\n count = 0\n dat = data['innings'][0]['1st innings']['deliveries']\n for i in list(range(len(dat))):\n for key in dat[i]:\n if dat[i][key]['batsman'] == 'RT Ponting':\n count = count + 1 \n \n\n return count\ndeliveries_count(data)\n\n\n\n\n\n","sub_path":"q04_count/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"434972605","text":"from argparse import ArgumentParser\n\nparser = ArgumentParser(description='Process some integers.')\nparser.add_argument('results_path', type=str,\n help='The path to results')\nparser.add_argument('-', dest='accumulate', action='store_const',\n const=sum, default=max,\n help='sum the integers (default: find the max)')\n\nargs = parser.parse_args()\nprint(args.accumulate(args.integers))\n","sub_path":"WorkTable/Tools/combine_results.py","file_name":"combine_results.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"83977532","text":"#!/usr/bin/python3\n\"\"\"\n New view for Amenities objects that handles all default RestFul API actions.\n\"\"\"\nfrom models.amenity import Amenity\nfrom models import storage\nfrom flask import Flask, request, jsonify, abort\nfrom api.v1.views import app_views\n\n\n@app_views.route('/amenities', strict_slashes=False, methods=['GET'])\ndef all_amenities():\n \"\"\" Retrieves the list of all Amenity objects. \"\"\"\n list_of_amenities = []\n for value in storage.all('Amenity').values():\n list_of_amenities.append(value.to_dict())\n return jsonify(list_of_amenities)\n\n\n@app_views.route('/amenities/', methods=['GET'])\ndef specific_amenity(amenity_id):\n \"\"\" Retrieves a Amenity object. \"\"\"\n full_amenity = storage.get(\"Amenity\", amenity_id)\n if full_amenity is None:\n abort(404)\n return jsonify(full_amenity.to_dict())\n\n\n@app_views.route('/amenities/', methods=['DELETE'])\ndef delete_amenity(amenity_id):\n \"\"\" Deletes a Amenity object. \"\"\"\n full_amenity = storage.get('Amenity', amenity_id)\n if full_amenity:\n storage.delete(full_amenity)\n storage.save()\n return jsonify({}), 200\n else:\n abort(404)\n\n\n@app_views.route('/amenities', strict_slashes=False, methods=['POST'])\ndef create_amenity():\n \"\"\" Creates a Amenity. \"\"\"\n dic = request.get_json()\n if not dic:\n abort(400, {'Not a JSON'})\n if 'name' not in dic:\n abort(400, {'Missing name'})\n new_amenity = Amenity(**dic)\n storage.new(new_amenity)\n storage.save()\n return jsonify(new_amenity.to_dict()), 201\n\n\n@app_views.route('amenities/', methods=['PUT'])\ndef updates_amenity(amenity_id):\n \"\"\" Updates a State object. \"\"\"\n dic = request.get_json()\n selected_amenity = storage.get('Amenity', amenity_id)\n if not selected_amenity:\n abort(404)\n if not dic:\n abort(400, {'Not a JSON'})\n for key, value in dic.items():\n if key not in ['id', 'created_at', 'updated_at']:\n setattr(selected_amenity, key, value)\n storage.save()\n return jsonify(selected_amenity.to_dict()), 200\n","sub_path":"api/v1/views/amenities.py","file_name":"amenities.py","file_ext":"py","file_size_in_byte":2106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"150081083","text":"from scipy.sparse import dok_matrix\nimport numpy as np\nimport scipy\nimport csv,os,sys,argparse,math\nimport sklearn\nfrom sklearn.cluster import KMeans\nfrom sklearn.preprocessing import normalize\nimport scipy.io,random\n\n\ndef clustering(M,K,maxiter,ninit,njobs):\n print('\\n#################################################################################################################################')\n print('Start the Kmeans clustering with',K,'clusters',maxiter,'maximum iterations',ninit,'initializations',njobs,'jobs')\n print('#################################################################################################################################\\n')\n model = KMeans(n_clusters=K,n_init=ninit,max_iter=maxiter,n_jobs=njobs)\n model_train = model.fit(M)\n labels = model_train.predict(M)\n return labels\n\ndef createMatrix(filein,n,k):\n M1 = dok_matrix((n,n))\n M2 = dok_matrix((n,n))\n tracker_i = []\n tracker_c = np.zeros(n)\n tracker_s = np.zeros(n)\n d1 = dict()\n counter= 0\n idx = -1\n print('Start building the dictionary')\n sumw=0\n maxw=0\n countw=0\n for line in filein:\n counter+=1\n if (counter%1000000) == 0:\n print(counter,'lines treated')\n\n l = line.strip().split(',')\n #Detect header\n try:\n x = int(l[0]) - 1\n y = int(l[1]) - 1\n w = int(l[2])\n d1[(x,y)] = w\n if x not in tracker_i:\n idx+=1\n tracker_i.append(x)\n tracker_s[idx] = w\n tracker_c[idx] += 1\n else:\n xi = tracker_i.index(x)\n tracker_s[xi] += w\n tracker_c[xi] += 1\n except ValueError as e:\n print('Wrong format for line',counter,', skipped')\n continue\n\n# print(tracker_s)\n# print(tracker_c)\n# if sys.version_info.major == 3:\n# input(\"Type enter to continue\")\n# else:\n# raw_input(\"Type enter ton continue\")\n d2 = dict()\n for i in range(n):\n if tracker_c[i] > 0:\n try:\n xi = tracker_i[i]\n d2[(xi,xi)] = tracker_s[i]/tracker_c[i]\n except:\n print(\"Error while entering diagonal value:\",tracker_s[i],\"/\",tracker_c[i])\n sys.exit(1)\n else:\n print(\"No entry for hash number:\",i)\n\n\n print('Create sparse matrix from dictionary')\n M1.update(d1)\n M2.update(d2)\n M3 = M1+M2\n M = M3.tocsr()\n #namemat_n='adjacency_matrix_normalized_l2_K_'+str(k)+'_random_index_'+str(K)+'.mtx'\n Mn = normalize(M,norm='l2',axis=1)\n #print('Saving normalized matrix as',namemat_n)\n #scipy.io.mmwrite(namemat_n,Mn)\n print('Finished creating normalized matrix')\n return Mn\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('-i','--input',\n type=argparse.FileType('r'),\n help=\"Input file, csv with h1,h2,n12\")\n parser.add_argument('-n','--nhashs',\n type=int,\n help=\"Number of hashs\")\n parser.add_argument('-k','--nClusters',\n type=int,\n help=\"Number of KMeans clusters\")\n parser.add_argument('-o','--output',\n type=argparse.FileType('w'),\n help=\"Output file\")\n parser.add_argument('-j','--nJobs',\n type=int,\n default=3,\n help=\"Number of jobs to use for computation (default set to 3)\")\n parser.add_argument('-m','--maxIter',\n type=int,\n default=300,\n help=\"Maximum number of iterations in computing KMeans\")\n parser.add_argument('-s','--nInit',\n type=int,\n default=10,\n help=\"Number of times the k means will run with different centroids (default 10)\")\n args = parser.parse_args()\n\n if len(sys.argv) < 9:\n parser.print_help()\n sys.exit(1)\n\n M = createMatrix(args.input,args.nhashs,args.nClusters)\n labels = clustering(M,args.nClusters,args.maxIter,args.nInit,args.nJobs)\n for l in labels:\n args.output.write(str(l)+'\\n')\n args.input.close()\n args.output.close()\n\nif __name__ == '__main__':\n main()\n \n","sub_path":"version_20160401.dir/study_period_4_weeks_2_week_ovlerap.dir/clusterhashtags.dir/grouphashtags.dir/kmeans_clustering_diag.py","file_name":"kmeans_clustering_diag.py","file_ext":"py","file_size_in_byte":4197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"74248775","text":"from rest_framework import viewsets, mixins, status\nfrom rest_framework.authentication import TokenAuthentication\nfrom rest_framework.decorators import action\nfrom rest_framework.response import Response\nfrom rest_framework.permissions import IsAuthenticated\n\nfrom core.models import Tag, Ingredient, Recipe\nfrom recipe.serializers import (\n TagSerializer,\n IngredientSerializer,\n RecipeSerializer,\n RecipeDetailSerializer,\n RecipeImageSerializer,\n)\n\n\nclass CommonRecipeAttributesMixin:\n \"\"\"Common recipe attributes mixin.\"\"\"\n\n queryset = NotImplemented\n request = NotImplemented\n authentication_classes = (\n TokenAuthentication,\n )\n permission_classes = (\n IsAuthenticated,\n )\n\n def get_queryset(self):\n \"\"\"Return objects for the current authenticated user only.\"\"\"\n qs = self.queryset\n\n is_assigned_only = bool(int(\n self.request.query_params.get('assigned_only', 0)\n ))\n if is_assigned_only:\n qs = qs.filter(recipe__isnull=False)\n\n return qs.filter(user=self.request.user).order_by('-name').distinct()\n\n def perform_create(self, serializer):\n \"\"\"Assign a tag to a user.\"\"\"\n serializer.save(user=self.request.user)\n\n\nclass TagViewSet(\n CommonRecipeAttributesMixin,\n viewsets.GenericViewSet,\n mixins.ListModelMixin,\n mixins.CreateModelMixin,\n):\n \"\"\"Manage Tags in database.\"\"\"\n\n queryset = Tag.objects.all()\n serializer_class = TagSerializer\n\n\nclass IngredientViewSet(\n CommonRecipeAttributesMixin,\n viewsets.GenericViewSet,\n mixins.ListModelMixin,\n mixins.CreateModelMixin,\n):\n \"\"\"Manage ingredients in the database.\"\"\"\n\n queryset = Ingredient.objects.all()\n serializer_class = IngredientSerializer\n\n\nclass RecipeViewSet(viewsets.ModelViewSet):\n \"\"\"Manage recipes in the database.\"\"\"\n\n queryset = Recipe.objects.all()\n serializer_class = RecipeSerializer\n authentication_classes = (\n TokenAuthentication,\n )\n permission_classes = (\n IsAuthenticated,\n )\n\n def get_queryset(self):\n \"\"\"Retrieve the own recipes.\"\"\"\n qs = self.queryset\n\n tags = self.request.query_params.get('tags')\n ings = self.request.query_params.get('ingredients')\n\n if tags:\n qs = qs.filter(tags__id__in=[int(t) for t in tags.split(',')])\n\n if ings:\n qs = qs.filter(\n ingredients__id__in=[int(i) for i in ings.split(',')],\n )\n\n return qs.filter(user=self.request.user)\n\n def get_serializer_class(self):\n \"\"\"Return appropriate serializer.\"\"\"\n if self.action == 'retrieve':\n return RecipeDetailSerializer\n if self.action == 'upload_image':\n return RecipeImageSerializer\n return self.serializer_class\n\n def perform_create(self, serializer):\n \"\"\"Create a recipe.\"\"\"\n serializer.save(user=self.request.user)\n\n @action(methods=['POST'], detail=True, url_path='upload-image')\n def upload_image(self, request, pk=None):\n \"\"\"Upload an image to a recipe.\"\"\"\n recipe = self.get_object()\n serializer = self.get_serializer(recipe, data=request.data)\n\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n","sub_path":"app/recipe/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"408991345","text":"class Solution:\n def maxSlidingWindow(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: List[int]\n \"\"\"\n res=[]\n idx=collections.deque()\n for i,n in enumerate(nums):\n while len(idx)>0 and n>=nums[idx[-1]]:\n idx.pop()\n idx.append(i)\n if i-idx[0]==k: idx.popleft()\n if i>=k-1: res.append(nums[idx[0]])\n \n return res\n \n \n","sub_path":"python/sliding-window-maximum.py","file_name":"sliding-window-maximum.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"337634102","text":"from cs50 import get_string\n\nsentences = 0\nwords = 1\nletters = 0\n\ntext = get_string('Text: ')\n\nfor c in text:\n if c in ['.', '?', '!']:\n sentences += 1\n elif c == ' ':\n words +=1\n elif c.isalpha():\n letters += 1;\n\nL = 100 * (letters / words)\nS = 100 * (sentences / words)\n\n\nindex = round(0.0588 * L - 0.296 * S - 15.8)\n\nif index < 1:\n print(\"Before Grade 1\")\nelif index > 16:\n print(\"Grade 16+\")\nelse:\n print(f'Grade {index}')","sub_path":"CS/6_Python/readability/readability.py","file_name":"readability.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"1732395","text":"import numpy as np\nimport pickle\nimport os\nimport game_training_manager as gtm\nimport matplotlib.pyplot as plt \nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Flatten, Dropout\n\ndef plot_history(history):\n loss_list = [s for s in history.history.keys() if 'loss' in s and 'val' not in s]\n acc_list = [s for s in history.history.keys() if 'acc' in s and 'val' not in s]\n \n if len(loss_list) == 0:\n print('Loss is missing in history')\n return \n \n ## As loss always exists\n epochs = range(1,len(history.history[loss_list[0]]) + 1)\n \n ## Loss\n plt.figure(1)\n for l in loss_list:\n plt.plot(epochs, history.history[l], 'b', label='Training loss (' + str(str(format(history.history[l][-1],'.5f'))+')'))\n \n plt.title('Loss')\n plt.xlabel('Epochs')\n plt.ylabel('Loss')\n plt.legend()\n \n ## Accuracy\n plt.figure(2)\n for l in acc_list:\n plt.plot(epochs, history.history[l], 'b', label='Training accuracy (' + str(format(history.history[l][-1],'.5f'))+')')\n\n plt.title('Accuracy')\n plt.xlabel('Epochs')\n plt.ylabel('Accuracy')\n plt.legend()\n plt.show()\n\ndef train(plot=False, model_name=\"keras_mlp\"):\n\twd = os.getcwd()\n\tsave_dir = os.path.join(wd, \"trained_models\")\n\ttrain_X = np.array(gtm.get_train_x(filename=\"rationalized_train.data\"))\n\ttrain_Y = np.array(gtm.get_train_y(filename=\"rationalized_train.data\"))\n\n\tmodel = Sequential()\n\tmodel.add(Dense(6, input_dim=6))\n\tmodel.add(Dense(50,activation='sigmoid'))\n\tmodel.add(Dense(215,activation='sigmoid'))\n\tmodel.add(Dense(50,activation='tanh'))\n\tmodel.add(Dense(1,activation='sigmoid'))\n\tmodel.compile(optimizer='sgd', loss='binary_crossentropy', metrics=['accuracy'])\n\n\thistory = model.fit(train_X, train_Y, epochs=1000, verbose=1, batch_size=8, shuffle=True)\n\n\tmodel_json = model.to_json()\n\tif not os.path.exists(save_dir):\n\t os.makedirs(save_dir)\n\twith open(os.path.join(save_dir, model_name + \".nn\"), \"w\") as json_file:\n\t json_file.write(model_json)\n\tmodel.save_weights(os.path.join(save_dir, model_name + \"_weights\" + \".nn\"))\n\n\tif plot:\n\t\tplot_history(history)\n\ntrain(plot=True, model_name=\"keras_mlp_01\")\ntest = gtm.get_trained_model(\"keras_mlp_01\")\nx = np.array([[5, 6.174829247276662, 9.43, -1.6332175569825653, 1.21, 0.48]]) #desired_output = 1\n#x = np.array([[5, 2.022439866604646, 9.13, -1.414263574654883, 1.21, 0.48]]) #desired_output = 0\nprint(x.shape)\nprint(test.predict(x))","sub_path":"MAN/simple_neural_net/Game/keras_net.py","file_name":"keras_net.py","file_ext":"py","file_size_in_byte":2468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"625686672","text":"import serial\r\nimport time\r\nimport pygame\r\nfrom pygame.locals import *\r\nimport sys\r\nimport csv\r\n\r\nser = serial.Serial('/dev/ttyACM0',9600)\r\ntime.sleep(2)\r\n\r\ndef main():\r\n pygame.init()\r\n screen = pygame.display.set_mode((500,300))\r\n pygame.display.set_caption(\"Humidity & Temperrature\")\r\n font = pygame.font.Font(None,55)\r\n while(1):\r\n screen.fill((0,0,0))\r\n #Humidity\r\n ser.write(b'H')\r\n h = ser.readline()\r\n h = h[:-1]\r\n #print('Humidity:' + h)\r\n text = font.render('Humidity:' + h + ' %',True,(255,255,255))\r\n screen.blit(text,[50,50])\r\n\r\n time.sleep(1)\r\n\r\n #temperature\r\n ser.write(b'T')\r\n t = ser.readline()\r\n t = t[:-1]\r\n #print('Temperature:' + t)\r\n text = font.render('Temperature:' + t+ ' C',True,(255,255,255))\r\n screen.blit(text,[50,100])\r\n\r\n body = [\r\n [h,t]\r\n ]\r\n\r\n with open('data.csv','w') as f:\r\n writer = csv.writer(f)\r\n writer.writerows(body)\r\n\r\n \r\n pygame.display.update()\r\n\r\n for event in pygame.event.get():\r\n if event.type == QUIT:\r\n ser.close()\r\n pygame.quit()\r\n sys.exit()\r\n\r\nif __name__==\"__main__\":\r\n main()\r\n\r\n\r\n\r\n","sub_path":"arduino-connect.py","file_name":"arduino-connect.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"65743315","text":"import numpy as np\r\nimport atomman as am\r\nfrom copy import deepcopy\r\nfrom math import ceil\r\nfrom collections import OrderedDict\r\n\r\n\r\ndef rotate(system, axes):\r\n \"\"\"\r\n Rotate a system by transforming both atomic positions and lattice vectors\r\n according to axes.\r\n Arguments:\r\n system -- atomman.System that is being rotated.\r\n axes -- three right-handed orthogonal vectors defining the transformation.\r\n The standard transformation matrix is taken by normalizing axes.\r\n\r\n The system returned should be identical to the original\r\n system, just with a new choice of axes. \r\n \"\"\"\r\n # normalize axes to get the transformation matrix, T\r\n T = am.tools.axes_check(axes)\r\n\r\n # transform the box vectors using T\r\n avect = T.dot(system.box.avect)\r\n bvect = T.dot(system.box.bvect)\r\n cvect = T.dot(system.box.cvect)\r\n\r\n # create a new system using deepcopy\r\n new_system = deepcopy(system)\r\n\r\n # transform the system's axes\r\n new_system.box_set(avect=avect, bvect=bvect, cvect=cvect, scale=True)\r\n\r\n return new_system\r\n\r\n\r\ndef rotate_cubic(system, axes):\r\n \"\"\"\r\n Rotate a cubic system according to the specified crystallographic axes.\r\n Returns an orthogonal system whose box lengths are:\r\n a * sqrt(i^2+j^2+k^2)\r\n where a is the original cubic box length, and ijk are the crystallographic\r\n indicies for the specific direction. \r\n \"\"\"\r\n # rotate system generically\r\n system = rotate(system, axes)\r\n\r\n # test for cubic\r\n a = system.box.a\r\n try:\r\n assert np.isclose(a, system.box.b), str(a) + ' ' + str(system.box.b)\r\n assert np.isclose(a, system.box.c), str(a) + ' ' + str(system.box.c)\r\n assert np.isclose(90.0, system.box.alpha), str(system.box.alpha)\r\n assert np.isclose(90.0, system.box.beta), str(system.box.beta)\r\n assert np.isclose(90.0, system.box.gamma), str(system.box.gamma)\r\n except:\r\n raise ValueError('Cubic system not given')\r\n\r\n # Test for integer axes values\r\n try:\r\n for ax_val in axes.flat:\r\n assert np.isclose(ax_val, int(ax_val))\r\n except:\r\n raise ValueError('axes values must be integers')\r\n\r\n # Get magnitudes of the axes\r\n mag = np.linalg.norm(axes, axis=1)\r\n\r\n # compute number of atoms for the new system\r\n natoms = system.natoms * mag[0] * mag[1] * mag[2]\r\n if np.isclose(int(round(natoms)), natoms):\r\n natoms = int(round(natoms))\r\n else:\r\n raise ValueError(\r\n 'not an integer number of atoms associated with the axes.')\r\n\r\n # create a new box with scaled lattice parameters\r\n box = am.Box(a=a * mag[0], b=a * mag[1], c=a *\r\n mag[2], origin=system.box.origin)\r\n\r\n # supersize the rotated box\r\n m = int(ceil(max(mag)))\r\n system = am.tools.supersize(system, (-m, m), (-m, m), (-m, m))\r\n\r\n # filter atoms for only those in the new box\r\n data = system.atoms.data\r\n\r\n # round x-positions near xlo, xhi and only keep data for atoms where xlo\r\n # <= x < xhi\r\n data[np.where(np.isclose(data.T[1], box.xlo,\r\n atol=1e-8, rtol=0)), 1] = box.xlo\r\n data = data[data.T[1] >= box.xlo]\r\n data[np.where(np.isclose(data.T[1], box.xhi,\r\n atol=1e-8, rtol=0)), 1] = box.xhi\r\n data = data[data.T[1] < box.xhi]\r\n\r\n # round y-positions near ylo, yhi and only keep data for atoms where ylo\r\n # <= y < yhi\r\n data[np.where(np.isclose(data.T[2], box.ylo,\r\n atol=1e-8, rtol=0)), 2] = box.ylo\r\n data = data[data.T[2] >= box.ylo]\r\n data[np.where(np.isclose(data.T[2], box.yhi,\r\n atol=1e-8, rtol=0)), 2] = box.yhi\r\n data = data[data.T[2] < box.yhi]\r\n\r\n # round z-positions near zlo, zhi and only keep data for atoms where zlo\r\n # <= z < zhi\r\n data[np.where(np.isclose(data.T[3], box.zlo,\r\n atol=1e-8, rtol=0)), 3] = box.zlo\r\n data = data[data.T[3] >= box.zlo]\r\n data[np.where(np.isclose(data.T[3], box.zhi,\r\n atol=1e-8, rtol=0)), 3] = box.zhi\r\n data = data[data.T[3] < box.zhi]\r\n\r\n # deepcopy the data array to guarantee that it is new and separate\r\n data = deepcopy(data)\r\n\r\n # rebuild views\r\n start = 0\r\n view = OrderedDict()\r\n for k in system.atoms.view:\r\n vshape = (len(data), ) + system.atoms.view[k].shape[1:]\r\n view[k] = data[:, start: start + system.atoms.view[k][0].size]\r\n view[k].shape = vshape\r\n start = start + system.atoms.view[k][0].size\r\n\r\n # create atoms from natoms, data, view and dtype\r\n atoms = am.Atoms(natoms=natoms, data=data, view=view,\r\n prop_dtype=system.atoms.dtype)\r\n\r\n # return new system\r\n return am.System(box=box, atoms=atoms)\r\n","sub_path":"rotate.py","file_name":"rotate.py","file_ext":"py","file_size_in_byte":4820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"614047861","text":"import logging\n\nfrom aiohttp_utils import Response\n\nfrom demo import status\n\n\nlogger = logging.getLogger(__name__)\n\nasync def request_logging_middleware(app, handler):\n async def middleware_handler(request):\n logger.info(request)\n return await handler(request)\n return middleware_handler\n\n\nasync def auth_middleware(app, handler):\n async def middleware(request):\n request.user = None\n token = request.headers.get('authorization', None)\n\n if token != 'abc123':\n return Response(status=status.HTTP_401_UNAUTHORIZED)\n\n # do user lookup here, maybe\n return await handler(request)\n return middleware\n\n\ndef setup_middlewares(app):\n app.middlewares.append(request_logging_middleware)\n app.middlewares.append(auth_middleware)\n","sub_path":"demo/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"141039290","text":"from flask import render_template, current_app as app\nfrom app.forms import ContactForm\nfrom flask_mail import Message\nfrom app import mail\n\n# def send_email():\n# form = ContactForm()\n# context = {\n# \"form\": form,\n# # \"google_maps_api_key\": app.config[\"GOOGLE_MAPS_API_KEY\"],\n# \"name\": form.name.data,\n# \"email\": form.email.data,\n# \"phone\": form.phone.data,\n# \"subject\": form.subject.data,\n# \"message\": form.message.data,\n# }\n# return requests.post(\n# app.config['MAIL_DOMAIN'],\n# auth=(\"api\", app.config['MAIL_API_KEY']),\n# data={\n# \"from\": f\"Zara Consulting <{app.config['COMPANY_EMAIL']}>\",\n# \"to\": [f\"{app.config['MAIL_ACCOUNT']}\"],\n# \"subject\": f\"[Zara Consulting] New inquiry\",\n# \"html\": render_template('email/mail.html', **context)\n# }\n# )\n\ndef send_email(subject, sender, recipients, html_body, reply_to=None, bcc=None):\n msg = Message(subject, sender=sender, recipients=recipients, reply_to=reply_to, bcc=bcc)\n msg.html = html_body\n print(msg.html)\n mail.send(msg)\n\ndef send_contact_email(form_data):\n # print(form_data)\n send_email(\n f'[{app.config.get(\"COMPANY_NAME_SHORT\")}] Contact Form Inquiry', \n sender='noreply@zaraconsulting.org',\n reply_to=form_data.get('email'),\n bcc=app.config.get('ADMIN'), \n recipients=[app.config.get('MAIL_USERNAME')],\n html_body=render_template('email/mail.html', **form_data)\n )","sub_path":"app/email.py","file_name":"email.py","file_ext":"py","file_size_in_byte":1434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"304056780","text":"# coding:utf-8\nfrom mail import attachmail\na =attachmail.AttatchMail\n\ndef send():\n '''\n server = smtplib.SMTP('smtp.163.com', 25)\n server.login('18818261892@163.com', 'LBQ'\n\n\n :param filname:\n :param file_path:\n :param subject:\n :param context:\n :return:\n '''\n\n To = ['fiz.lin@1cloudtech.com','1848406889@qq.com','fiz.lin@softtek.com']\n b =attachmail.AttatchMail(host='smtp.163.com', user_name='18818261892@163.com', pwd='96',\n context='THIS IS TENT', Subject='HELLO WORLD',\n To=To, filename='filname',\n file_path= '/Users/fiz/Desktop',port=25,nick_name='fiz',mail_adress='18818261892@163.com')\n b.send()\n\nsend()\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"231127347","text":"'''\nYou have an array of numbers.\nYour task is to sort ascending odd numbers but even numbers must be on their places.\n\nZero isn't an odd number and you don't need to move it. If you have an empty array, you need to return it.\n'''\n\ndef organiza_impares(referencia):\n # Separa ímpares da entrada\n impares = [x for x in referencia if x % 2 != 0]\n impares.sort() # Organiza ímpares em ordem crescente\n \n # Substitui na entrada ímpares por um marcador de posição qualquer,\n # no caso, \"A\"\n placeholder = [\"A\" if x % 2 != 0 else x for x in referencia]\n\n for impar in impares: # Para cada ímpar\n # substituir o próximo marcador \"A\" pelo ímpar\n placeholder[placeholder.index(\"A\")] = impar\n return placeholder # retorna a lista corrigida","sub_path":"all/082-Sort-the-Odd.py","file_name":"082-Sort-the-Odd.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"73882213","text":"import src.Search as S\nimport os\nimport timeit\nimport datetime\nimport gpxpy.gpx\n\nif __name__ == '__main__':\n try:\n max_depth = int(input('Write down the maximum depth desired: '))\n except ValueError:\n print(\"[ValueError] Not valid type. Must be an integer\")\n raise SystemExit\n\n try:\n inc_depth = int(input('Write down the increment of depth desired: '))\n except ValueError:\n print(\"[ValueError] Not valid type. Must be an integer\")\n raise SystemExit\n\n pruning = input('Do you want to use pruning? (y/n) ')\n\n if pruning == 'y':\n pruning = True\n elif pruning == 'n':\n pruning = False\n else:\n print(\"[ValueError] Not valid type. Must be \\\"y\\\" or \\\"n\\\"\")\n raise SystemExit\n\n strategy = input(\"Select the strategy to apply (bfs, dfs, dls, ids, ucs, gs, a*): \")\n\n if (strategy != 'bfs') and (strategy != 'dfs') and (strategy != 'dls') and (strategy != 'ids')\\\n and (strategy != 'ucs') and (strategy != 'gs') and (strategy != 'a*'):\n print(\"[ValueError] Not valid strategy. Must be \\\"bfs\\\", \\\"dfs\\\", \\\"dls\\\", \\\"ids\\\", \\\"ucs\\\", \\\"gs\\\" or \\\"a*\\\"\")\n raise SystemExit\n\n if (strategy == 'a*') or (strategy == 'gs'):\n heuristic = int(input(\"Select the heuristic to use (0, 1): \"))\n\n if (heuristic != 0) and (heuristic != 1):\n print(\"[ValueError] Not valid heuristic\")\n raise SystemExit\n else:\n heuristic = 0\n\n jsonPath = input(\"Enter the path to the .json file: \")\n\n start = timeit.default_timer()\n searching = S.Search(jsonPath, strategy, max_depth, inc_depth, pruning, heuristic)\n timespent = timeit.default_timer() - start\n print(\"Execution time: \" + str(timespent))\n\n if not searching.solution:\n print(\"\\nNo solution found\")\n else:\n file = open(\"solution.txt\", \"w+\")\n gpxFile = open(\"solution.gpx\", \"w+\")\n gpx = gpxpy.gpx.GPX()\n\n gpx_track = gpxpy.gpx.GPXTrack()\n gpx.tracks.append(gpx_track)\n\n gpx_segment = gpxpy.gpx.GPXTrackSegment()\n gpx_track.segments.append(gpx_segment)\n\n for node in searching.solution[0]:\n if node.parent is None:\n file.write(\"Initial Node: \" + node.state.currentPosition + \"\\nI have to visit \"\n + str(node.state.nodesRemaining) + \"\\n\")\n else:\n file.write(\"\\n\" + node.action + \"\\nI have to visit \" + str(node.state.nodesRemaining) + \"\\n\")\n\n gpx_segment.points.append(gpxpy.gpx.GPXTrackPoint(\n searching.problem.StateSpace.graph.positionNode(node.state.currentPosition)[1],\n searching.problem.StateSpace.graph.positionNode(node.state.currentPosition)[0],\n elevation=0, time=datetime.datetime.now(), name=node.state.currentPosition))\n\n file.write(\"\\nTotal nodes generated: \" + str(searching.solution[1]) + \"\\n\")\n file.write(\"The cost of the path is \" + str(searching.solution[0][-1].pathcost) + \"\\n\")\n file.write(\"The solution was found at depth \" + str(searching.solution[0][-1].d) + \"\\n\")\n file.write(\"The solution was found in \" + str(timespent) + \" seconds\")\n\n file.close()\n\n gpxFile.write(gpx.to_xml())\n gpxFile.close()\n\n print(\"\\nSolution found!! You can see it at \" + os.path.abspath(\"../solution.txt\") + \" and \"\n + os.path.abspath(\"../solution.gpx\"))\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"194194901","text":"import os\nimport torch\nfrom torch.autograd import Variable\nimport numpy as np\nimport cv2\nfrom ssd import build_ssd\nfrom data import VOC_CLASSES as labels\nif torch.cuda.is_available():\n torch.set_default_tensor_type('torch.cuda.FloatTensor')\n\n\ndef generate_frame(source, destination, net):\n for fname in os.listdir(source):\n if fname in destination:\n continue\n image = cv2.imread(os.path.join(source, fname))\n rgb_image = image.copy()\n\n x = cv2.resize(image, (300, 300)).astype(np.float32)\n x -= (104.0, 117.0, 123.0)\n x = x.astype(np.float32)\n x = x[:, :, ::-1].copy()\n x = torch.from_numpy(x).permute(2, 0, 1)\n\n xx = Variable(x.unsqueeze(0))\n\n xx = xx.cuda()\n y = net(xx)\n\n detections = y.data\n\n scale = torch.Tensor(rgb_image.shape[1::-1]).repeat(2)\n for i in range(detections.size(1)):\n j = 0\n while detections[0, i, j, 0] >= 0.17:\n score = detections[0, i, j, 0]\n label_name = labels[i - 1]\n if label_name == 'person':\n display_txt = '%s: %.2f' % (label_name, score)\n pt = (detections[0, i, j, 1:] * scale).cpu().numpy()\n w_tbox = abs(pt[0]-pt[2]-2)\n h_tbox = 50 * 0.005 * w_tbox\n\n color = (50, 50, 242)\n rgb_image = cv2.rectangle(rgb_image, (pt[0], pt[1]), (pt[2], pt[3]), color, 2)\n rgb_image = cv2.rectangle(rgb_image, (int(pt[0]-1), pt[1]), (int(pt[2]+1), int(pt[1]-h_tbox)),\n color, -1)\n rgb_image = cv2.putText(rgb_image, display_txt, (int(pt[0]-1), int(pt[1]-h_tbox/3)),\n cv2.FONT_HERSHEY_SIMPLEX, 0.005*abs(pt[0]-pt[2]),\n (255, 255, 255), 2)\n j += 1\n cv2.imwrite(os.path.join(destination, fname), rgb_image)\n\n\nif __name__ == '__main__':\n SOURCE = '/media/federico/Volume1/remote/datasets/jjta/jta_out/prova9'\n DESTINATION = '/media/federico/Volume1/remote/datasets/jjta/jta_out/prova10'\n\n net = build_ssd('test', 300, 21) # initialize SSD\n net.load_weights('./weights/ssd300_mAP_77.43_v2.pth')\n net = net.cuda()\n\n generate_frame(SOURCE, DESTINATION, net)\n","sub_path":"convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":2373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"290925560","text":"# -*- coding: utf-8 -*-\n'''\nЗадание 7.3b\n\nСделать копию скрипта задания 7.3a.\n\nДополнить скрипт:\n- Запросить у пользователя ввод номера VLAN.\n- Выводить информацию только по указанному VLAN.\n\nОграничение: Все задания надо выполнять используя только пройденные темы.\n\n'''\nwith open('CAM_table.txt','r') as f:\n\ti=0\n\ts=list('')\n\tfor line in f:\n\t\tif '.' in line:\n\t\t\ts += [line.split()]\ns.sort()\nvlan = str(input('Enter vlan number: '))\nfor i in range(len(s)):\n\ta,b,_,c = s[i]\n\tif a == vlan:\n\t\tprint('{} {} {}'.format(a,b,c))\n","sub_path":"exercises/07_files/task_7_3b.py","file_name":"task_7_3b.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"430643017","text":"#!/usr/bin/bash\n# -*- encoding: utf-8 -*-\n# filename: predcnn.py\n\n\nimport mxnet as mx\nfrom mxnet import gluon, nd, autograd\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom collections import namedtuple\n\n\n\nctx_gpu = mx.gpu()\n\n\nbatch_size = 256\nnum_inputs = 784\nnum_outputs = 10\nnum_fc = 512\ndef transform(data, label):\n return nd.transpose(data.astype(np.float32),(2,0,1))/255, label.astype(np.float32)\ncifar10_test = gluon.data.vision.CIFAR10('./cifar10/test', train=False, transform = transform)\ntest_data = gluon.data.DataLoader(cifar10_test, batch_size, shuffle=True)\n\ncifar10_train = gluon.data.vision.CIFAR10('./cifar10/train', train=True, transform = transform)\ntrain_data = gluon.data.DataLoader(cifar10_train, batch_size, shuffle=True)\n\n\n# import the model\nimport os\nsavedir = 'trycnn_save_export'\nabspath = ''.join([os.getcwd(), os.path.sep, savedir])\nif not os.path.exists(abspath):\n print('no such path: {}'.format(abspath))\n os._exit(0)\nelse:\n print(\"existing path found: {}\".format(abspath))\n\nnetsym = mx.sym.load(abspath+'/trycnn-symbol.json')\n\n\n\n\n\n\nnet = mx.mod.Module(symbol=netsym, label_names=None, context=ctx_gpu)\nnet.bind(data_shapes=[('data',(1,3,32,32))], for_training=True)\nnet.load_params(abspath+'/trycnn-0000.params')\nbatch = namedtuple('batch', ['data'])\n\n\n\n### predict\n# acc = mx.metric.Accuracy()\n# for data, label in test_data:\n# data = data.as_in_context(ctx_gpu)\n# label = label.as_in_context(ctx_gpu)\n#\n# net.forward(batch([data]))\n# scores = net.get_outputs()[0]\n#\n# pred = nd.argmax(scores, axis=1)\n# acc.update(label, pred)\n#\n# result = acc.get()[1]\n#\n# print('final accuracy is: {}'.format(result))\n#\n\n\n\n## one more epoch of training\nloss_fun = gluon.loss.SoftmaxCrossEntropyLoss()\n# net.init_optimizer(optimizer='adam', optimizer_params=(('learning_rate',1e-3), ('beta1',0.9), ('beta2', 0.999), ('epsilon', 1e-7), ('wd', 1e-3)))\n\nprint_each_iters = 20\naccuracy = mx.metric.Accuracy()\nfor i, (data, label) in enumerate(train_data):\n data = data.as_in_context(ctx_gpu)\n label = label.as_in_context(ctx_gpu)\n\n net.forward(batch([data]))\n scores = net.get_outputs()[0]\n\n print(scores)\n\n # scores.attach_grad()\n # with autograd.record():\n # loss = loss_fun(scores, label)\n # loss_avg = nd.mean(loss)\n # loss_avg.backward()\n #\n # print(type(scores.grad))\n #\n # net.backward()\n # net.update()\n #\n # accuracy.update(pred, label)\n # rate = accuracy.get()[1]\n #\n # if i % print_each_iters == 0:\n # print(\"epoch {}, iterator {}, loss is: {}\".format(e, i, loss_avg))\n\n\n\n\n","sub_path":"python/mxnet/predcnn.py","file_name":"predcnn.py","file_ext":"py","file_size_in_byte":2659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"366536809","text":"#!/usr/bin/env python3\n\nimport os\n\nos.environ['RADICAL_DEBUG'] = 'True'\n\n\nimport sys\nimport time\nimport argparse\n\nimport multiprocessing as mp\n# import pandas as pd\n# import numpy as np\n\nfrom openeye import oechem\nfrom impress_md import interface_functions as iface\n\n\nimport radical.utils as ru\nimport radical.pilot as rp\n\n\n# ------------------------------------------------------------------------------\n#\nclass MyWorker(rp.raptor.Worker):\n '''\n This class provides the required functionality to execute work requests.\n In this simple example, the worker only implements a single call: `dock`.\n '''\n\n # --------------------------------------------------------------------------\n #\n def __init__(self, cfg):\n\n cfg = ru.Config(cfg=ru.read_json(cfg))\n # cfg['cores'] = 48\n\n rp.raptor.Worker.__init__(self, cfg)\n\n # self.register_call('dock', self.dock)\n\n self._log.debug('started worker %s', self._uid)\n\n\n # --------------------------------------------------------------------------\n #\n def get_root_protein_name(self, file_name):\n\n return file_name.split(\"/\")[-1].split(\".\")[0]\n\n\n # --------------------------------------------------------------------------\n #\n def pre_exec(self):\n\n try:\n\n workload = self._cfg.workload\n\n self._log.debug('pre_exec (%s)', workload.output)\n\n receptor_file = 'input_dir/receptors.v8/%s.oeb' % workload.receptor\n smiles_file = 'input_dir/smiles/%s.csv' % workload.smiles\n output = './out.%s.sdf' % self._uid\n\n self.verbose = workload.verbose\n self.force_flipper = workload.force_flipper\n use_hybrid = workload.use_hybrid\n high_resolution = workload.high_resolution\n\n self.ofs = oechem.oemolostream(output)\n\n self.ofs_lock = mp.Lock()\n self.pdb_name = self.get_root_protein_name(receptor_file)\n\n self._fin = open(smiles_file, 'r')\n self.columns = self._cfg.columns\n self.smiles_col = self._cfg.smi_col\n self.name_col = self._cfg.lig_col\n self.idxs = self._cfg.idxs\n\n self.docker, _ = iface.get_receptor(receptor_file,\n use_hybrid=use_hybrid,\n high_resolution=high_resolution)\n\n except Exception:\n self._log.exception('pre_exec failed')\n raise\n\n\n # --------------------------------------------------------------------------\n #\n def get_data(self, off):\n\n self._fin.seek(off)\n line = self._fin.readline()\n print('LINE [%d]: %s' % (off, line.rstrip()))\n # ccount = line.count(',') # FIXME: CVS parse on incorrect counts\n data = line.split(',')\n return data\n\n\n # --------------------------------------------------------------------------\n #\n def dock(self, pos, off, uid):\n\n # self._prof.prof('dock_start', uid=uid)\n try:\n\n # TODO: move smiles, ligand_name into args\n data = self.get_data(off)\n smiles = data[self._cfg.smi_col]\n ligand_name = data[self._cfg.lig_col]\n\n score, res, ligand = iface.RunDocking_(smiles,\n dock_obj=self.docker,\n pos=pos,\n name=ligand_name,\n target_name=self.pdb_name,\n force_flipper=self.force_flipper)\n out = list()\n if self.ofs and ligand is not None:\n for i, col in enumerate(self._cfg.columns):\n if col.lower() != 'smiles':\n value = data[i].strip()\n if value and 'na' not in value.lower():\n try:\n oechem.OESetSDData(ligand, col, value)\n # out.append([i, 'ok'])\n except ValueError:\n # out.append([i, 'err_value'])\n pass\n else:\n pass\n # out.append([i, 'no_value'])\n\n # self._prof.prof('dock_io_start', uid=uid)\n\n with self.ofs_lock:\n oechem.OEWriteMolecule(self.ofs, ligand)\n try:\n oechem.flush()\n oechem.close()\n except:\n pass\n\n # self._prof.prof('dock_io_stop', uid=uid)\n\n else:\n out.append([None, 'skip'])\n\n finally:\n # self._prof.prof('dock_stop', uid=uid)\n pass\n\n # self._log.debug(out)\n return out\n\n\n# ------------------------------------------------------------------------------\n#\nif __name__ == '__main__':\n\n # the `info` dict is passed to the worker as config file.\n # Create the worker class and run it's work loop.\n worker = MyWorker(sys.argv[1])\n\n worker.start()\n worker.join()\n\n\n# ------------------------------------------------------------------------------\n\n","sub_path":"workflow-0/wf0_oe_frontera/impeccable/wf0_worker.py","file_name":"wf0_worker.py","file_ext":"py","file_size_in_byte":5511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"152550053","text":"# 표준 체중을 구하는 프로그램을 작성하시오\n# 표준 체중 : 각 개인의 키에 적당한 체중\n\n# 성별에 따른 공식\n# 남자 : 키(m) x 키(m) x 22\n# 여자 : 키(m) x 키(m) x 21\n\n# 조건1 : 표준 체중은 별도의 함수 내에서 계산\n # * 함수명 : std_weight\n # * 전달값 : 키(height), 성별(gender)\n# 조건2 : 표준 체중은 소수점 둘째자리까지 표시\n\n# 출력예제\n# 키 175cm 남자의 표준 체중은 67.38kg 입니다.\n\ndef std_weight(height, gender):\n if gender == \"여\":\n height = height / 100\n weight = str(height * height * 21)[:5]\n print(\"키 {0}cm 여성의 표준체중은 {1}kg 입니다.\".format(int(height*100), weight))\n elif gender == \"남\":\n # weight = str(height * height * 22)[:5]\n height = height / 100\n weight = round((height * height * 22), 5)\n print(\"키 {0}cm 남성의 표준체중은 {1}kg 입니다.\".format(int(height*100), weight))\n\nstd_weight(175, \"여\")\nstd_weight(190, \"남\")","sub_path":"average_weight.py","file_name":"average_weight.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"389571557","text":"## SQL Alchemy database setup.\nimport os\nimport sys\n\nfrom sqlalchemy import Column, ForeignKey, Integer, String\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import relationship\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy import create_engine\n\nBase = declarative_base()\n\n\nclass Catagory(Base):\n\t__tablename__ = 'catagory'\n\tid = Column(Integer, primary_key = True)\n\tname = Column(String(250), nullable = False)\n\n\nclass CatalogItem(Base):\n\t__tablename__ = 'catalog_item'\n\tid = Column(Integer, primary_key = True)\n\tname = Column(String(250), nullable = False)\n\tdescription = Column(String(250))\n\tprice = Column(String(8))\n\tcatagory_id = Column(Integer, ForeignKey('catagory.id'))\n\tcatagory = relationship(Catagory)\n\n# ORM finishing stuff for SqlAlchemy\nengine = create_engine('sqlite:///catalog.db')\nBase.metadata.create_all(engine)\n\nDBSession = sessionmaker(bind = engine)\nsession = DBSession()\nfirstCatagory = Catagory(name = \"Football\")\nsession.add(firstCatagory)\nfootball = CatalogItem(name = \"Football\", description = \"oblong spheroid generealy made of leather used to play American style Gridiron Football\",\n\t\t\t\t\t price = \"$50.00\", catagory_id = firstCatagory.id, catagory = firstCatagory)\nsession.add(football)\nvolleyball = Catagory(name = \"Volleyball\")\nsession.add(volleyball)\nvb_net = CatalogItem(name = \"Volleyball Net\", description = \"Net used to seperate sides of the court for Volleyball or badmitton\",\n\t\t\t\t\t price = \"$100.00\", catagory_id = volleyball.id, catagory = volleyball)\nsession.add(vb_net)\nvolley_ball = CatalogItem(name = \"Volleyball\", description = \"Ball for batting around above a net\",\n\t\t\t\t\t price = \"$30.00\", catagory_id = volleyball.id, catagory = volleyball)\nsession.add(volley_ball)\nsession.commit()","sub_path":"vagrant/catalog/catalog_database_setup.py","file_name":"catalog_database_setup.py","file_ext":"py","file_size_in_byte":1775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"106535729","text":"#!/usr/local/bin/python3\n\n# https://realpython.com/python-gui-tkinter/#building-a-text-editor-example-app\nimport harvestExpLearn8a as harvest\nimport tkinter as tk\nimport tkinter.ttk as ttk\nimport time\nimport sys\nfrom tkinter.filedialog import askopenfilename, asksaveasfilename\nimport os\nfrom os import path\nimport pickle\nimport csv\nfrom multiprocessing import Process, freeze_support\n\n\n########## from https://www.edureka.co/community/43417/stdout-to-tkinter-gui\nclass StdoutRedirector(object):\n def __init__(self,main_large_text_field):\n self.main_large_text_field = main_large_text_field\n\n def write(self,string):\n self.main_large_text_field.insert(tk.END, string)\n self.main_large_text_field.see(tk.END)\n\n###############################\n\t\t\nclass RunThis:\n\t\n\tdef __init__(self, master=None):\n#\t\t Frame.__init__(self, master)\n\t\tglobal DEBUG_PRINT\n\t\tDEBUG_PRINT = True\n\n\t\tself.window = master\n\t\tself.pickle_db_name = \"pickle_db_8\"\n\t\tself.script_path = ''\n#\t\t self.trainingSets = ''\n\t\tself.target_file_path = ''\n\t\tself.stopwords_file_path = ''\n\t\tself.trainingSets=\t[]\n\t\tself.training_file_path0 = ''\n\t\tself.training_file_path1 = ''\n\t\tself.training_file_path2 = ''\n\t\tself.script_key = 'script'\n\t\tself.target_key = 'target'\n\t\tself.stopwords_key = 'stopwords'\n\t\tself.training_file_key = 'training'\n\t\tself.training_file_key0 = 'training0'\n\t\tself.training_file_key1 = 'training1'\n\t\tself.training_file_key2 = 'training2'\n\t\tself.buttons_frame = tk.Frame(window, relief=tk.RAISED, bd=2)\n\t\t\n\t\tself.script_path_label = self.create_label(1, 'blue', self.script_path) \n\t\tself.target_path_label = self.create_label(1,'green', self.target_file_path)\n\t\tself.stopwords_file_path_label = self.create_label(1, 'blue', self.stopwords_file_path)\n\t\tself.training_sets_path_label = self.create_label(1, 'green', self.training_file_path0)\n\t\t\n\t\tself.main_large_text_field = tk.Text(window, fg = \"blue\")\n\t\tself.gui_list = []\n#\t\t self.update_cwd()\n\n#\t\t self.retrieve_file_paths_from_database()\n\n\t\t#,global main_large_text_field\n\t\tself.style = ttk.Style()\n\t\tself.style.configure('B.TButton', foreground='blue')\n\t\tself.style.configure('G.TButton', foreground='green')\n\t\tself.style.configure('R.TButton', foreground='red') \n\t\t\n#\t\tos.fdopen(sys.stdin.fileno(), 'rb', buffering=0)\n\t\tsys.stderr = sys.stdout\n\t\tsys.stdout = StdoutRedirector(self.main_large_text_field)\n\n\t\tself.go()\n\t\n\tdef go(self):\n\t\tself.create_window()\n\t\tself.add_paths_and_buttons()\n\t\tself.build_menus()\n\t\tself.setup_database()\n\t\t\n#\t\t self.print_file_paths()\n#\t\t self.display_file_paths()\n\n\tdef __repr__(self):\n\t\treturn (f'{self.__class__.__name__}')\n\n\t \n\tdef create_label(self, line_scale, color, text):\n#\t\t ltgray = '#f2f2f2'\n\t\tnumber_of_lines = 300\n\t\tlabel = tk.Label(self.buttons_frame, text='No file(s) currently selected.\\nClick the button above to select.',\n\t\t\t\t\t\t fg=color, wraplength = number_of_lines*line_scale, justify=tk.LEFT)\n#\t\t label.configure(state=tk.NORMAL)\t \n\t\treturn label\n\n#\t def create_text_field(self, line_scale, color, text):\n#\t\t ltgray = '#f2f2f2'\n#\t\t number_of_lines = 4\n#\t\t text_obj = tk.Text(self.buttons_frame, height=number_of_lines*line_scale, width=23, fg=color, bg = ltgray)\n#\t\t if text =='':\n#\t\t\t text_obj.insert(tk.END, 'No file(s) currently selected.\\nClick the button above to select.')\n#\t\t text_obj.configure(state=tk.NORMAL)\t \n#\t\t return text_obj\n\n\n\tdef setup_database(self):\n#\t\t https://docs.python.org/3/library/dbm.html#module-dbm\n\t\tprint(\"setup_database\")\n\t\tself.script_key = 'script'\n\t\tself.target_key = 'target'\n\t\tself.stopwords_key = 'stopwords'\n\t\tself.training_key = 'training'\n#\t\t os.chdir(os.path.dirname(__file__))\n\t\tprint(os.getcwd())\n\t\tdb_file = os.getcwd()+\"/\"+self.pickle_db_name\n\t\t#db_file = os.getcwd()+\"/toadstool\"\n\t\tif path.exists(db_file):\n#\t\t\t print(\"RT 87 db_path :\", db_file)\n\t\t\tsize = os.path.getsize(db_file)\n\t\t\tif (size > 0):\n\t\t\t\tself.get_file_paths_from_database()\t \n\n\t\t'''''\t\t \n\t\tif path.exists(db_path):\n\t\t\tself.db_has_data = True\n#\t\t\t self.get_file_paths_from_database()\n\t\t\tself.get_file_paths_from_database\t\t\t \n\t\telse:\t\t\t \n\t\t\tself.db_has_data = False\n#\t\t\t self.pickle_db_name = open(self.pickle_db_name, 'ab')\n\t\t\tself.get_file_paths_from_database\t\t\t \n\t\t\tself.db_has_data = True\n\t\t'''\n# \n\tdef store_file_paths_in_database(self):\n\t\ttry:\n\t\t\tself.pickle_write_db_name = open(self.pickle_db_name, 'wb')\n#\t\t\t db = {}\n#\t\t\t db[self.script_key] = self.script_path\n#\t\t\t db[self.target_key] = self.target_file_path\n#\t\t\t db[self.stopwords_key] = self.stopwords_file_path o\n\t\t\t\n\t\t\tpickle.dump(self.script_path, self.pickle_write_db_name)\n\t\t\tpickle.dump(self.target_file_path, self.pickle_write_db_name)\n\t\t\tpickle.dump(self.stopwords_file_path, self.pickle_write_db_name)\n#\t\t\t self.number_training_files_as_string = str( len(self.trainingSets))\n\t\t\tnumber_training_files = len(self.trainingSets)\n\t\t\tnumber_training_files_as_str = str(number_training_files)\n\t\t\tprint(\"RT 151 number of training files: \", number_training_files_as_str)\n#\t\t\t pickle.dump(number_training_files_as_str,\tself.pickle_db_name)\n\t\t\tpickle.dump(self.trainingSets, self.pickle_write_db_name)\n\t\t\t#for training_path in self.trainingSets:\n\t\t\t#\t pickle.dump(training_path, self.pickle_write_db_name)\n\t\t\t#\t print(\"RT 153 training_path\", training_path)\n#\t\t\t pickle.dump(str(self.trainingSets), self.pickle_db_name)\t\t \n\t\t\tself.pickle_write_db_name.close()\n\t\texcept EOFError as eof_err:\n\t\t\tprint(\"RT 154 EOF error: {0}\".format(eof_err))\n\t\texcept OSError as err:\n\t\t\tprint(\"RT 156 OS error: {0}\".format(err))\n\t\texcept ValueError:\n\t\t\tprint(\"RT 158 Could not convert data to an integer.\")\n\t\texcept TypeError:\n\t\t\tprint(\"RT 160 type error:\", sys.exc_info()[0])\n\t\texcept pickle.PickleError:\n\t\t\tprint(\"RT 162 pickle error:\", sys.exc_info()[0])\n\t\t\n\tdef get_file_paths_from_database(self):\n\t\ttry:\n\t\t\tself.pickle_open_db_name = open(self.pickle_db_name, 'rb')\n#\t\t\t db = pickle.load(self.pickle_db_name)\n#\t\t\t self.script_path = db[self.script_key]\n#\t\t\t self.target_file_path = db[self.target_key]\n#\t\t\t self.stopwords_file_path = db[self.stopwords_key]\n\t\t\tself.script_path = pickle.load(self.pickle_open_db_name)\n\t\t\tself.target_file_path = pickle.load(self.pickle_open_db_name)\n\t\t\tself.stopwords_file_path = pickle.load(self.pickle_open_db_name)\n#\t\t\t number_training_files\t= pickle.load(self.pickle_db_name)\n#\t\t\t number_training_files_as_string = pickle.load(self.pickle_db_name)\n#\t\t\t print(\"RT 181 number of elements: \", number_training_files_as_string)\n#\t\t\t number_training_files = int(number_training_files_as_string)\n#\t\t\t number_training_files = 10\n\t\t\tself.trainingSets = pickle.load(self.pickle_open_db_name)\n\t\t\t#for path in self.trainingSets(range = number_training_files):\n\t\t\t#for path in self.trainingSets:\n\t\t\tfor path1 in self.trainingSets:\n\t\t\t\tprint(path1)\n\t\t\t\t #pickle.dump(self.training_file_path+Str(index), self.pickle_db_name)\n\n\t\t\tself.pickle_open_db_name.close()\n\t\texcept TypeError as err:\n\t\t\tprint(\"RT 188 TypeError: \", err)\n\t\texcept pickle.UnpicklingError:\n\t\t\tprint(\"RT 150 pickle error:\", sys.exc_info()[0])\n\t\tself.display_file_paths()\n \n#\t\t\t self.script_path = db[self.script_key]\n#\t\t\t self.target_file_path = db[self.target_key]\n#\t\t\t self.stopwords_file_path = db[self.stopwords_key]\n#\t\t\t try:\n#\t\t\t\t a = 7\n# #\t\t\t\t\tself.trainingSets = db[self.training_key]\n# #\t\t\t\t\tprint(\"159 self.trainingSets_x: \", self.trainingSets_x)\n# #\t\t\t\t\tself.trainingSets = ast.literal_eval(self.trainingSets_x)\n#\t\t\t except TypeError:\n#\t\t\t\t print(\"RT 171 type error:\", sys.exc_info()[0])\n\n#\t\t\t self.pickle_db_name.close()\n#\t\t except EOFError as eof_err:\n#\t\t\t print(\"RT 165 EOF error: {0}\".format(eof_err))\n#\t\t except OSError as err:\n#\t\t\t print(\"RT 167 OS error: {0}\".format(err))\n#\t\t except ValueError:\n#\t\t\t print(\"RT 169 OS Could not convert data to an integer.\")\n\n\tdef display_training_sets(self):\n\t\tfiles = ''\n\t\tfor path1 in self.trainingSets:\n\t\t\tfile = os.path.basename(path1)+'\\n'\n\t\t\tfiles += file\n\t\tself.training_sets_path_label.configure(text = files, wraplength = 300)\n\t\n\tdef display_file_paths(self):\n\t\tprint('Entering display_file_paths()')\n\t\tself.print_file_paths()\n\t\tself.script_path_label.configure(text = self.script_path)\n\t\tself.target_path_label.configure(text = self.target_file_path)\t\t \n\t\tself.stopwords_file_path_label.configure(text = self.stopwords_file_path)\n\t\tself.display_training_sets()\n\t\t\n\tdef set_individual_training_files(self):\n\t\tindex = 0\n\t\tprint(\"In Set invidual training files\", self.trainingSets)\n\t\tfor file in self.trainingSets:\n\t\t\tif index == 0:\n\t\t\t\tself.training_file_path0 = file\n\t\t\tif index == 1:\n\t\t\t\tself.training_file_path1 = file\n\t\t\tif index == 2:\n\t\t\t\tself.training_file_path2 = file\n\t\t\tindex +=1\n\t\t\t\n\tdef print_file_paths(self):\n#\t\t self.get_file_paths_from_database()\n#\t\t self.get_individual_training_files()\n\t\tprint(\"\\n\")\n#\t\t print(self.cwd: \\n\", self.cwd, \"\\n\")\n\t\tprint(\"self.script_path: \\n\", self.script_path, \"\\n\")\n\t\tprint(\" self.target_file_path: \\n\", self.target_file_path, \"\\n\")\n\t\tprint(\" self.stopwords_file_path: \\n\", self.stopwords_file_path, \"\\n\")\n\t\tfor path1 in self.trainingSets:\n\t\t\tprint(path1)\n\n\tdef select_a_file(self, file_type_string):\n\t\t\"\"\"Select calculation script file.\"\"\"\n\t\tselected_file_path = askopenfilename(\n\t\t\tfiletypes=[(\"A file\", file_type_string)]\n\t\t)\n\t\tif not selected_file_path:\n\t\t\treturn\n\t\twith open(selected_file_path, \"r\") as input_file:\n\t\t\ttext = input_file.read()\n\t\t\tself.main_large_text_field.delete(1.0, tk.END)\n\t\t\tself.main_large_text_field.insert(tk.END, text)\n\t\twindow.title(f\"{selected_file_path}\")\n\t\tprint(\"\\n\\nRT 206 selected_file_path:\",selected_file_path)\n\t\treturn selected_file_path\n \n\tdef select_python_script(self):\n\t\t\"\"\"Select calculation script file.\"\"\"\n\t\tself.script_path = self.select_a_file(\"*.py\")\n\t\tself.display_file_paths()\n\t\tself.db_has_data= True\n\n\tdef select_target_file(self):\n\t\t\"\"\"Select a target file.\"\"\"\n\t\tself.target_file_path = self.select_a_file(\"*.csv\")\n\t\tself.display_file_paths()\n\t\tself.db_has_data= True\n\t\t\n\tdef select_stopwords_file(self):\n\t\t\"\"\"Open stopwords file for reading.\"\"\"\n\t\tself.stopwords_file_path = self.select_a_file(\"*.txt\")\n\t\tself.display_file_paths()\n\t\tself.db_has_data= True\n\n\tdef convert_tuple_into_list(self,tpl):\n\t\tlist = []\n\t\tfor element in tpl:\n\t\t\tlist.append(element)\n\t\treturn list\n\n\tdef select_training_files(self):\n\t\t\"\"\"Select training files.\"\"\"\n\t\ttraining_file_paths = askopenfilename(multiple=True,\n\t\t\tfiletypes=[(\"CSV Files\", \"*.csv\")]\n\t\t)\n\t\tif not training_file_paths:\n\t\t\treturn\n\t\tself.trainingSets = training_file_paths\n\t\tself.main_large_text_field.delete(1.0, tk.END)\n\t\tprint(304, training_file_paths)\n\t\ttrainingTuples = training_file_paths\n\t\ttrainingList = self.convert_tuple_into_list(trainingTuples)\n\t\tprint(trainingList)\n\t\tself.trainingSets = trainingList # actually, a list\n#\t\tprint( 304, \"RT self.trainingSets\", self.trainingSets)\n#\t\t self.training_file_paths = self.select_a_file(\"*.py\")\n#\t\t for file_path in trainingList:\n#\t\t\t self.main_large_text_field.insert(tk.END, file_path +\"\\n\")\n\t\tself.set_individual_training_files()\n\t\tself.display_file_paths()\n\t\twindow.title(f\"trainingFiles\")\n\t\t\n\n\n\tdef run_harvest(self):\n\t\tglobal argv\n\t\n\t\t\"\"\" run the calculation \"\"\"\n\t\twindow.title(f\"Calculations\")\n\t\tsys.argv = [self.script_path, self.trainingSets, \"-t\", self.target_file_path, \"-s\", self.stopwords_file_path]\n\t\tprint(\"RunThis 315 self.stopwords_file_path\t :\", self.stopwords_file_path)\n#\t\t text = self.main_large_text_field.get(1.0, tk.END)\n\t\tself.main_large_text_field.replace(1.0, tk.END, \"Starting the calculation...\")\n# \t\tprint(\"RT 323 Starting the calculation.\")\n\t\ttimeStart = time.time()\n\t\twindow.title(f\"Calculating\")\n#\t\t from multiprocessing import Process\n#\t\t p = Process(target=harvest.run_harvest_orig, args=())\n#\t\t p.start()\n#\t\t p.join()\n\t\t\n\t\tharvest.run_harvest_orig()\n\t\ttimeEnd = time.time()\n\t\telapsedTime = int(timeEnd-timeStart)\n\t\tresult = \"Finished the calculation in \" + str(elapsedTime) + \" seconds\"\n#\t\tself.main_large_text_field.insert(tk.END, result)\n#\t\tprint(\"RT 336 \", result)\n#\n#\t\t self.main_large_text_field.insert(tk.END, result)\n\t\t\n\tdef open_text_file(self):\n\t\t\"\"\"Open a file for editing.\"\"\"\n\t\tfilepath = askopenfilename(\n\t\t\t\tfiletypes=[(\"Text Files\", \"*.txt\")]\n\t\t\t)\n\t\tif not filepath:\n\t\t\treturn\n\t\tself.main_large_text_field.delete(1.0, tk.END)\n\t\twith open(filepath, \"r\") as input_file:\n\t\t\ttext = input_file.read()\n\t\t\tself.main_large_text_field.insert(tk.END, text)\n\t\t\twindow.title(f\"{filepath}\")\n\n\n\tdef open_result_file(self):\n\t\t\"\"\"Open a file.\"\"\"\n\t\tfilepath = askopenfilename(\n\t\t\tfiletypes=[(\"CSV Files\", \"*.csv\")]\n\t\t)\n\t\tif not filepath:\n\t\t\treturn\n#\t\tdisplayCSVFile(filepath)\n\t\tself.main_large_text_field.delete(1.0, tk.END)\n\t\twith open(filepath, \"r\") as output_result_file:\n\t\t\ttext = output_result_file.read()\n\t\t\tself.main_large_text_field.insert(tk.END, text)\n\t\twindow.title(f\"Result - {filepath}\")\n\t\t\n\tdef save_file(self):\n\t\t\"\"\"Save the current file as a new file.\"\"\"\n\t\tfilepath = asksaveasfilename(\n\t\t\tdefaultextension=\"csv\",\n\t\t\tfiletypes=[(\"CSV Files\", \"*.csv\"), (\"All Files\", \"*.*\")],\n\t\t)\n\t\tif not filepath:\n\t\t\treturn\n\t\twith open(filepath, \"w\") as output_file:\n\t\t\ttext = self.main_large_text_field.get(1.0, tk.END)\n\t\t\toutput_file.write(text)\n\t\twindow.title(f\"Simple Text Editor - {filepath}\")\n\t\t\n\tdef quit(self):\n\t\t\"\"\" quit the program \"\"\"\n#\t\t self.pickle_db_name.close()\n#\t\t self.db.close()\n\t\tself.store_file_paths_in_database()\n\t\tsys.stdout = sys.__stdout__\n\t\twindow.destroy()\n\n\tdef create_window(self):\n\t\twindow.title(\"Run This => BuildABear\")\n\t\twindow.rowconfigure(0, minsize=600, weight=1)\n\t\twindow.columnconfigure(1, minsize=1200, weight=1)\n\n\n\tdef build_menus(self):\n\t\tmenubar = tk.Menu(window)\n\t\tfilemenu = tk.Menu(menubar, tearoff=0)\n\t\tfilemenu.add_command(label=\"Select Python Script...\", command=self.select_python_script, accelerator=\"Command+1\")\n\t\tfilemenu.add_command(label=\"Select Target CSV File...\", command=self.select_target_file, accelerator=\"Command-2\")\n\t\tfilemenu.add_command(label=\"Select Stopwords Text File...\", command=self.select_stopwords_file, accelerator=\"Command-3\")\n\t\tfilemenu.add_command(label=\"Select Training CSV Files...\", command=self.select_training_files, accelerator=\"Command-4\")\n\t\tfilemenu.add_separator()\n\t\tfilemenu.add_command(label=\"Run\", command=self.run_harvest, accelerator=\"Command+5\")\n\t\tfilemenu.add_separator()\n\t\tfilemenu.add_command(label=\"display_file_paths\", command=self.display_file_paths, accelerator=\"Command+\")\n\t\tfilemenu.add_command(label=\"store_file_paths_in_database\", command=self.store_file_paths_in_database, accelerator=\"Command+\")\n\t\tfilemenu.add_command(label=\"get_file_paths_from_database\", command=self.get_file_paths_from_database, accelerator=\"Command+0\")\n\t\tmenubar.add_cascade(label=\"File\", menu=filemenu)\n\t\thelpmenu = tk.Menu(menubar, tearoff=0)\n\t\thelpmenu.add_command(label=\"About...\")\n\t\tmenubar.add_cascade(label=\"Help\", menu=helpmenu)\n\t\t# root.option_add('*tearOff', FALSE)\n\t\twindow.config(menu=menubar)\n\n\n\tdef create_button(self, txt, cmd, a_style):\n\t\tbutton = ttk.Button(self.buttons_frame, command=cmd, text=txt, style=a_style)\n\t\treturn button\n\n\n\tdef add_paths_and_buttons(self):\n\t\t# sys.argv = [self.script_path, self.trainingSets, \"-t\", self.target_file_path, \"-s\", self.stopwords_file_path]\n\t\tbutton_load_script = self.create_button(\"1. Select Python Script (e.g. harvest...)...\", self.select_python_script, 'B.TButton') \n\t\tbutton_open_target = self.create_button(\"2. Select Target...\", self.select_target_file, 'G.TButton')\n\t\tbutton_open_stopwords = self.create_button(\"3. Select Stopwords File...\", self.select_stopwords_file, 'B.TButton')\n\t\tbutton_select_training_files = self.create_button(\"4. Select TrainingSets...\", self.select_training_files, 'G.TButton')\n\t\tbutton_run = self.create_button(\"5. Run the calculation\", self.run_harvest, 'R.TButton')\n\t\tbutton_open_text_file = self.create_button(\"Display any Text File...\", self.open_text_file, 'bk.TButton')\n\t\tbutton_open_result = self.create_button(\"Open Result File...\", self.open_result_file, 'bk.TButton')\n\t\tbutton_quit = self.create_button(\"Quit\", self.quit, 'R.TButton')\n\t\t\n\t\tself.gui_list = [button_load_script, self.script_path_label,\n\t\t\t\t\t\t button_open_target, self.target_path_label,\n\t\t\t\t\t\t button_open_stopwords,self.stopwords_file_path_label,\t\n\t\t\t\t\t\t button_select_training_files, self.training_sets_path_label,\n\t\t\t\t\t\t button_run, button_open_text_file, button_open_result, button_quit]\n\t\tself.display_gui_list()\n\t\t\n\tdef display_gui_list(self):\n\t\tindex = 0\n\t\tfor object in self.gui_list:\n\t\t\tobject.grid(row=index, column=0, sticky=\"EW\", padx=5, pady=10)\n\t\t\tindex = index+1\n\n\n\n####### Execution starts here ########\nif __name__ == '__main__':\n\tfreeze_support()\n\twindow = tk.Tk()\n\t# window.after(0)\n\t# dbm_filename = 'dbm_file'\t # actually dbm_file.db\n\trt = RunThis(window)\n\trt.buttons_frame.grid(row=0, column=0, sticky=\"ns\")\n\trt.main_large_text_field.grid(row=0, column=1, sticky=\"nsew\")\n\twindow.mainloop()\n","sub_path":"RunThis_8.app/Contents/Resources/RunThis_8.py","file_name":"RunThis_8.py","file_ext":"py","file_size_in_byte":16880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"134214185","text":"#!/usr/bin/env python\nimport rospy\nfrom nav_msgs.msg import Odometry\nfrom tf.transformations import euler_from_quaternion, quaternion_from_euler\nfrom geometry_msgs.msg import Twist\nfrom controller.msg import Pathvector\n\nimport math\n \nroll = pitch = yaw = 0.0\ntarget = 0\nlength=0\nkp=0.5\n \ndef get_target (msg):\n global target,length\n x=msg.x\n y=msg.y \n target=math.atan2(y,x)\t\n length=math.sqrt(x*x+y*y)\n #print target\n\n\ndef get_rotation (msg):\n global roll, pitch, yaw\n orientation_q = msg.pose.pose.orientation\n orientation_list = [orientation_q.x, orientation_q.y, orientation_q.z, orientation_q.w]\n (roll, pitch, yaw) = euler_from_quaternion (orientation_list)\n #print yaw\n \nrospy.init_node('pathfollow_node')\n \nsub = rospy.Subscriber ('/odom', Odometry, get_rotation)\nsub2= rospy.Subscriber ('/pathv', Pathvector, get_target)\npub = rospy.Publisher('cmd_vel', Twist, queue_size=1)\nr = rospy.Rate(10)\ncommand =Twist()\n \nwhile not rospy.is_shutdown():\n #quat = quaternion_from_euler (roll, pitch,yaw)\n #print quat\n dif=target-yaw\n tangel=math.pi-abs(target)+math.pi-abs(yaw)\n if abs(target-yaw)>tangel:\n dif=math.copysign(tangel,-dif)\n\n command.angular.z = kp * dif\n if abs(dif)<0.6:\n command.linear.x=0.1\n else:\n command.linear.x=0.02\n pub.publish(command)\n print(\"target={} current:{}\", target,yaw)\n r.sleep()\n","sub_path":"catkin_ws/src/controller/src/pathfollow_node.py","file_name":"pathfollow_node.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"}