diff --git "a/5121.jsonl" "b/5121.jsonl" new file mode 100644--- /dev/null +++ "b/5121.jsonl" @@ -0,0 +1,652 @@ +{"seq_id":"10113289746","text":"from __future__ import print_function\n\nimport argparse\nimport re\n\ntry:\n from urllib.request import urlopen\n from urllib.error import HTTPError\nexcept ImportError:\n from urllib2 import urlopen, HTTPError\n\n\nparser = argparse.ArgumentParser(description=__doc__)\nparser.add_argument('url', help='url to check')\nparser.add_argument('pattern', help='regex to check for')\nparser.add_argument('--timeout', type=int, default=5, help='timeout in seconds (default 5)')\nargs = parser.parse_args()\n\nif not args.url.startswith('http'):\n args.url = 'http://{0}'.format(args.url)\n\ntry:\n request = urlopen(args.url, timeout=args.timeout)\n page = request.read().decode('utf-8')\nexcept HTTPError as e:\n raise SystemExit('{0} {1} ({2})'.format(e.code, e.reason, args.url))\n\nm = re.search(args.pattern, page)\n\nif m:\n print('status ok\\nmetric found string yes')\nelse:\n print('status err\\nmetric found string no')\n","repo_name":"racker/rackspace-monitoring-agent-plugins-contrib","sub_path":"content_check.py","file_name":"content_check.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","stars":71,"dataset":"github-code","pt":"27"} +{"seq_id":"73913201993","text":"# Imports\nimport requests\nimport pandas as pd\nimport censusdata as cnd\n# Census API stuff\napikey = 'YOURAPIKEYGOESHERE'\n\n## Get all state codes\ndef get_state_list(year):\n \n HOST = 'https://api.census.gov/data' \n year = f'{year}'\n dataset = 'acs/acs5'\n get_vars = ['NAME']\n predicates = {}\n predicates['get'] = ','.join(get_vars)\n predicates['for'] = 'state:*'\n base_url = \"/\".join([HOST, year, dataset])\n r = requests.get(base_url, params=predicates)\n global state_list\n state_list = []\n state_json = r.json()[1:]\n for state in state_json:\n state_list.append(state[1])\n states = pd.DataFrame(columns=r.json()[0], data = r.json()[1:])\n\nget_state_list(year=2018) #states don't change enough. \nprint(state_list)\n\n# cnd.printtable(cnd.censustable('acs5',2009,'B15002'))\ncnd.printtable(cnd.censustable('acs5',2009,'B19113'))\n# inc_search = cnd.search('acs5',2009,'label','Median Family Income')\n\n## Education variables\n'''List comprehensions seem scary at first.\n In general, a function is defined that will only be used in the context of this operation.\n We're creating this list to pull up the list of estimates from a given base table and add them to a list.\n We do the same thing for Margin of Error Estimates (at 90% CI).\n We'll later call on these variables in the API call.\n\n'''\ndef generate_varlist(base_table,maxvar,e_or_m):\n output_list = [(lambda x: base_table + '_' + str(x + 1).zfill(3) + f'{e_or_m}')(x) for x in range(maxvar)]\n return output_list\n# # https://api.census.gov/data/2009/acs/acs5/groups/B15002.html\neducation_est = generate_varlist('B15002',35,'E')\neducation_moe = generate_varlist('B15002',35,'M')\n# base_table = 'B15002'\nprint(education_est)\nprint(education_moe)\n\n# # https://api.census.gov/data/2009/acs/acs5/groups/B19113.html\nfam_inc_median = ['B19113_001E', 'B19113_001M']\n\n# # https://api.census.gov/data/2009/acs/acs5/groups/B19101.html\n# base_table = 'B19101'\nfam_inc_est = generate_varlist('B19101',17,'E')\nfam_inc_moe = generate_varlist('B19101',17,'M')\nprint(fam_inc_moe)\n\n# https://api.census.gov/data/2009/acs/acs5/groups/B19013.html\nhh_inc_median = ['B19013_001E','B19013_001M']\n\n# https://api.census.gov/data/2009/acs/acs5/groups/B19001.html\nhh_inc_est = generate_varlist('B19001',17,'E')\nhh_inc_moe = generate_varlist('B19001',17,'M')\n\n# https://api.census.gov/data/2010/acs/acs5/groups/B17026.html\n### NOTE: Does not come into play until 2010\npov_est = generate_varlist('B17026',17,'E')\npov_moe = generate_varlist('B17026',17,'M')\n\n# English vs. Spanish Speaker\n# \"B16007003 \n# B16007009 \n# B16007015\"\tB16007001 is total number as denominator for speaker variables\n# \"B16007004 \n# B16007010 \n# B16007016\"\tB16007001 is total number as denominator for speaker variables\n\n# BORNINUS - Born in US\n# B05001002\tB05001001 is total number as denominator for borninUS variable\n\n# MOVEDINLAST12MON - Moved in the last 12 months\n# 1-(B07001017/B07001001)\n\ndef get_tract_demog(year_start,year_end,var_list,debug=0):\n HOST = 'https://api.census.gov/data'\n dataset = 'acs/acs5'\n dfs = []\n for state in state_list:\n get_vars = []\n for var in var_list:\n get_vars.append(var)\n get_vars = ['NAME'] + get_vars\n predicates = {}\n predicates['get'] = ','.join(get_vars)\n predicates['for'] = 'tract:*'\n predicates['in'] = f'state:{state}'\n predicates['key'] = apikey;\n \n\n for year in range(year_start,year_end+1):\n base_url = '/'.join([HOST, str(year), dataset])\n r = requests.get(base_url, params = predicates)\n if debug != 0:\n print(r.text)\n df = pd.DataFrame(columns=r.json()[0], data = r.json()[1:])\n df['year'] = year\n dfs.append(df)\n _ = pd.concat(dfs)\n for var in var_list:\n _[var] = _[var].astype(float)\n return _\n\n# Use the function from above for the groups of variables defined in the previous cell\n\n# Education\nedu_est_df = get_tract_demog(year_start=2010, year_end=2018,var_list=education_est)\nedu_moe_df = get_tract_demog(year_start=2010, year_end=2018,var_list=education_moe)\n\n# Family Income\nfam_inc_median_df = get_tract_demog(year_start=2010, year_end=2018,var_list=fam_inc_median)\nfam_inc_est_df = get_tract_demog(year_start=2010, year_end=2018,var_list=fam_inc_est)\nfam_inc_moe_df = get_tract_demog(year_start=2010, year_end=2018,var_list=fam_inc_moe)\n\n# Household Income\nhh_inc_median_df = get_tract_demog(year_start=2010, year_end=2018,var_list=hh_inc_median)\nhh_inc_est_df = get_tract_demog(year_start=2010, year_end=2018,var_list=hh_inc_est)\nhh_inc_moe_df = get_tract_demog(year_start=2010, year_end=2018,var_list=hh_inc_moe)\n# Make a list of df. Join on year, state, county, and tract\n\ncensus_mashup = [edu_est_df, edu_moe_df, \n fam_inc_median_df, \n fam_inc_est_df, fam_inc_moe_df, \n hh_inc_median_df, \n hh_inc_est_df, hh_inc_moe_df,\n ]\n# If it is the first df, include \"NAME\", otherwise join and drop \"NAME\"\nfor idx,concept in enumerate(census_mashup):\n if idx == 0:\n census_mashup_df = concept\n print(idx)\n print(type(census_mashup_df))\n else:\n print(idx)\n census_mashup_df = pd.merge(census_mashup_df, concept.drop(['NAME'], axis=1), on=['year','state','county','tract'],suffixes = [None,None])\n\ncensus_mashup_df['GEOCODE']= census_mashup_df['state'] \\\n + census_mashup_df['county'] \\\n + census_mashup_df['tract']\n\n\nfile_loc = '//ghcmaster/ghri/Warehouse/management/Workspace/deruaj1/census_demog_dev/data/census_demog.csv'\ncensus_mashup_df.to_csv(file_loc,index=False)","repo_name":"kpwhri/ACS5YearToVDW","sub_path":"00_EXTRACT_ACS.py","file_name":"00_EXTRACT_ACS.py","file_ext":"py","file_size_in_byte":5705,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"13347535924","text":"from functools import partial\nclass Solution:\n # @param {integer[]} nums\n # @return {string}\n def largestNumber(self, nums):\n def _cmp(prefix, n1, n2):\n if not n1:\n if not n2:\n return 0\n else:\n return _cmp(\"\", prefix, n2)\n if not n2:\n return _cmp(\"\", n1, prefix)\n \n if n1[0]n2[0]:\n return 1\n else:\n return _cmp(prefix+n1[0], n1[1:], n2[1:])\n numstrs = [str(num) for num in nums]\n numstrs.sort(cmp = partial(_cmp, \"\"))\n result = \"\"\n \n if numstrs[-1]==\"0\":\n return \"0\"\n for n in numstrs[::-1]:\n result += n\n \n return result\n \n \n","repo_name":"RealHacker/leetcode-solutions","sub_path":"179_largest_number/largest_number_cmp.py","file_name":"largest_number_cmp.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","stars":648,"dataset":"github-code","pt":"27"} +{"seq_id":"74483189831","text":"import flask\nimport pickle\nimport numpy as np\nimport pandas as pd\n# Use pickle to load in the pre-trained model.\nwith open('employee.pkl', 'rb') as f:\n model = pickle.load(f)\napp = flask.Flask(__name__, template_folder='templates')\n@app.route('/', methods=['GET', 'POST'])\ndef main():\n if flask.request.method == 'GET':\n return(flask.render_template('employee.html'))\n if flask.request.method == 'POST':\n experience = flask.request.form['experience']\n testscore = flask.request.form['testscore']\n skills = flask.request.form['skills']\n input_variables = pd.DataFrame([[experience, testscore, skills]],\n columns=['Experience', 'Test Score', 'Skills'],\n dtype=float)\n prediction = model.predict(input_variables)[0]\n return flask.render_template('employee.html',\n original_input={'Experience':experience,\n 'Test Score':testscore,\n 'Skills':skills},\n result=prediction,\n )\nif __name__ == '__main__':\n app.run(debug=True)","repo_name":"siddhhu/sal-pred","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"37579370658","text":"import sys\nfrom collections import deque\n\n\ninput = sys.stdin.readline\nr, c = map(int, input().split())\narr = [list(input().rstrip()) for _ in range(r)]\nq_j = deque()\nq_f = deque()\nvisit_j = [[0] * c for _ in range(r)]\nvisit_f = [[0] * c for _ in range(r)]\ndx, dy = [-1, 1, 0, 0], [0, 0, -1, 1]\nanswer = []\n\n\nfor i in range(r):\n for j in range(c):\n if arr[i][j] == 'F':\n q_f.append((i, j))\n elif arr[i][j] == 'J':\n q_j.append((i, j))\n\nwhile q_f:\n x, y = q_f.popleft()\n for k in range(4):\n nx, ny = x + dx[k], y + dy[k]\n if 0 <= nx < r and 0 <= ny < c:\n if not visit_f[nx][ny] and arr[nx][ny] == '.':\n visit_f[nx][ny] = visit_f[x][y] + 1\n q_f.append((nx, ny))\n\nwhile q_j:\n x, y = q_j.popleft()\n for k in range(4):\n nx, ny = x + dx[k], y + dy[k]\n\n # 범위 밖\n if not (0 <= nx < r and 0 <= ny < c):\n print(visit_j[x][y] + 1)\n sys.exit()\n \n # 범위 안\n if not visit_j[nx][ny] and arr[nx][ny] == '.':\n if not visit_f[nx][ny] or visit_j[x][y] + 1 < visit_f[nx][ny]:\n visit_j[nx][ny] = visit_j[x][y] + 1\n q_j.append((nx, ny))\n\nprint('IMPOSSIBLE')","repo_name":"yezyvibe/Algorithm_PS","sub_path":"Backjoon/b_4179_불.py","file_name":"b_4179_불.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"73252017351","text":"from abc import ABCMeta\nfrom datetime import datetime\nfrom decimal import Decimal\nimport json\nimport time\nfrom typing import cast , Dict, Any, List, Optional\nfrom uuid import UUID\n\n\nfrom pyson.JsonDeserialize import getDeserializer\nfrom pyson.JsonGetter import getGetter\nfrom pyson.JsonTools import isPrimitive, getActualClass, getInitArgs, getDefaults, addTypeInfo, getListClass\nfrom pyson.JsonTypeInfo import Id, As, getTypeWrappingInfo\nfrom pyson.JsonValue import getJsonValue\nfrom uri.uri import URI\n\n\n# from pyson.JsonSubTypes import getSubTypes\nclass ObjectMapper: \n '''\n A very simple pyson-style objectmapper.\n '''\n def parse(self, data:object, clas:object )->object:\n '''\n @param data either a dict or a built-in object like an int\n @param clas the expected class contained in the data.\n If a dict, this class must have a __init__ function specifying the params\n needed and the data in this case should be a dict.\n Any is considered indicating that the expected argument is primitive.\n @return a clas instance matching the data\n '''\n # now distinguish \n if isPrimitive(clas,True) or clas==Any:\n return self.parseBase(data, clas)\n if (clas==list):\n #FIXME this is unreachable?\n raise ValueError(\"Illegal type, use List[X] instead of list\")\n if (clas==dict):\n #FIXME this is unreachable?\n raise ValueError(\"Illegal type, use Dict[X] instead of dict\")\n \n deserializer=getDeserializer(clas)\n if deserializer:\n return deserializer().deserialize(data, clas) \n \n if getJsonValue(clas):\n argclasses:dict=getInitArgs(clas)\n if len(argclasses)!=1:\n raise ValueError(\"Class \"+str(clas)+\" has @JsonValue getter but has multiple init arguments\")\n valueclas = list(argclasses.values())[0]\n return clas(self.parse(data, valueclas))\n\n if getTypeWrappingInfo(clas):\n if not isinstance(data, dict):\n raise ValueError(\"Expected class, therefore data must be a dict but got \"+str(data))\n (data, clas) = getActualClass(cast(dict, data),clas)\n\n if repr(clas).startswith('typing.'):\n return self.parseGeneric(data,clas)\n # after this, clas is NOT a generic like List[X] \n if issubclass(clas, BaseException): #type:ignore\n return self.parseException(data,clas)\n \n if type(data)==dict: # if it contains class, data must be dict\n return self.parseClass(cast(dict,data), clas)\n raise ValueError(\"Expected \"+str(clas)+\" but got '\"+str(data)+\"' which is a \"+str(type(data)))\n \n def parseBase(self,obj, clas)->object:\n '''\n @param obj a built-in object like an int\n @param clas the class of the expected object.\n If Any, then the obj is accepted as primitive (eg, int, dict, str)\n Else, if clas does not contain __init__, it must be a primitive\n @return the obj, after checking it's indeed a clas\n '''\n #datetime is special, the json primitive will be a int with millis since 1970\n if clas== datetime:\n if not type(obj)==int:\n raise ValueError(\"expected int (millis since 1970) but got \"+str(obj))\n return datetime.fromtimestamp(cast(int, obj)/1000.0)\n if clas==URI:\n if not type(obj)==str:\n raise ValueError(\"expected uri string but got \"+str(obj))\n return URI(obj)\n if clas==Decimal:\n # obj must be a float or int. We use str\n # to get the number truncated at correct #digits.\n # It is possible json already rounded the number\n return Decimal(str(obj))\n if clas==UUID:\n if not type(obj)==str:\n raise ValueError(\"expected UUID string but got \"+str(obj))\n return UUID(obj)\n if not (clas==Any or type(obj)==clas):\n raise ValueError(\"Expected \"+str(clas)+\" but got \"+str(obj)+\" which is a \"+str(type(obj)))\n return obj\n \n \n def parseClass(self, data:dict, clas)->object:\n '''\n @param data a dict with the values for class.__init__ function\n @return a clas instance matching the data\n '''\n if not isinstance(data,dict ):\n raise ValueError(\"data \"+str(data)+\" must be dict\")\n # then this class needs initialization\n initargs={}\n argclasses=getInitArgs(clas)\n defaults = getDefaults(clas)\n if not set(data.keys()).issubset(set(argclasses.keys())):\n raise ValueError(\"Constructor of \"+str(clas)+\" requires arguments \"+str(list(argclasses.keys()))+\" but got \"+str(list(data.keys())))\n for arg in argclasses:\n if arg in data:\n try:\n initargs[arg] = self.parse(data[arg], argclasses[arg])\n except ValueError as e:\n raise ValueError(\"Error parsing \"+str(data),e ) from e\n else: # does constructor have a devault for the missing avlue?\n if not arg in defaults:\n raise ValueError(str(clas)+\" constructor takes \"+str(arg)+\" which has no default value, but value missing in dict \"+str(data))\n return clas(**initargs)\n \n def parseGeneric(self, data, clas:object)->object:\n '''\n A generic is soemthing like typing Dict[str,str]. \n @param data may be list or dict, depending on the exact clas\n @return instance of the clas. Don't know how to write this for typing\n '''\n gname =repr(clas) # _name fails for eg typing.Union\n \n if gname.startswith('typing.List') or gname.startswith('typing.Set'):\n elementclas = clas.__args__[0]\n if type(data)!=list:\n raise ValueError(\"expected list[{elementclas}] but got \"+str(data))\n res=[self.parse(listitem, elementclas) for listitem in data]\n if gname.startswith('typing.List'):\n return res\n else:\n return set(res)\n \n if gname.startswith('typing.Dict'):\n keyclas = clas.__args__[0]\n if not keyclas.__hash__:\n raise ValueError(\"Dict cannot be serialized, key class \"+str(keyclas)+\" does not have __hash__\")\n elementclas = clas.__args__[1]\n if type(data)!=dict:\n raise ValueError(\"expected dict[{keyclass, elementclas}] but got \"+str(data))\n return { self.parse(key, keyclas) : self.parse(val, elementclas)\\\n for key,val in data.items() }\n \n if gname.startswith('typing.Union'):\n # Special to support optional: Union[class, NoneType]\n actualclasses = [actual for actual in clas.__args__ if actual!=type(None)]\n if len(actualclasses)!=1:\n raise ValueError(\"Union type only supported with NoneType, but found: \"+str(clas))\n if data==None:\n return None\n return self.parse(data, actualclasses[0])\n \n if gname.startswith('typing.Optional'):\n if data==None:\n return None\n return self.parse(data, clas.__args__[0])\n\n\n raise ValueError(\"Unsupported generic type \"+ str(clas))\n \n def parseException(self, data, excclass=Exception):\n '''\n Assumes argument for excclass constructor is the message.\n '''\n if not isinstance(data, dict):\n raise ValueError(\"Expected dict but got \"+repr(data))\n if not \"message\" in data:\n raise ValueError(\"Expected 'message' in \"+str(data))\n res=excclass(data['message'])\n if 'cause' in data:\n res.__cause__=self.parse(data['cause'], Optional[Exception])\n return res\n \n def toJson(self, data)->dict:\n '''\n @param data either a dict or a built-in object like an int\n @return a dict containing this object \n '''\n if isinstance(data, BaseException):\n return self.toJsonException(data)\n res:dict\n clas = type(data)\n # dict and list are handled separately because\n # we must serizliae keys and values separately\n if isPrimitive(clas):\n return self.toJsonBase(data) \n if clas==list or clas==tuple or clas==set:\n res=self.toJsonList(data)\n elif clas==dict:\n res=self.toJsonDict(data)\n elif type(clas)==type or type(clas)==ABCMeta:\n # is it general class? FIXME can this be done better?\n res = self.toJsonClass(data)\n else:\n raise ValueError(\"Unsupported object of type \"+str(clas))\n # check if wrapper setting is requested for this class\n if getTypeWrappingInfo(clas):\n res=addTypeInfo(clas,res);\n return res\n \n def toJsonClass(self,data:object)->dict:\n ''' \n @param data a class instance\n @return data a dict with the values \n The values are based on the class.__init__ function\n '''\n jsonvalue = getJsonValue(data)\n if jsonvalue:\n return self.toJson(jsonvalue())\n \n clas=type(data)\n res={}\n arg:str\n for arg in getInitArgs(clas):\n argvalue = getGetter(data, arg)()\n# gettername = 'get'+arg\n# if not hasattr(data, gettername) :# in clas.__dict__:\n# raise ValueError(\"The object \"+str(data)+ \"of type \"+ str(clas)+\" has no function \"+gettername)\n# argvalue = getattr(data, gettername)() #.__dict__[gettername]()\n res[arg]=self.toJson(argvalue)\n return res\n \n \n def toJsonBase(self,obj):\n '''\n @param obj a built-in object like an int or a datetime.\n obj does not contain __init__, it must be a built-in type\n @return the json style representation of teh built-in object.\n For datetime objects we use the linux timestamp (millis since 1970)\n '''\n if isinstance(obj, datetime):\n return round(datetime.timestamp(obj)*1000)\n if isinstance(obj, URI) or isinstance(obj, UUID):\n return str(obj)\n if isinstance(obj, Decimal):\n if obj == obj.to_integral_value():\n return int(obj) # python has no maxint \n return float(obj)\n return obj\n \n def toJsonList(self, listofobj):\n '''\n @param listofobj list or tuple of objects each to be serialized separately.\n @return list object to be put in the json representation, \n '''\n if len(listofobj)==0:\n return [] # empty list has no type. \n clas = getListClass(listofobj)\n # if isPrimitive(clas):\n # return listofobj\n # CHECK can we check if classes involved are properly annotated?\n #if not(clas==None or getTypeWrappingInfo(clas)):\n # raise ValueError(\"@JsonTypeInfo is required for list objects, but found \"+str(clas))\n return [self.toJson(elt) for elt in listofobj]\n \n def toJsonDict(self, dictofobj:Dict[Any,Any]):\n '''\n @param dictofobj dict with objects each to be serialized separately.\n The keys must be primitive, values must be all the same class.\n @return list object to be put in the json representation, \n '''\n if len(dictofobj)==0:\n return {} # empty list has no type. \n keyclas = getListClass(list(dictofobj.keys()))\n valclas = getListClass(list(dictofobj.values()))\n # if isPrimitive(clas):\n # return listofobj\n if keyclas!=None and not getJsonValue(keyclas):\n raise ValueError(\"key of dict must be primitive, but found \"+\\\n str(keyclas)+\" in \"+str(dictofobj))\n #if valclas and not getTypeWrappingInfo(valclas):\n # raise ValueError(\"@JsonTypeInfo is required for dict objects, but found \"+str(valclas))\n return { self.toJson(key):self.toJson(val) for key,val in dictofobj.items()}\n\n def toJsonException(self, e:BaseException):\n res:Dict[str ,Any] ={}\n if len(e.args)==1:\n res[\"message\"]=str(e.args[0])\n else:\n res[\"message\"]=str(e.args)\n res[\"stackTrace\"]=[]\n res[\"cause\"]=self.toJsonException(e.__cause__) if e.__cause__ else None\n return res\n ","repo_name":"HahaBill/CollaborativeAI","sub_path":"src/negotiating_agent/venv/lib/python3.8/site-packages/pyson/ObjectMapper.py","file_name":"ObjectMapper.py","file_ext":"py","file_size_in_byte":12557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"5116913338","text":"from __future__ import division\nimport os\nimport time\nfrom glob import glob\nimport tensorflow as tf\nimport numpy as np\nfrom six.moves import xrange\nfrom skimage import color\nimport cv2\nimport random\nimport cPickle as pickle\n\ndef load_data():\n print('loading data...')\n dirs = './data'\n filename = os.path.join(dirs,'sort-of-clevr.pickle')\n f = open(filename, 'r')\n train_datasets, test_datasets = pickle.load(f)\n rel_train = []\n rel_test = []\n norel_train = []\n norel_test = []\n print('processing data...')\n\n for img, relations, norelations in train_datasets:\n # img = np.swapaxes(img,0,2)\n for qst,ans in zip(relations[0], relations[1]):\n rel_train.append((img,qst,ans))\n for qst,ans in zip(norelations[0], norelations[1]):\n norel_train.append((img,qst,ans))\n\n for img, relations, norelations in test_datasets:\n # img = np.swapaxes(img,0,2)\n for qst,ans in zip(relations[0], relations[1]):\n rel_test.append((img,qst,ans))\n for qst,ans in zip(norelations[0], norelations[1]):\n norel_test.append((img,qst,ans)) \n \n return (rel_train, rel_test, norel_train, norel_test)\n\ndef cvt_data_axis(data):\n img = [e[0] for e in data]\n qst = [e[1] for e in data]\n ans = [e[2] for e in data]\n return (img,qst,ans)\n\ndef tensor_data(data, i, bs):\n img = np.asarray(data[0][bs*i:bs*(i+1)])\n qst = np.asarray(data[1][bs*i:bs*(i+1)])\n ans = np.asarray(data[2][bs*i:bs*(i+1)])\n return (img, qst, ans)\n\n\n\n\n","repo_name":"shamitlal/Relational_Network_Tensorflow","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"27"} +{"seq_id":"31827475468","text":"from flask import Flask,render_template,request,redirect,url_for\napp = Flask(__name__)\nfrom sympy import *\nx,y,z = symbols('x y z')\ninit_printing()\n\n\n@app.route(\"/\",methods=['GET','POST'])\ndef index():\n return render_template(\"home.html\")\n\n@app.route(\"/demo\",methods=['GET','POST'])\ndef demo():\n return render_template(\"demo.html\")\n\n@app.route(\"/result-nth-term\",methods=[\"POST\"]) \ndef result():\n name_of_user = request.form.get(\"name_of_user\") \n iterable_list = []\n numbers = request.form.get(\"numbers\")\n numbers = numbers.split(',')\n for num in numbers:\n if num != ',':\n iterable_list.append(int(num)) \n main_list = []\n filtered_list = []\n\n\n def get_new_list(arr):\n new_list = []\n for num in range(0,len(arr)-1):\n val = arr[num+1]-arr[num]\n new_list.append(val) \n main_list.insert(len(main_list),new_list)\n\n def filter_list_from_empty_values(arr):\n for array in arr:\n if len(array) != 0:\n filtered_list.append(array)\n\n\n def find_all_lists(arr):\n for num in arr:\n if len(main_list) == 0:\n get_new_list(arr)\n get_new_list(main_list[len(main_list)-1])\n filter_list_from_empty_values(main_list)\n return filtered_list \n\n find_all_lists(iterable_list)\n def factorial(num):\n val = 1\n n = num\n while n != 0:\n val = val * n\n n = n -1\n return val \n def factorial_of_exp(num):\n exp = ''\n n = num\n while n != 0:\n exp = exp + '(x-{n})*'.format(n=n)\n n =n-1\n # sympied = sympify(exp[:-1])\n return exp[:-1]\n def getFinalExpr():\n expr = '{}'.format(iterable_list[0])\n for arr in filtered_list:\n arrIndex = filtered_list.index(arr)\n deno = factorial(arrIndex+1)\n mult = arr[0]\n if mult>0:\n loopexpr = '(+{0}*'.format(mult)+'{}'.format(factorial_of_exp(arrIndex+1)) + '/{0})'.format(deno)\n else:\n loopexpr = '({0}*'.format(mult)+ '{}'.format(factorial_of_exp(arrIndex+1)) + '/{0})'.format(deno)\n\n expr = expr + '+({0})'.format(loopexpr)\n # expr = expr[:-1] \n expr = sympify(expr)\n return expr\n \n last = factor(getFinalExpr())\n expandedform = expand(last)\n #latex format\n latexexpanded = '$${}$$'.format(latex(expandedform))\n finalLast = '$${0}$$'.format(latex(last)) \n isLong = len(finalLast) > 60\n numbers_with_result = []\n return render_template(\"result.html\",\n finalExpand = latexexpanded,\n finalExp = finalLast,\n name_of_user=name_of_user,\n numbers = iterable_list,\n isLong=isLong)\n\n\nif __name__ == '__main__':\n # Threaded option to enable multiple instances for multiple user access support\n app.run(threaded=True, port=5000)","repo_name":"Tanjim702/Flask_Function_app","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3042,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"26612038907","text":"# задание\n# напишите сортировку с лямбдой, которая вернёт минимальный элемент из списка `people`, сортировка должна быть\n# сначала по возрасту, а потом по имени\n\n\npeople = [\n {\"name\": \"Alice\", \"age\": 25},\n {\"name\": \"Charlie\", \"age\": 20},\n {\"name\": \"Bob\", \"age\": 20},\n {\"name\": \"Diana\", \"age\": 30},\n]\n\n# решение\nmin_people = min(people, key=lambda x: (x[\"age\"], x[\"name\"]))\nprint(min_people) # Output: {'name': 'Bob', 'age': 20}\n","repo_name":"jjoskey/python_beginners_course","sub_path":"_22_lambda_func/_2_homework.py","file_name":"_2_homework.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"24554307081","text":"#!/usr/bin/env python3\n\nimport sys, os, time, json\nimport argparse\n\n# Command-line arguments\nparser = argparse.ArgumentParser(description='QA script for MC with pT hard bins')\nparser.add_argument('--sub',help='Subcycle: 16, 17 or 18', default='16')\nparser.add_argument('-o', '--output',help='Output ROOT file', default='NewMCQA.root')\nparser.add_argument('-p', '--print',help='Output PDF', default='NewMCQA.pdf')\nargs = parser.parse_args()\n\nimport ROOT\nimport ana_util\n\nargs.print = args.output.replace('.root','.pdf')\n\nMC_TAG = {}\nMC_TAG['18'] = 'LHC19i2a'\nMC_TAG['17'] = 'LHC19i2b'\nMC_TAG['16'] = 'LHC19i2c'\n\nfout = ROOT.TFile(args.output,'RECREATE')\nc = ROOT.TCanvas('cQA','J/#psi in jets MC production - Final QA (%s)' % MC_TAG[args.sub], 1200, 600)\nc.Draw()\n\nana_util.PrintCover(c,args.print)\n\nPT_HARD_BINS = [12, 16, 21, 28, 36, 45, 57, 70, 85, 100, -1]\nBINNING_PT = ana_util.BINNING_JET_PT\nQA_NAME = ['PtHard', 'PtHardScaled', 'VtxZ', 'ElePt','EleDCAxy','EleDCAz', 'JetPt', 'JetNtrk', 'TagJetPt', 'TagJetNtrk', 'DieleJetPt', 'DieleJetNtrk', 'JpsiPt', 'JpsiY']\nQA_HIST_CONFIG = {\n 'PtHard':{'Logy':True, 'X':[0,200], 'Y': [1e-8, 10.0], 'Ytitle': '1/#it{N}_{ev} d#it{N}_{evts}/d#it{p}_{T}', 'Legend': [0.65,0.1,0.9,0.5], 'Title':'Pythia event info. - pT hard (Unscale)', 'Sum':False},\n 'PtHardScaled':{'Logy':True, 'X':[0,200], 'Y': [1e-12, 0.1], 'Ytitle': '1/#it{N}_{ev} d#it{N}_{evts}/d#it{p}_{T}', 'Legend': [0.65,0.55,0.9,0.9], 'Title':'Pythia event info. - pT hard (Scaled)', 'Sum':False},\n 'VtxZ':{'Logy':False, 'X':[-20,20], 'Y': [0., 0.1], 'Ytitle': '1/#it{N}_{ev} d#it{N}_{ev}/dZ', 'Legend': [0.1,0.6,0.35,0.9], 'Title':'Event primary vertex Z', 'Sum':False},\n 'ElePt':{'Logy':True, 'X':[0,100], 'Y': [1e-10, 10], 'Ytitle': '1/#it{N}_{ev} d#it{N}_{trk}/d#it{p}_{T}', 'Legend': [0.68,0.62,0.9,0.9], 'Title':'Selected track/electron (TPC only) - #it{p}_{T}', 'Sum':True},\n 'EleDCAxy':{'Logy':True, 'X':[-2,2], 'Y': [1e-4, 100], 'Ytitle': '1/#it{N}_{ev} d#it{N}_{trk}/d#it{XY}', 'Legend': [0.1,0.6,0.35,0.9], 'Title':'Selected track/electron (TPC only) - #it{DCA}_{xy}', 'Sum':False},\n 'EleDCAz':{'Logy':True, 'X':[-5,5], 'Y': [1e-6, 100], 'Ytitle': '1/#it{N}_{ev} d#it{N}_{trk}/d#it{Z}', 'Legend': [0.1,0.6,0.35,0.9], 'Title':'Selected track/electron (TPC only) - #it{DCA}_{z}', 'Sum':False},\n 'JetPt':{'Logy':True, 'X':[0,100], 'Y': [1e-9, 1e2], 'Ytitle': '1/#it{N}_{ev} d#it{N}_{jet}/d#it{p}_{T}', 'Legend': [0.68,0.62,0.9,0.9], 'Title':'Inclusive jet - raw #it{p}_{T}', 'Sum':True},\n 'JetNtrk':{'Logy':False, 'X':[0,100], 'Y': [0, 12], 'Ytitle': '<#it{N}_{trk}>', 'Legend': [0.1,0.6,0.3,0.9], 'Title':'Inclusive jet - N constituents', 'Sum':True},\n 'TagJetPt':{'Logy':True, 'X':[0,100], 'Y': [1e-9, 5], 'Ytitle': '1/#it{N}_{ev} d#it{N}_{jet}/d#it{p}_{T}', 'Legend': [0.72,0.65,0.9,0.9], 'Title':'Inclusive jet (updated) - raw #it{p}_{T}', 'Sum':True},\n 'TagJetNtrk':{'Logy':False, 'X':[0,100], 'Y': [0, 12], 'Ytitle': '<#it{N}_{trk}>', 'Legend': [0.1,0.6,0.3,0.9], 'Title':'Inclusive jet (updated) - N constituents', 'Sum':True},\n 'DieleJetPt':{'Logy':True, 'X':[0,100], 'Y': [1e-10, 1e-2], 'Ytitle': '1/#it{N}_{ev} d#it{N}_{jet}/d#it{p}_{T}', 'Legend': [0.1,0.1,0.3,0.4], 'Title':'Dielectron tagged jet - raw #it{p}_{T}', 'Sum':True},\n 'DieleJetNtrk':{'Logy':False, 'X':[0,100], 'Y': [0, 12], 'Ytitle': '<#it{N}_{trk}>', 'Legend': [0.1,0.6,0.3,0.9], 'Title':'Dielectron tagged jet - N constituents', 'Sum':True},\n 'JpsiPt':{'Logy':True, 'X':[0,100], 'Y': [1e-8, 10], 'Ytitle': '1/#it{N}_{ev} d#it{N}_{J/#psi}/d#it{p}_{T}', 'Legend': [0.68,0.62,0.9,0.9], 'Title':'Generated J/#psi - #it{p}_{T}', 'Sum':True},\n 'JpsiY':{'Logy':False, 'X':[-2, 2], 'Y': [0, 1], 'Ytitle': '1/#it{N}_{ev} d#it{N}_{J/#psi}/d#it{Y}', 'Legend': [0.75,0.5,0.9,0.9], 'Title':'Generated J/#psi - #it{Y}', 'Sum':False}\n}\n\npTxtStats = ROOT.TPaveText(0.1, 0.02, 0.9, 0.98, \"brNDC\")\npTxtStats.SetFillColor(0)\npTxtStats.SetTextFont(42)\npTxtStats.SetTextSize(0.03)\ntxt = pTxtStats.AddText(\" #it{p}_{T,hard} | #it{N}_{events} | <#it{#sigma}> | <#it{N}_{trials}> | Scale factor |\") # Header\ntxt.SetTextFont(62)\n\nQA = list(range(len(PT_HARD_BINS) - 1))\nfor i,pTmin in enumerate(PT_HARD_BINS[:-1]):\n # Init\n QA[i] = {}\n QA[i]['pTHard'] = (PT_HARD_BINS[i], PT_HARD_BINS[i+1])\n if(PT_HARD_BINS[i+1] == -1):\n QA[i]['Title'] = \"#it{p}_{T} hard bin > %d GeV/c\" % PT_HARD_BINS[i]\n else:\n QA[i]['Title'] = \"#it{p}_{T} hard bin: %d - %d GeV/c\" % (PT_HARD_BINS[i], PT_HARD_BINS[i+1])\n f = ROOT.TFile('../output/JpsiJetMC_FullQA/JpsiJetMC_FullQA%s_bin%d_191017/AnalysisResults.root' % (args.sub, i+1))\n if(f.IsOpen()):\n print('>>> Processing ' + f.GetName())\n print('[-] Config : ' + QA[i]['Title'])\n else:\n exit(1)\n qa = f.JpsiJetAnalysis.Get('QAhistos_MC')\n qa.SetOwner(True)\n mc = f.JpsiJetAnalysis.Get('MChistos')\n mc.SetOwner(True)\n # QA\n # Generator\n genQA = mc.FindObject('Event')\n genQA.SetOwner(True)\n QA[i]['PtHard'] = genQA.FindObject('PtHard').Clone('hPtHard_%d' % i)\n QA[i]['NEvent'] = QA[i]['PtHard'].GetEntries()\n QA[i]['Ntrials'] = genQA.FindObject('Ntrials').GetBinContent(1) / QA[i]['NEvent']\n QA[i]['Xsec'] = genQA.FindObject('Xsec').GetBinContent(1) / QA[i]['NEvent']\n QA[i]['ScaleFactor'] = QA[i]['Xsec'] / QA[i]['Ntrials']\n QA[i]['PtHardScaled'] = genQA.FindObject('PtHard').Clone('hPtHardScaled_%d' % i)\n QA[i]['PtHardScaled'].Scale(QA[i]['ScaleFactor'])\n print('[-] N event : %1.3e' % QA[i]['NEvent'])\n txt = pTxtStats.AddText(\"%d - %d (GeV/#it{c})| %.2e | %.3e | %.3e | %.2e\" % (QA[i]['pTHard'][0], QA[i]['pTHard'][1], QA[i]['NEvent'], QA[i]['Xsec'], QA[i]['Ntrials'], QA[i]['ScaleFactor']))\n # Event\n diele = qa.FindObject('Dielectron')\n diele.SetOwner(True)\n evQA = diele.FindObject('Event')\n evQA.SetOwner(True)\n QA[i]['VtxZ'] = evQA.FindObject('VtxZ').Clone('hVtxZ_%d' % i)\n # Track / Electron\n eleP = diele.FindObject('Track_ev1+')\n eleP.SetOwner(True)\n QA[i]['ElePt'] = eleP.FindObject('Pt').Rebin(len(BINNING_PT)-1,'hElePt_%d' % i, BINNING_PT)\n QA[i]['EleDCAxy'] = eleP.FindObject('dXY').Clone('hEleDXY_%d' % i)\n QA[i]['EleDCAxy'].GetXaxis().SetRangeUser(-2.,2.)\n QA[i]['EleDCAz'] = eleP.FindObject('dZ').Clone('hEleDZ_%d' % i)\n QA[i]['EleDCAz'].GetXaxis().SetRangeUser(-5.,5.)\n eleN = diele.FindObject('Track_ev1-')\n eleN.SetOwner(True)\n QA[i]['ElePt'].Add(eleN.FindObject('Pt').Rebin(len(BINNING_PT)-1,'', BINNING_PT))\n QA[i]['EleDCAxy'].Add(eleN.FindObject('dXY'))\n QA[i]['EleDCAz'].Add(eleN.FindObject('dZ'))\n # Jet\n jetQA = qa.FindObject('Jet_AKTChargedR040_tracks_pT0150_pt_scheme')\n jetQA.SetOwner(True)\n hs = jetQA.FindObject('jetVars')\n QA[i]['JetPt'] = hs.Projection(0).Rebin(len(BINNING_PT)-1,'hJetPt_%d' % i, BINNING_PT)\n QA[i]['JetNtrk'] = jetQA.FindObject('Ntracks_pT').ProfileX('hJetNtrk_%d' % i).Rebin(len(BINNING_PT)-1,'', BINNING_PT)\n taggedJetQA = qa.FindObject('JpsiJet_AKTChargedR040_tracksWithPair_pT0150_pt_scheme')\n taggedJetQA.SetOwner(True)\n hs = taggedJetQA.FindObject('jetVars')\n QA[i]['TagJetPt'] = hs.Projection(0).Rebin(len(BINNING_PT)-1,'hTagJetPt_%d' % i, BINNING_PT)\n QA[i]['TagJetNtrk'] = taggedJetQA.FindObject('Ntracks_pT').ProfileX('hTagJetNtrk_%d' % i).Rebin(len(BINNING_PT)-1,'', BINNING_PT)\n # Dielectron tagged\n tagQA = qa.FindObject('PairInJet')\n tagQA.SetOwner(True)\n hs = tagQA.FindObject('PairVars')\n QA[i]['DieleJetPt'] = hs.Projection(5).Rebin(len(BINNING_PT)-1,'hDieleJetPt_%d' % i, BINNING_PT)\n QA[i]['DieleJetNtrk'] = tagQA.FindObject('Ntracks_pT').ProfileX('hDieleJetNtrk_%d' % i).Rebin(len(BINNING_PT)-1,'', BINNING_PT)\n # MC J/psi\n jpsiQA = mc.FindObject('JpsiBdecay')\n hs = jpsiQA.FindObject('jpsiVars')\n QA[i]['JpsiPt'] = hs.Projection(0).Rebin(len(BINNING_PT)-1,'hJpsiPt_%d' % i, BINNING_PT)\n QA[i]['JpsiY'] = hs.Projection(1)\n QA[i]['JpsiY'].SetName('hJpsiY_%d' % i)\n # End\n for hist in QA_NAME:\n QA[i][hist].SetDirectory(None)\n qa.Delete()\n mc.Delete()\n f.Close()\n\nfout.cd()\n# Print stats\nc.Clear()\nc.SetWindowSize(800, 800)\nc.Draw()\npTxtStats.Draw()\nc.Print(args.print, 'Title:EventStats')\nc.Write('cEvStats')\n\nfor hist in QA_NAME:\n c.Clear()\n c.SetWindowSize(1600, 1200)\n c.SetLogy(False)\n ana_util.COLOR = ana_util.SelectColor()\n ana_util.MARKER = ana_util.SelectMarker()\n # Hist config\n cfg = QA_HIST_CONFIG[hist]\n lgd = ROOT.TLegend(cfg['Legend'][0], cfg['Legend'][1], cfg['Legend'][2], cfg['Legend'][3])\n hSum = QA[0][hist].Clone('hSum'+hist)\n hSum.Reset()\n ana_util.SetColorAndStyle(hSum, ROOT.kRed, ana_util.kRound, 1.5)\n if(cfg['Sum']):\n lgd.AddEntry(hSum, 'Sum')\n for i,pTmin in enumerate(PT_HARD_BINS[:-1]):\n color = next(ana_util.COLOR)\n ana_util.SetColorAndStyle(QA[i][hist], color)\n QA[i][hist].GetYaxis().SetTitleOffset(1.2)\n QA[i][hist].Sumw2()\n if(hist.find('Ntrk') < 0):\n QA[i][hist].Scale(1./QA[i]['NEvent'],'width')\n else:\n QA[i][hist].Scale(1.,'width')\n QA[i][hist].SetTitle(QA[i]['Title'])\n hSum.Add(QA[i][hist], QA[i]['ScaleFactor'])\n if(i == 0):\n QA[i][hist].Draw('PE')\n else:\n QA[i][hist].Draw('same PE')\n lgd.AddEntry(QA[i][hist],QA[i][hist].GetTitle())\n if(cfg['Sum']):\n hSum.Draw('same')\n # Hist config\n lgd.Draw('same')\n c.SetLogy(cfg['Logy'])\n QA[0][hist].SetYTitle(cfg['Ytitle'])\n QA[0][hist].GetXaxis().SetRangeUser(cfg['X'][0], cfg['X'][1])\n QA[0][hist].GetYaxis().SetRangeUser(cfg['Y'][0], cfg['Y'][1])\n QA[0][hist].SetTitle(cfg['Title'])\n c.Modified()\n # Output\n c.Print(args.print, 'Title:' + hist)\n c.Write('c' + hist)\n\nfor i,pTmin in enumerate(PT_HARD_BINS[:-1]):\n print('[-] INFO : pT hard bin scale factor = %.3e / %.3e = %.2e' % (QA[i]['Xsec'], QA[i]['Ntrials'], QA[i]['ScaleFactor']))\n\nana_util.PrintCover(c,args.print,'End of QA',isBack=True)\nfout.Close()","repo_name":"yatowoo/JpsiJet","sub_path":"Plot/merge_qamc.py","file_name":"merge_qamc.py","file_ext":"py","file_size_in_byte":9762,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"27"} +{"seq_id":"9084875668","text":"# Given a fixed length array arr of integers, duplicate each occurrence of zero, shifting the remaining elements to the right.\n#\n# Note that elements beyond the length of the original array are not written.\n#\n# Do the above modifications to the input array in place, do not return anything from your function.\n\nclass Solution(object):\n def duplicateZeros(self, arr):\n \"\"\"\n :type arr: List[int]\n :rtype: None Do not return anything, modify arr in-place instead.\n \"\"\"\n index =0\n length = len(arr)\n\n while index < length:\n if arr[index] == 0:\n arr.pop()\n arr.insert(index,0)\n index += 1\n index += 1\n","repo_name":"riCoYanG-byte/leetcode","sub_path":"array/Regular/No.1089.py","file_name":"No.1089.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"27"} +{"seq_id":"16346568510","text":"import inspect\nimport warnings\nfrom typing import Tuple, Sequence, Dict, Any, Callable, Union, AbstractSet\n\nimport numpy as np\nimport xarray as xr\n\nfrom xcube.core.schema import CubeSchema\nfrom xcube.core.chunkstore import ChunkStore\nfrom xcube.core.verify import assert_cube\n\nCubeFuncOutput = Union[xr.DataArray, np.ndarray, Sequence[Union[xr.DataArray, np.ndarray]]]\nCubeFunc = Callable[..., CubeFuncOutput]\n\n_PREDEFINED_KEYWORDS = ['input_params', 'dim_coords', 'dim_ranges']\n\n\n# TODO: support vectorize = all cubes have same variables and cube_func receives variables as vectors (with extra dim)\n\ndef compute_cube(cube_func: CubeFunc,\n *input_cubes: xr.Dataset,\n input_cube_schema: CubeSchema = None,\n input_var_names: Sequence[str] = None,\n input_params: Dict[str, Any] = None,\n output_var_name: str = 'output',\n output_var_dtype: Any = np.float64,\n output_var_attrs: Dict[str, Any] = None,\n vectorize: bool = None,\n cube_asserted: bool = False) -> xr.Dataset:\n \"\"\"\n Compute a new output data cube with a single variable named *output_var_name*\n from variables named *input_var_names* contained in zero, one, or more\n input data cubes in *input_cubes* using a cube factory function *cube_func*.\n\n For a more detailed description of the function usage,\n please refer to :func:compute_dataset.\n\n :param cube_func: The cube factory function.\n :param input_cubes: An optional sequence of input cube datasets, must be provided if *input_cube_schema* is not.\n :param input_cube_schema: An optional input cube schema, \n must be provided if *input_cubes* is not. \n Will be ignored if *input_cubes* is provided.\n :param input_var_names: A sequence of variable names\n :param input_params: Optional dictionary with processing parameters passed to *cube_func*.\n :param output_var_name: Optional name of the output variable, defaults to ``'output'``.\n :param output_var_dtype: Optional numpy datatype of the output variable, defaults to ``'float32'``.\n :param output_var_attrs: Optional metadata attributes for the output variable.\n :param vectorize: Whether all *input_cubes* have the same variables which are concatenated and passed as vectors\n to *cube_func*. Not implemented yet.\n :param cube_asserted: If False, *cube* will be verified, otherwise it is expected to be a valid cube.\n :return: A new dataset that contains the computed output variable.\n \"\"\"\n return compute_dataset(cube_func,\n *input_cubes,\n input_cube_schema=input_cube_schema,\n input_var_names=input_var_names,\n input_params=input_params,\n output_var_name=output_var_name,\n output_var_dtype=output_var_dtype,\n output_var_attrs=output_var_attrs,\n vectorize=vectorize,\n cube_asserted=cube_asserted)\n\n\ndef compute_dataset(cube_func: CubeFunc,\n *input_cubes: xr.Dataset,\n input_cube_schema: CubeSchema = None,\n input_var_names: Sequence[str] = None,\n input_params: Dict[str, Any] = None,\n output_var_name: str = 'output',\n output_var_dims: AbstractSet[str] = None,\n output_var_dtype: Any = np.float64,\n output_var_attrs: Dict[str, Any] = None,\n vectorize: bool = None,\n cube_asserted: bool = False) -> xr.Dataset:\n \"\"\"\n Compute a new output dataset with a single variable named *output_var_name*\n from variables named *input_var_names* contained in zero, one, or more\n input data cubes in *input_cubes* using a cube factory function *cube_func*.\n\n *cube_func* is called concurrently for each of the chunks of the input variables.\n It is expected to return a chunk block whith is type ``np.ndarray``.\n\n If *input_cubes* is not empty, *cube_func* receives variables as specified by *input_var_names*.\n If *input_cubes* is empty, *input_var_names* must be empty too, and *input_cube_schema*\n must be given, so that a new cube can be created.\n\n The full signature of *cube_func* is:::\n\n def cube_func(*input_vars: np.ndarray,\n input_params: Dict[str, Any] = None,\n dim_coords: Dict[str, np.ndarray] = None,\n dim_ranges: Dict[str, Tuple[int, int]] = None) -> np.ndarray:\n pass\n\n The arguments are:\n\n * ``input_vars``: the variables according to the given *input_var_names*;\n * ``input_params``: is this call's *input_params*, a mapping from parameter name to value;\n * ``dim_coords``: a mapping from dimension names to the current chunk's coordinate arrays;\n * ``dim_ranges``: a mapping from dimension names to the current chunk's index ranges.\n\n Only the ``input_vars`` argument is mandatory. The keyword arguments\n ``input_params``, ``input_params``, ``input_params`` do need to be present at all.\n\n *output_var_dims* my be given in the case, where ...\n TODO: describe new output_var_dims...\n\n :param cube_func: The cube factory function.\n :param input_cubes: An optional sequence of input cube datasets, must be provided if *input_cube_schema* is not.\n :param input_cube_schema: An optional input cube schema, must be provided if *input_cubes* is not.\n :param input_var_names: A sequence of variable names\n :param input_params: Optional dictionary with processing parameters passed to *cube_func*.\n :param output_var_name: Optional name of the output variable, defaults to ``'output'``.\n :param output_var_dims: Optional set of names of the output dimensions,\n used in the case *cube_func* reduces dimensions.\n :param output_var_dtype: Optional numpy datatype of the output variable, defaults to ``'float32'``.\n :param output_var_attrs: Optional metadata attributes for the output variable.\n :param vectorize: Whether all *input_cubes* have the same variables which are concatenated and passed as vectors\n to *cube_func*. Not implemented yet.\n :param cube_asserted: If False, *cube* will be verified, otherwise it is expected to be a valid cube.\n :return: A new dataset that contains the computed output variable.\n \"\"\"\n if vectorize is not None:\n # TODO: support vectorize = all cubes have same variables and cube_func\n # receives variables as vectors (with extra dim)\n raise NotImplementedError('vectorize is not supported yet')\n\n if not cube_asserted:\n for cube in input_cubes:\n assert_cube(cube)\n\n # Check compatibility of inputs\n if input_cubes:\n input_cube_schema = CubeSchema.new(input_cubes[0])\n for cube in input_cubes:\n if not cube_asserted:\n assert_cube(cube)\n if cube != input_cubes[0]:\n # noinspection PyUnusedLocal\n other_schema = CubeSchema.new(cube)\n # TODO (forman): broadcast all cubes to same shape, rechunk to same chunks\n elif input_cube_schema is None:\n raise ValueError('input_cube_schema must be given')\n\n output_var_name = output_var_name or 'output'\n\n # Collect named input variables, raise if not found\n input_var_names = input_var_names or []\n input_vars = []\n for var_name in input_var_names:\n input_var = None\n for cube in input_cubes:\n if var_name in cube.data_vars:\n input_var = cube[var_name]\n break\n if input_var is None:\n raise ValueError(f'variable {var_name!r} not found in any of cubes')\n input_vars.append(input_var)\n\n # Find out, if cube_func uses any of _PREDEFINED_KEYWORDS\n has_input_params, has_dim_coords, has_dim_ranges = _inspect_cube_func(cube_func, input_var_names)\n\n def cube_func_wrapper(index_chunk, *input_var_chunks):\n nonlocal input_cube_schema, input_var_names, input_params, input_vars\n nonlocal has_input_params, has_dim_coords, has_dim_ranges\n\n # Note, xarray.apply_ufunc does a test call with empty input arrays,\n # so index_chunk.size == 0 is a valid case\n empty_call = index_chunk.size == 0\n\n # TODO: when output_var_dims is given, index_chunk must be reordered\n # as core dimensions are moved to the and of index_chunk and input_var_chunks\n if not empty_call:\n index_chunk = index_chunk.ravel()\n\n if index_chunk.size < 2 * input_cube_schema.ndim:\n if not empty_call:\n warnings.warn(f\"unexpected index_chunk of size {index_chunk.size} received!\")\n return None\n\n dim_ranges = None\n if has_dim_ranges or has_dim_coords:\n dim_ranges = {}\n for i in range(input_cube_schema.ndim):\n dim_name = input_cube_schema.dims[i]\n if not empty_call:\n start = int(index_chunk[2 * i + 0])\n end = int(index_chunk[2 * i + 1])\n dim_ranges[dim_name] = start, end\n else:\n dim_ranges[dim_name] = ()\n\n dim_coords = None\n if has_dim_coords:\n dim_coords = {}\n for coord_var_name, coord_var in input_cube_schema.coords.items():\n coord_slices = [slice(None)] * coord_var.ndim\n for i in range(input_cube_schema.ndim):\n dim_name = input_cube_schema.dims[i]\n if dim_name in coord_var.dims:\n j = coord_var.dims.index(dim_name)\n coord_slices[j] = slice(*dim_ranges[dim_name])\n dim_coords[coord_var_name] = coord_var[tuple(coord_slices)].values\n\n kwargs = {}\n if has_input_params:\n kwargs['input_params'] = input_params\n if has_dim_ranges:\n kwargs['dim_ranges'] = dim_ranges\n if has_dim_coords:\n kwargs['dim_coords'] = dim_coords\n\n return cube_func(*input_var_chunks, **kwargs)\n\n index_var = _gen_index_var(input_cube_schema)\n\n all_input_vars = [index_var] + input_vars\n\n input_core_dims = None\n if output_var_dims:\n input_core_dims = []\n has_warned = False\n for i in range(len(all_input_vars)):\n input_var = all_input_vars[i]\n var_core_dims = [dim for dim in input_var.dims if dim not in output_var_dims]\n must_rechunk = False\n if var_core_dims and input_var.chunks:\n for var_core_dim in var_core_dims:\n dim_index = input_var.dims.index(var_core_dim)\n dim_chunk_size = input_var.chunks[dim_index][0]\n dim_shape_size = input_var.shape[dim_index]\n if dim_chunk_size != dim_shape_size:\n must_rechunk = True\n break\n if must_rechunk:\n if not has_warned:\n warnings.warn(f'Input variables must not be chunked in dimension(s): {\", \".join(var_core_dims)}.\\n'\n f'Rechunking applies, which may drastically decrease runtime performance '\n f'and increase memory usage.')\n has_warned = True\n all_input_vars[i] = input_var.chunk({var_core_dim: -1 for var_core_dim in var_core_dims})\n input_core_dims.append(var_core_dims)\n\n output_var = xr.apply_ufunc(cube_func_wrapper,\n *all_input_vars,\n dask='parallelized',\n input_core_dims=input_core_dims,\n output_dtypes=[output_var_dtype])\n if output_var_attrs:\n output_var.attrs.update(output_var_attrs)\n return xr.Dataset({output_var_name: output_var}, coords=input_cube_schema.coords)\n\n\ndef _inspect_cube_func(cube_func: CubeFunc, input_var_names: Sequence[str] = None):\n args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations \\\n = inspect.getfullargspec(cube_func)\n cube_func_name = '?'\n if hasattr(cube_func, '__name__'):\n cube_func_name = cube_func.__name__\n true_args = [arg not in _PREDEFINED_KEYWORDS for arg in args]\n if False in true_args and any(true_args[true_args.index(False):]):\n raise ValueError(f'invalid cube_func {cube_func_name!r}: '\n f'any argument must occur before any of {\", \".join(_PREDEFINED_KEYWORDS)}, '\n f'but got {\", \".join(args)}')\n if not all(true_args) and varargs:\n raise ValueError(f'invalid cube_func {cube_func_name!r}: '\n f'any argument must occur before any of {\", \".join(_PREDEFINED_KEYWORDS)}, '\n f'but got {\", \".join(args)} before *{varargs}')\n num_input_vars = len(input_var_names) if input_var_names else 0\n num_args = sum(true_args)\n if varargs is None and num_input_vars != num_args:\n raise ValueError(f'invalid cube_func {cube_func_name!r}: '\n f'expected {num_input_vars} arguments, '\n f'but got {\", \".join(args)}')\n has_input_params = 'input_params' in args or 'input_params' in kwonlyargs\n has_dim_coords = 'dim_coords' in args or 'dim_coords' in kwonlyargs\n has_dim_ranges = 'dim_ranges' in args or 'dim_ranges' in kwonlyargs\n return has_input_params, has_dim_coords, has_dim_ranges\n\n\ndef _gen_index_var(cube_schema: CubeSchema):\n dims = cube_schema.dims\n shape = cube_schema.shape\n chunks = cube_schema.chunks\n\n # noinspection PyUnusedLocal\n def get_chunk(cube_store: ChunkStore, name: str, index: Tuple[int, ...]) -> bytes:\n data = np.zeros(cube_store.chunks, dtype=np.uint64)\n data_view = data.ravel()\n if data_view.base is not data:\n raise ValueError('view expected')\n if data_view.size < cube_store.ndim * 2:\n raise ValueError('size too small')\n for i in range(cube_store.ndim):\n j1 = cube_store.chunks[i] * index[i]\n j2 = j1 + cube_store.chunks[i]\n data_view[2 * i] = j1\n data_view[2 * i + 1] = j2\n return data.tobytes()\n\n store = ChunkStore(dims, shape, chunks)\n store.add_lazy_array('__index_var__', ', subject <%s>, status <%s>\",\n recipient,\n subject,\n status,\n )\n if recipient:\n # It is possible for more than one survey to share a fax machine\n interventions = Intervention.objects.filter(\n contact__normalised_fax=recipient, method=\"f\"\n )\n ids = [x.pk for x in interventions]\n if len(ids) == 0:\n raise Http404()\n if status == \"0\":\n interventions.update(receipt=True)\n logger.info(\"Intervention %s marked as received\", ids)\n elif int(status) > 0:\n interventions.update(receipt=False)\n logger.warn(\n \"Problem sending fax for intervention %s (status %s)\", ids, status\n )\n else:\n logger.info(\n \"Received temporary fax status for intervention %s (status %s)\",\n ids,\n status,\n )\n else:\n logger.warn(\"Unable to parse intervention\")\n return HttpResponse(\"OK\")\n\n\ndef measure_redirect(request, method, practice_id):\n intervention = Intervention.objects.get(method=method, practice_id=practice_id)\n if request.POST:\n # The user has filled out the one-off interstitial\n # questionnaire\n if request.POST[\"survey_response\"].lower() == \"yes\":\n intervention.contact.survey_response = True\n elif request.POST[\"survey_response\"].lower() == \"no\":\n intervention.contact.survey_response = False\n intervention.contact.save()\n else:\n intervention.hits += 1\n intervention.save()\n if intervention.contact.total_hits() == 1:\n return render(request, \"questionnaire.html\")\n return redirect(intervention.get_target_url())\n\n\ndef intervention_message(request, intervention_id):\n intervention = get_object_or_404(Intervention, pk=intervention_id)\n practice_name = intervention.contact.cased_name\n context = {}\n show_header_from = True\n if intervention.method == \"p\":\n show_header_to = True\n else:\n show_header_to = False\n template = \"intervention.html\"\n encoded_image = make_chart(intervention.metadata[\"value\"])\n with open(\n os.path.join(settings.BASE_DIR, \"nimodipine\", \"static\", \"header.png\"), \"rb\"\n ) as img:\n header_image = base64.b64encode(img.read()).decode(\"ascii\")\n with open(\n os.path.join(settings.BASE_DIR, \"nimodipine\", \"static\", \"footer.png\"), \"rb\"\n ) as img:\n footer_image = base64.b64encode(img.read()).decode(\"ascii\")\n intervention_url = \"op2.org.uk{}\".format(intervention.get_absolute_url())\n intervention_url = '{}'.format(\n intervention_url, intervention_url\n )\n context.update(\n {\n \"intervention\": intervention,\n \"practice_name\": practice_name,\n \"intervention_url\": SafeText(intervention_url),\n \"encoded_image\": encoded_image,\n \"header_image\": header_image,\n \"footer_image\": footer_image,\n \"show_header_from\": show_header_from,\n \"show_header_to\": show_header_to,\n }\n )\n return render(request, template, context=context)\n\n\ndef make_chart(practice_value):\n \"\"\"Draw lines on a pre-made chart pointing to a peak (always in the\n same place), and a point on the axis (variable).\n\n Args:\n practice_value: numeric value that will be plotted on x-axis\n\n Returns:\n base64-encoded image\n\n \"\"\"\n # set up chart, dimensions\n base_image_path = os.path.join(\n settings.BASE_DIR, \"nimodipine\", \"static\", \"chart.png\"\n )\n im = Image.open(base_image_path)\n d = ImageDraw.Draw(im)\n try:\n fnt = ImageFont.truetype(\"arial.ttf\", 14)\n except OSError: # font not installed\n try:\n # Use Free version of Arial\n fnt = ImageFont.truetype(\"LiberationSans-Regular.ttf\", 14)\n except OSError:\n # fallback to anything\n logger.warn(\"Falling back to default font for drawing charts\")\n fnt = ImageFont.load_default()\n\n blue_text = \"99% of practices \\n(0 tablets per 1000 patients)\"\n red_text = \"Your practice\\n({} tablets per 1000 patients)\".format(round(float(practice_value)))\n x_axis_origin_coords = (69, 221)\n x_axis_end_coords = (388, 221)\n x_axis_width = x_axis_end_coords[0] - x_axis_origin_coords[0]\n x_axis_max = 240 # The value at the extreme end of X-axis\n blue_line_coords = (77, 17) # coords of pointer to the peak in the chart\n\n practice_x = x_axis_origin_coords[0] + int(\n (float(practice_value) / x_axis_max * x_axis_width)\n )\n practice_coords = (practice_x, x_axis_origin_coords[1])\n # Arrived at by trial-and-error, so red text never overflows right edge of chart:\n red_text_max_x = 180\n red_text_min_x = blue_line_coords[0] + 2\n\n def arrow(d, arrow_end, feather_end, fill=\"red\", width=1):\n if arrow_end[0] == feather_end[0]:\n orientation = \"vertical\"\n elif arrow_end[1] == feather_end[1]:\n orientation = \"horizontal\"\n else:\n raise BaseException(\"Must be horizontal or vertical\")\n\n d.line((arrow_end, feather_end), fill=fill, width=width)\n if orientation == \"vertical\":\n d.line(\n (arrow_end, (arrow_end[0] - 5, arrow_end[1] - 5)),\n fill=fill,\n width=width,\n )\n d.line(\n (arrow_end, (arrow_end[0] + 5, arrow_end[1] - 5)),\n fill=fill,\n width=width,\n )\n else:\n d.line(\n (arrow_end, (arrow_end[0] + 5, arrow_end[1] - 5)),\n fill=fill,\n width=width,\n )\n d.line(\n (arrow_end, (arrow_end[0] + 5, arrow_end[1] + 5)),\n fill=fill,\n width=width,\n )\n\n # Draw line pointing at peak\n blue_line_feather_end_coords = (blue_line_coords[0] + 60, blue_line_coords[1])\n blue_text_coords = (\n blue_line_feather_end_coords[0] + 5,\n blue_line_feather_end_coords[1] - 6,\n )\n arrow(d, blue_line_coords, blue_line_feather_end_coords, fill=\"blue\")\n d.text(blue_text_coords, blue_text, font=fnt, fill=\"blue\")\n\n # Draw line pointing at practice\n red_line_feather_end_coords = (practice_coords[0], practice_coords[1] - 25)\n red_text_x = red_line_feather_end_coords[0] - 20\n if red_text_x < red_text_min_x:\n red_text_x = red_text_min_x\n elif red_text_x > red_text_max_x:\n red_text_x = red_text_max_x\n red_text_coords = (red_text_x, red_line_feather_end_coords[1] - 40)\n arrow(d, practice_coords, red_line_feather_end_coords)\n d.text(red_text_coords, red_text, font=fnt, fill=\"red\")\n\n # Render image to base64-encoding\n mock_file = BytesIO()\n im.save(mock_file, \"png\")\n mock_file.seek(0)\n return base64.b64encode(mock_file.read()).decode(\"ascii\")\n","repo_name":"ebmdatalab/nimodipine-rct","sub_path":"nimodipine-webapp/nimodipine/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8041,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"16906650615","text":"\"\"\"\nThe file for defining objects in the game\n\"\"\"\n\nfrom pygame import Rect, Surface, draw\nfrom pygame.sprite import Sprite\nfrom collections import deque\n\nfrom mlgame.utils.enum import StringEnum, auto\n\nclass Food(Sprite):\n def __init__(self):\n super().__init__()\n\n self.rect = Rect(0, 0, 10, 10)\n\n surface = Surface(self.rect.size)\n draw.circle(surface, (232, 54, 42), self.rect.center, 5)\n\n self.image = surface\n\n @property\n def pos(self):\n return self.rect.topleft\n\n @pos.setter\n def pos(self, value):\n self.rect.topleft = value\n\nclass SnakeBody(Sprite):\n def __init__(self, init_pos, color):\n super().__init__()\n\n self.rect = Rect(init_pos[0], init_pos[1], 10, 10)\n\n width = self.rect.width\n height = self.rect.height\n\n self.image = Surface((width, height))\n self.image.fill(color)\n draw.line(self.image, (0, 0, 0), (width - 1, 0), (width - 1, height - 1))\n draw.line(self.image, (0, 0, 0), (0, height - 1), (width - 1, height - 1))\n\n @property\n def pos(self):\n return self.rect.topleft\n\n @pos.setter\n def pos(self, value):\n self.rect.topleft = value\n\nclass SnakeAction(StringEnum):\n UP = auto()\n DOWN = auto()\n LEFT = auto()\n RIGHT = auto()\n NONE = auto()\n\nclass Snake:\n def __init__(self):\n self.head = SnakeBody((40, 40), (31, 204, 42)) # Green\n\n self.body = deque()\n self.body_color = (255, 255, 255) # White\n # Note the ordering of appending elements\n self.body.append(SnakeBody((40, 30), self.body_color))\n self.body.append(SnakeBody((40, 20), self.body_color))\n self.body.append(SnakeBody((40, 10), self.body_color))\n\n # Initialize the action to going down\n self._action = SnakeAction.DOWN\n\n @property\n def head_pos(self):\n return self.head.pos\n\n def is_body_pos(self, position):\n \"\"\"\n Check if there has a snake body at the given position\n \"\"\"\n for body in self.body:\n if body.pos == position:\n return True\n\n return False\n\n def grow(self):\n \"\"\"\n Add a new snake body at the tail\n \"\"\"\n new_body = SnakeBody(self.body[-1].pos, self.body_color)\n self.body.append(new_body)\n\n return new_body\n\n def move(self, action):\n \"\"\"\n Move the snake according to the given action\n \"\"\"\n # If there is no action, take the same action as the last frame.\n if action == SnakeAction.NONE:\n action = self._action\n\n # If the head will go back to the body,\n # take the same action as the last frame.\n possible_head_pos = self._get_possible_head_pos(action)\n if possible_head_pos == self.body[0].pos:\n action = self._action\n\n # Move the body 1 step ahead\n tail = self.body.pop()\n tail.pos = self.head.pos\n self.body.appendleft(tail)\n\n # Get the next head position according to the valid action\n next_head_pos = self._get_possible_head_pos(action)\n self.head.pos = next_head_pos\n\n # Store the action\n self._action = action\n\n def _get_possible_head_pos(self, action):\n \"\"\"\n Get the possible head position according to the given action\n \"\"\"\n if action == SnakeAction.UP:\n move_delta = (0, -10)\n elif action == SnakeAction.DOWN:\n move_delta = (0, 10)\n elif action == SnakeAction.LEFT:\n move_delta = (-10, 0)\n elif action == SnakeAction.RIGHT:\n move_delta = (10, 0)\n\n return self.head.rect.move(move_delta).topleft\n","repo_name":"LanKuDot/MLGame","sub_path":"games/snake/game/gameobject.py","file_name":"gameobject.py","file_ext":"py","file_size_in_byte":3705,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"27"} +{"seq_id":"40229768293","text":"from tkinter import *\r\nfrom tkinter import messagebox\r\nfrom tkinter import ttk\r\nimport pygame\r\nimport turtle as t\r\nimport random\r\n\r\n\r\n\r\ninf = {}\r\n\r\n\r\ndef login_click1():\r\n \r\n messagebox.showinfo(title=\"알림\", message=\"존재하지 않는 아이디 입니다. 회원가입을 해주세요.\")\r\n e1.delete(0, END)\r\n e2.delete(0, END)\r\n \r\ndef login_click2():\r\n \r\n a = inf[e1.get()]\r\n messagebox.showinfo(title=\"알림\", message=a[\"age\"]+\" \"+a[\"gender\"]+\" \"+a[\"name\"]+\" 님 환영합니다.\")\r\n e1.delete(0, END)\r\n e2.delete(0, END)\r\n\r\n global score \r\n score = 0 # 점수 저장\r\n global playing\r\n playing = False #현재 게임이 플레이 중인지 확인하는 함수\r\n te = t.Turtle()\r\n te.color(\"red\")\r\n te.speed(150)\r\n te.up()\r\n te.goto(0,200)\r\n\r\n ts = t.Turtle()\r\n ts.shape(\"circle\")\r\n ts.color(\"green\")\r\n ts.speed(20)\r\n ts.up()\r\n ts.goto(0,-200)\r\n\r\n\r\n def turn_right():\r\n t.setheading(0)\r\n def turn_up():\r\n t.setheading(90)\r\n def turn_left():\r\n t.setheading(180)\r\n def turn_down():\r\n t.setheading(270)\r\n\r\n def start(): #게임을 시작하는 함수\r\n global playing\r\n if playing ==False:\r\n playing =True\r\n t.clear() #메시지를 지움\r\n play()\r\n\r\n def play():\r\n global score \r\n global playing \r\n t.fd(20) \r\n if random.randint(1,5) == 3: #1에서 5까지 임의수를 뽑는건데 임의수=3이면의 가정(20%확률)\r\n ang = te.towards(t.pos()) #position\r\n te.setheading(ang)\r\n speed = score + 25 #점수가 올라가면 빨라짐\r\n if speed > 115: #속도가 15를 넘지 않게함\r\n speed = 15\r\n te.forward(speed)\r\n if t.distance(te) < 12: #주인공과 거리가 12보다 작으면 게임을 종료함\r\n text = \"Score:\" +str(score)\r\n message(\"Game Over\", text)\r\n playing = False\r\n score = 0\r\n ts.goto(0,-200)\r\n if t.distance(ts) < 12: #주인공과 거리가 12보다 작으면\r\n score = score + 1 #점수를 올림\r\n t.write(score)#점수를 화면에 표시\r\n star_x = random.randint (-230, 230)\r\n star_y = random.randint (-230, 230)\r\n ts.goto(star_x, star_y) #먹이를 옮김\r\n if playing:\r\n t.ontimer(play, 100)\r\n\r\n def message(m1,m2): #메세지를 화면에 표시\r\n t.clear()\r\n t.goto(0,100)\r\n t.write(m1, False, \"center\", (\"\", 20))\r\n t.goto(0, -100)\r\n t.write(m2, False, \"center\", (\"\", 15))\r\n t.home()\r\n\r\n\r\n t.title(\"Turtle Run\") #제목\r\n t.setup(500,500)\r\n t.bgcolor(\"orange\")\r\n t.shape(\"turtle\")\r\n t.speed(0)\r\n t.up()\r\n t.color(\"white\")\r\n t.onkeypress(turn_right, \"Right\") #방향키 오른쪽 화살표\r\n t.onkeypress(turn_up, \"Up\")\r\n t.onkeypress(turn_left, \"Left\")\r\n t.onkeypress(turn_down, \"Down\")\r\n t.onkeypress(start, \"space\") #시작\r\n t.listen()\r\n message(\"Turtle Run\", \"[space]\") #첨가\r\n\r\n t.mainloop()\r\n \r\n\r\ndef login_click3():\r\n messagebox.showinfo(title=\"알림\", message=\"비밀번호가 일치하지 않습니다.\")\r\n e2.delete(0, END) \r\n\r\ndef login():\r\n \r\n \r\n if e1.get() not in inf.keys():\r\n login_click1()\r\n \r\n elif e1.get() in inf.keys():\r\n \r\n a = inf[e1.get()]\r\n if a[\"Password\"] == e2.get():\r\n login_click2()\r\n else :\r\n login_click3()\r\n\r\ndef entry():\r\n \r\n window1 = Tk()\r\n window1.title(\"회원가입\")\r\n \r\n strs = StringVar()\r\n strs2 = StringVar()\r\n\r\n l1 = Label(window1 , text=\"회원 정보를 입력 및 선택 하시오.\", font=\"helvetica 10\")\r\n l1.grid(row=0, column=1)\r\n l2 = Label(window1, text=\"ID\")\r\n l2.grid(row=1, column=0)\r\n l3 = Label(window1, text=\"Password\")\r\n l3.grid(row=2, column=0)\r\n l4 = Label(window1, text=\"name\")\r\n l4.grid(row=3, column=0)\r\n l5 = Label(window1, text=\"age\")\r\n l5.grid(row=4, column=0)\r\n l6 = Label(window1, text=\"gender\")\r\n l6.grid(row=5, column=0)\r\n \r\n e1 = Entry(window1, bg=\"white\", fg=\"black\")\r\n e1.grid(row=1, column=1,columnspan=3)\r\n e2 = Entry(window1, bg=\"white\", fg=\"black\")\r\n e2.grid(row=2, column=1,columnspan=3)\r\n e3 = Entry(window1, bg=\"white\", fg=\"black\")\r\n e3.grid(row=3, column=1,columnspan=3)\r\n \r\n com1 = ttk.Combobox(window1, textvariable=strs, width = 18)\r\n com1['value'] = ('나이를 선택하시오.','10대','20대','30대','40대')\r\n com1.current(0)\r\n com1.grid(row=4, column=1,columnspan=3)\r\n com2 = ttk.Combobox(window1, textvariable=strs2, width = 18)\r\n com2['value'] = ('성별을 선택하시오.','남성','여성')\r\n com2.current(0)\r\n com2.grid(row=5, column=1,columnspan=3)\r\n \r\n def entry_click():\r\n \r\n ID = e1.get()\r\n Password = e2.get()\r\n name = e3.get()\r\n age = com1.get()\r\n gender = com2.get()\r\n \r\n information = {'Password':Password,'name':name,'age':age,'gender':gender}\r\n \r\n inf[ID] = information\r\n \r\n print(inf)\r\n \r\n messagebox.showinfo(title=\"회원가입 성공\", message=\"회원가입이 완료되었습니다.\")\r\n com1.current(0)\r\n com2.current(0)\r\n e1.delete(0, END)\r\n e2.delete(0, END)\r\n e3.delete(0, END)\r\n \r\n b1 = Button(window1, text=\"입력완료\",command=entry_click)\r\n b1.grid(row=6, column=1)\r\n \r\n window1.mainloop()\r\n \r\ndef find():\r\n \r\n window2 = Tk()\r\n window2.title(\"비밀번호 찾기\")\r\n \r\n l1 = Label(window2 , text=\"ID를 입력하세요 :\")\r\n l1.grid(row=0, column=0)\r\n e1 = Entry(window2, bg=\"pink\", fg=\"white\")\r\n e1.grid(row=0, column=1,columnspan=3)\r\n \r\n def find_click():\r\n \r\n if e1.get() in inf.keys():\r\n a = inf[e1.get()]\r\n messagebox.showinfo(title=\"비밀번호 알림\", message=a[\"Password\"])\r\n e1.delete(0, END)\r\n \r\n else :\r\n login_click1()\r\n e1.delete(0, END)\r\n \r\n b1 = Button(window2, text=\"확인\",command=find_click)\r\n b1.grid(row=2, column=1)\r\n \r\n window2.mainloop()\r\n \r\n \r\nwindow = Tk()\r\n\r\nl1 = Label(window , text=\"ID\")\r\nl2 = Label(window, text=\"Password\")\r\nl1.grid(row=0, column=0)\r\nl2.grid(row=1, column=0)\r\n\r\ne1 = Entry(window, bg=\"skyblue\", fg=\"black\")\r\ne2 = Entry(window, bg=\"skyblue\", fg=\"black\")\r\ne1.grid(row=0, column=1,columnspan=3)\r\ne2.grid(row=1, column=1,columnspan=3)\r\n\r\nb1 = Button(window, text=\"로그인\",command=login)\r\nb2 = Button(window, text=\"회원가입\",command=entry)\r\nb3 = Button(window, text=\"Password 찾기\",command=find)\r\nb1.grid(row=2, column=0)\r\nb2.grid(row=2, column=1)\r\nb3.grid(row=2, column=3)\r\n\r\nwindow.mainloop()\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\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"joungyoumin/jym","sub_path":"동계 SW project (상일여고)/combination.py","file_name":"combination.py","file_ext":"py","file_size_in_byte":6939,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"18161010983","text":"#bucle while\n# ? ciclo que continua mientras una condición es\n# ? verdadera y se detiene cuando es falsa \n\nx = 20\nwhile x < 35:\n print(x)\n x+=3\n\nprint(\"_____________\")\ntupla = (1, 2, 3, 4, 5, 6, 7, 8)\n\ny = 20\nwhile y > len(tupla):\n print(y)\n y-=2\n","repo_name":"leafarJS/introduccion_python","sub_path":"09_bucle_while.py","file_name":"09_bucle_while.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"24107751024","text":"from dataclasses import dataclass\n\n\ndef path_points(path):\n allpos = dict()\n pos = (0, 0)\n steps = 0\n for move in path.split(','):\n direction, length = move[0], int(move[1:])\n # could be a hash map instead\n if direction == 'R':\n axis, increment = 0, 1\n elif direction == 'L':\n axis, increment = 0, -1\n elif direction == 'U':\n axis, increment = 1, 1\n elif direction == 'D':\n axis, increment = 1, -1\n else:\n raise ValueError(direction)\n\n for j in range(1, length+1):\n steps += 1\n pos = list(pos)\n pos[axis] += increment\n pos = tuple(pos)\n if pos in allpos:\n continue\n\n allpos[pos] = steps\n\n return allpos\n\n\ndef min_dist(path1, path2):\n common = set(path_points(p1).keys()) & set(path_points(p2).keys())\n return min(abs(pos[0]) + abs(pos[1]) for pos in common)\n\n\np1 = 'R8,U5,L5,D3'\np2 = 'U7,R6,D4,L4'\nassert min_dist(p1, p2) == 6\n\np1 = 'R75,D30,R83,U83,L12,D49,R71,U7,L72'\np2 = 'U62,R66,U55,R34,D71,R55,D58,R83'\nassert min_dist(p1, p2) == 159\n\np1 = 'R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51'\np2 = 'U98,R91,D20,R16,D67,R40,U7,R15,U6,R7'\nassert min_dist(p1, p2) == 135\n\n# TASK 1\n\nwith open('day3_data.txt') as f:\n p1, p2 = next(f), next(f)\n\nprint(min_dist(p1, p2))\n\n# TASK 2\n\n\ndef min_cost(path1, path2):\n pp1 = path_points(path1)\n pp2 = path_points(path2)\n common = set(pp1.keys()) & set(pp2.keys())\n return min(pp1[key] + pp2[key] for key in common)\n\n\np1 = 'R8,U5,L5,D3'\np2 = 'U7,R6,D4,L4'\nassert min_cost(p1, p2) == 30\n\np1 = 'R75,D30,R83,U83,L12,D49,R71,U7,L72'\np2 = 'U62,R66,U55,R34,D71,R55,D58,R83'\nassert min_cost(p1, p2) == 610\n\np1 = 'R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51'\np2 = 'U98,R91,D20,R16,D67,R40,U7,R15,U6,R7'\nassert min_cost(p1, p2) == 410\n\nwith open('day3_data.txt') as f:\n p1, p2 = next(f), next(f)\n\nprint(min_cost(p1, p2))\n","repo_name":"kokes/adventofcode2019","sub_path":"day3.py","file_name":"day3.py","file_ext":"py","file_size_in_byte":1977,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"15585752938","text":"from __future__ import print_function\nimport os\nimport sys\n\ndef getconfig(qmc):\n f = open(\"%s.config.iblockxyz\"%(qmc),'r')\n A=f.read()\n D=A.split(\"\\n\")\n D.remove('');\n ZZ={}\n for k in range(0,len(D)):\n E=D[k].split(\" \")\n E.remove('');\n F={}\n for l in range(0,3):\n F[l]=float(E[l])\n ZZ[k]=F\n\n return (ZZ)\n\ndef configtransz(ZZ,zd,dzm,dzp):\n for k in range(0,len(ZZ)):\n Z=ZZ[k]\n if Z[0]>zd:\n Z[0]=Z[0]+dzp\n else:\n Z[0]=Z[0]+dzm\n\ndef printconfig(ZZ):\n mstrout=\"\"\n for k in range(0,len(ZZ)):\n Z=ZZ[k]\n mstrout=mstrout+\"%.15f %.15f %.15f\"%(Z[0],Z[1],Z[2])\n if k!=(len(ZZ)-1):\n mstrout=mstrout+\"\\n\"\n\n return (mstrout)\n","repo_name":"wuyb02/qmpy","sub_path":"qmcconfigread.py","file_name":"qmcconfigread.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"1310280701","text":"#sending messages to a broker with 1 topic and 2 partitions\n# we will have a single publisher/producer\n#we will have a single topic\n# our topic will have two partitions\n#the message will be published to a particular predefined pertion \n\n# although messages are randomly sent to different partitons of a topic we can decide to send to a particular partition\n\n#when we define a producer we can use a partitioner method to decide what patition the producer should send to.\n\n#we will use a method to define this new behaviour\n\nfrom kafka.admin import KafkaAdminClient, NewTopic\nfrom kafka import KafkaProducer\nfrom data import get_registered_user\nimport json\nimport time\n\ndef json_serializer(data):\n return json.dumps(data).encode('utf-8')\n\ndef get_partition(key, all, available):\n #we want to always send the message to partition 0\n return 0\n\n\nadmin_client = KafkaAdminClient(\n bootstrap_servers=\"localhost:9092\" \n #client_id='test'\n)\n\ntopic_list = []\ntopic_list.append(NewTopic(name=\"example_topic\", num_partitions=2, replication_factor=1))\nadmin_client.create_topics(new_topics=topic_list, validate_only=False)\n\n\n\nproducer = KafkaProducer(bootstrap_servers=['localhost:9092'],\n value_serializer=json_serializer,\n partitioner=get_partition)\n\n\nif __name__ == \"__main__\":\n while True:\n registered_user = get_registered_user()\n print(\"sending a new message\")\n producer.send(\"example_topic\", registered_user)\n print(\"sent: \", registered_user)\n time.sleep(4)\n","repo_name":"JesuFemi-O/kafka-python-for-beginners","sub_path":"ex_3.py","file_name":"ex_3.py","file_ext":"py","file_size_in_byte":1551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"8371041128","text":"import cv2 as cv\r\nimport numpy as np\r\n\r\nsrc1 = cv.imread('averaging.jpg')\r\nsrc2 = cv.imread('indir.jfif')\r\nsrc3= cv.imread('ylm2.jfif')\r\n\r\nhsv1=cv.cvtColor(src1,cv.COLOR_BGR2HSV)\r\nhsv2=cv.cvtColor(src2,cv.COLOR_BGR2HSV)\r\nhsv3=cv.cvtColor(src3,cv.COLOR_BGR2HSV)\r\n\r\nhist1=cv.calcHist([hsv1],[0,1],None,[60,64],[0,180,0,256])\r\nhist2=cv.calcHist([hsv2],[0,1],None,[60,64],[0,180,0,256])\r\nhist3=cv.calcHist([hsv3],[0,1],None,[60,64],[0,180,0,256])\r\n\r\ncv.normalize(hist1,hist1,0,1.0,cv.NORM_MINMAX)\r\ncv.normalize(hist2,hist2,0,1.0,cv.NORM_MINMAX)\r\ncv.normalize(hist3,hist3,0,1.0,cv.NORM_MINMAX)\r\n\r\na=cv.compareHist(hist1,hist2,cv.HISTCMP_CORREL)\r\nb=cv.compareHist(hist1,hist3,cv.HISTCMP_CORREL)\r\nc=cv.compareHist(hist2,hist3,cv.HISTCMP_CORREL)\r\n\r\nprint(a)\r\nprint(b)\r\nprint(c)","repo_name":"ylmgrbzz/Learning-to-OpenCV-with-Python","sub_path":"OpenCV/histogramComp.py","file_name":"histogramComp.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"2284176460","text":"# Compares several models ability to predict solubility\nimport matplotlib.pyplot as plt\nfrom rdkit import Chem\nfrom rdkit.Chem import rdMolDescriptors, Descriptors\nfrom chemical_models import AtomPairSolubility, LogP, LogPSolubility, CombinedSolubility\n\ndata = open('data/water_solubility/aqsol.txt', 'r')\n\nlogP_model = LogP('logP')\nlogP_solubility_model = LogPSolubility('logS_logP')\natom_pair_sol_model = AtomPairSolubility('water_solubility')\ncombined_model = CombinedSolubility('combined_solubility')\n\nx1, x2, x3, x4 = [], [], [], []\ny1, y2, y3, y4 = [], [], [], []\n\n# Read the molecule and corresponding solubility and split into X and Y\nfor line in data.readlines():\n split = line.split(' ')\n\n compound = Chem.MolFromSmiles(split[0])\n fingerprint = rdMolDescriptors.GetHashedAtomPairFingerprintAsBitVect(compound)\n\n logP = logP_model.run(fingerprint)\n logP_sol = logP_solubility_model.run(logP)\n atom_pair_sol = atom_pair_sol_model.run(fingerprint)\n combined_sol = combined_model.run(compound, logP, logP_sol, atom_pair_sol)\n\n # Additional ESOL empirical model to increase accuracy\n mw = Descriptors.ExactMolWt(compound)\n rb = rdMolDescriptors.CalcNumRotatableBonds(compound)\n ap = len(compound.GetSubstructMatches(Chem.MolFromSmarts('[a]')))/compound.GetNumHeavyAtoms()\n esol = 0.16 - 0.63*logP - 0.0062*mw + 0.066*rb - 0.74*ap\n\n x1.append(float(logP_sol))\n x2.append(float(atom_pair_sol))\n x3.append(float(esol))\n x4.append(float(combined_sol))\n\n y1.append(float(split[1][:-1]))\n y2.append(float(split[1][:-1]))\n y3.append(float(split[1][:-1]))\n y4.append(float(split[1][:-1]))\n\nplt.subplot(221)\nplt.scatter(x1, y1, s=1)\nplt.xlabel('Predicted')\nplt.ylabel('Experimental')\nplt.title('Solubility from Octanol/Water Partition Coefficient(LogP)')\n\nplt.subplot(222)\nplt.scatter(x2, y2, s=1)\nplt.xlabel('Predicted')\nplt.ylabel('Experimental')\nplt.title('Solubility from Atom Pair Fingerprint')\n\nplt.subplot(223)\nplt.scatter(x3, y3, s=1)\nplt.xlabel('Predicted')\nplt.ylabel('Experimental')\nplt.title('Solubility from ESOL')\n\nplt.subplot(224)\nplt.scatter(x4, y4, s=1)\nplt.xlabel('Predicted')\nplt.ylabel('Experimental')\nplt.title('Solubility From Combined Neural Network')\n\nplt.tight_layout()\n\nplt.show()\n\n","repo_name":"Zerwer/Chemistry","sub_path":"graphs/water_solubility.py","file_name":"water_solubility.py","file_ext":"py","file_size_in_byte":2264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"9784547441","text":"# For hackathon on Mon. May 8th\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom pathlib import Path\n\nfrom pandarallel import pandarallel\npandarallel.initialize(progress_bar=True)\n\n\ndef comma_to_int(df, col_name):\n df[col_name] = df[col_name].apply(lambda x: x.replace(',', '') if type(x) == str else x) \n df[col_name] = df[col_name].astype(float)\n df[col_name] = df[col_name].astype(int)\n return df\n\n\ndef clean_column_types():\n filepath = Path('.', 'nogit_data', 'list_of_post_contents.csv')\n filepath = './nogit_data/list_of_post_contents.csv'\n\n df = pd.read_csv(filepath)\n\n # -- Drop N/As and duplicates and unused columns\n df = df.dropna(subset='time_downloaded') # drop (my hacky) comment rows \n df = df.drop_duplicates('post_id') # post_id is unique across entire forum\n df.to_csv('nogit_data/list_of_post_contents_nona.csv', index=False)\n\n df.drop(columns=['comment', 'join_date_data', 'posted_date_data'], inplace=True)\n df.drop(columns=['num_likers'], inplace=True)\n\n # -- Turns strings into datetime type\n # use join_date_readable, not join_date_data; the two columns don't quite match up \n # df.join_date_data.parallel_apply(lambda x: pd.to_datetime(x, unit = 's'))\n df.join_date_readable.parallel_apply(lambda x: pd.to_datetime(x))\n\n # -- Turn strings into integers\n df = pd.read_csv('nogit_data/list_of_post_contents_nona.csv')\n for column in ['post_ordinal', 'author_num_posts', 'thread_page_num', 'thread_max_pages', 'num_quotes']:\n print(column)\n df = comma_to_int(df, column)\n\n # -- Remove mixed type from post_text by replacing NaNs with strings \n df['post_text'] = df['post_text'].fillna('N/A')#, inplace=True)\n\n def debug_types():\n # -- Check column types \n with pd.option_context('display.max_rows', 100, 'display.max_columns', 30):\n display(df[df.duplicated(subset=['post_ordinal', 'post_id', 'post_text'])])\n # DtypeWarning: Columns (3) have mixed types. Specify dtype option on import or set low_memory=False.\n for col in df.columns:\n unique_types = df[col].apply(type).unique()\n if len(unique_types) > 1: # if a column is mixed type\n print(col, unique_types)\n\n # -- Export finally\n readable = ['author', 'posted_date_readable', 'src_category_name', 'thread_page_url', 'thread_page_name', 'post_ordinal', 'post_text']\n df[readable].to_csv('nogit_data/post_data_only.csv', index=False)\n df.to_csv('nogit_data/dtype_fixed_posts_df.pkl')\n\nclean_column_types()","repo_name":"nro-bot/imi_datasets","sub_path":"HackathonDataset/fix_dtypes_for_hackathon.py","file_name":"fix_dtypes_for_hackathon.py","file_ext":"py","file_size_in_byte":2579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"42043581580","text":"import mimetypes\nfrom pathlib import PurePath, Path\n\nfrom django.conf import settings\nfrom django.contrib.staticfiles.templatetags.staticfiles import static\n\nfrom easy_thumbnails.files import Thumbnailer\n\n\nROOT = Path(settings.MEDIA_ROOT).resolve()\n\n\ndef safe_join(root, path, strict=False):\n '''\n Safely join two paths, and resolve as an absolute, ensuring the result is\n still under the root.\n\n Raises ValueError if resulting path is not under root.\n If strict = True, raises FileNotFoundError if root or the resulting path do\n not exist.\n '''\n p_root = Path(root).resolve(strict=strict)\n p_path = PurePath(path)\n\n p_full = (p_root / p_path).resolve(strict=strict)\n p_full.relative_to(p_root)\n return p_full\n\n\ndef dir_tree(root):\n '''\n Recursively produces a tree of directory info.\n '''\n try:\n return sorted([\n {\n 'name': p.name,\n 'path': str(p.relative_to(ROOT)),\n 'children': dir_tree(p),\n }\n for p in root.iterdir()\n if p.is_dir()\n ], key=lambda x: x['name'])\n except PermissionError:\n return []\n\n\ndef file_details(path):\n '''\n Returns a dict of info about a Path\n '''\n # st = path.stat()\n content_type, encoding = mimetypes.guess_type(path.name)\n\n if path.is_dir():\n img = static('filem/img/mimetypes/inode-directory.png')\n content_type = 'inode/directory'\n elif content_type is None:\n img = static('filem/img/mimetypes/unknown.png')\n elif content_type.startswith('image/'):\n tf = Thumbnailer(name=str(path.relative_to(ROOT)))\n img = tf.get_thumbnail({\n 'size': (64, 64),\n 'crop': 'auto',\n 'upscale': True,\n }).url\n else:\n try:\n img = static('filem/img/mimetypes/%s.png' % (content_type.replace('/', '-'),))\n except:\n img = static('filem/img/mimetypes/unknown.png')\n return {\n 'name': path.name,\n 'is_dir': path.is_dir(),\n 'is_file': path.is_file(),\n 'is_symlink': path.is_symlink(),\n # 'size': st.st_size,\n # 'mode': st.st_mode,\n # 'mtime': st.st_mtime,\n # 'ctime': st.st_ctime,\n 'content-type': content_type,\n # 'encoding': encoding,\n 'thumb': img,\n }\n","repo_name":"funkybob/django-filem","sub_path":"filem/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2343,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"27"} +{"seq_id":"39309608144","text":"# -*- encoding: utf-8 -*-\n\"\"\"\nPython Application\nLicence: Trisim Technologies Pvt. Ltd.\n\"\"\"\n\nimport csv, json, os, glob, subprocess\nfrom shutil import make_archive\n\nfrom flask import Blueprint, request, abort, jsonify, make_response, send_file\n\nfrom solver_api.auth.views import token_required\nimport convert_user_to_run_info\nimport BlenderDEM_Functions as BF\n\nsolver = Blueprint(\n 'solver',\n __name__,\n url_prefix='/api/solver/'\n )\n\ndef setup():\n pass\n\ndef validate_solver_start_data(data):\n case_id = data.get('case_id', None)\n #print(\"validate_solver_start_data: \", data)\n if not case_id or not isinstance(case_id, str):\n return (False, 'case_id not passed')\n\n if data.get('ProjectID'):\n # solver adds this key\n return (False, 'Unexpected input ProjectID')\n\n formulation = data.get('formulation', None)\n if not formulation or not isinstance(formulation, list):\n return (False, 'formulation not passed')\n\n setting = data.get('simulation_settings', None)\n if not setting or not isinstance(setting, dict):\n return (False, 'setting not passed')\n\n if data.get('blender', None) or data.get('blender_minimum_dimension'):\n # Solver populates these fields. They should not be passed by module2\n return (False, 'Unexpected input blender or blender_minimum_dimension')\n\n blender = data.get('blender_data', None)\n if not blender or not isinstance(blender, dict):\n return (False, 'blender_data not passed')\n\n blender_name = blender.get('name', None)\n if not blender_name or not isinstance(blender_name, str):\n return (False, 'blender name not passed')\n\n blender_minimum_dimension = blender.get('E', None)\n if not blender_minimum_dimension:\n return (False, 'blender key E not passed')\n\n return (True, \"\")\n\ndef prepare_run_dict(data):\n blender = data.get('blender_data', None)\n if not blender or not isinstance(blender, dict):\n msg = 'Invalid input'\n abort(make_response(msg, 400))\n\n data['ProjectID'] = data['case_id']\n data['blender'] = blender['name']\n data['blender_minimum_dimension'] = blender['E']\n return data\n\ndef is_result_ready(case_id):\n path = solver_get_result_path(case_id)\n ready = False\n if os.path.exists(path) and os.path.isfile(path):\n ready = True\n return ready\n\ndef get_run_dir(case_id):\n cwd = os.path.dirname(os.path.abspath(__file__))\n run_dir = os.path.split(cwd)\n #print(\"get run dir\", cwd, run_dir)\n #return os.path.join(cwd, '..', 'runs', case_id)\n return os.path.join(run_dir[0], 'runs', case_id)\n\ndef is_case_running(case_id):\n run_dir = get_run_dir(case_id)\n print(\"run_dir\", run_dir)\n lock_file_path = os.path.join(run_dir, str(case_id)+'.rocky.lock')\n running = False\n print(\"Status\", case_id, running, lock_file_path)\n if os.path.exists(lock_file_path) and os.path.isfile(lock_file_path):\n running = True\n return running\n\ndef get_case_status(case_id):\n case_status = 'not run'\n running_status = is_case_running(case_id)\n if running_status:\n case_status = 'running'\n elif not running_status:\n run_dir = get_run_dir(case_id)\n log_file_path = os.path.join(run_dir, str(case_id)+'.rocky.files', 'simulation', 'rocky_simulation.rocky20.log')\n if os.path.exists(log_file_path) and os.path.isfile(log_file_path):\n i = 1\n # reading log's last 10 line's\n for line in reversed(list(open(log_file_path))):\n line_ = line.rstrip()\n if line_ == 'Simulation done.':\n case_status = 'complete'\n else:\n pass # case_status = 'crash'\n if i == 10:\n break\n i+=1\n additional = BF.DEM_check_status(case_id)\n return {'status':case_status,'additional':additional}\n\ndef solver_get_result_path(case_id='CASE_ID-0'):\n return os.path.join(get_run_dir(case_id), 'blender_outputs', 't_RSD_LMI_1_species_1.csv')\n\ndef solver_get_result_dir(case_id='CASE_ID-0'):\n return os.path.join(get_run_dir(case_id), 'blender_outputs')\n\n# Any File to base64 string\ndef b64encode(file_name):\n import base64\n # noinspection PyBroadException\n try:\n with open(file_name, \"rb\") as file_handler:\n encoded_string = base64.b64encode(file_handler.read()).decode(\"utf-8\")\n except Exception as e:\n print(e)\n return encoded_string\n# ======================== Solver ===============================\n\n@solver.route('/status', methods=['GET'])\ndef solver_all_status():\n return '

Welcome to solver_all_status

'\n\n@solver.route('/start', methods=['POST'])\ndef solver_start():\n data = request.get_json()\n #print(\"solver_start\", data)\n if not data or \\\n not isinstance(data, dict):\n msg = 'Invalid input'\n abort(make_response(msg, 400))\n\n #doe_solver_args - collect all run_info JSONs and send to solver API\n doe_solver_args = {}\n doe_solver_args['doe_runs'] = []\n\n #Collect all DOE runs data. Single run is also treated as DOE run with single run inside\n doe_runs = data['doe_runs']\n for srun in doe_runs:\n (validated, msg) = validate_solver_start_data(srun)\n if not validated:\n abort(make_response(msg, 400))\n\n srun = prepare_run_dict(srun)\n cwd = os.path.dirname(os.path.abspath(__file__))\n path = os.path.join(cwd, '..', 'run_info.json')\n with open(path) as run_info:\n run_info_ = json.load(run_info)\n Data_runinfo = convert_user_to_run_info.main(run_info_, srun)\n doe_solver_args['doe_runs'].append(Data_runinfo)\n\n \n \"\"\"\n (validated, msg) = validate_solver_start_data(data)\n if not validated:\n abort(make_response(msg, 400))\n\n data = prepare_run_dict(data)\n cwd = os.path.dirname(os.path.abspath(__file__))\n path = os.path.join(cwd, '..', 'run_info.json')\n with open(path) as run_info:\n run_info_ = json.load(run_info)\n Data_runinfo = convert_user_to_run_info.main(run_info_, data)\n\n data = json.dumps(Data_runinfo)\n \"\"\"\n #print(\"doe_solver_args\", doe_solver_args)\n data = json.dumps(doe_solver_args)\n p = subprocess.Popen([\"_env/Scripts/python.exe\", \"Blender_execution_default_results.py\", data], stdin=None, stdout=None, shell=False) #,env={\"PATH\": \"/_env\"}, cwd = None)#, creationflags = subprocess.CREATE_NEW_CONSOLE) #env={\"PATH\": \"/usr/bin\"})\n \n \"\"\"\n #Run DEM\n BF.DEM_Run(data)\n\n #Post processing\n BF.DEM_postprocess_eulerian_RSD_LMI_1(data)\n BF.DEM_postprocess_eulerian_RSD_LMI_2(data)\n BF.eqbm_results1(data)\n \n BF.Extract_collision_frequancy(data)\n BF.Extract_Images(data)\n BF.animation(data)\n \"\"\"\n print(\"Blender_execution_default_results is launched as subprocess\")\n return jsonify(success=True)\n\n@solver.route('/doestart', methods=['POST'])\ndef doe_solver_start():\n data = request.get_json()\n if not data or \\\n not isinstance(data, dict):\n msg = 'Invalid input'\n abort(make_response(msg, 400))\n\n doe_runs = data['doe_runs']\n\n for srun in doe_runs:\n (validated, msg) = validate_solver_start_data(srun)\n if not validated:\n abort(make_response(msg, 400))\n\n srun = prepare_run_dict(srun)\n cwd = os.path.dirname(os.path.abspath(__file__))\n path = os.path.join(cwd, '..', 'run_info.json')\n with open(path) as run_info:\n run_info_ = json.load(run_info)\n data = convert_user_to_run_info.main(run_info_, srun)\n \n #print(\"Running doe run: \", srun)\n \n #Run DEM\n BF.DEM_Run(data)\n\n #Post processing\n BF.DEM_postprocess_eulerian_RSD_LMI_1(data)\n BF.DEM_postprocess_eulerian_RSD_LMI_2(data)\n BF.eqbm_results1(data)\n \n BF.Extract_collision_frequancy(data)\n BF.Extract_Images(data)\n BF.animation(data)\n \n\n return jsonify(success=True)\n\n@solver.route('/stop', methods=['POST'])\ndef solver_stop():\n return '

Welcome to solver_stop

'\n\n@solver.route('/status/', methods=['GET'])\ndef solver_status(case_id):\n resp = get_case_status(case_id)\n return jsonify(message=resp['status'],additional=resp['additional'], success=True)\n\n@solver.route('/result/prepare/')\ndef solver_prepare_result(case_id):\n if is_result_ready(case_id):\n return jsonify(success=True)\n\n data = request.get_json()\n if not data or not isinstance(data, dict):\n msg = 'Invalid input'\n abort(make_response(msg, 400))\n\n (validated, msg) = validate_solver_start_data(data)\n if not validated:\n abort(make_response(msg, 400))\n\n data = prepare_run_dict(data)\n\n cwd = os.path.dirname(os.path.abspath(__file__))\n path = os.path.join(cwd, '..', 'run_info.json')\n with open(path) as run_info:\n run_info_ = json.load(run_info)\n data = convert_user_to_run_info.main(run_info_, data)\n\n BF.DEM_postprocess_eulerian_RSD_LMI_1(data)\n BF.DEM_postprocess_eulerian_RSD_LMI_2(data)\n\n BF.Extract_collision_frequancy(data)\n BF.Extract_Images(data)\n BF.animation(data)\n\n return jsonify(success=True)\n\n\n@solver.route('/result/preparemore/', methods=['POST'])\ndef solver_prepare_result_more(case_id):\n data = request.get_json()\n if not data or not isinstance(data, dict):\n msg = 'Invalid input'\n abort(make_response(msg, 400))\n\n (validated, msg) = validate_solver_start_data(data)\n if not validated:\n abort(make_response(msg, 400))\n\n data = prepare_run_dict(data)\n\n cwd = os.path.dirname(os.path.abspath(__file__))\n path = os.path.join(cwd, '..', 'run_info.json')\n with open(path) as run_info:\n run_info_ = json.load(run_info)\n \n Data_runinfo = convert_user_to_run_info.main(run_info_, data)\n data = json.dumps(Data_runinfo)\n p = subprocess.Popen([\"_env/Scripts/python.exe\", \"Blender_execution_additional_results.py\", data], stdin=None, stdout=None, shell=False)\n\n \"\"\"\n BF.DEM_postprocess_eulerian_RSD_LMI_local(data)\n BF.DEM_postprocess_dump_particle_data_per_rev(data)\n BF.Extract_time_surfaceVelocity_collision(data)\n\n BF.eqbm_results2(data)\n \"\"\"\n print(\"DEM additional results processing is launched\")\n\n return jsonify(success=True)\n\n@solver.route('/result/get/')\ndef solver_get_result(case_id):\n if not is_result_ready(case_id):\n msg = 'Result is not ready. Please prepare result.'\n abort(make_response(msg, 400))\n\n data = request.get_json()\n species_id = data[\"species_id\"]\n if not data or not isinstance(data, dict):\n msg = 'Invalid input'\n abort(make_response(msg, 400))\n\n if species_id == 'all_materials':\n csv_arr = [x for x in os.listdir(solver_get_result_dir(case_id)) if x.startswith(\"t_RSD_LMI_1_species_\")]\n species_ids = [item.split('.')[0][-1] for item in csv_arr]\n else:\n species_ids = [species_id]\n\n rsd_trace,lmi_trace = [],[]\n for species_id in species_ids:\n #Sample file name to construct - t_RSD_LMI_1_species_1.csv\n path = os.path.join(solver_get_result_dir(case_id), 't_RSD_LMI_1_species_' + species_id + '.csv')\n time_list1,rsd_list1,lmi_list1 = [],[],[]\n with open(path) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n line_count = 0\n for row in csv_reader:\n if line_count == 0:\n line_count += 1\n else:\n time_list1.append(row[0])\n rsd_list1.append(row[1])\n lmi_list1.append(row[2])\n line_count += 1\n\n path = os.path.join(solver_get_result_dir(case_id), 't_RSD_LMI_2_species_' + species_id + '.csv')\n time_list2,rsd_list2,lmi_list2,bin_cols,bin_time,bin_list = [],[],[],[],[],{}\n bin_counter = 1\n if os.path.exists(path) and os.path.isfile(path):\n with open(path) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n line_count = 0\n for row in csv_reader:\n if line_count == 0:\n line_count += 1\n for i, col in enumerate(row):\n if 'bin' in col:\n bin_cols.append(i)\n bin_num = 'bin' + str(bin_counter)\n x = col.split(\"n\")\n y = float(x[1]) + 1\n z = str(y)\n z= z.split(\".\")\n bin_counter += 1\n #print(z[0])\n #bin_num = str(z[0])\n bin_list[bin_num] = []\n else:\n time_list2.append(row[0])\n rsd_list2.append(row[1])\n lmi_list2.append(row[2])\n line_count += 1\n bin_counter = 1\n bin_time.append(row[0])\n for i in bin_cols:\n bin_num = 'bin' + str(bin_counter)\n x = col.split(\"n\")\n y = float(x[1]) + 1\n z = str(y)\n z= z.split(\".\")\n bin_counter += 1\n #print(z[0])\n #bin_num = str(z[0])\n bin_list[bin_num].append(row[i])\n\n rsd_trace.append({'x':time_list1,'y':rsd_list1,'mode': 'lines','name': 'species_' + species_id + '-Mode 1',})\n rsd_trace.append({'x':time_list2,'y':rsd_list2,'mode': 'lines','name': 'species_' + species_id + '-Mode 2',})\n lmi_trace.append({'x': time_list1, 'y': lmi_list1, 'mode': 'lines', 'name': 'species_' + species_id + '-Mode 1', })\n lmi_trace.append({'x': time_list2, 'y': lmi_list2, 'mode': 'lines', 'name': 'species_' + species_id + '-Mode 2', })\n\n data = {'rsd_trace':rsd_trace,'lmi_trace':lmi_trace,'bin_list': bin_list,'bin_time': bin_time,}\n return jsonify(data)\n\n\n@solver.route('/result/getavgresults/')\ndef solver_get_avg_result(case_id):\n \"\"\"if not is_result_ready(case_id):\n msg = 'Result is not ready. Please prepare result.'\n abort(make_response(msg, 400))\"\"\"\n\n data = request.get_json()\n if not data or not isinstance(data, dict):\n msg = 'Invalid input'\n abort(make_response(msg, 400))\n\n path = os.path.join(solver_get_result_dir(case_id), 'equilibrium_values.json')\n rsd1_data = []\n \n with open(path) as json_file:\n avgresult = json.load(json_file)\n search_key = 'RSD1'\n res = [val for key, val in avgresult.items() if search_key in key]\n\n #print(\"Avg result data: \", res)\n return jsonify(res)\n\n\n\nclass CsvToJsonConverter(object):\n def __init__(self, csv_file, filter_callback):\n self._csv_file = csv_file\n self._filter_callback = filter_callback\n\n def Convert(self):\n result = dict()\n with open(self._csv_file) as csv_file:\n reader = csv.DictReader(csv_file, delimiter=',')\n for row in reader:\n for k,v in row.items():\n if not self._filter_callback(k, v):\n continue\n if not result.get(k):\n result[k] = list()\n result[k].append(v)\n return result\n\nclass RunOutput(object):\n BIN = 'bin'\n\n def __init__(self, runs_dir, case_id):\n self._case_id = case_id\n self._runs_dir = runs_dir\n self._run_result_path = os.path.join(self._runs_dir, self._case_id)\n self._output_path = os.path.join(self._runs_dir, self._case_id,\n 'blender_outputs')\n self._mp4_path = os.path.join(self._output_path, 'out_video.mp4')\n\n def Zip(self):\n base_name = self._output_path\n zip_format = 'zip'\n root_dir = self._run_result_path\n base_dir = self._output_path #We want to ZIP only blender_outputs.\n return make_archive(base_name, zip_format, root_dir, \"blender_outputs\")\n\n def AnimationMp4(self):\n return self._mp4_path\n\n def _CsvToJson(self, csv_file):\n def filter_callback(key, value):\n if not key.startswith(RunOutput.BIN):\n return False\n try:\n vf = float(value)\n except ValueError as e:\n return False\n return True\n\n converter = CsvToJsonConverter(csv_file, filter_callback)\n json_result = converter.Convert()\n\n result = list()\n for key, value in json_result.items():\n if not isinstance(value, list):\n raise ValueError('Fatal Error - Parsing failed')\n if len(value) <= 0:\n continue\n try:\n ks = key[len(RunOutput.BIN):]\n kv = int(float(ks))\n bin_dict = {\n 'bin': kv,\n 'mass_fractions': value\n }\n result.append(bin_dict)\n except Exception as e:\n raise ValueError('Unexpected column name %s' % (key))\n return result\n\n def _CsvFilePath(self):\n return os.path.join(self._output_path, 't_RSD_LMI_2.csv')\n\n def _HasCsvOutput(self, file_path):\n if not os.path.isfile(file_path):\n return False\n return True\n\n def HasCsvOutput(self):\n return self._HasCsvOutput(self._CsvFilePath())\n\n def MassFractionData(self):\n csv_file = self._CsvFilePath()\n if not self._HasCsvOutput(csv_file):\n msg = 'Blender output is not ready'\n raise ValueError(msg)\n result = {\n 'time': 'time_list',\n 'mass_fraction_data': self._CsvToJson(csv_file),\n }\n return result\n\n@solver.route('/saor_start', methods=['POST'])\ndef solver_saor_start():\n saor_args = request.get_json()\n if not saor_args or \\\n not isinstance(saor_args, dict):\n msg = 'Invalid input'\n abort(make_response(msg, 400))\n\n print(\"SAOR Rocky saor_start\")\n print(saor_args)\n\n data = json.dumps(saor_args)\n p = subprocess.Popen([\"_env/Scripts/python.exe\", \"Blender_saor.py\", data], stdin=None, stdout=None, shell=False)\n\n #fixme - Add validation of input data\n #BF.saor(data)\n\n return jsonify(success=True)\n\ndef solver_get_saor_result_dir(case_id='CASE_ID-0'):\n return os.path.join(get_run_dir(case_id), 'outputs')\n\ndef solver_get_saor_result_path(case_id='CASE_ID-0'):\n return os.path.join(get_run_dir(case_id), 'outputs', 'saor.json')\n\n@solver.route('/saor_status/', methods=['GET'])\ndef saor_status(case_id):\n status = get_saor_case_status(case_id)\n return jsonify(message=status, success=True)\n\ndef get_saor_case_status(case_id):\n case_status = 'not run'\n running_status = is_saor_case_running(case_id)\n if running_status:\n case_status = 'running'\n \n ready = is_saor_result_ready(case_id)\n if ready:\n case_status = 'complete'\n\n #print(\"Case status: \" + case_status)\n return case_status\n\ndef is_saor_result_ready(case_id):\n path = solver_get_saor_result_path(case_id)\n path_img = solver_if_images_are_ready(case_id)\n ready = False\n if os.path.exists(path) and os.path.isfile(path):\n if os.path.exists(path_img) and os.path.isfile(path_img):\n ready = True\n return ready\n\ndef solver_if_images_are_ready(case_id='CASE_ID-0'):\n return os.path.join(get_run_dir(case_id), 'outputs', 'SAoR_0.9.png')\n\ndef is_saor_case_running(case_id):\n saor_img_file = os.path.join(get_run_dir(case_id), 'outputs', 'SAoR_*.*.png')\n #print(saor_img_file)\n running = False\n file_list = glob.glob(saor_img_file)\n #print(file_list)\n \n if len(file_list) > 0:\n running = True\n\n #print(\"SAOR status: \" + str(running))\n return running\n\n@solver.route('/saor_result/get/')\ndef solver_get_saor_result(case_id):\n if not is_saor_result_ready(case_id):\n msg = 'Result is not ready. Please prepare result.'\n abort(make_response(msg, 400))\n\n path = os.path.join(solver_get_saor_result_dir(case_id), 'saor.json')\n result = {}\n \n with open(path) as json_file:\n result = json.load(json_file)\n #print(\"************************ read result\")\n #json_data = jsonify(result)\n #print(\"************************ read result 2\")\n resp = {'data': result, 'message': 'SAoR Data is read successfully',}\n \n return jsonify(resp)\n \n@solver.route('/result/get_zip/')\ndef get_zipped_result(case_id):\n try:\n cwd = os.path.dirname(os.path.abspath(__file__))\n runs_dir = os.path.join(cwd, '..', 'runs')\n if not runs_dir or not os.path.isdir(runs_dir):\n msg = 'Output for Run %s is not available' % (case_id)\n raise ValueError(msg)\n\n output = RunOutput(runs_dir, case_id)\n zip_file = output.Zip()\n if not os.path.isfile(zip_file):\n msg = 'Fatal error: failed to create zip'\n raise ValueError(msg)\n\n return send_file(zip_file, mimetype='zip', attachment_filename='%s' % os.path.basename(zip_file), as_attachment=True)\n except Exception as e:\n msg = 'Get Zipped Result failed with error %s' % (e)\n print(msg)\n abort(make_response(msg, 400))\n\n@solver.route('/result/get_animation/')\ndef get_animation_result(case_id):\n try:\n cwd = os.path.dirname(os.path.abspath(__file__))\n runs_dir = os.path.join(cwd, '..', 'runs')\n if not runs_dir or not os.path.isdir(runs_dir):\n msg = 'Output for Run %s is not available' % (case_id)\n raise ValueError(msg)\n\n output = RunOutput(runs_dir, case_id)\n mp4_file = output.AnimationMp4()\n if not os.path.isfile(mp4_file):\n msg = 'Fatal error: failed to create animation mp4'\n raise ValueError(msg)\n\n return jsonify(b64encode(mp4_file))\n except Exception as e:\n msg = 'API get animation result failed with error %s' % (e)\n print(msg)\n abort(make_response(msg, 400))\n\n@solver.route('/result/get_mass_fraction_data/')\ndef get_mass_fraction_data(case_id):\n try:\n cwd = os.path.dirname(os.path.abspath(__file__))\n runs_dir = os.path.join(cwd, '..', 'runs')\n if not runs_dir or not os.path.isdir(runs_dir):\n msg = 'Output for Run %s is not available' % (case_id)\n raise ValueError(msg)\n\n output = RunOutput(runs_dir, case_id)\n if not output.HasCsvOutput():\n msg = 'Run %s output not present' % (case_id)\n raise ValueError(msg)\n result_dict = output.MassFractionData()\n return jsonify(result_dict)\n except Exception as e:\n msg = 'Get mass fraction data failed with error %s' % (e)\n abort(make_response(msg, 400))\n\n\n# =============================================================================\n# __name__\n# =============================================================================\n\nif __name__ == '__main__':\n setup()\n","repo_name":"abmachinthosh/anagha","sub_path":"rocky_automation/solver_api/case_management_api.py","file_name":"case_management_api.py","file_ext":"py","file_size_in_byte":23426,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"7898827851","text":"import random\nimport time\n\nimport kinbaku as kn\nfrom tqdm import tqdm\n\n# number of nodes and edges\nN = 2000\nM = 100 * N\n\n# create graph\nG = kn.Graph(\"test.db\", flag=\"n\")\nfor _ in tqdm(range(M), desc=\"inserting edges\"):\n u = str(random.randint(0, N-1))\n v = str(random.randint(0, N-1))\n G.add_edge(u, v)\ndel G\n\n# adjacency matrix of the whole graph\nstart = time.time()\nG = kn.Graph(\"test.db\", flag=\"r\")\nA, index_to_node = G.adjacency_matrix()\nprint(time.time() - start)\n\n# adjacency matrix of a subgraph\nstart = time.time()\nG = kn.Graph(\"test.db\", flag=\"r\")\nA, index_to_node = G.subgraph([str(i) for i in range(100)])\nprint(time.time() - start)\n","repo_name":"kerighan/kinbaku","sub_path":"examples/adjacency_matrix.py","file_name":"adjacency_matrix.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"27"} +{"seq_id":"36629902689","text":"from term import Term\n\n\nclass Polinom:\n def __init__(self, terms):\n self._terms = {}\n\n for term in terms:\n self.add_term(term)\n\n def add_term(self, term):\n if term.power not in self._terms:\n self._terms[term.power] = term\n else:\n self._terms[term.power] += term\n\n def __str__(self):\n sorted_terms = []\n\n for term_power in sorted(self._terms.keys(), reverse=True):\n if self._terms[term_power] != Term.constant(0):\n sorted_terms.append(str(self._terms[term_power]))\n\n return ' + '.join(sorted_terms)\n\n def derivative(self):\n terms_derivatives = [\n term.derived for term in self._terms.values()\n ]\n\n return Polinom(terms_derivatives)\n\n @classmethod\n def parse_from_string(cls, s):\n unparsed_terms = s.split('+')\n\n terms = [\n Term.parse_term(t) for t in unparsed_terms\n ]\n\n return cls(terms)\n","repo_name":"Anton-Naumov/Programming-101-with-Python","sub_path":"week04/derivates/polinom.py","file_name":"polinom.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"5614391177","text":"# program flow\n# 1- ask user : manage or make files first?\n# 2-manage :\n# call manage and sort files to default folders\n# 2-make files:\n# choose the files he wants and make him choose type of files to be put in it\nimport os\nimport shutil\nimport pathlib\n\nVideos = ['.mp4', '.mpg', '.mp2', '.mpeg', '.mpe', '.mpv', '.mp4', '.m4p', '.m4v', '.avi', '.wmv', '.mov', '.wmv',\n '.flv', '.swf', '.webm']\nAudio = ['.wav', '.wave', '.aiff', '.pcm', '.au', '.flac', '.m4a', '.caf', '.wma', '.wmv', '.mp3', '.ogg', '.3gp',\n '.aac', '.mp3']\nphotos = ['.tif', '.jpg', '.png', '.gif']\ncompressed = ['.rar', '.zip']\nDocuments = ['.pdf', '.doc', '.txt', '.docx', '.odt', '.html', '.xlsx', '.pptx']\ncDir = os.getcwd() # gets the current folder\n\n# ------------------------------------------------------------------------\nextension = \"\"\n\n\ndef check_audio(audio):\n for item in Audio:\n for item1 in audio:\n if item == item1:\n return item1\n else:\n continue\n\n\ndef check_video(video):\n for item in Videos:\n for item1 in video:\n if item == item1:\n return item1\n else:\n continue\n\n\ndef check_compressed(compressedfile):\n for item in compressed:\n for item1 in compressedfile:\n if item == item1:\n return item1\n else:\n continue\n\n\ndef check_document(document):\n for item in Documents:\n for item1 in document:\n if item == item1:\n return item1\n else:\n continue\n\n\ndef check_photo(photo):\n for item in photos:\n for item1 in photo:\n if item == item1:\n return item1\n else:\n continue\n\n\ndef emptyFolders(dir):\n empty_dirs = []\n for i in dir:\n if os.path.exists(i) and os.path.isdir(i):\n if not os.listdir(i):\n print(\"Directory {} is empty\".format(i))\n empty_dirs.append(i)\n if len(empty_dirs) == 0:\n None\n else:\n return empty_dirs\n\n\ndef manage_empty(emptyFolders):\n if emptyFolders is None:\n return 0\n delete = input(\"Enter 1 to delete all empty folders or 2 to select what you want or any other key to keep them\")\n if delete.casefold() == \"1\":\n for i in range(len(emptyFolders)):\n try:\n os.removedirs(emptyFolders[i])\n except FileNotFoundError:\n None\n elif delete.casefold() == \"2\":\n deleted_folders = []\n deleted_folders = input(\"Type name of folders you want to remove from these:\" + \" \".join(emptyFolders)).split()\n for folder in range(len(emptyFolders)):\n os.removedirs(deleted_folders[folder])\n\n\ndef manage():\n autoFolders = ['Audio', 'Videos', 'Photos', 'Compressed', 'others', 'Documents']\n for root, subDirs, files in os.walk(cDir):\n deletedFolders = emptyFolders(subDirs)\n manage_empty(deletedFolders)\n for file in files:\n oldPath = os.path.join(root, file)\n extenstion = pathlib.Path(oldPath).suffix\n try:\n if extenstion in Audio:\n if not os.path.isdir('Audio'):\n os.makedirs('Audio')\n shutil.move(oldPath, cDir + \"\\\\Audio\")\n # this to check background images\n if extenstion in Videos:\n if not os.path.isdir('Videos'):\n os.makedirs('Videos')\n shutil.move(oldPath, cDir + \"\\\\Videos\")\n # this to check compreessed files\n if extenstion in compressed:\n if not os.path.isdir('Compressed'):\n os.makedirs('Compressed')\n shutil.move(oldPath, cDir + \"\\\\Compressed\")\n if extenstion in photos:\n if not os.path.isdir('Photos'):\n os.makedirs('Photos')\n shutil.move(oldPath, str(cDir) + \"\\\\photos\")\n if extenstion in Documents:\n if not os.path.isdir('Documents'):\n os.makedirs('Documents')\n shutil.move(oldPath, cDir + \"\\\\Documents\")\n else:\n continue\n\n except:\n None\n\n\nnewFolders = []\n\naudioFormats = ''\nvideoFormats = ''\ncompressedFormats = ''\nphotoFormats = ''\ndocumentFormats = ''\n\n# path of formats by user\n\naudiopath = ''\nphotopath = ''\nvideopath = ''\ncompressedPath = ''\ndocumentpath = ''\n\n\ndef sort_compressed():\n print(\n \"Enter formats for types of compressed files you want to put it like these ---> Formats:\" + \" \".join(\n compressed))\n print(\"put it like : .zip,.rar\")\n global compressedFormats\n compressedFormats = list(input().split(','))\n if check_compressed(compressedFormats) in compressed:\n compressedFolder = input(\"Type foldername from these to put these extensions in folder:\" + \" \".join(newFolders))\n\n if compressedFolder in newFolders:\n global compressedPath\n compressedPath = cDir + '\\\\{}'.format(compressedFolder)\n return compressedPath\n\n\ndef sort_photos():\n print(\"Enter formats for types of audio files you want to put it like these ---> Formats:\" + \" \".join(photos))\n print(\"put it like : .jpg,.png\")\n global photoFormats\n photoFormats = list(input().split(','))\n if check_photo(photoFormats) in photos:\n photoFolder = input(\"Type foldername from these to put these extensions in folder:\" + \" \".join(newFolders))\n if photoFolder in newFolders:\n global photopath\n photoPath = cDir + '\\\\{}'.format(photoFolder)\n return photoPath\n\n\ndef sort_videos():\n print(\"Enter formats for types of video files you want to put it like these ---> Formats:\" + \" \".join(Videos))\n print(\"put it like : .mp4,.mkv\")\n global videoFormats\n videoFormats = list(input().split(','))\n if check_video(videoFormats) in Videos:\n videoFolder = input(\"Type foldername from these to put these extensions in folder:\" + \" \".join(newFolders))\n\n if videoFolder in newFolders:\n global videopath\n videoPath = cDir + '\\\\{}'.format(videoFolder)\n return videoPath\n\n\ndef sort_audio():\n print(\"Enter formats for types of audio files you want to put it like these ---> Formats:\" + \" \".join(Audio))\n print(\"put it like : .mp3,.3gp\")\n global audioFormats\n audioFormats = list(input().split(','))\n if check_audio(audioFormats) in Audio:\n audioFolder = input(\n \"Type foldername from these to put these extensions in folder--\" + \" \".join(newFolders)).strip()\n\n if audioFolder in newFolders:\n global audiopath\n audiopath = cDir + '\\\\{}'.format(audioFolder)\n return audiopath\n\n\ndef sort_documents():\n print(\n \"Enter formats for types of documents files you want to put it like these ---> Formats:\" + \" \".join(Documents))\n print(\"put it like : .pdf,.XLSX,.docx\")\n global documentFormats\n documentFormats = list(input().split(','))\n if check_document(documentFormats) in Documents:\n documentFolder = input(\"Type foldername from these to put these extensions in folder:\" + \" \".join(newFolders))\n\n if documentFolder in newFolders:\n global documentpath\n documentpath = cDir + \"\\\\{}\".format(documentFolder)\n return documentpath\n\n\ndef sort_extensions():\n print(\"choose what you want to arrange:\")\n your_choice = input(\"do you want to arrange audio files?---> answer yes or no: \")\n if your_choice.casefold() == \"yes\":\n global audiopath\n audiopath = sort_audio()\n elif your_choice.casefold() == \"no\":\n print(\"ok\")\n else:\n print(\"wrong entry\")\n # ---------------\n your_choice = input(\"do you want to arrange compressed files?---> answer yes or no: \")\n if your_choice.casefold() == \"yes\":\n global compressedPath\n compressedPath = sort_compressed()\n elif your_choice.casefold() == \"no\":\n print(\"ok\")\n else:\n print(\"wrong entry\")\n # -----------\n your_choice = input(\"do you want to arrange photos files?---> answer yes or no: \")\n if your_choice.casefold() == \"yes\":\n global photopath\n photopath = sort_photos()\n elif your_choice.casefold() == \"no\":\n print(\"ok\")\n else:\n print(\"wrong entry\")\n # ---------\n your_choice = input(\"do you want to arrange video files?---> answer yes or no: \")\n if your_choice.casefold() == \"yes\":\n global videopath\n videopath = sort_videos()\n elif your_choice.casefold() == \"no\":\n print(\"ok\")\n else:\n print(\"wrong entry\")\n # ------\n your_choice = input(\"do you want to arrange document files?---> answer yes or no: \")\n if your_choice.casefold() == \"yes\":\n global documentpath\n documentpath = sort_documents()\n elif your_choice.casefold() == \"no\":\n print(\"ok\")\n else:\n print(\"wrong entry\")\n\n\ndef askForFolders():\n global oldPath, newFolders\n add = True\n newFolders = input(\"what folders do you want to create? \").split()\n while add is True:\n ask = input(\"do you want to add something else?\")\n if ask.casefold() == \"no\":\n add = False\n print(\"ok\")\n elif ask.casefold() == \"yes\":\n newFolders += input(\"type another name here : \").split()\n else:\n print(\"you entered invalid entry\")\n # ----------------------------------------------\n # function to find the files and put it to folders\n for i in range(len(newFolders)):\n try:\n os.makedirs('{}'.format(newFolders[i]))\n except FileExistsError:\n print(\"some files already exists\")\n continue\n\n print(\"these are your folders choose type of files to be put in these folders: \" + \" \".join(newFolders))\n # this fn choose what type of files and gets their folder address\n\n sort_extensions()\n # this loop goes for the main folder then files and other subfolders in it\n deletedFolders = []\n ignore_folder = []\n exclude_folder = []\n for root, subDirs, files in os.walk(cDir):\n deletedFolders = emptyFolders(subDirs)\n manage_empty(deletedFolders)\n dirname = os.path.basename(root)\n if dirname in ignore_folder:\n if root == cDir:\n None\n else:\n continue\n else:\n None\n try:\n for file in files:\n oldPath = os.path.join(root, file)\n extenstion = pathlib.Path(oldPath).suffix\n if extenstion in audioFormats:\n shutil.move(oldPath, audiopath)\n elif extenstion in videoFormats:\n shutil.move(oldPath, os.path.join(videopath, file))\n elif extenstion in compressedFormats:\n shutil.move(oldPath, compressedPath)\n elif extenstion in photoFormats:\n shutil.move(oldPath, photopath)\n elif extenstion in documentFormats:\n shutil.move(oldPath, documentpath)\n else:\n None\n except:\n if oldPath == audiopath:\n print(\"File is aleardy moved to audiopath\")\n elif oldPath == videopath:\n print(\"File is aleardy moved to video path\")\n elif oldPath == compressedPath:\n print(\"File is aleardy moved to compressed path\")\n elif oldPath == photopath:\n print(\"File is aleardy moved to photo path\")\n elif oldPath == documentpath:\n print(\"File is aleardy moved to document path\")\n\n ask_subfolder = input(\"Do you want to arrange these folders?: \" + \" \".join(subDirs))\n if ask_subfolder.casefold() == \"yes\":\n exclude_folder = input(\"do you want to exclude anyfolders from them?\\n\")\n if exclude_folder.casefold() == 'yes':\n exclude_folder = input(\"Type them here : \").split()\n ignore_folder.extend(exclude_folder)\n\n elif ask_subfolder.casefold() == \"no\":\n ignore_folder.extend(subDirs)\n else:\n print(\"type yes or no please\")\n ask_subfolder = input()\n\n\n# ask for how many folders and put it in list\nprint(\"Hi, This is Files Manager program if you want auto manage\\n \"\n \"type '1' or type '2' for modefied Managment\\n \"\n \"You can create folders then choose any extenstion you want\"\n \"?\")\n\n\ndef askFirst():\n choose = input()\n if choose.__contains__(\"1\"):\n manage()\n elif choose.__contains__(\"2\"):\n\n askForFolders()\n else:\n print(\"you entered wrong entry,try again \")\n askFirst()\n\n\n# program begins\naskFirst()","repo_name":"AhmedMohamed365/FilesOrganizer","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":13060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"74181150471","text":"\"\"\"\nA circular racetrack has N runners on it, all running at distinct\nconstant speeds in the same direction. There is only one spot along\nthe track (say, the starting line) where any runner is allowed to\npass any other runner; if two runners \"collide\" at any other point\nalong the circle, then the race is over and everyone stops.\nFor which N is it possible for N runners to run this way indefinitely?\n\nThe original problem asked for N = 10.\nThis script encodes the problem in the Z3 Theorem Prover.\nIt only works for up to N = 4, where it successfully finds a set of\npossible runners; for a larger number, it thinks for a while, and\neventually says \"unknown\".\n\nExample solution obtained by Z3 when N = 4:\n speed0 = 6,\n speed1 = 8,\n speed2 = 9,\n speed3 = 12\n\nNotes on problem encoding:\n We observe that for any two runners at speeds r, s (in laps / hour),\n they meet every 1 / |s - r| hours. This means that r / |s - r| (the\n distance traveled in laps) must be a positive integer. We can also\n drop the absolute value and simply state that there is some integer n\n (possibly negative) such that r = (s - r) * n.\n This condition, for every pair of speeds, is sufficient to imply the\n constraints in the original problem, as long as we additionally state\n that all speeds are positive integers (in particular, not zero).\n (That they are nonzero rules out n = 0 and also means they must be\n distinct, from r = (s - r) * n.)\n\nProof that there is a solution for all N:\n We proceed by induction.\n Suppose that there is a solution with runner speeds r_1, r_2, ..., r_N,\n and assume WLOG that r_i are all positive integers. Let\n R = LCM(r_1, r_2, ..., r_N)\n and consider the set of N+1 positive integers\n R, R + r_1, R + r_2, ..., R + r_n.\n We claim that this set of runner speeds works. First, consider the\n pair of speeds (R + r_i) and (R + r_j): their difference is (r_i - r_j).\n This divides r_i and r_j by inductive hypothesis, and it divides R\n because it divides r_i (since R is the LCM), so it divides (R + r_i)\n and (R + r_j). Second, consider the pair of speeds R and (R + r_i).\n The difference is r_i, which divides R since it is the LCM,\n so it divides R and R + r_i. This completes the inductive step.\n Finally, for the base case we take a single runner with speed 1, and\n this completes the proof.\n\"\"\"\n\nimport z3\n\n\"\"\"\nSolve the runner problem for N runners.\n\"\"\"\ndef solve_runner_problem(N):\n solver = z3.Solver()\n\n # Assign a positive integer speed to each runner.\n # This is WLOG since the ratio of any two runners' speeds is rational.\n speeds = [z3.Int(\"speed\" + str(i)) for i in range(N)]\n for s in speeds:\n solver.add(s > 0)\n\n # For any pair of speeds r and s, r / (s - r) is an integer.\n for i in range(N):\n for j in range(i+1, N):\n n_i_j = z3.FreshInt()\n solver.add(speeds[i] == (speeds[j] - speeds[i]) * n_i_j)\n\n # Print and then solve the constraints.\n print(f\"Constraints: {solver.assertions()}\")\n result = str(solver.check())\n print(f\"Result: {result}\")\n if result == 'sat':\n print(f\"Model: {solver.model()}\")\n\n\"\"\"\nWhen run from the command line: try with 1, 2, 3, 4, and 5 runners.\n\"\"\"\nfor N in range(1, 6):\n print(f\"========== Number of runners: {N} ==========\")\n solve_runner_problem(N)\n","repo_name":"cdstanford/curiosities","sub_path":"n-runners/n-runners.py","file_name":"n-runners.py","file_ext":"py","file_size_in_byte":3386,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"28785241484","text":"from __future__ import annotations\n\nimport uno\nfrom com.sun.star.sheet import XSolver\n\nfrom ooodev.exceptions import ex\nfrom ooodev.office.calc import Calc\nfrom ooodev.utils.lo import Lo\nfrom ooodev.utils.props import Props\n\n\nclass Solver2:\n @staticmethod\n def main(verbose: bool = False) -> None:\n with Lo.Loader(connector=Lo.ConnectPipe(), opt=Lo.Options(verbose=verbose)) as loader:\n doc = Calc.create_doc(loader)\n sheet = Calc.get_sheet(doc=doc)\n\n # specify the variable cells\n x_pos = Calc.get_cell_address(sheet=sheet, cell_name=\"B1\") # X\n y_pos = Calc.get_cell_address(sheet=sheet, cell_name=\"B2\") # Y\n vars = (x_pos, y_pos)\n\n # specify profit equation\n Calc.set_val(value=\"=B1+B2\", sheet=sheet, cell_name=\"B3\")\n objective = Calc.get_cell_address(sheet, \"B3\")\n\n # set up equation formula without inequality (only one needed)\n # x^2 + y^2\n Calc.set_val(value=\"=B1*B1 + B2*B2\", sheet=sheet, cell_name=\"B4\")\n\n # create three constraints (using the 3 variables)\n\n sc1 = Calc.make_constraint(num=1, op=\">=\", sheet=sheet, cell_name=\"B4\")\n # x^2 + y^2 >= 1\n sc2 = Calc.make_constraint(num=2, op=\"<=\", sheet=sheet, cell_name=\"B4\")\n # x^2 + y^2 <= 2\n\n constraints = (sc1, sc2)\n\n # initialize the nonlinear solver (SCO)\n try:\n solver = Lo.create_instance_mcf(XSolver, \"com.sun.star.comp.Calc.NLPSolver.SCOSolverImpl\", raise_err=True)\n except ex.MissingInterfaceError:\n print('Solver not available on this system: \"com.sun.star.comp.Calc.NLPSolver.SCOSolverImpl\"')\n Lo.close_doc(doc)\n return\n solver.Document = doc\n solver.Objective = objective\n solver.Variables = vars\n solver.Constraints = constraints\n solver.Maximize = True\n\n Props.show_obj_props(\"Solver\", solver)\n # switch off nonlinear dialog about current progress\n # and restrict the search to the top-right quadrant of the graph\n Props.set(solver, EnhancedSolverStatus=False, AssumeNonNegative=True)\n\n # execute the solver\n solver.solve()\n Calc.solver_report(solver)\n Lo.close_doc(doc)\n","repo_name":"Amourspirit/python-ooouno-ex","sub_path":"ex/auto/calc/odev_non_linear_solve/solver2.py","file_name":"solver2.py","file_ext":"py","file_size_in_byte":2395,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"27"} +{"seq_id":"72773179273","text":"# Code for proving Robin's theorum for a suitable range of natural numbers \n\nfrom math import log\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef factorize(n, primes):\n factors = []\n for p in primes:\n if p*p > n: break\n i = 0\n while n % p == 0:\n n //= p\n i+=1\n if i > 0:\n factors.append((p, i));\n if n > 1: factors.append((n, 1))\n \n return factors\n\n\ndef divisors(factors):\n div = [1]\n for (p, r) in factors:\n div = [d * p**e for d in div for e in range(r + 1)]\n return div\n\n\ndef list_to_number(n):\n numbers = set(range(n, 1, -1))\n primes = []\n while numbers:\n p = numbers.pop()\n primes.append(p)\n numbers.difference_update(set(range(p*2, n+1, p)))\n return primes\n\ngamma = float(0.57721566490153286060651209008240243104215933593992)\n\nsecVal = list(); sig = list()\npwData = float(pow(1e+1, gamma))\n\nn = 2\nnumList = list()\nwhile n < 10000:\n secVal.append(pwData*n*log(log(n)))\n sig.append(sum(divisors(factorize(n, list_to_number(n)))))\n n = n + 1\n numList.append(n)\n\nplt.plot(numList, secVal, label=\"e^y*n*lnln(n)\")\nplt.plot(numList, sig, label=\"Sigma(n)\")\nplt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,\n ncol=2, mode=\"expand\", borderaxespad=0.)\n\n\nplt.savefig('fig.png')\n\n\n","repo_name":"Ambuj-UF/Machine-Learning-Theorems","sub_path":"robin.py","file_name":"robin.py","file_ext":"py","file_size_in_byte":1335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"36111348790","text":"import time\r\nimport random\r\nimport keyboard\r\nimport socket\r\n\r\n\r\nclass Car:\r\n def __init__(self,width,height):\r\n self.width=width\r\n self.height=height\r\n self.ppl=[]\r\n self.line=False;\r\n self.another_car=False\r\n self.anoth_car_w=[((self.width/2)-5)-1,((self.width/2)-5)-2,((self.width/2)-5)-3,((self.width/2)-5)-4,((self.width/2)-5)-5,((self.width/2)-5)-6,((self.width/2)-5)-7,((self.width/2)-5)-8,((self.width/2)-5)-9,((self.width/2)-5)-10,((self.width/2)-5)-11]\r\n self.anoth_car_h=[-2,-1,0,1]\r\n self.car_w=[((self.width/2)-5)-1,((self.width/2)-5)-2,((self.width/2)-5)-3,((self.width/2)-5)-4,((self.width/2)-5)-5,((self.width/2)-5)-6,((self.width/2)-5)-7,((self.width/2)-5)-8,((self.width/2)-5)-9,((self.width/2)-5)-10,((self.width/2)-5)-11]\r\n self.car_h=[self.height-1,self.height-2,self.height-3]\r\n self.location=\"left\"\r\n self.speed=50\r\n\r\n def AnotherCar(self):\r\n poss=random.randint(0,6)\r\n if poss==3:\r\n if self.another_car==False:\r\n if self.location==\"left\":\r\n self.anoth_car_w=[((self.width/2)-5)+19,((self.width/2)-5)+18,((self.width/2)-5)+17,((self.width/2)-5)+16,((self.width/2)-5)+15,((self.width/2)-5)+14,((self.width/2)-5)+13,((self.width/2)-5)+12,((self.width/2)-5)+11,((self.width/2)-5)+10,((self.width/2)-5)+9]\r\n\r\n if self.location==\"right\":\r\n self.anoth_car_w=[((self.width/2)-5)-1,((self.width/2)-5)-2,((self.width/2)-5)-3,((self.width/2)-5)-4,((self.width/2)-5)-5,((self.width/2)-5)-6,((self.width/2)-5)-7,((self.width/2)-5)-8,((self.width/2)-5)-9,((self.width/2)-5)-10,((self.width/2)-5)-11]\r\n \r\n self.another_car=True\r\n\r\n def Another_car_movment(self):\r\n for i in range(0,len(self.anoth_car_h)):\r\n self.anoth_car_h[i]+=1\r\n if self.anoth_car_h[0]>self.height:\r\n self.another_car=False\r\n self.anoth_car_h=[-2,-1,0,1] \r\n\r\n def input(self):\r\n if keyboard.is_pressed('a'):\r\n if self.location==\"right\":\r\n for i in range(0,len(self.car_w)):\r\n self.car_w[i]-=20\r\n self.location=\"left\"\r\n\r\n if keyboard.is_pressed('d'):\r\n if self.location==\"left\":\r\n for i in range(0,len(self.car_w)):\r\n self.car_w[i]+=20\r\n self.location=\"right\"\r\n\r\n def velocity(self):\r\n if keyboard.is_pressed('w'):\r\n self.speed+=5\r\n\r\n if keyboard.is_pressed('s'):\r\n if self.speed>5:\r\n self.speed-=5\r\n\r\n def people(self):\r\n possibality=random.randint(1, 10)\r\n if possibality >4 and possibality <10 and len(self.ppl)= 1:\n try:\n new_subnet_zone = new_subnet_zones.pop()\n new_subnet = self._CreateSubnetInZone(new_subnet_zone)\n return new_subnet\n except:\n logging.info('Unable to create subnet in zone %s', new_subnet_zone)\n raise Exception('Unable to create subnet in any availability zones')\n\n def _CreateDbSubnetGroup(self, subnets):\n \"\"\"Creates a new db subnet group.\n\n Args:\n subnets: a list of strings.\n The db subnet group will consit of all subnets in this list.\n \"\"\"\n db_subnet_group_name = 'pkb-db-subnet-group-{0}'.format(FLAGS.run_uri)\n\n create_db_subnet_group_cmd = util.AWS_PREFIX + (\n ['rds',\n 'create-db-subnet-group',\n '--db-subnet-group-name', db_subnet_group_name,\n '--db-subnet-group-description', 'pkb_subnet_group_for_db',\n '--region', self.region,\n '--subnet-ids'] + [subnet.id for subnet in subnets] +\n ['--tags'] + util.MakeFormattedDefaultTags())\n\n vm_util.IssueCommand(create_db_subnet_group_cmd)\n\n # save for cleanup\n self.db_subnet_group_name = db_subnet_group_name\n self.security_group_id = (self.client_vm.network.regional_network.\n vpc.default_security_group_id)\n\n def _SetupNetworking(self):\n \"\"\"Sets up the networking required for the RDS database.\"\"\"\n if self.spec.engine in _RDS_ENGINES:\n self.subnets_used_by_db.append(self.client_vm.network.subnet)\n self._CreateSubnetInAdditionalZone()\n elif self.spec.engine in _AURORA_ENGINES:\n self._CreateSubnetInAllZonesAssumeClientZoneExists()\n else:\n raise Exception('Unknown how to create network for {0}'.format(\n self.spec.engine))\n\n self._CreateDbSubnetGroup(self.subnets_used_by_db)\n\n open_port_cmd = util.AWS_PREFIX + [\n 'ec2',\n 'authorize-security-group-ingress',\n '--group-id', self.security_group_id,\n '--source-group', self.security_group_id,\n '--protocol', 'tcp',\n '--port={0}'.format(DEFAULT_POSTGRES_PORT),\n '--region', self.region]\n stdout, stderr, _ = vm_util.IssueCommand(open_port_cmd)\n logging.info('Granted DB port ingress, stdout is:\\n%s\\nstderr is:\\n%s',\n stdout, stderr)\n\n def _TeardownNetworking(self):\n \"\"\"Tears down all network resources that were created for the database.\"\"\"\n if hasattr(self, 'db_subnet_group_name'):\n delete_db_subnet_group_cmd = util.AWS_PREFIX + [\n 'rds',\n 'delete-db-subnet-group',\n '--db-subnet-group-name', self.db_subnet_group_name,\n '--region', self.region]\n vm_util.IssueCommand(delete_db_subnet_group_cmd)\n\n for subnet_for_db in self.subnets_owned_by_db:\n subnet_for_db.Delete()\n\n def _Create(self):\n \"\"\"Creates the AWS RDS instance.\n\n Raises:\n Exception: if unknown how to create self.spec.engine.\n\n \"\"\"\n if self.spec.engine in _RDS_ENGINES:\n\n instance_identifier = self.instance_id\n self.all_instance_ids.append(instance_identifier)\n cmd = util.AWS_PREFIX + [\n 'rds',\n 'create-db-instance',\n '--db-instance-identifier=%s' % instance_identifier,\n '--engine=%s' % self.spec.engine,\n '--master-username=%s' % self.spec.database_username,\n '--master-user-password=%s' % self.spec.database_password,\n '--allocated-storage=%s' % self.spec.disk_spec.disk_size,\n '--storage-type=%s' % self.spec.disk_spec.disk_type,\n '--db-instance-class=%s' % self.spec.vm_spec.machine_type,\n '--no-auto-minor-version-upgrade',\n '--region=%s' % self.region,\n '--engine-version=%s' % self.spec.engine_version,\n '--db-subnet-group-name=%s' % self.db_subnet_group_name,\n '--vpc-security-group-ids=%s' % self.security_group_id,\n '--availability-zone=%s' % self.spec.vm_spec.zone,\n '--tags'] + util.MakeFormattedDefaultTags()\n\n if self.spec.disk_spec.disk_type == aws_disk.IO1:\n cmd.append('--iops=%s' % self.spec.disk_spec.iops)\n # TODO(ferneyhough): add backup_enabled and backup_window\n\n vm_util.IssueCommand(cmd)\n\n elif self.spec.engine in _AURORA_ENGINES:\n zones_needed_for_high_availability = len(self.zones) > 1\n if zones_needed_for_high_availability != self.spec.high_availability:\n raise Exception('When managed_db_high_availability is true, multiple '\n 'zones must be specified. When '\n 'managed_db_high_availability is false, one zone '\n 'should be specified. '\n 'managed_db_high_availability: {0} '\n 'zone count: {1} '.format(\n zones_needed_for_high_availability,\n len(self.zones)))\n\n cluster_identifier = 'pkb-db-cluster-' + FLAGS.run_uri\n # Create the cluster.\n cmd = util.AWS_PREFIX + [\n 'rds', 'create-db-cluster',\n '--db-cluster-identifier=%s' % cluster_identifier,\n '--engine=%s' % self.spec.engine,\n '--engine-version=%s' % self.spec.engine_version,\n '--master-username=%s' % self.spec.database_username,\n '--master-user-password=%s' % self.spec.database_password,\n '--region=%s' % self.region,\n '--db-subnet-group-name=%s' % self.db_subnet_group_name,\n '--vpc-security-group-ids=%s' % self.security_group_id,\n '--availability-zones=%s' % self.spec.zones[0],\n '--tags'] + util.MakeFormattedDefaultTags()\n\n self.cluster_id = cluster_identifier\n vm_util.IssueCommand(cmd)\n\n for zone in self.zones:\n\n # The first instance is assumed to be writer -\n # and so use the instance_id for that id.\n if zone == self.zones[0]:\n instance_identifier = self.instance_id\n else:\n instance_identifier = self.instance_id + '-' + zone\n\n self.all_instance_ids.append(instance_identifier)\n\n cmd = util.AWS_PREFIX + [\n 'rds',\n 'create-db-instance',\n '--db-instance-identifier=%s' % instance_identifier,\n '--db-cluster-identifier=%s' % cluster_identifier,\n '--engine=%s' % self.spec.engine,\n '--engine-version=%s' % self.spec.engine_version,\n '--no-auto-minor-version-upgrade',\n '--db-instance-class=%s' % self.spec.vm_spec.machine_type,\n '--region=%s' % self.region,\n '--availability-zone=%s' % zone,\n '--tags'] + util.MakeFormattedDefaultTags()\n vm_util.IssueCommand(cmd)\n\n else:\n raise Exception('Unknown how to create AWS data base engine {0}'.format(\n self.spec.engine))\n\n def _Delete(self):\n \"\"\"Deletes the underlying resource.\n\n Implementations of this method should be idempotent since it may\n be called multiple times, even if the resource has already been\n deleted.\n \"\"\"\n for current_instance_id in self.all_instance_ids:\n cmd = util.AWS_PREFIX + [\n 'rds',\n 'delete-db-instance',\n '--db-instance-identifier=%s' % current_instance_id,\n '--skip-final-snapshot',\n '--region', self.region,\n ]\n vm_util.IssueCommand(cmd)\n\n if self.cluster_id is not None:\n cmd = util.AWS_PREFIX + [\n 'rds',\n 'delete-db-cluster',\n '--db-cluster-identifier=%s' % self.cluster_id,\n '--skip-final-snapshot',\n '--region', self.region,\n ]\n vm_util.IssueCommand(cmd)\n\n def _Exists(self):\n \"\"\"Returns true if the underlying resource exists.\n\n Supplying this method is optional. If it is not implemented then the\n default is to assume success when _Create and _Delete do not raise\n exceptions.\n \"\"\"\n for current_instance_id in self.all_instance_ids:\n cmd = util.AWS_PREFIX + [\n 'rds',\n 'describe-db-instances',\n '--db-instance-identifier=%s' % current_instance_id,\n '--region=%s' % self.region\n ]\n _, _, retcode = vm_util.IssueCommand(cmd)\n if retcode != 0:\n return False\n\n return True\n\n def _ParseEndpointFromInstance(self, describe_instance_json):\n \"\"\"Parses the json output from the CLI and returns the endpoint.\n\n Args:\n describe_instance_json: output in json format from calling\n 'aws rds describe-db-instances'\n\n Returns:\n endpoint of the server as a string\n \"\"\"\n return describe_instance_json['DBInstances'][0]['Endpoint']['Address']\n\n def _ParsePortFromInstance(self, describe_instance_json):\n \"\"\"Parses the json output from the CLI and returns the port.\n\n Args:\n describe_instance_json: output in json format from calling\n 'aws rds describe-db-instances'\n\n Returns:\n port on which the server is listening, as an int\n \"\"\"\n if describe_instance_json is None:\n return None\n return int(describe_instance_json['DBInstances'][0]['Endpoint']['Port'])\n\n def _ParseEndpointFromCluster(self, describe_cluster_json):\n \"\"\"Parses the json output from the CLI and returns the endpoint.\n\n Args:\n describe_cluster_json: output in json format from calling\n 'aws rds describe-db-clusters'\n\n Returns:\n endpoint of the server as a string\n \"\"\"\n return describe_cluster_json['DBClusters'][0]['Endpoint']\n\n def _ParsePortFromCluster(self, describe_cluster_json):\n \"\"\"Parses the json output from the CLI and returns the port.\n\n Args:\n describe_cluster_json: output in json format from calling\n 'aws rds describe-db-instances'\n\n Returns:\n port on which the server is listening, as an int\n \"\"\"\n if describe_cluster_json is None:\n return None\n return int(describe_cluster_json['DBClusters'][0]['Port'])\n\n def _SavePrimaryAndSecondaryZones(self, describe_instance_json):\n \"\"\"Saves the primary, and secondary (only if HA) zone of the server.\n\n Args:\n describe_instance_json: output in json format from calling\n 'aws rds describe-db-instances'\n \"\"\"\n\n if self.spec.engine in _AURORA_ENGINES:\n self.primary_zone = self.zones[0]\n if len(self.zones) > 1:\n self.secondary_zone = ','.join(self.zones[1:])\n else:\n db_instance = describe_instance_json['DBInstances'][0]\n self.primary_zone = (\n db_instance['AvailabilityZone'])\n if self.spec.high_availability:\n if 'SecondaryAvailabilityZone' in db_instance:\n self.secondary_zone = db_instance['SecondaryAvailabilityZone']\n else:\n # the secondary DB for RDS is in the second subnet.\n self.secondary_zone = self.subnets_used_by_db[1].zone\n\n def _IsReady(self, timeout=IS_READY_TIMEOUT):\n \"\"\"Return true if the underlying resource is ready.\n\n This method will query all of the instance every 5 seconds until\n its instance state is 'available', or until a timeout occurs.\n\n Args:\n timeout: timeout in seconds\n\n Returns:\n True if the resource was ready in time, False if the wait timed out\n or an Exception occurred.\n \"\"\"\n\n if not self.all_instance_ids:\n return False\n\n for instance_id in self.all_instance_ids:\n if not self._IsInstanceReady(instance_id, timeout):\n return False\n\n return True\n\n def _PostCreate(self):\n \"\"\"Perform general post create operations on the cluster.\n\n Raises:\n Exception: If could not ready the instance after modification to\n multi-az.\n \"\"\"\n\n need_ha_modification = self.spec.engine in _RDS_ENGINES\n\n if self.spec.high_availability and need_ha_modification:\n # When extending the database to be multi-az, the second region\n # is picked by where the second subnet has been created.\n cmd = util.AWS_PREFIX + [\n 'rds',\n 'modify-db-instance',\n '--db-instance-identifier=%s' % self.instance_id,\n '--multi-az',\n '--apply-immediately',\n '--region=%s' % self.region\n ]\n vm_util.IssueCommand(cmd)\n\n if not self._IsInstanceReady(self.instance_id, timeout=IS_READY_TIMEOUT):\n raise Exception('Instance could not be set to ready after '\n 'modification for high availability')\n\n json_output = self._DescribeInstance(self.instance_id)\n self._SavePrimaryAndSecondaryZones(json_output)\n if self.cluster_id:\n self._GetPortsForClusterInstance(self.cluster_id)\n else:\n self._GetPortsForWriterInstance(self.all_instance_ids[0])\n\n def _IsInstanceReady(self, instance_id, timeout=IS_READY_TIMEOUT):\n \"\"\"Return true if the instance is ready.\n\n This method will query the instance every 5 seconds until\n its instance state is 'available', or until a timeout occurs.\n\n Args:\n instance_id: string of the instance to check is ready\n timeout: timeout in seconds\n\n Returns:\n True if the resource was ready in time, False if the wait timed out\n or an Exception occurred.\n \"\"\"\n start_time = datetime.datetime.now()\n\n while True:\n if (datetime.datetime.now() - start_time).seconds >= timeout:\n logging.exception('Timeout waiting for sql instance to be ready')\n return False\n json_output = self._DescribeInstance(instance_id)\n try:\n state = json_output['DBInstances'][0]['DBInstanceStatus']\n pending_values = json_output['DBInstances'][0]['PendingModifiedValues']\n logging.info('Instance state: %s', state)\n if pending_values:\n logging.info('Pending values: %s', (str(pending_values)))\n\n if state == 'available' and not pending_values:\n break\n except:\n logging.exception('Error attempting to read stdout. Creation failure.')\n return False\n time.sleep(5)\n\n return True\n\n def _DescribeInstance(self, instance_id):\n cmd = util.AWS_PREFIX + [\n 'rds',\n 'describe-db-instances',\n '--db-instance-identifier=%s' % instance_id,\n '--region=%s' % self.region\n ]\n stdout, _, _ = vm_util.IssueCommand(cmd, suppress_warning=True)\n json_output = json.loads(stdout)\n return json_output\n\n def _DescribeCluster(self, cluster_id):\n cmd = util.AWS_PREFIX + [\n 'rds',\n 'describe-db-clusters',\n '--db-cluster-identifier=%s' % cluster_id,\n '--region=%s' % self.region\n ]\n stdout, _, _ = vm_util.IssueCommand(cmd, suppress_warning=True)\n json_output = json.loads(stdout)\n return json_output\n\n def _GetPortsForWriterInstance(self, instance_id):\n \"\"\"Assigns the ports and endpoints from the instance_id to self.\n\n These will be used to communicate with the data base.\n \"\"\"\n json_output = self._DescribeInstance(instance_id)\n self.endpoint = self._ParseEndpointFromInstance(json_output)\n self.port = self._ParsePortFromInstance(json_output)\n\n def _GetPortsForClusterInstance(self, cluster_id):\n \"\"\"Assigns the ports and endpoints from the cluster_id to self.\n\n These will be used to communicate with the data base.\n \"\"\"\n json_output = self._DescribeCluster(cluster_id)\n self.endpoint = self._ParseEndpointFromCluster(json_output)\n self.port = self._ParsePortFromCluster(json_output)\n\n def _AssertClientAndDbInSameRegion(self):\n \"\"\"Asserts that the client vm is in the same region requested by the server.\n\n Raises:\n AwsManagedRelationalDbCrossRegionException: if the client vm is in a\n different region that is requested by the server.\n \"\"\"\n if self.client_vm.region != self.region:\n raise AwsManagedRelationalDbCrossRegionException((\n 'client_vm and managed_relational_db server '\n 'must be in the same region'))\n\n def _CreateDependencies(self):\n \"\"\"Method that will be called once before _CreateResource() is called.\n\n Supplying this method is optional. It is intended to allow additional\n flexibility in creating resource dependencies separately from _Create().\n \"\"\"\n self._AssertClientAndDbInSameRegion()\n self._SetupNetworking()\n\n def _DeleteDependencies(self):\n \"\"\"Method that will be called once after _DeleteResource() is called.\n\n Supplying this method is optional. It is intended to allow additional\n flexibility in deleting resource dependencies separately from _Delete().\n \"\"\"\n self._TeardownNetworking()\n\n def _FailoverHA(self):\n \"\"\"Fail over from master to replica.\"\"\"\n\n if self.spec.engine in _RDS_ENGINES:\n cmd = util.AWS_PREFIX + [\n 'rds',\n 'reboot-db-instance',\n '--db-instance-identifier=%s' % self.instance_id,\n '--force-failover',\n '--region=%s' % self.region\n ]\n vm_util.IssueCommand(cmd)\n elif self.spec.engine in _AURORA_ENGINES:\n new_primary_id = self.all_instance_ids[1]\n cmd = util.AWS_PREFIX + [\n 'rds',\n 'failover-db-cluster',\n '--db-cluster-identifier=%s' % self.cluster_id,\n '--target-db-instance-identifier=%s' % new_primary_id,\n '--region=%s' % self.region\n ]\n vm_util.IssueCommand(cmd)\n else:\n raise Exception('Unknown how to failover {0}'.format(\n self.spec.engine))\n","repo_name":"chameleonTK/cloud-recommendation-kubernetes","sub_path":"PerfKitBenchmarker/perfkitbenchmarker/providers/aws/aws_managed_relational_db.py","file_name":"aws_managed_relational_db.py","file_ext":"py","file_size_in_byte":24062,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"27"} +{"seq_id":"22162622888","text":"import os\nimport mysql.connector\nfrom mysql.connector import Error\nimport logging\nfrom LoggerManager import NewLogger\nimport os\nimport json\nimport csv\n\n\nclass DatabaseManager:\n \n def __init__(self, host_name, username, password, db, logger_file_name=''):\n self.conn = mysql.connector.connect(host=host_name, user=username, passwd=password, database=db, allow_local_infile=True)\n self.database = db\n self.logger_file_name = logger_file_name\n self.database_logger = NewLogger('DatabaseManager', self.logger_file_name)\n self.cursor = self.conn.cursor()\n\n def select_data(self, sql_string):\n logging.info('Select data run on ' + self.database + ' database')\n table_data = self.cursor.execute(sql_string)\n table_data = self.cursor.fetchall()\n return print(table_data)\n\n def create_table(self,sql_string):\n try:\n logging.info('Create new table in ' + self.database + ' database')\n self.cursor.execute(sql_string)\n self.conn.commit()\n print('Table created successfully.')\n except mysql.connector.Error as ex:\n logging.error('create table on: ' + self.database + ' for query: '+str(ex))\n finally:\n if (self.conn.is_connected()):\n self.cursor.close()\n self.conn.close()\n print(\"MySQL connection is closed\")\n\n def insert_sql_data(self,sql_string):\n try:\n logging.info('Insert sql data run on: ' + self.database + ' database')\n self.cursor.execute(sql_string)\n self.conn.commit()\n print('New row added successfully.')\n except mysql.connector.Error as ex:\n logging.error('Insert sql data run on: ' + self.database + ' for query: '+str(ex))\n finally:\n if (self.conn.is_connected()):\n self.cursor.close()\n self.conn.close()\n print(\"MySQL connection is closed\")\n \n def modify_sql_data(self,SqlString):\n try:\n logging.info('Modify sql data run on ' + self.database + ' database')\n self.cursor.execute(SqlString)\n self.conn.commit()\n print('Modify data successfully.')\n except mysql.connector.Error as ex:\n logging.error('Modify sql data run on ' + self.database + ' for query: '+str(ex))\n finally:\n if (self.conn.is_connected()):\n self.cursor.close()\n self.conn.close()\n print(\"MySQL connection is closed\")\n\n def delete_sql_data(self,SqlString):\n try:\n logging.info('Delete sql data run on ' + self.database + ' database')\n self.cursor.execute(SqlString)\n self.conn.commit()\n print('Delete data successfully.')\n except mysql.connector.Error as ex:\n logging.error('Delete sql data run on ' + self.database + ' for query: '+str(ex))\n finally:\n if (self.conn.is_connected()):\n self.cursor.close()\n self.conn.close()\n print(\"MySQL connection is closed\")\n\n def export_data(self,SqlString,file_type,table_name):\n try:\n if file_type.casefold() == 'json':\n logging.info('Export table ' + table_name + ' to ' + file_type +' file.')\n self.cursor.execute(SqlString)\n row_headers = [column[0] for column in self.cursor.description]\n data=self.cursor.fetchall()\n json_data = { table_name : []}\n out_file = open(\"employees.json\", \"w\")\n for result in data:\n json_data[table_name].append(dict(zip(row_headers,result)))\n json.dump(json_data, out_file,indent=4, default=str)\n out_file.close()\n print('Table convert into json file successfully.')\n elif file_type.casefold() == 'csv':\n logging.info('Export database ' + self.database + ' to ' + file_type +' file.')\n self.cursor.execute(SqlString)\n data = self.cursor.fetchall()\n column_names = [column[0] for column in self.cursor.description]\n out_file = open('employee.csv', 'w')\n myFile = csv.writer(out_file)\n myFile.writerow(column_names)\n myFile.writerows(data)\n out_file.close()\n print('Table convert into CSV file successfully.')\n except mysql.connector.Error as ex:\n logging.error('Export sql data run on ' + self.database + ' for query: '+str(ex))\n finally:\n if (self.conn.is_connected()):\n self.cursor.close()\n self.conn.close()\n print(\"MySQL connection is closed\")\n\n def import_data(self,SqlString):\n try:\n logging.info('Import data on ' + self.database + ' database')\n self.cursor.execute(SqlString)\n self.conn.commit()\n print('Import data successfully.')\n except mysql.connector.Error as ex:\n logging.error('Import data run on ' + self.database + ' for query: '+str(ex))\n finally:\n if (self.conn.is_connected()):\n self.cursor.close()\n self.conn.close()\n print(\"MySQL connection is closed\")","repo_name":"shivamgupta7/python-program","sub_path":"SQL-Database/DatabaseManager.py","file_name":"DatabaseManager.py","file_ext":"py","file_size_in_byte":5400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"24116122222","text":"import re\nimport tkinter as tk\nimport tkinter.messagebox as msgbox\nimport webbrowser\nfrom urllib import parse\nwindow = tk.Tk()\nwindow.title('哈哈哈哈哈哈')\nwindow.geometry('300x230')\nvar = tk.StringVar()\nzc = tk.Label(window, text='输入视频链接:(Ctrl 和 V 一块按可以粘贴哦!!!)')\nzc.pack()\ne = tk.Entry(window, show=None)\ne.pack()\n#port1 = 'http://www.wmxz.wang/video.php?url='\nport2 = 'http://jx.618ge.com/?url='\nport3 = 'https://www.administratorw.com/admin.php?url='\nport4 = 'http://17kyun.com/api.php?url='\nport1 = 'http://api.bbbbbb.me/jx/?url='\ndef bf1():\n if re.match(r'^https?:/{2}\\w.+$', e.get()):\n ip = e.get()\n ip = parse.quote_plus(ip)\n webbrowser.open(port1 + ip)\n else:\n msgbox.showerror(title='错误', message='视频链接地址无效,请重新输入!')\nb1 = tk.Button(window,text='播放方法1',font=('楷体', 12), fg='red',width=15,height=2,command=bf1)\nb1.pack()\ndef bf2():\n if re.match(r'^https?:/{2}\\w.+$', e.get()):\n ip = e.get()\n ip = parse.quote_plus(ip)\n webbrowser.open(port2 + ip)\n else:\n msgbox.showerror(title='错误', message='视频链接地址无效,请重新输入!')\nb2 = tk.Button(window,text='播放方法2',font=('楷体', 12), fg='Purple',width=15,height=2,command=bf2)\nb2.pack()\ndef bf3():\n if re.match(r'^https?:/{2}\\w.+$', e.get()):\n ip = e.get()\n ip = parse.quote_plus(ip)\n webbrowser.open(port3 + ip)\n else:\n msgbox.showerror(title='错误', message='视频链接地址无效,请重新输入!')\nb3 = tk.Button(window,text='播放方法3',font=('楷体', 12), fg='yellow',width=15,height=2,command=bf3)\nb3.pack()\ndef bf4():\n if re.match(r'^https?:/{2}\\w.+$', e.get()):\n ip = e.get()\n ip = parse.quote_plus(ip)\n webbrowser.open(port4 + ip)\n else:\n msgbox.showerror(title='错误', message='视频链接地址无效,请重新输入!')\nb4 = tk.Button(window,text='播放方法4',font=('楷体', 12), fg='blue',width=15,height=2,command=bf4)\nb4.pack()\n\nwindow.mainloop()\n\n","repo_name":"3167253066/python","sub_path":"python入门/视频破解 包/多通道.py","file_name":"多通道.py","file_ext":"py","file_size_in_byte":2096,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"7906101523","text":"#방 바닥 세로 크기 N, 가로 크기 M\nN, M = map(int, input().split())\nfloor = []\nfor i in range(N):\n floor.append(list(input()))\ncount = 0\n\n#세로 장식 i\nfor i in range(N):\n j = 0\n while j 1:\n new_pos = can_build(highest, c_level, start_pos, friend_index)\n if not new_pos[0]:\n return [True, 15, new_pos[1]]\n else:\n return [False, 15, new_pos[1]]\n\n # Only 1 building that needs to be moved towards\n else:\n direction = get_direction(start_pos, highest[0]) # Move in this direction\n move_pos = new_position(direction, start_pos)\n\n if move_pos not in workerLoc and int(highest[1]) - 1 == c_level:\n return [True, 25, move_pos]\n else:\n return [False, 20, can_build(highest, c_level, start_pos, friend_index)[1]]\n\n else: # Already at the highest level\n new_pos = can_build(highest, c_level, start_pos, friend_index)\n if new_pos[0]:\n return [False, 30, new_pos[1]]\n else:\n return [False, 30, new_pos]\n\n\ndef get_highest():\n \"\"\"\n Get the highest buildings currently on the board\n\n :return: A list containing the highest buildings and their level\n \"\"\"\n highest, build_loc = [], []\n\n for i in range(5):\n for j in range(5):\n if board[i][j] in [\"| L1 |\", \"| L2 |\", \"| L3 |\"]:\n build_loc.append([i, j])\n\n if not build_loc:\n return\n\n for build in build_loc:\n if not max_height(build): # Not a valid building\n level = get_level_from_board(build)\n if not highest: # First building to be checked so automatically the highest\n highest = [build, level]\n else:\n for i in range(len(build_loc) - 1): # Already checked first building\n if build != highest[0] and highest[1] < level: # New building higher level so replace\n highest = [build, level]\n\n elif highest[1] == level and highest[0] != build: # New building same level so append\n highest.append(build)\n return highest\n\n\ndef std_ref(ref):\n \"\"\"\n Take either a worker or building reference and only return the level\n\n :param ref: The reference to the building or worker\n :return: Integer representing the current level\n \"\"\"\n return ref.replace(\"|\", \"\").replace(\" \", \"\").replace(\"L\", \"\").replace(\"C\", \"\").replace(\"D\", \"\")\n\n\ndef best_build(start_pos, reach, friend_index):\n \"\"\"\n Find the best position to be built on\n\n :param start_pos: The current workers position\n :param reach: The building reach of the worker\n :param friend_index: The index of the current workers friend\n :return: The best position to build in\n \"\"\"\n for pos in reach:\n if get_level_from_board(pos) > 0 and not max_height(pos): # First check if a nearby building can be used\n return pos\n\n # Attempt to build towards friend worker\n friend_pos = friend_loc(friend_index)\n\n if friend_loc(friend_index) in reach:\n return friend_pos\n else:\n space_around = get_space_around(start_pos, friend_pos, reach)\n if space_around: # Build near friend\n return space_around\n else: # Cannot build towards other worker so next available space\n return reach[0]\n\n\ndef can_build(highest, c_level, start_pos, friend_index):\n \"\"\"\n Evaluate the current buildings around the worker and return the best position to either climb or build on\n\n :param highest: A list containing the highest buildings\n :param c_level: The current workers level\n :param start_pos: The current workers initial position\n :param friend_index: The index of the workers friend\n :return: A flag (Climb or build) and the new position to perform that action on\n \"\"\"\n reachable = can_reach(start_pos, highest, c_level, \"build\")\n build_same = []\n build_new = []\n\n # Going to climb or build\n for pos in reachable:\n # Know there is a building to check\n pos_level = get_level_from_board(pos)\n if pos_level > 0:\n if pos_level - 1 == c_level: # Building can be climbed\n return False, new_position(get_direction(start_pos, pos), start_pos)\n\n # Opportunity for worker to build on top of another building\n elif pos_level == c_level:\n build_same.append(pos)\n\n # Worker has to build new\n elif pos not in workerLoc:\n build_new.append(pos)\n\n # Shows priority of opportunities\n if build_same: # Building same level so building on it\n return True, build_same[0]\n elif build_new: # No available buildings, so build new one\n return True, best_build(start_pos, can_reach(start_pos, highest, c_level, \"build\"), friend_index)\n else: # No position to build or move to\n return True, get_best(highest, reachable)\n\n\ndef can_reach(start_pos, highest, c_level, movement):\n \"\"\"\n Given a movement type (Climb or build) return a list of all possible positions the given action can be done for\n\n :param start_pos: The workers initial position\n :param highest: The current highest buildings on the board\n :param c_level: The current workers level\n :param movement: A flag representing either Climb (True) or Build (False)\n :return: The current reach of the worker\n \"\"\"\n reach, match = [], []\n # Going through all adjacent spaces\n for op in [\"W\", \"A\", \"S\", \"D\", \"WA\", \"WD\", \"SA\", \"SD\"]:\n pos = new_position(op, start_pos)\n\n # Position in bounds, not occupied by worker and not already realised\n if pos not in workerLoc and not out_bounds(pos) and not max_height(pos) and pos not in reach:\n pos_level = get_level_from_board(pos)\n if pos_level > 0 and movement == \"climb\":\n b_level = get_level_from_board(pos)\n\n if b_level - 1 == c_level or b_level == c_level or b_level < c_level:\n reach.append(pos)\n\n for val in highest:\n if val[0] in reach:\n match.append(val[0])\n\n elif pos_level == 0 and movement == \"move\":\n match.append(pos)\n\n else: # If wanting to build, can build at any level as long as no worker\n match.append(pos)\n if len(match) > 1:\n return match\n else:\n return match[0]\n\n\ndef get_best(highest, reachable):\n \"\"\"\n A last resort to find the best position to move to given access to buildings\n\n :param highest: List of the highest buildings on the board\n :param reachable: Current reach of the selected worker\n :return: Either the best position to move to or nothing\n \"\"\"\n best = []\n\n for pos in reachable:\n pos_reach = len(can_reach(pos, highest, highest[1], \"climb\")) # Each reachable buildings counts as a point\n pos_level = get_level_from_board(pos)\n\n if pos_level > 0: # Being able to climb selected pos adds values\n pos_reach += 1\n\n best.append(pos_reach)\n\n if len(best) > 1:\n return reachable[best.index(max(best))]\n\n\ndef get_space_around(current_pos, friend_pos, reach):\n \"\"\"\n If a building cannot be reached via WASD directions attempt to use WA, WD, SA an SD\n\n :param current_pos: Current position of the worker\n :param friend_pos: Current position of the workers friend\n :param reach: Current move reach of the worker\n :return: The next best position\n \"\"\"\n if current_pos[0] == friend_pos[0] or current_pos[1] == friend_pos[1]: # On same row or in same column\n above_pos = [friend_pos[0] + 1, friend_pos[1]]\n below_pos = [friend_pos[0] - 1, friend_pos[1]]\n\n left_pos = [friend_pos[0], friend_pos[1] + 1]\n right_pos = [friend_pos[0], friend_pos[1] - 1]\n\n else: # Do not share a row or column\n above_pos = [current_pos[1] - 1, current_pos[1] - 1]\n below_pos = [current_pos[1] - 1, current_pos[1] + 1]\n\n left_pos = [current_pos[0] + 1, current_pos[0] - 1]\n right_pos = [current_pos[0] + 1, current_pos[0] + 1]\n\n # Return applicable position, no preference of order\n if above_pos in reach:\n return above_pos\n elif below_pos in reach:\n return below_pos\n elif left_pos in reach:\n return left_pos\n elif right_pos in reach:\n return right_pos\n\n\ndef get_direction(start_pos, target_pos):\n \"\"\"\n Given the starting and target positions get the direction required to move to or towards the target\n\n :param start_pos: The initial position of the worker\n :param target_pos: The desired position of the worker\n :return: A string representing the relevant direction\n \"\"\"\n start_x, start_y = start_pos[0], start_pos[1] # Left/Right\n new_x, new_y = target_pos[0], target_pos[1] # Up/Down\n\n x_change = start_x - new_x\n y_change = start_y - new_y\n\n if x_change == 0 and y_change >= 1:\n return \"A\"\n elif x_change == 0 and y_change <= -1:\n return \"D\"\n elif y_change == 0 and x_change >= 1:\n return \"W\"\n elif y_change == 0 and x_change <= -1:\n return \"S\"\n elif x_change >= 1 and y_change >= 1:\n return \"WA\"\n elif x_change >= 1 and y_change <= -1:\n return \"WD\"\n elif x_change <= -1 and y_change <= -1:\n return \"SD\"\n elif x_change <= -1 and y_change >= 1:\n return \"SA\"\n\n\ndef friend_loc(index):\n \"\"\"\n Give the location of the workers friend\n\n :param index: Current workers index\n :return: The friends location\n \"\"\"\n if index == 0:\n return workerLoc[3]\n else:\n return workerLoc[2]\n","repo_name":"tjl0005/Santorini-Boardgame","sub_path":"Text Version/algorithm/greedy.py","file_name":"greedy.py","file_ext":"py","file_size_in_byte":10783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"18998701281","text":"#!/usr/bin/env python3\n\nimport rospy \nimport numpy as np\nfrom nav_msgs.msg import OccupancyGrid\nfrom robotics_final_project.msg import NodeRow, NodeMatrix\n\nclass Node(object):\n def __init__(self, x: int, y: int):\n self.fcost = 1000\n self.hcost = 1000\n self.gcost = 1000\n self.x = x\n self.y = y\n self.parent = None\n\nclass Pathfinder(object):\n def __init__(self):\n self.current = None\n self.start = None\n self.goal = None\n self.grid = []\n\n self.map = None\n self.width = 0\n self.height = 0\n self.map_initialized = False\n\n rospy.init_node(\"target_path\")\n # /target_nodes is where start and end positions are received\n rospy.Subscriber(\"target_nodes\", NodeMatrix, self.get_target)\n rospy.Subscriber(\"map\", OccupancyGrid, self.get_map)\n # Path calculated and sent to robot_controller\n self.path_pub = rospy.Publisher(\"target_path\", NodeMatrix, queue_size=10)\n\n def get_target(self, data):\n # When a new path request arrives, initialize the starting, goal, and current nodes\n self.start = Node(data.matrix[0].row[0], data.matrix[0].row[1])\n self.start.parent = [self.start.x, self.start.y]\n self.goal = Node(data.matrix[1].row[0], data.matrix[1].row[1])\n self.current = Node(data.matrix[0].row[0], data.matrix[0].row[1])\n self.current.parent = [self.current.x, self.current.y]\n # Make sure that the map is initialized before starting the algorithm\n while not self.map_initialized:\n rospy.sleep(0.1)\n self.a_star()\n\n def downsample_map(self):\n # An attempt to stop the robot from navigating through walls by downsampling\n # the map by a factor of 4. Ultimately seems to be unsuccessful\n new_map_data = np.reshape(self.map_data, (self.width, self.height))\n a = new_map_data[::4, ::4]\n b = new_map_data[1::4, 1::4]\n c = new_map_data[2::4, 2::4]\n d = new_map_data[3::4, 3::4]\n new_map_data = a | b \n new_map_data = new_map_data | c\n new_map_data = new_map_data | d\n self.map_data = new_map_data.flatten()\n self.width = int(self.width / 4)\n self.height = int(self.height / 4)\n\n def pad_map(self):\n # Another attempt to stop the robot from navigating through walls, this time\n # by padding the walls (I think the issue is that paths hug walls)\n new_map_data = np.reshape(self.map_data, (self.width, self.height))\n for i in np.reshape(self.map_data, (self.width, self.height)):\n for j in i:\n if j == 100:\n for k in [0, 1, 2]:\n for h in [0, 1, 2]:\n new_map_data[i + k][j + h] = 100\n new_map_data[i + k][j - h] = 100\n new_map_data[i - k][j + h] = 100\n new_map_data[i - k][j - h] = 100\n self.map_data = new_map_data.flatten()\n\n def get_map(self, data):\n self.map = data\n map_info = self.map.info\n self.map_data = self.map.data\n self.map_resolution = map_info.resolution\n self.width = map_info.width\n self.height = map_info.height\n self.map_origin = map_info.origin\n # Initialize the pathfinding grid with appropriate dimensions\n for i in range(self.width):\n row = []\n for j in range(self.height):\n row.append(Node(i, j))\n self.grid.append(row)\n # Use one of the attempted solutions, neither are great as of right now\n # self.downsample_map()\n self.pad_map()\n self.map_initialized = True\n print(\"Pathfinding: map initialized\")\n\n def get_neighbors(self, current):\n # Get the 8 coordinates surrounding the current cell\n offsets = [-1, 0, 1]\n neighbors = []\n for x_offset in offsets:\n for y_offset in offsets:\n # Ensure that they fall within the bounds of the board and are valid positions\n if (x_offset != y_offset or x_offset != 0) and \\\n (current.x + x_offset < self.width) and \\\n (current.y + y_offset < self.height) and \\\n (current.x + x_offset >= 0) and (current.y + y_offset >= 0) and \\\n (self.map_data[(current.x + x_offset) + (current.y + y_offset)*self.width] == 0):\n neighbors.append([current.x + x_offset, current.y + y_offset])\n return neighbors\n\n def update_gcost(self, node: Node):\n if node.x == self.start.x and node.y == self.start.y:\n return 0\n # If the parent is adjacent, add 10, if diagonal, add 14\n diff = abs(node.parent[0] - node.x) + abs(node.parent[1] - node.y)\n if diff == 2:\n return 14 + self.update_gcost(self.grid[node.parent[0]][node.parent[1]])\n if diff == 1:\n return 10 + self.update_gcost(self.grid[node.parent[0]][node.parent[1]])\n else:\n return 0\n\n def update_hcost(self, node: Node):\n dist_x = abs(node.x - self.goal.x)\n dist_y = abs(node.y - self.goal.y)\n return (14 * min([dist_x, dist_y])) + (10 * abs(dist_x - dist_y))\n \n def a_star(self):\n open_list = []\n closed_list = []\n open_list.append(self.current)\n update_fcost = lambda node : node.gcost + node.hcost\n\n while self.current.x != self.goal.x or self.current.y != self.goal.y:\n lowest = open_list[0]\n for cell in open_list:\n if self.grid[cell.x][cell.y].fcost < self.grid[lowest.x][lowest.y].fcost:\n lowest = cell\n self.current = lowest\n open_list.remove(self.current)\n closed_list.append(self.current)\n\n if self.current.x == self.goal.x and self.current.y == self.goal.y:\n break\n \n ns = self.get_neighbors(self.current)\n # print(\"n neighbors: \", len(ns))\n for nb in ns:\n if self.grid[nb[0]][nb[1]] not in closed_list:\n old_parent = self.grid[nb[0]][nb[1]].parent\n test_node = self.grid[nb[0]][nb[1]]\n test_node.parent = [self.current.x, self.current.y]\n new_gcost = self.update_gcost(test_node)\n\n if new_gcost < self.grid[nb[0]][nb[1]].gcost or \\\n (self.grid[nb[0]][nb[1]] not in open_list):\n self.grid[nb[0]][nb[1]].parent = [self.current.x, self.current.y]\n self.grid[nb[0]][nb[1]].gcost = new_gcost\n self.grid[nb[0]][nb[1]].hcost = \\\n self.update_hcost(self.grid[nb[0]][nb[1]])\n self.grid[nb[0]][nb[1]].fcost = \\\n update_fcost(self.grid[nb[0]][nb[1]])\n\n if self.grid[nb[0]][nb[1]] not in open_list:\n open_list.append(self.grid[nb[0]][nb[1]])\n else:\n self.grid[nb[0]][nb[1]].parent = old_parent\n\n path = []\n pub_path = NodeMatrix()\n while self.current.x != self.start.x or self.current.y != self.start.y:\n path.append(self.current)\n pub_path.matrix.append(NodeRow(row=[self.current.x, self.current.y]))\n self.current = self.grid[self.current.parent[0]][self.current.parent[1]]\n\n self.path_pub.publish(pub_path)\n\n return path\n\n\nif __name__ == '__main__':\n # m = 10\n # n = 12\n # start = Node(1, 1)\n # end = Node(7, 9)\n pf = Pathfinder()\n rospy.spin()\n # path = pf.a_star()\n # for p in path:\n # print(p.x, p.y, p.gcost, p.hcost)\n # # print(path)\n # print(path[-1].x, path[-1].y)","repo_name":"pancakefries/robotics_final_project","sub_path":"scripts/pathfinding.py","file_name":"pathfinding.py","file_ext":"py","file_size_in_byte":7895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"4942232809","text":"from flask import Blueprint, request\nfrom find_restaurant.api.findRestaurant import getGeocodeLocation\nfrom find_restaurant.api.query import editARestaurant, addARestaurant, getARestaurant, getAllRestaurants, deleteRestaurant, check_api_key\nfrom find_restaurant import dbsession\nfrom find_restaurant.member.models import UserPref\nimport json\n\napi = Blueprint('api', __name__)\n\n\n@api.route('/restaurants', methods=['GET', 'POST'])\n@check_api_key\ndef loadRestaurants():\n if request.method == 'POST':\n location_name = request.args.get('location', '')\n latitude, long = getGeocodeLocation(location_name)\n all_restaurants = json.loads(findRestaurants(str(latitude), str(long)))\n for restaurant in all_restaurants:\n addRestaurant(restaurant)\n return \"Added to database.\"\n if request.method == 'GET':\n return getAllRestaurants()\n\n\n@api.route('/restaurant/add', methods=['POST'])\ndef addRestaurant():\n restaurant_info = request.get_json()\n return addARestaurant(restaurant_info)\n\n\n@api.route('/restaurant/', methods=['GET', 'DELETE'])\n@check_api_key\ndef getRestaurant(restaurant_id):\n if request.method == 'GET':\n return getARestaurant(restaurant_id)\n if request.method == 'DELETE':\n return deleteRestaurant(restaurant_id)\n\n@api.route('/restaurant/edit', methods=['PUT'])\n@check_api_key\ndef editRestaurant():\n restaurant_info = request.get_json()\n data = editARestaurant(restaurant_info)\n return data\n","repo_name":"tanjibpa/restful-api-with-flask","sub_path":"find_restaurant/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"24465572238","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('main', '0002_match_test'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='match',\n name='test',\n ),\n ]\n","repo_name":"DSouzaM/League-New-Meta","sub_path":"newmeta/apps/main/migrations/0003_remove_match_test.py","file_name":"0003_remove_match_test.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"27"} +{"seq_id":"40920264391","text":"import my_openalpr as openalpr\nimport cv2\n\nprint(openalpr.__version__)\nprint(hasattr(openalpr, \"recognize\"))\n\nimgs = [\"/polo/sin_fondo_chica.jpg\",\n \"/polo/torcida_recortada.jpg\",\n \"/polo/fondo_blanco.jpg\"]\n\nimage = cv2.imread('D:\\Proyectos\\Blipconnection\\patentes\\ '[:-1]+imgs[0])\n\n# Reconocer la matrícula\nplates = openalpr.recognize(image)\n\n# Imprimir la matrícula reconocida\nprint(plates[0].plate)\n","repo_name":"AnaGarofalo/patentes","sub_path":"prueba_openalr.py","file_name":"prueba_openalr.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"9082885147","text":"\n# coding: utf-8\n\n# In[328]:\n\n\nimport requests\nimport pandas as pd\nimport numpy as np\nimport warnings\nwarnings.filterwarnings('ignore')\nimport matplotlib \nget_ipython().magic(u'matplotlib inline')\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn import linear_model\n\n\n# In[329]:\n\n\nresponse = requests.get(\"https://opensky-network.org/api/states/all\")\n#response.content\n\n\n# In[330]:\n\n\njson_data = response.json()\n#print(json_data)\n\n\n# In[331]:\n\n\na =json_data[\"states\"]\n#a\n\n\n# In[332]:\n\n\ndf = pd.DataFrame(a)\ndf\n\n\n# In[333]:\n\n\n\ndf.rename(columns={0 : \"icao24\",1 : \"callsign\",2 : \"origin_country\",3 : \"time_position\",\n 4 : \"last_contact\",5 : \"longitude\",6 : \"latitude\",7 : \"geo_altitude\",\n 8 : \"on_ground\",9 : \"velocity\",10 : \"heading\",11 : \"vertical_rate\",\n 12 : \"sensors\",13 : \"baro_altitude\",14 : \"squawk\",15 : \"spi\",\n 16 : \"position_source\"}, inplace=True)\n\n\n# In[334]:\n\n\ndf.columns\n\n\n# In[335]:\n\n\n#Keep only the rows with at least 15 non-na values:\ndf = df.dropna(thresh=15)\n\n\n# In[336]:\n\n\ndf.drop(df.columns[[0, 1, 2, 3, 4, 12, 16]], axis=1, inplace=True)\ndf = df.dropna(thresh=10)\ndf\n\n\n# In[337]:\n\n\ndf.spi.unique()\n\n\n# In[338]:\n\n\ny = df.spi\n\n\n# In[339]:\n\n\nfrom sklearn.cross_validation import train_test_split\n\n\n# In[340]:\n\n\nX_train, X_test, y_train, y_test = train_test_split(df, y, \n test_size=0.2, \n random_state=0)\n\n\n# In[341]:\n\n\nprint(X_train.shape, y_train.shape)\n\n\n# In[342]:\n\n\nprint(X_test.shape, y_test.shape)\n\n\n# In[343]:\n\n\nfrom sklearn import tree\nfrom sklearn import svm\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier\n\n\n# In[344]:\n\n\nmodel = LogisticRegression()\n\n\n# In[345]:\n\n\nmodel.fit(X_train, y_train)\n\n\n# In[346]:\n\n\nmodel.score(X_train, y_train)\n\n\n# In[347]:\n\n\n#Predict Output\npredicted= model.predict(X_test)\n\n\n# In[348]:\n\n\npredicted\n\n\n# In[349]:\n\n\n# calculate accuracy\nfrom sklearn import metrics\n\n\n# In[350]:\n\n\nprint(metrics.accuracy_score(y_test, predicted))\n\n\n# In[351]:\n\n\ns = pd.Series(df.spi)\n\n\n# In[352]:\n\n\nfinalCount = s.value_counts()\n\n\n# In[353]:\n\n\nfinalCountDataframe = pd.DataFrame(finalCount)\n\n\n# In[354]:\n\n\nfinalCountDataframe\n\n\n# In[355]:\n\n\nfinalCountDataframe.rename(columns={'spi' : \"count\"}, inplace=True)\n\n\n# In[356]:\n\n\nfinalCountDataframe\n\n\n# In[357]:\n\n\nfinalCountDataframe = pd.DataFrame.transpose(finalCountDataframe)\n\n\n# In[358]:\n\n\nfinalCountDataframe\n\n\n# In[359]:\n\n\nimport matplotlib.pyplot as plt\n\n\n\n# In[360]:\n\n\nFinalBarPlot = finalCountDataframe.plot(kind='bar', title =\"V comp\", figsize=(15, 10), legend=True, fontsize=12)\n\n\n# In[361]:\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n\n# In[366]:\n\n\n\nN = len(df.index)\n\n\n\n# In[367]:\n\n\nN\n\n\n# In[368]:\n\n\nx = df.velocity\ny = df.heading\n\n\n# In[369]:\n\n\ncolors = np.random.rand(N)\narea = np.pi * (15 * np.random.rand(N))**2 # 0 to 15 point radii\n\nplt.scatter(x, y, s=area, c=colors, alpha=0.5)\nplt.show()\n\n","repo_name":"sk2008/Flight-Data-Analysis","sub_path":"PBL-Data-Analysis.py","file_name":"PBL-Data-Analysis.py","file_ext":"py","file_size_in_byte":3054,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"11916466506","text":"# import data from a file or from a website\nimport copy\nimport requests\nimport re\nfrom bs4 import BeautifulSoup\nimport numpy as np\nimport matplotlib.pyplot as plt\n#from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes\nimport matplotlib.colors as colors\nimport matplotlib.cm as cmx\nimport pandas as pd\n#import pdb\n\ndef importData(params):\n queryType = determineIfFileWebpagePandas(params)\n #print(queryType)\n columns = ['origin','year','make','model',\n 'trim','miles','color','price','dist']\n carsDF = pd.DataFrame(columns=columns)\n #return carsDF\n numListings = 501 #anticipate lots of listings\n if queryType == 'files': #load and parse files\n for eachFile in params['files']:\n print(eachFile)\n with open(eachFile, 'rb') as html:\n soup = BeautifulSoup(html)\n # some saved files contain unicode char's the above handles it\n origin = determineOrigin(soup) #works\n #print(origin)\n [numListings,carsDF] = parseData(soup, origin, carsDF) # the carDF is output, and then input again to be appended\n print(len(carsDF))\n #[soup,carsDF] = parseData(soup, origin, carsDF) # for debug\n #return [soup,carsDF]\n return carsDF #the complete carsDF is returned\n \n elif queryType == 'webpage':\n params['years'] = range(params['beginYear'],params['endYear']+1)\n for site in params['sites']: # scan over the sites\n if site =='autotrader':\n for year in params['years']:\n k=0\n while k<=5 and numListings>100*k: #get 100 listings per page - it will find partials\n #print(year)\n #return\n passParams = copy.deepcopy(params)\n passParams['year'] = str(year) #pass only one year at a time\n searchString = createAutotraderRequest(passParams,k)\n #print(searchString)\n \n #user_agent = {'User-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36'}\n user_agent = {'User-agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:41.0) Gecko/20100101 Firefox/41.0'}\n r = requests.get(searchString, headers = user_agent)\n data = r.text\n soup = BeautifulSoup(data)\n origin = determineOrigin(soup) #works\n [numListings, carsDF] = parseData(soup, origin, carsDF)\n #print(len(carsDF))\n k = k+1\n elif site == 'cars':\n for year in params['years']:\n k=0\n while k<=3 and numListings>400: #get 100 listings per page\n #print(year)\n #return\n passParams = copy.deepcopy(params)\n passParams['year'] = str(year) #pass only one year at a time\n return\n searchString = createCarsRequest(passParams,k)\n print(searchString)\n \n user_agent = {'User-agent': 'Mozilla/5.0'}\n r = requests.get(searchString, headers = user_agent)\n data = r.text\n soup = BeautifulSoup(data)\n origin = determineOrigin(soup) #works\n [numListings, carsDF] = parseData(soup, origin, carsDF)\n #print(len(carsDF))\n k = k+1\n carsDF['year']=carsDF['year'].astype('int')\n carsDF['price']=carsDF['price'].astype('int')\n carsDF['miles']=carsDF['miles'].astype('int')\n return carsDF #debug return carsDF\n\n \ndef determineIfFileWebpagePandas(params):\n if 'files' in params.keys():\n return 'files'\n elif 'df' in params.keys():\n return 'df'\n elif 'Make' in params.keys():\n return 'webpage'\n \ndef createAutotraderRequest(params,k):\n makeString = params['Make'].upper()\n modelString = params['Model'].upper()\n endYearString = str(params['year'])\n startYearString = str(params['year'])\n zipString = str(params['zip'])\n firstRecord = str(100*k+1)\n if len(makeString)>6:\n makeCode1 = makeString[0:5].upper()\n else:\n makeCode1 = makeString.upper()\n# autoTraderString = 'http://www.autotrader.com/cars-for-sale/'\\\n# + zipString + '?endYear=' + endYearString + '&makeCode1=' + makeString\\\n# + '&mmt=[' + makeString + '[' + modelString + '[]][]]&modelCode1=' + \\\n# modelString + '&searchRadius=100&startYear=' + startYearString+\\\n# 'firstRecord=' + firstRecord + '&numRecords=100' #figure out how to get multiple pages\n \n # autoTraderString = 'http://www.autotrader.com/cars-for-sale/'\\\n # + endYearString + '/' + makeString + '/' + modelString + '/Arnold+MD-21012?endYear='\\\n # + endYearString + '&firstRecord=' + firstRecord + '&makeCode1=' + makeString.upper() + '&mmt=[' + makeString.upper() + '['+ modelString.upper() + '[]][]]&modelCode1=' + modelString.upper() + '&numRecords=100&searchRadius=100&showcaseListingId=410488662&showcaseOwnerId=100000440&startYear=2012&Log=0'\n\n # autoTraderString = 'http://www.autotrader.com/cars-for-sale/'\\\n # + makeString + '/' + modelString + '/Arnold+MD-21012?endYear='\\\n # + endYearString + '&firstRecord=' + firstRecord + '&makeCode1=' + makeCode1 + '&mmt=[' + makeCode1 + '['+ modelString.upper() + '[]][]]&modelCode1=' + modelString.upper() + '&numRecords=100&searchRadius=200&startYear='+ startYearString+ '&Log=0'\n\n autoTraderString = 'http://www.autotrader.com/cars-for-sale/'\\\n + endYearString + '/' + makeString.title() + '/' + modelString.title() + '/' + zipString+ '?endYear='\\\n + endYearString + '&firstRecord=' + firstRecord + '&numRecords=100&searchRadius=100&startYear='+ startYearString+ '&Log=0'\n\n\n\n #print(autoTraderString)\n \n return autoTraderString\n\n\ndef createCarsRequest(params,k):\n makeString = params['Make'].upper()\n modelString = params['Model'].upper()\n endYearString = str(params['year'])\n startYearString = str(params['year'])\n zipString = str(params['zip'])\n firstRecord = str(100*k+1)\n\n\n temp1 = ' http://www.cars.com/for-sale/searchresults.action?feedSegId=28705&rpp=100&sf2Nm=miles&requestorTrackingInfo=RTB_SEARCH&yrId=39723&sf1Nm=price&sf2Dir=ASC&stkTypId=28881&PMmt=1-1-0&zc=21012&rd=100&mdId=20606&mkId=20017&sf1Dir=DESC&searchSource=UTILITY&crSrtFlds=stkTypId-feedSegId-mkId-mdId&pgId=2102&rn=50'\n \n temp2 = 'http://www.cars.com/for-sale/searchresults.action?feedSegId=28705&rpp=50&sf2Nm=miles&requestorTrackingInfo=RTB_SEARCH&yrId=47272&sf1Nm=price&sf2Dir=ASC&stkTypId=28881&PMmt=1-1-0&zc=21012&rd=100&mdId=20606&mkId=20017&sf1Dir=DESC&searchSource=UTILITY&crSrtFlds=stkTypId-feedSegId-mkId-mdId&pgId=2102&rn=50' \n \n carsString = 'http://www.autotrader.com/cars-for-sale/'\\\n + endYearString + '/' + makeString + '/' + modelString + '/Arnold+MD-21012?endYear='\\\n + endYearString + '&firstRecord=' + firstRecord + '&makeCode1=' + makeString.upper() + '&mmt=[' + makeString.upper() + '['+ modelString.upper() + '[]][]]&modelCode1=' + modelString.upper() + '&numRecords=100&searchRadius=100&showcaseListingId=410488662&showcaseOwnerId=100000440&startYear=2012&Log=0'\n \n #print(autoTraderString)\n \n return carsString\n\n\n\n\n\ndef determineOrigin(soup):\n origin = 'unknown'\n try:\n temp = soup.find_all(\"title\")[0].text.find(\"Autotrader\")\n if temp>-1:\n origin = 'Autotrader'\n except ValueError:\n print(\"\")\n try:\n temp = soup.find_all(\"title\")[0].text.find(\"Cars.com\")\n if temp>-1:\n origin = 'Cars'\n except ValueError:\n print(\"\")\n return origin\n\ndef parseData(soup, origin, carsDF):\n if origin==\"Autotrader\":\n carsDF = parseAutotrader(soup, carsDF)\n #len(carsDF)\n if origin==\"Cars\":\n #print(\"Cars!!\")\n #return [soup, carsDF]\n carsDF = parseCars(soup, carsDF)\n return carsDF\n\n#################################################################\n# FUNCTION TO PARSE DATA FROM AUTOTRADER #\n#################################################################\n\n#function to parse data from Autotrader.com\ndef parseAutotrader(soup, carsDF):\n origin = 'autotrader'\n columns = list(carsDF.columns.values)\n \n #DETERMINE NUMBER OF LISTINGS\n numListings = soup.find_all(\"span\",{\"class\": \"num-listings\"})[0].text\n numListings = numListings.replace(',','')\n numListings = int(numListings)\n \n #print(numListings)\n #exclude spotlight listings\n \n g_dataNew = soup.find_all(\"div\",{\"class\": \"listing listing-findcar listing-dealer listing-isClickable\"})\n g_dataOld = soup.find_all(\"div\",{\"class\": \"listing listing-findcar listing-dealer \"})\n \n if len(g_dataNew)>len(g_dataOld):\n g_data = g_dataNew\n else:\n g_data = g_dataOld\n #print(len(g_dataNew))\n #print(len(g_dataOld))\n\n cars = []\n \n price = []\n mileage = []\n distance = []\n \n for item in g_data:\n dict = {}\n \n #GET YEAR MAKE MODEL\n #GET PRICE\n \n try:\n makeText = item.find_all(\"span\",{\"data-birf-log\":\"component\"})\n \n YMM = []\n trim1 = []\n year1 = []\n make1 = []\n model1 = []\n uniqueList = []\n YMM = makeText[0].text\n trim1 = makeText[2].text\n \n #print(YMM)\n #print(trim)\n #print(uniqueList)\n #the first one is YMM\n YMM = YMM.replace('\\n','').split(' ')\n if YMM[0][0] in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ': #most likely branch\n type1 = YMM[0] # Used or Certified\n year1 = int(YMM[1]) #\n make1 = YMM[2]\n model1 = YMM[3]\n else:\n type1 = 'unknown' # Used or Certified\n year1 = int(YMM[0]) #\n make1 = YMM[1]\n model1 = YMM[2]\n \n #print(year1)\n #print(year1)\n #print(make1)\n #print(model1)\n #print(trim1)\n #return\n except (ValueError, IndexError):\n make1 = 'unknown'\n model1 = 'unkonwn'\n year1 = np.nan\n trim1 = 'unkonwn'\n type1 = unkonwn\n #print('error')\n #return\n \n #GET PRICE\n try:\n #print(item.prettify())\n #price1 = item.find_all(\"div\",{\"class\":\" listing-content \"})\n #print(price1)\n #print(item)\n #pdb.set_trace()\n price1 = item.find_all(\"div\",{\"class\":\"atcui-column listingColumn1\"})\n price1 = item.find_all(\"h4\",{\"class\":\"primary-price\"})[0].text\n #print(price1)\n price1 = float(price1.split()[0].replace(',','').replace('$',''))\n \n \n except (ValueError, IndexError):\n price1 = 0\n #GET MILES\n try:\n #print(item.prettify())\n miles1 = item.find_all(\"span\",{\"class\":\"mileage\"})[0].text\n miles1 = float(miles1.split()[0].replace(',',''))\n except (ValueError, IndexError):\n miles1 = 0\n \n #GET COLOR\n try:\n temp1 = item.find_all(\"div\",{\"class\":\"atcui-column listingColumn2\"})\n #print(\"here\")\n #print(temp1)\n color1 = temp1[0].find_all(\"span\",{\"class\":\"color\"})[0].text.lower()\n color1 = color1.replace('\\n','')\n if len(color1.split())>3:\n color1 = 'unknown'\n except (ValueError, IndexError): \n color1 = 'unknown'\n \n #print(color1)\n \n #GET DISTANCE\n try:\n temp1 = item.find_all(\"div\",{\"class\":\"owner-details\"})\n dist1 = temp1[0].find_all(\"span\",{\"class\":\"distance-cont\"})\n dist1 = int(dist1[0].text.split(' ')[0])\n except (ValueError, IndexError):\n dist1 = 0\n #print(dist1)\n \n data =[origin,year1,make1,model1,trim1,miles1,color1,price1,dist1]\n columns = list(carsDF.columns.values)\n temp1df = [data]\n temp3df = pd.DataFrame(temp1df, columns=columns)\n carsDF = carsDF.append(temp3df, ignore_index=True)\n \n #print(carsDF.head())\n return [numListings, carsDF]\n\n\n\n#################################################################\n# FUNCTION TO PARSE DATA FROM CARS.COM #\n#################################################################\n\n#functions to parse data from cars.com\ndef priceFilter(input):\n output = float(input.replace('$','').replace(',',''))\n return output\n\ndef milesFilter(input):\n output = float(input.replace(',','').split(' ')[0])\n return output\n\ndef yearFilter(input):\n return int(input)\n \ndef distanceFilter(input):\n return float(input.replace('~','').replace('mi. away',''))\n\ndef noChange(input):\n return input\n\ndef getValues(input,key):\n output=[]\n for i in input:\n output.append(i[key])\n return output\n\ndef getMMT(input):\n make = 'unkonwn'\n model = 'unknown'\n trim = 'unkonwn'\n tempList = input.split(' ')\n if (len(tempList))>2:\n make = tempList[0]\n model = tempList[1]\n trim = ' '.join(tempList[2:])\n return [make,model,trim]\n \n \n \n \n#get clean data from cars.com\ndef parseCars(soup, carsDF):\n origin = 'Cars.com'\n columns = list(carsDF.columns.values)\n \n #exclude spotlight listings\n k = 0\n sortBy = {\"priceSort\":0,\"milesSort\":0,\n \"modelYearSort\":0,\"exteriorColorSort\":\"unknown\",\n \"mmtSort\":\"unknown\",\"engineDescriptionSort\":\"unknown\",\n \"stockNumberSort\":\"unknown\",\"seller-distance muted locationSort\":0}\n filterFunction = {\"priceSort\":priceFilter,\n \"milesSort\":milesFilter,\n \"modelYearSort\":yearFilter,\n \"exteriorColorSort\":noChange,\n \"mmtSort\":noChange,\n \"engineDescriptionSort\":noChange,\n \"stockNumberSort\":noChange,\n \"seller-distance muted locationSort\":distanceFilter}\n g_data = soup.find_all(\"div\",{\"class\":\"row vehicle\"})\n\n #print(len(g_data))\n #return # DEBUG\n cars = []\n for item in g_data:\n #print(item.prettify())\n #return\n tempDict = {}\n for carAttribute in list(sortBy.keys()):\n \n try:\n temp1 = item.find_all(\"span\",{\"class\":carAttribute})[0].text\n temp1 = filterFunction[carAttribute](temp1)\n except (ValueError, IndexError):\n temp1 = sortBy[carAttribute] #assign default value\n \n #temp2 = item.find_all(\"span\",{\"class\":\"exteriorColorSort\"})[0].text\n #temp3 = item.find_all(\"span\",{\"class\":\"priceSort\"})[0].text\n #print the price\n #print(temp1[0].find_all(\"h4\",{\"class\":\"primary-price\"})[0].text)\n #print(item)\n #print(temp1)\n \n #print(temp2)\n #print(temp2)\n \n \n tempDict.update({carAttribute:temp1})\n #print(tempDict)\n \n #columns = ['origin','year','make','model',\n # 'trim','miles','color','price','dist']\n \n MMT = getMMT(tempDict['mmtSort'])\n \n data = [origin,tempDict['modelYearSort'],MMT[0],MMT[1],\n MMT[2],tempDict['milesSort'],tempDict['exteriorColorSort'],\n tempDict['priceSort'],tempDict['seller-distance muted locationSort']]\n columns = list(carsDF.columns.values)\n temp1df = [data]\n temp3df = pd.DataFrame(temp1df, columns=columns)\n carsDF = carsDF.append(temp3df, ignore_index=True)\n \n #print(carsDF.head())\n #return\n k = k+1\n \n #if k>15:\n # break\n return carsDF\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\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"cchabalk/usedCarMarketExplorer","sub_path":"myImports/carDDDASImports.py","file_name":"carDDDASImports.py","file_ext":"py","file_size_in_byte":16531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"5375946789","text":"#TODO: Fix the alignment score when clipped_for_overlap becomes true\nimport numpy as np\n\nINF = 1e9\nONE_TO_ONE = \"ONE_TO_ONE\"\nONE_TO_MANY = \"ONE_TO_MANY\"\nMANY_TO_ONE = \"MANY_TO_ONE\"\nMANY_TO_MANY = \"MANY_TO_MANY\"\n\nclass Aligner:\n def __init__(self, \n similarity_matrix, \n ignore=None,\n no_gap=True, \n gap_start_penalty=-0.9, \n gap_continue_penalty=-0.5, \n use_global_prior=False,\n matching_strategy=ONE_TO_ONE,\n ):\n if ignore is None:\n ignore = [set(), set()]\n self.similarity_matrix = similarity_matrix\n self.ignore = ignore\n self.no_gap = no_gap\n self.gap_start_penalty = gap_start_penalty\n self.gap_continue_penalty = gap_continue_penalty\n self.use_global_prior = use_global_prior\n self.sw_computed = False\n self.matching_strategy = matching_strategy\n\n if self.no_gap:\n self.gap_start_penalty = -INF\n self.gap_continue_penalty = -INF\n \n def global_prior(self, b, m):\n mu_b = math.ceil(b * self.N_M/self.N_B)\n exponent = (m - mu_b) * (m - mu_b) / (2*self.N_M*self.N_M)\n exponent *= -1\n return math.exp(exponent)*0.0125\n\n def compute_smith_waterman(self):\n self.dp = np.zeros(\n (self.similarity_matrix.shape[0]+1, \n self.similarity_matrix.shape[1]+1, 2, 2)\n )\n if self.use_global_prior:\n self.N_M = self.dp.shape[0]\n self.N_B = self.dp.shape[1]\n self.parent = {}\n n = self.similarity_matrix.shape[0]\n m = self.similarity_matrix.shape[1]\n \n #Align n text units of first book against m text units of second book \n #gc => gap_continue\n #similarity matrix uses 0 based indexing, dp(alone) uses 1 based indexing\n #print(n,m)\n for i in range(n+1):\n for j in range(m+1):\n for gc_1 in range(2):\n for gc_2 in range(2):\n #base case\n if i == 0 or j == 0:\n self.dp[i][j][gc_1][gc_2] = 0\n self.parent[(i, j, gc_1, gc_2)] = (-1, -1, -1, -1)\n continue\n \n #Recurrence\n best = 0\n self.parent[(i, j, gc_1, gc_2)] = (-1, -1, -1, -1)\n #handle ignore cases first\n if i in self.ignore[0]:\n parent_value = self.dp[i-1][j][gc_1][gc_2]\n self.dp[i][j][gc_1][gc_2] = parent_value\n self.parent[(i, j, gc_1, gc_2)] = (i-1, j, gc_1, gc_2)\n elif j in self.ignore[1]:\n parent_value = self.dp[i][j-1][gc_1][gc_2]\n self.dp[i][j][gc_1][gc_2] = parent_value\n self.parent[(i, j, gc_1, gc_2)] = (i, j-1, gc_1, gc_2)\n else:\n # first try gaps\n if gc_1 == 1:\n #continue gap for first text\n current_value = (self.dp[i-1][j][gc_1][gc_2] + \n self.gap_continue_penalty)\n if best < current_value:\n best = current_value\n self.parent[(i, j, gc_1, gc_2)] = (i-1, j, gc_1, gc_2)\n else:\n #start new gap for first text\n current_value = (self.dp[i-1][j][1][gc_2] + \n self.gap_start_penalty)\n if best < current_value:\n best = current_value\n self.parent[(i, j, gc_1, gc_2)] = (i-1, j, 1, gc_2)\n if gc_2 == 1:\n #continue gap for second text\n current_value = (self.dp[i][j-1][gc_1][gc_2] + \n self.gap_continue_penalty)\n if best < current_value:\n best = current_value\n self.parent[(i, j, gc_1, gc_2)] = (i, j-1, gc_1, gc_2)\n else:\n #start new gap for second text\n current_value = (self.dp[i][j-1][gc_1][1] + \n self.gap_start_penalty)\n if best < current_value:\n best = current_value\n self.parent[(i, j, gc_1, gc_2)] = (i, j-1, gc_1, 1)\n if self.use_global_prior:\n # 1 <= gb <= 2 always true\n gb = self.global_prior(j, i) # if positive sim, higher is better\n else:\n gb = 0\n # try matching\n current_value = (self.dp[i-1][j-1][0][0] + \n self.similarity_matrix[i-1][j-1] + gb) \n if best < current_value:\n best = current_value\n self.parent[(i, j, gc_1, gc_2)] = (i-1, j-1, 0, 0)\n \n if self.matching_strategy in [ONE_TO_MANY, MANY_TO_MANY]:\n # try matching the first one with multiple units from the second\n # sequence\n\n current_value = (self.dp[i][j-1][1][0] + \n self.similarity_matrix[i-1][j-1] + gb +\n self.gap_start_penalty) \n if best < current_value:\n best = current_value\n self.parent[(i, j, gc_1, gc_2)] = (i, j-1, 1, 0)\n\n if self.matching_strategy in [MANY_TO_ONE, MANY_TO_MANY]:\n # try matching the second one with multiple units from the first\n # sequence\n\n current_value = (self.dp[i-1][j][0][1] + \n self.similarity_matrix[i-1][j-1] + gb +\n self.gap_start_penalty) \n if best < current_value:\n best = current_value\n self.parent[(i, j, gc_1, gc_2)] = (i-1, j, 0, 1)\n\n self.dp[i][j][gc_1][gc_2] = best\n \n\n def set_global_align_variables(self):\n n = self.dp.shape[0]\n m = self.dp.shape[1]\n if n > m:\n #print(\"ERRROR!\\nThe first one should be the smaller sequence.\")\n pass\n\n self.dp_2d = np.zeros((n,m))\n self.is_masked_rows = np.zeros(n)\n self.is_masked_cols = np.zeros(m)\n self.s1_to_s2_align = np.full(n, -1)\n self.s2_to_s1_align = np.full(m, -1)\n self.all_cells = []\n for i in range(n):\n for j in range(m):\n self.dp_2d[i][j] = self.dp[i][j][0][0]\n self.all_cells.append({'dp_val': self.dp_2d[i][j], 'i':i, 'j':j})\n self.all_cells.sort(key=lambda x: x['dp_val'], reverse=True)\n\n def traverse(self, i, j, match_element_pair_threshold=0):\n gc_1 = 0\n gc_2 = 0\n seq1_end = i\n seq2_end = j\n clipped_for_overlap = False\n alignment_score = self.dp_2d[i][j]\n while i > 0 and j > 0:\n if self.dp[i][j][gc_1][gc_2] == 0:\n break\n if self.is_masked_rows[i] == 1 or self.is_masked_cols[j] == 1:\n clipped_for_overlap = True\n break\n current_parent = self.parent[(i, j, gc_1, gc_2)]\n if current_parent[0] != i: \n self.is_masked_rows[i] = 1\n if current_parent[1] != j:\n self.is_masked_cols[j] = 1\n\n if (\n (current_parent[0] == i-1 and current_parent[1] == j-1) and\n (self.similarity_matrix[i-1][j-1] > match_element_pair_threshold)\n ):\n #print(self.similarity_matrix[i-1][j-1])\n self.s1_to_s2_align[i] = j\n self.s2_to_s1_align[j] = i\n \n if ((self.matching_strategy in [ONE_TO_MANY, MANY_TO_MANY]) and \n (current_parent == (i, j-1, 1, 0)) and\n (self.similarity_matrix[i-1][j-1] > match_element_pair_threshold)\n ):\n self.s2_to_s1_align[j] = i\n if self.s1_to_s2_align[i] == -1:\n self.s1_to_s2_align[i] = j\n if ((self.matching_strategy in [MANY_TO_ONE, MANY_TO_MANY]) and \n (current_parent == (i-1, j, 0, 1)) and\n (self.similarity_matrix[i-1][j-1] > match_element_pair_threshold)\n ):\n self.s1_to_s2_align[i] = j \n if self.s2_to_s1_align[j] == -1:\n self.s2_to_s1_align[j] = i\n i, j, gc_1, gc_2 = current_parent\n \n seq1_st = i+1\n seq2_st = j+1\n if (seq1_st > seq1_end) or (seq2_st > seq2_end):\n return None \n else: \n alignment_score = self.dp_2d[seq1_end][seq2_end] - self.dp_2d[seq1_st-1][seq2_st-1]\n if alignment_score <= 0:\n return None\n seq1_st -= 1\n seq2_st -= 1\n seq1_end -= 1\n seq2_end -= 1 \n return {\n 'seq1_st':seq1_st,\n 'seq1_end':seq1_end,\n 'seq2_st':seq2_st,\n 'seq2_end':seq2_end,\n 'clipped_for_overlap':clipped_for_overlap,\n 'alignment_score':alignment_score,\n } \n \n def create_alignments(self, match_element_pair_threshold=0, top_k=-1):\n if self.sw_computed is False:\n self.compute_smith_waterman()\n self.set_global_align_variables()\n aligned_segments = []\n for count, cell in enumerate(self.all_cells):\n if count == top_k or cell['dp_val'] == 0:\n break\n current_aligned_segment = self.traverse(cell['i'], cell['j'])\n if current_aligned_segment is not None:\n aligned_segments.append(current_aligned_segment)\n for i in range(1, len(self.s1_to_s2_align)):\n if self.s1_to_s2_align[i] >= 0:\n self.s1_to_s2_align[i-1] = self.s1_to_s2_align[i] - 1\n else:\n self.s1_to_s2_align[i-1] = self.s1_to_s2_align[i]\n for i in range(1, len(self.s2_to_s1_align)):\n if self.s2_to_s1_align[i] >= 0:\n self.s2_to_s1_align[i-1] = self.s2_to_s1_align[i] - 1\n else:\n self.s2_to_s1_align[i-1] = self.s2_to_s1_align[i]\n self.s1_to_s2_align = self.s1_to_s2_align[:-1]\n self.s2_to_s1_align = self.s2_to_s1_align[:-1]\n\n aligned_segments.sort(reverse = True, key=lambda x: x['alignment_score'])\n return aligned_segments, self.s1_to_s2_align, self.s2_to_s1_align\n","repo_name":"tanzir5/alignment_tool2.0","sub_path":"aligners/smith_waterman.py","file_name":"smith_waterman.py","file_ext":"py","file_size_in_byte":9561,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"27"} +{"seq_id":"13766417166","text":"#ques 1\r\ndef area_sphere(r):\r\n return 4*3.14*r*r\r\nradius=int(input(\"enter radius of sphere:\"))\r\nprint(area_sphere(radius))\r\n#ques 2\r\ndef perfectNumber(n):\r\n l=[]\r\n for i in range(1,n):\r\n if n%i==0:\r\n l.append(i)\r\n if sum(l)==n:\r\n return True\r\nfor i in range (1,1001):\r\n if perfectNumber(i):\r\n print(i,\" is a perfect number\")\r\n #ques 3\r\ndef printTable(n):\r\n for i in range(1,11):\r\n print(n,\"x\",i,\"=\",n*i)\r\nn=int(input(\"enter number:\"))\r\nprintTable(n)\r\n #ques 4\r\ndef power(base, exp):\r\n if (exp == 1):\r\n return (base)\r\n if (exp != 1):\r\n return (base * power(base, exp - 1))\r\nbase = int(input(\"Enter base: \"))\r\nexp = int(input(\"Enter exponential value: \"))\r\nprint(\"Result:\", power(base, exp))\r\n","repo_name":"pawan12kamboj/python","sub_path":"assignment 6.py","file_name":"assignment 6.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"9393146970","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport cv2\r\n\r\n\r\nfoto = cv2.imread(\"gri fındık.png\", cv2.IMREAD_GRAYSCALE )\r\n\r\nhistogram = [0] * 256\r\n\r\nfor row in foto:\r\n for pixel_value in row:\r\n histogram[pixel_value] += 1\r\n\r\n\r\nfor i, count in enumerate(histogram):\r\n print(f'Gri Seviye {i}: {count} piksel')\r\n\r\n\r\nplt.bar(range(256), histogram)\r\nplt.title('Fotoğrafın Histogramı')\r\nplt.xlabel('Gri Değer')\r\nplt.ylabel('Piksel Sayısı')\r\nplt.show()\r\n","repo_name":"MyGamerPony/Image-Processing-Assignments","sub_path":"histogram 1. ödevim/1.Histogram ödevi.py","file_name":"1.Histogram ödevi.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"38087979616","text":"# For the sake of this exercise, humans have two hidden states: happy (H) and sad (S),\n# which the robot will need to deduce from five actions:\n# cooking (CO), crying (CR), sleeping (SL), socializing (SO), and watching TV (W).\n\n# From a series of experiments, the robot designers have determined that\n# as people move from one task to another, sad people remain sad 80% of the time\n# and happy people remain happy 90% of the time\n# (the remainder of the time they switch from sad to happy or happy to sad).\n# Initially, 60% of people are happy. That is, P(x0 = H) = 0.6.\n\n# The designers have also determined that for happy and sad people, the activity breakdown is as follows:\n# P(CO | S) = 10%, P(CO | H) = 30%\n# P(CR | S) = 20%, O(CR | H) = 0%\n# P(SL | S) = 40%, P(SL | H) = 30%\n# P(SO | S) = 0%, P(SO | H) = 30%\n# P(WTV | S) = 30%, P(W | H) = 10%\n\nimport numpy as np\nimport math as math\n\n# index 0 is sad, 1 is happy\nhidden_states = (\"sad\", \"happy\")\nactions = (\"CO\", \"CR\", \"SL\", \"SO\", \"WTV\")\n\n# prior_trans_prob = P(qt=Si | qt-1=Sj), prior transition probability matrix\nprior_trans_prob = np.array([[0.8, 0.2],\n [0.1, 0.9]])\n\n# prior_emis_prob = P(Ot | qt), prior emission probability matrix\nprior_emis_prob = np.array([[0.1, 0.2, 0.4, 0, 0.3],\n [0.3, 0, 0.3, 0.3, 0.1]])\n\naction_to_idx = {}\nfor idx, action in enumerate(actions):\n action_to_idx[action] = idx\n\n# prior_init_prob = P(q1 = Si), prior initial probability matrix\nprior_init_prob = np.array([0.4, 0.6])\n\n# hidden markov model:\n# lambda = { init-prob, trans-prob, emission-prob }\ndef HmmFwdBwd(prior_init_prob, prior_trans_prob, prior_emis_prob, action_seq):\n\n T = len(action_seq)\n\n if T == 0:\n return 0\n\n num_states = prior_emis_prob.shape[0]\n num_observ = prior_emis_prob.shape[1]\n\n action_seq_idx = []\n for act_name in action_seq:\n action_seq_idx.append(action_to_idx[act_name])\n\n # forward probability alpha_t(i) = P(O_1:t, qt = Si | lambda)\n fwd_probs = np.zeros((num_states, T))\n # backward probablity beta_t(i) = P(O_t+1:T, qt = Si | lambda)\n bwd_probs = np.zeros((num_states, T))\n\n # fwd_probs(i, 0) = init_prob(i) * emis_prob(i, O0)\n act_idx_0 = action_seq_idx[0]\n fwd_probs[:, 0] = prior_init_prob * prior_emis_prob[:, act_idx_0]\n\n # calculate fwd_probs(i, t), 1 <= t <= T - 1\n for t in range(1, T):\n act_idx = action_seq_idx[t]\n\n for istate in range(num_states):\n t1 = np.dot(fwd_probs[:, t-1], prior_trans_prob[:, istate])\n fwd_probs[istate][t] = t1 * prior_emis_prob[istate, act_idx]\n\n # bwd_probs(i, T-1) = 1.0\n bwd_probs[:, T-1] = 1.0\n\n # calculate bwd_probs(i, t),\n for t in range(T-2, -1, -1):\n t_plus_1 = t + 1\n act_idx_plus_1 = action_seq_idx[t_plus_1]\n for istate in range(num_states):\n ss = 0.0\n for jstate in range(num_states):\n s1 = prior_trans_prob[istate][jstate]\n s2 = prior_emis_prob[jstate][act_idx_plus_1]\n s3 = bwd_probs[jstate][t_plus_1]\n ss += s1 * s2 * s3\n bwd_probs[istate, t] = ss\n\n return fwd_probs, bwd_probs\n\ndef HmmTrain(prior_init_prob, prior_trans_prob, prior_emis_prob, train_seq, num_iterations):\n T = len(train_seq)\n num_states = prior_emis_prob.shape[0]\n num_actions = prior_emis_prob.shape[1]\n\n init_prob = prior_init_prob.copy()\n trans_prob = prior_trans_prob.copy()\n emis_prob = prior_emis_prob.copy()\n\n for i_iter in range(num_iterations):\n\n fwd_probs, bwd_probs = HmmFwdBwd(init_prob, trans_prob, emis_prob, train_seq)\n\n prob_train_seq = np.sum(fwd_probs[:, T-1])\n\n # sigma(i, j, t): P(qt = Si, qt+1 = Sj | O, lambda)\n sigma = np.zeros((num_states, num_states, T-1))\n for istate in range(num_states):\n for jstate in range(num_states):\n for t in range(T-1):\n act_idx = action_to_idx[train_seq[t+1]]\n t1 = emis_prob[jstate, act_idx]\n sigma[istate, jstate, t] = fwd_probs[istate, t] * trans_prob[istate, jstate] * t1 * bwd_probs[jstate, t+1] / prob_train_seq\n print(\"sigma:\")\n print(sigma)\n\n # gamma(i, t) = P(qt = Si | O, lambda)\n gamma = np.zeros((num_states, T-1))\n for t in range(T-1):\n for istate in range(num_states):\n gamma[istate, t] = np.sum(sigma[istate, :, t])\n print(\"gamma:\")\n print(gamma)\n\n new_init_prob = np.zeros(init_prob.shape)\n new_init_prob = gamma[:, 0]\n print(\"new-init-prob:\")\n print(new_init_prob)\n\n new_trans_prob = np.zeros(trans_prob.shape)\n for istate in range(num_states):\n for jstate in range(num_states):\n new_trans_prob[istate, jstate] = np.sum(sigma[istate, jstate, :]) / np.sum(gamma[istate, :])\n print(\"new-trans-prob:\")\n print(new_trans_prob)\n\n new_emis_prob = np.zeros(emis_prob.shape)\n for jstate in range(num_states):\n for kaction in range(num_actions):\n p = 0.0\n for t in range(T-1):\n act_idx = action_to_idx[train_seq[t]]\n if act_idx == kaction:\n p += gamma[jstate, t]\n new_emis_prob[jstate, kaction] = p / np.sum(gamma[jstate, :])\n print(new_emis_prob)\n\n\n\n return init_prob, trans_prob, emis_prob\n\nnum_states = len(hidden_states)\nnum_actions = len(actions)\n\nHmmTrain(prior_init_prob, prior_trans_prob, prior_emis_prob, (\"CO\", \"WTV\", \"CR\", \"CO\", \"SO\"))\n\n\n# for i0 in range(num_actions):\n# total_prob = 0\n# for i1 in range(num_actions):\n# for i2 in range(num_actions):\n# for i3 in range(num_actions):\n# action_seq = (actions[i0], actions[i1], actions[i2], actions[i3])\n# #print(action_seq)\n# fwd_probs, bwd_probs = Hmm(prior_init_prob,\n# prior_trans_prob,\n# prior_emis_prob,\n# action_seq)\n# ss = np.dot(bwd_probs[:, 0], prior_init_prob)\n# total_prob += ss\n# print(total_prob)\n","repo_name":"xukan840730/learning","sub_path":"ml/hmm/full-hmm.py","file_name":"full-hmm.py","file_ext":"py","file_size_in_byte":6289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"172445671","text":"from django.http import Http404\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.core.paginator import Paginator\nfrom django.views.decorators.http import require_POST\nfrom django.contrib import auth\nfrom forms import *\n\nfrom models import *\n\ndef test(request, *args, **kwargs):\n return HttpResponse('OK', status=200)\n\ndef mainpage(request):\n questions = Question.objects.new()\n limit = 10\n try:\n page = int(request.GET.get('page', 1))\n except ValueError:\n raise Http404\n paginator = Paginator(questions, limit)\n paginator.baseulr = '/question/'\n questions = paginator.page(page)\n return render(request, 'qa/questions.html', {\n 'questions': questions.object_list,\n 'paginator': paginator,\n 'page': page,\n })\n\ndef popularpage(request):\n questions = Question.objects.popular()\n limit = 10\n try:\n page = int(request.GET.get('page', 1))\n except ValueError:\n raise Http404\n paginator = Paginator(questions, limit)\n paginator.baseulr = '/popular/'\n questions = paginator.page(page)\n return render(request, 'qa/questions.html', {\n 'questions': questions.object_list,\n 'paginator': paginator,\n 'page': page,\n })\n\ndef questionpage(request, questionid):\n q = Question.objects.get(id = questionid)\n answers = q.answer_set.all()\n return render(request, 'qa/question.html', {\n 'question': q,\n 'answers': answers,\n 'form': AskForm(),\n })\n\ndef askpage(request):\n if request.method == 'POST':\n form = AskForm(request.POST)\n if request.user.is_authenticated():\n form._user = request.user\n if form.is_valid():\n q = form.save()\n return HttpResponseRedirect('/question/' + str(q.id) + '/')\n else:\n form = AskForm()\n return render(request, 'qa/ask.html', { 'form': form })\n\n@require_POST\ndef answerpage(request):\n form = AnswerForm(request.POST)\n if request.user.is_authenticated():\n form._user = request.user\n if form.is_valid():\n a = form.save()\n return HttpResponseRedirect('/question/' + str(a.question.id) + '/')\n else:\n return HttpResponseRedirect('/question/' + str(form.question.id) + '/?err=1')\n\ndef signuppage(request):\n if request.method == 'POST':\n form = SignupForm(request.POST)\n if form.is_valid():\n user = form.save()\n auth.login(request, user)\n return HttpResponseRedirect('/')\n else:\n form = SignupForm()\n return render(request, 'qa/signup.html', { 'form': form })\n\ndef loginpage(request):\n if request.method == 'POST':\n form = LoginForm(request.POST)\n if form.is_valid():\n user = form.load()\n auth.login(request, user)\n return HttpResponseRedirect('/')\n else:\n form = LoginForm()\n return render(request, 'qa/login.html', { 'form': form })","repo_name":"simonnik/stepik_web_project","sub_path":"ask/qa/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3024,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"16711437421","text":"FILETYPE = 'cmnd'\n\ndef testfilename(filename):\n mistakes = []\n\n if type(filename) != type('string'):\n mistakes.append('typeError')\n \n if str(filename)[-1] == '.':\n mistakes.append('nameError')\n\n typeoffile = filename.split('.')[-1]\n if typeoffile != FILETYPE:\n mistakes.append('Wrong filename')\n\n if len(mistakes) == 0:\n return True\n else:\n return False","repo_name":"Alekseypavlov14/programming-language","sub_path":"compiller/filename/testfilename.py","file_name":"testfilename.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"36146456080","text":"import discord\nimport os\nfrom helpers import get_goat, dir_path\n\ncommands = [\"goatcount\"]\nrequires_mention = False\naccepts_mention = False\ndescription = \"Wie viele süße Ziegen? owo\"\n\n\nasync def execute(message):\n msg = '{} süße Ziegen!!!'.format(len([g for g in os.listdir(dir_path + '/assets/goats/') if not g.endswith('.mp4') and not g.endswith('.db')]))\n await message.channel.send(msg)\n","repo_name":"vincentscode/ExtendedKawaii-DiscordBot","sub_path":"actions/goatcount.py","file_name":"goatcount.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"27"} +{"seq_id":"37782129220","text":"import pytest\n\nfrom pybotters_wrapper.binance.binancecoinm import BinanceCOINMWrapperFactory\n\n\n@pytest.fixture\ndef tester(order_normalized_store_tester):\n dummy_data = {\n \"s\": \"ETHUSD_230630\",\n \"c\": \"cSHy1KWSVtXLqk3F7AjuUC\",\n \"S\": \"BUY\",\n \"o\": \"LIMIT\",\n \"f\": \"GTC\",\n \"q\": \"1000\",\n \"p\": \"2099.21\",\n \"ap\": \"0\",\n \"sp\": \"0\",\n \"x\": \"NEW\",\n \"X\": \"NEW\",\n \"i\": 614846957,\n \"l\": \"0\",\n \"z\": \"0\",\n \"L\": \"0\",\n \"T\": 1681734583165,\n \"t\": 0,\n \"b\": \"4.76369681\",\n \"a\": \"0\",\n \"m\": False,\n \"R\": False,\n \"wt\": \"CONTRACT_PRICE\",\n \"ot\": \"LIMIT\",\n \"ps\": \"BOTH\",\n \"cp\": False,\n \"ma\": \"ETH\",\n \"rp\": \"0\",\n \"pP\": False,\n \"si\": 0,\n \"ss\": 0,\n }\n return order_normalized_store_tester(\n builder_factory_method=BinanceCOINMWrapperFactory.create_normalized_store_builder,\n dummy_data=dummy_data,\n expected_item={\n \"id\": \"614846957\",\n \"symbol\": \"ETHUSD_230630\",\n \"side\": \"BUY\",\n \"price\": 2099.21,\n \"size\": 1000.0,\n \"type\": \"LIMIT\",\n },\n )\n\n\ndef test_insert(tester):\n tester.test_insert()\n\n\ndef test_update(tester):\n tester.test_update()\n\n\ndef test_delete(tester):\n tester.test_delete()\n\n\ndef test_item(tester):\n tester.test_item()\n","repo_name":"ko0hi/pybotters-wrapper","sub_path":"tests/binancecoinm/test_normalized_store_order.py","file_name":"test_normalized_store_order.py","file_ext":"py","file_size_in_byte":1426,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"27"} +{"seq_id":"33444523138","text":"# -*- coding: utf-8 -*-\nimport re\nimport logging\n\nfrom libs.pymongodb import pymongodb\n\n\n# Func which converting text rate like ['star', 'full'] into int like 1\ndef convert_text_rate_into_int(item):\n if item[1] == 'full':\n return 1\n elif item[1] == 'half':\n return 0.5\n elif item[1] == '':\n return 0\n\n\n# Func which sum list items.\ndef list_sum(num_list):\n sum_ = 0\n\n for i in num_list:\n sum_ = sum_ + i\n\n return sum_\n\n\n# Func which split list by n elems.\ndef split_list(lst, n):\n return [lst[i:i + n] for i in range(0, len(lst), n)]\n\n\n# Transform text rating into integer values list.\ndef run_rate_transform(ico_stars_ratings):\n int_rate_lst = list(map(convert_text_rate_into_int, ico_stars_ratings)) # transform text into int vals.\n splitted_list = split_list(int_rate_lst, 5) # split list by 5 elems.\n final_lst = list(map(list_sum, splitted_list)) # sum sub lists values.\n\n return final_lst\n\n\n# Func which creating categories data list from bsobj.\ndef create_cats_data_list(bsobj_cats):\n data = []\n cat_num = 0\n\n for cat in bsobj_cats:\n cat_num += 1\n\n if 'upcoming' not in cat['href'] and 'ongoing' not in cat['href'] and 'all' not in cat['href']:\n data.append({'title': cat['title'], 'link': cat['href'], 'cat_num': cat_num})\n\n return data\n\n\n# Func which replace whitespaces and & to _.\ndef clear_title(cat_title):\n pattern = re.compile(r'&')\n\n try:\n re.search(pattern, cat_title).group()\n return cat_title.replace('&', '_').replace(' ', '')\n\n except AttributeError:\n return cat_title.replace(' ', '_')\n\n\n# Func which split range into nums.\ndef split_range_into_nums(diaposon):\n lst = []\n [lst.append(num) for num in range(diaposon[0], diaposon[1] + 1) if num != 0]\n\n return lst\n\n\n# Func which split num by diapasons , like -> 15: (0,2),(3,5)...etc.\ndef split_num_by_ranges(step, num):\n lst = []\n\n for i in range(0, round(step)):\n if i * 3 + 2 + 3 < num:\n lst.append((i * 3, i * 3 + 2))\n\n else:\n lst.append((i * 3, num))\n break\n\n lst = list(map(split_range_into_nums, lst))\n\n return lst\n\n\n# Func which search specific status in url.\ndef search_status(url):\n pattern = re.compile(r'ended|upcoming|ongoing')\n return re.search(pattern, url).group()\n\n\n# Func which sort collection docs for cats: ended, upcoming, ongoing.\ndef sort_col_docs():\n collections_names = ['ended', 'upcoming', 'ongoing']\n\n for col_name in collections_names:\n mongo = pymongodb.MongoDB('icobazaar')\n sorted_docs = mongo.find_with_sort(col_name, 'ico_star_rating')\n mongo.drop_collection(col_name)\n mongo.insert_many(sorted_docs, col_name)\n\n\n# Func which logging message into file.\ndef logger(msg, file):\n logger = logging.getLogger('Main')\n logger.setLevel(logging.INFO)\n\n fh = logging.FileHandler(file)\n fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'\n formatter = logging.Formatter(fmt)\n fh.setFormatter(formatter)\n logger.addHandler(fh)\n logger.info(msg)\n","repo_name":"mkbeh/moonwalker","sub_path":"libs/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3171,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"3916102614","text":"# class for star set\nimport numpy as np\nfrom scipy.linalg import block_diag\nimport linalg\n\n# should support comparing polytopes\nclass Polyhadron(object):\n pass\n\nclass Box(object):\n def __init__(self, lbs, ubs):\n lbs = np.array(lbs)\n ubs = np.array(ubs)\n assert (lbs.shape[0] == ubs.shape[0])\n self.dim = lbs.shape[0]\n v2 = np.vstack([lbs, ubs])\n self.lbs = np.amin(v2, axis = 0)\n self.ubs = np.amax(v2, axis = 0)\n \n def getStar(self):\n c = (self.lbs + self.ubs)/2.0\n vec = (self.ubs - self.lbs)/2.0\n \n C = np.hstack([np.eye(self.dim), -np.eye(self.dim)])\n D = np.hstack([np.ones(self.dim),np.ones(self.dim)])\n vs = []\n for idx in range(self.dim):\n tempv = np.zeros(self.dim)\n tempv[idx] = vec[idx]\n vs.append(tempv)\n \n vs = np.array(vs)\n return Star(c, vs, C, D)\n\n def __str__(self):\n ret_str = []\n for idx in range(self.dim):\n ret_str.append( str(self.lbs[idx]) + '-->' + str(self.ubs[idx]) )\n return 'Box : [' + ','.join(ret_str) + ']'\n\n\n\n\nclass Star (object):\n # preds * C <= D !!!\n # vs : [v0; v1; v2; ] \n def __init__(self, center, vs, C, D):\n self.dim = center.shape[0]\n self.center = center\n self.vs = vs\n self.C = C\n self.D = D\n self.num_pred_var = C.shape[0]\n assert (self.dim == vs.shape[1])\n assert (self.num_pred_var == vs.shape[0])\n assert (C.shape[1] == D.shape[0])\n def copy(self):\n return Star(center = self.center, vs = self.vs, C = self.C, D=self.D)\n \n def ExtendDim(self, ilb, iub):\n add_dim = ilb.shape[0]\n assert (add_dim == iub.shape[0])\n #self.center = np.hstack([self.center, np.zeros(add_dim)])\n self.vs = np.hstack([self.vs, np.zeros((self.vs.shape[0], add_dim))])\n b = Box(ilb, iub)\n st = b.getStar()\n st.vs = np.hstack([np.zeros((st.vs.shape[0], self.dim)), st.vs])\n #st.center = np.hstack([np.zeros( self.dim), st.center])\n \n self.vs = np.vstack([self.vs, st.vs])\n self.center = np.hstack([self.center , st.center])\n self.C = block_diag(self.C, st.C)\n self.D = np.hstack([self.D, st.D])\n\n self.dim += add_dim\n self.num_pred_var += st.num_pred_var\n\n assert (self.dim == self.vs.shape[1])\n assert (self.num_pred_var == self.vs.shape[0])\n assert (self.C.shape[1] == self.D.shape[0])\n\n # x * W + b --> y\n def AffineTransform(self, W,b):\n assert (self.dim == W.shape[0])\n assert (W.shape[1] == b.shape[0])\n self.vs = np.matmul(self.vs, W)\n self.center = np.matmul(self.center, W) + b\n self.dim = W.shape[1]\n \n def isEmpty(self):\n return (not linalg.check_sat(self.C, self.D))\n\n # x * H <= g\n def ApplyHalfSpaceIntersection(self, H, g):\n ndim, n_ineq = H.shape\n assert ( n_ineq == g.shape[0])\n assert ( ndim == self.dim )\n newC = np.matmul( self.vs , H)\n newD = g - np.matmul( self.center, H )\n assert (newC.shape[0] == self.num_pred_var)\n assert (newC.shape[1] == newD.shape[0])\n\n self.C = np.hstack([self.C, newC])\n self.D = np.hstack([self.D, newD])\n \n def getBox(self):\n if self.num_pred_var == 0:\n return Box(lbs = self.center, ubs = self.center)\n \n if self.isEmpty():\n return None\n \n lbs, ubs = linalg.MinMaxOfStar(center = self.center, vs = self.vs, C=self.C, D=self.D)\n return Box(lbs, ubs)\n\n def __str__(self):\n retstr = 'STAR: center:' + str(self.center) + '\\n'\n for vidx in range(self.num_pred_var):\n retstr += ' ' + str(self.vs[vidx]) + '\\n'\n retstr += 'C= \\n'+ str(self.C) + '\\n'\n retstr += 'D= \\n'+ str(self.D) + '\\n'\n return (retstr)\n \n\n\nif __name__ == \"__main__\":\n b0 = Box([1.0, -1.0], [2.0, 4.0])\n print (b0)\n s0 = b0.getStar()\n print (s0)\n print (s0.getBox())\n\n s0.ApplyHalfSpaceIntersection(np.array([[1.0],[1.0]]), np.array([2.0]))\n print (s0.getBox())\n\n s0.ExtendDim(np.array([-2]),np.array([1]))\n print (s0.getBox())\n","repo_name":"zhanghongce/star-set-rnn","sub_path":"star.py","file_name":"star.py","file_ext":"py","file_size_in_byte":4254,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"17919744885","text":"# -*- coding: utf-8 -*-\nfrom constants import *\nfrom LogicalBoard import LogicalBoard, moves\nfrom random import choice\nfrom Helpers import norm\n\n# TODO: agregar pases como posibles movimientos\ndef generateMoves(team):\n generated_moves = [] \n directions = range(len(moves))\n p1, p2, p3 = team\n for d1 in directions:\n for d2 in directions:\n for d3 in directions:\n generated_moves.append({\n p1.id: {'move_type': MOVIMIENTO, 'value': d1},\n p2.id: {'move_type': MOVIMIENTO, 'value': d2},\n p3.id: {'move_type': MOVIMIENTO, 'value': d3}\n })\n return generated_moves\n\ndef static_move(team):\n return [{p.id: {'move_type': MOVIMIENTO, 'value': 0} for p in team}]\n\nclass GeneticTeam:\n\n def __init__(self, team, oponent_team, genome):\n self.team = team\n self.oponent_team = oponent_team\n self.genome = genome\n\n self.players = None\n self.columns = None\n self.rows = None\n self.steps = None\n self.oponent_players = None\n\n def startGame(self, columns, rows, steps, side, players, oponent_players): \n self.columns = columns\n self.rows = rows\n self.steps = steps\n self.oponent_players = oponent_players\n self.side = side\n\n if self.team == A:\n self.logicalBoard = LogicalBoard(columns, rows, players, oponent_players)\n else:\n self.logicalBoard = LogicalBoard(columns, rows, oponent_players, players)\n\n return self.starting_positions();\n\n def starting_positions(self):\n column = 0 if self.side == LEFT else self.columns - 1\n return {i: (i, column) for i in range(3)}\n\n def move(self, board_state):\n self.logicalBoard.undoMove(board_state)\n\n team_moves = generateMoves(self.logicalBoard[self.team])\n \n # Dejo al equipo contrario sin moverse\n oponent_moves = static_move(self.logicalBoard[self.oponent_team])\n # Si quiero considerar todas las posibilidades, tengo que usar la linea comentada\n # oponent_moves = generateMoves(self.logicalBoard[self.oponent_team])\n \n best_move = []\n best_move_value = None\n\n\n # Miro la mejor jugada asumiendo que el oponente se mueve siempre lo peor posible respecto a mi jugada\n for team_move in team_moves:\n if not self.logicalBoard.isValidTeamMove(self.logicalBoard[self.team], team_move):\n continue\n \n move_value = None\n for oponent_move in oponent_moves:\n if not self.logicalBoard.isValidTeamMove(self.logicalBoard[self.oponent_team], oponent_move):\n continue\n\n if self.team == A:\n self.logicalBoard.makeMove(team_move, oponent_move)\n else:\n self.logicalBoard.makeMove(oponent_move, team_move)\n\n new_value = self.evaluateBoard()\n if move_value is None or move_value > new_value:\n move_value = new_value\n\n self.logicalBoard.undoMove()\n\n if best_move_value is None or best_move_value < move_value:\n best_move.append(team_move)\n best_move_value = move_value\n\n # El jugador es medio random, pero esto no es algo que los jugadores geneticos deban considerar\n # Es solo para que sirva mejor como jugador de debuggin\n return choice(best_move[-2:])\n\n def finished(self, status):\n pass\n\n def done(self):\n pass\n\n def evaluateBoard(self):\n res = 0\n\n # Distancia maxima entre dos objetos en el tablero, sirve para normalizar\n max_distance = float(norm([self.rows, self.columns]))\n\n # Distancia de la pelota al arco rival y propio\n ball = self.logicalBoard.free_ball;\n if ball is None:\n for p in self.logicalBoard.team_A + self.logicalBoard.team_B:\n if p.ball is not None:\n ball = p.ball\n break\n\n rival_goal_distance = min([norm((g[0] - ball.i, g[1] - ball.j)) for g in self.logicalBoard.getGoal(self.oponent_team)])\n rival_goal_distance = float(max_distance - rival_goal_distance) / max_distance # Mas lejos mas bajo y normalizado entre 0 y 1\n \n goal_distance = min([norm((g[0] - ball.i, g[1] - ball.j)) for g in self.logicalBoard.getGoal(self.team)])\n goal_distance = float(max_distance - goal_distance) / max_distance # Mas lejos mas bajo y normalizado entre 0 y 1\n\n res += self.genome[0]*rival_goal_distance\n res += self.genome[1]*goal_distance\n\n # Poseción de la pelota mia y del rival\n in_posetion = 0.0\n rival_in_posetion = 0.0\n if self.logicalBoard.free_ball is None:\n for p in self.logicalBoard[self.team]:\n if p.ball is not None:\n in_posetion = 1.0\n break\n\n for p in self.logicalBoard[self.oponent_team]:\n if p.ball is not None:\n rival_in_posetion = 1.0\n break\n\n res += self.genome[2]*in_posetion\n res += self.genome[3]*rival_in_posetion\n\n # Distancia de todos los jugadores a la pelota\n ball_distance = sum([norm((p.i - ball.i, p.j - ball.j)) for p in self.logicalBoard[self.team]])\n ball_distance = float(3*max_distance - ball_distance) / float(3*max_distance)\n \n rival_ball_distance = sum([norm((p.i - ball.i, p.j - ball.j)) for p in self.logicalBoard[self.oponent_team]])\n rival_ball_distance = float(max_distance - rival_ball_distance) / max_distance\n\n res += self.genome[4]*ball_distance\n res += self.genome[5]*rival_ball_distance\n\n # Dispersion\n dispersion = sum([norm((p1.i - p2.i, p1.j - p2.j)) for p1 in self.logicalBoard[self.team] for p2 in self.logicalBoard[self.team]])\n dispersion = float(dispersion) / float(3*max_distance)\n\n res += self.genome[6]*dispersion\n\n # Distancia a los jugadores oponentes (salvo el que tiene la pelota)\n distances_to_oponent = sum([norm((p1.i - p2.i, p1.j - p2.j)) for p1 in self.logicalBoard[self.team] for p2 in self.logicalBoard[self.oponent_team]])\n distances_to_oponent = float(distances_to_oponent) / float(3*max_distance)\n\n res += self.genome[7]*dispersion\n\n return res\n","repo_name":"joaromera/heuristics-metaheuristics","sub_path":"elizondo/gui/GeneticTeam.py","file_name":"GeneticTeam.py","file_ext":"py","file_size_in_byte":6466,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"17112064317","text":"# eme.py\n# \n# Photon statistics retrieval from measured multichannel coincidences using the EME method.\n\nimport math\nimport scipy.special as sc\nimport numpy as np\nfrom scipy.misc import factorial\n\n# response function (matrix) of multichannel detector\n# eta - quantum efficiency\n# mMax - nuber of detection channels\n# nMax - nuber of elements of photon statistics\ndef DET(mMax,nMax,eta):\n\tdet = np.zeros((mMax+1,nMax+1))\n\tfor m in range(mMax+1):\n\t\tfor n in range(nMax+1):\n\t\t\tif m > n:\n\t\t\t\tdet[m][n] = 0\n\t\t\telif m < n:\n\t\t\t\tsummary = []\n\t\t\t\tfor j in range(0,m+1):\n\t\t\t\t\tsummary.append(((-1)**j)*sc.binom(m,j)*((1-eta)+((m-j)*eta)/mMax)**n)\n\t\t\t\tdet[m][n] = sc.binom(mMax,m)*np.sum(summary)\n\t\t\telse:\n\t\t\t\tdet[m][n] = (eta/mMax)**n*(factorial(mMax)/factorial(mMax-n))\t\n\treturn det\n\n# photon statistics retrieval using EME algorithm\n# iterations - the maximum number of iterations (actual number is much lower, based on \"epsilon\")\n# epsilon - the distance between n-th and (n+1)-th iterations when the process is stopped\n# c - click statistics\n# pn - photon statistics\ndef EME(mMax,nMax,eta,det,l,c):\n\titerations = 10**8\n\tepsilon = 10**(-12)\n\tpn=np.array([1./(nMax+1)]*(nMax+1))\n\titeration=0\n\twhile (iteration= th:\n return a * math.pow(x, r) + m\n else:\n return x + b\n\ndef inverse_warper(y, a, b, m, r, th):\n if y >= th + b:\n return math.pow((y-m)/a, 1.0/r)\n else:\n return y - b\n\ndef calculate_remap(image, gamma, threshold, warper):\n\n \"\"\"\n calculate remap matrix for a given warper f(x)\n (f(x) = ax^gamma+m when x>threshold, f(x) = x+b when x int:\n count = 0\n c = [h1!=h2 for h1,h2 in zip(a,sorted(a))]\n for i in c :\n if i:\n count+=1\n return count\n\n\n\nheights = [1,1,4,2,1,3]\nlenght= heightChecker(heights)\n\nprint(lenght)\n\"\"\"\nOutput: 3\nExplanation:\nCurrent array : [1,1,4,2,1,3]\nTarget array : [1,1,1,2,3,4]\nOn index 2 (0-based) we have 4 vs 1 so we have to move this student.\nOn index 4 (0-based) we have 1 vs 3 so we have to move this student.\nOn index 5 (0-based) we have 3 vs 4 so we have to move this student.\n\n\"\"\"\n","repo_name":"Saksham1997/leetrank_practice","sub_path":"height_checker.py","file_name":"height_checker.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"43437093139","text":"print(\"PARA USAR O PROGRAMA UTILIZE AS SEGUINTES TECLAS:\\nOBS: VALORIZE A DIFERENÇA ENTRE LETRAS MAIÚSCULAS E MINÚSCULAS\")\nprint(\"a - PRA ESQUERDA\")\nprint(\"d - PRA DIREITA\")\nprint(\"w - PRA CIMA\")\nprint(\"s - PRA BAIXO\")\nprint(\"+ - AUMENTA A ESCALA DO DESENHO\")\nprint(\"- - DIMINUI A ESCALA DO DESENHO\")\nprint(\"r - ROTACIONA\")\n\n\nfrom OpenGL.GL import *\nfrom OpenGL.GLUT import *\nfrom OpenGL.GLU import *\n\nescala = 1\ntran_x = 0\ntran_y = 0\nrotacao = 1\nteste = 0\n\n\ndef display():\n glClear(GL_COLOR_BUFFER_BIT)\n glMatrixMode(GL_PROJECTION)\n glLoadIdentity()\n gluOrtho2D(-15,15,-15,15)\n glScalef(escala, escala, 0)\n glTranslatef(tran_x, tran_y, 0)\n glRotatef(rotacao,rotacao, rotacao, 0)\n glBegin(GL_QUADS)\n glColor3f(0,0,255)\n glVertex2f(-2,2)\n glVertex2f(2,2)\n glVertex2f(2,-2)\n glVertex2f(-2,-2)\n glEnd()\n\n glFlush()\n\n\ndef temporizador(value):\n global escala, tran_y, tran_x, rotacao, ang, teste\n if teste == 1:\n escala = escala + 0.005\n elif teste == 2:\n escala = escala - 0.005\n elif teste == 3:\n tran_y = tran_y + 0.005\n elif teste == 4:\n tran_y = tran_y - 0.005\n elif teste == 5:\n tran_x = tran_x + 0.005\n elif teste == 6:\n tran_x = tran_x - 0.005\n elif teste == 7:\n rotacao = rotacao + 1\n elif teste == 8:\n rotacao = rotacao - 1\n glutTimerFunc(10,temporizador, 1)\n display()\n\ndef teclado(key, x, y):\n global escala, tran_y, tran_x, rotacao, ang, teste \n\n if ord(key) == 119:\n teste = 3 \n elif ord(key) == 115:\n teste = 4\n elif ord(key) == 100:\n teste = 5 \n elif ord(key) == 97:\n teste = 6 \n elif ord(key) == 43: \n teste = 1\n elif ord(key) == 45: \n teste = 2\n elif ord(key) == 114:\n teste = 7 \n elif ord(key) == 82:\n teste = 8\n display()\n\n\n\nglutInit()\nglutInitDisplayMode(GLUT_SINGLE | GLUT_RGB) \nglutInitWindowSize(500, 500) \nglutInitWindowPosition(100, 100) \nglutCreateWindow(\"ANIMACOES\")\nglClearColor(1, 0, 0, 0)\nglutTimerFunc(10,temporizador, 1)\nglutKeyboardFunc(teclado)\nglutDisplayFunc(display) \nglutMainLoop()","repo_name":"adrianomoraes597/computacao_grafica_pyOpenGL","sub_path":"animacoes.py","file_name":"animacoes.py","file_ext":"py","file_size_in_byte":2142,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"20103312218","text":"from django import forms\nfrom django.contrib.auth.models import User\nfrom .models import Announcement, SportsEvent, Team\n\nclass AnncForm(forms.ModelForm):\n class Meta:\n model = Announcement\n fields = ('title', 'text', 'picture')\n\nclass DateInput(forms.DateInput):\n input_type = 'date'\n\nclass EventForm(forms.ModelForm):\n class Meta:\n model = SportsEvent\n fields = ('name', 'start_date', 'team_limit', 'size_limit', 'text', 'picture', 'is_deleted')\n widgets = {\n 'start_date': DateInput(),\n }\n\nclass TeamForm(forms.ModelForm):\n class Meta:\n model = Team\n fields = ('name', 'students')\n\n def __init__(self, *args, **kwargs):\n super(TeamForm, self).__init__(*args, **kwargs)\n self.fields['name'].widget.attrs.update({'placeholder' : '範例:老司機隊', 'class' : 'form-control'})\n self.fields['students'].widget.attrs.update({'class' : 'form-control'})\n\n self.fields['name'].label='隊伍名稱'\n self.fields['students'].label='隊伍成員 (按住ctrl鍵一次選取多名隊員)'\n self.fields['students'].queryset= User.objects.order_by('username')\n\n mychoices = []\n for userid, username in self.fields['students'].choices:\n tempuser = User.objects.get(username=username)\n mychoices.append((tempuser.id, username+\" \"+tempuser.last_name+tempuser.first_name))\n self.fields['students'].choices = mychoices","repo_name":"SongRongLee/nctu-sports","sub_path":"web/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"35263721719","text":"class Solution:\n def findMin(self, nums: List[int]) -> int:\n\n l, r = 0, len(nums) - 1\n res = nums[0]\n\n while l <= r:\n\n # slight optimization\n # if already sorted\n if nums[l] < nums[r]:\n return min(res, nums[l])\n\n mid = (l + r) // 2\n res = min(res, nums[mid])\n\n # check which portion we are in\n if nums[mid] > nums[r]:\n l = mid + 1\n else:\n r = mid - 1\n\n return res\n","repo_name":"Jinb2/grind75","sub_path":"revisions/binarySearch/findMinimumInSortedArray.py","file_name":"findMinimumInSortedArray.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"36630144789","text":"import re\nfrom models.exceptions import NotValidVehicleData\n\n\nclass Vehicle:\n def __init__(self, *, id, category, make, model, register_number, gear_box):\n self.id = id\n self.category = category\n self.make = make\n self.model = model\n self.register_number = register_number\n self.gear_box = gear_box\n\n def __str__(self):\n return f'{self.make} {self.model} with RegNumber: {self.register_number}'\n\n @classmethod\n def id_validator(cls, id):\n return id\n\n @classmethod\n def category_validator(cls, category):\n if category == '' or len(category) > 30:\n raise NotValidVehicleData('Invalid category!')\n return category\n\n @classmethod\n def make_validator(cls, make):\n if make == '' or len(make) > 30:\n raise NotValidVehicleData('Invalid make!')\n return make\n\n @classmethod\n def model_validator(cls, model):\n if model == '' or len(model) > 30:\n raise NotValidVehicleData('Invalid model!')\n return model\n\n @classmethod\n def register_number_validator(cls, register_number):\n if re.match('[A-Z] \\d{5} [A-Z][A-Z]$', register_number) is None:\n raise NotValidVehicleData('Invalid register number'\n 'The format is \"[A-Z] DDDD [A-Z][A-Z]\"!')\n return register_number\n\n @classmethod\n def gear_box_validator(cls, gear_box):\n if gear_box != 'manual' and gear_box != 'automatic':\n raise NotValidVehicleData('Invalid gear box!')\n return gear_box\n\n @classmethod\n def make_vehicle(cls, row):\n return cls(\n id=row[0],\n category=row[1],\n make=row[2],\n model=row[3],\n register_number=row[4],\n gear_box=row[5]\n )\n","repo_name":"Anton-Naumov/Programming-101-with-Python","sub_path":"week10/Vehicle_Repair_Manager/models/vehicle.py","file_name":"vehicle.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"19026072029","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 Codec:\n #Creating a depth first search string representation of tree\n def serialize_help(self, node):\n if node is None:\n self.serialize.append(\"None\")\n return\n self.serialize.append(str(node.val))\n self.serialize_help(node.left)\n self.serialize_help(node.right)\n \n \n def serialize(self, root):\n self.serialize = []\n self.serialize_help(root)\n return \",\".join(self.serialize)\n \"\"\"Encodes a tree to a single string.\n \n :type root: TreeNode\n :rtype: str\n \"\"\"\n #Creating a tree using depth first serach algorithm\n def deserialize_help(self): \n self.ind += 1\n if self.deserialize[self.ind] == \"None\":\n return None\n node = TreeNode(int(self.deserialize[self.ind]))\n \n node.left = self.deserialize_help()\n node.right = self.deserialize_help()\n return node\n \n def deserialize(self, data):\n self.deserialize = data.split(\",\")\n self.ind = -1\n return self.deserialize_help()\n \n \"\"\"Decodes your encoded data to tree.\n \n :type data: str\n :rtype: TreeNode\n \"\"\"\n \n\n# Your Codec object will be instantiated and called as such:\n# ser = Codec()\n# deser = Codec()\n# ans = deser.deserialize(ser.serialize(root))\n","repo_name":"YangCorey/Personal","sub_path":"leetcode/serialize_and_deserialize/serialize.py","file_name":"serialize.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"72023671433","text":"# coding=utf-8\nfrom django.views.generic.edit import FormView\nfrom elections.forms import ElectionSearchByTagsForm\nfrom django.core.urlresolvers import reverse\nfrom django.views.generic import DetailView\nfrom django.views.generic.base import TemplateView\nfrom elections.models import Election, Area\nfrom elections.models import Candidate, QuestionCategory, CandidateFlatPage\nfrom votai_utils.views import HomeViewBase\nimport logging\nfrom backend_citizen.forms import GroupCreationForm\nfrom candidator.models import Topic, TakenPosition\nfrom django.shortcuts import get_object_or_404\nfrom django.contrib.auth.forms import AuthenticationForm\nfrom backend_citizen.forms import UserCreationForm as RegistrationForm\nfrom popular_proposal.models import PopularProposal\nfrom popular_proposal.filters import ProposalWithoutAreaFilter\nfrom django_filters.views import FilterMixin\nfrom django.core.cache import cache\nfrom django.conf import settings\nfrom django.http import HttpResponseRedirect, Http404\nfrom constance import config\n\nlogger = logging.getLogger(__name__)\n\n\nclass ElectionsSearchByTagView(FormView):\n form_class = ElectionSearchByTagsForm\n template_name = 'search/tags_search.html'\n\n def get(self, request, *args, **kwargs):\n form_class = self.get_form_class()\n form = self.get_form(form_class)\n if form.is_valid():\n return self.form_valid(form)\n else:\n return self.form_invalid(form)\n\n def form_valid(self, form):\n search_result = form.get_search_result()\n context = self.get_context_data(form=form, result=search_result)\n return self.render_to_response(context)\n\n def get_form_kwargs(self):\n kwargs = super(ElectionsSearchByTagView, self).get_form_kwargs()\n kwargs.update({\n 'data': self.request.GET\n })\n return kwargs\n\n def get_context_data(self, form, **kwargs):\n context = super(ElectionsSearchByTagView, self)\\\n .get_context_data(**kwargs)\n context['form'] = form\n return context\n\n def get_success_url(self):\n return reverse('tags_search')\n\n\nclass HomeView(HomeViewBase):\n def get_context_data(self, **kwargs):\n context = super(HomeView, self).get_context_data(**kwargs)\n context['form'] = ElectionSearchByTagsForm()\n\n featured_elections = cache.get('featured_elections')\n if featured_elections is None:\n featured_elections = Election.objects.filter(highlighted=True)\n cache.set('featured_elections', featured_elections, 600)\n context['featured_elections'] = featured_elections\n\n context['searchable_elections_enabled'] = True\n context['register_new_form'] = RegistrationForm()\n context['login_form'] = AuthenticationForm()\n context['group_login_form'] = GroupCreationForm()\n total_proposals = cache.get('total_proposals')\n if total_proposals is None:\n total_proposals = PopularProposal.objects.count()\n cache.set('total_proposals', total_proposals, 600)\n context['total_proposals'] = total_proposals\n proposals_with_likers = cache.get('proposals_with_likers')\n if proposals_with_likers is None:\n proposals_with_likers = PopularProposal.ordered.by_likers()[:9]\n cache.set('proposals_with_likers', proposals_with_likers, 600)\n context['proposals_with_likers'] = proposals_with_likers\n featured_proposals = cache.get('featured_proposals')\n if featured_proposals is None:\n featured_proposals = PopularProposal.objects.filter(featured=True).filter(content_type__app_label=\"popular_proposal\")\n cache.set('featured_proposals', featured_proposals, 600)\n context['featured_proposals'] = featured_proposals\n featured_candidates = cache.get('featured_candidates')\n if featured_candidates is None:\n featured_candidates = Candidate.objects.filter(commitments__isnull=False).filter(elections__name=\"Presidencia\")\n cache.set('featured_candidates', featured_candidates)\n context['candidates'] = featured_candidates\n if settings.IMPORTANT_CANDIDATE_IN_LANDING:\n context['important_candidate'] = Candidate.objects.get(id=settings.IMPORTANT_CANDIDATE_IN_LANDING)\n return context\n\n\nclass ElectionDetailViewBase(DetailView):\n model = Election\n\n\nclass ElectionDetailView(ElectionDetailViewBase):\n\n def get_context_data(self, **kwargs):\n context = super(ElectionDetailView, self).get_context_data(**kwargs)\n if 'slug_candidate_one' in self.kwargs:\n if self.object.candidates.filter(id=self.kwargs['slug_candidate_one']).exists():\n context['first_candidate'] = self.object.candidates\\\n .get(id=self.kwargs['slug_candidate_one'])\n if 'slug_candidate_two' in self.kwargs:\n if self.object.candidates.filter(id=self.kwargs['slug_candidate_two']).exists():\n context['second_candidate'] = self.object.candidates\\\n .get(id=self.kwargs['slug_candidate_two'])\n return context\n\n\nclass FaceToFaceView(ElectionDetailView):\n def get_context_data(self, **kwargs):\n context = super(FaceToFaceView, self).get_context_data(**kwargs)\n if 'first_candidate' in context and 'second_candidate' in context:\n candidate1, candidate2 = context['first_candidate'], \\\n context['second_candidate']\n categories = self.object.categories.all()\n equal_answers = 0\n categories = QuestionCategory.objects.filter(election=self.object)\n topics = Topic.objects.filter(category__in=categories)\n total_questions = topics.count()\n taken_positions = TakenPosition.objects.filter(topic__in=topics)\n for topic in topics:\n try:\n taken_position1 = taken_positions\\\n .get(person=candidate1, topic=topic)\n taken_position2 = taken_positions\\\n .get(person=candidate2, topic=topic)\n if taken_position2.position == taken_position1.position:\n equal_answers += 1\n except TakenPosition.DoesNotExist:\n pass\n if total_questions:\n context['similitude'] = equal_answers * 100 / total_questions\n else:\n context['similitude'] = 0\n return context\n\n\nclass CandidateDetailView(DetailView):\n model = Candidate\n slug_field = 'slug'\n context_object_name = 'candidate'\n\n def get_queryset(self):\n queryset = super(CandidateDetailView, self).get_queryset()\n candidates_per_election_key = u'candidates_for_' + self.get_cache_post_fix()\n queryset_ = cache.get(candidates_per_election_key)\n if queryset_ is None:\n\n if 'election_slug' in self.kwargs.keys():\n queryset_ = queryset.filter(elections__slug=self.kwargs['election_slug'])\n if 'area_slug' in self.kwargs.keys():\n queryset_ = queryset.filter(elections__area__slug=self.kwargs['area_slug'])\n cache.set(candidates_per_election_key,\n queryset_,\n 60 * config.INFINITE_CACHE\n )\n\n return queryset_\n def get_cache_post_fix(self):\n cache_key = \"\"\n kwarg_keys = self.kwargs.keys()\n kwarg_keys.remove('slug')\n for k in kwarg_keys:\n cache_key += self.kwargs.get(k)\n cache_key += self.kwargs['slug']\n return cache_key\n\n def get_object(self, queryset=None):\n cache_key = 'candidate_' + self.get_cache_post_fix()\n candidate = cache.get(cache_key)\n if candidate is None:\n candidate = super(CandidateDetailView, self).get_object(queryset)\n cache.set(cache_key, candidate, 60 * config.INFINITE_CACHE)\n cache_key_ranking = u'ranking-for-' + candidate.id\n _candidate = cache.get(cache_key_ranking)\n if _candidate is None:\n try:\n _candidate = self.model.ranking.filter(id=candidate.id).last()\n except self.model.DoesNotExist:\n raise Http404(u\"Este candidato no existe\")\n cache.set(cache_key_ranking,\n _candidate,\n 60 * config.SOUL_MATE_INFO_ABOUT_CANDIDATES_MINUTES)\n return _candidate\n\n def get_context_data(self, **kwargs):\n context = super(CandidateDetailView, self).get_context_data(**kwargs)\n if self.object is None:\n raise Http404(u\"Este candidato no existe\")\n context['election'] = self.object.election\n return context\n\nclass AreaDetailView(DetailView, FilterMixin):\n model = Area\n context_object_name = 'area'\n template_name = 'area.html'\n # slug_field = 'id'\n\n def dispatch(self, request, *args, **kwargs):\n area = self.get_object()\n if area.classification in settings.FILTERABLE_AREAS_TYPE and area.parent:\n return HttpResponseRedirect(Area.objects.get(id=area.parent.id).get_absolute_url())\n return super(AreaDetailView, self).dispatch(request, *args, **kwargs)\n\n\n def get_context_data(self, **kwargs):\n context = super(AreaDetailView, self).get_context_data(**kwargs)\n initial = self.request.GET or None\n\n kwargs = {'data': initial or None,\n 'area': self.object\n }\n filterset = ProposalWithoutAreaFilter(**kwargs)\n context['proposal_filter_form'] = filterset.form\n\n context['popular_proposals'] = filterset.qs\n return context\n\n def get_queryset(self, *args, **kwargs):\n return Area.objects.all()\n\n\nclass CandidateFlatPageDetailView(DetailView):\n model = CandidateFlatPage\n context_object_name = 'flatpage'\n template_name = 'flatpages/candidate_flatpages.html'\n\n def get_queryset(self):\n qs = CandidateFlatPage.objects.filter(candidate__slug=self.kwargs['slug'])\n return qs\n\n def get_object(self, queryset=None):\n if queryset is None:\n queryset = self.get_queryset()\n return get_object_or_404(self.model, url=self.kwargs['url'])\n\n def get_context_data(self, **kwargs):\n context = super(CandidateFlatPageDetailView, self)\\\n .get_context_data(**kwargs)\n context['election'] = self.object.candidate.election\n context['candidate'] = self.object.candidate\n return context\n\n\nclass KnowYourCandidatesView(TemplateView):\n template_name = \"know_your_candidates.html\"\n\n def append_all_other_candidates(self, context):\n candidate_positions = config.SHOW_ALL_CANDIDATES_IN_THIS_ORDER.split(\",\")\n context['positions'] = []\n for position in candidate_positions:\n position = position.strip()\n\n candidates = Candidate.objects.filter(elections__position=position)\n if settings.LIST_ONLY_COMMITED_CANDIDATES:\n candidates = candidates.exclude(commitments__isnull=True)\n context['positions'].append({'name': position,\n 'candidates': candidates})\n return context\n\n def get_context_data(self, **kwargs):\n context = super(KnowYourCandidatesView, self).get_context_data(**kwargs)\n try:\n election = Election.objects.get(id=config.DEFAULT_ELECTION_ID)\n except:\n election = Election.objects.filter(area__id=config.DEFAULT_AREA).first()\n if election and election.second_round:\n election = election.second_round\n context['default_election'] = election\n if config.SHOW_ALL_CANDIDATES_IN_THIS_ORDER:\n context = self.append_all_other_candidates(context)\n return context\n","repo_name":"ciudadanointeligente/votainteligente-portal-electoral","sub_path":"elections/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11853,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"27"} +{"seq_id":"41424297843","text":"from django.contrib import admin\n\nfrom .models import Contact\n\n\nclass ContactAdmin(admin.ModelAdmin):\n list_display = ['elder', 'added_by', 'name', 'email', 'phone']\n fieldsets = (\n (\"Form Kontak\",\n {\n 'classes': ('wide',),\n 'fields': ('elder', 'name', 'address', 'phone', 'email', 'status')}),\n )\n\n def save_model(self, request, obj, form, change):\n obj.added_by = request.user\n obj.save()\n\n\nadmin.site.register(Contact, ContactAdmin)","repo_name":"kaqfa/elderly_cloud","sub_path":"contact/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"27"} +{"seq_id":"27356856686","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def length(self, head: Optional[ListNode]) -> int:\n length = 0\n node = head\n while node:\n length += 1\n node = node.next\n return length\n \n def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:\n if head.next is None:\n head = None\n return head\n \n middleNode = self.length(head) // 2\n \n node = head\n count = 0\n \n while node:\n if count == middleNode - 1:\n #node.next is the node to be removed\n # so simply assign node.next.next to node.next\n node.next = node.next.next\n break\n \n node = node.next\n count += 1\n return head\n ","repo_name":"madhvi-n/leetcode-python","sub_path":"2095-delete-the-middle-node-of-a-linked-list/2095-delete-the-middle-node-of-a-linked-list.py","file_name":"2095-delete-the-middle-node-of-a-linked-list.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"16712610261","text":"import numpy as np\nfrom scipy.stats import truncnorm\nimport torch\n\n\ndevice = 'cuda'\ntruncated = 0.8\nn_classes = 120\nnz = 120\n\n\ndef sample_truncated_normal(size, threshold, device):\n values = truncnorm.rvs(-threshold, threshold, size=size)\n return torch.from_numpy(values).to(device)\n\n\ndef sample(model, zs, batch_size=32, class_id=None, aux_labels=None):\n out = []\n\n n_images = zs.shape[0]\n n_batches = int(np.ceil(n_images / batch_size))\n\n if aux_labels is None:\n aux_labels = np.full(n_images, class_id)\n\n for i_batch in range(n_batches):\n batch_idx_start = i_batch*batch_size\n batch_idx_end = min((i_batch+1)*batch_size, n_images)\n\n gen_z = zs[batch_idx_start:batch_idx_end]\n\n batch_aux_labels = aux_labels[batch_idx_start:batch_idx_end]\n aux_labels_ohe = np.eye(n_classes)[batch_aux_labels]\n aux_labels_ohe = torch.from_numpy(aux_labels_ohe[:, :])\n aux_labels_ohe = aux_labels_ohe.float().to(device)\n\n with torch.no_grad():\n gen_images = model(gen_z, aux_labels_ohe)\n gen_images = gen_images.to('cpu')\n\n # denormalize\n gen_images = gen_images * 0.5 + 0.5\n out.append(gen_images)\n\n return torch.cat(out, dim=0)\n\n\ndef linear_interpolation(start_z, end_z, steps):\n interpolation_steps = torch.linspace(0.0, 1.0, steps, device=device)\n z = start_z[None] + (end_z[None, :] - start_z[None, :]) * interpolation_steps[:, None]\n return z\n\n\ndef get_cycling_grid_same(height, width, cycles, frames_per_half_cycle):\n all_zs = torch.empty((height, width, cycles * 2 * frames_per_half_cycle, 120), device=device)\n\n z_shared = sample_truncated_normal(120, truncated, device)\n for c in range(cycles):\n z_individual = sample_truncated_normal(120, truncated, device)\n z_individual = z_individual.unsqueeze(0).unsqueeze(0).expand(height, width, -1)\n\n f_idx_start = c * 2 * frames_per_half_cycle\n f_idx_end = f_idx_start + frames_per_half_cycle\n for h in range(height):\n for w in range(width):\n all_zs[h, w, f_idx_start:f_idx_end] = linear_interpolation(z_shared, z_individual[h, w], frames_per_half_cycle)\n\n z_shared = sample_truncated_normal(120, truncated, device)\n\n f_idx_start = c * 2 * frames_per_half_cycle + frames_per_half_cycle\n f_idx_end = f_idx_start + frames_per_half_cycle\n for h in range(height):\n for w in range(width):\n all_zs[h, w, f_idx_start:f_idx_end] = linear_interpolation(z_individual[h, w], z_shared, frames_per_half_cycle)\n\n return all_zs\n\n\ndef get_cycling_grid(height, width, cycles, frames_per_half_cycle):\n all_zs = torch.empty((height, width, cycles * 2 * frames_per_half_cycle, 120), device=device)\n\n z_shared = sample_truncated_normal(120, truncated, device)\n for c in range(cycles):\n z_individual = sample_truncated_normal((height, width, 120), truncated, device=device)\n f_idx_start = c * 2 * frames_per_half_cycle\n f_idx_end = f_idx_start + frames_per_half_cycle\n for h in range(height):\n for w in range(width):\n all_zs[h, w, f_idx_start:f_idx_end] = linear_interpolation(z_shared, z_individual[h, w], frames_per_half_cycle)\n\n z_shared = sample_truncated_normal(120, truncated, device)\n\n f_idx_start = c * 2 * frames_per_half_cycle + frames_per_half_cycle\n f_idx_end = f_idx_start + frames_per_half_cycle\n for h in range(height):\n for w in range(width):\n all_zs[h, w, f_idx_start:f_idx_end] = linear_interpolation(z_individual[h, w], z_shared, frames_per_half_cycle)\n\n return all_zs\n","repo_name":"alekseynp/kaggle-latent-dogs","sub_path":"sampling.py","file_name":"sampling.py","file_ext":"py","file_size_in_byte":3684,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"33880628546","text":"\"\"\"adding pile_four and pile_five to games\n\nRevision ID: 7ac7bcced493\nRevises: 8a4a21f93ad4\nCreate Date: 2022-05-25 12:26:47.311959\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\n# revision identifiers, used by Alembic.\nrevision = '7ac7bcced493'\ndown_revision = '8a4a21f93ad4'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('games', sa.Column('pile_four', postgresql.JSONB(astext_type=sa.Text()), nullable=True))\n op.add_column('games', sa.Column('pile_five', postgresql.JSONB(astext_type=sa.Text()), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('games', 'pile_five')\n op.drop_column('games', 'pile_four')\n # ### end Alembic commands ###\n","repo_name":"chimerror/jellicent-backend","sub_path":"migrations/versions/7ac7bcced493_adding_pile_four_and_pile_five_to_games.py","file_name":"7ac7bcced493_adding_pile_four_and_pile_five_to_games.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"25846666471","text":"import os\nimport sys\nimport argparse\n\nfrom migen import *\n\nimport platform.qmtech100tcoreboard as platform_mod\nfrom platform.qmtech_db_fpga_xc7a35T_ddr3 import user_leds, d7seg\n\n\nclass Decode7Seg(Module):\n def __init__(self):\n self.numin = numin = Signal(4)\n self.output = output = Signal(8)\n\n #decode number to figures\n self.sync += [\n Case(numin, {\n 0x0: output.eq(~0x3F),\n 0x1: output.eq(~0x06),\n 0x2: output.eq(~0x5B),\n 0x3: output.eq(~0x4F),\n 0x4: output.eq(~0x66),\n 0x5: output.eq(~0x6D),\n 0x6: output.eq(~0x7D),\n 0x7: output.eq(~0x07),\n 0x8: output.eq(~0x7F),\n 0x9: output.eq(~0x6F),\n 0xA: output.eq(~0x77),\n 0xB: output.eq(~0x7C),\n 0xC: output.eq(~0x39),\n 0xD: output.eq(~0x5E),\n 0xE: output.eq(~0x79),\n 0xF: output.eq(~0x71),\n })\n ]\n\n\nclass MyLedBlink(Module):\n\n def __init__(self, platform):\n decode7seg = Decode7Seg()\n self.submodules += decode7seg\n\n self.led = led = platform.request(\"user_led\")\n counter = Signal(35)\n\n # Get the board leds\n user_leds = Cat(*[platform.request(\"user_led\", i) for i in range(1, 6)])\n self.user_leds = user_leds\n\n # Counter logic\n self.sync += counter.eq(counter + 1)\n\n # Output the results via an LED\n self.comb += led.eq(counter[26])\n self.comb += user_leds.eq(Cat(*[counter[i] for i in range(25, 20, -1)]))\n\n self.dig = dig = platform.request(\"dig\")\n\n number_out = Signal()\n\n # Assign numbers to 7-segment display\n self.sync += [\n Case(counter[18:20], {\n 0x0: (decode7seg.numin.eq(counter[23:27]),\n dig.dig.eq(0x4)),\n 0x1: (decode7seg.numin.eq(counter[27:31]),\n dig.dig.eq(0x2)),\n 0x2: (decode7seg.numin.eq(counter[31:35]),\n dig.dig.eq(0x1)),\n }),\n self.dig.seg.eq(decode7seg.output),\n ]\n\ndef main():\n # Handle command line imput\n parser = argparse.ArgumentParser(description=\"Qmtech xc7a100t DDR3 Open Aars logical analyzer\")\n parser.add_argument(\"-b\", \"--build\", action=\"store_true\", help=\"Build bitstream\")\n parser.add_argument(\"-l\", \"--load\", action=\"store_true\", help=\"Load bitstream\")\n parser.add_argument(\"-p\", \"--platform\",\n type=str,\n default=\"xc7a100t_ddr3\",\n choices=['xc7a35t_ddr3', 'xc7a100t_ddr3'],\n help=\"Platform/Board type\"\n )\n args = parser.parse_args()\n\n # Setup the platform\n platform = platform_mod.Platform(args.platform) # Instantiate QmTech core board\n platform.add_extension(user_leds)\n platform.add_extension(d7seg)\n\n dut = MyLedBlink(platform)\n\n if args.build:\n platform.build(dut)\n\n if args.load:\n platform.create_programmer().load_bitstream(\"build/top.bit\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"ranzbak/qmtech_migen_platform","sub_path":"qm_db_test.py","file_name":"qm_db_test.py","file_ext":"py","file_size_in_byte":3204,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"27"} +{"seq_id":"25322802511","text":"import time\nfrom collections.abc import Callable\nfrom deap import base\nfrom deap import tools\nfrom tqdm import tqdm\nimport numpy as np\nimport queue\nimport random\nfrom multiprocessing import (\n connection,\n) # Has to be here to avoid threading import bug...\nfrom threading import Thread\n\nfrom robot.individual import Individual\nfrom controllers.controller import Controller\nfrom controllers.coupled_oscillator import CoupledOscillator\nfrom evolutionary_algorithms.tournament_remove import TournamentRemove\nfrom evaluation.evaluator import Evaluator\n\ndef pareto_selection(population: list, n: int):\n if len(population) <= n:\n return population\n\n pareto_front = []\n sorted_pop = sorted(population, key=lambda x: x.fitness, reverse=True)\n\n while len(pareto_front) < n:\n pareto_front.append(sorted_pop[0]) # Highest fitness\n for ind in sorted_pop[1:]:\n if ind.morph_age < pareto_front[-1].morph_age:\n pareto_front.append(ind)\n if len(pareto_front) >= n:\n break\n \n for ind in pareto_front:\n if ind in sorted_pop:\n sorted_pop.remove(ind)\n \n return pareto_front[:n]\n\n\nclass Cheney(TournamentRemove):\n def __init__(self, evaluation_func: Callable[[Individual], float], controller_class: type[Controller], \n controller_mutation_sigma: float, create_simple: bool,\n parallel_processes: int = 1, no_graphics: bool = True, protection: bool = True):\n super().__init__(evaluation_func, controller_class, controller_mutation_sigma, # Only mutate one controller parameter per module on average\n create_simple, 0, parallel_processes, no_graphics, protection)\n if protection:\n self.toolbox.register(\"select\", pareto_selection)\n else:\n self.toolbox.register(\"select\", self.toolbox.get_best)\n\n def spec_dict(self) -> dict:\n spec_dict = super().spec_dict()\n if self.protection:\n spec_dict[\"evolution\"] = \"elitist protection\"\n else:\n spec_dict[\"evolution\"] = \"elitist no protection\"\n return spec_dict\n","repo_name":"tobiaspaulsen/modular-robots","sub_path":"evolutionary_algorithms/cheney.py","file_name":"cheney.py","file_ext":"py","file_size_in_byte":2161,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"23843345542","text":"# Standard Library\nimport unittest\nfrom unittest.mock import MagicMock, patch\n\nfrom crypto_bot import bot\n\n\nclass TestCommon(unittest.TestCase):\n def test_convert_epoch(self):\n epoch_ms = 1618987244277\n self.assertEqual(bot.convert_epoch(epoch_ms), \"2021-04-21 08:40:44.277000\")\n\n def test_round_point(self):\n self.assertEqual(bot.round_point(\"60827.25060827\"), 60827.0)\n self.assertEqual(bot.round_point(\"60827.5060827\"), 60827.5)\n self.assertEqual(bot.round_point(\"60827.7060827\"), 60827.5)\n\n @patch(\"crypto_bot.bot.BybitWebsocket\")\n @patch(\"crypto_bot.bot.bybit\")\n def test_exchange_factory(self, bybit_mock, ws_mock):\n self.assertIsInstance(bot.exchange_factory(\"bybit\"), bot.BybitExchange)\n\n @patch(\"crypto_bot.bot.BybitWebsocket\")\n @patch(\"crypto_bot.bot.bybit\")\n def test_exchange_factory_2(self, bybit_mock, ws_mock):\n with self.assertRaises(NotImplementedError):\n bot.exchange_factory(\"not_an_exchange\")\n\n def test_orders_head(self):\n orders = bot.Orders(\n longs={\n \"924a7a02-1c95-4328-b306-d154fe7db074\": bot.Order(\n order_id=\"924a7a02-1c95-4328-b306-d154fe7db074\",\n side=\"Buy\",\n price=53585.5,\n quantity=1,\n order_status=\"New\",\n ),\n \"2d81bc14-d738-4952-8036-1a996437d6e9\": bot.Order(\n order_id=\"2d81bc14-d738-4952-8036-1a996437d6e9\",\n side=\"Buy\",\n price=53467.0,\n quantity=2,\n order_status=\"New\",\n ),\n \"6939be11-b806-425c-bd63-ca2aef5d786d\": bot.Order(\n order_id=\"6939be11-b806-425c-bd63-ca2aef5d786d\",\n side=\"Buy\",\n price=53313.0,\n quantity=4,\n order_status=\"New\",\n ),\n \"ea93f451-b559-4daa-9616-4d97e7465926\": bot.Order(\n order_id=\"ea93f451-b559-4daa-9616-4d97e7465926\",\n side=\"Buy\",\n price=52853.0,\n quantity=16,\n order_status=\"New\",\n ),\n \"b7f3c04e-066f-45a0-a9f0-bdf1061310c1\": bot.Order(\n order_id=\"b7f3c04e-066f-45a0-a9f0-bdf1061310c1\",\n side=\"Buy\",\n price=52515.0,\n quantity=32,\n order_status=\"New\",\n ),\n \"0c4fd7e7-4754-40a2-bc1c-8660602f1872\": bot.Order(\n order_id=\"0c4fd7e7-4754-40a2-bc1c-8660602f1872\",\n side=\"Buy\",\n price=52075.5,\n quantity=64,\n order_status=\"New\",\n ),\n \"d39db473-3a23-49b3-91d9-f971f881ad17\": bot.Order(\n order_id=\"d39db473-3a23-49b3-91d9-f971f881ad17\",\n side=\"Buy\",\n price=53113.0,\n quantity=8,\n order_status=\"New\",\n ),\n \"defdb93e-4e7f-439a-8547-a825cc4a19fa\": bot.Order(\n order_id=\"defdb93e-4e7f-439a-8547-a825cc4a19fa\",\n side=\"Buy\",\n price=51504.5,\n quantity=128,\n order_status=\"New\",\n ),\n \"dfc715e3-39ea-49ef-a595-de0699434fac\": bot.Order(\n order_id=\"dfc715e3-39ea-49ef-a595-de0699434fac\",\n side=\"Buy\",\n price=50762.0,\n quantity=256,\n order_status=\"New\",\n ),\n \"077c1205-16a5-4839-9073-922f65fe1968\": bot.Order(\n order_id=\"077c1205-16a5-4839-9073-922f65fe1968\",\n side=\"Buy\",\n price=48542.5,\n quantity=1024,\n order_status=\"New\",\n ),\n },\n shorts={\n \"18e39252-de1b-45d8-a671-a3cad422bc11\": bot.Order(\n order_id=\"18e39252-de1b-45d8-a671-a3cad422bc11\",\n side=\"Sell\",\n price=53706.5,\n quantity=1,\n order_status=\"New\",\n ),\n \"19e39252-de1b-45d8-a671-a3cad422bc11\": bot.Order(\n order_id=\"19e39252-de1b-45d8-a671-a3cad422bc11\",\n side=\"Sell\",\n price=53706.5,\n quantity=2,\n order_status=\"New\",\n ),\n },\n )\n self.assertEqual(\n orders.head_longs(),\n bot.Order(\n order_id=\"924a7a02-1c95-4328-b306-d154fe7db074\",\n side=\"Buy\",\n price=53585.5,\n quantity=1,\n order_status=\"New\",\n ),\n )\n\n self.assertEqual(orders.shorts_qty(), 3)\n self.assertEqual(orders.head_longs().quantity, 1)\n\n def test_bankruptcy_price(self):\n self.assertEqual(\n bot.bankruptcy_price(10000 / 8000, 10000, 0.5, 0, 0), 5718.571428571428\n )\n\n def test_liquidation_price(self):\n self.assertEqual(\n bot.liquidation_price(10000, 8000, 0.5, 0, 0, 0.005), 5739.083528002316\n )\n\n def test_allocate_longs(self):\n self.assertEqual(\n list(\n bot.allocate_longs(\n 60000, 1, idx=1, multiplicator=10, intercept=7, growth_factor=1.3\n )\n ),\n [\n (59909.0, 1, -91),\n (59790.5, 2, -118),\n (59636.5, 4, -154),\n (59436.5, 8, -200),\n (59176.5, 16, -260),\n (58838.5, 32, -338),\n (58399.0, 64, -440),\n (57828.0, 128, -571),\n (57085.5, 256, -742),\n (56120.5, 512, -965),\n (54866.0, 1024, -1254),\n (53235.0, 2048, -1631),\n ],\n )\n\n\n@patch(\"crypto_bot.bot.BybitWebsocket\")\n@patch(\"crypto_bot.bot.bybit\")\nclass TestCharlieBot(unittest.TestCase):\n def test_simplebot(self, bybit_mock, ws_mock):\n bybit_mock.bybit.return_value = MagicMock()\n ws_mock.BybitWebsocket.return_value = MagicMock()\n short_big_spread = 50\n short_small_spread = 10\n init_quantity = 1\n exchange_name = \"bybit\"\n sb = bot.CharlieBot(\n short_big_spread,\n short_small_spread,\n init_quantity,\n exchange_name,\n )\n self.assertEqual(sb.short_big_spread, 50)\n self.assertEqual(sb.short_small_spread, 10)\n self.assertEqual(sb.init_quantity, 1)\n self.assertEqual(sb.exchange_name, \"bybit\")\n\n\n@patch(\"crypto_bot.bot.BybitWebsocket\")\n@patch(\"crypto_bot.bot.bybit\")\nclass TestBybitExchange(unittest.TestCase):\n def test_position(self, bybit_mock, ws_mock):\n ex = bot.BybitExchange()\n ex.position\n bybit_mock.bybit().Positions.Positions_myPosition.assert_called_with(\n symbol=\"BTCUSD\"\n )\n\n def test_position_value(self, mock_bybit, ws_mock):\n ex = bot.BybitExchange()\n # mock_bybit.bybit().Positions.Positions_myPosition().result().__getitem__.return_value = (\n mock_bybit.bybit().Positions.Positions_myPosition().result = lambda: (\n {\n \"ret_code\": 0,\n \"ret_msg\": \"OK\",\n \"ext_code\": \"\",\n \"ext_info\": \"\",\n \"result\": {\n \"id\": 0,\n \"position_idx\": 0,\n \"mode\": 0,\n \"user_id\": 153179,\n \"risk_id\": 1,\n \"symbol\": \"BTCUSD\",\n \"side\": \"Buy\",\n \"size\": 1,\n \"position_value\": \"0.00001791\",\n \"entry_price\": \"55834.72920156\",\n \"is_isolated\": False,\n \"auto_add_margin\": 0,\n \"leverage\": \"100\",\n \"effective_leverage\": \"100\",\n \"position_margin\": \"0.00000021\",\n \"liq_price\": \"2.5\",\n \"bust_price\": \"2.5\",\n \"occ_closing_fee\": \"0.0003\",\n \"occ_funding_fee\": \"0\",\n \"take_profit\": \"0\",\n \"stop_loss\": \"0\",\n \"trailing_stop\": \"0\",\n \"position_status\": \"Normal\",\n \"deleverage_indicator\": 1,\n \"oc_calc_data\": '{\"blq\":0,\"slq\":0,\"bmp\":0,\"smp\":0,\"fq\":-1,\"bv2c\":0.0115075,\"sv2c\":0.0114925}',\n \"order_margin\": \"0\",\n \"wallet_balance\": \"0.5\",\n \"realised_pnl\": \"0\",\n \"unrealised_pnl\": -1e-08,\n \"cum_realised_pnl\": \"0\",\n \"cross_seq\": 2898033321,\n \"position_seq\": 0,\n \"created_at\": \"2021-04-21T16:27:37.947905736Z\",\n \"updated_at\": \"2021-04-21T16:53:29.651160082Z\",\n \"tp_sl_mode\": \"Full\",\n },\n \"time_now\": \"1619024009.787388\",\n \"rate_limit_status\": 119,\n \"rate_limit_reset_ms\": 1619024009784,\n \"rate_limit\": 120,\n },\n None,\n )\n\n self.assertEqual(\n ex.position,\n bot.Position(\n entry_price=55834.5,\n real_entry_price=55834.72920156,\n quantity=1,\n rate_limit_status=119,\n rate_limit_reset=\"2021-04-21 18:53:29.784000\",\n rate_limit=120,\n unrealised_pnl=-1e-08,\n liq_price=2.5,\n ),\n )\n\n def test_position_empty(self, bybit_mock, ws_mock):\n ex = bot.BybitExchange()\n # mock_bybit.bybit().Positions.Positions_myPosition().result().__getitem__.return_value = (\n bybit_mock.bybit().Positions.Positions_myPosition().result = lambda: (\n {\n \"ret_code\": 0,\n \"ret_msg\": \"OK\",\n \"ext_code\": \"\",\n \"ext_info\": \"\",\n \"result\": {\n \"id\": 0,\n \"position_idx\": 0,\n \"mode\": 0,\n \"user_id\": 2681267,\n \"risk_id\": 1,\n \"symbol\": \"BTCUSD\",\n \"side\": \"None\",\n \"size\": 0,\n \"position_value\": \"0\",\n \"entry_price\": \"0\",\n \"is_isolated\": False,\n \"auto_add_margin\": 1,\n \"leverage\": \"100\",\n \"effective_leverage\": \"100\",\n \"position_margin\": \"0\",\n \"liq_price\": \"0\",\n \"bust_price\": \"0\",\n \"occ_closing_fee\": \"0\",\n \"occ_funding_fee\": \"0\",\n \"take_profit\": \"0\",\n \"stop_loss\": \"0\",\n \"trailing_stop\": \"0\",\n \"position_status\": \"Normal\",\n \"deleverage_indicator\": 0,\n \"oc_calc_data\": '{\"blq\":0,\"slq\":0,\"bmp\":0,\"smp\":0,\"bv2c\":0.0115075,\"sv2c\":0.0114925}',\n \"order_margin\": \"0\",\n \"wallet_balance\": \"0.00698913\",\n \"realised_pnl\": \"0\",\n \"unrealised_pnl\": 0,\n \"cum_realised_pnl\": \"-0.00025533\",\n \"cross_seq\": 6028527302,\n \"position_seq\": 0,\n \"created_at\": \"2021-04-12T10:29:40.395983654Z\",\n \"updated_at\": \"2021-04-21T00:00:02.116270109Z\",\n },\n \"time_now\": \"1619009282.617507\",\n \"rate_limit_status\": 119,\n \"rate_limit_reset_ms\": 1619009282614,\n \"rate_limit\": 120,\n },\n None,\n )\n with self.assertRaises(bot.NotInCycle):\n ex.position\n\n @unittest.skip\n def test_rest_orders(self, bybit_mock, ws_mock):\n ex = bot.BybitExchange()\n ex.orders\n bybit_mock.bybit().Order.Order_getOrders.assert_called_with(\n symbol=\"BTCUSD\", order_status=\"New\"\n )\n\n def test_orders_empty(self, bybit_mock, ws_mock):\n ex = bot.BybitExchange()\n\n ws_mock.get_data.return_value = []\n self.assertEqual(ex.orders, bot.Orders(longs={}, shorts={}))\n\n def test_orders(self, bybit_mock, ws_mock):\n ex = bot.BybitExchange()\n\n ws_mock.BybitWebsocket().get_data.return_value = [\n {\n \"user_id\": 2681267,\n \"position_idx\": 0,\n \"order_status\": \"New\",\n \"symbol\": \"BTCUSD\",\n \"side\": \"Buy\",\n \"order_type\": \"Limit\",\n \"price\": \"55600\",\n \"qty\": \"2\",\n \"time_in_force\": \"PostOnly\",\n \"order_link_id\": \"\",\n \"order_id\": \"d0aa620e-bcbd-41c6-9315-f1be7570bfe3\",\n \"created_at\": \"2021-04-20T12:35:28.941Z\",\n \"updated_at\": \"2021-04-20T12:35:28.941Z\",\n \"leaves_qty\": \"2\",\n \"leaves_value\": \"0.00003597\",\n \"cum_exec_qty\": \"0\",\n \"cum_exec_value\": \"0\",\n \"cum_exec_fee\": \"0\",\n \"reject_reason\": \"EC_NoError\",\n },\n {\n \"user_id\": 2681267,\n \"position_idx\": 0,\n \"order_status\": \"New\",\n \"symbol\": \"BTCUSD\",\n \"side\": \"Buy\",\n \"order_type\": \"Limit\",\n \"price\": \"55600\",\n \"qty\": \"1\",\n \"time_in_force\": \"PostOnly\",\n \"order_link_id\": \"\",\n \"order_id\": \"d3aa620e-bcbd-41c6-9315-f1be7570bfe3\",\n \"created_at\": \"2021-04-20T12:35:28.941Z\",\n \"updated_at\": \"2021-04-20T12:35:28.941Z\",\n \"leaves_qty\": \"1\",\n \"leaves_value\": \"0.00003597\",\n \"cum_exec_qty\": \"0\",\n \"cum_exec_value\": \"0\",\n \"cum_exec_fee\": \"0\",\n \"reject_reason\": \"EC_NoError\",\n },\n {\n \"user_id\": 2681267,\n \"position_idx\": 0,\n \"order_status\": \"New\",\n \"symbol\": \"BTCUSD\",\n \"side\": \"Sell\",\n \"order_type\": \"Limit\",\n \"price\": \"56300\",\n \"qty\": \"1\",\n \"time_in_force\": \"PostOnly\",\n \"order_link_id\": \"\",\n \"order_id\": \"5b7eebcf-c43c-4396-8aea-07c6d9dad76e\",\n \"created_at\": \"2021-04-20T12:35:09.135Z\",\n \"updated_at\": \"2021-04-20T12:35:09.135Z\",\n \"leaves_qty\": \"1\",\n \"leaves_value\": \"0.00001776\",\n \"cum_exec_qty\": \"0\",\n \"cum_exec_value\": \"0\",\n \"cum_exec_fee\": \"0\",\n \"reject_reason\": \"EC_NoError\",\n },\n {\n \"user_id\": 2681267,\n \"position_idx\": 0,\n \"order_status\": \"New\",\n \"symbol\": \"BTCUSD\",\n \"side\": \"Sell\",\n \"order_type\": \"Limit\",\n \"price\": \"56500\",\n \"qty\": \"1\",\n \"time_in_force\": \"PostOnly\",\n \"order_link_id\": \"\",\n \"order_id\": \"88d6be9c-c6f4-4c2b-87c4-05cb67d2bfc4\",\n \"created_at\": \"2021-04-20T12:35:00.350Z\",\n \"updated_at\": \"2021-04-20T12:35:00.350Z\",\n \"leaves_qty\": \"1\",\n \"leaves_value\": \"0.00001769\",\n \"cum_exec_qty\": \"0\",\n \"cum_exec_value\": \"0\",\n \"cum_exec_fee\": \"0\",\n \"reject_reason\": \"EC_NoError\",\n },\n ]\n\n self.assertEqual(\n ex.orders,\n bot.Orders(\n longs={\n \"d3aa620e-bcbd-41c6-9315-f1be7570bfe3\": bot.Order(\n order_id=\"d3aa620e-bcbd-41c6-9315-f1be7570bfe3\",\n side=\"Buy\",\n price=55600.0,\n quantity=1,\n order_status=\"New\",\n ),\n \"d0aa620e-bcbd-41c6-9315-f1be7570bfe3\": bot.Order(\n order_id=\"d0aa620e-bcbd-41c6-9315-f1be7570bfe3\",\n side=\"Buy\",\n price=55600.0,\n quantity=2,\n order_status=\"New\",\n ),\n },\n shorts={\n \"5b7eebcf-c43c-4396-8aea-07c6d9dad76e\": bot.Order(\n order_id=\"5b7eebcf-c43c-4396-8aea-07c6d9dad76e\",\n side=\"Sell\",\n price=56300.0,\n quantity=1,\n order_status=\"New\",\n ),\n \"88d6be9c-c6f4-4c2b-87c4-05cb67d2bfc4\": bot.Order(\n order_id=\"88d6be9c-c6f4-4c2b-87c4-05cb67d2bfc4\",\n side=\"Sell\",\n price=56500.0,\n quantity=1,\n order_status=\"New\",\n ),\n },\n ),\n )\n\n def test_bid(self, bybit_mock, ws_mock):\n ex = bot.BybitExchange()\n ex.bid\n bybit_mock.bybit().Market.Market_symbolInfo.assert_called_once()\n\n def test_ask(self, bybit_mock, ws_mock):\n ex = bot.BybitExchange()\n ex.ask\n bybit_mock.bybit().Market.Market_symbolInfo.assert_called_once()\n\n def test_cancel_all(self, bybit_mock, ws_mock):\n ex = bot.BybitExchange()\n ex.cancel_all()\n bybit_mock.bybit().Order.Order_cancelAll.assert_called_with(symbol=\"BTCUSD\")\n\n def test_cancel(self, bybit_mock, ws_mock):\n ex = bot.BybitExchange()\n ex.cancel(\"88d6be9c-c6f4-4c2b-87c4-05cb67d2bfc4\")\n bybit_mock.bybit().Order.Order_cancel.assert_called_with(\n symbol=\"BTCUSD\", order_id=\"88d6be9c-c6f4-4c2b-87c4-05cb67d2bfc4\"\n )\n\n def test_long(self, bybit_mock, ws_mock):\n ex = bot.BybitExchange()\n ex.long(0, 0)\n bybit_mock.bybit().Order.Order_new.assert_called_with(\n side=\"Buy\",\n symbol=\"BTCUSD\",\n order_type=\"Limit\",\n qty=0,\n price=0,\n time_in_force=\"PostOnly\",\n )\n\n def test_short(self, bybit_mock, ws_mock):\n ex = bot.BybitExchange()\n ex.short(0, 0)\n bybit_mock.bybit().Order.Order_new.assert_called_with(\n side=\"Sell\",\n symbol=\"BTCUSD\",\n order_type=\"Limit\",\n qty=0,\n price=0,\n time_in_force=\"PostOnly\",\n )\n\n # def test_trigger_long(self):\n # pass\n\n # # trigger_long(self) -> None:\n","repo_name":"netsamir/musing","sub_path":"tests/test_bot.py","file_name":"test_bot.py","file_ext":"py","file_size_in_byte":19100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"40557267727","text":"\"\"\"希尔排序(Shell Sort)\n先将整个待排序的���录序列分割成为若干子序列分别进行直接插入排序,具体算法描述:\n1. 选择一个增量序列t1,t2,…,tk,其中ti>tj,tk=1;\n2. 按增量序列个数k,对序列进行k 趟排序;\n3. 每趟排序,根据对应的增量ti,将待排序列分割成若干长度为m 的子序列,分别对各子表进行直接插入排序。仅增量因子为1 时,\n整个序列作为一个表来处理,表长度即为整个序列的长度。\n\n希尔排序是插入排序的高效实现(大家可以比对一下插入排序和希尔排序的代码),对简单插入排序减少移动次数优化而来。\n简单插入排序每次插入都要移动大量数据,前后插入时的许多移动都是重复操作,若一步到位移动效率会高很多。\n若序列基本有序,简单插入排序不必做很多移动操作,效率很高。\n希尔排序将序列按固定间隔划分为多个子序列,在子序列中简单插入排序,先做远距离移动使序列基本有序;逐渐缩小间隔重复操作,\n 最后间隔为1时即简单插入排序。\n希尔排序对序列划分O(n)次,每次简单插入排序O(logn),时间复杂度O(nlogn)\n额外空间开销出在插入过程数据移动需要的一个暂存,空间复杂度O(1)\n\n希尔排序的核心在于间隔序列的设定。既可以提前设定好间隔序列,也可以动态的定义间隔序列\n\"\"\"\n\n\ndef ShellSort(lst):\n def shellinsert(arr, d):\n n = len(arr)\n for i in range(d, n):\n j = i - d\n temp = arr[i] # 记录要出入的数\n while j >= 0 and arr[j] > temp: # 从后向前,找打比其小的数的位置\n arr[j + d] = arr[j] # 向后挪动\n j -= d\n if j != i - d:\n arr[j + d] = temp\n\n n = len(lst)\n if n <= 1:\n return lst\n d = n // 2\n while d >= 1:\n shellinsert(lst, d)\n d = d // 2\n return lst\n\n\nx = input(\"请输入待排序数列:\\n\")\ny = x.split()\narr = []\nfor i in y:\n arr.append(int(i))\narr = ShellSort(arr)\n# print(arr)\nprint(\"数列按序排列如下:\")\nfor i in arr:\n print(i, end=' ')\n","repo_name":"cp4011/Algorithms","sub_path":"New_Interview/排序算法/4_希尔排序.py","file_name":"4_希尔排序.py","file_ext":"py","file_size_in_byte":2237,"program_lang":"python","lang":"zh","doc_type":"code","stars":3,"dataset":"github-code","pt":"27"} +{"seq_id":"5402241635","text":"import numpy as np\nimport os\nimport glob\n\n\nwith open(\"test.txt\",\"w\") as f:\n f.write(\"这是个测试!\") # 自带文件关闭功能,不需要再写f.close()\n'''\nFOR UCF CRIME\n'''\nroot_path = 'D:\\\\Code\\\\Course\\\\DeepMIL_I3D\\\\Test\\\\RGB'\ndirs = os.listdir(root_path)\nprint(dirs)\nwith open('ucf-i3d-test.list', 'w+') as f:\n\n normal = []\n for dir in dirs:\n files = sorted(glob.glob(os.path.join(root_path, dir, \"*.npy\")))\n for file in files:\n if 'x264.' in file: ## comments\n if 'Normal_' in file:\n normal.append(file)\n else:\n newline = file+'\\n'\n f.write(newline)\n for file in normal:\n newline = file+'\\n'\n f.write(newline)\n","repo_name":"justDoIt1314/DeepMIL_I3D_Simple","sub_path":"list/make_list.py","file_name":"make_list.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"14431253435","text":"#!/usr/bin/python3\n\"\"\"This module houses a function tha indents a text.\n\"\"\"\n\n\ndef text_indentation(text):\n \"\"\"This function indents a text due to the appearance of some characters.\n \"\"\"\n if not isinstance(text, str):\n raise TypeError('text must be a string')\n\n if len(text) == 0:\n raise TypeError(\"text must not be empty\")\n\n for no, i in enumerate(text):\n if i == '.':\n print(\".\")\n print()\n continue\n if i == '?':\n print(\"?\")\n print()\n continue\n if i == ':':\n print(\":\")\n print()\n continue\n if text[no - 1] in ('.', '?', ':') and i == \" \":\n continue\n if text[no - 1] == \" \" and i == \" \":\n continue\n print(\"{}\".format(i), end='')\n","repo_name":"Alexdev68/alx-higher_level_programming","sub_path":"0x07-python-test_driven_development/5-text_indentation.py","file_name":"5-text_indentation.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"20078943504","text":"import re\nimport socket\nfrom copy import copy, deepcopy\nfrom typing import Any, Dict, List, Optional, Tuple\nfrom testcompose.models.container.supported_placeholders import SupportedPlaceholders\nfrom testcompose.models.container.running_container import RunningContainer\n\n\nclass ContainerUtils:\n @staticmethod\n def replace_container_config_placeholders(\n service_env_variables: Dict[str, Any],\n running_containers: Dict[str, RunningContainer],\n service_name: str,\n exposed_ports: List[str],\n ) -> Tuple[Dict[str, Any], List[str]]:\n \"\"\"Utility method to replace placeholders in the service containers.\n Placeholders are usually of the form *${container_name.containerenv_variable}*.\n\n Args:\n service_env_variables (Dict[str, Any]): Dict of config environment variables\n running_containers Dict[str, RunningContainer]: Running container object\n service_name (str): service name as specified in the config\n exposed_ports (List[str]): container exposed ports\n\n Raises:\n ValueError: when a placeholder variable is not of the form service_name.variable_name\n AttributeError: When a service name could not be found in the list of services obtained from the\n provided config file.\n\n Returns:\n Tuple[Dict[str, Any], List[str]]: A tuple of `env_config` and `exposed_ports`\n \"\"\"\n pattern: str = \"\\\\$\\\\{([^}]*)}\"\n substituted_env_variables: Dict[str, Any] = copy(service_env_variables)\n modified_exposed_ports: List[str] = deepcopy(exposed_ports)\n cmpl: Any = re.compile(pattern=pattern).findall\n for k, v in service_env_variables.items():\n if isinstance(v, str):\n replaced_variable: str = v\n for occurence in cmpl(v):\n if len(str(occurence).split(\".\")) != 2:\n raise ValueError\n container_name, variable_name = str(occurence).split(\".\")\n value = None\n value, _exposed_ports = ContainerUtils._external_ports_variables(\n running_containers,\n service_name,\n container_name,\n variable_name,\n modified_exposed_ports,\n )\n if _exposed_ports:\n modified_exposed_ports = deepcopy(_exposed_ports)\n replaced_variable = replaced_variable.replace(f\"${{{occurence}}}\", str(value))\n substituted_env_variables[k] = replaced_variable\n return substituted_env_variables, modified_exposed_ports\n\n @staticmethod\n def _get_free_host_port() -> str:\n \"\"\"Get a free random port number from the container host\n\n Returns:\n str: port number\n \"\"\"\n _socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)\n _socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)\n _socket.settimeout(2)\n _socket.bind((\"\", 0))\n _, port = _socket.getsockname()\n _socket.close()\n return port\n\n @staticmethod\n def _external_ports_variables(\n running_containers: Dict[str, RunningContainer],\n service_name: str,\n container_name: str,\n variable_name: str,\n exposed_ports: List[str] = list(),\n ) -> Tuple[Optional[str], List[str]]:\n value: Optional[str] = None\n _exposed_ports: List[str] = list()\n if container_name.lower() == SupportedPlaceholders.SELF_HOST or variable_name.lower() in [\n SupportedPlaceholders.CONTAINER_HOSTNAME,\n SupportedPlaceholders.EXTERNAL_PORT,\n SupportedPlaceholders.CONTAINER_HOST_ADDRESS,\n ]:\n if (\n container_name.lower() == SupportedPlaceholders.SELF_HOST\n and variable_name.lower() == SupportedPlaceholders.CONTAINER_HOSTNAME\n ):\n value = service_name\n elif (\n container_name.lower() != SupportedPlaceholders.SELF_HOST\n and variable_name.lower() == SupportedPlaceholders.CONTAINER_HOSTNAME\n ):\n value = container_name\n else:\n if variable_name.lower().startswith(SupportedPlaceholders.EXTERNAL_PORT):\n value, _exposed_ports = ContainerUtils._external_port_variables(\n variable_name, exposed_ports\n )\n elif variable_name.lower() == SupportedPlaceholders.CONTAINER_HOST_ADDRESS:\n value = socket.gethostbyname(socket.gethostname())\n else:\n value = running_containers[\n f\"{container_name.lower()}\"\n ].generic_container.container_environment_variables[f\"{variable_name.upper()}\"]\n\n return value, _exposed_ports\n\n @staticmethod\n def _external_port_variables(variable_name: str, exposed_ports: List[str]) -> Tuple[str, List[str]]:\n _exposed_ports: List[str] = deepcopy(exposed_ports)\n container_port: str = re.sub(SupportedPlaceholders.EXTERNAL_PORT + \"_\", \"\", variable_name)\n host_port: str = ContainerUtils._get_free_host_port()\n if container_port and container_port not in exposed_ports:\n raise AttributeError(\n f\"self.hostport_{container_port} must be a valid supplied exposed_ports value!\"\n )\n _exposed_ports.remove(container_port)\n _exposed_ports.append(f\"{host_port}:{container_port}\")\n value: str = str(host_port)\n return value, _exposed_ports\n","repo_name":"rugging24/python-testcompose","sub_path":"testcompose/containers/container_utils.py","file_name":"container_utils.py","file_ext":"py","file_size_in_byte":5700,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"27"} +{"seq_id":"29064355783","text":"import sqlite3\nfrom datetime import datetime\n\nclass Product:\n def __init__(self, name, description, price, category, image, stock):\n self.name = name\n self.description = description\n self.price = price\n self.category = category\n self.image = image\n self.stock = stock\n self.created = datetime.now()\n\n def save(self):\n try:\n conn = sqlite3.connect('petshop.db')\n cursor = conn.cursor()\n cursor.execute(\n \"INSERT INTO Product (name, description, price, category, image, stock, created) \"\n \"VALUES (?, ?, ?, ?, ?, ?, ?)\",\n (self.name, self.description, self.price, self.category, self.image, self.stock, self.created)\n )\n conn.commit()\n conn.close()\n return True, 'Product added successfully'\n except Exception as e:\n return False, str(e)\n","repo_name":"SaswataPatra/PetKart","sub_path":"products_module/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"32975984316","text":"import multiprocessing as mp\n\n\nclass MyFancyClass():\n def __init__(self, name):\n self.name = name\n\n def do_something(self):\n proc_name = mp.current_process().name\n print(f'Doing something fancy in {proc_name} for {self.name}!')\n\n\ndef worker(q):\n obj = q.get()\n obj.do_something()\n\n\nif __name__ == '__main__':\n queue = mp.Queue()\n p = mp.Process(target=worker, args=(queue,))\n p.start()\n\n queue.put(MyFancyClass('Fancy Dan'))\n # Wait for the worker to finish\n queue.close()\n # join_thread() can be called only after close()\n queue.join_thread()\n # block until the background thread(managing the Queue) is terminated\n p.join()\n","repo_name":"250mon/SMIT","sub_path":"2_1_Multiprocessing/ipc_queue.py","file_name":"ipc_queue.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"26595196718","text":"import pyttsx3\nimport datetime\nimport speech_recognition as sr\nimport wikipedia\nimport webbrowser\n\n\n# ------------------ this function is for voice ------------------\n\n\n# now creating a function which will speak\n\nengine = pyttsx3.init(\"sapi5\")\n# sapi5 is APi of microsoft this api is used for speech recognision\n\nvoices = engine.getProperty(\"voices\")\n\n# now using engine variable for speaking it\n\nengine.setProperty(\"voice\", voices[0].id)\n# i am using voice for index number 0 because at index number 0 male voice is present\n# if I will use index number 1 then female voice will used\n\n# --------------------------------------------------------------\n\n# now creating a function which input the argument and speaks it\n\ndef speak(audio):\n\n engine.say(audio)\n engine.runAndWait()\n\n# this function is used for getting voice as argument as pronouncing it\n\n# now we are defining the main function\n\n\n# now if I want my chota jarvis to wish me\n# i have to give create a funcion which will wish me\n\ndef take_command():\n\n # this will input the command from user and output this in form of string\n \n r = sr.Recognizer()\n\n # assigning a variable for inputing the speech\n\n with sr.Microphone() as source:\n\n # this will input from microphone as source\n # and print this statement as he is listning\n\n print(\"Listening .......\")\n\n r.pause_threshold = 1\n\n # what this function will do\n\n # when a person is speaking it the command will listen and if user takes\n # a break then system will consider that the command is complete\n # initially the time command is 0.8\n # we have been changed it to 1\n # so it will give us more time\n\n # now we will use listen module of speech recognition\n\n audio = r.listen(source)\n\n # this audio is coming from source as we have been assigned it earlier\n\n # now lets try this\n # by using try function\n\n try:\n\n print(\"Recognizing....\")\n \n # we have been used this r because above we have been defined as recognizer\n\n\n query = r.recognize_google(audio, language= \"en-in\")\n\n # now the input is firstly recognized by google in language enlish\n # en-in ---> english - india\n\n # now we are going to print what user said\n\n print(\"User said: \", query)\n\n # now if didn't listen it\n # then it will through an error\n\n except Exception as e:\n\n # this will accept the exception and input it in variable e\n\n # and print that\n # if you are a proper coder then you will not give the error to user\n\n # so we will not print the exception\n\n # print(e)\n\n # now if recognizer didn't listen it then firstly it will print error\n # then print a message\n\n print(\"Sorry please say again ....\")\n\n return \"None\"\n\n return query\n\n\ndef wish():\n\n hour = int(datetime.datetime.now().hour)\n\n # this will give the right time in form of hours\n\n # now if jarvis want to wish us then there will be some time\n\n # for instance if there is after noon then this will wish me good afternoon\n \n\n if hour >= 0 and hour < 12:\n speak(\"Good Morning !!\")\n\n elif hour >= 12 and hour < 18:\n speak(\"Good Afternoon\")\n\n else:\n speak(\"Good evening !!\")\n\n\n # now the basic question arises is that if we wish someone\n # then we will also say our name\n\n # now we will create a speak function which will speak\n # about jarvis\n\n speak(\"I am jarvis Sir. Please tell how may I help you .\")\n\n \n\n\ndef chota_jarvis():\n # this will send all the messages to other function and for that we\n # just have to call this function\n\n # speak(\"Praveen is badass !!!!\")\n\n wish()\n\n # now we will use a infinte loop\n # for input\n\n # for the best we will use while loop\n\n while True:\n\n query = take_command().lower()\n\n # it will take the command in lower string and perform it\n\n # we have been print it above but now we want to execute this task\n\n \n # now we will search on the basis of input query\n\n # now we will search \"wikipedia\" in query if this is present\n # then it will use wikipedia module\n\n if \"wikipedia\" in query:\n\n speak(\"Searching wikipedia .....\")\n query = query.replace(\"wikipedia\", \"\")\n # replacing the word wikipedia with \"\"\n\n result = wikipedia.summary(query, sentences=1)\n\n # now we will use wikipedia module for getting the summary\n # of the query in one line\n\n # we have been replaced wikipedia word because we want\n # to give that query to wikipedia to search it and provide us answer\n \n # now we will print the output using speak function\n\n speak(\"According to wikipedia ....\")\n speak(result)\n # now this will just speak it\n # this will not print it\n print(result)\n\n\n # now let say if user want to open google or youtube\n # then for this case we have to inport web browser module\n\n elif \"open youtube\" in query:\n\n\n webbrowser.open(\"youtube.com\")\n \n elif \"open google\" in query:\n\n webbrowser.open(\"google.com\")\n\n elif \"open twitter\" in query:\n\n webbrowser.open(\"twitter.com\")\n\n elif \"open github\" in query:\n\n webbrowser.open(\"github.com\")\n\n elif \"open spotify\" in query or \"open music\" in query:\n\n webbrowser.open(\"spotify.com\")\n\n\n elif \"open instagram\" in query:\n\n webbrowser.open(\"instagram.com\")\n\n\n elif \"open stackoverflow\" in query:\n\n webbrowser.open(\"stackoverflow.com\")\n\n elif \"the time\" in query:\n strtime = datetime.datetime.now().strftime(\"%H:%M:%S\")\n speak(\"The time is \", strtime)\n\n# for sending email firstly read about SMTP\n\n\n\nchota_jarvis()\n","repo_name":"Praveen230102/Projects_Python","sub_path":"Small_Jarvis.py","file_name":"Small_Jarvis.py","file_ext":"py","file_size_in_byte":5934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"6740973934","text":"val = list()\nwhile True:\n v = int(input('Digite um valor:'))\n if v not in val:\n val.append(v)\n print('Valor adicionado com sucesso...')\n else:\n print('Valor duplicado...Não vou adicionar!')\n r = str(input('Quer continuar? [S/N]')).strip().upper()\n while r not in 'SN':\n r = str(input('Tente novamente...Quer continuar? [S/N]')).strip().upper()\n if r in 'N':\n break\nval.sort()\nprint(f'Você digitou os valores {val}')\n\n","repo_name":"matheuspicollideoliveira/python3","sub_path":"exercícios/módulo 3/ex079.py","file_name":"ex079.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"37189280305","text":"#!/usr/bin/python3\nif __name__ == \"__main__\":\n import calculator_1 as calc\n import sys\n\n n_args = len(sys.argv)\n if n_args != 4:\n print(\"Usage: ./100-my_calculator.py \")\n exit(1)\n ops = {\n \"+\": calc.add,\n \"-\": calc.sub,\n \"*\": calc.mul,\n \"/\": calc.div\n }\n if sys.argv[2] not in ops.keys():\n print(\"Unknown operator. Available operators: +, -, * and /\")\n exit(1)\n\n res = ops[sys.argv[2]](int(sys.argv[1]), int(sys.argv[3]))\n print(\"{} {} {} = {}\".format(sys.argv[1], sys.argv[2], sys.argv[3], res))\n","repo_name":"bravemaster3/alx-higher_level_programming","sub_path":"0x02-python-import_modules/100-my_calculator.py","file_name":"100-my_calculator.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"69823172231","text":"import pathlib\nimport tempfile\nfrom snakemake.shell import shell\nfrom snakemake_wrapper_utils.base import WrapperBase\nfrom snakemake_wrapper_utils.bcftools import get_bcftools_opts\n\n\nclass Wrapper(WrapperBase):\n\n def __init__(self, snakemake) -> None:\n super().__init__(snakemake)\n\n def parser(self):\n self.log = self.snakemake.log_fmt_shell(stdout=False, stderr=True)\n # bcftools options\n self.bcftools_opts = get_bcftools_opts(\n self.snakemake, parse_ref=False, parse_memory=False\n )\n self.view_extra = self.snakemake.params.get(\"view_extra\", \"\")\n\n ## Extract arguments: header\n header = self.snakemake.input.get(\"header\", None)\n self.header = f\"-h {header}\" if header else \"\"\n # samples\n samples = self.snakemake.input.get(\"samples\", \"\")\n self.samples = f\"-s {samples}\" if samples else \"\"\n\n def run(self):\n with tempfile.TemporaryDirectory() as tmpdir:\n tmp_prefix = pathlib.Path(tmpdir) / \"bcftools_reheader.\"\n\n shell(\n \"(bcftools reheader\"\n \" --threads {self.snakemake.threads}\"\n \" {self.header}\"\n \" {self.samples}\"\n \" {self.extra}\"\n \" --temp-prefix {tmp_prefix}\"\n \" {self.snakemake.input[0]}\"\n \"| bcftools view\"\n \" {self.bcftools_opts}\"\n \" {self.view_extra}\"\n \") {self.log}\"\n )\n\n\nif __name__ == '__main__':\n Wrapper(snakemake)","repo_name":"dxsbiocc/Workflow","sub_path":"wrappers/bcftools/reheader/wrapper.py","file_name":"wrapper.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"27"} +{"seq_id":"42442102489","text":"from django.db import models\nfrom django.db.models.fields import TextField\nfrom wagtail.admin.edit_handlers import (FieldPanel, MultiFieldPanel,\n StreamFieldPanel)\nfrom wagtail.core.fields import StreamField\nfrom wagtail.core.models import Page\nfrom wagtail.images.edit_handlers import ImageChooserPanel\n\nfrom home.blocks import AboutStreamBlock\n\n\nclass AboutPage(Page):\n main_image = models.ForeignKey(\n 'wagtailimages.Image',\n on_delete=models.PROTECT,\n related_name='+',\n help_text='Main image for the page',\n verbose_name='Main image')\n main_header = models.CharField(\n max_length=100,\n verbose_name='Main header',\n help_text='Text to displayed on the main image. Max 100 chars.')\n main_body = TextField(\n max_length=300,\n verbose_name='Image brief body',\n help_text='Few lines to be displayed on the image. Max 300 chars.')\n about_body = StreamField(\n AboutStreamBlock(), verbose_name=\"Page body\", blank=True)\n lower_section = StreamField(\n AboutStreamBlock(), verbose_name=\"Lower section\", blank=True)\n content_panels = Page.content_panels + [\n MultiFieldPanel(\n [\n ImageChooserPanel(\"main_image\"),\n FieldPanel(\"main_header\"),\n FieldPanel(\"main_body\", classname=\"full\"),\n ],\n heading=\"Hero Section\"),\n StreamFieldPanel('about_body'),\n StreamFieldPanel('lower_section'),\n ]\n parent_page_types = ['home.HomePage']\n","repo_name":"ITcracy/wpc_proj","sub_path":"wpc_website/about/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"27"} +{"seq_id":"9554388198","text":"'''\nCreated on Apr 20, 2019\n\n@author: mac\n'''\nfrom StockMgr.StockMgrBanKuai import CStockMgrBanKuai\nimport os\n\nclass CAnalysisOneDay(object):\n def __init__(self):\n pass\n \n \n def AnalysisOneNewDay(self,fileName, filters, exceptBanKuai = ()):\n mgr = CStockMgrBanKuai()\n mgr.stockPreprocess(fileName)\n for flt in filters:\n mgr.AnalysisOneFileWithFilter(fileName, flt, exceptBanKuai)\n \n \n def AnalysisOneOldDay(self, csvFile, filter_):\n mgr = CStockMgrBanKuai()\n mgr.ReadFromCSVAndFilter(csvFile, filter_)\n \n \n def CovertToCSVOnly(self, fileName):\n mgr = CStockMgrBanKuai()\n mgr.stockPreprocess(fileName)\n \n \n \n def AnalysisOneFolder(self, csvFolder, filters,exceptBanKuai = ()):\n mgr = CStockMgrBanKuai()\n filenames=os.listdir(csvFolder)\n for csvFile in filenames:\n if csvFile.find('.csv') == -1:\n continue\n fullPath = os.path.join(csvFolder, csvFile)\n for filter_ in filters:\n mgr.ReadFromCSVAndFilter(fullPath,filter_,exceptBanKuai)\n \n \nif __name__ == '__main__':\n fileName = u'/Volumes/Data/StockAssistant/stockAnalysis/data/RawData/2019-04-20.xls'\n \n analy = CAnalysisOneDay()\n analy.CovertToCSVOnly(fileName)\n ","repo_name":"EasyStock/stockAnalysis","sub_path":"src/Analysis/AnalysisOneDay.py","file_name":"AnalysisOneDay.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"74826937966","text":"from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, RegexHandler\r\nfrom api_key import TELEGRAM_BOT_TOKEN\r\n\r\nimport logging\r\nimport datetime as dt\r\n\r\nlogging.basicConfig(format='%(name)s - %(levelname)s - %(message)s',\r\n level=logging.INFO,\r\n filename='bot3_calculator.log'\r\n )\r\n\r\nPROXY = {'proxy_url': 'socks5://t1.learn.python.ru:1080',\r\n 'urllib3_proxy_kwargs': {'username': 'learn', 'password': 'python'}}\r\n\r\ndef greet_user(bot, update):\r\n text = 'Вызван /start'\r\n print(text)\r\n update.message.reply_text(text)\r\n\r\n\r\ndef calculation(bot, update):\r\n user_text = update.message.text\r\n signs = '-+*/'\r\n if user_text.endswith('='):\r\n user_text = user_text[:-1]\r\n if user_text == '':\r\n print('Неверный формат')\r\n update.message.reply_text('Неверный формат')\r\n return\r\n else:\r\n for char in user_text:\r\n if not char.isdigit():\r\n if not char in signs:\r\n print('Неверный формат')\r\n update.message.reply_text('Неверный формат')\r\n return\r\n \r\n for elem in signs:\r\n if elem in user_text:\r\n sep_sign = elem\r\n print(sep_sign)\r\n try:\r\n one = float(user_text.split(sep_sign)[0])\r\n two = float(user_text.split(sep_sign)[1])\r\n except ValueError:\r\n print('Неверный формат')\r\n update.message.reply_text('Неверный формат')\r\n\r\n if sep_sign == '+':\r\n answer = one + two\r\n elif sep_sign == '-':\r\n answer = one - two\r\n elif sep_sign == '*':\r\n answer = one * two\r\n elif sep_sign == '/':\r\n\r\n try:\r\n answer = one / two\r\n except ZeroDivisionError:\r\n print('Делить на 0 нельзя')\r\n update.message.reply_text('Делить на 0 нельзя')\r\n return\r\n\r\n if answer % 1 == 0:\r\n answer = int(answer)\r\n\r\n print(answer)\r\n update.message.reply_text(answer)\r\n else:\r\n print('Вы забыли знак равенства')\r\n update.message.reply_text('Вы забыли знак равенства')\r\n\r\n\r\ndef main():\r\n mybot = Updater(TELEGRAM_BOT_TOKEN, request_kwargs=PROXY)\r\n\r\n\r\n dp = mybot.dispatcher\r\n dp.add_handler(CommandHandler('start', greet_user))\r\n dp.add_handler(MessageHandler(Filters.text, calculation))\r\n\r\n\r\n mybot.start_polling()\r\n mybot.idle()\r\n\r\nmain()\r\n","repo_name":"eshevarova/lesson3","sub_path":"bot3_calculator.py","file_name":"bot3_calculator.py","file_ext":"py","file_size_in_byte":2747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"8784884109","text":"from django.db import models\n\n# Create your models here.\n\nfrom django.db import models\nfrom django.contrib.auth.models import User\nfrom PIL import Image\nfrom django.utils.datetime_safe import date\n\nclass Course(models.Model):\n id = models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')\n num = models.IntegerField('Course Number')\n title = models.CharField('Course', max_length=31)\n\n def __str__(self):\n return self.title\n\n class Meta:\n verbose_name = 'Курс'\n verbose_name_plural = 'Курсы'\n\n\nclass Profile(models.Model):\n id = models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')\n user = models.OneToOneField(User, related_name='Profile',unique=True ,on_delete=models.CASCADE)\n image = models.ImageField( upload_to='profile_pics',null=True,default='default.png')\n course = models.ForeignKey(Course, verbose_name='Course',related_name='Profiles', on_delete=models.CASCADE, default='')\n tutorPermissions = models.BooleanField('Права тьютора', default=False)\n initiative = models.BooleanField('Инициатива', default=False)\n\n def __str__(self):\n return f'{self.user.username} Profile'\n\n def save(self, *args, **kwargs):\n super().save(*args, **kwargs)\n\n img = Image.open(self.image.path)\n\n if img.height > 300 or img.width > 300:\n output_size = (300, 300)\n img.thumbnail(output_size)\n img.save(self.image.path)\n\n# def save(self):\n# super().save()\n\n# img = Image.open(self.image.path)\n\n# if img.height > 300 or img.width > 300:\n# output_size = (300, 300)\n# img.thumbnail(output_size)\n# img.save(self.image.path)","repo_name":"nonskayaa/ItisTutors","sub_path":"itisTutors/users/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1791,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"2"} +{"seq_id":"6675418387","text":"import sys\nimport random\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import QMainWindow, QApplication\nfrom PyQt5.QtGui import QPainter, QColor, QPen\n\n\nclass First(QMainWindow): # Экран приветсвия\n def __init__(self): # иницилизация\n super(QMainWindow, self).__init__()\n uic.loadUi('Ui.ui', self) # загрузка макета\n self.flag = None\n self.press.clicked.connect(self.flag_on)\n\n def flag_on(self):\n self.flag = True\n self.update()\n\n def paintEvent(self, e):\n if self.flag is True:\n qp = QPainter()\n qp.begin(self)\n qp.setBrush(QColor(255, 255, 0))\n x = random.randint(5, 500)\n y = random.randint(5, 500)\n qp.drawEllipse(x, x, y, y)\n qp.end()\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n w = First()\n w.show() # открываем начальное окно - приветсвия\n sys.exit(app.exec_())\n\n","repo_name":"Emil-BAD/ui","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"40167906203","text":"import os\nfrom albumentations.pytorch import ToTensorV2\nimport pandas as pd\nimport numpy as np\n\nimport torch\nfrom torch import functional as F\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision.transforms import transforms\n\nimport pytorch_lightning as pl\n\nfrom PIL import Image\n\nfrom utils import preprocess_image\n\nfrom config import CONFIG\n\ncfg = CONFIG()\n\ndfx = pd.read_csv(cfg.trainset)\n\nclass Data(Dataset):\n def __init__(self, dataframe, transform, one_hot = False, use_preprocess = True):\n super().__init__()\n self.dataframe = dataframe\n self.transform = transform\n self.one_hot = one_hot\n self.use_preprocess = use_preprocess\n \n def __len__(self):\n return self.dataframe.shape[0]\n \n def __getitem__(self, item):\n img_path = self.dataframe.iloc[item]['image_path']\n target = self.dataframe.iloc[item]['label']\n image = Image.open(img_path).convert('RGB')\n image = np.asarray(image)\n if self.use_preprocess :\n image = preprocess_image(image)\n if self.transform is not None:\n image = self.transform(image = image)['image']\n if self.one_hot:\n return image, F.one_hot(torch.tensor(target), num_classes=cfg.num_classes)\n else:\n return image, torch.tensor(target)\n\nclass TestData(Dataset):\n def __init__(self, dataframe, transform, use_preprocess = True):\n super().__init__()\n self.dataframe = dataframe\n self.transform = transform\n self.use_preprocess = use_preprocess\n \n def __len__(self):\n return self.dataframe.shape[0]\n \n def __getitem__(self, item):\n img_id = self.dataframe.iloc[item]['filename']\n img_path = os.path.join(cfg.test_images,img_id)\n image = Image.open(img_path).convert('RGB')\n image = np.asarray(image)\n if self.use_preprocess:\n image = preprocess_image(image)\n if self.transform is not None:\n image = self.transform(image = image)['image']\n\n return image\n\nclass DataModule(pl.LightningDataModule):\n\n def __init__(self, fold: int, train_batch_size: int, valid_batch_size: int, one_hot: bool = False):\n super().__init__()\n self.fold = fold\n self.train_batch_size = train_batch_size\n self.valid_batch_size = valid_batch_size\n self.one_hot = one_hot\n self.train_transform = cfg.train_aug\n self.valid_transform = cfg.val_aug\n\n def setup(self, stage: str = None):\n df_train = dfx[dfx.kfold != self.fold].reset_index(drop=True)\n df_valid = dfx[dfx.kfold == self.fold].reset_index(drop=True)\n\n df_train = df_train.reset_index(drop=True)\n df_valid = df_valid.reset_index(drop=True)\n\n self.train_dataset = Data(\n dataframe = df_train,\n transform = self.train_transform,\n one_hot = self.one_hot,\n use_preprocess = cfg.use_preprocess\n )\n\n self.valid_dataset = Data(\n dataframe = df_valid,\n transform = self.valid_transform,\n one_hot = self.one_hot,\n use_preprocess = cfg.use_preprocess\n ) \n\n def train_dataloader(self):\n return DataLoader(self.train_dataset, batch_size = self.train_batch_size, shuffle = True, pin_memory = True, num_workers = 4, drop_last=True)\n \n def val_dataloader(self):\n return DataLoader(self.valid_dataset, batch_size = self.valid_batch_size, shuffle = False, pin_memory = True, num_workers = 4, drop_last=True)","repo_name":"Devesh2707/Knee-Osteoarthritis","sub_path":"dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":3543,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"2"} +{"seq_id":"71828086126","text":"#!/usr/bin/python3\n# ZR6TG - Tom - 2022/06/23\n\n# basic signals detection code ported from https://github.com/m0dts/QO-100-WB-Live-Tune\n\nimport asyncio\nimport pygame\nimport websockets\nimport os\nfrom datetime import datetime\nimport pygame.gfxdraw\n#os.environ[\"SDL_FBDEV\"] = \"/dev/fb0\"\n\n# CONFIGURATION\nFFT_URL = \"wss://eshail.batc.org.uk/wb/fft\" #official batc fft\n#FFT_URL = \"ws://192.168.0.244:7681\"\n\nCALLSIGN = \"ZR6TG\"\nCOL_BG = (20, 29, 43)\nCOL_SPECTRUM = (217, 127, 43)\nCOL_TEXT = (224,224,224)\n\nWIDTH = 800\nHEIGHT = 480\n\nclass Clock:\n def __init__(self, time_func=pygame.time.get_ticks):\n self.time_func = time_func\n self.last_tick = time_func() or 0\n \n async def tick(self, fps=0):\n if 0 >= fps:\n return\n \n end_time = (1.0 / fps) * 1000\n current = self.time_func()\n time_diff = current - self.last_tick\n delay = (end_time - time_diff) / 1000\n \n self.last_tick = current\n if delay < 0:\n delay = 0\n \n await asyncio.sleep(delay)\n\nclass Graphics:\n \n def __init__(self, width, height):\n self.start_freq = 10490.5\n self.width = width\n self.height = height\n self.x_tab = (self.width-50) /922\n self.font = pygame.font.SysFont('freesans', 20)\n self.bigfont = pygame.font.SysFont('freesans', 180)\n self.mediumfont = pygame.font.SysFont('freesans', 50)\n\n\n def align_symbolrate(self, width):\n if width < 0.002: return 0\n if width < 0.065: return 0.035\n if width < 0.086: return 0.066\n if width < 0.195: return 0.125\n if width < 0.277: return 0.250\n if width < 0.388: return 0.333\n if width < 0.700: return 0.500\n if width < 1.2: return 1.0\n if width < 1.6: return 1.5\n if width < 2.2: return 2\n \n return int(width)\n\n async def find_signals(self, fft_data):\n signals = []\n i = 0\n j = 0\n noise_level = 11000\n signal_threshold = 18000\n in_signal = False\n start_signal = 0\n end_signal = 0\n mid_signal = 0\n signal_strength = 0\n signal_bw = 0\n signal_freq = 0\n acc = 0\n acc_i = 0\n\n i = 2\n while i < len(fft_data):\n\n if in_signal == False:\n if (fft_data[i] + fft_data[i-1] + fft_data[i-2]) / 3 > signal_threshold:\n in_signal = True\n start_signal = i\n else:\n if (fft_data[i] + fft_data[i-1] + fft_data[i-2]) / 3 < signal_threshold:\n in_signal = False\n end_signal = i\n\n acc = 0\n acc_i = 0\n\n j = int(start_signal + (0.3 * ( end_signal - start_signal )))\n\n while ( j < start_signal + (0.8 * (end_signal - start_signal))):\n acc = acc + fft_data[j]\n acc_i = acc_i + 1\n j+=1\n\n if acc_i == 0:\n in_signal = False\n continue\n\n signal_strength = acc / acc_i\n\n # find real start\n j = start_signal \n while (fft_data[j] - noise_level) < 0.75 * (signal_strength - noise_level):\n start_signal = j\n j+=1\n\n # find real end\n j = end_signal\n end_signal_orig = j\n while (fft_data[j] - noise_level) < 0.75 * (signal_strength - noise_level): \n end_signal = j\n\n if j <= 0:\n end_signal = end_signal_orig\n fake_end = True\n break\n j -= 1\n\n\n mid_signal = start_signal + ((end_signal - start_signal)/2)\n signal_freq = self.start_freq + (((mid_signal + 1) / (len(fft_data)) * 9))\n signal_bw = self.align_symbolrate((end_signal - start_signal) * (9 / len(fft_data)))\n\n if signal_bw >= 0.033:\n signals.append({'start': start_signal, 'end' : end_signal, 'mid' : mid_signal, 'freq' : signal_freq, 'signal_strength' : signal_strength/255, 'signal_bw' : signal_bw})\n\n\n\n i += 1\n\n return signals\n\n\n async def update(self, window, fft):\n polygon_data = []\n fft_data = []\n x = 0\n\n while ( x < len(fft)-1 ):\n db = [fft[x],fft[x+1]]\n #y = int.from_bytes(db, 'little')/255\n fft_data.append(int.from_bytes(db, 'little'))\n polygon_data.append((25 + (x/2 * self.x_tab),480-int.from_bytes(db, 'little')/255))\n x += 2\n\n signals = await self.find_signals(fft_data)\n\n polygon_data.append((25,480))\n pygame.gfxdraw.filled_polygon(window, polygon_data,COL_SPECTRUM)\n pygame.gfxdraw.aapolygon(window, polygon_data,(197,244,103))\n\n # show time\n #timeStr = datetime.now().strftime(\"%H:%M:%S\")\n timeStr = datetime.now().strftime(\"%H:%M\")\n\n text_width, text_height = self.bigfont.size(timeStr)\n text = self.bigfont.render(timeStr, True, COL_TEXT)\n window.blit(text, (400 - text_width/2, 80))\n\n dateStr = datetime.now().strftime(\"%m/%d\")\n \n text_width, text_height = self.bigfont.size(dateStr)\n text = self.mediumfont.render(dateStr, True, COL_TEXT)\n window.blit(text, (665 ,5))\n\n # show callsign\n text_width, text_height = self.bigfont.size(CALLSIGN)\n text = self.mediumfont.render(CALLSIGN, True, COL_TEXT)\n window.blit(text, (5 ,5))\n\n for sig in signals:\n text_width, text_height = self.font.size(str(round(sig['freq'],2)))\n text = self.font.render(str(round(sig['freq'],2)) + \"\", True, COL_TEXT)\n window.blit(text, (25 + (int(sig['mid']) * self.x_tab) - text_width/2, 480 - int(sig['signal_strength']) - 60))\n text_width, text_height = self.font.size(str(int(sig['signal_bw'] * 1000)) + \"Ks\")\n\n text = self.font.render(str(int(sig['signal_bw'] * 1000)) + \"Ks\", True, COL_TEXT)\n window.blit(text, (25 + (int(sig['mid']) * self.x_tab) - text_width/2, 480 - int(sig['signal_strength']) - 40))\n\n \nclass Socket:\n def __init__(self):\n self.websocket = None\n\n async def startup(self):\n self.websocket = await websockets.connect(FFT_URL)\n\n async def updateFFT(self):\n return await self.websocket.recv()\n\nasync def main():\n \n window = pygame.display.set_mode((WIDTH, HEIGHT))\n pygame.mouse.set_visible(False)\n\n graphics = Graphics(WIDTH, HEIGHT)\n clock = Clock()\n socket = Socket()\n await socket.startup()\n\n while True:\n\n fft = await socket.updateFFT()\n window.fill(COL_BG)\n await graphics.update(window, fft)\n pygame.display.flip()\n \n await clock.tick(30)\n \n \nif __name__ == \"__main__\":\n pygame.init()\n asyncio.run(main())\n pygame.quit()","repo_name":"tomvdb/wb-clock","sub_path":"wb_clock.py","file_name":"wb_clock.py","file_ext":"py","file_size_in_byte":7129,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"1603162280","text":"\"\"\"\nAPI module\n\nCreating classes to learn a model, predict and\nserve these predictions.\n\n.. autosummary::\n :toctree:\n\n models\n train\n predict\n wsgi\n gini\n\"\"\"\nimport numpy as np\nfrom flask_restx import Resource, Namespace, fields, reqparse\nfrom flask import jsonify\nfrom loguru import logger\n\nfrom API import __version__\nfrom API.API.predict import predict\n\napi = Namespace('')\n\nmy_output = api.model(\"output\", {'version': fields.String})\n\n\n@api.route('/version')\nclass Version(Resource):\n \"\"\"\n Flask resource to spit current version\n \"\"\"\n @api.marshal_with(my_output)\n def get(self):\n logger.debug(\"Successful GET\")\n return {\"version\": __version__}\n\n\nstr_required = {\n 'type': str,\n 'required': True,\n 'default': None\n}\n\nint_required = {\n 'type': int,\n 'required': True,\n 'default': None\n}\n\nfloat_required = {\n 'type': float,\n 'required': True,\n 'default': None\n}\n\nbool_required = {\n 'type': bool,\n 'required': True,\n 'default': None\n}\n\n\ndef check_between_0_1(x):\n \"\"\"\n Checks if input is between 0 and 1.\n\n :param x: input\n :type x: float or int\n :return: x\n \"\"\"\n if not 0 <= x <= 1:\n logger.error(\"Invalid value for proportion_for_test: must be between 0 and 1.\")\n else:\n return x\n\n\nb0_1_required = {\n 'type': lambda x: check_between_0_1(x),\n 'required': True,\n 'default': None\n}\n\nb0_1_not_required = {\n 'type': lambda x: check_between_0_1(x),\n 'required': False,\n 'default': None\n}\n\npredict_parser = reqparse.RequestParser()\npredict_parser.add_argument('UserId',\n help='Description of UserId.',\n **str_required)\npredict_parser.add_argument('Event',\n help='Description of Event.',\n **str_required)\npredict_parser.add_argument('Category',\n help='Description of Category.',\n **str_required)\n\n\n@api.route('/predict')\nclass Predictor(Resource):\n \"\"\"\n Flask resource to predict\n \"\"\"\n def post(self):\n \"\"\"\n post method for Predictor resource: gets the new predictors in the request, predicts and outputs the score.\n ---\n parameters:\n - in: body\n name: body\n schema:\n id: Predict\n required:\n - UserId\n - Event\n - Category\n properties:\n Var_1:\n type: float\n description: Description of Var_1.\n Var_2:\n type: float\n description: Description of Var_2.\n Var_3:\n type: integer\n description: Description of Var_3.\n responses:\n 200:\n description: output of the model\n 400:\n description: model found but failed\n 500:\n description: all other server errors\n \"\"\"\n kwargs = predict_parser.parse_args(strict=True)\n logger.info(\"Successfully parsed arguments\")\n result = predict(**kwargs)\n logger.info(\"Successfully predicted\")\n\n if not result[\"is_fake_probability\"] == np.nan:\n response = jsonify(result)\n response.status_code = 200\n else:\n response = jsonify(\"Model failed\")\n response.status_code = 400\n\n return response\n","repo_name":"adimajo/mlitw2","sub_path":"API/API/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"24178247531","text":"import argparse\nimport json\nimport os\nfrom datetime import datetime, timedelta\n\ntry:\n from .src.apod import Apod\nexcept ImportError:\n from src.apod import Apod\n\n\nclass Main:\n def __init__(self):\n self.err = \"\"\n self.options: dict = {\n \"From a Single Day\": self.get_single_image, \n \"From a Range of Days\": self.get_range_images,\n \"From Random Days\": self.get_random_images,\n \"Since Last Requested Day\": self.get_from_last_image\n }\n\n def main(self):\n \"\"\"\n Entry point into script.\n \"\"\"\n\n print(\"Checking for existing images directory\")\n try:\n images_dir = self.setup()\n apod = Apod(images_dir)\n except ValueError as errv:\n print(errv)\n return 0\n\n args = self.get_args()\n try:\n args.func(apod, cmd_args=args)\n except ValueError as errv: # There was an error running the selected function\n print(errv)\n print(\"Quitting\")\n except AttributeError: # There were no arguments passed to the program\n while True:\n option = self.get_option()\n if option:\n self.set_err()\n break\n self.set_err(\"Invalid Option Number\")\n \n # Lookup the selected option name in the options dictionary and call the associated method value\n while True:\n try:\n self.options[option](apod)\n break\n except ValueError as errv:\n self.err = errv\n\n def set_err(self, message: str = \"\"):\n \"\"\"\"\n Sets the error message. If message is not specified, it will set error to an empty string.\n \"\"\"\n \n self.err = message\n\n def clear_screen(self):\n \"\"\"\n Run clear console command based on detected OS\n \"\"\"\n \n if os.name == 'nt':\n os.system('cls')\n else:\n os.system('clear')\n\n def get_args(self) -> argparse.Namespace:\n parser = argparse.ArgumentParser()\n subparsers = parser.add_subparsers(help=\"Method of pulling images\")\n \n single_day = subparsers.add_parser(\"single-day\",\n aliases = ['sd'],\n help=\"pull images from a single day\")\n single_day.add_argument(\"-d\", \"--date\", default=\"\", help=\"date to pull image from. YYYY-MM-DD format. defaults to today.\")\n single_day.set_defaults(func=self.get_single_image)\n \n range_days = subparsers.add_parser(\"range-days\",\n aliases = ['rgd'],\n help=\"pull images from a range of days\")\n range_days.add_argument(\"start_date\", help=\"first date in range. YYYY-MM-DD format\")\n range_days.add_argument(\"-e\", \"--end-date\", default=\"\", help=\"last date in range. YYYY-MM-DD format. defaults to today.\")\n range_days.set_defaults(func=self.get_range_images)\n\n random_days = subparsers.add_parser(\"random-days\",\n aliases = ['rnd'],\n help=\"pulls provided number of random images\")\n random_days.add_argument(\"count\", help=\"number of images to pull\")\n random_days.set_defaults(func=self.get_random_images)\n\n from_last_day = subparsers.add_parser(\"from-last-day\",\n aliases = ['fld'],\n help=\"pulls images between today and the last requested image date\")\n from_last_day.set_defaults(func=self.get_from_last_image)\n\n args = parser.parse_args()\n return args\n\n def setup(self):\n \"\"\"\n Checks if the images directory has already been set up. If it hasn't, create it and then run the create for every other directory and file needed.\n \"\"\"\n \n data_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"data\")\n images_path_file = os.path.join(data_dir, \"images_path.txt\")\n\n # Once an images directory has been chosen, it should be saved in ./data/images_path.txt\n # If the data directory or images_path.txt file don't exist, or if the file is empty, an images directory is not set.\n if os.path.exists(data_dir) and os.path.exists(images_path_file) and os.path.getsize(images_path_file) > 0:\n images_dir = self.load_images_dir(images_path_file)\n print(f\"Found {images_dir}\")\n else:\n self.clear_screen()\n images_dir = self.get_images_dir(data_dir)\n api_key = self.get_api_key()\n self.clear_screen()\n print(\"\\nSetting up file system\")\n self.create_dirs(data_dir, images_dir, api_key)\n self.save_image_dir(images_path_file, images_dir)\n if api_key == \"\":\n raise ValueError(f\"API Key not set.\\nPlease add API Key to api_key.txt located in {images_dir}\")\n\n return images_dir\n\n def get_images_dir(self, data_dir_path: str) -> str:\n \"\"\"\n Get the path of the desired image directory from the user\n If no path is specified, will set it to the data directory\n \"\"\"\n \n print(\"Provide a path to store the fetched images.\")\n print(\"The path should be the absolute path to the folder the images are to be placed in.\")\n images_dir = input(\" [./data/images]: \")\n if images_dir == \"\":\n images_dir = os.path.join(data_dir_path, \"images\")\n return images_dir\n\n def get_api_key(self) -> str:\n \"\"\"\n Prompt the user for their api key to add to api_key.txt\n If the user prefers to do it manually, the key can be left blank\n User must fill in key before running program\n \"\"\"\n \n print(\"\\nEnter API Key.\\nIf left blank, the program will exit after creating directories so you can add the key \\\nmanually to the api_key.txt file.\\nThis will be in the path you chose in the last step.\")\n api_key = input(\": \")\n return api_key\n\n def create_dirs(self, data_dir: str, images_dir: str, api_key: str) -> None:\n \"\"\"\n Creates the required directories and files if not already present.\n \"\"\"\n\n images_path_file = os.path.join(data_dir, \"images_path.txt\")\n api_key_file = os.path.join(data_dir, \"api_key.txt\")\n responses_file = os.path.join(data_dir, \"responses.json\")\n\n directories = [data_dir, images_dir, images_dir]\n files = [images_path_file, api_key_file, responses_file]\n\n for directory in directories:\n if not os.path.exists(directory):\n print(f\"Creating {directory}\")\n os.mkdir(directory)\n else:\n print(f\"Skipping {directory}. Already exists.\")\n\n for file in files:\n if not os.path.exists(file):\n print(f\"Creating {file}\")\n if file == api_key_file and api_key != \"\":\n with open(file, \"w\", encoding=\"utf-8\") as make_file:\n make_file.write(api_key)\n else:\n with open(file, \"x\", encoding=\"utf-8\") as make_file:\n pass\n else:\n print(f\"Skipping {file}. Already exists.\")\n\n # Save the path to the Apod Image Directory\n def save_image_dir(self, images_path_file: str, images_dir: str) -> None:\n \"\"\"\n Saves the path to the image directory to the data/images_path.txt file\n \"\"\"\n \n with open(images_path_file, \"w\", encoding=\"utf-8\") as images_file:\n images_file.write(images_dir)\n\n # Load the path to the Apod Image Directory\n def load_images_dir(self, images_path_file: str) -> None:\n \"\"\"\n Loads a saved image directory from data/images_path.txt\n \"\"\"\n \n with open(images_path_file, \"r\", encoding=\"utf-8\") as images_file:\n images_path = images_file.read()\n return images_path\n\n def get_option(self) -> str:\n \"\"\"\n Prompt for how images should be pulled.\n \"\"\"\n\n print(\"\\nNasa APOD Image Saver\\n\")\n option_names = list(self.options.keys())\n print(\"How should images be pulled?\\n\")\n for i, option in enumerate(option_names, start=1):\n print(f\"{i}. {option}\")\n print(self.err)\n option_num = input(\"