blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
281
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
6
116
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
313 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
18.2k
668M
star_events_count
int64
0
102k
fork_events_count
int64
0
38.2k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
107 values
src_encoding
stringclasses
20 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
4
6.02M
extension
stringclasses
78 values
content
stringlengths
2
6.02M
authors
listlengths
1
1
author
stringlengths
0
175
be1cb3e2ca6cfb578e3b4fa497d817263e0644a2
572236666850ab79611ed3b6da3aee3704f35afa
/leetcode/010/code01051.py
394c5ebb0084e23bf20b16ffb8d2d984376a7870
[]
no_license
denamyte/Python-misc
c9eee55232329299b7d12357579920c6517dbdd0
66fc2a9804868ad2408f1cfa3116b0901a950083
refs/heads/main
2023-08-18T12:33:40.256174
2021-10-23T21:54:28
2021-10-23T21:54:28
322,969,789
0
0
null
null
null
null
UTF-8
Python
false
false
671
py
from typing import List class Solution: def heightChecker(self, heights: List[int]) -> int: """ https://leetcode.com/problems/height-checker/ """ h = sorted(heights) moved = 0 for i in range(len(heights)): if heights[i] != h[i]: moved += 1 return moved index = 0 def test(ar: List[int], expected_moves: int): moves = Solution().heightChecker(ar) global index index += 1 print(f'''Test #{index}: array: {ar}; expected moves: {expected_moves}; actual moves: {moves}. ''') test([1, 1, 4, 2, 1, 3], 3) test([5, 1, 2, 3, 4], 5) test([1, 2, 3, 4, 5], 0)
[ "denamyte@gmail.com" ]
denamyte@gmail.com
4e0fd38b831e207c672c8e5a4a06d116ca4d223e
3dcd5c3d18b9b37d6ab93349f91a60aacd3c3de6
/service/app.py
99f903621efb133f982e6afb25936a1b57121bb7
[ "MIT" ]
permissive
jonnybazookatone/citation_helper_service
2f614e6f525e228ee90cbe2c7c75faf40b24b60e
dd9db7cfb5740429df3fe2f173c2b9ed71793e71
refs/heads/master
2021-01-17T18:04:15.765790
2015-11-10T16:41:59
2015-11-10T16:41:59
45,925,360
0
0
null
2015-11-10T16:38:10
2015-11-10T16:38:10
null
UTF-8
Python
false
false
1,379
py
from flask import Flask from views import CitationHelper from flask.ext.restful import Api from flask.ext.discoverer import Discoverer from flask.ext.consulate import Consul, ConsulConnectionError import logging.config def create_app(): """ Create the application and return it to the user :return: flask.Flask application """ app = Flask(__name__, static_folder=None) app.url_map.strict_slashes = False Consul(app) load_config(app) logging.config.dictConfig( app.config['CITATION_HELPER_LOGGING'] ) api = Api(app) api.add_resource(CitationHelper, '/') discoverer = Discoverer(app) return app def load_config(app): """ Loads configuration in the following order: 1. config.py 2. local_config.py (ignore failures) 3. consul (ignore failures) :param app: flask.Flask application instance :return: None """ app.config.from_pyfile('config.py') try: app.config.from_pyfile('local_config.py') except IOError: app.logger.warning("Could not load local_config.py") try: app.extensions['consul'].apply_remote_config() except ConsulConnectionError, e: app.logger.error("Could not apply config from consul: {}".format(e)) if __name__ == "__main__": app = create_app() app.run(debug=True, use_reloader=False)
[ "ehenneken@cfa.harvard.edu" ]
ehenneken@cfa.harvard.edu
66132fd2622620008df1bf5da31fc56479c8812c
f12dd0b2214882cbfa477e216a939becee16f70e
/myEnvironments/djangoPy3Env/bin/pip3.6
2605ddfa2c52e8ea2a1146a0c116ad666c67bbe8
[]
no_license
jupiterorbita/python_stack
b62e2ad9a0b893f6be855fb5b0c94a00ea54b23e
554b2dbd1853fbae6864c3bd64b25a91d7cbebb0
refs/heads/master
2020-03-16T00:09:43.986289
2018-05-22T20:01:56
2018-05-22T20:01:56
132,409,196
0
0
null
null
null
null
UTF-8
Python
false
false
277
6
#!/Users/jman/Desktop/CD/python_stack/myEnvironments/djangoPy3Env/bin/python3.6 # -*- coding: utf-8 -*- import re import sys from pip._internal import main if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit(main())
[ "john.williams@outlook.com" ]
john.williams@outlook.com
a2397630ed41926dd03f160daaf34fd7b95a8670
45ab4c22d918dc4390572f53c267cf60de0d68fb
/src/Analysis/Engine/Impl/Typeshed/third_party/2and3/werkzeug/_compat.pyi
74981331c7de5221f3fe7114e32b5f8d3c300296
[ "MIT", "Apache-2.0" ]
permissive
sourcegraph/python-language-server
580a24fd15fe9d4abeb95e9333d61db1c11a2670
64eae156f14aa14642afcac0e7edaf5d7c6d1a1c
refs/heads/master
2023-04-09T21:17:07.555979
2018-12-06T23:25:05
2018-12-06T23:25:05
155,174,256
2
2
Apache-2.0
2018-10-29T08:06:49
2018-10-29T08:06:49
null
UTF-8
Python
false
false
1,280
pyi
import sys from typing import Any if sys.version_info < (3,): import StringIO as BytesIO else: from io import StringIO as BytesIO PY2 = ... # type: Any WIN = ... # type: Any unichr = ... # type: Any text_type = ... # type: Any string_types = ... # type: Any integer_types = ... # type: Any iterkeys = ... # type: Any itervalues = ... # type: Any iteritems = ... # type: Any iterlists = ... # type: Any iterlistvalues = ... # type: Any int_to_byte = ... # type: Any iter_bytes = ... # type: Any def fix_tuple_repr(obj): ... def implements_iterator(cls): ... def implements_to_string(cls): ... def native_string_result(func): ... def implements_bool(cls): ... range_type = ... # type: Any NativeStringIO = ... # type: Any def make_literal_wrapper(reference): ... def normalize_string_tuple(tup): ... def try_coerce_native(s): ... wsgi_get_bytes = ... # type: Any def wsgi_decoding_dance(s, charset='', errors=''): ... def wsgi_encoding_dance(s, charset='', errors=''): ... def to_bytes(x, charset=..., errors=''): ... def to_native(x, charset=..., errors=''): ... def reraise(tp, value, tb=None): ... imap = ... # type: Any izip = ... # type: Any ifilter = ... # type: Any def to_unicode(x, charset=..., errors='', allow_none_charset=False): ...
[ "alsher@microsoft.com" ]
alsher@microsoft.com
938b8e7477a37f042c3b5d6c014c9bf48c7e6eea
d50205227e87eccd08e72db353fd62c4c9cf5549
/超好用的终端/syos.py
ba865cc15a1dac1a1a8aef99e901c81be8e45e93
[]
no_license
SanYuanAndy/python
d0e99553e447af885b219857eef84643ece1b70b
34be4747b7d9283f90c8333b0c89795e22a549ee
refs/heads/master
2021-01-12T07:31:39.526331
2018-10-24T02:48:02
2018-10-24T02:48:02
76,971,687
2
0
null
null
null
null
UTF-8
Python
false
false
4,127
py
#coding=utf8 import subprocess import time import threading import sys import Queue from syutil import print_t from syutil import print_n class writeThread(threading.Thread): def __init__(self, proc, target): threading.Thread.__init__(self) self.proc = proc self.target = target self.file = None self.proc_exited = False if target != None and len(target)!= 0: self.target = target try: self.file = open(self.target, 'w') except Exception, e: print_t(str(e)) def run(self): buf = '' while True: if self.proc.msg_queue.empty(): if len(buf) != 0: self.print_cache(buf) buf = '' msg = self.proc.msg_queue.get() buf = "%s%s"%(buf, msg) if len(msg) == 0: self.print_cache(buf)#输出缓存数据 buf = '' break if not self.proc_exited: print_n('>') if self.file != None: try: self.file.close() self.file = None except Exception, e: pass def print_cache(self, content): #两种可能不抛异常:1、不含中文。2、含中文、但是中文编码是utf8 try: content = content.decode('utf8').encode('gbk') except Exception, e: pass if self.file != None: self.file.write(content) else: print_n(content) def proc_wait(self): pass self.proc_exited = True class readThread(threading.Thread): def __init__(self, proc, target): threading.Thread.__init__(self) self.proc = proc def run(self): buffer = "" while True: #buffer = self.proc.stdout.readline()#直到读到换行符才会返回 #self.proc.stdout.read()#读到结束符才返回 #self.proc.stdout.read(count)#读到count个字节才返回 buffer = self.proc.proc.stdout.read(1) if len(buffer) == 0: ret = self.proc.isAlive() if ret: pass #print_t(ret) #continue self.proc.msg_queue.put(buffer) break self.proc.msg_queue.put(buffer) class SelfProcess: proc_cnt = 0 def __init__(self, sProcName, nTimeOut): temp = sProcName.split('>') self.sProcName = sProcName self.nTimeOut = nTimeOut #stdout = subprocess.PIPE表示子进程的标准输出会被重定向到特定管道,这样父进程和子进程就可以通讯了 #如果shell = True,表示目录执行程序,由Shell进程调起。 #中间会产生以下流程:创建shell(cmd)进程,shell(cmd)进程创建目标进程。这样的话,目标进程是本进程的孙子进程,而不是子进程 #可以推测,cmd窗口中命令行输出重定向到文件,应该也是这种实现方式 self.proc = subprocess.Popen(temp[0], stdin = subprocess.PIPE, stdout = subprocess.PIPE, shell = False) target =None if len(temp) == 2: target = temp[1].replace(" ", "") #print target if self.proc != None: self.msg_queue = Queue.Queue() self.t1 = readThread(self, target) self.t1.start() self.t2 = writeThread(self, target) self.t2.start() def terminate(self): if self.isAlive(): self.proc.terminate() def wait(self): if self.isAlive(): self.t2.proc_wait() self.t1.join(5) self.t2.join(5) def write(self, strInput): if self.isAlive(): self.proc.stdin.write(strInput) def isAlive(self): if self.proc != None and self.proc.poll() == None: return True else: return False if __name__ == '__main__': proc = SelfProcess("adb logcat -v time > yzs", 10)
[ "yuanmu zhao" ]
yuanmu zhao
a628c39bd53cea1ff8df84544f1156e18f04b8b5
a58d398cf4702e0ca085acefab86eba5a8d39fdc
/keywordjournal/__init__.py
3e64e4065ea223dcbc390405639d4c1309dfaaa1
[]
no_license
dnlk/keywordjournal
ffe3197de6fb9af4a486cec51b5eb3283763b848
3ae3e38ceacfd78f4fe4c565b4c73f1098ca418d
refs/heads/master
2020-05-20T09:02:39.807276
2017-10-07T02:27:11
2017-10-07T02:27:11
49,175,625
2
0
null
null
null
null
UTF-8
Python
false
false
45
py
# Author: Daniel Kinney # All rights reserved
[ "kinney.daniel.j@gmail.com" ]
kinney.daniel.j@gmail.com
0161da69528b89021b5f9ac89a7e9680621fe545
40d6b88cdc8b2fea3010b0438e2cd52f9241510d
/userspermissions/managers.py
503fe6105049285a17bfd35f5fa5115ed70c6314
[]
no_license
TannyS26/Enterprise-Resource-Planning
19e11d9375573fb9cffb1cbb19eb4eb8796a3d9b
452d74b1a302cd11fe7852f15d47842cbcf5eb4f
refs/heads/master
2022-07-19T02:59:36.026694
2020-05-16T08:14:05
2020-05-16T08:14:05
264,387,377
1
0
null
null
null
null
UTF-8
Python
false
false
1,376
py
from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import ugettext_lazy as _ class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) user = self.model( email=self.normalize_email(email), **extra_fields, ) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, password, **extra_fields)
[ "noreply@github.com" ]
noreply@github.com
62a430d7658748dc827ca7a1a71a21975277174b
2e70b3ce93762c5b66fba57f8b9cba37aacf0702
/new/account/migrations/0005_auto_20190528_1610.py
184bec8ce2a97ea9516a3f76e5495f0cfbb17c49
[]
no_license
mahidul-islam/jamah
02be511fe119e8934ec7d5aa1eaa8e2b24fad246
c8ddf9a8094d33e8b1d6cb834eab3d9f18b1a9ea
refs/heads/master
2022-05-13T15:11:38.609550
2019-06-08T04:52:09
2019-06-08T04:52:09
184,331,276
2
0
null
2022-04-22T21:27:18
2019-04-30T21:04:06
Python
UTF-8
Python
false
false
541
py
# Generated by Django 2.2.1 on 2019-05-28 16:10 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('account', '0004_account_mother_account'), ] operations = [ migrations.AlterField( model_name='transaction', name='comes_from', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='transaction_outs', to='account.Account'), ), ]
[ "mizihan84@gmail.com" ]
mizihan84@gmail.com
e140257cdc000876565032ee918fb13aca9affd4
26cedf237c596f38e9ca129151930c8ecae8898d
/visualise_music.py
9c3bde4b7100b1a1b0eb473f23efef65129e9e0b
[]
no_license
PrajwalSood/Metal.AI
707d019cec5398e67696c5d085527815254f0c71
e5eb67430a561eaeaec3875a41bfee1bf9554310
refs/heads/master
2023-04-01T18:00:26.941536
2021-04-08T11:32:08
2021-04-08T11:32:08
355,123,910
1
0
null
null
null
null
UTF-8
Python
false
false
528
py
# -*- coding: utf-8 -*- """ Created on Tue Apr 6 14:51:32 2021 @author: prajw """ from music21 import converter # Define data directory data_dir = 'data/' # Parse MIDI file and convert notes to chords score = converter.parse(data_dir+"Black Sabbath - Bassically.mid").chordify() # Display as sheet music - requires MuseScore 3 to be installed try: print(score.show()) except: print('Check your MuseScore 3 installation') #dispaly as text in console print(score.show('text')) print(score.elements[10].duration)
[ "prajwalsood@gmail.com" ]
prajwalsood@gmail.com
d911b045663d565be92524dcbdeb0dee537c4ee8
a72106acf426859b49be66ec7a1d209d8ffb59d1
/importer/indico_importer/converter.py
f8b138c0a1ca528382992688f5347a4d08c1ba43
[ "MIT" ]
permissive
indico/indico-plugins-attic
12502c891805e092b936c42a779fa9c667ee23d6
64a6bffe4dc7e30e2874dd4d6aac9908038910f1
refs/heads/master
2021-06-23T03:51:21.500524
2021-03-17T10:35:24
2021-03-17T10:35:24
201,440,329
1
0
null
null
null
null
UTF-8
Python
false
false
4,001
py
# This file is part of the Indico plugins. # Copyright (C) 2002 - 2020 CERN # # The Indico plugins are free software; you can redistribute # them and/or modify them under the terms of the MIT License; # see the LICENSE file for more details. from __future__ import unicode_literals APPEND = object() class RecordConverter(object): """ Converts a dictionary or list of dictionaries into another list of dictionaries. The goal is to alter data fetched from connector class into a format that can be easily read by importer plugin. The way dictionaries are converted depends on the 'conversion' variable. conversion = [ (sourceKey, destinationKey, conversionFuncion(optional), converter(optional))... ] It's a list tuples in which a single element represents a translation that will be made. Every element of the list is a tuple that consists of from 1 to 4 entries. The first one is the key name in the source dictionary, the value that applies to this key will be the subject of the translation. The second is the key in the destination dictionary at which translated value will be put. If not specified its value will be equal the value of the first element. If the second element is equal *append* and the converted element is a dictionary or a list of dictionaries, destination dictionary will be updated by the converted element.Third, optional, element is the function that will take the value from the source dictionary and return the value which will be inserted into result dictionary. If the third element is empty defaultConversionMethod will be called. Fourth, optional, element is a RecordConverter class which will be executed with converted value as an argument. """ conversion = [] @staticmethod def default_conversion_method(attr): """ Method that will be used to convert an entry in dictionary unless other method is specified. """ return attr @classmethod def convert(cls, record): """ Converts a single dictionary or list of dictionaries into converted list of dictionaries. """ if isinstance(record, list): return [cls._convert(r) for r in record] else: return [cls._convert(record)] @classmethod def _convert_internal(cls, record): """ Converts a single dictionary into converted dictionary or list of dictionaries into converted list of dictionaries. Used while passing dictionaries to another converter. """ if isinstance(record, list): return [cls._convert(r) for r in record] else: return cls._convert(record) @classmethod def _convert(cls, record): """ Core method of the converter. Converts a single dictionary into another dictionary. """ if not record: return {} converted_dict = {} for field in cls.conversion: key = field[0] if len(field) >= 2 and field[1]: converted_key = field[1] else: converted_key = key if len(field) >= 3 and field[2]: conversion_method = field[2] else: conversion_method = cls.default_conversion_method if len(field) >= 4: converter = field[3] else: converter = None try: value = conversion_method(record[key]) except KeyError: continue if converter: value = converter._convert_internal(value) if converted_key is APPEND: if isinstance(value, list): for v in value: converted_dict.update(v) else: converted_dict.update(value) else: converted_dict[converted_key] = value return converted_dict
[ "adrian.moennich@cern.ch" ]
adrian.moennich@cern.ch
7119c5b74f8e158542ca3c1bef363c1492989457
2e376c1e945cd1e8afb211d3f57d6773c33f9988
/create_symbol_file.py
beb6c06ff08bbfb8fb140ac04fe0f4c78aa653cf
[]
no_license
kjmeagher/nitrile
203c3d20ea116d737948593b51f605a3f35867bc
4667e0bd3eaf3e865cdd78be2693066fb8ace009
refs/heads/master
2016-08-10T10:02:51.864159
2015-12-27T18:37:13
2015-12-27T18:37:13
48,655,568
0
0
null
null
null
null
UTF-8
Python
false
false
6,060
py
#import ParseLatex import string from nitrile.latex.latex2e.latex2e import latex2e from nitrile.latex.latex2e.package_defs import Symbol whitespace = string.whitespace+u'\xa0'+u"\N{THIN SPACE}"+ u"\N{soft hyphen}" f=open("symbols.tex",'w') f.write(r"\documentclass{article}"+"\n"+ r"\begin{document}"+"\n" + r"\setlength{\columnsep}{1.5in}\twocolumn"+ "\n"+ r"\setlength\parindent{0pt}"+"\n" ) chars = [ chr(i) for i in range(32,128)] #print chars verb = '+' package = latex2e() #codes = sorted({ k for c in dir(package) if c.endswith("_codes") for k in getattr(package,c).keys()}) codes = [chr(c) for c in range(256)] n = 0 for code in codes: text_code = package.text_codes.get(code,package.verb_codes.get(code,None)) text_n = 1 text_code = package.text_codes.get(code,package.verb_codes.get(code,None)) if text_code is None: text_code = code if isinstance(text_code,basestring): if text_code in whitespace: text_n=0 else: text_code = text_code elif isinstance(text_code,type) and text_code.__name__=="Symbol": text_code = text_code.c elif isinstance(text_code,type) and text_code.__name__ == "MultiParser__": text_n=len(text_code.values) text_code = code else: text_n =0 text_code = " " math_n = 1 math_code = package.math_codes.get(code,package.text_codes.get(code,package.verb_codes.get(code,None))) if math_code is None: math_code = code if isinstance(math_code,basestring): if math_code in whitespace: math_n=0 else: math_code = math_code elif isinstance(math_code,type) and math_code.__name__=="Symbol": math_code = math_code.c elif isinstance(math_code,type) and math_code.__name__ == "MultiParser__": math_n= len(math_code.values) math_code = code else: math_n=0 math_code = " " if code == verb: v = chr(ord(verb)+1) else: v = verb #if text_code not in whitespace or math_code not in whitespace: for i in range(1,max(text_n,math_n)+1): print repr(code),repr(i*code),repr(text_code),repr(math_code),i,text_n,math_n s = i*code+"\\hfill$" + i*code +"$\\hfill\\verb"+v+i*code+v #print c,d,repr(s) f.write(s+'\n\n') if math_n or text_n: n+=1 if n >5: break f.write('\pagebreak\n\n') cmds = sorted({ k for c in dir(package) if c.endswith("_cmds") for k in getattr(package,c).keys()}) n = 0 for cmd in cmds: text_info = package.all_cmds.get(cmd,package.text_cmds.get(cmd,None)) if isinstance(text_info,basestring): text_cmd = cmd elif isinstance(text_info,type) and text_info.__name__=="Symbol" and text_info.c not in whitespace: print repr(text_info.c) text_cmd = cmd elif isinstance(text_info,type) and text_info.__name__ == "MultiParser__": text_cmd = cmd else: text_cmd = " " math_info = package.all_cmds.get(cmd,package.math_cmds.get(cmd,None)) if isinstance(math_info,basestring): math_cmd = cmd elif isinstance(math_info,type) and math_info.__name__=="Symbol" and math_info.c not in whitespace: math_cmd = cmd elif isinstance(math_info,type) and math_info.__name__ == "MultiParser__": math_cmd = cmd else: math_cmd = " " if verb in cmd: v = chr(ord(verb)+1) else: v = verb if text_cmd not in whitespace or math_cmd not in whitespace: print repr(text_cmd),repr(math_cmd) s = "\\"+text_cmd+"\\hfill$\\" + math_cmd +"$\\hfill\\verb"+verb+"\\"+cmd+verb #print c,d,repr(s) f.write(s+'\n\n') n +=1 if n > 5: break #else: # print "ERROR", repr(cmd) """ print repr(string.whitespace) for mode,a,b in [ ("all","",""), #("all","$","$"), #("text","",""), #("math","$","$") ]: commands = getattr(latex2e(),mode+"_commands") f.write(r"\section{"+mode+" Symbols}"+'\n') n =0 for c,d in sorted(commands.items()): if type(d).__name__ == "instance" and d.__class__.__name__=="symbol": if c in chars: chars.remove(c) s = a+"\\"+c+b+"\\hfill\\verb"+verb+"\\"+c+verb print c,d,repr(s) f.write(s+'\n\n') n+=1 if n > 5: break #f.write(r"\section{"+mode+" Accents}"+'\n') #for c,d in sorted(commands.items()): # print c,d,type(d) # if type(d).__name__ == "instance" and d.__class__.__name__=="combining": # s="" # for char in ['A','E','I','O','U','a','e','i','o','u','\i']: ## s+= a+"\\"+c+"{"+char+"}"+b # s+="\\hfill\\verb"+verb+"\\"+c+verb # print repr(s) # f.write(s+'\n\n') """ """ f.write(r"\section{Math Accents}"+'\n') for c,d in sorted(ParseLatex.math_commands.items()): if type(d) == dict and d.get('element',None)=="combining": s="$" for char in ['A','E','I','O','U','a','e','i','o','u','\imath']: s+= "{\\"+c+' '+char+'}' s+="$\\hfill\\verb"+verb+"\\"+c+verb print repr(s) f.write(s+'\n\n') f.write(r"\section{Text Symbols}"+'\n') for c,d in sorted(ParseLatex.text_commands.items()): if type(d) == dict and d.get('element',None)=="symbol": if c in chars: chars.remove(c) s = "\\"+c+"\\hfill\\verb"+verb+"\\"+c+verb print repr(s) f.write(s+'\n\n') f.write(r"\section{Math Symbols}"+'\n') for c,d in sorted(ParseLatex.math_commands.items()): if type(d) == dict and d.get('element',None)=="symbol": if c in chars: chars.remove(c) s = "$\\"+c+"$\\hfill\\verb"+verb+"\\"+c+verb print repr(s) f.write(s+'\n\n') """ print verb in chars f.write(r'\end{document}'+'\n\n') f.close()
[ "kmeagher@ulb.ac.be" ]
kmeagher@ulb.ac.be
49be7f76c9ec89e45b8a74c10f33d65ad424437b
f3e816f6469f19b2d31adf396cbec30e78eef83f
/chapter15/15.24.py
c7ef2767540858393e75c136b4c6f6b5bb09d15e
[]
no_license
CUGshadow/Solution_to_Daniel_Liang_python_exercises
976d267217cd09fde20549768aea0a4abf7bb1d9
6beaa3b143253a88660f8d54a2012762dd5f731b
refs/heads/master
2023-03-23T02:11:33.226402
2019-02-22T05:32:51
2019-02-22T05:32:51
null
0
0
null
null
null
null
UTF-8
Python
false
false
578
py
# (Number of files in a directory) Write a program that prompts the user to enter a # directory and displays the number of files in the directory. import os def getNumberOfFiles(path): count = 0 if not os.path.isfile(path): lst = os.listdir(path) for subdirectory in lst: count += getNumberOfFiles(path + "\\" + subdirectory) else: count += 1 return count def test(): inputDirectory = input("Enter a directory:") print("Total number of files inside the directory is", str(getNumberOfFiles(inputDirectory))) test()
[ "noreply@github.com" ]
noreply@github.com
2ebd509922758a17835e51eedfb03ade0b3c5743
4766f861b7e3eecf2dae050590e10d5b9b49545d
/course/migrations/0001_initial.py
c387881bbc721bbdcafb3ac6478e3a0d4bbf8bd7
[]
no_license
moramadan98/Clever
4fc1965050a559a92b42bcb4c8a6ce64d7c4304a
45ddd59da8a4ff9f48a20c3d5ecf023bda3ab8be
refs/heads/master
2022-12-04T09:17:55.414454
2020-08-15T17:18:08
2020-08-15T17:18:08
287,759,140
0
0
null
null
null
null
UTF-8
Python
false
false
1,923
py
# Generated by Django 3.1 on 2020-08-15 15:45 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Category', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=150)), ], ), migrations.CreateModel( name='Course', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=150)), ('instructor', models.CharField(max_length=150)), ('duration', models.IntegerField(default=1)), ('leactures', models.IntegerField(default=1)), ('quizzes', models.IntegerField(default=0)), ('price', models.IntegerField(default=0)), ('description', models.TextField(max_length=200)), ('certification', models.CharField(choices=[('yes', 'yes'), ('no', 'no')], max_length=5)), ('image', models.ImageField(upload_to='course/')), ('category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='course.category')), ], ), migrations.CreateModel( name='Apply', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ('email', models.EmailField(max_length=254)), ('course', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='course.course')), ], ), ]
[ "aboellamm@gmail.com" ]
aboellamm@gmail.com
8c3b5e2281d80a86b3c7c5c5f51f8ef6abd109c6
4ec6e157a1420096bfef27de7262734a2d5207d2
/san/target/__init__.py
7d02f7f8691e7e11fcbe63995ce9b95e4a76b003
[]
no_license
akatrevorjay/solarsan-simple
e4800b87093da1e86a401279c50fc07bc8687a20
4b3f58da40a5596d52454907d80fdfca1c6807a3
refs/heads/master
2021-01-18T12:36:28.854915
2014-01-29T19:07:03
2014-01-29T19:07:03
15,594,879
0
0
null
null
null
null
UTF-8
Python
false
false
19,448
py
import logging log = logging.getLogger(__name__) import os from uuid import uuid4 from .. import conf from ..utils.exceptions import FormattedException, ignored from ..storage import ZVolume from .rtsutils import generate_wwn, is_valid_wwn from .scst import scstsys class TargetBaseException(FormattedException): pass def dictattrs(**attrs): return '; '.join(['%s=%s' % (k, v) for k, v in attrs.iteritems()]) def get_handler(handler): return getattr(scstsys.handlers, handler, None) def get_driver(driver): return getattr(scstsys.targets, driver, None) def get_target(driver, target): driver = get_driver(driver) if not driver: return return getattr(driver, target, None) def get_ini_group(driver, target, group): tgt = get_target(driver, target) if not tgt: return return getattr(tgt.ini_groups, group, None) class BackStoreError(TargetBaseException): pass class BackStoreActiveError(BackStoreError): pass class BackStoreNotActiveError(BackStoreError): pass class BackStore(object): # Name name = None # Handler handler = None class handlers: """ SCST BackStore Handler Choices """ BLOCKIO = 'vdisk_blockio' FILEIO = 'vdisk_fileio' # Checks/Helpers @property def active(self): return bool(str(self.name) in scstsys.devices) # SCST helpers @property def _scsthnd(self): return get_handler(self.handler) @property def _scstdev(self): return getattr(scstsys.devices, self.name, None) # attributes attributes = None @property def _scstattrs(self): if self.attributes: return dictattrs(**self.attributes) else: return '' # Config def load(self): #TODO load target from config raise NotImplementedError() def save(self): #TODO save target to config raise NotImplementedError() # Operations def start(self, target, group): log.debug('Starting backstore %s for Group %s Target %s', self, group, target) with ignored(BackStoreActiveError): self.open() return True def stop(self, target, group): log.debug('Stopping backstore %s for Group %s Target %s', self, group, target) # TODO What about a backstore that's used in multiple groups or targets? with ignored(BackStoreNotActiveError): self.close() return True def open(self): if self.active: raise BackStoreActiveError(self) log.debug('Opening backstore device %s', self) self._scsthnd.mgmt = 'add_device {0.name} {0._scstattrs}'.format(self) return True def close(self): if not self.active: raise BackStoreNotActiveError(self) log.debug('Closing backstore device %s', self) self._scsthnd.mgmt = 'del_device {0.name}'.format(self) return True def resync_size(self): if not self.active: raise BackStoreNotActiveError(self) log.debug('Resyncing backstore device %s', self) self._scstdev.resync_size = 0 return True class BlockDeviceBackStore(BackStore): # Device path path = None # Handler handler = BackStore.handlers.BLOCKIO @property def attributes(self): return dict(filename=self.path) @property def available(self): # TODO Should really check if it's RW if not self.is_active I suppose return os.path.exists(self.path) class ZVolumeBackStore(BlockDeviceBackStore): # ZVolume name volume_name = None @classmethod def from_zvolume(cls, volume): self = cls() self.volume = volume return self # ZVolume helper, it's possible that the zvolume could no longer exist, so # be wary of such. _volume = None @property def volume(self): """ Returns ZVolume object. """ if not self._volume: self._volume = ZVolume.open(self.volume_name) return self._volume @volume.setter def volume(self, zvol): if not zvol.exists(): raise ValueError('ZVolume "%s" does not exist.' % zvol) self._volume = zvol self.volume_name = zvol.name # TODO Maybe this should be done only if we don't have one or are # closed? This could leave opened zombie backstores. self.name = self.volume_name.replace('/', '__') @property def path(self): """ Returns path of ZVolume block device. """ return '/dev/zvol/%s' % self.volume_name class AclError(FormattedException): pass class Acl(object): # List of allowed initiators initiators = None # TODO insecure option #insecure = m.BooleanField() # TODO chap auth #chap = m.BooleanField() #chap_user = m.StringField() #chap_pass = m.StringField() def start(self, target, group): log.debug('Starting %s for %s for %s', self, group, target) return self.add_to_target_portal_group(target, group) def stop(self, target, group): log.debug('Stopping %s for %s for %s', self, group, target) return self.remove_from_target_portal_group(target, group) def add_to_target_portal_group(self, target, group): ini_group = get_ini_group(target.driver, target.name, group.name) if not ini_group: log.warn('Cannot get target %s portal group %s initiator group.', target, group) return for initiator in self.initiators: if initiator in ini_group.initiators: continue log.debug('Adding intiator %s for %s for %s for %s', initiator, self, group, target) ini_group.initiators.mgmt = 'add %s' % initiator def remove_from_target_portal_group(self, target, group): ini_group = get_ini_group(target.driver, target.name, group.name) if not ini_group: log.warn('Cannot get target %s portal group %s initiator group.', target, group) return for initiator in self.initiators: if initiator not in ini_group.initiators: continue log.debug('Removing initiator %s for %s for %s for %s', initiator, self, group, target) ini_group.initiators.mgmt = 'del %s' % initiator # TODO This should not happen. We want to be able to append # multiple Acls self.remove_all_from_target_portal_group(target, group) def remove_all_from_target_portal_group(self, target, group): ini_group = get_ini_group(target.driver, target.name, group.name) if not ini_group: log.warn('Cannot get target %s portal group %s initiator group.', target, group) return log.debug('Clearing all initiators for %s for %s for %s', self, group, target) ini_group.initiators.mgmt = 'clear' class PortalGroupError(TargetBaseException): pass class PortalGroup(object): # Name name = None # List of BackStores luns = None # Acl acl = None def __init__(self): self.acl = Acl() self.luns = list() def is_active_on_target(self, target): tgt = get_target(target.driver, target.name) return tgt and self.name in tgt.ini_groups def start(self, target): log.debug('Starting PortalGroup %s for Target %s', self, target) self._add_portal_group(target) self._add_acl(target) self._add_luns(target) return True def stop(self, target): log.debug('Stopping Group %s for Target %s', self, target) self._remove_luns(target) self._remove_acl(target) self._remove_portal_group(target) return True def _add_portal_group(self, target): if not self.is_active_on_target(target): log.debug('Adding PortalGroup %s for Target %s', self, target) tgt = get_target(target.driver, target.name) if not tgt: raise PortalGroupError('Could not get target {0.name}'.format(target)) tgt.ini_groups.mgmt = 'create %s' % self.name return True def _remove_portal_group(self, target): if self.is_active_on_target(target): log.debug('Removing Group %s for Target %s', self, target) tgt = get_target(target.driver, target.name) if not tgt: raise PortalGroupError('Could not get target {0.name}'.format(target)) tgt.ini_groups.mgmt = 'del %s' % self.name def _add_acl(self, target): log.debug('Adding Acl %s for Group %s for Target %s', self.acl, self, target) return self.acl.start(target, self) def _remove_acl(self, target): log.debug('Removing Acl %s for Group %s for Target %s', self.acl, self, target) return self.acl.stop(target, self) def _add_luns(self, target): ini_group = get_ini_group(target.driver, target.name, self.name) for lun, backstore in enumerate(self.luns): lun += 1 if not backstore.active: log.debug('Starting backstore %s for %s for %s', backstore, self, target) backstore.start(target, self) if not str(lun) in ini_group.luns: log.debug('Adding lun %d with backstore %s for %s for %s', lun, backstore, self, target) """parameters: read_only""" ini_group.luns.mgmt = 'add {0.name} {1}'.format(backstore, lun) def _remove_luns(self, target): ini_group = get_ini_group(target.driver, target.name, self.name) for lun, backstore in enumerate(self.luns): lun += 1 if ini_group and str(lun) in ini_group.luns: log.debug('Removing lun %d with backstore %s for %s for %s', lun, backstore, self, target) ini_group.luns.mgmt = 'del {0}'.format(lun) if backstore.active: # TODO What about backstores that are being used by other # target/pgs? log.debug('Stopping backstore %s for Group %s Target %s', backstore, self, target) backstore.stop(target, self) # TODO We shoudn't have to do this. # Clear out luns for group, to be safe self._remove_all_luns(target) def _remove_all_luns(self, target): if self.is_active_on_target(target): ini_group = get_ini_group(target.driver, target.name, self.name) ini_group.luns.mgmt = 'clear' #@property #def attributes(self): # """The following target driver attributes available: IncomingUser, OutgoingUser # The following target attributes available: IncomingUser, OutgoingUser, allowed_portal # """ # # How to require chap auth for discovery: # #422 echo "192.168.1.16 AccessControl" >/sys/kernel/scst_tgt/targets/iscsi/iSNSServer # #423 echo "add_attribute IncomingUser joeD 12charsecret" >/sys/kernel/scst_tgt/targets/iscsi/mgmt # #424 echo "add_attribute OutgoingUser jackD 12charsecret1" >/sys/kernel/scst_tgt/targets/iscsi/mgmt # return dict( # #IncomingUser='test testtesttesttest', # #IncomingUser1='test1 testtesttesttest1', # #OutgoingUser='test testtesttesttest', # ) # #def _add_group_attrs(self): # ini_group = get_ini_group(target.driver, target.name, self.name) # # #log.debug('Adding %s attributes.', self) # attributes = self.attributes # if attributes: # log.debug('Adding attribute to %s: %s', self, attributes) # for k, v in self.attributes.iteritems(): # ini_group.mgmt = 'add_target_attribute {0.name} {1} {2}'.format(self, k, v) class Target(object): name = None uuid = None # Initiator groups groups = None def __init__(self, name=None, uuid=None, groups=None): #if not name: # pass self.name = name if not uuid: uuid = uuid4() self.uuid = uuid if not groups: groups = list() self.groups = groups def save(self, *args, **kwargs): raise NotImplementedError() def start(self): log.info('Starting %s', self) self._add_target() for group in self.groups: group.start(target=self) self.enabled = True self.driver_enabled = True def stop(self): log.info('Stopping %s', self) if self.added: for group in self.groups: group.stop(target=self) self.enabled = False self._del_target() self.driver_enabled = False def get_all_luns(self): for group in self.groups: for lun in group.luns: yield lun def get_all_lun_devices(self): devices = [] for lun in self.get_all_luns(): dev = lun.device if dev not in devices: devices.append(dev) yield dev def get_all_unavailable_luns(self): for lun in self.get_all_luns(): if not lun.is_available(): yield lun # TODO Temp hack @property def devices(self): for lun in self.get_all_luns(): # TODO what about volume backstores? dev = lun.resource yield dev @property def _scstdrv(self): return get_driver(self.driver) @property def added(self): return self.name in self._scstdrv @added.setter def added(self, value): if value is True: if not self.added: self._add_target() else: if self.added: self._del_target() is_added = added @property def parameters(self): return dictattrs( #rel_tgt_id=randrange(1000, 3000), #read_only=int(False), ) def _add_target(self): log.debug('Adding %s', self) if not self.is_added: drv = self._scstdrv parameters = self.parameters if parameters: log.debug('Parameters for %s: %s', self, parameters) drv.mgmt = 'add_target {0.name} {1}'.format(self, parameters) self._add_target_attrs() @property def attributes(self): """The following target driver attributes available: IncomingUser, OutgoingUser The following target attributes available: IncomingUser, OutgoingUser, allowed_portal """ # How to require chap auth for discovery: #422 echo "192.168.1.16 AccessControl" >/sys/kernel/scst_tgt/targets/iscsi/iSNSServer #423 echo "add_attribute IncomingUser joeD 12charsecret" >/sys/kernel/scst_tgt/targets/iscsi/mgmt #424 echo "add_attribute OutgoingUser jackD 12charsecret1" >/sys/kernel/scst_tgt/targets/iscsi/mgmt return dict( #IncomingUser='test testtesttesttest', #IncomingUser1='test1 testtesttesttest1', #OutgoingUser='test testtesttesttest', ) def _add_target_attrs(self): #log.debug('Adding %s attributes.', self) attributes = self.attributes if attributes: log.debug('Adding attribute to %s: %s', self, attributes) for k, v in self.attributes.iteritems(): self._scstdrv.mgmt = 'add_target_attribute {0.name} {1} {2}'.format(self, k, v) def _del_target(self): log.debug('Removing Target %s', self) if self.is_added: self._del_target_attrs() drv = self._scstdrv drv.mgmt = 'del_target {0.name}'.format(self) def _del_target_attrs(self): log.debug('Removing %s attributes.', self) attributes = self.attributes if attributes: drv = self._scstdrv log.debug('Removing attribute to %s: %s', self, attributes) for k, v in self.attributes.iteritems(): try: drv.mgmt = 'del_target_attribute {0.name} {1} {2}'.format(self, k, v) except IOError: pass @property def enabled(self): tgt = get_target(self.driver, self.name) if not tgt: return False return bool(tgt.enabled) @enabled.setter def enabled(self, value): if not self.added: return if value == self.enabled: return tgt = get_target(self.driver, self.name) if value: log.debug('Enabling Target %s', self) else: log.debug('Disabling Target %s', self) value = int(bool(value)) if tgt.enabled != value: tgt.enabled = value is_enabled = enabled # TODO This does not belong here, it belongs in a Driver class. @property def driver_enabled(self): drv = get_driver(self.driver) if not drv: return False return bool(int(drv.enabled)) # TODO This does not belong here, it belongs in a Driver class. @driver_enabled.setter def driver_enabled(self, value): drv = get_driver(self.driver) if not drv: return False value = int(bool(value)) if value == self.driver_enabled: return for root, dirs, files in os.walk(drv._path_): break drv_subdir_count = len(dirs) # TODO Driver class that handles it's own parameters and shit if value: log.info('Enabling iSNS server with access control.') drv.iSNSServer = 'localhost AccessControl' if not value and drv_subdir_count: log.info('Not disabling driver %s as it is currently in use.', self.driver) return elif not value: log.info('Disabling driver %s as it is no longer in use.', self.driver) else: log.info('Enabling driver %s.', self.driver) drv.enabled = value def __unicode__(self): return self.__repr__() @classmethod def search_hard(cls, **kwargs): if not kwargs: return for subcls in cls.__subclasses__(): try: qs = subcls.objects.get(**kwargs) return qs except subcls.DoesNotExist: pass class iSCSITarget(Target): driver = 'iscsi' #portal_port = m.IntField() def generate_wwn(self, serial=None): self.name = generate_wwn('iqn') return True def save(self, *args, **kwargs): """Overrides save to ensure name is a valid iqn; generates one if None""" if self.name: if not is_valid_wwn('iqn', self.name): raise ValueError("The name '%s' is not a valid iqn" % self.name) else: self.generate_wwn() super(iSCSITarget, self).save(*args, **kwargs) class SRPTarget(Target): #driver = 'srpt' driver = 'iscsi' @property def _scstdrv(self): #if not hasattr(self, '_scstdrv_cache') or self._scstdrv_cache_verify != self.driver: # self._scstdrv_cache = get_driver(self.driver) # self._scstdrv_cache_verify = self.driver #return self._scstdrv_cache return get_driver(self.driver)
[ "trevorj@skywww.net" ]
trevorj@skywww.net
f39c546e73926e4b6dde4a1c3d565c4484856f29
dc308f01a03cc5acbf1acf93b05b306b36841648
/myapp/models.py
0528ad2cd82dfa505df99311a99bb1baa0642369
[]
no_license
swamyanvitha/blog
bd978565f31830108efbfe04892bb8a17738bf2c
0d6990ec67e5ee13292e7a5238c402b7fbdfcc5a
refs/heads/master
2022-04-18T10:56:12.071669
2020-04-15T12:17:45
2020-04-15T12:17:45
255,903,624
0
0
null
null
null
null
UTF-8
Python
false
false
127
py
from django.db import models # Create your models here. class Person(models.Model): name = models.CharField(max_length = 30)
[ "swamy.anvitha@vitap.ac.in" ]
swamy.anvitha@vitap.ac.in
a5ae930e8fe263663440b7fda29bd5a056e44d78
b589f3997e790c3760ab6ddce1dd1b7813cfab3a
/232.py
e2c5834920299064245bc4ccf2a5c4e5fe64f1ff
[]
no_license
higsyuhing/leetcode_easy
56ceb2aab31f7c11671d311552aaf633aadd14a8
48d516fdbb086d697e2593a9ce1dbe6f40c3c701
refs/heads/master
2022-12-04T00:49:33.894066
2022-11-15T20:44:36
2022-11-15T20:44:36
135,224,120
0
0
null
null
null
null
UTF-8
Python
false
false
2,159
py
class MyQueue(object): def __init__(self): """ Initialize your data structure here. """ self.stack1 = [] self.stack2 = [] self.slen = 0 self.curr = 1 # push stack, 2 for pop stack def push(self, x): """ Push element x to the back of queue. :type x: int :rtype: void """ if self.curr == 1: self.stack1.append(x) self.slen = self.slen + 1 pass else: for index in range(self.slen): self.stack1.append(self.stack2.pop()) pass self.stack1.append(x) self.slen = self.slen + 1 self.curr = 1 pass return def pop(self): """ Removes the element from in front of queue and returns that element. :rtype: int """ if self.slen == 0: print "Error! " return 0 if self.curr == 1: for index in range(self.slen-1): self.stack2.append(self.stack1.pop()) pass self.slen = self.slen - 1 self.curr = 2 return self.stack1.pop() else: self.slen = self.slen - 1 return self.stack2.pop() pass def peek(self): """ Get the front element. :rtype: int """ if self.slen == 0: print "Error! " return 0 if self.curr == 1: for index in range(self.slen): self.stack2.append(self.stack1.pop()) pass self.curr = 2 return self.stack2[self.slen-1] else: return self.stack2[self.slen-1] pass def empty(self): """ Returns whether the queue is empty. :rtype: bool """ if self.slen == 0: return True else: return False # Your MyQueue object will be instantiated and called as such: # obj = MyQueue() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.peek() # param_4 = obj.empty()
[ "noreply@github.com" ]
noreply@github.com
ae5e290bc78c26ac181b86513279b342823c5f81
da407694ec45f9dea19546bfcf81e41ac6f58a86
/dataloader/yolov3_parser.py
fe27983903b67be012bd78949440136966d0cadb
[]
no_license
lucifer443/Yolov3_tensorflow-keras
ca273cae1ff2a376ca3956df1551aa9a4e89d1a6
9c44391876f91b66a60b4e04e428fc896072c2fb
refs/heads/master
2022-12-17T15:46:03.751463
2020-09-22T16:11:07
2020-09-22T16:11:07
294,705,195
0
0
null
null
null
null
UTF-8
Python
false
false
17,962
py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Data parser and processing. Parse image and ground truths in a dataset to training targets and package them into (image, labels) tuple for RetinaNet. T.-Y. Lin, P. Goyal, R. Girshick, K. He, and P. Dollar Focal Loss for Dense Object Detection. arXiv:1708.02002 """ import tensorflow as tf from dataloader import anchor from dataloader import mode_keys as ModeKeys from dataloader import tf_example_decoder from utils import autoaugment_utils from utils import box_utils from utils import input_utils def process_source_id(source_id): """Processes source_id to the right format.""" if source_id.dtype == tf.string: source_id = tf.cast(tf.strings.to_number(source_id), tf.int32) with tf.control_dependencies([source_id]): source_id = tf.cond( pred=tf.equal(tf.size(input=source_id), 0), true_fn=lambda: tf.cast(tf.constant(-1), tf.int32), false_fn=lambda: tf.identity(source_id)) return source_id def pad_groundtruths_to_fixed_size(gt, n): """Pads the first dimension of groundtruths labels to the fixed size.""" gt['boxes'] = input_utils.pad_to_fixed_size(gt['boxes'], n, -1) gt['is_crowds'] = input_utils.pad_to_fixed_size(gt['is_crowds'], n, 0) gt['areas'] = input_utils.pad_to_fixed_size(gt['areas'], n, -1) gt['classes'] = input_utils.pad_to_fixed_size(gt['classes'], n, -1) return gt class Parser(object): """Parser to parse an image and its annotations into a dictionary of tensors.""" def __init__(self, output_size, min_level, max_level, num_scales, aspect_ratios, anchor_size, match_threshold=0.5, unmatched_threshold=0.5, aug_rand_hflip=False, aug_scale_min=1.0, aug_scale_max=1.0, use_autoaugment=False, autoaugment_policy_name='v0', skip_crowd_during_training=True, max_num_instances=100, use_bfloat16=True, mode=None): """Initializes parameters for parsing annotations in the dataset. Args: output_size: `Tensor` or `list` for [height, width] of output image. The output_size should be divided by the largest feature stride 2^max_level. min_level: `int` number of minimum level of the output feature pyramid. max_level: `int` number of maximum level of the output feature pyramid. num_scales: `int` number representing intermediate scales added on each level. For instances, num_scales=2 adds one additional intermediate anchor scales [2^0, 2^0.5] on each level. aspect_ratios: `list` of float numbers representing the aspect raito anchors added on each level. The number indicates the ratio of width to height. For instances, aspect_ratios=[1.0, 2.0, 0.5] adds three anchors on each scale level. anchor_size: `float` number representing the scale of size of the base anchor to the feature stride 2^level. match_threshold: `float` number between 0 and 1 representing the lower-bound threshold to assign positive labels for anchors. An anchor with a score over the threshold is labeled positive. unmatched_threshold: `float` number between 0 and 1 representing the upper-bound threshold to assign negative labels for anchors. An anchor with a score below the threshold is labeled negative. aug_rand_hflip: `bool`, if True, augment training with random horizontal flip. aug_scale_min: `float`, the minimum scale applied to `output_size` for data augmentation during training. aug_scale_max: `float`, the maximum scale applied to `output_size` for data augmentation during training. use_autoaugment: `bool`, if True, use the AutoAugment augmentation policy during training. autoaugment_policy_name: `string` that specifies the name of the AutoAugment policy that will be used during training. skip_crowd_during_training: `bool`, if True, skip annotations labeled with `is_crowd` equals to 1. max_num_instances: `int` number of maximum number of instances in an image. The groundtruth data will be padded to `max_num_instances`. use_bfloat16: `bool`, if True, cast output image to tf.bfloat16. mode: a ModeKeys. Specifies if this is training, evaluation, prediction or prediction with groundtruths in the outputs. """ self._mode = mode self._max_num_instances = max_num_instances self._skip_crowd_during_training = skip_crowd_during_training self._is_training = (mode == ModeKeys.TRAIN) self._example_decoder = tf_example_decoder.TfExampleDecoder( include_mask=False) # Anchor. self._output_size = output_size self._min_level = min_level self._max_level = max_level self._num_scales = num_scales self._aspect_ratios = aspect_ratios self._anchor_size = anchor_size self._match_threshold = match_threshold self._unmatched_threshold = unmatched_threshold # Data augmentation. self._aug_rand_hflip = aug_rand_hflip self._aug_scale_min = aug_scale_min self._aug_scale_max = aug_scale_max # Data Augmentation with AutoAugment. self._use_autoaugment = use_autoaugment self._autoaugment_policy_name = autoaugment_policy_name # Device. self._use_bfloat16 = use_bfloat16 # Data is parsed depending on the model Modekey. if mode == ModeKeys.TRAIN: self._parse_fn = self._parse_train_data elif mode == ModeKeys.EVAL: self._parse_fn = self._parse_eval_data elif mode == ModeKeys.PREDICT or mode == ModeKeys.PREDICT_WITH_GT: self._parse_fn = self._parse_predict_data else: raise ValueError('mode is not defined.') def __call__(self, value): """Parses data to an image and associated training labels. Args: value: a string tensor holding a serialized tf.Example proto. Returns: image: image tensor that is preproessed to have normalized value and dimension [output_size[0], output_size[1], 3] labels: cls_targets: ordered dictionary with keys [min_level, min_level+1, ..., max_level]. The values are tensor with shape [height_l, width_l, anchors_per_location]. The height_l and width_l represent the dimension of class logits at l-th level. box_targets: ordered dictionary with keys [min_level, min_level+1, ..., max_level]. The values are tensor with shape [height_l, width_l, anchors_per_location * 4]. The height_l and width_l represent the dimension of bounding box regression output at l-th level. num_positives: number of positive anchors in the image. anchor_boxes: ordered dictionary with keys [min_level, min_level+1, ..., max_level]. The values are tensor with shape [height_l, width_l, 4] representing anchor boxes at each level. image_info: a 2D `Tensor` that encodes the information of the image and the applied preprocessing. It is in the format of [[original_height, original_width], [scaled_height, scaled_width], [y_scale, x_scale], [y_offset, x_offset]]. groundtruths: source_id: source image id. Default value -1 if the source id is empty in the groundtruth annotation. boxes: groundtruth bounding box annotations. The box is represented in [y1, x1, y2, x2] format. The tennsor is padded with -1 to the fixed dimension [self._max_num_instances, 4]. classes: groundtruth classes annotations. The tennsor is padded with -1 to the fixed dimension [self._max_num_instances]. areas: groundtruth areas annotations. The tennsor is padded with -1 to the fixed dimension [self._max_num_instances]. is_crowds: groundtruth annotations to indicate if an annotation represents a group of instances by value {0, 1}. The tennsor is padded with 0 to the fixed dimension [self._max_num_instances]. """ with tf.name_scope('parser'): data = self._example_decoder.decode(value) return self._parse_fn(data) def _parse_train_data(self, data): """Parses data for training and evaluation.""" classes = data['groundtruth_classes'] boxes = data['groundtruth_boxes'] is_crowds = data['groundtruth_is_crowd'] # Skips annotations with `is_crowd` = True. if self._skip_crowd_during_training and self._is_training: num_groundtrtuhs = tf.shape(input=classes)[0] with tf.control_dependencies([num_groundtrtuhs, is_crowds]): indices = tf.cond( pred=tf.greater(tf.size(input=is_crowds), 0), true_fn=lambda: tf.where(tf.logical_not(is_crowds))[:, 0], false_fn=lambda: tf.cast(tf.range(num_groundtrtuhs), tf.int64)) classes = tf.gather(classes, indices) boxes = tf.gather(boxes, indices) # Gets original image and its size. image = data['image'] # NOTE: The autoaugment method works best when used alongside the standard # horizontal flipping of images along with size jittering and normalization. if self._use_autoaugment: image, boxes = autoaugment_utils.distort_image_with_autoaugment( image, boxes, self._autoaugment_policy_name) image_shape = tf.shape(input=image)[0:2] # Normalizes image with mean and std pixel values. image = input_utils.normalize_image(image) # Flips image randomly during training. if self._aug_rand_hflip: image, boxes = input_utils.random_horizontal_flip(image, boxes) # Converts boxes from normalized coordinates to pixel coordinates. boxes = box_utils.denormalize_boxes(boxes, image_shape) # Resizes and crops image. image, image_info = input_utils.resize_and_crop_image( image, self._output_size, padded_size=input_utils.compute_padded_size( self._output_size, 2 ** self._max_level), aug_scale_min=self._aug_scale_min, aug_scale_max=self._aug_scale_max) image_height, image_width, _ = image.get_shape().as_list() # Resizes and crops boxes. image_scale = image_info[2, :] offset = image_info[3, :] boxes = input_utils.resize_and_crop_boxes( boxes, image_scale, image_info[1, :], offset) # Filters out ground truth boxes that are all zeros. indices = box_utils.get_non_empty_box_indices(boxes) boxes = tf.gather(boxes, indices) classes = tf.gather(classes, indices) # Assigns anchors. input_anchor = anchor.Anchor( self._min_level, self._max_level, self._num_scales, self._aspect_ratios, self._anchor_size, (image_height, image_width)) anchor_labeler = anchor.AnchorLabeler( input_anchor, self._match_threshold, self._unmatched_threshold) (cls_targets, box_targets, num_positives) = anchor_labeler.label_anchors( boxes, tf.cast(tf.expand_dims(classes, axis=1), tf.float32)) # If bfloat16 is used, casts input image to tf.bfloat16. if self._use_bfloat16: image = tf.cast(image, dtype=tf.bfloat16) # Packs labels for model_fn outputs. labels = { 'cls_targets': cls_targets, 'box_targets': box_targets, 'anchor_boxes': input_anchor.multilevel_boxes, 'num_positives': num_positives, 'image_info': image_info, } return image, labels def _parse_eval_data(self, data): """Parses data for training and evaluation.""" groundtruths = {} classes = data['groundtruth_classes'] boxes = data['groundtruth_boxes'] # Gets original image and its size. image = data['image'] image_shape = tf.shape(input=image)[0:2] # Normalizes image with mean and std pixel values. image = input_utils.normalize_image(image) # Converts boxes from normalized coordinates to pixel coordinates. boxes = box_utils.denormalize_boxes(boxes, image_shape) # Resizes and crops image. image, image_info = input_utils.resize_and_crop_image( image, self._output_size, padded_size=input_utils.compute_padded_size( self._output_size, 2 ** self._max_level), aug_scale_min=1.0, aug_scale_max=1.0) image_height, image_width, _ = image.get_shape().as_list() # Resizes and crops boxes. image_scale = image_info[2, :] offset = image_info[3, :] boxes = input_utils.resize_and_crop_boxes( boxes, image_scale, image_info[1, :], offset) # Filters out ground truth boxes that are all zeros. indices = box_utils.get_non_empty_box_indices(boxes) boxes = tf.gather(boxes, indices) classes = tf.gather(classes, indices) # Assigns anchors. input_anchor = anchor.Anchor( self._min_level, self._max_level, self._num_scales, self._aspect_ratios, self._anchor_size, (image_height, image_width)) anchor_labeler = anchor.AnchorLabeler( input_anchor, self._match_threshold, self._unmatched_threshold) (cls_targets, box_targets, num_positives) = anchor_labeler.label_anchors( boxes, tf.cast(tf.expand_dims(classes, axis=1), tf.float32)) # If bfloat16 is used, casts input image to tf.bfloat16. if self._use_bfloat16: image = tf.cast(image, dtype=tf.bfloat16) # Sets up groundtruth data for evaluation. groundtruths = { 'source_id': data['source_id'], 'num_groundtrtuhs': tf.shape(data['groundtruth_classes']), 'image_info': image_info, 'boxes': box_utils.denormalize_boxes( data['groundtruth_boxes'], image_shape), 'classes': data['groundtruth_classes'], 'areas': data['groundtruth_area'], 'is_crowds': tf.cast(data['groundtruth_is_crowd'], tf.int32), } groundtruths['source_id'] = process_source_id(groundtruths['source_id']) groundtruths = pad_groundtruths_to_fixed_size( groundtruths, self._max_num_instances) # Packs labels for model_fn outputs. labels = { 'cls_targets': cls_targets, 'box_targets': box_targets, 'anchor_boxes': input_anchor.multilevel_boxes, 'num_positives': num_positives, 'image_info': image_info, 'groundtruths': groundtruths, } return image, labels def _parse_predict_data(self, data): """Parses data for prediction.""" # Gets original image and its size. image = data['image'] image_shape = tf.shape(input=image)[0:2] # Normalizes image with mean and std pixel values. image = input_utils.normalize_image(image) # Resizes and crops image. image, image_info = input_utils.resize_and_crop_image( image, self._output_size, padded_size=input_utils.compute_padded_size( self._output_size, 2 ** self._max_level), aug_scale_min=1.0, aug_scale_max=1.0) image_height, image_width, _ = image.get_shape().as_list() # If bfloat16 is used, casts input image to tf.bfloat16. if self._use_bfloat16: image = tf.cast(image, dtype=tf.bfloat16) # Compute Anchor boxes. input_anchor = anchor.Anchor( self._min_level, self._max_level, self._num_scales, self._aspect_ratios, self._anchor_size, (image_height, image_width)) labels = { 'anchor_boxes': input_anchor.multilevel_boxes, 'image_info': image_info, } # If mode is PREDICT_WITH_GT, returns groundtruths and training targets # in labels. if self._mode == ModeKeys.PREDICT_WITH_GT: # Converts boxes from normalized coordinates to pixel coordinates. boxes = box_utils.denormalize_boxes( data['groundtruth_boxes'], image_shape) groundtruths = { 'source_id': data['source_id'], 'num_detections': tf.shape(data['groundtruth_classes']), 'boxes': boxes, 'classes': data['groundtruth_classes'], 'areas': data['groundtruth_area'], 'is_crowds': tf.cast(data['groundtruth_is_crowd'], tf.int32), } groundtruths['source_id'] = process_source_id(groundtruths['source_id']) groundtruths = pad_groundtruths_to_fixed_size( groundtruths, self._max_num_instances) labels['groundtruths'] = groundtruths # Computes training objective for evaluation loss. classes = data['groundtruth_classes'] image_scale = image_info[2, :] offset = image_info[3, :] boxes = input_utils.resize_and_crop_boxes( boxes, image_scale, image_info[1, :], offset) # Filters out ground truth boxes that are all zeros. indices = box_utils.get_non_empty_box_indices(boxes) boxes = tf.gather(boxes, indices) # Assigns anchors. anchor_labeler = anchor.AnchorLabeler( input_anchor, self._match_threshold, self._unmatched_threshold) (cls_targets, box_targets, num_positives) = anchor_labeler.label_anchors( boxes, tf.cast(tf.expand_dims(classes, axis=1), tf.float32)) labels['cls_targets'] = cls_targets labels['box_targets'] = box_targets labels['num_positives'] = num_positives return image, labels
[ "bitcm@foxmail.com" ]
bitcm@foxmail.com
bcfa1e855126ba5ffc64815bfe4e16c21e3acff7
814a7dda3a723c2b4f3a97a7b4d317141d791b26
/chapter03/ex03.py
84089ca5df7b2ff193d858a45e7bd2e7118d9ce4
[]
no_license
yuemj8665/MJ_PythonBasic
dbc84bf4f4fc8818af4a7f7b3cb5d3b6a7cae3e2
a32660a2e81c21d2b2d1ce0eb7c2d11c417892c7
refs/heads/master
2023-03-22T03:06:06.186074
2021-03-21T05:42:39
2021-03-21T05:42:39
347,890,170
1
0
null
null
null
null
UTF-8
Python
false
false
690
py
# 경계선 line = "================================" # 변수를 선언하고 음수, 0, 양수를 각각 변수에 담는다 iNum1 = -1234567890 iNum2 = 0 iNum3 = 1234567890 # type함수를 이용하여 각 변수에 담긴 데이터 타입을 확인한다 print(type(iNum1)) print(type(iNum2)) print(type(iNum3)) # 경계선 print(line) # 데이터를 변수에 담지 않고 type() 함수를 사용하여 데이터 타입을 확인한다 print(type(-1234567890)) print(type(0)) print(type(1234567890)) print(line) # 데이터를 연산한 결과에 대해서도 type() 함수를 이용 할 수 있다. print(type(10+100)) print(type(10-100)) print(type(10*100)) print(type(10/100))
[ "yuemjmahu@gmail.com" ]
yuemjmahu@gmail.com
faec70dcd5ad974da0c95a2aabe5061a3055ab19
104a0148271a7c736dbadaca13a1fb983ab85167
/iDAQ/iDAQ/urls.py
26481d70649b317fed9966e9601fb0becb14ab09
[]
no_license
TeamATAuomationTeknix/iDAQ
ac6c83ecf17a1d40667ff372ee959174aefb8917
e86dd5bc9e0bb031a1c0fa7c4a735520489743e1
refs/heads/main
2023-05-04T08:55:37.494581
2021-05-28T06:34:32
2021-05-28T06:34:32
344,101,713
0
0
null
2021-03-22T05:40:06
2021-03-03T11:21:51
Python
UTF-8
Python
false
false
165
py
from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('',include('bknd_iDAQ.urls')) ]
[ "54470073+TeamATAuomationTeknix@users.noreply.github.com" ]
54470073+TeamATAuomationTeknix@users.noreply.github.com
cd9b8f28a800ec32b5f41c2a68cdac3eed121c9a
8de9bfc59996b90b0b6fc54a87189e6ea84070d6
/Nth_Largest_List.py
9c3a8954fddfc6c61d18ea8fbbf912f6f2cdffba
[]
no_license
infantcyril/Python_Practise
f992ac92feb272a5e5fbe1a1e9e8a804f6b054a8
a8af863ecc93346fe15a5a80bc8cf5bd7b90c63b
refs/heads/master
2020-04-09T12:10:02.118970
2018-12-14T11:18:35
2018-12-14T11:18:35
160,337,869
0
0
null
null
null
null
UTF-8
Python
false
false
1,714
py
create_lis = [] def nth_largest(lis): create_lis = [] new_lis = [] final_lis = [] check_list = 0 check_value = 0 while(check_list == 0): check_list = 1 try: lis_len = int(input("Enter the max lenth of list")) except ValueError: print("Enter a valid input") check_list = 0 while(check_value == 0): check_value = 1 try: while lis_len != 0: value_list = int(input("Enter the integer value to be present in your list")) create_lis.append(value_list) lis_len-=1 except ValueError: print("Enter a valid input") check_value = 0 print(create_lis) while create_lis: minimum = create_lis[0] for i in create_lis: if i < minimum: minimum = i new_lis.append(minimum) create_lis.remove(minimum) for i in new_lis: if i not in final_lis: final_lis.append(i) size = (len(final_lis)) check_n = 0 while(check_n == 0): check_n = 1 try: n = int(input("Enter the value of n:")) if n > size or n <= 0: print("This list has only" ,size,"unique values! Please enter a value between 1 and",size) check_n = 0 except ValueError: print("Enter a valid input") check_value = 0 #print(new_lis) #print(final_lis) print("The" ,n ,"largest number in the list is",final_lis[size - n]) nth_largest(create_lis)
[ "noreply@github.com" ]
noreply@github.com
7e878f5b9883e5ac0dc76a842350076534aa0576
2d85cb9e2d79f3d58f81dfa41ee468fee861a322
/sourceCode/lidar_Playground.py
8bc1cb415b82325cb3da21f735d8a6ee6e191355
[]
no_license
aldenkane/valet
076d68553efb1511dce5d7930d7979e13b6df67b
9c55ee68b50624245df6c54059649ef759e2c1d1
refs/heads/master
2021-02-14T04:25:10.820801
2020-03-06T06:04:08
2020-03-06T06:04:08
244,768,124
0
0
null
null
null
null
UTF-8
Python
false
false
902
py
import smbus # Declare Globals and Device Parameters CHANNEL = 1 DEVICE_ADDRESS = 0x62 ACQ_COMMANDS = 0x00 STATUS = 0x01 FULL_DELAY_LOW = 0x10 FULL_DELAY_HIGH = 0X11 RESET_BYTE = 0x00 BIASED_DISTANCE = 0X04 read_Distance = 0 # Declare Bus w/ SMbus, Intialize I2C bus = smbus.SMBus(CHANNEL) # Initialize LiDAR by Writing to Correction Distance Mode to ACQ Register bus.write_byte_data(DEVICE_ADDRESS, ACQ_COMMANDS, BIASED_DISTANCE) # Read Distance Data while True: r_1 = bus.read_byte_data(DEVICE_ADDRESS, STATUS) r_1_Bin = bin(r_1) print("Read Status Binary: " + str(r_1_Bin)) print("Read Status: " + str(r_1) + ' cm') if r_1 == 1: read_Distance_0 = bus.read_byte_data(DEVICE_ADDRESS, FULL_DELAY_LOW) read_Distance_1 = bus.read_i2c_block_data(DEVICE_ADDRESS, FULL_DELAY_LOW, 2) print("Read Distance " + str(read_Distance_0) + ' cm') exit()
[ "akane2@nd.edu" ]
akane2@nd.edu
02e84f2320b6330cb6d40f012e3fc4299202767c
b75dde40bfe632ab2e17dbfa8c3201d03a01c873
/kinematics/src/transform_func.py
2749eb9fd83f2d4b1e23edc7bf27ddc9b0ee311f
[]
no_license
MKraienhorst/rnm_D
9a7a8fcd1116bc6a6510ff8588109ac5f2f5168e
2d50818e0edf1fa6ba15079bcc52b07d4c6471d6
refs/heads/master
2021-06-26T15:37:54.073940
2020-12-01T09:22:38
2020-12-01T09:22:38
182,816,191
0
0
null
null
null
null
UTF-8
Python
false
false
1,784
py
#!/usr/bin/env python # -*- coding: utf-8 -*- from math import * import tf.transformations as tf from geometry_msgs.msg import Pose def ur2ros(ur_pose): """Transform pose from UR format to ROS Pose format""" # ROS pose ros_pose = Pose() # Position ros_pose.position.x = ur_pose[0] ros_pose.position.y = ur_pose[1] ros_pose.position.z = ur_pose[2] # angle normalized angle = sqrt(ur_pose[3] ** 2 + ur_pose[4] ** 2 + ur_pose[5] ** 2) orient = [i / angle for i in ur_pose[3:6]] #rx ry rz to rotation matrix np_T = tf.rotation_matrix(angle, orient) #rotation matrix to quaternion np_q = tf.quaternion_from_matrix(np_T) ros_pose.orientation.x = np_q[0] ros_pose.orientation.y = np_q[1] ros_pose.orientation.z = np_q[2] ros_pose.orientation.w = np_q[3] return ros_pose def ros2np(ros_pose): """Transform pose from ROS Pose format to np.array format""" # orientation np_pose = tf.quaternion_matrix([ros_pose.orientation.x, ros_pose.orientation.y, ros_pose.orientation.z, ros_pose.orientation.w]) # position np_pose[0][3] = ros_pose.position.x np_pose[1][3] = ros_pose.position.y np_pose[2][3] = ros_pose.position.z return np_pose def np2ros(np_pose): """Transform pose from np.array format to ROS Pose format""" # ROS pose ros_pose = Pose() # ROS position ros_pose.position.x = np_pose[0, 3] ros_pose.position.y = np_pose[1, 3] ros_pose.position.z = np_pose[2, 3] # ROS orientation np_q = tf.quaternion_from_matrix(np_pose) ros_pose.orientation.x = np_q[0] ros_pose.orientation.y = np_q[1] ros_pose.orientation.z = np_q[2] ros_pose.orientation.w = np_q[3] return ros_pose
[ "noreply@github.com" ]
noreply@github.com
ad8c3ae77b57cf5ad1c8038f5ec41c8a394762dc
eb9d561a7b60053f69d9f6b4d7f8411199bd84e7
/src/puzzle_image_solver.py
d73ba30c5f848c44aa1f742ae3597a6a90d2cff1
[]
no_license
v-y-l/Block-Design
7f31590c1aa27a3642cdd2696cbf21e6ed7b7757
8765e514dbd1241ac1b9f719de6aab473bce239a
refs/heads/main
2023-02-15T09:05:42.493960
2021-01-13T02:07:45
2021-01-13T02:07:45
303,569,736
0
0
null
null
null
null
UTF-8
Python
false
false
9,964
py
from cv2 import imread, cvtColor, COLOR_BGR2RGB from PIL import Image, ImageDraw from utils.constants import BLOCK_LENGTH, EDGE_OFFSET, PUZZLE_OPTIONS from utils.enums import BlockPattern, SearchType, BlockAction, PuzzleAction from utils.helper import get_pattern from search import random_search, sequential_search from block_image import BlockImage import numpy as np import csv class PuzzleImageSolver: def __init__(self, name = 'puzzle_a', config = { 'solvers': { SearchType.Face: random_search, SearchType.PuzzlePiece: sequential_search }, # Value from 0 to 1, represents % of memory # loss on the puzzle each turn 'puzzle_memory_loss_factor': 0.0, # Number of puzzle pieces solved before memory loss # e.g. if = 4, then memory loss happens on 4th piece 'puzzle_memory_loss_counter_limit': 0, # Value from 0 to 1, represents % of memory recovered # from the puzzle 'glance_factor': 1.0, # If provided, saves snapshot of each state to the path 'state_image_path': '', } ): self.name = name or 'puzzle_a' self.solvers = config.get("solvers", { SearchType.Face: random_search, SearchType.PuzzlePiece: sequential_search }) self.puzzle_memory_loss_factor = config.get("puzzle_memory_loss_factor", 0.0) self.puzzle_memory_loss_counter_limit = config.get( "puzzle_memory_loss_counter_limit", 0) self.glance_factor = config.get("glance_factor", 1.0) self.action_counter = {} self.state_image_path = config.get("state_image_path", "") self._setup_puzzle() self.look_at_puzzle((0,0), self.glance_factor) def _setup_puzzle(self): self.block = None self.image_path = PUZZLE_OPTIONS[self.name] self.action_history = [] self.num_rows, self.num_cols, self.bgr_len = ( imread(self.image_path).shape) # Glance factor presumes that the puzzle is a square min_glance_factor = float(BLOCK_LENGTH - 10) / self.num_cols if not self.glance_factor >= min_glance_factor: raise Exception( "Specified glance factor {} must be at least {} to cover one square".format( self.glance_factor, min_glance_factor)) # Start with a blank slate self.image = np.zeros((self.num_rows, self.num_cols, self.bgr_len), np.uint8) self.unsolved_pieces = [] # Represents as top left coordinate for r in range(0, self.num_rows - EDGE_OFFSET, BLOCK_LENGTH): for c in range(0, self.num_cols - EDGE_OFFSET, BLOCK_LENGTH): self.unsolved_pieces.append((r, c)) self.block_bank = [ BlockImage(1, i+1, self) for i in range(len(self.unsolved_pieces))] self.solved_pieces = {piece:None for piece in self.unsolved_pieces} self.puzzle_memory_loss_counter = 0 ''' Adds to the history of executed actions on each block. ''' def add_to_history(self, row, action): self.increment_action(action) self.action_history.append(row) action_index = len(self.action_history) if self.state_image_path: self.save_puzzle_image("{}/puzzle_image_{}.png".format( self.state_image_path, action_index)) ''' Simulates picking up a block ''' def pick_up_next_block(self): if not self.block_bank: raise Exception("No more blocks in block bank") if not self.block or self.block.is_solved: self.block = self.block_bank.pop() self.add_to_history(self.block.to_csv_row(BlockAction.PickUpFromBank), BlockAction.PickUpFromBank) ''' Returns the puzzle piece in symbolic form given some r, c. ''' def get_pattern(self, r, c): return get_pattern(r, c, self.image) ''' Returns a numpy array with shape of num_rows x num_cols x bgr pixels. ''' def get_image(self): return self.image ''' For testing purposes to check if full puzzle is correctly parsed. ''' def get_puzzle(self): return [self.get_pattern(r, c) for (r, c) in self.unsolved_pieces] ''' Get the patterns of pieces solved so far. ''' def get_solved_pieces_patterns(self): solved_pieces_patterns = [] for pieces in sorted(self.solved_pieces): block = self.solved_pieces[pieces] solved_pieces_patterns.append(block.get_pattern()) return solved_pieces_patterns ''' Save the puzzle as an image. ''' def save_puzzle_image(self, name): image = Image.fromarray(cvtColor(self.image, COLOR_BGR2RGB), 'RGB') for piece in self.solved_pieces: if self.solved_pieces[piece]: base_r, base_c = piece top_r = base_r + BLOCK_LENGTH *.25 top_c = base_c + BLOCK_LENGTH *.25 bottom_r = base_r + BLOCK_LENGTH *.75 bottom_c = base_c + BLOCK_LENGTH *.75 draw = ImageDraw.Draw(image) draw.ellipse((top_c, top_r, bottom_c, bottom_r), fill = 'blue', outline ='blue') image.save(name, "PNG") ''' Opens the puzzle as an image. ''' def show_image(self, image=[]): if len(image) == 0: image = self.image Image.fromarray(cvtColor(image, COLOR_BGR2RGB), 'RGB').show() ''' Sets a memory_loss_factor % of image to black to simulate forgetfulness. ''' def forget_puzzle(self): if (self.puzzle_memory_loss_factor) == 0: return num_rows, num_cols, bgr_len = self.image.shape total_pixels = num_rows * num_cols total_pixels_to_forget = int( total_pixels * self.puzzle_memory_loss_factor) tmp_image = self.image.reshape(total_pixels, bgr_len) mask = np.ones((total_pixels, bgr_len), np.uint8) mask[:total_pixels_to_forget] = [0, 0, 0] np.random.shuffle(mask) # Expensive tmp_image *= mask self.image = tmp_image.reshape(num_rows, num_cols, bgr_len) ''' Increment the action counter by an action. ''' def increment_action(self, action): self.action_counter[action] = self.action_counter.get(action, 0) + 1 ''' Increment the turn counter in turns of forgetfulness. ''' def increment_memory_loss_counter(self): if self.puzzle_memory_loss_counter_limit > 0: self.puzzle_memory_loss_counter = ( (self.puzzle_memory_loss_counter + 1) % self.puzzle_memory_loss_counter_limit ) ''' Take a look at the puzzle to refresh our memory of it. ''' def look_at_puzzle(self, point, factor): row, col = point self.add_to_history( self.to_csv_row(PuzzleAction.LookAtPuzzle, "{}|{}".format(row, col)), PuzzleAction.LookAtPuzzle) remembered_puzzle_pieces = ( imread(self.image_path)[row:row + int(self.num_rows * factor), col:col + int(self.num_cols * factor)]) self.image[row:row + int(self.num_rows * factor) ,col:col + int(self.num_cols * factor)] = ( remembered_puzzle_pieces) ''' If the solver is forgetting some of the puzzle on this turn ''' def should_forget(self): return (self.puzzle_memory_loss_counter == self.puzzle_memory_loss_counter_limit - 1) ''' Returns a list of actions executed by each block to solve the problem. ''' def solve(self): face_searcher = self.solvers[SearchType.Face] puzzle_piece_searcher = self.solvers[SearchType.PuzzlePiece] # The actions taken for each block to get to the destination state actions_per_block = [] while self.unsolved_pieces: self.pick_up_next_block() if self.should_forget(): self.forget_puzzle() self.increment_memory_loss_counter() unsolved_piece_pattern, unsolved_piece = puzzle_piece_searcher(self) if unsolved_piece_pattern == BlockPattern.Unknown: continue search_face_actions = face_searcher( self.block, unsolved_piece_pattern, actions_per_block) self.block.is_solved = True self.unsolved_pieces.remove(unsolved_piece) self.solved_pieces[unsolved_piece] = self.block if self.state_image_path: self.save_puzzle_image("{}/puzzle_image_final.png".format( self.state_image_path)) return actions_per_block ''' Prints a puzzle action in csv readable form. ''' def to_csv_row(self, action, point): return str(self) + ",action," + action.name + ",point," + point ''' Prints out all executed actions. ''' def print_history(self, csv_path=''): csv_writer = None if csv_path != '': file = open(csv_path, 'a') csv_writer = csv.writer(file, # A hack, since our true delimiter is "," delimiter='&', quoting=csv.QUOTE_NONE) for i, action in enumerate(self.action_history): row = "{},{}".format(i, action) if csv_writer: csv_writer.writerow([row]) else: print(row) if csv_writer: file.close() def __str__(self): return 'Puzzle,{}'.format(self.name)
[ "vlinvlin6@gmail.com" ]
vlinvlin6@gmail.com
1110f7e0dacac9ef0b6b69c736d03aa57d46b364
006341ca12525aa0979d6101600e78c4bd9532ab
/CMS/Zope-3.2.1/Dependencies/zope.component-Zope-3.2.1/zope.component/bbb/utility.py
f626f6c3e1a4329b351d849e1924758ce526722a
[ "ZPL-2.1", "Python-2.0", "ICU", "LicenseRef-scancode-public-domain", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "ZPL-2.0" ]
permissive
germanfriday/code-examples-sandbox
d0f29e20a3eed1f8430d06441ac2d33bac5e4253
4c538584703754c956ca66392fdcecf0a0ca2314
refs/heads/main
2023-05-30T22:21:57.918503
2021-06-15T15:06:47
2021-06-15T15:06:47
377,200,448
0
0
null
null
null
null
UTF-8
Python
false
false
2,507
py
############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """utility service $Id: utility.py 38178 2005-08-30 21:50:19Z mj $ """ from zope.component.exceptions import Invalid, ComponentLookupError from zope.component.interfaces import IUtilityService, IRegistry from zope.component.service import GlobalService, IService, IServiceDefinition from zope.component.site import UtilityRegistration import zope.interface class IGlobalUtilityService(IUtilityService, IRegistry): def provideUtility(providedInterface, component, name='', info=''): """Provide a utility A utility is a component that provides an interface. """ class UtilityService(object): """Provide IUtilityService Mixin that superimposes utility management on adapter registery implementation """ def __init__(self, sitemanager=None): self.__parent__ = None if sitemanager is None: from zope.component.site import GlobalSiteManager sitemanager = GlobalSiteManager() self.sm = sitemanager def __getattr__(self, name): attr = getattr(self.sm, name) if attr is not None: return attr attr = getattr(self.sm.utilities, name) if attr is not None: return attr raise AttributeError(name) class GlobalUtilityService(UtilityService, GlobalService): zope.interface.implementsOnly(IGlobalUtilityService) def __init__(self, sitemanager=None): super(GlobalUtilityService, self).__init__(sitemanager) def provideUtility(self, providedInterface, component, name='', info=''): self.sm.provideUtility(providedInterface, component, name, info) def registrations(self): for reg in self.sm.registrations(): if isinstance(reg, UtilityRegistration): if not reg.provided in (IService, IServiceDefinition): yield reg
[ "chris@thegermanfriday.com" ]
chris@thegermanfriday.com
17cd0e56dc3b5a0327dc795dd7cb543a6b31e925
7ecc0f1281944aa2aacf249664f7b45d5e658f6f
/apps/goods/migrations/0001_initial.py
6190a3c6c78d9ae367730abefb2a0a5883aad112
[]
no_license
shx-1999/MxShop
c886a8699e4b538ab1466e34ee05b7296a5c92a9
092bad3784d60baa5283b4606ab346d587fe2b7f
refs/heads/master
2023-03-18T02:52:57.467721
2020-01-09T08:29:41
2020-01-09T08:29:41
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,312
py
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2019-01-12 04:54 from __future__ import unicode_literals import DjangoUeditor.models import datetime from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Banner', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('image', models.ImageField(upload_to='banner', verbose_name='轮播图片')), ('index', models.IntegerField(default=0, verbose_name='轮播顺序')), ('add_time', models.DateTimeField(default=datetime.datetime.now, verbose_name='添加时间')), ], options={ 'verbose_name': '轮播商品', 'verbose_name_plural': '轮播商品', }, ), migrations.CreateModel( name='Goods', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('goods_sn', models.CharField(default='', max_length=50, verbose_name='商品唯一货号')), ('name', models.CharField(max_length=300, verbose_name='商品名')), ('click_num', models.IntegerField(default=0, verbose_name='点击数')), ('sold_num', models.IntegerField(default=0, verbose_name='商品销售量')), ('fav_num', models.IntegerField(default=0, verbose_name='收藏数')), ('goods_num', models.IntegerField(default=0, verbose_name='库存数')), ('market_price', models.FloatField(default=0, verbose_name='市场价格')), ('shop_price', models.FloatField(default=0, verbose_name='本店价格')), ('goods_brief', models.TextField(max_length=500, verbose_name='商品简短描述')), ('goods_desc', DjangoUeditor.models.UEditorField(default='', verbose_name='内容')), ('ship_free', models.BooleanField(default=True, verbose_name='是否承担运费')), ('goods_front_image', models.ImageField(blank=True, null=True, upload_to='goods/images/', verbose_name='封面图')), ('is_new', models.BooleanField(default=False, verbose_name='是否新品')), ('is_hot', models.BooleanField(default=False, verbose_name='是否热销')), ('add_time', models.DateTimeField(default=datetime.datetime.now, verbose_name='添加时间')), ], options={ 'verbose_name': '商品', 'verbose_name_plural': '商品', }, ), migrations.CreateModel( name='GoodsCategory', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(default='', help_text='类别名', max_length=30, verbose_name='类别名')), ('code', models.CharField(default='', help_text='类别code', max_length=30, verbose_name='类别code')), ('desc', models.TextField(default='', help_text='类别描述', verbose_name='类别描述')), ('category_type', models.IntegerField(choices=[(1, '一级类目'), (2, '二级类目'), (3, '三级类目')], help_text='类目级别', verbose_name='类目级别')), ('is_tab', models.BooleanField(default=False, help_text='是否导航', verbose_name='是否导航')), ('add_time', models.DateTimeField(default=datetime.datetime.now, verbose_name='添加时间')), ('parent_category', models.ForeignKey(blank=True, help_text='父目录', null=True, on_delete=django.db.models.deletion.CASCADE, related_name='sub_cat', to='goods.GoodsCategory', verbose_name='父类目级别')), ], options={ 'verbose_name': '商品类别', 'verbose_name_plural': '商品类别', }, ), migrations.CreateModel( name='GoodsCategoryBrand', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(default='', help_text='品牌名', max_length=30, verbose_name='品牌名')), ('desc', models.TextField(default='', help_text='品牌描述', max_length=200, verbose_name='品牌描述')), ('image', models.ImageField(max_length=200, upload_to='brands/images/')), ('add_time', models.DateTimeField(default=datetime.datetime.now, verbose_name='添加时间')), ], options={ 'verbose_name': '品牌', 'verbose_name_plural': '品牌', }, ), migrations.CreateModel( name='GoodsImage', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('image', models.ImageField(blank=True, null=True, upload_to='', verbose_name='图片')), ('image_url', models.CharField(blank=True, max_length=300, null=True, verbose_name='图片url')), ('add_time', models.DateTimeField(default=datetime.datetime.now, verbose_name='添加时间')), ('goods', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='images', to='goods.Goods', verbose_name='商品')), ], options={ 'verbose_name': '商品图片', 'verbose_name_plural': '商品图片', }, ), migrations.AddField( model_name='goods', name='category', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='goods.GoodsCategory', verbose_name='商品类目'), ), migrations.AddField( model_name='banner', name='goods', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='goods.Goods', verbose_name='商品'), ), ]
[ "1450655645@qq.com" ]
1450655645@qq.com
e71f0a615ae491bb9857459804dafdee895970ae
fd5bc0e8a3ac2b7ba793287084f725a8cd10b5ef
/tests/bench/loadrelated.py
9942ed0b1e2b9a0ae4d8a8c7c923e95f0e30e58e
[ "BSD-3-Clause" ]
permissive
moyaya/python-stdnet
404cb645b80c59b08ce4506480ce897c24032dcd
8d6c41ba1ddb8024e6bfab859f99bf96966d04cf
refs/heads/master
2021-01-24T01:00:18.203118
2012-01-13T18:23:20
2012-01-13T18:23:20
null
0
0
null
null
null
null
UTF-8
Python
false
false
571
py
'''Benchmark load realted.''' from stdnet import test, transaction from stdnet.utils import populate, zip from examples.data import FinanceTest, Instrument, Fund, Position class LoadRelatedTest(FinanceTest): def setUp(self): self.data.makePositions() def testLoad(self): for p in Position.objects.all(): self.assertTrue(p.instrument.name) def testLoadRelated(self): for p in Position.objects.all().load_related('instrument'): self.assertTrue(p.instrument.name)
[ "luca.sbardella@gmail.com" ]
luca.sbardella@gmail.com
6afd0f56225c145cef326c7abc2c9be8c444f047
435e0fd161236462e3af4bcd046a98afb78443db
/Aula6_2.py
344945006b4421170921b26d9905301d777f8e14
[]
no_license
bernardbrandao/Python2019_1
cf4049dcfee6b4a5daace93f0b75f9cc675e85c4
6dd309b3f1d7f39c475dcb2a9a0c4bd63bf2c416
refs/heads/master
2020-04-28T12:19:22.036873
2019-05-28T20:45:33
2019-05-28T20:45:33
175,272,823
0
0
null
null
null
null
UTF-8
Python
false
false
324
py
import turtle t= turtle.Turtle() lenght = int(input("Digite o tamanho do lado do quadrado: ")) def square(t,lenght): jn = turtle.Screen() # Configurar a janela e seus atributos# jn.bgcolor("lightyellow") jn.title("Quadrado") for i in range (4): t.forward(lenght) t.left(90) square(t,lenght)
[ "noreply@github.com" ]
noreply@github.com
c91bf2757b50135b93cccc7037a6b4d71b11c283
7aaa5d539dc49e007ca7c152ba01b5e7d2c9f4b3
/ALDS1/11B_DepthFirstSearch.py
5702a719d8ef57302acc9ebc11bcfa0969a0e9e8
[]
no_license
fujihiraryo/aizu-online-judge
3011180660bec1febd4d7b973855814646625346
f5435eaa4612773e9c1c48bf72dfdfd2921be114
refs/heads/master
2022-05-17T18:14:54.828672
2022-04-24T04:17:20
2022-04-24T04:17:20
233,409,027
0
0
null
null
null
null
UTF-8
Python
false
false
1,177
py
import sys sys.setrecursionlimit(10 ** 7) class DFS: def __init__(self, graph): n = len(graph) self.graph = graph self.visited = [0] * n self.preorder = [] self.postorder = [] self.pretime = [0] * n self.posttime = [0] * n self.time = 0 self.parent = [-1] * n self.children = [[] for _ in range(n)] for i in range(n): if self.visited[i]: continue self.visit(i) def visit(self, x): self.visited[x] = 1 self.preorder.append(x) self.pretime[x] = self.time self.time += 1 for y in self.graph[x]: if self.visited[y]: continue self.parent[y] = x self.children[x].append(y) self.visit(y) self.postorder.append(x) self.posttime[x] = self.time self.time += 1 n = int(input()) graph = [[] for _ in range(n)] for _ in range(n): x, _, *lst = map(int, input().split()) for y in lst: graph[x - 1].append(y - 1) dfs = DFS(graph) for x in range(n): print(x + 1, dfs.pretime[x] + 1, dfs.posttime[x] + 1)
[ "fujihiraryo.team-lab.com" ]
fujihiraryo.team-lab.com
7b9ac2b2812f556029a4cc9536b2977c7bc6f657
d1aa55ea8cfabf6051af24bb31a25dd9df4a0d41
/pip.py
fc9c3ebc0e92932f0324ed027943120f05e6b930
[]
no_license
Deoduce2me/temp-predict
9a8a3bc08e5f62e84343e84b28d13bc50c84a682
59f105fd8a310f775f234ecf2c07611c295639a4
refs/heads/main
2023-08-29T20:33:58.975874
2021-10-12T19:27:55
2021-10-12T19:27:55
416,043,166
0
0
null
null
null
null
UTF-8
Python
false
false
3,166
py
import pandas as pd import seaborn as sns import streamlit as st # import plotly.express as px # import shap st.set_option('deprecation.showPyplotGlobalUse', False) import matplotlib import matplotlib.pyplot as plt import numpy as np import string import altair as alt import pickle st.title('Temperature Prediction') st.write('This app predicts Temperature value from other Parameters ') abid=pd.read_csv('Abid Combine.csv') abid['Month'] = pd.to_datetime(abid['Month'], format='%m').dt.month_name().str.slice(stop=3) # xx=abid.drop(['Month','Temperature (degree celsius)'],axis=1) # #xx # yy= abid[['Temperature (degree celsius)']] # abid # st.table(abid.plot(x="Month", kind="line",figsize=(18,5))) st.table(abid) # chart = alt.Chart(abid).mark_line().encode( # x=alt.X('Month'), # y=alt.Y('value:Q') # ).properties(title="Hello World") # st.altair_chart(chart, use_container_width=True) st.line_chart(abid.drop(['Month'],axis=1)) if st.checkbox("Show Correlation Plot"): st.write("### Heatmap") fig, ax = plt.subplots() st.write(sns.heatmap(abid.drop(['Month'],axis=1).corr(), annot=True, linewidths=0.5)) st.pyplot() # figs = plt.figure() # ax = figs.add_subplot(1,1,1) # # plt.scatter(abid) # # st.write(fig) # xopt=['Month'] # yopt=["Temperature (degree celsius)", "Relative Humidity(%)","Pressure(hPa)","Wind speed(m/s)","Wind direction(deg)","Rainfall(mm)"] # figs= px.scatter(abid,x='Month',y=yopt) # # st.plotly_chart(figs) #loading our model model1 = pickle.load(open('Best.pkl','rb')) # r_sq = model1.score(xx, yy) # print('coefficient of determination:', r_sq) # st.write("### r_sq") def main(): st.markdown("<h1 style='text-align: center; color: White;background-color:#e84343'>TEMPERATURE PREDICTOR</h1>", unsafe_allow_html=True) # st.markdown("<h3 style='text-align: center; color: Black;'>Drop in The required Inputs and we will do the rest.</h3>", unsafe_allow_html=True) st.markdown("<h4 style='text-align: center; color: Black;'>Submission for ADS PROJECT</h4>", unsafe_allow_html=True) st.sidebar.header("What is this Project about?") st.sidebar.text("It is a Web app that would help predict Temperature.") st.sidebar.header("What tools were used to make this?") st.sidebar.text("The Model was made using a dataset from http://www./soda-pro.com/web-services/radiation/helioclim-1 along with using jupyter notebook to train the model. We made use of Sci-Kit learn in order to make our Linear Regression Model.") Rel_Hum = st.slider("Input your Relative Humidity(%)",0.000,100.000) press= st.slider("Input your Pressure(hPa)",0.000,1500.000) wind_speed = st.slider("Input your Wind speed(m/s)",0.000,10.000) wind_direction = st.slider("Input your Wind direction(deg)",0.000,500.000) rainfall = st.slider("Input your Rainfall(mm)",0.000,500.000) inputs = [[Rel_Hum,press,wind_speed,wind_direction,rainfall]] #our inputs if st.button('Predict'): #making and printing our prediction result = model1.predict(inputs) updated_res = result.flatten().astype(float) st.success('The Temperature is {}degree celsius'.format(updated_res)) if __name__ =='__main__': main() #calling the main method
[ "deolasolomon10@yahoo.co.uk" ]
deolasolomon10@yahoo.co.uk
0bf464fb6204343b71d383b81c94bf835f6e6d58
58c34c597e825634fb5833b22e178df4fe570d39
/lib/adapter/cheat_cheat.py
9844008c6be19c9654ed8c373292de2a9e5132c6
[ "MIT", "CC-BY-SA-3.0" ]
permissive
sullivant/cheat.sh
2eb731eb1d7c6b03d65b2dd5f9b6a325b167c005
e2e69b61a361751a145b977ca2f58ae4a50d756e
refs/heads/master
2020-05-30T09:36:58.834850
2019-05-31T19:47:53
2019-05-31T19:47:53
189,649,817
1
0
MIT
2019-05-31T19:45:23
2019-05-31T19:45:22
null
UTF-8
Python
false
false
549
py
""" Adapter for https://github.com/cheat/cheat Cheatsheets are located in `cheat/cheatsheets/` Each cheat sheet is a separate file without extension """ # pylint: disable=relative-import,abstract-method from .git_adapter import GitRepositoryAdapter class Cheat(GitRepositoryAdapter): """ cheat/cheat adapter """ _adapter_name = "cheat" _output_format = "code" _cache_needed = True _repository_url = "https://github.com/cheat/cheat" _cheatsheet_files_prefix = "cheat/cheatsheets/" _cheatsheet_file_mask = "*"
[ "igor@chub.in" ]
igor@chub.in
11e6f88fc786ee42dd1cebc462803a9365604476
f7d3b572b62bc4b8400a84ac2afa5d01cb96196b
/ex32_Lists.py
91ac3784ec9ac415e767adf2ea4bcbc6d381bf4a
[]
no_license
nairarunraj/LearnPythonTheHardWay
559432351dcd96f4e13c630815f03babf3ef7ba1
a7c398fcc92921f5bc8dcaa3774712c09beed519
refs/heads/master
2021-01-23T16:24:50.302675
2017-06-17T20:14:29
2017-06-17T20:14:29
93,296,687
0
0
null
null
null
null
UTF-8
Python
false
false
779
py
# ex32 Lists the_count = [1,2,3,4,5] fruits = ['apples', 'oranges', 'mangoes', 'pears'] change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] # going through a List for number in the_count: print "This is count %d" % number # same as above for fruit in fruits: print "A fruit of type %s" % fruit # also, we can go through mixed Lists # use %r because it can be either a string or a number # %s works too btw for i in change: print "I got %s" % i # Building lists elements = [] # use the range function to do 0 to 5 counts for i in range(0, 6): print "Adding %d to the list" % i elements.append(i) # Easier way to assign a range elements = range(0, 6) # print the elements for i in elements: print "Element - %d" % i
[ "arunraj@msn.com" ]
arunraj@msn.com
244ecb3d7cda2b212c28968b72151583aa73ab22
7fb87945b77d3adaedd8a155c981e97946734e41
/packstack/plugins/amqp_002.py
bc822100bc810d982c6734ba0f87cfae7797e907
[ "Apache-2.0" ]
permissive
Tony910517/openstack
916b36368ea9f17958e4eb04bd1f9daf3aba9213
4c1380a03c37e7950dcf2bba794e75b7e4a8dfd0
refs/heads/master
2020-05-20T01:05:22.499224
2019-05-07T01:11:05
2019-05-07T01:11:05
185,292,662
0
0
null
null
null
null
UTF-8
Python
false
false
7,981
py
# -*- coding: utf-8 -*- # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. """ Installs and configures AMQP """ from packstack.installer import basedefs from packstack.installer import validators from packstack.installer import processors from packstack.installer import utils from packstack.modules.common import filtered_hosts from packstack.modules.documentation import update_params_usage from packstack.modules.ospluginutils import appendManifestFile from packstack.modules.ospluginutils import createFirewallResources from packstack.modules.ospluginutils import getManifestTemplate from packstack.modules.ospluginutils import generate_ssl_cert # ------------- AMQP Packstack Plugin Initialization -------------- PLUGIN_NAME = "AMQP" PLUGIN_NAME_COLORED = utils.color_text(PLUGIN_NAME, 'blue') def initConfig(controller): params = [ {"CMD_OPTION": "amqp-backend", "PROMPT": "Set the AMQP service backend", "OPTION_LIST": ["rabbitmq"], "VALIDATORS": [validators.validate_options], "DEFAULT_VALUE": "rabbitmq", "MASK_INPUT": False, "LOOSE_VALIDATION": False, "CONF_NAME": "CONFIG_AMQP_BACKEND", "USE_DEFAULT": False, "NEED_CONFIRM": False, "CONDITION": False, "DEPRECATES": ['CONFIG_AMQP_SERVER']}, {"CMD_OPTION": "amqp-host", "PROMPT": "Enter the host for the AMQP service", "OPTION_LIST": [], "VALIDATORS": [validators.validate_ssh], "DEFAULT_VALUE": utils.get_localhost_ip(), "MASK_INPUT": False, "LOOSE_VALIDATION": True, "CONF_NAME": "CONFIG_AMQP_HOST", "USE_DEFAULT": False, "NEED_CONFIRM": False, "CONDITION": False}, {"CMD_OPTION": "amqp-enable-ssl", "PROMPT": "Enable SSL for the AMQP service?", "OPTION_LIST": ["y", "n"], "VALIDATORS": [validators.validate_options], "DEFAULT_VALUE": "n", "MASK_INPUT": False, "LOOSE_VALIDATION": False, "CONF_NAME": "CONFIG_AMQP_ENABLE_SSL", "USE_DEFAULT": False, "NEED_CONFIRM": False, "CONDITION": False}, {"CMD_OPTION": "amqp-enable-auth", "PROMPT": "Enable Authentication for the AMQP service?", "OPTION_LIST": ["y", "n"], "VALIDATORS": [validators.validate_options], "DEFAULT_VALUE": "n", "MASK_INPUT": False, "LOOSE_VALIDATION": False, "CONF_NAME": "CONFIG_AMQP_ENABLE_AUTH", "USE_DEFAULT": False, "NEED_CONFIRM": False, "CONDITION": False}, ] update_params_usage(basedefs.PACKSTACK_DOC, params, sectioned=False) group = {"GROUP_NAME": "AMQP", "DESCRIPTION": "AMQP Config parameters", "PRE_CONDITION": False, "PRE_CONDITION_MATCH": True, "POST_CONDITION": False, "POST_CONDITION_MATCH": True} controller.addGroup(group, params) params = [ {"CMD_OPTION": "amqp-nss-certdb-pw", "PROMPT": "Enter the password for NSS certificate database", "OPTION_LIST": [], "VALIDATORS": [validators.validate_not_empty], "DEFAULT_VALUE": "PW_PLACEHOLDER", "PROCESSORS": [processors.process_password], "MASK_INPUT": True, "LOOSE_VALIDATION": True, "CONF_NAME": "CONFIG_AMQP_NSS_CERTDB_PW", "USE_DEFAULT": False, "NEED_CONFIRM": True, "CONDITION": False}, ] update_params_usage(basedefs.PACKSTACK_DOC, params, sectioned=False) group = {"GROUP_NAME": "AMQPSSL", "DESCRIPTION": "AMQP Config SSL parameters", "PRE_CONDITION": "CONFIG_AMQP_ENABLE_SSL", "PRE_CONDITION_MATCH": "y", "POST_CONDITION": False, "POST_CONDITION_MATCH": True} controller.addGroup(group, params) params = [ {"CMD_OPTION": "amqp-auth-user", "PROMPT": "Enter the user for amqp authentication", "OPTION_LIST": [], "VALIDATORS": [validators.validate_not_empty], "DEFAULT_VALUE": "amqp_user", "MASK_INPUT": False, "LOOSE_VALIDATION": True, "CONF_NAME": "CONFIG_AMQP_AUTH_USER", "USE_DEFAULT": False, "NEED_CONFIRM": False, "CONDITION": False}, {"CMD_OPTION": "amqp-auth-password", "PROMPT": "Enter the password for user authentication", "OPTION_LIST": ["y", "n"], "VALIDATORS": [validators.validate_not_empty], "PROCESSORS": [processors.process_password], "DEFAULT_VALUE": "PW_PLACEHOLDER", "MASK_INPUT": True, "LOOSE_VALIDATION": True, "CONF_NAME": "CONFIG_AMQP_AUTH_PASSWORD", "USE_DEFAULT": False, "NEED_CONFIRM": True, "CONDITION": False}, ] update_params_usage(basedefs.PACKSTACK_DOC, params, sectioned=False) group = {"GROUP_NAME": "AMQPAUTH", "DESCRIPTION": "AMQP Config Athentication parameters", "PRE_CONDITION": "CONFIG_AMQP_ENABLE_AUTH", "PRE_CONDITION_MATCH": "y", "POST_CONDITION": False, "POST_CONDITION_MATCH": True} controller.addGroup(group, params) def initSequences(controller): amqpsteps = [ {'title': 'Adding AMQP manifest entries', 'functions': [create_manifest]} ] controller.addSequence("Installing AMQP", [], [], amqpsteps) # ------------------------ step functions ------------------------- def create_manifest(config, messages): server = utils.ScriptRunner(config['CONFIG_AMQP_HOST']) if config['CONFIG_AMQP_ENABLE_SSL'] == 'y': config['CONFIG_AMQP_SSL_ENABLED'] = True config['CONFIG_AMQP_PROTOCOL'] = 'ssl' config['CONFIG_AMQP_CLIENTS_PORT'] = "5671" amqp_host = config['CONFIG_AMQP_HOST'] service = 'AMQP' ssl_key_file = '/etc/pki/tls/private/ssl_amqp.key' ssl_cert_file = '/etc/pki/tls/certs/ssl_amqp.crt' cacert = config['CONFIG_AMQP_SSL_CACERT_FILE'] = ( config['CONFIG_SSL_CACERT'] ) generate_ssl_cert(config, amqp_host, service, ssl_key_file, ssl_cert_file) else: # Set default values config['CONFIG_AMQP_CLIENTS_PORT'] = "5672" config['CONFIG_AMQP_SSL_ENABLED'] = False config['CONFIG_AMQP_PROTOCOL'] = 'tcp' if config['CONFIG_AMQP_ENABLE_AUTH'] == 'n': config['CONFIG_AMQP_AUTH_PASSWORD'] = 'guest' config['CONFIG_AMQP_AUTH_USER'] = 'guest' manifestfile = "%s_amqp.pp" % config['CONFIG_AMQP_HOST'] manifestdata = getManifestTemplate('amqp') if config['CONFIG_IP_VERSION'] == 'ipv6': config['CONFIG_AMQP_HOST_URL'] = "[%s]" % config['CONFIG_AMQP_HOST'] else: config['CONFIG_AMQP_HOST_URL'] = config['CONFIG_AMQP_HOST'] fw_details = dict() # All hosts should be able to talk to amqp for host in filtered_hosts(config, exclude=False): key = "amqp_%s" % host fw_details.setdefault(key, {}) fw_details[key]['host'] = "%s" % host fw_details[key]['service_name'] = "amqp" fw_details[key]['chain'] = "INPUT" fw_details[key]['ports'] = ['5671', '5672'] fw_details[key]['proto'] = "tcp" config['FIREWALL_AMQP_RULES'] = fw_details manifestdata += createFirewallResources('FIREWALL_AMQP_RULES') appendManifestFile(manifestfile, manifestdata, 'pre')
[ "471123674@qq.com" ]
471123674@qq.com
7283480faacc4de152ff7da36c1ab85ef857e4ab
0ec072ea843808dd2fe7077c18afbebb8fe4b243
/unrolled/scripts/launch_impacts.py
179ac2151f232435e699575b7d25e6a1a89e7812
[]
no_license
Arc-Pintade/combine-ttbar
edbbabc9b06993d19803c8dda3ce7fe812a13e24
f327e9ef73ed9c9553a86aad55421354024be40a
refs/heads/main
2023-06-16T03:35:44.844492
2021-07-13T09:13:51
2021-07-13T09:13:51
385,536,458
0
1
null
null
null
null
UTF-8
Python
false
false
1,738
py
import os, sys import argparse ################### ## Initialisation ################### parser = argparse.ArgumentParser() parser.add_argument('observable', help='display your observable') parser.add_argument('year', help='year of samples') parser.add_argument('asimov',nargs='?', help='set if asimov test', default='') args = parser.parse_args() observable = args.observable year = args.year asimov = args.asimov asi = '' if asimov == 'asimov': print '################' print '# Asimov test : ' print '################' print '' asi = '--expectSignal 1 -t -1' test = False ################### ## Core ################### print '-------------------------' print ' >>> combine on datacard ' print '-------------------------' cmd = 'text2workspace.py ./inputs/'+year+'/'+observable+'_unrolled_datacard.txt ' cmd += '-o '+observable+'_impacts.root' cmd1 = 'combineTool.py -M Impacts -d '+observable+'_impacts.root '+asi+' -m 125 ' cmd2 = cmd1 cmd3 = cmd1 cmd1 += '--doInitialFit --robustFit 1' cmd2 += '--robustFit 1 --doFits' cmd3 += '-o '+observable+'_impacts.json ' cmd4 = 'plotImpacts.py -i '+observable+'_impacts.json -o '+observable+'_impacts' os.system(cmd) os.system(cmd1) os.system(cmd2) os.system(cmd3) os.system(cmd4) if asimov == 'asimov': os.system('mv '+observable+'_impacts* impacts/'+year+'/asimov/') os.system('mv *.png impacts/'+year+'/asimov/') os.system('mv *.root impacts/'+year+'/asimov/') os.system('mv *.out impacts/'+year+'/asimov/') else: os.system('mv '+observable+'_impacts* impacts/'+year+'/') os.system('mv *.png impacts/'+year+'/') os.system('mv *.root impacts/'+year+'/') os.system('mv *.out impacts/'+year+'/')
[ "a.carle@ipnl.in2p3.fr" ]
a.carle@ipnl.in2p3.fr
83e8e38db5ad1710bc6f9d49896e7d20d3f3ee3b
599c925482db61a256d3e0c44c62beb607c5367b
/Config.py
3a780cfd72ac3e3aba59bc5db630733ae46f7325
[ "MIT" ]
permissive
bubundas17/ai-btc-trading-bot
d994ec85ea917f64f3ec1b630c4f264b6ff8cbb4
8be09c24e171ed1bd5f09d802cbfdd7a83246b4e
refs/heads/main
2023-08-08T09:09:45.803740
2021-08-30T06:50:46
2021-08-30T06:50:46
400,804,251
0
0
null
null
null
null
UTF-8
Python
false
false
668
py
DATASET_DIR = "datasets/" COIN_PAIR = "BTC-USD" GRANULARITY = 60 # Data every 1 minute TRAINING_MONTHS = ["2018_06","2018_07","2018_08","2018_09","2018_10","2018_11","2018_12","2019_01", "2019_02","2019_03","2019_04","2019_05","2019_06","2019_07","2019_08","2019_09", "2019_10","2019_11","2019_12","2020_01","2020_02","2020_03","2020_04","2020_05", "2020_06","2020_07","2020_08"] TESTING_MONTHS = ["2020_09","2020_10"] # Model and Auto Trader CHANGE_RATE_THRESHOLD = 0.005 TRAINING_WINDOW = 360 # Window to use for training in minutes LABELING_WINDOW = 360 # How far ahead to look for labeling / prediction
[ "bubundas17@gmail.com" ]
bubundas17@gmail.com
57cd82ee8cf61947cac176ab1e3935c3582c06d2
bc2a96e8b529b0c750f6bc1d0424300af9743904
/acapy_client/models/credential_definition_send_request.py
8d1879bd302faeaabbeac1ec17a5fbce0eddf4c4
[ "Apache-2.0" ]
permissive
TimoGlastra/acapy-client
d091fd67c97a57f2b3462353459780281de51281
d92ef607ba2ff1152ec15429f2edb20976991424
refs/heads/main
2023-06-29T22:45:07.541728
2021-08-03T15:54:48
2021-08-03T15:54:48
396,015,854
1
0
Apache-2.0
2021-08-14T13:22:28
2021-08-14T13:22:27
null
UTF-8
Python
false
false
2,441
py
from typing import Any, Dict, List, Type, TypeVar, Union import attr from ..types import UNSET, Unset T = TypeVar("T", bound="CredentialDefinitionSendRequest") @attr.s(auto_attribs=True) class CredentialDefinitionSendRequest: """ """ revocation_registry_size: Union[Unset, int] = UNSET schema_id: Union[Unset, str] = UNSET support_revocation: Union[Unset, bool] = UNSET tag: Union[Unset, str] = UNSET additional_properties: Dict[str, Any] = attr.ib(init=False, factory=dict) def to_dict(self) -> Dict[str, Any]: revocation_registry_size = self.revocation_registry_size schema_id = self.schema_id support_revocation = self.support_revocation tag = self.tag field_dict: Dict[str, Any] = {} field_dict.update(self.additional_properties) field_dict.update({}) if revocation_registry_size is not UNSET: field_dict["revocation_registry_size"] = revocation_registry_size if schema_id is not UNSET: field_dict["schema_id"] = schema_id if support_revocation is not UNSET: field_dict["support_revocation"] = support_revocation if tag is not UNSET: field_dict["tag"] = tag return field_dict @classmethod def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: d = src_dict.copy() revocation_registry_size = d.pop("revocation_registry_size", UNSET) schema_id = d.pop("schema_id", UNSET) support_revocation = d.pop("support_revocation", UNSET) tag = d.pop("tag", UNSET) credential_definition_send_request = cls( revocation_registry_size=revocation_registry_size, schema_id=schema_id, support_revocation=support_revocation, tag=tag, ) credential_definition_send_request.additional_properties = d return credential_definition_send_request @property def additional_keys(self) -> List[str]: return list(self.additional_properties.keys()) def __getitem__(self, key: str) -> Any: return self.additional_properties[key] def __setitem__(self, key: str, value: Any) -> None: self.additional_properties[key] = value def __delitem__(self, key: str) -> None: del self.additional_properties[key] def __contains__(self, key: str) -> bool: return key in self.additional_properties
[ "dbluhm@pm.me" ]
dbluhm@pm.me
27282a88578e3530b456399cac4b11018cde5044
a8e2c66b3ebadfc17ee9aee197b3f466534cee16
/ytn11/wh/wh/items.py
0c48330df2942d96bbb37a839696a43850e30629
[]
no_license
yintiannong/98kar
49b6db186a4543a7c50671df990bb491846c1a98
3863529f57e9d2d9bc1bdf8188916e25ad289db0
refs/heads/master
2022-01-07T05:49:31.566453
2019-05-22T07:04:45
2019-05-22T07:04:45
187,794,966
0
0
null
null
null
null
UTF-8
Python
false
false
849
py
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy class WhItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() company = scrapy.Field() company_id = scrapy.Field() postion_id = scrapy.Field() company_type = scrapy.Field() company_size = scrapy.Field() url = scrapy.Field() postion = scrapy.Field() salary = scrapy.Field() education=scrapy.Field() address = scrapy.Field() exe = scrapy.Field() job_type = scrapy.Field() update_time = scrapy.Field() data_from = scrapy.Field() desc_job = scrapy.Field() salary2 = scrapy.Field() conpany_address = scrapy.Field() phone_num = scrapy.Field() hr_name = scrapy.Field()
[ "1532295578@qq.com" ]
1532295578@qq.com
90ddd58ed63dd5bf7a2c7433de0046b40811ee14
4d7fd59810aad8bd63bbf8fcc2dbb1158009bdd0
/split-2020-05-02_15-13-21-928.py
ca6b708705f54cac4c2b848bb21eb51a42814426
[]
no_license
doughbuoy/learning_python
0346ffd97c310a9bd4fec69c2d5958fb0fc71dcc
36816c2cb024b60366c5df0d4bf6e11d142e7ece
refs/heads/master
2022-12-04T05:57:44.301124
2020-08-28T00:44:41
2020-08-28T00:44:41
259,989,146
0
0
null
2020-08-28T00:44:43
2020-04-29T17:05:10
Python
UTF-8
Python
false
false
71
py
s1 = ["the", "rain", "in", "spain"] s2 = " ".join(list) print(s2)
[ "noreply@github.com" ]
noreply@github.com
ea084e6356250780555a7360743a44f37ffc78be
b38004d90ce4c2367e24635c995655c51bbcacc1
/project/settings.py
c6022b7ff2dcc6ea9d5a49d456d43f1683045882
[]
no_license
pplusua/djng
7db5bf43d564ead39ba2abc886671b7ca7a52117
42c949f26f8ba5f6d356fbec4c6e634724981ac9
refs/heads/main
2023-04-30T18:03:03.453538
2021-05-23T20:31:42
2021-05-23T20:31:42
370,151,359
0
0
null
null
null
null
UTF-8
Python
false
false
3,512
py
""" Django settings for project project. Generated by 'django-admin startproject' using Django 3.2. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-n62t2^-zkku7prpcvocm%_w+a3+kcs9(1p5bp1beug1tf7ezv1' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ["134.249.120.125"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'news.apps.NewsConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'project.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'ru' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'project/static'), ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
[ "pplusua@gmail.com" ]
pplusua@gmail.com
fd390f8efeda3d52513efe145ef2bdebcc777c5a
e8d97c6d1544d5ddcf24e511d003a2999fdef2f7
/config.py
c69d7c80817655a4c85d0b5044d9d70abcbaa8a1
[ "MIT" ]
permissive
rotide/rpi.tv
e94c34b55ba80aca917ad6bc6b59d0b666d9b5fc
d71ab115a02f1fcf10135a7b73ac0017329ccdff
refs/heads/master
2021-01-25T14:03:52.962950
2018-04-01T11:32:27
2018-04-01T11:32:27
123,646,319
0
0
null
null
null
null
UTF-8
Python
false
false
565
py
import os from dotenv import load_dotenv basedir = os.path.abspath(os.path.dirname(__file__)) load_dotenv(os.path.join(basedir, '.env')) class Config(object): # Edit in .env file SECRET_KEY = os.environ.get('SECRET_KEY') or 'NOT_so_SECR3T_kEY' # User Configurables #SQLALCHEMY_DATABASE_URI = "sqlite:////path/to/database/app.db" SQLALCHEMY_DATABASE_URI = "mysql+pymysql://rpitv:testpassword@172.17.0.2:3306/rpitv" SQLALCHEMY_TRACK_MODIFICATIONS = False CELERY_BROKER_URL = "redis://localhost:6379/0" VIDEO_BASE_DIR = "/mnt/media"
[ "timo@rotide.com" ]
timo@rotide.com
23db145ef45ccfbc249edf95091b895c9b2e79d5
c09beed3fc2a3233a9eba680ffcdfe37349ad221
/controller/fonts.py
537d0db5b5e32cf63fc2b5695a0d5483411a9e92
[ "MIT" ]
permissive
luctowers/pixel-perf-monitor
0c50d384b6310be3a4a584f7a0a5cfea87865d7e
75c45206102a6c3a5a3e55cf4c14643db6706314
refs/heads/main
2023-01-21T11:23:24.969718
2020-11-30T01:10:19
2020-11-30T01:10:19
307,035,285
0
0
null
null
null
null
UTF-8
Python
false
false
101
py
from adafruit_bitmap_font import bitmap_font MINISTAT_FONT = bitmap_font.load_font("/ministat.bdf")
[ "luctowers@gmail.com" ]
luctowers@gmail.com
ade0b23d401c7a201eec94e034a7bb38e413996e
9abc2f4fbf1b31b5a56507437b4a8d9c3f3db7e6
/users/urls.py
98678c65848e0cd95f42b0434063e6edf15da19f
[]
no_license
odbalogun/ticketr
e9fe8461d66dabe395f0e1af8fbecc67dbb16e97
94f24c82f407f861f1614a151feb3fdd62b283e5
refs/heads/master
2022-11-30T22:40:30.931160
2019-08-09T14:34:38
2019-08-09T14:34:38
188,833,600
0
0
null
2022-11-22T03:50:30
2019-05-27T11:50:07
Python
UTF-8
Python
false
false
595
py
from django.urls import path # from .views import CustomLoginView, UserCreateView, UserListView, CustomLogoutView from .views import CustomLoginView, CustomLogoutView, ProfileView from django.contrib.auth.decorators import login_required app_name = 'users' urlpatterns = [ # path('', UserListView.as_view(), name='list'), path('login/', CustomLoginView.as_view(), name='login'), path('logout/', CustomLogoutView.as_view(), name='logout'), path('profile/', login_required(ProfileView.as_view()), name='profile') # path('create/', UserCreateView.as_view(), name='create'), ]
[ "oduntan@live.com" ]
oduntan@live.com
3a481645968d196dbced2a5b0818981b0be1d315
ec11e20bc42167414c1a785f653bbbb588173b02
/ddd/infrastructure/provider/catalog_provider_impl.py
f8a4f4d23d2d79d99b5b244293d4faf4089e990c
[ "MIT" ]
permissive
shijie3/python_ddd_sample
b5cdc1903737d3ea50359d28fa812175866a774d
cdd50950800869d2a70a8b488c46ce7fb5cdbc85
refs/heads/master
2021-05-06T09:17:11.472927
2017-12-13T16:20:23
2017-12-13T16:20:23
114,055,251
0
0
null
2017-12-13T00:50:45
2017-12-13T00:50:44
null
UTF-8
Python
false
false
455
py
# coding=utf-8 from domain.provider.catalog_provider import CatalogProvider class CatalogProviderImpl(CatalogProvider): def check_status(self, package): print('check package status') if __name__ == '__main__': from domain.base import Provider provider = CatalogProviderImpl() print('Subclass:', issubclass(CatalogProviderImpl, Provider)) print('Instance:', isinstance(provider, Provider)) provider.check_status(None)
[ "15950562214@sina.cn" ]
15950562214@sina.cn
481d85e6d7a0a603c4b60c1f68028ce733577d8c
8caafdb429f464cc74759daedb72f75e6482bdf5
/L3 convert the matrix to a sparse matrix using some threshold value.py
b21e934bf683224e974c20405ef0712c74248ba1
[]
no_license
K-Jaswanth/DSP-Lab-and-Assignments
b782a2db1e357d6501e3274e5d31810c7621b6bb
59fcf6fd9ba5aeb964007d1418627006fa71ee62
refs/heads/master
2023-01-31T22:44:42.495877
2020-12-16T03:40:42
2020-12-16T03:40:42
291,894,654
0
0
null
null
null
null
UTF-8
Python
false
false
792
py
#convert the matrix to a sparse matrix using some threshold value a= int(input("Enter Number of rows:")) b= int(input("Enter columns:")) matrix=[] for i in range (a): c=[] for j in range(b): j=int(input("Enter Number in matrix"+str(i)+" "+str(j)+" ")) c.append(j) print() matrix.append(c) for i in range (a): for j in range (b): print (matrix [i][j],end="") print() thres=1 for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] <thres+1: matrix[i][j]=0 sparseMatrix = [] for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] != 0: temp = [i, j, matrix[i][j]] sparseMatrix.append(temp) print(sparseMatrix)
[ "noreply@github.com" ]
noreply@github.com
787c22defeb8c8744d74df13cbcedfae63fabfcc
c61d334ada07f688d0b4ab1418effa5e1009b234
/setup.py
c24257ff607c07d6255eb6502699b766561adf4c
[ "MIT" ]
permissive
ShrekFelix/Variational-AutoEncoder
50746ad38cf557ac9683b2c51c1f80c575c23823
de4bbb9fc0e048be722bfd458aa2cdfc86fc9604
refs/heads/master
2020-03-15T00:54:24.127187
2018-05-03T03:10:48
2018-05-03T03:10:48
131,881,040
3
0
null
null
null
null
UTF-8
Python
false
false
408
py
import setuptools setuptools.setup(name = "Variational_Autoencoder", version = "1.0.2", author='Weiyu Yan', author_email='weiyu.yan@duke.edu', url='https://github.com/ShrekFelix/Variational-AutoEncoder', py_modules = ['VAE'], packages=setuptools.find_packages(), python_requires='>=3', )
[ "wy47@duke.edu" ]
wy47@duke.edu
03b4ed7bc4ae7aa65adab896b0959ce2eca16921
d02bace077e11573b2f3f03e5a1bf4bc2d0986e7
/workflow/rules/mapping_classified_isoforms.smk
6a4cf4ddd9e2a70d439c91e318a93dfef59eded7
[ "BSD-3-Clause" ]
permissive
wuzengding/PBFLIP
dd85af0ef0d09b75191a4804327ea609460813dd
f356e3a0d8fedc39ab81ae89ffd937eb4a49ffeb
refs/heads/master
2023-09-03T10:37:34.825399
2021-11-15T15:07:22
2021-11-15T15:07:22
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,631
smk
rule run_classified_tx_mapping: input: squanti3_output_filtered = rules.run_sqanti3_filter.output[5] output: squanti3_output_filtered_bam_tx = rules.all.input[33] params: genome = config["REFERENCES"]["genome"], ax = "splice", secondary = "no", o = "-O6,24", b4 = "-B4", uf = "-uf", temp_out_sam = "results/FinalResults/{0}_sqanti3_classification.filtered_lite_mapped_hg38_sorted.sam".format(CASENAME), picard = config["PICARD"]["default"], mem = "-Xmx40g", parallel_threads = "-XX:ParallelGCThreads=1", temp_dir = "-Djava.io.tmpdir=/data/tmp", sort_order = "coordinate" log: "log/run_classified_tx_mapping.log" threads: 18 shell: """ {config[MAPPERS][mapper_default]} \ -t {threads} \ -ax {params.ax} \ --secondary={params.secondary} \ {params.o} \ {params.b4} \ {params.uf} \ {params.genome} \ {input.squanti3_output_filtered} > {params.temp_out_sam} 2> {log} java {params.mem} {params.parallel_threads} {params.temp_dir} \ -jar {params.picard} \ SortSam \ I={params.temp_out_sam} \ O={output.squanti3_output_filtered_bam_tx} \ SORT_ORDER={params.sort_order} 2>> {log} samtools index {output.squanti3_output_filtered_bam_tx} 2>> {log} rm {params.temp_out_sam} """
[ "saranga.wijeratne@nationwidechildrens.org" ]
saranga.wijeratne@nationwidechildrens.org
90e60df945a1366f436926f97bb2b496e2311a33
5dc12bcddcfcf4a9a07792058dff9e27891ed145
/recursion/sum.py
dedeeb9adbbdc89243ef4e86142b757a6b18f949
[]
no_license
ajitabhkalta/Python-DataStructures
e18079a68d89218aa2bacfe36f6e70966a968779
c3e498154ecca4c366ed7613039779b112335715
refs/heads/master
2020-07-01T20:16:02.371302
2019-08-19T16:41:03
2019-08-19T16:41:03
201,286,881
0
0
null
null
null
null
UTF-8
Python
false
false
88
py
def rec_sum(n): if n==0: return 0 else: return n+ rec_sum(n-1)
[ "ajitabhkalta@gmail.com" ]
ajitabhkalta@gmail.com
311b64e499752b8f19be4d85c59a5b14455ada39
a1a57977131ea917a3f3094dae4a3d18846103c0
/unittests/pytests/problems/TestTimeStepUser.py
c53c39a3337525c4aa9aa5702ae8367062012113
[ "MIT" ]
permissive
rwalkerlewis/pylith
cef02d5543e99a3e778a1c530967e6b5f1d5dcba
8d0170324d3fcdc5e6c4281759c680faa5dd8d38
refs/heads/master
2023-08-24T18:27:30.877550
2020-08-05T16:37:28
2020-08-05T16:37:28
154,047,591
0
0
MIT
2018-10-21T20:05:59
2018-10-21T20:05:59
null
UTF-8
Python
false
false
4,095
py
#!/usr/bin/env python # # ====================================================================== # # Brad T. Aagaard, U.S. Geological Survey # Charles A. Williams, GNS Science # Matthew G. Knepley, University of Chicago # # This code was developed as part of the Computational Infrastructure # for Geodynamics (http://geodynamics.org). # # Copyright (c) 2010-2017 University of California, Davis # # See COPYING for license information. # # ====================================================================== # ## @file unittests/pytests/problems/TestTimeStepUser.py ## @brief Unit testing of TimeStepUser object. import unittest from pylith.problems.TimeStepUser import TimeStepUser from pyre.units.time import second,year stepsE = [2*1.0, 2*2.0, 2*3.0] # ---------------------------------------------------------------------- class Integrator: def __init__(self, dt): self.dt = dt def stableTimeStep(self, mesh): return self.dt # ---------------------------------------------------------------------- class TestTimeStepUser(unittest.TestCase): """ Unit testing of TimeStepUser object. """ def setUp(self): from spatialdata.units.Nondimensional import Nondimensional normalizer = Nondimensional() normalizer._configure() normalizer.setTimeScale(0.5*year) tstep = TimeStepUser() tstep._configure() tstep.filename = "data/timesteps.txt" tstep.preinitialize() tstep.initialize(normalizer) self.tstep = tstep return def test_constructor(self): """ Test constructor. """ tstep = TimeStepUser() tstep._configure() return def test_initialize(self): """ Test initialize(). """ tstep = self.tstep for stepE, step in zip(stepsE, tstep.steps): self.assertEqual(stepE, step) return def test_numTimeSteps(self): """ Test numTimeSteps(). """ tstep = self.tstep self.assertEqual(1, tstep.numTimeSteps()) tstep.totalTimeN = 12.0 / 0.5 # nondimensionalize self.assertEqual(6, tstep.numTimeSteps()) tstep.loopSteps = True tstep.totalTimeN = 7.0 / 0.5 # nondimensionalize self.assertEqual(5, tstep.numTimeSteps()) return def test_timeStep(self): """ Test timeStep(). """ tstep = self.tstep step1 = 1.0 / 0.5 # nondimensionalize step2 = 2.0 / 0.5 # nondimensionalize step3 = 3.0 / 0.5 # nondimensionalize integrators = [Integrator(40.0), Integrator(80.0)] from pylith.topology.Mesh import Mesh mesh = Mesh() self.assertEqual(step1, tstep.timeStep(mesh, integrators)) self.assertEqual(step2, tstep.timeStep(mesh, integrators)) self.assertEqual(step3, tstep.timeStep(mesh, integrators)) self.assertEqual(step3, tstep.timeStep(mesh, integrators)) self.assertEqual(step3, tstep.timeStep(mesh, integrators)) tstep.index = 0 tstep.loopSteps = True self.assertEqual(step1, tstep.timeStep(mesh, integrators)) self.assertEqual(step2, tstep.timeStep(mesh, integrators)) self.assertEqual(step3, tstep.timeStep(mesh, integrators)) self.assertEqual(step1, tstep.timeStep(mesh, integrators)) self.assertEqual(step2, tstep.timeStep(mesh, integrators)) integrators = [Integrator(0.01), Integrator(8.0)] caught = False try: tstep.timeStep(mesh, integrators) except RuntimeError: caught = True self.failUnless(caught) return def test_currentStep(self): """ Test currentStep(). """ tstep = self.tstep integrators = [Integrator(4.0), Integrator(8.0)] from pylith.topology.Mesh import Mesh from pylith.mpi.Communicator import petsc_comm_world mesh = Mesh() #mesh.setComm(petsc_comm_world()) tstep.timeStep(mesh, integrators) stepE = 1.0 / 0.5 # Nondimensionalize self.assertEqual(stepE, tstep.currentStep()) return def test_factory(self): """ Test factory method. """ from pylith.problems.TimeStepUser import time_step ts = time_step() return # End of file
[ "baagaard@usgs.gov" ]
baagaard@usgs.gov
ebc5ee0c112bd9c061dc40a028fd788a5af265fb
ad219848618b2625d15df3dd4c8f5deab91e469e
/udp_transport/udp_client.py
92142ae1ed36552413937dc4a15a3949701d66c6
[]
no_license
suse-grit/IO_network
bfbeb407af5a132aa42b66f93305ba853fc5ff11
d0cec22e0d71a5f720f88aad0ae7232875eb84a0
refs/heads/master
2022-04-25T02:19:10.186434
2020-04-17T01:30:20
2020-04-17T01:30:20
256,127,777
1
0
null
null
null
null
UTF-8
Python
false
false
539
py
# 基于UDP传输服务的网络套接字实现(client) from socket import * import sys ADDR = ("127.0.0.1", 8888) client = socket(AF_INET, SOCK_DGRAM) # 设置客户端套接字IO为超时非阻塞(如果服务端无响应,则客户端程序退出!) client.settimeout(3) while True: try: data = input("meg>>").encode() client.sendto(data, ADDR) meg, addr = client.recvfrom(1024) print(addr, meg.decode(), sep=":") except timeout: sys.exit("服务器无响应,程序退出!")
[ "1129212285@qq.com" ]
1129212285@qq.com
706c3a6306bafbc40a4821e71421ca92672a7840
4bf67ba6af581c75676663470bcb56c93b1f9e62
/src/Problem_4/answer.py
0e7943846cabcb81f731d27324f6f6ce45b9367f
[ "MIT" ]
permissive
MattSeen/project-euler
e56119dfd8cb305f3db9107d824c8984b5b99587
7a0b5ce6ed906415b34a37a0ccde7c0a486dd8d4
refs/heads/master
2020-05-18T05:59:00.564573
2014-02-10T10:23:45
2014-02-10T10:23:45
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,304
py
''' My attempt at Problem 4. This provides the right answer, however it is quite slow for what it is doing and I would like to know how I can go about speeding it up. ''' def is_palindromic(num): ''' Test if a number is palindromic, Essentially a string test... probably a performance bottle neck. Alterative mathematical implementation ''' test_value = abs(num) if(test_value < 10): return True # temp = str(test_value) # return (temp == temp[::-1]) num = test_value reverse = 0 while num > 0: remainder = num % 10 reverse = reverse * 10 + remainder num = num / 10 return (test_value == reverse) def get_largest_palindrom(range_start, range_end): ''' Something goes here. ''' if range_start > range_end: return -1 largest_num = 0 for outer in xrange(range_start, range_end): for inner in xrange(range_start, range_end): num = outer * inner if is_palindromic(num): if largest_num < num: largest_num = num return largest_num def main(): ''' Entry point. ''' answer = get_largest_palindrom(100, 999) print answer if __name__ == '__main__': main()
[ "matt.c1986+github.project.euler@gmail.com" ]
matt.c1986+github.project.euler@gmail.com
286fe2e7cad64b074222523912f3524af494f398
fde6fdafd494ae3b088c9a371f45209087250de5
/travello/migrations/0001_initial.py
494a48226eea32fe7450442da0f78913018df60a
[]
no_license
ashutosh181/Django-Projects
9e94aae3ad91a727844dc1d1decbb3936d685a7f
ec110a98c80b3029beb0ccd56d33de7e18165322
refs/heads/master
2022-11-03T12:34:40.242958
2020-06-15T21:14:28
2020-06-15T21:14:28
272,537,143
0
1
null
2020-06-15T20:57:01
2020-06-15T20:28:10
HTML
UTF-8
Python
false
false
639
py
# Generated by Django 3.0.1 on 2019-12-26 20:16 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Destination', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ('img', models.ImageField(upload_to='pics')), ('offer', models.BooleanField(default=False)), ], ), ]
[ "noreply@github.com" ]
noreply@github.com
a4be89634604128b43e928cc1f94b4b75f7f344c
f9c0650e70d7ae5bf5b071c57e6e2358fdd856af
/vital_site/vital/views/student_view.py
634ae58818a8a07327ce3dba8dbe6bfda2b81752
[]
no_license
mrunmayichuri/virtual_lab
36f60a448c41e77027d532903ea051e896355aec
40d8004af8841a2170b796501a54e7579beaba94
refs/heads/master
2021-01-20T16:34:54.494460
2016-05-27T16:13:44
2016-05-27T16:13:44
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,383
py
from django.shortcuts import get_object_or_404, render, redirect from django.contrib.auth.decorators import login_required from ..models import Course, Registered_Courses, Virtual_Machines from ..forms import Course_Registration_Form from ..utils import audit import logging logger = logging.getLogger(__name__) # Create your views here. @login_required(login_url='/vital/login/') def registered_courses(request): logger.debug("In registered courses") # reg_courses = Registered_Courses.objects.filter(user_id=request.user.id, course__status='ACTIVE') reg_courses = Registered_Courses.objects.filter(user_id=request.user.id) message = '' if len(reg_courses) == 0: message = 'You have no registered courses' return render(request, 'vital/registered_courses.html', {'reg_courses': reg_courses, 'message':message}) @login_required(login_url='/vital/login/') def course_vms(request, course_id): logger.debug("in course vms") virtual_machines = Virtual_Machines.objects.filter(course_id=course_id) return render(request, 'vital/course_vms.html', {'virtual_machines': virtual_machines}) @login_required(login_url='/vital/login/') def unregister_from_course(request, course_id): logger.debug("in course unregister") user = request.user reg_courses = Registered_Courses.objects.filter(course_id=course_id, user_id=user.id) course_to_remove = reg_courses[0] audit(request, course_to_remove, 'User '+str(user.id)+' unregistered from course -'+str(course_id)) course_to_remove.delete() return redirect('/vital/courses/registered/') def dummy_console(request): return render(request, 'vital/dummy.html') @login_required(login_url='/vital/login/') def register_for_course(request): logger.debug("in register for course") error_message = '' if request.method == 'POST': form = Course_Registration_Form(request.POST) if form.is_valid(): logger.debug(form.cleaned_data['course_registration_code']+"<>"+str(request.user.id)+"<>"+ str(request.user.is_faculty)) try: course = Course.objects.get(registration_code=form.cleaned_data['course_registration_code']) user = request.user if len(Registered_Courses.objects.filter(course_id=course.id, user_id=user.id)) > 0: error_message = 'You have already registered for this course' else: if course.capacity > len(Registered_Courses.objects.filter(course_id=course.id)): registered_course = Registered_Courses(course_id=course.id, user_id=user.id) registered_course.save() audit(request, registered_course, 'User '+str(user.id)+' registered for new course -'+str(course.id)) # PLACE TO DO CREATING VMS FOR USER FOR THE COURSE return redirect('/vital/courses/registered/') else: error_message = 'The course has reached its maximum student capacity.' except Course.DoesNotExist: error_message = 'Invalid registration code. Check again.' else: form = Course_Registration_Form() return render(request, 'vital/course_register.html', {'form': form, 'error_message': error_message})
[ "richie@Richies-MBP.fios-router.home" ]
richie@Richies-MBP.fios-router.home
506619fa2048aa6c9646656e136d94d4afed722d
390181ba87477d4d7b8b3ccf209a3d12f1b9528f
/base/IO/do_string.py
d37a49271ed81090eb49b78bd612852e5241b30a
[]
no_license
emperwang/python_operation
8f5d75255cfc7f83911f784224f098bcc8b9e84f
9b4b85fa23ce531cff5c75f08a9e84735e7b5f37
refs/heads/master
2023-02-20T13:14:50.960939
2022-09-17T01:04:44
2022-09-17T01:04:44
158,133,758
1
0
null
2023-02-16T04:33:21
2018-11-18T22:36:47
Python
UTF-8
Python
false
false
375
py
#!/usr/bin/env python3 # -*- coding:utf-8 -*- from io import StringIO # write to string io f = StringIO() f.write('hello') f.write(' ') f.write('world!') print(f.getvalue()) #Read from stringio f = StringIO('水面细风生,\n菱歌慢慢声。\n客亭临小市,\n灯火夜妆明。') while True: s = f.readline() if s == '': break print(s.strip())
[ "544094478@qq.com" ]
544094478@qq.com
0f6854369ee7234b1e1fa884efb0fdd17d10e3cf
b0435e890ca9b8b73cb6a15e531ccdac13d4c97d
/182/182.py
f29587701ce58b450581c397f39fdb46ba3365ae
[]
no_license
zlsa/dailyprogrammer
261d00afa8051b2aaa179a86aad89012c070beaa
b66e21b6d6b6f2527fee2f6813d0ae4caffda06f
refs/heads/master
2016-08-08T15:20:03.651014
2014-10-03T23:34:13
2014-10-03T23:34:13
null
0
0
null
null
null
null
UTF-8
Python
false
false
729
py
#!/usr/bin/python3 with open("input.txt", "r") as f: line = f.readline().strip().split() cols, width, spaces = [int(x) for x in line] x = f.read().split() output = [] buf = "" for word in x: if len(word) + len(buf) + 1 > width: output.append(buf) buf = "" buf = (buf + " " + word).strip() lines = int(len(output) / cols) columns = [[]] counter = 0 for i in range(0, len(output)): if counter > lines: columns.append([]) counter = 0 columns[-1].append(output[i]) counter += 1 row = 0 output = "" for i in range(0, lines): for col in range(0, cols): output += columns[col][i].ljust(width) + (" " * spaces) output += "\n" print(output)
[ "zlsa@outlook.com" ]
zlsa@outlook.com
05aa5d78f1a77c1849dde9dff4856a79eddc89a7
c1c87cd334972c01935dbb72769064e5d0066ac8
/pickpack/robots/scratchpad.py
2d469bd1d6d84f59c8bd0ec2db7949dd53ec5962
[]
no_license
defgsus/pypickpack
576e9471c9cc7cce60c1010d51b4ea85ec00ecfc
8a604ec1502c615bf24d77f09d564962c3d04930
refs/heads/master
2022-12-28T13:17:18.306748
2020-10-09T00:50:41
2020-10-09T00:50:41
269,505,707
0
0
null
null
null
null
UTF-8
Python
false
false
5,253
py
import random from .base import RobotBase from .._2d import direction_int from ..astar import astar_search from ..log import log from ..static_map import StaticMap from ..items import Article, PickOrder class RandomRobot(RobotBase): def __init__(self, id): super().__init__(id) def process(self, world, time_delta): if self.is_next_move_frame(world): if random.randrange(10) == 0: self.dir_x, self.dir_y = random.choice(((-1, 0), (1, 0), (0, -1), (0, 1))) if not world.agent_move(self, self.direction): self.dir_x, self.dir_y = random.choice(((-1, 0), (1, 0), (0, -1), (0, 1))) class RobotFollowPlayer(RobotBase): def __init__(self, id): super().__init__(id) def process(self, world, time_delta): if self.is_next_move_frame(world): way_to_player = astar_search( self.position, world.player.position, lambda pos: self.get_adjacent_nodes(world, pos, exclude_agents={self}) ) self.debug_way = None if way_to_player: next_pos = way_to_player[1] dirx, diry = direction_int(self.position, next_pos) if dirx or diry: world.agent_move(self, (dirx, diry)) self.debug_way = way_to_player class Robot(RobotBase): def __init__(self, id): super().__init__(id) self.performance = 0 def copy(self): c = super().copy() c.performance = self.performance return c def on_has_put(self, item, position=None, other_agent=None): from ..agents import Package from ..items import Article if isinstance(item, Article): if isinstance(other_agent, Package): self.performance += 1 def process(self, world, time_delta): possible_actions = self.get_possible_actions(world) evaluated_actions = self.evaluate_actions(world, possible_actions) #possible_actions.sort(key=lambda action: action.get_estimated_cost(world, self)) #log(possible_actions) #log(evaluated_actions) if evaluated_actions: log(evaluated_actions[0]) action = evaluated_actions[0]["action"] #action = random.choice(possible_actions) action.execute(world, self) def get_possible_actions(self, world): from ..actions import MoveTo, MoveBefore, PickDirection, PutDirection from ..agents import Player, Package, Shelf, Computer from ..items import Article, PickOrder classes_to_approach = (Computer, PickOrder, Player, Robot, Package, Shelf, Article) possible_actions = [ # MoveBefore(world.player.position), PickDirection((-1, 0)), PickDirection((1, 0)), PickDirection((0, -1)), PickDirection((0, 1)), ] for item in self.items: possible_actions += [ PutDirection((-1, 0), item.id), PutDirection((1, 0), item.id), PutDirection((0, -1), item.id), PutDirection((0, 1), item.id), ] for klass in classes_to_approach: agent = world.get_closest_agent(self.position, klass, exclude_agents=[self]) if agent: possible_actions.append(MoveBefore(agent.position)) return possible_actions def evaluate_actions(self, world, actions): ret_actions = [] for action in actions: value = self._evaluate_action(world, action, depth=1) if value is not None: ret_actions.append({ "action": action, "value": value, }) ret_actions.sort(key=lambda a: -a["value"]) return ret_actions def _evaluate_action(self, world, action, depth): action = action.copy() world_copy = world.copy() self_copy = world_copy.agents.get_by_id(self.id) action_passed = False for i in range(100): if not action.execute(world_copy, self_copy): break if action.is_finished(world_copy, self_copy): action_passed = True break if not action_passed: return cur_value = self_copy.get_heuristic_value(world_copy) if depth < 1: return cur_value best_action, best_value = None, None new_actions = self_copy.get_possible_actions(world_copy) for new_action in new_actions: value = self._evaluate_action(world_copy, new_action, depth - 1) if value is not None: if best_value is None or value > best_value: best_action, best_value = new_action, value return max(best_value, cur_value) if best_value is not None else cur_value def get_heuristic_value(self, world): value = 0 value += min(0, self.max_items - len(self.items) * 4) value += len(self.items_by_class(Article)) * 2 value += len(self.items_by_class(PickOrder)) * 3 value += self.performance * 5 return value
[ "s.berke@netzkolchose.de" ]
s.berke@netzkolchose.de
e28bd946d5521c44aeca3d41a3f8e06641c1bca6
498c6775739fedca23ad3a78151106bb5496185a
/back_end_mod_python/locker_info.py
baba43db2b7bbfca6e23431c967efed711438fa1
[]
no_license
dimahajan/locker_system
31a0bc5a87531d9491397f29c7a750fe173d18b8
7b18d50dec2377b93745455146fec636994d7e29
refs/heads/master
2020-05-06T15:38:46.546067
2019-05-03T00:04:52
2019-05-03T00:04:52
180,200,832
0
0
null
null
null
null
UTF-8
Python
false
false
2,932
py
import MySQLdb import json from config_path import data import datetime def add(self, key, val): self[key] = val def index(req): db = MySQLdb.connect("localhost",data.mysql_user,data.mysql_pswd,data.database) cursor = db.cursor() s = "select lk_id from locker where cb_id=%s;"%(req.form['cb_id']); cursor.execute(s); row_headers=[x[0] for x in cursor.description] #this will extract row headers rvs = cursor.fetchall() json_data=[] for result in rvs: json_data.append(dict(zip(row_headers,result))) s = "select lk_id from locker_issues where cb_id=%s and upto_date > '%s';"%(req.form['cb_id'], str(datetime.datetime.now())); cursor.execute(s); rv = cursor.fetchall() rv = [i[0] for i in rv] [add(data1,'assigned', True) if int(data1['lk_id']) in rv else add(data1,'assigned', False) for data1 in json_data] if(req.form['std']=='Y'): s = "select lk_id, a.roll_no, name, from_date, upto_date from (select name, roll_no from student where roll_no in (select roll_no from locker_issues where cb_id=%s and upto_date > '%s')) as a JOIN (select roll_no, lk_id, from_date, upto_date from locker_issues where cb_id=%s and upto_date > '%s') as b ON a.roll_no = b.roll_no;"%(req.form['cb_id'], str(datetime.datetime.now()), req.form['cb_id'], str(datetime.datetime.now())); cursor.execute(s); row_headers=[x[0] for x in cursor.description] #this will extract row headers rv = cursor.fetchall() json_data1=[] for result in rv: json_data1.append(dict(zip(row_headers,result))) ids = [dt['lk_id'] for dt in json_data1] rvs = [i[0] for i in rvs] ls = [] for rs in rvs: for jd in json_data1: if(rs == jd['lk_id']): ls.append(jd) break if(rs not in ids): ls.append({'lk_id': rs, 'roll_no': 0}) rls =[int(i['roll_no']) for i in ls ] s = 'select rollno, img from imgpath where rollno in %s'%(str(tuple(rls))) cursor.execute(s); row_headers=[x[0] for x in cursor.description] #this will extract row headers rv = cursor.fetchall() json_data2=[] for result in rv: json_data2.append(dict(zip(row_headers,result))) for i in ls: for j in json_data2: if i['roll_no'] == j['rollno']: i['img'] = j['img'] break; return json.dumps(ls, indent=4, sort_keys=True, default=str)
[ "mahajandi927@gmail.com" ]
mahajandi927@gmail.com
e8ae67da9e630730ae1df9ffca7fa2d4296f1d26
24dac117231c9ca39e09e1fd27db8de295a7fe45
/Trident/settings.py
2c943c27e79ee0020f4fe655aed1df9d616f3972
[]
no_license
rohitrajput-42/Trident
784f23b9fa02d405d55715ded627c274a1c887f2
0d75ef954c5d6f88d3b4937e90ab9aace120bdb9
refs/heads/main
2023-06-13T06:10:19.172276
2021-07-10T16:25:22
2021-07-10T16:25:22
384,705,434
0
0
null
null
null
null
UTF-8
Python
false
false
3,092
py
import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '9ew388dr7b@prao9gium)@&@r0ma0dze5%-1fg!1jiwe)@hcpg' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home', 'product', 'accounts', 'crispy_forms', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Trident.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'Trident.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'assets') MEDIA_URL = "image/download/" MEDIA_ROOT = BASE_DIR LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'home' CRISPY_TEMPLATE_PACK = 'bootstrap4'
[ "rohit1471997@gmail.com" ]
rohit1471997@gmail.com
cab9449ed8faee9af97c99a92ed9f878789fa9d4
ad652d8eb0b4f94a4a106098193ec0dbfef9025e
/app/blackjack/cards/__init__.py
78ab51c271c768ba7975932da1c9bf1e8d066647
[ "MIT" ]
permissive
ecsnavarretemit/it-238-blackjack
8afd1719f8fc1947c0f26431eee17cc88238ccc0
b83fcdca1b6c653a95e95597f15ab1e7fcbea3ad
refs/heads/master
2021-04-30T22:54:11.442167
2016-10-13T13:36:36
2016-10-13T13:36:36
67,337,531
0
0
null
null
null
null
UTF-8
Python
false
false
121
py
# __init__.py # # Copyright(c) Exequiel Ceasar Navarrete <esnavarrete1@up.edu.ph> # Licensed under MIT # Version 2.0.0
[ "esnavarrete1@up.edu.ph" ]
esnavarrete1@up.edu.ph
e8c9c8c1592000cd770a1637b2d29b4689424637
56d1504524ef8d396fbb07b82bd23b3bdef48a01
/clase1_intro_python/clases.py
7cb2d4763a5f433fe848cd0c2bfa8a5878c53415
[]
no_license
itactuk/ITT521
134eb008d5b8819fb041bc6a2c3981ebf92d9b31
9fac795f735d422555de5e750fbe31751f4eab15
refs/heads/master
2020-12-08T07:40:03.515236
2020-03-25T23:59:57
2020-03-25T23:59:57
232,928,303
0
0
null
2020-02-13T01:32:01
2020-01-09T23:47:18
Python
UTF-8
Python
false
false
446
py
class Persona: pass class Estudiante(Persona): def __init__(self, nombre, apellido): # constructor self.nombre = nombre self.apellido = apellido def obten_nombre_completo(self): return self.nombre + " " + self.apellido listado_est = [Estudiante("Jesus", "Rosario"), Estudiante("Oscar", "Siri")] for est in listado_est: print(est.apellido) print(est.nombre) print(est.obten_nombre_completo())
[ "ivantm24@gmail.com" ]
ivantm24@gmail.com
8daf812112e2be6da2dd6092b66af41511905194
cde3b4f9da0bc8cd4771b78cfae790ffebbd0726
/variable_position_plotter.py
11fc3fe2b475036b203ed03e119e3e9bcd7a33c7
[ "MIT" ]
permissive
pabloslash/H1rnN1
2d697b7a36f818ae9e28d7bfab9fac7790251770
fa95d0d0f5cb069870b961851a64c935cba26c07
refs/heads/master
2020-04-21T04:00:20.613433
2018-11-09T20:53:26
2018-11-09T20:53:26
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,798
py
import matplotlib.pyplot as plt from fasta_sampler_v2 import * import numpy as np from mpl_toolkits.axes_grid1 import make_axes_locatable plt.style.use('fivethirtyeight') width = 0.5 # the width of the bars thresh = 0.1 fs = FastaSamplerV2('data/HA_n_2010_2018.fa', 'data/HA_s_2010_2018.fa') fs.set_validation_years([2016, 2017]) years = list(fs.north.keys()) years.sort() # Transition labels ylabs = [] for i in range(1, len(years)): ylabs.append('{} to {}'.format(years[i-1], years[i])) n_frames = [] for y in years: temp = fs.get_flu_sequences_for_year(y) print(temp.shape) temp = fs.get_count_matrix_from_sequences(temp.values) temp /= temp.sum(axis=1).values[0] # Normalize n_frames.append(temp) s_frames = [] for y in years: temp = fs.get_flu_sequences_for_year(y, False) print(temp.shape) temp = fs.get_count_matrix_from_sequences(temp.values) temp /= temp.sum(axis=1).values[0] # Normalize s_frames.append(temp) n_changes = [] s_changes = [] for i in range(1, len(n_frames)): fig, ax = plt.subplots(figsize=(12, 10)) n_new = (np.abs(n_frames[i] - n_frames[i - 1])).sum(axis=1).values s_new = (np.abs(s_frames[i] - s_frames[i - 1])).sum(axis=1).values n_changes.append(n_new) s_changes.append(s_new) ind = np.arange(len(n_new)) indices = n_new > thresh sub_ind = ind[indices] sub_n = n_new[indices] rects1 = ax.bar(np.arange(len(sub_n)) - width/2, sub_n, width, label='Northern\nHemisphere') rects2 = ax.bar(np.arange(len(sub_n)) + width/2, s_new[indices], width, label='Southern\nHemisphere') ax.set_ylabel('Normalized change') ax.set_xlabel('Amino Acid Position') ax.set_title('Amino Change Frequency by Position\n' \ 'Year {} to {}'.format(years[i-1], years[i])) ax.set_xticks(np.arange(len(sub_n))) ax.set_xticklabels(sub_ind, rotation=45) ax.legend() plt.show() for changes in [n_changes, s_changes]: changes = np.array(changes) d = pd.DataFrame(changes) d = d.T sub = d.loc[(d > thresh).any(axis=1)] fig, ax = plt.subplots(figsize=(16, 8), dpi= 80, facecolor='w', edgecolor='k') im = ax.imshow(sub.T.values, interpolation='nearest') ax.set_xticks(list(range(sub.shape[0]))) ax.set_yticks(list(range(sub.shape[1]))) ax.set_yticklabels(ylabs, fontsize=10) ax.set_xticklabels(list(sub.index.values), fontsize=10, rotation=45) ax.grid(linewidth=0.2) ax.set_xlabel('Amino Acid Position') ax.set_ylabel('Year to year change') ax.set_title('Frequency of Amino Acid Change\nfrom Year to Year by Position') divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(im, cax=cax) plt.show()
[ "michaelewiest@gmail.com" ]
michaelewiest@gmail.com
c1b5b68b839b14ebd5fd4d98a8bd3722aace376d
2572ee0bc833948ceeca74cc7abe80431172b0a8
/mitmdump_Test/test.py
78d51f4e8d09d32ba10eaacaadd1d16c0e110548
[]
no_license
Alacazar99/Spider_Train
723890b07ae29867a1fedb67b144f1014d496b09
e8cd573e8c6541c0a7c96944efeeee4454cdf1bb
refs/heads/master
2020-12-24T01:52:18.872411
2020-02-21T02:19:47
2020-02-21T02:19:47
237,341,938
2
0
null
null
null
null
UTF-8
Python
false
false
488
py
from mitmproxy import ctx # 写法唯一(请求) def request(flow): # print(flow.request.headers) # ctx.log.info(str(flow.request.headers)) # ctx.log.warn(str(flow.request.headers)) ctx.log.error(str(flow.request.url)) # ctx.log.error(str(flow.request.host)) ctx.log.error(str(flow.request.method)) ctx.log.error(str(flow.request.path)) # 响应 def response(flow): ctx.log.error(str(flow.response.status_code)) ctx.log.error(str(flow.response.text))
[ "11788248080@qq.com" ]
11788248080@qq.com
232440fd03b37880a2d7298b501b1131d2089d5a
9b5e6a76efb087d8609d691864a5bcea45557d98
/django-react/backend/scholar_apis/scholar_apis/settings.py
76f106617fd642db3d9ce637a07d05ef21627106
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
arman-mahtabfar/Database-Systems-Final-Project
bd699dc109c64c8dbe7597e14007e980e1033739
9e209385749e7dadc3cc7d89f597a49bc2323a54
refs/heads/master
2023-08-15T03:30:22.682212
2021-05-17T18:53:02
2021-05-17T18:53:02
282,971,203
0
0
null
2021-09-22T19:41:50
2020-07-27T17:40:28
JavaScript
UTF-8
Python
false
false
3,429
py
""" Django settings for scholar_apis project. Generated by 'django-admin startproject' using Django 3.0.4. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '&4(3w0gvh&=*(#5gq*+sb=^!yex^@$4w$p=(i3sg(xgu8)z7_%' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'apis', ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ] } MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'scholar_apis.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'scholar_apis.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'custom-google-scholar.db'), } } # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_URL = '/static/' CORS_ORIGIN_WHITELIST = ['http://localhost:3000']
[ "ndholaria@ymail.com" ]
ndholaria@ymail.com
e0b7d6575a5dbdbe61538bb40f2b8eef2706675c
11b1324a40f2652b2153e93e038644ec7e9179a1
/blocks/PageLabel.py
510fa377d2b7b7a88267eb7c0d51ed4f54e77f1c
[ "MIT" ]
permissive
shyamal388/PythonBlocks
73487e2b326aaeed51cdd02f4fd08e4e4164063b
4d42121e4af850ba1bf9a4140c11fe10ba218cdd
refs/heads/master
2021-06-03T11:12:32.557846
2016-09-09T01:39:26
2016-09-09T01:39:26
null
0
0
null
null
null
null
UTF-8
Python
false
false
857
py
#------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: A21059 # # Created: 10/03/2015 # Copyright: (c) A21059 2015 # Licence: <your licence> #------------------------------------------------------------------------------- from blocks.BlockLabel import BlockLabel from PyQt4 import QtGui class PageLabel(BlockLabel): def __init__(self,initLabelText, labelType, isEditable, blockID): BlockLabel.__init__(self,initLabelText, '', '', labelType, isEditable, blockID, False, QtGui.QColor(255,255,0)); def update(self): x = 5; y = 5; rb = RenderableBlock.getRenderableBlock(blockID); if (rb != None): x += descale(rb.getControlLabelsWidth()); self.setPixelLocation( rescale(x), rescale(y)); if __name__ == '__main__': main()
[ "shijq73@gmail.com" ]
shijq73@gmail.com
33533937019486440ae14a967746c3353ca9444f
1735ea59cc57f9a957c7c1fd9a6d5e5b88a858b2
/demo/trial.py
9eb837d57c2329adacd94b8743977cfeb7abcf12
[ "MIT" ]
permissive
haydensoliver/CI_testing
ce67fa70765f6047b62b42cfbab1108469416e58
4a3b99d907f6a00c9f504c6634d36624205a0dc8
refs/heads/master
2021-08-14T22:44:33.880652
2017-11-16T22:53:36
2017-11-16T22:53:36
null
0
0
null
null
null
null
UTF-8
Python
false
false
189
py
def square(x): """Finds the square of the input. Args: x (float): The number to be squared. Returns: x2 (float): The squared number. """ return x**2
[ "haydenoliver@gmail.com" ]
haydenoliver@gmail.com
711b995a8369c87c09b980abf3c79b0a044d7f61
224341b3c27675c7c0b330b52bac68d49322ed59
/search/tests.py
0cbc93929e42e5e449b564dabbba458172a7372e
[]
no_license
daniel0001/Stream_3_Project_Ecomm_Django
a60b8eae5a36d863fe196d0fddc92b9906a9758b
588c8dd7754f068a9ecf63db5195a0f720111cbd
refs/heads/master
2022-12-12T21:30:07.026462
2017-08-25T21:40:43
2017-08-25T21:40:43
95,681,489
4
6
null
2022-12-07T23:59:51
2017-06-28T15:00:15
Python
UTF-8
Python
false
false
318
py
from django.test import TestCase from .views import do_search from django.core.urlresolvers import resolve from django.shortcuts import render_to_response class SearchTest(TestCase): def test_search_resolves(self): search_page = resolve('/search/') self.assertEqual(search_page.func, do_search)
[ "daniel.j.halliday@gmail.com" ]
daniel.j.halliday@gmail.com
4c8971b0827e6cb43b0f8b51b54e802d32cbf1ca
e832bcb28ca605bd6fefdbff7572958eb708c2ad
/src/basic-c2/fizzbuzz.py
146c06f37b4b7e80571f5ac056bd4ed6e97e0103
[]
no_license
n18002/programming-term2
35059b15f56d13575b299f64ea4de3f63a46c232
b7cb1c73956c96f23710e2b88149e2d8ca00481b
refs/heads/master
2020-03-22T08:59:28.907436
2018-08-14T00:43:51
2018-08-14T00:43:51
139,806,118
0
0
null
2018-07-05T06:42:08
2018-07-05T06:42:07
null
UTF-8
Python
false
false
226
py
# FizzBuzz for i in range(1, 21): if i % 15 == 0: print("FizzBuzz") continue if i % 3 == 0: print("Fizz") continue if i % 5 == 0: print("Buzz") continue print(i)
[ "n18002@std.it-college.ac.jp" ]
n18002@std.it-college.ac.jp
1f720ff637cb1caa2f963b6153bab22843de5da5
3d78431e010a6b6751b001a59072574b8c5b31f7
/project3/Proj04-01/Proj04-01.py
bff8b0fa410f0fe8f0a2e2b09554b0b99ab185d7
[ "Apache-2.0" ]
permissive
zhouzhaoze/dip
9f488d241a42f4b9367c6ebe4e08c0dc3a42122a
b76fe1602bf8dd0463f9bebc416c8a07b4be351b
refs/heads/master
2020-07-04T15:58:46.805718
2014-01-11T16:22:20
2014-01-11T16:22:20
null
0
0
null
null
null
null
UTF-8
Python
false
false
80
py
Fig0441(a)(characters_test_pattern).tif Fig0441(a)(characters_test_pattern).tif
[ "zhouzhaoze@gmail.com" ]
zhouzhaoze@gmail.com
ab8e757773af8ba61a9c52e6cac7917efc261dae
294969e5d123e0487ed80de2a34428fd7d89dfd5
/leetcode/83.RemoveDuplicates.py
1a1d52a628895d1ea5e91e29a5d49d1fb2622742
[]
no_license
chenfu2017/Algorithm
0a750c4b2f380cbcb838d2da2352ec4e95067341
ccb3106ae489268aa8f868a43ecdf802a02adc22
refs/heads/master
2022-04-27T09:28:05.296285
2022-03-28T07:18:32
2022-03-28T07:18:32
141,994,018
0
0
null
null
null
null
UTF-8
Python
false
false
635
py
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def deleteDuplicates(self, head): """ :type head: ListNode :rtype: ListNode """ cur = head while cur and cur.next: if cur.val == cur.next.val: cur.next = cur.next.next else: cur = cur.next return head n1=ListNode(1) n2=ListNode(2) n3=ListNode(3) n1.next=n2 n2.next=n3 head = Solution().deleteDuplicates(n1) while head!=None: print(head.val,end='->') head=head.next
[ "21114056@qq.com" ]
21114056@qq.com
97d8cba869429754597a0b5a709fd04ee8ff53d9
9b1689f89932ea3745bf2d60d7c8671a5605cd14
/core/forms.py
18be891785baa310bf65c9f88a2fb0089d13f5ba
[]
no_license
milkbread/KeinAbenteuer
15cdfea0f1d12068ce2a6d1493143f0f378e9def
5b5cb74274b1914e5ccd45625f8bb9935eddac4e
refs/heads/master
2021-01-23T03:05:21.872367
2017-04-19T18:25:28
2017-04-19T18:25:28
86,049,174
0
0
null
null
null
null
UTF-8
Python
false
false
1,219
py
from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.core.validators import EmailValidator from django.http import JsonResponse from .models import Article, Image class UserCreateForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ("username", "email", "password1", "password2") def save(self, commit=True): form = super(UserCreateForm, self) response = {'errors': '', 'response': ''} if self.is_valid(): user = form.save(commit=False) user.email = self.cleaned_data["email"] if commit: user.save() response['response'] = {'status': 'success'} return JsonResponse(response) else: response['errors'] = form.errors return JsonResponse(response) class ArticleForm(forms.ModelForm): class Meta: model = Article fields = ('title', 'text', 'published_date') class ImageForm(forms.ModelForm): image = forms.ImageField(label='Image') class Meta: model = Image fields = ('image', )
[ "milkbread@freenet.de" ]
milkbread@freenet.de
9d85fc17cd0873dc77dd627536c1d99207955bd1
9997d05c9214261d3f105b4e0d21ad3d14d0d18a
/lab04.py
e61028d6676abd849e4715d93bee6bc64d6f7cca
[]
no_license
razsofanni/Programming1
8c7674d6acc9debc4558c40947d58395580b72d3
0186f7530c11bffa345483fd7c737ee29f5e5323
refs/heads/master
2020-04-23T22:11:12.464569
2019-02-10T17:09:00
2019-02-10T17:09:00
null
0
0
null
null
null
null
UTF-8
Python
false
false
972
py
import numpy as np import time as t def inverseVector(a): b = np.array(a[a.size-1]) for i in range(a.size-2,-1,-1): b = np.append(b,a[i]) return b def sortVector(v): n = v.size for i in range(0,n): for j in range(i+1,n): if v[i] > v[j]: v[i],v[j] = v[j],v[i] return v #EX1: a = np.arange(10,50) b = inverseVector(a) print(a) print(b) #EX2: b = np.array(np.ceil(100*np.random.random((30))),dtype='uint8') minB = b.min() maxB = np.max(b) print(b) print(minB, maxB) ind = np.where((b==minB) | (b==maxB)) print(ind) #EX3: d = np.random.randint(1,100,15) d[d==d.max()]=-1 print(d) #EX4: c = np.arange(-3,15) c[(c<8) & (c>3)] = -1 print(c) #RX5: d = np.random.randint(1,50,15) n = int(input('Give a number:')) e = np.abs(d-n) print(d) print(d[e==e.min()]) #EX6: e = np.random.randint(1,50,15) print(e) start = t.time() e1 = sortVector(e) ended = t.time() print(e1) print('{:.15f}'.format(ended-start))
[ "harangi.balazs@gmail.com" ]
harangi.balazs@gmail.com
da0cf16a619a641ec2a5b388af90896b9d3fb729
f2bd826ee5f52c5f22d5956285ae40a1ca31d4b1
/ticketflix/session/migrations/0001_initial.py
2f12b60277435abc96ee06c84b795e72431ff033
[ "MIT" ]
permissive
DSW-2018-2/Ticketflix
0a4e99553a20de6ba15fd029e0968ad4b88a032f
d417895904c1a12ba2a9d761d7e60be77b7bcac2
refs/heads/develop
2021-07-23T05:46:07.615523
2018-11-23T13:11:37
2018-11-23T13:11:37
145,330,742
3
2
MIT
2018-11-23T08:11:54
2018-08-19T19:14:41
Python
UTF-8
Python
false
false
711
py
# Generated by Django 2.0.8 on 2018-11-09 16:01 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Session', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('date', models.DateField()), ('time', models.TimeField()), ('place', models.CharField(max_length=50)), ('available_ticket_number', models.IntegerField()), ('total_ticket_number', models.IntegerField()), ], ), ]
[ "anlugueso@gmail.com" ]
anlugueso@gmail.com
7fe85ac767a6d7d65b177843840575145099759e
b97db3190d8f61b70868744bfc9413e2701b09cc
/old files/app_old.py
89f483cfc4bcb585657fb0dbf6c63eb4543fc88d
[]
no_license
BensonHermes/CoCo-Alert
258f2ff967a30140418490b25a33971e3ee64467
a72fc93c293c3a422b024c2bfcffe3b9e8b38071
refs/heads/main
2023-04-23T13:51:11.591125
2021-05-09T13:49:02
2021-05-09T13:49:02
321,382,136
0
0
null
null
null
null
UTF-8
Python
false
false
15,444
py
from io import StringIO import requests from pyquery import PyQuery as pq import matplotlib.pyplot as plt import numpy as np import pandas as pd import pyimgur from selenium import webdriver import mysql.connector from mysql.connector import Error from flask import Flask, request, abort from linebot import ( LineBotApi, WebhookHandler ) from linebot.exceptions import ( InvalidSignatureError ) from linebot.models import * #======這裡是呼叫的檔案內容===== #from selenium import webdriver from message import * from new import * from Function import * from rate1 import * from twStock import * from bbi_selenium import * from selenium import webdriver from pyquery import PyQuery as pq # chrome_options = webdriver.ChromeOptions() # chrome_options.binary_location = os.environ.get("GOOGLE_CHROME_BIN") # chrome_options.add_argument("--headless") # chrome_options.add_argument("--disable-dev-shm-usage") # chrome_options.add_argument("--no-sandbox") # driver = webdriver.Chrome(executable_path=os.environ.get("CHROMEDRIVER_PATH"), chrome_options=chrome_options) #======這裡是呼叫的檔案內容===== app = Flask(__name__) # Channel Access Token line_bot_api = LineBotApi('F7fZ4NRk3qz1K4XPu6EKW6pejsgcWA6esSdwme1oVWyy2DzCB1gtZRXNwNC6+NLa+62r8OUl9w7EbHnUDP3EWocuWwCcpK5HpMmQkXQ8+4LIoIGT037RCmzohu84RsigD4o20eXGNJFiA9HkMWjOvQdB04t89/1O/w1cDnyilFU=') # Channel Secret handler = WebhookHandler('fca3781ffe4aa6bf0cfa89f33a635182') # 監聽所有來自 /callback 的 Post Request @app.route("/callback", methods=['POST']) def callback(): # get X-Line-Signature header value signature = request.headers['X-Line-Signature'] # get request body as text body = request.get_data(as_text=True) app.logger.info("Request body: " + body) # handle webhook body try: handler.handle(body, signature) except InvalidSignatureError: abort(400) return 'OK' def trial(): return 'trial' def stock_graph(): import pyimgur #plt.savefig('send.png') CLIENT_ID = 'a0206b635136159' PATH = "2317.png" im = pyimgur.Imgur(CLIENT_ID) uploaded_image = im.upload_image(PATH, title="Uploaded with PyImgur") uploaded_image=uploaded_image.link return uploaded_image # img_url = glucose_graph() # print(img_url) def doSQL(int order, str sqlStatement, list data): try: # 連接 MySQL/MariaDB 資料庫 connection = mysql.connector.connect( host='140.119.19.73', # 主機名稱 port='9306', database='TG06', # 資料庫名稱 user='TG06', # 帳號 password='i8p3q6') # 密碼 # 查詢資料庫 cursor = connection.cursor() if(order==0): cursor.execute(sqlStatement) # 列出查詢的資料' records = cursor.fetchall() return records # for (Course_id, Course_name) in cursor: # print("Course_id: %s, Course_name: %s" % (Course_id, Course_name)) else: cursor.execute(sqlStatement,data) connection.commit() except Error as e: print("資料庫連接失敗:", e) finally: if (connection.is_connected()): cursor.close() connection.close() print("資料庫連線已關閉") # 處理訊息 @handler.add(MessageEvent, message=TextMessage) def handle_message(event): msg = event.message.text if 'newswebsite' in msg: message = imagemap_message() line_bot_api.reply_message(event.reply_token, message) elif '啟動' in msg: a='按1 登入\n 輸入2 註冊帳號\n' line_bot_api.reply_message(event.reply_token, TextSendMessage(text=a)) elif '1' == msg: a='請輸入『登入帳號/密碼』 例如『登入aronov/20201234』\n' line_bot_api.reply_message(event.reply_token, TextSendMessage(text=a)) elif '登入' in msg: message = TextSendMessage(text=msg) line_bot_api.reply_message(event.reply_token, message) elif '2' ==msg: a='註冊帳號 請輸入『新用戶/帳號/密碼/住家地址/工作地址/常拜訪地址』例如『新用戶/aronov/20201234/台北市文山區指南路二段64號/臺北市信義區信義路五段7號/NULL』(不包含上下引號)\n' line_bot_api.reply_message(event.reply_token, TextSendMessage(text=a)) elif '註冊帳號' in msg: a='帳號註冊成功\n' line_bot_api.reply_message(event.reply_token, TextSendMessage(text=a)) elif 'tvshows' in msg: message = imagemap_message_program() line_bot_api.reply_message(event.reply_token, message) elif '最新活動訊息' in msg: message = buttons_message() line_bot_api.reply_message(event.reply_token, message) elif '註冊會員' in msg: message = Confirm_Template() line_bot_api.reply_message(event.reply_token, message) elif '旋轉木馬' in msg: message = Carousel_Template() line_bot_api.reply_message(event.reply_token, message) elif '圖片畫廊' in msg: message = test() line_bot_api.reply_message(event.reply_token, message) elif '功能列表' in msg: message = function_list() line_bot_api.reply_message(event.reply_token, message) # elif 'rate' in msg: # a=rate() # line_bot_api.reply_message(event.reply_token, TextSendMessage(text=a)) elif '功能' in msg: a='1:輸入 『rate』 得知美國公債報價、銀行拆借利率、FED利率、Tips\n2:輸入 『worldequity』\n得知全球股票市場和指數期貨市場報價\n3:輸入 『twstock+股票代碼』\n得知該台股2019年走勢\n4:輸入 『news』\n得知台股與國際股市新聞\n5:輸入 『sectors』\n獲取美股各產業漲跌幅\n6:輸入 『commodity』 取得原物料最新報價\n7:輸入 『BIresearch』 獲取Bloomberg Intelligence研究報告\n8:輸入 『equityprimer』 獲取Bloomberg Intelligence個股研究報告\n9:輸入 『newswebsite』\n進入財經新聞網站\n10:輸入 『tvshows』\n觀看彭博社精選節目' line_bot_api.reply_message(event.reply_token, TextSendMessage(text=a)) elif 'trial' in msg: a=trial() line_bot_api.reply_message(event.reply_token, TextSendMessage(text=a)) elif 'pic' in msg: message = ImageSendMessage(original_content_url='https://img.shop.com/Image/260000/268600/268630/products/1577221645__400x400__.jpg',preview_image_url='https://img.shop.com/Image/260000/268600/268630/products/1577221645__400x400__.jpg') line_bot_api.reply_message(event.reply_token, message) elif 'twstock' in msg: userIn = msg userIn=userIn[7:] a=twStock(userIn) # a=str(a) # url='https://i.'+a[9:]+'.png' # a=url message = ImageSendMessage(original_content_url=a,preview_image_url=a) line_bot_api.reply_message(event.reply_token, message) elif 'rate' in msg: a=rate1() line_bot_api.reply_message(event.reply_token, TextSendMessage(text=a)) elif '2330' in msg: # img_url=make_stock_graph(message) # #url='https://i.ibb.co/G9922WL/2317.png' # url='https://i.'+img_url[9:]+'.png' a='https://i.imgur.com/hGPVUaM.png' message = ImageSendMessage(original_content_url=a,preview_image_url=a) line_bot_api.reply_message(event.reply_token, message) elif 'news' in msg: res=requests.get("https://news.cnyes.com/news/cat/tw_stock") html=pq(res.text) newsTaiwan=[] for i in html('._1xc2').items(): newsTaiwan.append(i.text()) #print(newsTaiwan) newsDomestic="" newsTw=[] n=0 for i in newsTaiwan: newsDomestic+=i n+=1 if n==2: n=0 newsTw.append(newsDomestic) newsDomestic="" res=requests.get("https://news.cnyes.com/news/cat/wd_stock") html=pq(res.text) newsGlobal=[] for i in html('._1xc2').items(): newsGlobal.append(i.text()) #print(newsTaiwan) newsGlobal1="" newsInt=[] n=0 for i in newsGlobal: newsGlobal1+=i n+=1 if n==2: n=0 newsInt.append(newsGlobal1) newsGlobal1="" str1='' str1+='台灣新聞: \n' for i in newsTw: str1=str1+i+'\n' str1 = str1+'\n' str1 = str1+'-------------------------------\n' str1+='國際新聞: \n' for i in newsInt: str1=str1+i+'\n' str1 = str1+'\n' str1 = str1+'-------------------------------\n' line_bot_api.reply_message(event.reply_token, TextSendMessage(text=str1)) elif 'sectors' in msg: res=requests.get("https://www.reuters.com/finance/global-market-data") html=pq(res.text) sectorDict={} sectorList=[] for i in html('div.industryNav').items(): sectorDict={} commodityDict={} name=i('h3>a').text() print(name) sectorDict['Sector']=name changePercent=i('div.sectorChange').text() print(changePercent) sectorDict['Change %']=changePercent sectorList.append(sectorDict) for i in html('div.industryNav').items(): sectorDict={} name=i('h3>a').text() sectorDict['Sector']=name changePercent=i('div.sectorChange').text() sectorDict['Change %']=changePercent sectorList.append(sectorDict) str1 = '' for i in sectorList: for key,value in i.items(): str1 = str1+key+':' str1 = str1+value+'\n' str1 = str1+'\n' message = TextSendMessage(text=str1) line_bot_api.reply_message(event.reply_token, message) elif 'commodity' in msg: res=requests.get("https://finance.yahoo.com/commodities") html=pq(res.text) commodityDict={} commodityList=[] for i in html('tbody[data-reactid="45"]>tr').items(): commodityDict={} name=i('td.data-col1').text() commodityDict['Name']=name last=i('td.data-col2').text() commodityDict['Value']=last change=i('td.data-col4').text() commodityDict['Change']=change changePercent=i('td.data-col5').text() commodityDict['Change %']=changePercent oi=i('td.data-col7').text() commodityDict['Open Interest']=oi commodityList.append(commodityDict) str1 = '' n=0 for i in commodityList: for key,value in i.items(): n+=1 str1 = str1+key+':' str1 = str1+value+'\n' str1 = str1+'\n' if n==100: break message = TextSendMessage(text=str1) line_bot_api.reply_message(event.reply_token, message) elif 'worldequity' in msg: res=requests.get("https://www.reuters.com/markets/stocks") html=pq(res.text) equityDict={} equityList=[] for i in html("tr.data").items(): equityDict={} index=i('a.MarketsTable-name-1U4vs').text() equityDict["Index"]=index last=i('span.MarketsTable-value-FP5ul').text() price="".join(last.split(',')) equityDict["Last"]=price change=i('td.MarketsTable-net_change-1ZX13>span.TextLabel__regular___2X0ym').text() equityDict["Change"]=str(change) changePercent=i('td.MarketsTable-percent_change-2HcuU>span.TextLabel__regular___2X0ym').text() changePercent=changePercent.replace('+','') changePercent=changePercent.replace('%','') equityDict["%Change"]=str(changePercent) equityList.append(equityDict) str1 = '' for i in equityList: for key,value in i.items(): str1 = str1+key+':' str1 = str1+value+'\n' str1 = str1+'\n' message = TextSendMessage(text=str1) line_bot_api.reply_message(event.reply_token, message) elif 'BIresearch' in msg: drive_url='https://drive.google.com/drive/folders/1Sp-_x8YDjtH_JejsSklnoOdnj26HrDQF?usp=sharing' message = TextSendMessage(text=drive_url) line_bot_api.reply_message(event.reply_token, message) elif 'equityprimer' in msg: drive_url='https://drive.google.com/drive/folders/1stFsB_pOx6fvc9yFyute3bAKilfHB6IX?usp=sharing' message = TextSendMessage(text=drive_url) line_bot_api.reply_message(event.reply_token, message) elif 'bbi' in msg: driver.get('https://www.bloomberg.com/markets/rates-bonds/bloomberg-barclays-indices') # driver.current_url html=driver.find_element_by_css_selector("*").get_attribute("outerHTML") doc=pq(html) n=0 bbiIndices=[] for i in doc("tr.data-table-row").items(): n+=1 bbiIndicesDict={} if n<=10: abb=i('div.data-table-row-cell__link-block[data-type="abbreviation"]').text() bbiIndicesDict["Ticker"]=abb name=i('div.data-table-row-cell__link-block[data-type="full"]').text() bbiIndicesDict["Name"]=name value=i('td:nth-child(2)').text() #price.replace(',','') # value="".join(value.split(',')) # value=float(value) bbiIndicesDict["Value"]=value change=i('td:nth-child(3)').text() bbiIndicesDict["Change"]=change mtd=i('td:nth-child(4)').text() bbiIndicesDict["MTD Return"]=mtd ytd=i('td:nth-child(5)').text() bbiIndicesDict["52-Week Return"]=ytd bbiIndices.append(bbiIndicesDict) else: break str1 = '' for i in bbiIndices: for key,value in i.items(): str1 = str1+key+':' str1 = str1+value+'\n' str1 = str1+'\n' message = TextSendMessage(text=str1) line_bot_api.reply_message(event.reply_token, message) else: message = TextSendMessage(text=msg) line_bot_api.reply_message(event.reply_token, message) import os if __name__ == "__main__": port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port)
[ "chowduen@gmail.com" ]
chowduen@gmail.com
5b6cadc2c2a55ba0c6c1312bc01be4305c233b71
2b6edda9ba2ddef59f84e74f4a7abfad585f170c
/Arrange_the_Buses.py
0f0598dabdacda35093d51987922a11ecc082dd5
[]
no_license
pulavartivinay/Online-Hackathon-Questions
8622e3975b0faf12493784bcec033597265f90ce
7b020673134033554e62a3dff9fc3bac5b18d5cd
refs/heads/master
2022-08-01T11:56:57.809677
2020-05-26T18:06:24
2020-05-26T18:06:24
null
0
0
null
null
null
null
UTF-8
Python
false
false
530
py
import copy N, C, K = input().split() N = int(N) C = int(C) K = int(K) arrival_times = [] for kl in range(0,N): betkcksdck = input() betkcksdck = int(betkcksdck) arrival_times.append(betkcksdck) arrival_times.sort() print(arrival_times) buses = 1 ti = arrival_times[0] i = 0 capacity = 0 while(i < N): if ti <= arrival_times[i] <= ti+K and capacity < C: capacity = capacity + 1 i = i + 1 else: ti = arrival_times[i] buses = buses + 1 capacity = 0 print(buses)
[ "noreply@github.com" ]
noreply@github.com
8fe3027fbbf33de53ec0d87b322cf791331c758e
b9bc40b7abe6fe3bf6f870ffd6ee4766325ff875
/Time Series/scripts/TS_Autoregression.py
fefb6a6da47348f7eb5197f553b0c0adc3901e6e
[]
no_license
nbinuani/SAFRAN_TS_study
4b045c5555cc66188716e6fff2b12934d7a8b4fb
cc15db0b2cc66a62247f638d5f55af91e5d16d62
refs/heads/main
2023-02-25T16:28:50.196583
2021-02-01T00:33:05
2021-02-01T00:33:05
null
0
0
null
null
null
null
UTF-8
Python
false
false
11,056
py
import warnings import pandas as pd import numpy as np import matplotlib.pyplot as plt from statsmodels.tsa.seasonal import seasonal_decompose from statsmodels.tsa.stattools import adfuller from statsmodels.graphics.tsaplots import plot_pacf, plot_acf from statsmodels.graphics.gofplots import qqplot from statsmodels.tsa.ar_model import AR from statsmodels.tsa.ar_model import ARResults import plotly.offline as py import plotly.graph_objs as go from sklearn.metrics import mean_squared_error from scipy.stats import linregress def ts_plot(y, lags=None, title=''): ''' Calculate acf, pacf, histogram, and qq plot for a given time series ''' # if time series is not a Series object, make it so if not isinstance(y, pd.Series): y = pd.Series(y) # initialize figure and axes fig = plt.figure(figsize=(10, 8)) layout = (3, 2) ts_ax = plt.subplot2grid(layout, (0, 0), colspan=2) acf_ax = plt.subplot2grid(layout, (1, 0)) pacf_ax = plt.subplot2grid(layout, (1, 1)) qq_ax = plt.subplot2grid(layout, (2, 0)) hist_ax = plt.subplot2grid(layout, (2, 1)) # time series plot y.plot(ax=ts_ax) plt.legend(loc='best') ts_ax.set_title(title) # acf and pacf plot_acf(y, lags=lags, ax=acf_ax, alpha=0.05) plot_pacf(y, lags=lags, ax=pacf_ax, alpha=0.05) # smt.graphics.plot_acf(y, lags=lags, ax=acf_ax, alpha=0.05) # smt.graphics.plot_pacf(y, lags=lags, ax=pacf_ax, alpha=0.05) # qq plot qqplot(y, line='s', ax=qq_ax) qq_ax.set_title('Normal QQ Plot') # hist plot y.plot(ax=hist_ax, kind='hist', bins=25) hist_ax.set_title('Histogram') plt.tight_layout() plt.show() return def _my_AR(ts, SPLIT): # create lagged dataset dataframe = pd.concat([ts.shift(1), ts], axis=1) dataframe.columns = ['t-1', 't+1'] # split into train and test sets X = dataframe.values train_size = int(len(X) *SPLIT) train, test = X[1:train_size], X[train_size:] train_X, train_y = train[:, 0], train[:, 1] test_X, test_y = test[:, 0], test[:, 1] # persistence model on training set train_pred = [x for x in train_X] # calculate residuals train_resid = [train_y[i] - train_pred[i] for i in range(len(train_pred))] # model the training set residuals model = AR(train_resid) model_fit = model.fit() window = model_fit.k_ar coef = model_fit.params # walk forward over time steps in test history = train_resid[len(train_resid) - window:] history = [history[i] for i in range(len(history))] predictions = list() expected_error = list() for t in range(len(test_y)): # persistence yhat = test_X[t] error = test_y[t] - yhat expected_error.append(error) # predict error length = len(history) lag = [history[i] for i in range(length - window, length)] pred_error = coef[0] for d in range(window): pred_error += coef[d + 1] * lag[window - d - 1] predictions.append(-1*pred_error) history.append(error) print('predicted error=%f, expected error=%f' % (pred_error, error)) # plot predicted error # plt.plot(expected_error) # plt.plot(predictions, color='red') # plt.show() AR_train = model_fit.fittedvalues return predictions, AR_train def test_stationarity(timeseries): # Perform Dickey-Fuller Test print("Result of Dickey-Fuller Test:") dftest = adfuller(timeseries, autolag='AIC') dfoutput = pd.Series(dftest[0:4], index=['Test Statistic', 'p-value', '#Lags Used', 'Number of Observations Used']) for key, value in dftest[4].items(): dfoutput['Critical Value (%s)' % key] = value print(dfoutput) p_value = dfoutput['Test Statistic'] alpha = dfoutput['Critical Value (1%)'] stationnary = bool if p_value < alpha : stationnary = True else: stationnary = False return dfoutput, stationnary def stationnary_coef(data, type): print('Test Stationanry '+str(type)) data_trend_sta, data_stationary = test_stationarity(data) differenciation = 0 if data_stationary == False: differenciation = 1 return differenciation def _differenciation(ts, coef_diff): ts_diff = ts - ts.shift(coef_diff) return ts_diff def _mydrift(predictions, lim_sup, lim_inf): #color = ['red', 'orange', 'green'] color = ['rgb(215, 11, 11)', 'rgb(240, 140, 0)', 'rgb(0, 204, 0)'] nb_pts_critic = int(len(predictions)/2) clign = color[2] if predictions[: nb_pts_critic].mean() > lim_sup or predictions[: nb_pts_critic].mean() < lim_inf : clign = color[0] elif predictions[nb_pts_critic:].mean() > lim_sup or predictions[nb_pts_critic:].mean() < lim_inf : clign = color[1] print('Code couleur des avertissements :') print('Rouge = premières valeurs de prédiction au dessus des limites = état critique') print('Orange = dernières valeurs de prédiction au dessus des limites = avertissement') print('Vert = RAS') print(clign) return clign def _error(original, create): error = mean_squared_error(original, create) print('MSE prediction : ' + str(error)) return error def main(): # Load DATA dateparse = lambda dates: pd.datetime.strptime(dates, '%Y-%m-%d') path = r'D:\users\S598658\Projects\Flat_pattern\env\Data_production_variations.csv' data = pd.read_csv(path, sep=',', parse_dates=['TimeIndex'], index_col='TimeIndex', date_parser=dateparse) data = data[70:130] ts = data["Data"] last_element = ts.index[-1] nb_predictions = 20 SPLIT = 1 - (nb_predictions/len(ts)) WD = int(len(data)/30) # window for test stationnary print('WD : %i' % WD) TRAIN_SIZE = int(len(ts) * SPLIT) ts_train, ts_test = ts[0:TRAIN_SIZE + 1], ts[TRAIN_SIZE:len(ts)] # Decompostition decomposition = seasonal_decompose(ts, freq=WD) trend = decomposition.trend seasonal = decomposition.seasonal residual = decomposition.resid residual.fillna(residual.mean(), inplace=True) trend.fillna(trend.mean(), inplace=True) d = stationnary_coef(ts, 'TS') ts = _differenciation(ts, d) ts.fillna(ts.mean(), inplace=True) predictions, ar = _my_AR(ts, SPLIT) # predictions = -1*predictions my_AR_pred = pd.Series(index=ts_test.index, data=predictions) model = AR(ts_train, freq='D', dates=ts_train.index) #model = AR(ts_train) model_fit = model.fit(ic='aic') predictions = model_fit.predict(start=TRAIN_SIZE, end=TRAIN_SIZE + len(ts_test)-1) AR_model = pd.Series(index=ts_train.index, data=model_fit.fittedvalues) AR_pred = pd.Series(index=ts_test.index, data=predictions) AR_final = pd.concat([AR_model, AR_pred], axis=0) mean_my_AR = int(sum(my_AR_pred)) / len(my_AR_pred) std_my_AR = np.std(my_AR_pred) my_AR_born_sup = my_AR_pred + (mean_my_AR - 1.96 * std_my_AR) / np.sqrt(len(ts_test)) my_AR_born_inf = my_AR_pred - (mean_my_AR - 1.96 * std_my_AR) / np.sqrt(len(ts_test)) mean_AR = int(sum(AR_pred)) / len(AR_pred) std_AR = np.std(AR_pred) AR_born_sup = AR_pred + (mean_AR - 1.96 * std_AR) / np.sqrt(len(ts_test)) AR_born_inf = AR_pred - (mean_AR - 1.96 * std_AR) / np.sqrt(len(ts_test)) # Estimation error on predictions print("my AR MSE : ") _error(ts_test, my_AR_pred) print("AR MSE : ") _error(ts_test, AR_pred) limite_sup = 1 limite_inf = -1 LIN_TRAIN = len(ts_test) x = [l for l in range(len(AR_final))] x_pred = x[len(x) - LIN_TRAIN:] AR_final_lin = AR_final[len(AR_final) - LIN_TRAIN:] ## Linear regression slope, intercept, r_value, p_value, std_err = linregress(x=x_pred, y=AR_final_lin.values) trend = [] for w in range(len(x_pred)): trend.append(slope * x_pred[w] + intercept) avertissement_color = _mydrift(AR_pred, limite_sup, limite_inf) ############ # Plotting results trace0 = go.Scatter( x=data.index, y=data.Data, mode='markers', name='TS' ) trace2 = go.Scatter( x=my_AR_pred.index, y=my_AR_pred, mode='lines', name='my_AR Test Set' ) trace3 = go.Scatter( x=my_AR_pred.index, y=my_AR_born_sup, name='Born Sup', line=dict( color='gray', dash='dot') ) trace4 = go.Scatter( x=my_AR_pred.index, y=my_AR_born_inf, name='Born Inf', line=dict( color='gray', dash='dot' ) ) trace5 = go.Scatter( x=my_AR_pred.index, y=my_AR_born_sup, fill='tonexty', mode='none', name='IC 95%' ) trace6 = go.Scatter( x=AR_model.index, y=AR_model, mode='lines', name='AR Train Set' ) trace7 = go.Scatter( x=AR_pred.index, y=AR_pred, mode='lines', name='AR Test Set' ) trace8 = go.Scatter( x=AR_pred.index, y=AR_born_sup, name='Born Sup', line=dict( color='gray', dash='dot') ) trace9 = go.Scatter( x=AR_pred.index, y=AR_born_inf, name='Born Inf', line=dict( color='gray', dash='dot' ) ) trace10 = go.Scatter( x=AR_pred.index, y=AR_born_sup, fill='tonexty', mode='none', name='IC 95%' ) trace11 = go.Scatter( x=AR_pred.index, y=trend, mode='lines', name='Reg lin TREND', marker=dict( size=5, color=avertissement_color), line=dict( width=5, color=avertissement_color ) ) layout = go.Layout({ 'shapes': [ { 'type': 'line', 'x0': '2015-01-01', 'y0': limite_sup, 'x1': last_element, 'y1': limite_sup, 'line': { 'color': 'red', } }, { 'type': 'line', 'x0': '2015-01-01', 'y0': limite_inf, 'x1': last_element, 'y1': limite_inf, 'line': { 'color': 'red' } } ] }) donnees = [trace0, trace2, trace3, trace4, trace5] fig = dict(data=donnees, layout=layout) py.plot(fig, filename='TS_my_AR.html') donnees_1 = [trace0, trace6, trace7, trace8, trace9, trace10] fig = dict(data=donnees_1, layout=layout) py.plot(fig, filename='TS_AR.html') if __name__ == '__main__': main()
[ "noreply@github.com" ]
noreply@github.com
988093f63770c71efcf6e570ccfa0b3f7bda10b4
2ae81662418731b71d4eec7c03033c0969b6a849
/Tarea9_PriorityQueue/colas.py
50b0477847a6ea949b0801ccf80538bd3827ad27
[]
no_license
GabrielED39/edd_1310_2021
f7031af44204547f81a639ee24e0842899e0f7a0
f9ba716045df114796839315706888c104a618cb
refs/heads/master
2023-02-21T18:21:07.023437
2021-01-26T19:01:44
2021-01-26T19:01:44
299,690,306
0
1
null
null
null
null
UTF-8
Python
false
false
2,301
py
class Queue: def __init__(self): self.__data = list() def is_empty(self): return len(self.__data) == 0 def length(self): return len(self.__data) def enqueue (self,elem): self.__data.append(elem) def dequeue (self): if not self.is_empty(): return self.__data.pop(0) else: return None def to_string(self): cadena = "" for elem in self.__data: cadena = cadena + "| " + str(elem) cadena = cadena +"|" return cadena #TareaPriority Queue class PriorityQueue: def __init__(self): self.__data = list() def is_empty(self): return len(self.__data) == 0 def enqueue (self,elem): self.__data.append(elem) def dequeue (self): try: num = 0 for m in range(len(self.__data)): if self.__data[m] > self.__data[num]: num = m data = self.__data[num] del self.__data[num] return data except IndexError: print() exit() def to_string(self): cadena = "" for elem in self.__data: cadena = cadena + "| " + str(elem) cadena = cadena +"|" return cadena class BoundedPriorityQueue: def __init__(self,niveles): self.__data = [Queue() for x in range(niveles)] self.__size = 0 def is_empty(self): return self.__size == 0 def length(self): return self.__size def enqueue(self, prioridad, elem): if prioridad < len(self.__data) and prioridad >= 0: self.__data[prioridad].enqueue(elem) self.__size += 1 def dequeue(self): if not self.is_empty(): for nivel in self.__data: if not nivel.is_empty(): self.__size -= 1 return nivel.dequeue() def to_string(self): for nivel in range(len(self.__data)): print(f"Nivel {nivel} --> { self.__data[nivel].to_string() }")
[ "noreply@github.com" ]
noreply@github.com
5037eeb948d7012d2b93974d59a6007759548c45
c62101b453cb6cb6a95ee5e9564fb850fff60e29
/python3/ex23.py
05b67f08cc7cc3ad3219ab4f4a0c2dd58155220e
[]
no_license
xcl666/xcllinux
c99efae146029e433a26efa6308f8c27fb87859a
21f271d1c56544f9c1f9f4cab87a3fc19538c869
refs/heads/master
2021-01-01T05:12:36.565404
2019-05-02T17:35:22
2019-05-02T17:35:22
56,660,753
2
0
null
2019-05-02T17:35:23
2016-04-20T06:18:11
Python
UTF-8
Python
false
false
79
py
ages = {"Dave":24,"Mary":42,"John":58} print(ages["Dave"]) print(ages["Mary"])
[ "xuechuangli666@gmail.com" ]
xuechuangli666@gmail.com
2653c1c7714a9e90ef73155806c6a74d85da40ce
4458acc7a3d3ae62c3fc38180b0cb6664aa5ee81
/apiIsoccer/manage.py
946cb9eeaa6a137891a53534d091b46055c91acd
[]
no_license
CarlosW1998/API-Isoccer
a485820ed887b1cce88286263fd3f51e988d006c
2af18ebbb23853cdbd5e6eb52632e0b24682454a
refs/heads/master
2020-03-24T19:00:19.048868
2018-08-24T23:05:27
2018-08-24T23:05:27
142,906,482
0
0
null
null
null
null
UTF-8
Python
false
false
542
py
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "apiIsoccer.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv)
[ "carlos-walte@hotmail.com" ]
carlos-walte@hotmail.com
f5cac25727d84e57b5c34717762405b9f312bb8c
dba5170a4c9afdf863fdd82cd1239fd72573a464
/gameObjects/boulderFragment.py
cd267217be2e33b929d1950971057190b6cfabcb
[ "BSD-3-Clause" ]
permissive
jceipek/Mind-Rush
29846d62c11be1b48f46f7ba031462c27e251487
8a4f81ac7536a66112dceaea3dac7cbcb9bbd3dc
refs/heads/master
2020-03-27T22:31:02.605360
2013-01-12T18:01:19
2013-01-12T18:01:19
1,708,207
1
0
null
null
null
null
UTF-8
Python
false
false
1,422
py
# # boulderFragment.py # # Copyright (C)2011 Julian Ceipek and Patrick Varin # # Redistribution is permitted under the BSD license. See LICENSE for details. # from gameObject import GameObject from engine.functions import pathJoin class BoulderFragment(GameObject): def __init__(self, parent, pos=(0,0), vel=(0,0), id=0, screenBoundaries = None): fragmentPath = pathJoin(('images','fragments','fragment'+str(id)+'.png')) fragmentImage = self.imageCache.getImage(fragmentPath, colorkey='alpha', mask=False) rect = self.imageCache.getRect(fragmentPath) GameObject.__init__(self, fragmentImage, parent, pos, vel) if screenBoundaries == None: raise Exception('Boulders must have screen boundaries') self.boundaries = (screenBoundaries[0]-rect.width, screenBoundaries[1]-rect.height, screenBoundaries[2]+rect.width, screenBoundaries[3]+rect.height) self.acceleration = (0,0.001) def kill(self): GameObject.kill(self) def update(self, *args): GameObject.update(self, *args) #kill when off-screen: if ((self.rect.topleft[0] < self.boundaries[0]) or (self.rect.topleft[0] + self.rect.width > self.boundaries[2]) or (self.rect.topleft[1] + self.rect.height > self.boundaries[3])): self.kill()
[ "julian.ceipek@gmail.com" ]
julian.ceipek@gmail.com
5a62962d922aeedf0aa8bb0afb0a6222f293c6b5
a4999206e2cd8c760f745444e79ff4d4c5e166a9
/myapp/models.py
89c7b1a7a0016fc6884c11461eb7e8f256def7a0
[]
no_license
natisdale/Exhibitions
64d080adb7a06f53e77d265f414550c5820bf1c1
c1d9a2e375da550e985f712ef9a92bff3a3e239d
refs/heads/main
2023-04-26T15:38:59.780165
2021-05-19T23:54:32
2021-05-19T23:54:32
336,041,832
0
0
null
null
null
null
UTF-8
Python
false
false
3,518
py
from datetime import datetime from django.conf import settings from django.db import models from django.contrib.auth.models import User #from django.contrib.auth.models import AbstractUser, BaseUserManager # class CustomUserManager(BaseUserManager): # def create_user(self, email, password=None): # if not email: # raise ValueError('Users must have an email address') # user = self.model( # email=self.normalize_email(email), # ) # user.set_password(password) # user.save(using=self._db) # return user # def create_superuser(self, email, password=None): # user = self.create_user( # username=username, # email=self.normalize_email(email), # password=password, # ) # user.is_admin = True # user.save(using=self._db) # return user # class CustomUser(AbstractUser): # username = None # email = models.EmailField( # verbose_name='email address', # max_length=255, # unique=True, # ) # is_active = models.BooleanField(default=True) # is_admin = models.BooleanField(default=False) # objects = CustomUserManager() # USERNAME_FIELD = 'email' # REQUIRED_FIELDS = [] # def __str__(self): # return self.username # image path functions adapated from # https://docs.djangoproject.com/en/2.0/ref/models/fields/#django.db.models.FileField.upload_to def exhibitionImagePath(instance, filename): return 'student_{0}/{1}'.format(instance.student.id, filename) def artImagePath(instance, filename): return 'student_{0}/{1}'.format(instance.exhibition.student.id, filename) def getRequestUser(request): return request.user.id def getUserExhibition(instance): return Exhibition.objects.filter(user=instance.user).first() class Mentor(models.Model): firstName = models.CharField(max_length=20) lastName = models.CharField(max_length=40) def __str__(self): return self.lastName + ', ' + self.firstName class Category(models.Model): name = models.CharField(max_length=15) def __str__(self): return self.name class Exhibition(models.Model): student = models.ForeignKey( settings.AUTH_USER_MODEL, default=1, on_delete=models.CASCADE, ) title = models.CharField(max_length=150) BFA = 'B' MFA = 'M' TYPE = [ (BFA, 'BFA'), (MFA, 'MFA'), ] degree = models.CharField( max_length=1, choices=TYPE, default=BFA, ) public = models.BooleanField(default=False) flyer = models.ImageField( upload_to=exhibitionImagePath, blank=True, null=True,) startDate = models.DateField( auto_now=False, auto_now_add=False, default=datetime.now, ) endDate = models.DateField( auto_now=False, auto_now_add=False, default=datetime.now ) artistStatement = models.TextField( blank=True, null=True, ) mentors = models.ManyToManyField(Mentor) categories = models.ManyToManyField(Category) def __str__(self): return self.title class ArtWork(models.Model): title = models.CharField(max_length=150) exhibition = models.ForeignKey( Exhibition, on_delete=models.CASCADE, null=True, ) image = models.ImageField(upload_to=artImagePath) def __str__(self): return self.title
[ "natisdale@mail.csuchico.edu" ]
natisdale@mail.csuchico.edu
26448faf3cba7c0c50f9b20ffe7ffba940ed1a4b
0ceb04ce763cf8b73f9b71a211990070abc1f5bb
/src/helpers/plotterHelper.py
3685e691e8b957c5a86229632115e90d10ddc46d
[ "MIT" ]
permissive
fangzhimeng/MachineLearningRegressionBenchmark
e04412581ca21d82f4bbff64ba29ec9795337cac
42a83a1261dbf6b30624e9950db5b2d297622d76
refs/heads/main
2023-03-21T04:57:51.633945
2021-01-10T20:20:24
2021-01-10T20:20:24
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,840
py
from matplotlib import pyplot from pandas.plotting import register_matplotlib_converters from matplotlib import style from numpy import arange, linspace, ndarray, array, unique from scipy.interpolate import make_interp_spline, BSpline from src.store import Store style.use('ggplot') register_matplotlib_converters() class PlotterHelper: @staticmethod def show(): pyplot.show() @staticmethod def plotEvaluations(names: list, results: list, figure: str, show: bool = False): f = pyplot.figure(figure) x = arange(len(names)) # the label locations width = 0.35 # the width of the bars rects1 = pyplot.bar(x - width / 2, results, width) # Add some text for names, title and custom x-axis tick names, etc. pyplot.ylabel('Scores') pyplot.title('Models Scores') pyplot.xticks(x, names) def autolabel(rects): """Attach a text label above each bar in *rects*, displaying its height.""" for rect in rects: height = rect.get_height() pyplot.annotate('{}'.format(height), xy=(rect.get_x() + rect.get_width() / 2, height), xytext=(0, -75), # 3 points vertical offset textcoords="offset points", ha='center', va='bottom', rotation=90) autolabel(rects1) f.tight_layout() if show: pyplot.show() else: return f @staticmethod def plotFormula(store: Store, figure: str, show: bool = False): features = store.features fig = pyplot.figure(figure, figsize=[10, 10]) pyplot.suptitle(store.model.getAlgorithmUsed(), y=1, fontsize=18) pyplot.title(store.resultingFunction, wrap=True, fontsize=10) pyplot.xlabel('Variables - X') pyplot.ylabel('Results - Y') for feature in features: x = store.dataSet.getFeatureData(feature) y = store.dataSet.getLabelData() uqIdx = PlotterHelper.uniqueIndexes(x, y) x, y = PlotterHelper.sortRelatedLists(x[uqIdx], y[uqIdx]) xNew = linspace(x.min(), x.max(), store.numberOfSamples) bSpline = make_interp_spline(x, y) yNew = bSpline(xNew) pyplot.plot(xNew, yNew, label=feature) pyplot.legend(loc=3) if show: pyplot.show() else: return fig @staticmethod def sortRelatedLists(list1: ndarray, list2: ndarray) -> (array, array): x, y = (array(t) for t in zip(*sorted(zip(list1, list2)))) return x, y @staticmethod def uniqueIndexes(x: array, y: array): arr = array([*zip(y, x)]) return unique(arr[:, 1], return_index=True)[1]
[ "iulian.octavian.preda@gmail.com" ]
iulian.octavian.preda@gmail.com
95637f216d9d117730f49b84e3ec74f12d08b5c7
14dbf7e02bd2d71347457efcf63411b00fe38e44
/src/catalog/views.py
768c2e14805bb564a6bedb617c525cac759ef51d
[]
no_license
raghavmalawat/django-mozilla-tutorials
a1c866ad4a7bf6c65cd28e87698975fa061e5609
dbcc8f941f2e16d801341747a1d1c85b908ce2e4
refs/heads/master
2021-06-21T13:32:57.477036
2019-11-26T21:33:51
2019-11-26T21:33:51
223,615,668
0
0
null
2021-06-10T22:19:08
2019-11-23T16:03:22
Python
UTF-8
Python
false
false
5,286
py
from django.shortcuts import render from catalog.models import Book, Author, BookInstance, Genre from django.views import generic from django.shortcuts import get_object_or_404 from django.contrib.auth.mixins import LoginRequiredMixin import datetime from django.http import HttpResponseRedirect from django.urls import reverse from catalog.forms import RenewBookForm from django.contrib.auth.decorators import permission_required from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from .models import Author from django.contrib.auth.mixins import PermissionRequiredMixin # Create your views here. def index(request): """View function for home page of site.""" # Generate counts of some of the main objects num_books = Book.objects.all().count() num_instances = BookInstance.objects.all().count() # Available books (status = 'a') num_instances_available = BookInstance.objects.filter(status__exact='a').count() # The 'all()' is implied by default. num_authors = Author.objects.count() num_genre = Genre.objects.count() meluha_count = len(Book.objects.filter(title__icontains='meluha')) # Number of visits to this view, as counted in the session variable. num_visits = request.session.get('num_visits', 0) request.session['num_visits'] = num_visits + 1 context = { 'num_books': num_books, 'num_instances': num_instances, 'num_instances_available': num_instances_available, 'num_authors': num_authors, "num_genre" : num_genre, "meluha_count" : meluha_count, 'num_visits': num_visits, } # Render the HTML template index.html with the data in the context variable return render(request, 'index.html', context=context) class BookListView(generic.ListView): model = Book paginate_by = 10 class BookDetailView(generic.DetailView): model = Book class AuthorListView(generic.ListView): model = Author paginate_by = 10 class AuthorDetailView(generic.DetailView): model = Author class LoanedBooksByUserListView(LoginRequiredMixin, generic.ListView): """Generic class-based view listing books on loan to current user.""" model = BookInstance template_name = 'catalog/bookinstance_list_borrowed_user.html' paginate_by = 10 def get_queryset(self): return BookInstance.objects.filter(borrower=self.request.user).filter(status__exact='o').order_by('due_back') class LoanedBooksAllListView(PermissionRequiredMixin, generic.ListView): """Generic class-based view listing all books on loan. Only visible to users with can_mark_returned permission.""" model = BookInstance permission_required = 'catalog.can_mark_returned' template_name = 'catalog/bookinstance_list_borrowed_all.html' paginate_by = 10 def get_queryset(self): return BookInstance.objects.filter(status__exact='o').order_by('due_back') @permission_required('catalog.can_mark_returned') def renew_book_librarian(request, pk): book_instance = get_object_or_404(BookInstance, pk=pk) # If this is a POST request then process the Form data if request.method == 'POST': # Create a form instance and populate it with data from the request (binding): form = RenewBookForm(request.POST) # Check if the form is valid: if form.is_valid(): # process the data in form.cleaned_data as required (here we just write it to the model due_back field) book_instance.due_back = form.cleaned_data['renewal_date'] book_instance.save() # redirect to a new URL: return HttpResponseRedirect(reverse('all-borrowed') ) # If this is a GET (or any other method) create the default form. else: proposed_renewal_date = datetime.date.today() + datetime.timedelta(weeks=3) form = RenewBookForm(initial={'renewal_date': proposed_renewal_date}) context = { 'form': form, 'book_instance': book_instance, } return render(request, 'catalog/book_renew_librarian.html', context) class AuthorCreate(PermissionRequiredMixin, CreateView): model = Author fields = '__all__' initial = {'date_of_death': '05/01/2018'} permission_required = 'catalog.can_mark_returned' class AuthorUpdate(PermissionRequiredMixin, UpdateView): model = Author fields = ['first_name', 'last_name', 'date_of_birth', 'date_of_death'] permission_required = 'catalog.can_mark_returned' class AuthorDelete(PermissionRequiredMixin, DeleteView): model = Author success_url = reverse_lazy('authors') permission_required = 'catalog.can_mark_returned' # Classes created for the forms challenge class BookCreate(PermissionRequiredMixin, CreateView): model = Book fields = '__all__' permission_required = 'catalog.can_mark_returned' class BookUpdate(PermissionRequiredMixin, UpdateView): model = Book fields = '__all__' permission_required = 'catalog.can_mark_returned' class BookDelete(PermissionRequiredMixin, DeleteView): model = Book success_url = reverse_lazy('books') permission_required = 'catalog.can_mark_returned'
[ "raghavmalawat@gmail.com" ]
raghavmalawat@gmail.com
6b25126d87e2eec487b5fa04969c41631bd9f465
9fcff439d07809c333ac3d90e30c0468c0c53d79
/LiveCarPrice/app.py
6d3fd2788bf8e4a8331b7556b83486a265c915eb
[]
no_license
jeetbhatt-sys/Car_Price_Prediction
565ea4714171dd8576db322c554c15d677ee3825
7835b66e862ce55a655748d8da9679bf2e7efa74
refs/heads/main
2023-05-29T20:57:32.311057
2021-06-14T18:15:16
2021-06-14T18:15:16
376,916,600
0
0
null
null
null
null
UTF-8
Python
false
false
2,085
py
# -*- coding: utf-8 -*- """ Created on Mon Jun 14 23:20:48 2021 @author: jbhatt """ from flask import Flask, render_template, request import jsonify import requests import pickle import numpy as np import sklearn from sklearn.preprocessing import StandardScaler app = Flask(__name__) model = pickle.load(open('random_forest_regression_model.pkl', 'rb')) @app.route('/',methods=['GET']) def Home(): return render_template('index.html') standard_to = StandardScaler() @app.route("/predict", methods=['POST']) def predict(): Fuel_Type_Diesel=0 if request.method == 'POST': Year = int(request.form['Year']) Present_Price=float(request.form['Present_Price']) Kms_Driven=int(request.form['Kms_Driven']) Kms_Driven2=np.log(Kms_Driven) Owner=int(request.form['Owner']) Fuel_Type_Petrol=request.form['Fuel_Type_Petrol'] if(Fuel_Type_Petrol=='Petrol'): Fuel_Type_Petrol=1 Fuel_Type_Diesel=0 else: Fuel_Type_Petrol=0 Fuel_Type_Diesel=1 Year=2020-Year Seller_Type_Individual=request.form['Seller_Type_Individual'] if(Seller_Type_Individual=='Individual'): Seller_Type_Individual=1 else: Seller_Type_Individual=0 Transmission_Mannual=request.form['Transmission_Mannual'] if(Transmission_Mannual=='Mannual'): Transmission_Mannual=1 else: Transmission_Mannual=0 prediction=model.predict([[Present_Price,Kms_Driven2,Owner,Year,Fuel_Type_Diesel,Fuel_Type_Petrol,Seller_Type_Individual,Transmission_Mannual]]) output=round(prediction[0],2) if output<0: return render_template('index.html',prediction_texts="Sorry you cannot sell this car") else: return render_template('index.html',prediction_text="You Can Sell The Car at {}".format(output)) else: return render_template('index.html') if __name__=="__main__": app.run(debug=True)
[ "noreply@github.com" ]
noreply@github.com
32ae20672aa8d52e9e5ae580dac2e7c2a5b941c4
0df602f1cc4a5531069954b9a94eca195d720531
/test/conmax.py
3aedee7a3ce0268fa359573baa28f249e33170d6
[ "LicenseRef-scancode-warranty-disclaimer", "MIT", "BSD-3-Clause-Open-MPI", "BSD-2-Clause", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
zjc5415/qml
fcfa67c85a69f990e130bea2be57b8182671cdd1
6e639c6438448d7b7090bb4d6ab2efb3dc9f3b94
refs/heads/master
2020-12-24T19:17:35.115241
2015-12-27T10:56:29
2015-12-27T10:56:29
null
0
0
null
null
null
null
UTF-8
Python
false
false
23,952
py
#!/usr/bin/env python from __future__ import division from fractions import Fraction from decimal import Decimal from qform import * def qforms(x): if isinstance(x, str): return x else: return qform(x) def test_root_opt(): output("""\ rootx_opt:{ f:{(x-3)*x-5}; $[x=0;.qml.root[f;4 7]; x=1;(::;0<)@'.qml.rootx[`full;f;4,7.]`x`iter; x=2;(null;::;::;::;`sign=)@' .qml.rootx[`full`quiet`iter,200,`tol,0;f;6 7.] `x`last`err`iter`sig; x=3;y~@[(),.qml.root[;-1 1]@;z;`$]; x=4;y~@[(),.qml.root[::;]@;z;`$]; x=5;y~@[(),.qml.rootx[;::;-1 1]@;z;`$]; '`]}; test["rootx_opt[0;::;::]";"5"]; test["rootx_opt[1;::;::]";"5 1"]; test["rootx_opt[2;::;::]";"1 7 8 200 1"]; test["rootx_opt[3;`type;`]";"1"]; test["rootx_opt[3;`type;()]";"1"]; test["rootx_opt[3;`type;{0},{0}]";"1"]; test["rootx_opt[3;`foo;{'`foo}]";"1"]; test["rootx_opt[3;`type;{()}]";"1"]; test["rootx_opt[3;`rank;{y}]";"1"]; test["rootx_opt[4;`type;0]";"1"]; test["rootx_opt[4;`length;()]";"1"]; test["rootx_opt[4;`length;1#0]";"1"]; test["rootx_opt[4;`length;3#0]";"1"]; test["rootx_opt[4;`type;`,0]";"1"]; test["rootx_opt[4;`type;0,`]";"1"]; test["rootx_opt[4;`sign;1 1]";"1"]; test["rootx_opt[5;`opt;`foo]";"1"];""") def test_root(): output("""\ root_n:{[norm;f;x0] norm .qml.rootx[`quiet;f;x0]}; solve_n:{[norm;f;x0] norm .qml.solvex[`quiet;f;x0]};""") def emit(func, alt_x0, x, norm = "::", root = True, solve = True): alt_funcs = [func, "'[neg;]" + func, "'[{x*x};]" + func] if root: for func in alt_funcs[:2]: for i, j in ((0, 2), (3, 0), (2, 1), (1, 3)): output(" test[\"root_n[%s;%s;(%s;%s)]\";\"%s\"];" % (norm, func, qforms(alt_x0[i]), qforms(alt_x0[j]), qforms(x))) if solve: for func in alt_funcs: for x0 in alt_x0: output(" test[\"solve_n[%s;%s;%s]\";\"%s\"];" % (norm, func, qforms(x0), qforms(x))) emit("(42-)", [0, 1, 100, 200], 42) emit("{(x-100)*x-3}", [-2, 0, 5, 10], 3) emit("{(x-2)*5+(4*x)+x*x}", [-100, 0, 5, 100], 2, solve = False) # 1 emit("{.5+.qml.sin x}", [-5, 0, 5, 10], "pi%3", norm = "{abs(1.5*pi)-x mod 2*pi}") emit("{.qml.sin[x]+(x%4)+1%7}", [-10, -5, 0, 5], Decimal("-0.11448565782234166611"), solve = False) emit("{(x*.qml.exp x)-2}", [-Fraction(1, 2), 0, 1, Fraction(3, 2)], Decimal("0.85260550201372549135")) emit("(abs@.qml.e-)", [-2, -1, 3, 4], "e", root = False) emit("{-1e-1+.qml.atan[x]+pi%2}", [0, -1, -25, -100], Decimal("-9.9666444232592378598")) emit("{$[0<=x-:1;.qml.sqrt[x]-1e-1;1%x]}", [-10, 0, 2, 10], Fraction(101, 100), solve = False) emit("{.qml.log 1-abs 42-x}", [Fraction(209, 5), Fraction(293, 7), Fraction(337, 8), Fraction(169, 4)], 42, root = False) def test_line_opt(): output("""\ linex_opt:{ f:{(x-3)*x-5}; $[x=0;.qml.line[f;0;1]; x=1;(::;::;0<)@'.qml.linex[enlist`full;f;0.;1]`x`f`iter; x=2;{(null y 0;x[y 1]-y 2;0<y 3;`iter=y 4)}[f] .qml.linex[`full`quiet`iter`tol!1 1 3 0;f;0.;1.] `x`last`f`iter`sig; x=3;y~@[(),.qml.linex[;f;0;1]@;z;`$]; x=4;y~@[(),.qml.line[;0;1]@;z;`$]; x=5;y~@[(),.qml.line[abs;;].;z;`$]; x=6;y~@[(),.qml.linex[;abs;0;1]@;z;`$]; '`]}; test["linex_opt[0;::;::]";"4"]; test["linex_opt[1;::;::]";"4 -1 1"]; test["linex_opt[2;::;::]";"1 0 1 1"]; test["linex_opt[3;`iter;`iter,1]";"1"]; test["linex_opt[4;`type;`]";"1"]; test["linex_opt[4;`type;()]";"1"]; test["linex_opt[4;`type;{0},{0}]";"1"]; test["linex_opt[4;`foo;{'`foo}]";"1"]; test["linex_opt[4;`type;{()}]";"1"]; test["linex_opt[4;`rank;{y}]";"1"]; test["linex_opt[5;`type;`,0]";"1"]; test["linex_opt[5;`type;0,`]";"1"]; test["linex_opt[5;`type;(`;enlist 0)]";"1"]; test["linex_opt[5;`type;(enlist 0;`)]";"1"]; test["linex_opt[6;`opt;`foo]";"1"];""") def test_line(): output("""\ line_n:{[norm;f;base;x0] norm .qml.linex[`quiet;f;base;x0]}; minx_n:{[norm;opt;f;x0] norm .qml.minx[`quiet,opt;f;x0]};""") def emit(func, alt_x0, x, norm = "::"): for i, j in ((0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (3, 2), (3, 1), (3, 0), (2, 1), (2, 0)): output(" test[\"line_n[%s;%s;%s;%s]\";\"%s\"];" % (norm, func, qforms(alt_x0[i]), qforms(alt_x0[j]), qforms(x))) for x0 in alt_x0: for opts in ["()", "`slp", "`nm", "`sbplx"]: output(" test[\"minx_n[%s;%s;%s;%s]\";\"%s\"];" % (norm, opts, func, qforms(x0), qforms(x))) emit("{(x-2)*x+1}", [-1, 0, 1, 2], Fraction(1, 2)) emit("{(x*(x+1)*x+3)-(x<-2)*8+x*x*x}", [-2, -1, 0, 3], "(1%3)*-4+.qml.sqrt 7") emit("{1+x*-4+(x*.qml.sqrt[2]-4)+x*x*x}", [-3, -1, 2, 5], ".qml.sqrt 2") emit(".qml.cos", [-4, 0, 1, 7], "pi", norm = "mod[;2*pi]") emit("{.qml.sin[x]+x*x%5}", [-5, -3, 3, 5], Decimal("-1.1105105035811121290")) emit("{x*.qml.exp[x]-2}", [-1, 0, 1, 2], Decimal("0.37482252818362338162")) emit("abs@.qml.e-", [-2, -1, 3, 4], "e") emit("{-1%1+1e3*.qml.pow[x-1e4;2]}", [0, 1, 19999, 20000], 10000) emit("{-1%x-x<1}", [1, "1+100*.qml.eps", 2, 3], 1) emit("{-1e300|.qml.log abs 42-x*x}", [-10, 0, 50, 100], ".qml.sqrt 42", norm = "abs") def test_solve_opt(): output("""\ solvex_opt:{ f:{20-x-2*y},{-10-(3*x)+4*y}; $[x=0;.qml.solve[f;0 0]; x=1;(::;0<)@' .qml.solvex[`full`rk`steps`tol`iter!1,1b,10,.1,100;f;0.,0] `x`iter; x=2;(all null@;::;prec>abs@;0<;`feas=)@' .qml.solvex[`full`quiet`slp`tol,0;f;0.,0] `x`last`err`iter`sig; x=3;y~@[(),.qml.solve[{1};]@;z;`$]; x=4;y~@[(),.qml.solve[;0]@;z;`$]; x=5;y~@[(),.qml.solvex[;{0};0]@;z;`$]; '`]}; test["solvex_opt[0;::;::]";"6 -7"]; test["solvex_opt[1;::;::]";"(6 -7;1)"]; test["solvex_opt[2;::;::]";"(1;6 -7;1;1;1)"]; test["solvex_opt[3;`feas;enlist 0#0]";"1"]; test["solvex_opt[4;`type;`]";"1"]; test["solvex_opt[4;`type;`,0]";"1"]; test["solvex_opt[4;`type;{0},`]";"1"]; test["solvex_opt[4;`type;({0};`,0)]";"1"]; test["solvex_opt[4;`type;({0};{0},`)]";"1"]; test["solvex_opt[4;`type;({0};`,{0})]";"1"]; test["solvex_opt[4;`foo;{'`foo}]";"1"]; test["solvex_opt[4;`type;{()}]";"1"]; test["solvex_opt[4;`rank;{y}]";"1"]; test["solvex_opt[5;`opt;`foo]";"1"]; test["solvex_opt[5;`opt;`slp`rk]";"1"]; test["solvex_opt[5;`opt;`slp`steps,10]";"1"];""") def test_solve(): def emit(funcs, dfuncs, alt_x0, x, comment = ""): if isinstance(funcs, str): assert not dfuncs alt_funcs = [ funcs, "'[neg;]each reverse" + funcs, "raze .[;(::;0);'[neg;]]reverse each 2 cut" + funcs ] else: if len(funcs) == 0: alt_funcs = ["()"] elif len(funcs) == 1: alt_funcs = [ funcs[0], "'[neg;]%s" % funcs[0] ] else: alt_funcs = [ ",".join(funcs), "'[neg;]each %s" % ",".join(funcs[::-1]), "(%s)" % ";".join( ("%s" if i % 2 else "'[neg;]%s") % funcs[min(i ^ 1, len(funcs)-1)] for i in range(len(funcs))) ] if dfuncs: assert len(funcs) == len(dfuncs) != 0 if len(funcs) == 1: alt_funcs += [ "enlist%s,%s" % (funcs[0], dfuncs[0]), "enlist('[neg;]each %s,%s)" % (funcs[0], dfuncs[0]) ] else: alt_funcs += [ "(%s)" % ";".join( map(",".join, zip(funcs, dfuncs))), "('[neg;]'')(%s)" % ";".join( map(",".join, reversed(zip(funcs, dfuncs)))), "(%s)" % ";".join( ("%s" if i % 2 else "'[neg;]each %s") % "%s,%s" % (funcs[min(i ^ 1, len(funcs)-1)], dfuncs[min(i ^ 1, len(funcs)-1)]) for i in range(len(funcs))) ] if comment: comment = " / " + comment for funcs in alt_funcs: for x0 in alt_x0: output(" test[\"solve_n[::;%s;%s]\";\"%s\"];%s" % (funcs, qforms(x0), qforms(x), comment)) emit(["{0}", "{0}"], None, ["enlist 0#0."], [[]]) emit([], None, [[6, 7]], [6, 7]) emit(["(42-)"], ["{-1}"], [0], 42) emit(["(1-.qml.log@)", "{(x-.qml.e)*x-1}"], None, [-1], None, comment = "was invalid read") emit(["(1-.qml.log@)", "{(x-.qml.e)*x-1}"], ["(-1%)", "{-1-.qml.e-2*x}"], [1, 2, 3], "e") emit(["{25-(x*x)+y*y}", "{64-x*7+3*y}"], ["{-2*(x;y)}", "{(-7-3*y;-3*x)}"], [[0, 0], [5, 10], [7, -15]], [4, 3]) emit(["{25-(x*x)+y*y}", "{y-1+x%.qml.pow[16;1%x]}"], ["{-2*(x;y)}", "{y;((-1-.qml.log[16]%x)%.qml.pow[16;1%x];1)}"], [[1, 0], [2, -1], [10, 10]], [4, 3]) emit(["{y-.qml.sin x}", "{y-.qml.sin[x]+1+x%7}"], ["{y;(neg .qml.cos x;1)}", "{y;(neg .qml.cos[x]+1%7;1)}"], [[0, 0], [30, 0], [-20, -10]], "(-7;.qml.sin -7)") emit(["{3+y-y*x*x}", "{5-(x*x)+y*y}", "{y-.qml.exp x-2}"], ["{(-2*x*y;1-x*x)}", "{-2*(x;y)}", "{y;(neg .qml.exp x-2;1)}"], [[1, 0], [4, -2], [10, 2]], [2, 1]) emit(["{1-z-y}", "{2-x-(4*y)-3*z}", "{3-(4*z)-y+4*x}"], ["{z;0 1 -1}", "{z;-1 4 -3}", "{z;4 1 -4}"], [[0, 0, 0], [5, -3, 1], [-1000, 2000, 4000]], [4, 5, 6]) emit(["{-6-x+y+z}", "{50-(x*x)+(y*y)+z*z}", "{60-x*y*z}", "{32-y*z-x}"], ["{z;-1 -1 -1}", "{-2*(x;y;z)}", "{neg(y*z;x*z;x*y)}", "{(y;x-z;neg y)}"], [[1, -3, -3], [5, 0, -5], [12, -8, 4]], [3, -4, -5]); emit("{1-last x},{sum .qml.pow[x;til 6]*}each -1 1 -2 2 -5", None, [[[0] * 6], [[-100] * 6], [[0, 100, -200, -200, 100, 0]]], [[20, 4, -25, -5, 5, 1]]) emit(["{y;.qml.log[x]-(.qml.asin[.qml.sin[pi*x]]%pi)+x*(1+2*.qml.log 1.5)%3}", "{sum x*x:21 -17-(1 -2.;3 4.)mmu y}"], None, [[Fraction(7, 4), [1, 2]], [Fraction(5, 4), [2, -4]], [Fraction(1, 10), [2, 0]]], [Fraction(3, 2), [5, -8]]) def test_min_opt(): output("""\ minx_opt:{[x;opt;y;z] f:{(x*x)+(2*y*y)-x*y+1}; m:$[opt~();.qml.min;.qml.minx opt]; $[x=0;.qml.min[f;0 0]; x=1;(::;::;0<)@'.qml.minx[opt,`full;f;0 0]`x`f`iter; x=2;(all null@;::;::;::;`iter=)@' .qml.minx[opt,`full`quiet`iter,0;f;1 -1] `x`last`f`iter`sig; x=3;(0#0.)~last .qml.min[{y;0};(0;())]; x=4;y~@[(),m[abs;]@;z;`$]; x=5;y~@[(),m[;0]@;z;`$]; x=6;y~@[(),m .;z;`$]; x=7;y~@[(),.qml.minx[;{0};0]@;z;`$]; '`]}; test["minx_opt[0;();::;::]";"4 1%7"]; test["minx_opt[1;();::;::]"; "(4 1%7;-2%7;1)"]; test["minx_opt[1;`nm;::;::]"; "(4 1%7;-2%7;1)"]; test["minx_opt[1;`sbplx;::;::]";"(4 1%7;-2%7;1)"]; test["minx_opt[2;();::;::]"; "(1;1 -1;3;0;1)"]; test["minx_opt[2;`nm;::;::]"; "(1;1 -1;3;1;1)"]; test["minx_opt[2;`sbplx;::;::]";"(1;1 -1;3;1;1)"]; test["minx_opt[3;();::;::]";"1"];""") def emit(err, arg): output(' test["minx_opt[%s;%s;%s;%s]";"1"];' % (which, opt, err, arg)) which = 4 for opt in ["()", "`nm", "`sbplx"]: emit("`type", "`") emit("`nan", "0n") for opt in ["`nm", "`sbplx"]: emit("`limit", "10001#0") emit("`limit", "100 cut 10001#0") which = 5 for opt in ["()", "`nm", "`sbplx"]: emit("`type", "`") emit("`type", "()") emit("`type", "`,0") emit("`type", "{},`") emit("`type", "`,{}") emit("`foo", "{'`foo}") emit("`type", "{()}") emit("`rank", "{y}") which = 6 opt = "()" emit("`rank", "({0},{y};0)") emit("`type", "({0},{`};0)") emit("`type", "({0},{0};1#0)") emit("`type", "({0},{1#0};0)") emit("`type", "({0},{2#0};1#0)") emit("`type", "({y;0},{y;3#0};2#0)") emit("`type", "({y;0},{y;enlist 2#0};2#0)") emit("`type", "({0},{2#0};enlist 2#0)") which = 7 opt = "::" emit("`opt", "`foo") emit("`opt", "`slp`rk") emit("`opt", "`slp`steps,10") emit("`opt", "`nm`sbplx") emit("`opt", "`nm`slp") emit("`opt", "`nm`rk") emit("`opt", "`nm`tol,1e-6") emit("`opt", "`nm`steps,10") def test_min(): def emit(func, dfunc, alt_x0, x, more = False): alt_funcs = [(False, func)] if dfunc: alt_funcs += [(True, "%s,%s" % (func, dfunc))] for opts in ["", "`nm", "`sbplx"]: if more: opts += "`iter,100000" for grad, func in alt_funcs: for x0 in alt_x0: if grad and ("`nm" in opts or "`sbplx" in opts): continue output(" test[\"minx_n[::;%s;%s;%s]\";\"%s\"];" % (opts or "()", func, qforms(x0), qforms(x))) emit("{-1}", None, ["enlist 0#0."], [[]]) emit("{(a*a:x-1)+10*b*b:y-1+x*x}", "{((2*x-1)-40*x*y-1+x*x;20*y-1+x*x)}", [[0, 0], [5, 5], [-10, 10]], [1, 2]) emit("{(x*x*x)+(y*y*y)+(2*x*y)+.qml.pow[5;neg x]+.qml.pow[4;neg y]}", "{((3*x*x)+(2*y)-.qml.log[5]*.qml.pow[5;neg x];(2*x)+(3*y*y)-.qml.log[4]*.qml.pow[4;neg y])}", [[0, 0], [-10, 0], [10, -20]], [Decimal("0.34343411653951616845"), Decimal("0.28609347201908362344")]) emit("{(x*x*x)+(y*y*y)+(2*x*y)+.qml.pow[5;neg x]+.qml.pow[4;neg y]+z*z+y}", "{((3*x*x)+(2*y)-.qml.log[5]*.qml.pow[5;neg x];(2*x)+(3*y*y)+z-.qml.log[4]*.qml.pow[4;neg y];y+2*z)}", [[0, 0, 0], [1, 1, -1], [10, -20, 30]], [Decimal("0.29002456462855436461"), Decimal("0.37840366475888345284"), Decimal("-0.18920183237944172642")]) emit("{[x;y;z;u]sum x*x:(x-3;(9*y)-x*x;z-x-y;u-z*z)}", "{[x;y;z;u]sum 2*(1 0 0 0;(-2*x;9;0;0);-1 1 1 0;(0;0;-2*z;1))*(x-3;(9*y)-x*x;z-x-y;u-z*z)}", [[0, 0, 0, 0], [-1, -2, -3, -4], [500, -1000, 1000, -500]], [3, 1, 2, 4], more = True) emit("{{sum{x*x}sum[z*x]-y}[(x;x*x);.qml.sin[10*x]+2*.qml.atan 10*x:til[11]%10]}[]", "{{enlist x mmu 2*sum[x*z]-y}[(x;x*x);.qml.sin[10*x]+2*.qml.atan 10*x:til[11]%10]}[]", [[[0, 0]], [[10, -5]], [[-100, 50]]], [[Decimal("9.4011843228733705351"), Decimal("-6.7445676817128794990")]], more = True) def test_conmin_opt(): output("""\ conminx_opt:{[x;opt;y;z] f:{(x*x)+(y*y)+(2*x*y)-2*x}; c:{y-2+x},{y-1}; m:$[opt~();.qml.conmin;.qml.conminx opt]; $[x=0;.qml.conmin[f;c;0 0]; x=1;{(::;::;::;0<)@'x`x`f`cons`iter} .qml.conminx[`full`quiet`slp`lincon`tol,.1;f;c;0 0]; x=2;{(all null@;::;::;::;::;::;`iter=)@'x`x`last`f`cons`err`iter`sig} .qml.conminx[`full`quiet`rk`steps`iter!1 1 1 3 0;f;c;-.5 -1]; x=3;{(z[`f]-x . l;0<>z`f;z[`err]+min[y .\:l:z`last];`feas=z`sig)}[f;c1] .qml.conminx[opt,`full`quiet;f;c1:c,{neg y};0 0]; x=4;y~@[(),m[;{x};0]@;z;`$]; x=5;y~@[(),m[{x};;0n]@;z;`$]; x=6;y~@[(),m[{x};;0]@;z;`$]; x=7;y~@[(),m .;z;`$]; x=8;y~@[(),m[{0};{-1},{1};]@;z;`$]; x=9;y~@[(),.qml.conminx[;{0};();0]@;z;`$]; '`]}; test["conminx_opt[0;();::;::]";"-3 5%4"]; test["conminx_opt[1;();::;::]";"(-3 5%4;7%4;0 1%4;1)"]; test["conminx_opt[2;();::;::]";"(1;-.5 -1;3.25;-2.5 -2;2.5;0;1)"]; test["conminx_opt[3;();::;::]"; "0 1 0 1"]; test["conminx_opt[3;`cobyla;::;::]";"0 1 0 1"];""") def emit(err, arg): output(' test["conminx_opt[%s;%s;%s;%s]";"1"];' % (which, opt, err, arg)) which = 4 for opt in ["()", "`cobyla"]: emit("`type", "`") emit("`type", "()") emit("`type", "`,0") emit("`type", "{},`") emit("`type", "`,{}") emit("`foo", "{'`foo}") emit("`type", "{()}") emit("`rank", "{y}") which = 5 for opt in ["`cobyla"]: emit("`nan", "{x}") emit("`nan", "()") which = 6 for opt in ["()", "`cobyla"]: emit("`type", "`") emit("`type", "{0},`,{0}") emit("`type", "({0};`,0)") emit("`type", "({0};{0},`)") emit("`type", "({0};`,{0})") emit("`foo", "{'`foo}") emit("`foo", "{0},{'`foo},{0}") emit("`type", "{()}") emit("`type", "{0},{()},{0}") emit("`rank", "{y}") emit("`rank", "{0},{y},{0}") for opt in ["`cobyla"]: emit("`limit", "10001#{0}") emit("`limit", "10001#enlist{0},{0}") which = 7 for opt in ["()"]: emit("`rank", "({0};enlist{0},{y};0)") emit("`type", "({0};enlist{0},{`};0)") emit("`type", "({0};enlist{0},{0};1#0)") emit("`type", "({0};enlist{0},{1#0};0)") emit("`type", "({0};enlist{0},{2#0};1#0)") emit("`type", "({y;0};enlist{y;0},{y;3#0};2#0)") emit("`type", "({y;0};enlist{y;0},{y;enlist 2#0};2#0)") emit("`type", "({0};enlist{0},{2#0};enlist 2#0)") which = 8 for opt in ["()", "`cobyla", "`cobyla`full"]: emit("`feas", "enlist 0#0") for opt in ["`cobyla"]: emit("`limit", "10001#0") emit("`limit", "100 cut 10001#0") which = 9 opt = "::" emit("`opt", "`foo") emit("`opt", "`slp`rk") emit("`opt", "`slp`steps,10") emit("`opt", "`cobyla`slp") emit("`opt", "`cobyla`rk") emit("`opt", "`cobyla`steps,10") def test_conmin(): def emit(func, dfunc, cons, dcons, alt_x0, x, linear = False, more = False): opts = "`quiet" alt_opts = [opts] if linear: alt_opts += [opts + "`lincon", opts + "`slp"] alt_opts += [opts + "`cobyla"] alt_funcs = [(False, func)] if dfunc: alt_funcs += [(True, "%s,%s" % (func, dfunc))] if isinstance(cons, str): assert not dcons alt_cons = [(False, cons), (False, "reverse" + cons)] elif cons: alt_cons = [(False, ",".join(cons))] if len(cons) > 1: alt_cons += [(False, ",".join(cons[::-1]))] if dcons: assert len(cons) == len(dcons) if len(cons) == 1: alt_cons += [ (True, "enlist%s,%s" % (cons[0], dcons[0]))] else: alt_cons += [ (True, "(%s)" % ";".join( map(",".join, zip(cons, dcons)))), (True, "(%s)" % ";".join( "%s,%s" % (cons[i], dcons[i]) if i % 2 else cons[i] for i in reversed(range(len(cons))))) ] else: alt_cons = [(False, "()")] for cgrad, cons in alt_cons: for fgrad, func in alt_funcs: for x0 in alt_x0: for opts in alt_opts: if (fgrad or cgrad) and ("`nm" in opts or "`cobyla" in opts): continue if more: opts += "`iter,100000" if "`cobyla" in opts: opts += "00,`tol,1e-6" output( " test[\".qml.conminx[%s;%s;%s;%s]\";\"%s\"];" % (opts, func, cons, qforms(x0), qforms(x))) emit("{-1}", None, ["{1}"], None, ["enlist 0#0."], [[]]) emit("{(a*a:x-1)+10*b*b:y-1+x*x}", "{((2*x-1)-40*x*y-1+x*x;20*y-1+x*x)}", [], [], [[0, 0], [5, 5], [-10, 10]], [1, 2]) emit("{(x*x*x*x)+y*(3*x*1+x*6)+y*y*y-8}", "{((4*x*x*x)+y*3*1+x*12;(3*x*1+x*6)+4*y*y*y-6)}", ["{x-y+1}"], ["{y;1 -1}"], [[0, 0], [15, 5], [-10, -5]], [Decimal("6.1546405692889590154"), Decimal("-4.1526183884860082232")], linear = True) emit("{neg(5*x)+(3*y)+7*z}", "{z;-5 -3 -7}", ["{z;10-(2*x)+4*y}", "{15-(3*z)-y}", "{9-x+y+z}", "{z;x}", "{z;y}", "{z}"], ["{z;-2 -4 0}", "{z;0 1 -3}", "{z;-1 -1 -1}", "{z;1 0 0}", "{z;0 1 0}", "{z;0 0 1}"], [[0, 0, 0], [-8, -10, -3], [200, 400, 100]], [4, 0, 5], linear = True) emit("{[x;y;z;u]sum x*x:(x-3;(9*y)-x*x;z-x-y;u-z*z)}", "{[x;y;z;u]sum 2*(1 0 0 0;(-2*x;9;0;0);-1 1 1 0;(0;0;-2*z;1))*(x-3;(9*y)-x*x;z-x-y;u-z*z)}", ["{[x;y;z;u]sum -1 -1 1 1%v+1e-99%v:(x;y;z;u)}", "{[x;y;z;u]min(x;y;z;u)}"], ["{[x;y;z;u] -1 -1 1 1*(1e-99-v)%w*w:1e-99+v*:v:(x;y;z;u)}", "{[x;y;z;u]v=min v:(x;y;z;u)}"], [[1, 1, 1, 1], [2, -3, 4, -5], [1000, 1000, 500, 500]], [Decimal("3.1355504511518109809"), Decimal("1.1046418527109901434"), Decimal("1.4278718594741174466"), Decimal("1.9089393921649469239")], more = True) emit("{(x mmu (.01 .02 -.003;.02 .2 -.004;-.003 -.004 .001) mmu x)-.7*.1 .25 .05 mmu x:0.+x}", "{enlist(2*(.01 .02 -.003;.02 .2 -.004;-.003 -.004 .001)mmu 0.+x)-.7*.1 .25 .05}", ["{x 0}", "{x 1}", "{x 2}", "{sum(1%3)-x}", "{sum x-1%3}"], ["{enlist 1 0 0}", "{enlist 0 1 0}", "{enlist 0 0 1}", "{enlist -1 -1 -1}", "{enlist 1 1 1}"], [[[0, 0, 0]], [[0, Fraction(1, 2), Fraction(1, 2)]], [[Fraction(371, 3), Fraction(-217, 48), Fraction(4445, 12)]]], [[Fraction(3, 4), Fraction(1, 4), 0]], linear = True) emit("{neg x+2*y}", "{y;-1 -2}", ["{25-(x*x)+y*y}", "{1+(3*x)-x*y*(3+1%.qml.sqrt 11)%.qml.sqrt 14}", "{(67+2*.qml.sqrt 154)-(x*x)+(2*x*y)+4*y*y}", "{x-.5*y}"], ["{-2*(x;y)}", "{3 0-(y;x)*(3+1%.qml.sqrt 11)%.qml.sqrt 14}", "{(67+2*.qml.sqrt 154)-2*(x+y;x+4*y)}", "{y;1 -.5}"], [[0, 0], [-2, -8], [-7, 15]], ".qml.sqrt 11 14") emit("{y;0}", "{y;(0;0 0)}", "{x,(''[neg;x])}{y;.qml.log[x]-(.qml.asin[.qml.sin[pi*x]]%pi)+x*(1+2*.qml.log 1.5)%3},{sum{x*x}21 -17-(1 -2.;3 4.)mmu y}", None, [[Fraction(7, 4), [1, 3]], [Fraction(5, 4), [2, -4]], [Fraction(1, 10), [2, 0]]], [Fraction(3, 2), [5, -8]], more = True) def tests(): reps(25) prec("1e-5") test_root_opt() test_root() prec("1e-6") test_line_opt() test_line() prec("1e-4") test_solve_opt() test_solve() test_min_opt() test_min() prec("1e-3") test_conmin_opt() test_conmin() if __name__ == "__main__": tests()
[ "aaz@q-fu.com" ]
aaz@q-fu.com
fdf78e71f194e48b46db854cb4ed230f5fc0b717
b06ae2ee287ff08cf0c38606a20f2479398e646d
/faceRecog.py
51c172a11b305a6d41afd87a306b3fadab119039
[]
no_license
arkumish/pic-and-place
7d52f02fb5bf175d6cc7457549946d2af072d3db
56edc62b90c4fac8f1645def4cb43013643ef7f0
refs/heads/master
2022-12-09T11:25:45.684743
2019-11-22T20:59:03
2019-11-22T20:59:03
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,092
py
import face_recognition import os known_faces = [] known_image_list = [] def loadKnownImage(knownDirecName): for (root,direc,file) in os.walk(knownDirecName): fileList = file os.chdir(knownDirecName) for file in fileList: known_image_list.append(face_recognition.load_image_file(file)) #print(os.getcwd()) os.chdir("..") #print(os.getcwd()) print(len(known_image_list)) for known_image in known_image_list: known_faces.append(face_recognition.face_encodings(known_image)[0]) return(fileList) def loadAndCheck(unknownImageList): row = len(unknownImageList) col = len(known_image_list) found_faces = [[False]*col]*row os.chdir("unknown") for i in range(len(unknownImageList)): unknown_face = face_recognition.load_image_file(unknownImageList[i]) unknown_face_encoding = face_recognition.face_encodings(unknown_face) for face in unknown_face_encoding: results = face_recognition.compare_faces(known_faces, face, 0.54) for j in range(len(known_image_list)): if(results[j]): found_faces[i][j] = True os.chdir("..") return (found_faces,row,col)
[ "shellkoresahu@gmail.com" ]
shellkoresahu@gmail.com
849982e32acbbd86a80a1a28776728f8b7d0c1cd
fce49ad9f71d286c039cb804f9038a28fd9c6e6f
/source/country/utils.py
9d90692bf42e6ad616943e92a02f40ad0a63bee8
[]
no_license
x4rMa/mngweb
714c5ca49ab56074b0681f93a447c629b85e1570
fb8709f26b70a81ab87cb6c690607beb7c244416
refs/heads/master
2021-01-13T02:52:04.026573
2016-12-21T17:58:30
2016-12-21T17:58:30
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,277
py
from django.utils import timezone from portal.services import limsfm_get_countries from .models import Country def update_countries(): """update country data via. the LIMSfm api""" print("Fetching countries from LIMSfm...") try: countries = limsfm_get_countries() except Exception as e: print("An exception occured: %s" % e) print("Updating local database table...") created_count = 0 updated_count = 0 start_time = timezone.now() for country in countries: updated_values = { 'iso2': country['iso2_id'], 'iso3': country['iso3'], 'name': country['name'], 'phone_country_code': country['phone_country_code'], 'phone_trunk_code': country['phone_trunk_code'], } obj, created = Country.objects.update_or_create( iso2=country['iso2_id'], defaults=updated_values) if created: created_count += 1 else: updated_count += 1 delete_set = Country.objects.filter(updated__lt=start_time) deleted_count = len(delete_set) delete_set.delete() print("Countries update completed. %d created, %d updated, %d deleted." % (created_count, updated_count, deleted_count))
[ "andysmith.d@gmail.com" ]
andysmith.d@gmail.com
68dc9f5f113ec712039c84be9b87ece7752d9d5c
6055e035d28558c263abe438aa49ae5ce03e9ce7
/estado_gerenciar_pessoas.py
9b5a9cb4afb1be910f655f6bff96ad6383936cbd
[]
no_license
alisson-fs/projeto-ES-I
a9e78e59ce73e09fcbcafd85fcd477f85967aa5e
881b34ef374e57a0fd1e1f525a1e0e32aedc19cd
refs/heads/main
2023-08-17T06:42:33.811925
2021-09-21T17:08:42
2021-09-21T17:08:42
384,255,836
0
0
null
2021-07-08T21:55:36
2021-07-08T21:49:16
null
UTF-8
Python
false
false
1,959
py
from PySimpleGUI.PySimpleGUI import TRANSPARENT_BUTTON from pessoa import Pessoa from estado import Estado import PySimpleGUI as sg from registro_pessoas import RegistroPessoas class EstadoGerenciarPessoas(Estado): def __init__(self): super().__init__() self.__registro_pessoas = RegistroPessoas() def run(self): linha0 = [sg.Text("UFLIX", size=(30,1), font=("Helvetica",25))] linha1 = [sg.Text("Buscar clientes:", size=(30,1), font=("Helvetica",15))] linha2 = [sg.Text("CPF:", size=(30,1), font=("Helvetica",12))] linha3 = [sg.InputText("", key="pessoa")] linha4 = [sg.Text("ERRO: Cliente inválido!", size=(30,1), font=("Helvetica",12))] linha5 = [sg.Button("Voltar"), sg.Button("Visualizar"), sg.Button("Adicionar cliente"), sg.Button("Remover cliente")] if self.erro: self.container = [linha0, linha1, linha2, linha3, linha4, linha5] else: self.container = [linha0, linha1, linha2, linha3, linha5] self.window = sg.Window("UFLIX", self.container, font=("Helvetica", 14)) self.erro = False def ler_evento(self, event, values): pessoa = self.__registro_pessoas.consultar(values["pessoa"]) if event == "Voltar": self.window.close() return "catalogo" if event == "Visualizar": self.window.close() if pessoa != None: self.__registro_pessoas.atual = pessoa return "visualizar_pessoa" else: self.erro = True if event == "Adicionar cliente": self.window.close() return "cadastro" if event == "Remover cliente": self.window.close() if pessoa != None: self.__registro_pessoas.remover(pessoa.cpf) return "lista_pessoas" else: self.erro = True return "lista_pessoas"
[ "alissonfs100@gmail.com" ]
alissonfs100@gmail.com
f7b3b2faa86e0a9a1ac895411d5a0ba761b172ea
9907134b0da8e5391c51b00c426c648eece7b4b9
/Unidad 2/pfijo.py
a7a60477a2df6797926949881bacf7f7f695a593
[]
no_license
hectorrdz98/metodos-numericos
1fd21593c8c324f0e0e643cc08a8d930ea2e8cf3
dab8e9425f454be60a74d30c985a643bcb915ce6
refs/heads/master
2022-01-22T07:26:48.566615
2019-05-29T12:26:43
2019-05-29T12:26:43
167,975,465
0
0
null
null
null
null
UTF-8
Python
false
false
588
py
import math p0 = 3.8 n = 3 tol = 0.0001 def g(p): return -4 + (4*p) - (0.5 * p * p) flag = False for i in range(n): p = g(p0) print('\nVamos en {}, con g(p0)={} y p0={}'.format(i+1,g(p0),p0)) print('El abs={}'.format(math.fabs(p-p0))) if math.fabs(p-p0) <= tol: print('\nEl valor de p0={} ya se encuentra dentro de la tol de {} con {} ite'.format(p0,tol,i+1)) flag = True break p0 = p if not flag: print('\nSe realizaron las {} iteraciones, pero no se llegó a la tol de {}'.format(n,tol)) print('Se llegó a p0={}'.format(p0))
[ "=" ]
=
b0ebf56863454ffb4571867555552aad6d06569d
6527b66fd08d9e7f833973adf421faccd8b765f5
/yuancloud/addons/hw_proxy/controllers/main.py
1a934348be4f3f21a928d20583d78d39b10c4c17
[]
no_license
cash2one/yuancloud
9a41933514e57167afb70cb5daba7f352673fb4d
5a4fd72991c846d5cb7c5082f6bdfef5b2bca572
refs/heads/master
2021-06-19T22:11:08.260079
2017-06-29T06:26:15
2017-06-29T06:26:15
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,759
py
# -*- coding: utf-8 -*- import logging import commands import json import os import os.path import yuancloud import time import random import subprocess import json import werkzeug import werkzeug.wrappers _logger = logging.getLogger(__name__) from yuancloud import http from yuancloud.http import request # Those are the builtin raspberry pi USB modules, they should # not appear in the list of connected devices. BANNED_DEVICES = set([ "0424:9514", # Standard Microsystem Corp. Builtin Ethernet module "1d6b:0002", # Linux Foundation 2.0 root hub "0424:ec00", # Standard Microsystem Corp. Other Builtin Ethernet module ]) # drivers modules must add to drivers an object with a get_status() method # so that 'status' can return the status of all active drivers drivers = {} class Proxy(http.Controller): def get_status(self): statuses = {} for driver in drivers: statuses[driver] = drivers[driver].get_status() return statuses @http.route('/hw_proxy/hello', type='http', auth='none', cors='*') def hello(self): return "ping" @http.route('/hw_proxy/handshake', type='json', auth='none', cors='*') def handshake(self): return True @http.route('/hw_proxy/status', type='http', auth='none', cors='*') def status_http(self): resp = """ <!DOCTYPE HTML> <html> <head> <title>YuanCloud's PosBox</title> <style> body { width: 480px; margin: 60px auto; font-family: sans-serif; text-align: justify; color: #6B6B6B; } .device { border-bottom: solid 1px rgb(216,216,216); padding: 9px; } .device:nth-child(2n) { background:rgb(240,240,240); } </style> </head> <body> <h1>Hardware Status</h1> <p>The list of enabled drivers and their status</p> """ statuses = self.get_status() for driver in statuses: status = statuses[driver] if status['status'] == 'connecting': color = 'black' elif status['status'] == 'connected': color = 'green' else: color = 'red' resp += "<h3 style='color:"+color+";'>"+driver+' : '+status['status']+"</h3>\n" resp += "<ul>\n" for msg in status['messages']: resp += '<li>'+msg+'</li>\n' resp += "</ul>\n" resp += """ <h2>Connected Devices</h2> <p>The list of connected USB devices as seen by the posbox</p> """ devices = commands.getoutput("lsusb").split('\n') count = 0 resp += "<div class='devices'>\n" for device in devices: device_name = device[device.find('ID')+2:] device_id = device_name.split()[0] if not (device_id in BANNED_DEVICES): resp+= "<div class='device' data-device='"+device+"'>"+device_name+"</div>\n" count += 1 if count == 0: resp += "<div class='device'>No USB Device Found</div>" resp += "</div>\n</body>\n</html>\n\n" return request.make_response(resp,{ 'Cache-Control': 'no-cache', 'Content-Type': 'text/html; charset=utf-8', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', }) @http.route('/hw_proxy/status_json', type='json', auth='none', cors='*') def status_json(self): return self.get_status() @http.route('/hw_proxy/scan_item_success', type='json', auth='none', cors='*') def scan_item_success(self, ean): """ A product has been scanned with success """ print 'scan_item_success: ' + str(ean) @http.route('/hw_proxy/scan_item_error_unrecognized', type='json', auth='none', cors='*') def scan_item_error_unrecognized(self, ean): """ A product has been scanned without success """ print 'scan_item_error_unrecognized: ' + str(ean) @http.route('/hw_proxy/help_needed', type='json', auth='none', cors='*') def help_needed(self): """ The user wants an help (ex: light is on) """ print "help_needed" @http.route('/hw_proxy/help_canceled', type='json', auth='none', cors='*') def help_canceled(self): """ The user stops the help request """ print "help_canceled" @http.route('/hw_proxy/payment_request', type='json', auth='none', cors='*') def payment_request(self, price): """ The PoS will activate the method payment """ print "payment_request: price:"+str(price) return 'ok' @http.route('/hw_proxy/payment_status', type='json', auth='none', cors='*') def payment_status(self): print "payment_status" return { 'status':'waiting' } @http.route('/hw_proxy/payment_cancel', type='json', auth='none', cors='*') def payment_cancel(self): print "payment_cancel" @http.route('/hw_proxy/transaction_start', type='json', auth='none', cors='*') def transaction_start(self): print 'transaction_start' @http.route('/hw_proxy/transaction_end', type='json', auth='none', cors='*') def transaction_end(self): print 'transaction_end' @http.route('/hw_proxy/cashier_mode_activated', type='json', auth='none', cors='*') def cashier_mode_activated(self): print 'cashier_mode_activated' @http.route('/hw_proxy/cashier_mode_deactivated', type='json', auth='none', cors='*') def cashier_mode_deactivated(self): print 'cashier_mode_deactivated' @http.route('/hw_proxy/open_cashbox', type='json', auth='none', cors='*') def open_cashbox(self): print 'open_cashbox' @http.route('/hw_proxy/print_receipt', type='json', auth='none', cors='*') def print_receipt(self, receipt): print 'print_receipt' + str(receipt) @http.route('/hw_proxy/is_scanner_connected', type='json', auth='none', cors='*') def is_scanner_connected(self, receipt): print 'is_scanner_connected?' return False @http.route('/hw_proxy/scanner', type='json', auth='none', cors='*') def scanner(self, receipt): print 'scanner' time.sleep(10) return '' @http.route('/hw_proxy/log', type='json', auth='none', cors='*') def log(self, arguments): _logger.info(' '.join(str(v) for v in arguments)) @http.route('/hw_proxy/print_pdf_invoice', type='json', auth='none', cors='*') def print_pdf_invoice(self, pdfinvoice): print 'print_pdf_invoice' + str(pdfinvoice)
[ "liuganghao@lztogether.com" ]
liuganghao@lztogether.com
e584d6444f27ac9720ec741f0572adfc28f60949
549275146dc8ecdba9144a6aed2796baa1639eb3
/Codes/gracekoo/71_simplify-path.py
807cc60379f65ff9e0e24b1db82cabb8a8468010
[ "Apache-2.0" ]
permissive
asdf2014/algorithm
fdb07986746a3e5c36bfc66f4b6b7cb60850ff84
b0ed7a36f47b66c04b908eb67f2146843a9c71a3
refs/heads/master
2023-09-05T22:35:12.922729
2023-09-01T12:04:03
2023-09-01T12:04:03
108,250,452
270
87
Apache-2.0
2021-09-24T16:12:08
2017-10-25T09:45:27
Java
UTF-8
Python
false
false
630
py
# -*- coding: utf-8 -*- # @Time: 2020/3/12 12:01 # @Author: GraceKoo # @File: 71_simplify-path.py # @Desc:https://leetcode-cn.com/problems/simplify-path/ class Solution: def simplifyPath(self, path: str) -> str: if not path: return "" result_list = [] path = path.split("/") for value in path: if value == "..": if result_list: result_list.pop() elif value and value != ".": result_list.append(value) return "/" + "/".join(result_list) so = Solution() print(so.simplifyPath("/a/./b/../../c/"))
[ "gracekoo199@gmail.com" ]
gracekoo199@gmail.com
56be8fc42fe96b6bfce531741aa29291d015af4f
f806558088d5446635115ebe1191b703e503e536
/blog/models.py
e02e3dc46c3c440dec65e44b50921f2f6150c0b0
[]
no_license
HQ1363/HBlog
9cbd3f177526dfcb87d324e451ff60289f1d79de
4b40bd7dcded141b4807065a03542fe4282c88a9
refs/heads/master
2020-09-12T02:13:23.915180
2019-02-05T16:19:16
2019-02-05T16:19:16
222,266,681
0
0
null
2019-11-19T14:53:01
2019-11-17T15:10:07
Python
UTF-8
Python
false
false
3,626
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token from django.utils.translation import ugettext_lazy as _ from comm.utils.common import json_loads class JSONField(models.TextField): """ defined JSON Field """ description = _("JSON") def get_internal_type(self): return "JSONField" def to_python(self, value): value = super(JSONField, self).to_python(value) return json_loads(value) # Create your models here. class UserProfile(models.Model): """ 扩展user表字段 """ user = models.OneToOneField(User) def __str__(self): return self.user.username def __unicode__(self): return self.user.username class ModelBase(models.Model): """ the model base """ id = models.AutoField(primary_key=True) created_time = models.DateTimeField('创建时间', auto_now_add=True) updated_time = models.DateTimeField('更新时间', auto_now=True) is_valid = models.BooleanField('逻辑删除字段', default=True) class Meta: abstract = True class Category(ModelBase): """ 博客分类 """ name = models.CharField('名称', max_length=50) def __unicode__(self): return self.name __str__ = __unicode__ class Tag(ModelBase): """ 标签 """ name = models.CharField(max_length=30) def __unicode__(self): return self.name __str__ = __unicode__ class Blog(ModelBase): """ 博文 """ STATUS_DRAFT = 1 STATUS_PUBLISH = 2 STATUS_OFFLINE = 3 STATUS_TEXT = { STATUS_DRAFT: '草稿箱', STATUS_PUBLISH: '发布中', STATUS_OFFLINE: '已下线' } title = models.CharField(verbose_name='标题', max_length=80) author = models.CharField(verbose_name='作者', max_length=32) content = models.TextField(verbose_name='博客正文') categories = models.ManyToManyField(Category, verbose_name='分类') tags = models.ManyToManyField(Tag, verbose_name='标签') status = models.SmallIntegerField(verbose_name='状态', default=STATUS_PUBLISH) commentable = models.BooleanField(verbose_name='可评论', default=True) summary = models.CharField(verbose_name='文章摘要', max_length=2048, null=True) visitors = models.BigIntegerField(verbose_name='访问量', default=0) class Meta: ordering = ('-created_time', ) def __unicode__(self): return self.title __str__ = __unicode__ class Comment(ModelBase): """ 评论 """ blog = models.ForeignKey(Blog, verbose_name='博客', related_name="comments") name = models.CharField(verbose_name='称呼', max_length=64) email = models.EmailField(verbose_name='邮箱') comment = models.ForeignKey(u'self', related_name=u'comments', verbose_name='评论的评论', null=True) content = models.CharField('内容', max_length=480) class Meta: ordering = ('-id', ) verbose_name = '评论' verbose_name_plural = '评论' def __unicode__(self): return self.content __str__ = __unicode__ @receiver(post_save, sender=User) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.get_or_create(user=instance)
[ "huangqiang1363@outlooktlook.com" ]
huangqiang1363@outlooktlook.com
b37c7369aca8f5f50c6d95de5bc3431d254cf30f
d0fc402348cc87cf378336a2e4173cd9eede3c9b
/std_generator/data_helper.py
761bad756f0aad0b95b0ebd660b46c603fd4468c
[]
no_license
dominthomas/gpu_farm
154ef37003a6692b3f6a8157975f222b8560b2b3
67f5e1326e7d5579004f4acc1d31c66b19615f6b
refs/heads/master
2021-02-09T04:51:11.028799
2020-04-19T14:44:10
2020-04-19T14:44:10
244,241,602
0
0
null
null
null
null
UTF-8
Python
false
false
2,079
py
import nibabel import numpy as np from tensorflow import keras as K class DataGenerator(K.utils.Sequence): def __init__(self, list_IDs, labels, batch_size=5, dim=(176, 256, 256), n_channels=1, n_classes=10, shuffle=True): """Initialization""" self.dim = dim self.batch_size = batch_size self.labels = labels self.list_IDs = list_IDs self.n_channels = n_channels self.n_classes = n_classes self.shuffle = shuffle self.on_epoch_end() def on_epoch_end(self): 'Updates indexes after each epoch' self.indexes = np.arange(len(self.list_IDs)) if self.shuffle: np.random.shuffle(self.indexes) def __data_generation(self, list_IDs_temp): """Generates data containing batch_size samples""" # X : (n_samples, *dim, n_channels) # Initialization X = np.empty((self.batch_size, *self.dim, self.n_channels)) y = np.empty(self.batch_size, dtype=int) # Generate data for i, ID in enumerate(list_IDs_temp): # Store sample nifti = np.asarray(nibabel.load(ID).get_fdata()) xs, ys, zs = np.where(nifti != 0) nifti = nifti[min(xs):max(xs) + 1, min(ys):max(ys) + 1, min(zs):max(zs) + 1] nifti = nifti[0:100, 0:100, 0:100] X[i,] = np.reshape(nifti, (100, 100, 100, 1)) # Store class y[i] = self.labels[ID] return X, K.utils.to_categorical(y, num_classes=self.n_classes) def __len__(self): """Denotes the number of batches per epoch""" return int(np.floor(len(self.list_IDs) / self.batch_size)) def __getitem__(self, index): """Generate one batch of data""" # Generate indexes of the batch indexes = self.indexes[index * self.batch_size:(index + 1) * self.batch_size] # Find list of IDs list_IDs_temp = [self.list_IDs[k] for k in indexes] # Generate data X, y = self.__data_generation(list_IDs_temp) return X, y
[ "dthomas@donbibi.localdomain" ]
dthomas@donbibi.localdomain
7274d5d6acd06026bb0e3945cca73daf74e06bf3
4e163aa4aa0f4c4ddc22f74ae21b6fb1c85a7a09
/134.加油站.py
2f5d07a462e88ceb77dbdc591efd179e9402385b
[]
no_license
dxc19951001/Everyday_LeetCode
72f46a0ec2fc651168129720ad0b1e7b5c372b0b
3f7b2ea959308eb80f4c65be35aaeed666570f80
refs/heads/master
2023-08-03T09:22:08.467100
2023-07-23T17:08:27
2023-07-23T17:08:27
270,723,436
1
0
null
null
null
null
UTF-8
Python
false
false
1,093
py
# coding=utf-8 """ @project: Everyday_LeetCode @Author:Charles @file: 134.加油站.py @date:2023/1/10 15:35 """ class Solution(object): def canCompleteCircuit(self, gas, cost): """ :type gas: List[int] :type cost: List[int] :rtype: int """ # 贪心算法 # 1.如果sum(gas) < sum(cost),说明加油满足不了消耗,所以无法跑完一圈 # 2.为了跑完一圈,则再前往一个加油站时要有油 # 所以cur_sum += gas[i] - cost[i],必须一直为正数 # 若出现负数则表示无法跑到下一个加油站 # 题目说明有唯一的解,所以当cur_sum一直大于0的起始点,就为出发点 if sum(gas) < sum(cost): return -1 start = 0 cur_sum = 0 for i in range(len(gas)): print(gas[i] - cost[i]) cur_sum += gas[i] - cost[i] print("cur sun", cur_sum) if cur_sum < 0: cur_sum = 0 start = i + 1 return start
[ "870200615@qq.com" ]
870200615@qq.com
2c32504fb46d86aea756f86f1695781efe8a8e17
0966c0630bb3d9824e11c986a825d3bf32af9ab3
/ex032.py
42897da311e5dee5c53bd4ce621e09692548294c
[]
no_license
Jacksonleste/exercicios-python-curso-em-video
b5995216b5cc61dbbd6fdd2ebc87ec40673eb2ac
aad364e440e315df9cd1a1ca661c7d15d07704de
refs/heads/main
2023-04-10T13:52:44.254157
2021-04-13T03:13:51
2021-04-13T03:13:51
328,409,343
0
0
null
null
null
null
UTF-8
Python
false
false
375
py
from datetime import datetime ano = int(input('\033[30;1mInsira um ano qualquer para verificar se ele é bissexto:(coloque 0 para o ano atual)')) if ano == 0: ano = datetime.now().year if ano%4 == 0 and ano%400 == 0 or ano%100 ==0: print('\033[34m{}\033[30m é um ano bissexto.'.format(ano)) else: print('\033[34m{}\033[30m não é um ano bissexto.'.format(ano))
[ "jacksongoncalves.leste@gmail.com" ]
jacksongoncalves.leste@gmail.com
c57d4e1cdaa74d2a4820707c049cc11363c0b70c
2597c0487ce5b7a388df2e5c377721c139a1acd8
/bin/python/comparison.py
1fc37db8d81e9b0967940e802c66faaf4f806885
[]
no_license
cilesiz/fluffy-octo-system
8ca5b46fb2bad0ad9599be24eaeb8b01c3cb06f0
8d6e7d32d7a07c4e68dfb154d3460a9ca55726c3
refs/heads/master
2020-03-20T02:58:02.157506
2015-12-27T06:02:32
2015-12-27T06:02:32
null
0
0
null
null
null
null
UTF-8
Python
false
false
114
py
#!/usr/bin/env python message = "new string" message2 = "new string" if message == message2: print "they match"
[ "rossof@icloud.com" ]
rossof@icloud.com
0ce3f3e0f988af4b88d92db58c8ad975c29f0f93
795d0debe9a09d47c95ebcd0b32534f8b5d3c0b5
/TheBeginning/py_basics_assignments/42.py
a3b25830c3c1502679eb8884d7949e86ff6073ba
[]
no_license
Binovizer/Python-Beginning
db8afb2362369a7ca2f098af6e021551dee960b5
f8ee01355e859264269389a0de90f700b0052904
refs/heads/master
2020-05-26T15:24:18.378884
2017-05-07T13:51:35
2017-05-07T13:51:35
82,492,211
0
0
null
null
null
null
UTF-8
Python
false
false
211
py
def rev(string1): if(len(string1) == 0 or len(string1) == 1): return string1 else: return rev(string1[1:]) + string1[0] string1 = input("Enter any string : ") print(rev(string1))
[ "mohd.nadeem3464@gmail.com" ]
mohd.nadeem3464@gmail.com
5fd5f69280f7e2c8dfa60b2c1d5a770471cc61ab
163bbb4e0920dedd5941e3edfb2d8706ba75627d
/Code/CodeRecords/2520/60790/274856.py
18e4e0a2884251d28a2c4c3bc79d6f4d2f5ba4c8
[]
no_license
AdamZhouSE/pythonHomework
a25c120b03a158d60aaa9fdc5fb203b1bb377a19
ffc5606817a666aa6241cfab27364326f5c066ff
refs/heads/master
2022-11-24T08:05:22.122011
2020-07-28T16:21:24
2020-07-28T16:21:24
259,576,640
2
1
null
null
null
null
UTF-8
Python
false
false
168
py
R=int(input()) C=int(input()) r0=int(input()) c0=int(input()) print(sorted([[i, j] for i in range(R) for j in range(C)], key=lambda x: abs(x[0] - r0) + abs(x[1] - c0)))
[ "1069583789@qq.com" ]
1069583789@qq.com
35227700b56937c04f644617981a3abdf9158a9c
11c096d0ce9d9145dddf857d513b7539c65962bf
/MarchingSquares_lights.py
6a27bc94010b595e7f8a968acc82f53f27d71ead
[]
no_license
JessieThomson/CodeSamples
a93322d3a68de602ae5f612cfad67939969ec077
ecd131a318b3f063f2eb34acd22c213fe4fc7952
refs/heads/master
2022-03-27T07:47:06.033354
2019-12-20T10:09:10
2019-12-20T10:09:10
109,897,459
0
0
null
null
null
null
UTF-8
Python
false
false
4,544
py
import pygame, sys, time, random from pygame.locals import * import numpy as np class Particle: """ @summary: Data class to store particle details i.e. Position, Direction and speed of movement, radius, etc """ def __init__(self): self.__version = 0 """@type: int""" self.__position = [] # Sub dicts of the whole vertexMarkupDict self.__movement = [] self.__radius = 0 # Python overrides ------------------------------------------------------------------------------------------------- def __str__(self): printStr = '' printStr += 'Position: (' + str(self.__position[0]) + ',' + str(self.__position[1]) + ') ' printStr += 'Direction and Speed: (' + str(self.__movement[0]) + ',' + str(self.__movement[1]) + ') ' printStr += 'Radius: ' + str(self.__radius) return printStr def __setitem__(self, position, movement, rad, c): print position, movement, rad # TODO: Check inputs self.__position = position self.__movement = movement self.__radius = rad # Properties ------------------------------------------------------------------------------------------------------- @property def Position(self): return self.__position @property def Movement(self): return self.__movement @property def Radius(self): return self.__radius # Methods ---------------------------------------------------------------------------------------------------------- def SetPosition(self, pos): self.__position = pos def SetMovement(self, move): self.__movement = move def SetRadius(self, rad): self.__radius = rad def CalculateGrid(screenWidth, screenHeight, resolution): x_size = resolution + divmod(screenWidth, resolution)[1] y_size = resolution + divmod(screenHeight, resolution)[1] print x_size, y_size grid = [] for y in range(0, y_size): temp_list = [] for x in range(0, x_size): temp_list += [[x * (screenWidth / x_size), y * (screenHeight / y_size)]] grid += [temp_list] print np.array(grid).shape return grid pygame.init() windowSurface = pygame.display.set_mode((500, 400), 0, 32) pygame.display.set_caption("Paint") # get screen size info = pygame.display.Info() sw = info.current_w sh = info.current_h grid = CalculateGrid(sw, sh, 50) # NEED TO CALCULATE OCCUPIED VALUE FOR ALL GRID CELLS!!!!!!!!!!!!!!!! y_size = len(grid[:]) x_size = len(grid[0]) cell_size_x = sw / x_size cell_size_y = sh / y_size print x_size, y_size # for celly in range(0, y_size): # for cellx in range(0, x_size): # print grid[celly][cellx][0] max_dx = 5 max_dy = 5 min_radius = 15 max_radius = 60 circle_objs = [] num_circles = 10 for i in range(0, num_circles): p = Particle() p.SetRadius(random.randrange(min_radius, max_radius)) p.SetPosition([random.randrange(p.Radius, sw - p.Radius), random.randrange(p.Radius, sh - p.Radius)]) p.SetMovement([random.random() * max_dx + 1, random.random() * max_dy + 1]) circle_objs += [p] BLACK = (0, 0, 0) GREEN = (0, 255, 0) windowSurface.fill(BLACK) while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() windowSurface.fill(BLACK) for particle in circle_objs: dx = particle.Movement[0] dy = particle.Movement[1] radius = particle.Radius # update position with direction particle.SetPosition([particle.Position[0] + dx, particle.Position[1] + dy]) pos = particle.Position # check bounds if (pos[0] - radius) + dx < 0 or (pos[0] + radius) + dx > sw: dx = -dx particle.SetMovement([dx, dy]) if (pos[1] - radius) + dy < 0 or (pos[1] + radius) + dy > sh: dy = -dy particle.SetMovement([dx, dy]) # pygame.draw.circle(windowSurface, GREEN, (int(pos[0]), int(pos[1])), radius, 1) for cellx in range(0, x_size): for celly in range(0, y_size): sum_cell = 0 for p in circle_objs: sum_cell += pow(p.Radius, 2) / (pow((grid[celly][cellx][0]) - p.Position[0], 2) + pow((grid[celly][cellx][1]) - p.Position[1], 2)) if sum_cell > 1: pygame.draw.rect(windowSurface, GREEN, [grid[celly][cellx][0], grid[celly][cellx][1], 3, 3], 0) pygame.time.Clock().tick(20) pygame.display.update()
[ "JessieThomson@me.com" ]
JessieThomson@me.com
f38e52cda7f5a3f771a65f7eeb92d6375981bb4a
f25440c9f9fd470ba44394a36d5659dd47ee8800
/tests/conftest.py
6ee0b688b6b226162706d75c8e1acd7eadcb3541
[]
no_license
kqf/hubmap
75010d9109f8b8656e244179de5de226be584d5b
37b3d839f0ad3f47dc39c1b9b036cb1acc27ca2c
refs/heads/master
2023-02-20T04:06:00.145932
2021-01-23T07:56:13
2021-01-23T07:56:13
317,635,257
0
0
null
null
null
null
UTF-8
Python
false
false
552
py
import pytest import tempfile from pathlib import Path from models.preprocess import write from models.mc import make_blob, blob2image @pytest.fixture def size(): return 256 @pytest.fixture def fake_dataset(size=256, nfiles=5): with tempfile.TemporaryDirectory() as dirname: path = Path(dirname) for i in range(nfiles): mask = make_blob(size, size) write(mask, path / str(i) / "mask.png") tile = blob2image(mask) write(tile, path / str(i) / "tile.png") yield path
[ "noreply@github.com" ]
noreply@github.com
42f478e01f3ca3ec68d1abb1a1fbf7bba99fdb5e
9647e44409b261f823ceccce79b4ec34ea3a9bd6
/timeapp/__init__.py
e2d04bb17d4cbbe39ae8da13fd276aa0441176e2
[ "MIT" ]
permissive
iskenderunlu/jogging-time-management
a7cbaf37fd6678571608b7d9277655f7fcc3e136
1cf88bee2abe1f237a2e6f194264064ec89d6e4a
refs/heads/master
2022-11-28T22:12:12.948328
2020-08-19T11:31:25
2020-08-19T11:31:25
288,540,160
0
0
null
null
null
null
UTF-8
Python
false
false
90
py
## write according to your app name here default_app_config = 'Timeapp.apps.TimeappConfig'
[ "iskenderunlu804@gmail.com" ]
iskenderunlu804@gmail.com
bfe6d113c6248860931cd8d1870126fdd8a59693
2194b6c17f3153c5976d6ac4a9ab78211027adab
/otoroshi_admin_api_client/models/otoroshimodels_rs_algo_settings.py
d3bb0d40170f95f52921aa7d6749dcfb1d4114f7
[]
no_license
krezreb/otoroshi-admin-api-client
7fab5e873c9c5950d77fffce6bcf80d3fdf4c319
9b3156c11eac227024cfe4a26c0129618deb2c4d
refs/heads/master
2023-05-08T08:32:00.982987
2021-05-27T09:55:00
2021-05-27T09:55:00
371,324,636
0
0
null
null
null
null
UTF-8
Python
false
false
3,732
py
from typing import Any, Dict, List, Type, TypeVar, Union, cast import attr from ..models.null import Null from ..models.otoroshimodels_rs_algo_settings_type import OtoroshimodelsRSAlgoSettingsType from ..types import UNSET, Unset T = TypeVar("T", bound="OtoroshimodelsRSAlgoSettings") @attr.s(auto_attribs=True) class OtoroshimodelsRSAlgoSettings: """Settings to use RSA signing algorithm""" private_key: Union[Null, Unset, str] = UNSET size: Union[Unset, int] = UNSET public_key: Union[Unset, str] = UNSET type: Union[Unset, OtoroshimodelsRSAlgoSettingsType] = UNSET additional_properties: Dict[str, Any] = attr.ib(init=False, factory=dict) def to_dict(self) -> Dict[str, Any]: private_key: Union[Dict[str, Any], Unset, str] if isinstance(self.private_key, Unset): private_key = UNSET elif isinstance(self.private_key, Null): private_key = UNSET if not isinstance(self.private_key, Unset): private_key = self.private_key.to_dict() else: private_key = self.private_key size = self.size public_key = self.public_key type: Union[Unset, str] = UNSET if not isinstance(self.type, Unset): type = self.type.value field_dict: Dict[str, Any] = {} field_dict.update(self.additional_properties) field_dict.update({}) if private_key is not UNSET: field_dict["privateKey"] = private_key if size is not UNSET: field_dict["size"] = size if public_key is not UNSET: field_dict["publicKey"] = public_key if type is not UNSET: field_dict["type"] = type return field_dict @classmethod def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: d = src_dict.copy() def _parse_private_key(data: object) -> Union[Null, Unset, str]: if isinstance(data, Unset): return data try: if not isinstance(data, dict): raise TypeError() _private_key_type_0 = data private_key_type_0: Union[Unset, Null] if isinstance(_private_key_type_0, Unset): private_key_type_0 = UNSET else: private_key_type_0 = Null.from_dict(_private_key_type_0) return private_key_type_0 except: # noqa: E722 pass return cast(Union[Null, Unset, str], data) private_key = _parse_private_key(d.pop("privateKey", UNSET)) size = d.pop("size", UNSET) public_key = d.pop("publicKey", UNSET) _type = d.pop("type", UNSET) type: Union[Unset, OtoroshimodelsRSAlgoSettingsType] if isinstance(_type, Unset): type = UNSET else: type = OtoroshimodelsRSAlgoSettingsType(_type) otoroshimodels_rs_algo_settings = cls( private_key=private_key, size=size, public_key=public_key, type=type, ) otoroshimodels_rs_algo_settings.additional_properties = d return otoroshimodels_rs_algo_settings @property def additional_keys(self) -> List[str]: return list(self.additional_properties.keys()) def __getitem__(self, key: str) -> Any: return self.additional_properties[key] def __setitem__(self, key: str, value: Any) -> None: self.additional_properties[key] = value def __delitem__(self, key: str) -> None: del self.additional_properties[key] def __contains__(self, key: str) -> bool: return key in self.additional_properties
[ "josephbeeson@gmail.com" ]
josephbeeson@gmail.com
32fe115b47214dd5d925bc1419747dfcf52e0871
150d9e4cee92be00251625b7f9ff231cc8306e9f
/NextGreaterElement.py
eba1f8d0ae08308ff8e272cffeec6304822d027f
[]
no_license
JerinPaulS/Python-Programs
0d3724ce277794be597104d9e8f8becb67282cb0
d0778178d89d39a93ddb9b95ca18706554eb7655
refs/heads/master
2022-05-12T02:18:12.599648
2022-04-20T18:02:15
2022-04-20T18:02:15
216,547,245
0
0
null
null
null
null
UTF-8
Python
false
false
4,114
py
''' 496. Next Greater Element I The next greater element of some element x in an array is the first greater element that is to the right of x in the same array. You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2. For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2. If there is no next greater element, then the answer for this query is -1. Return an array ans of length nums1.length such that ans[i] is the next greater element as described above. Example 1: Input: nums1 = [4,1,2], nums2 = [1,3,4,2] Output: [-1,3,-1] Explanation: The next greater element for each value of nums1 is as follows: - 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1. - 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3. - 2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1. Example 2: Input: nums1 = [2,4], nums2 = [1,2,3,4] Output: [3,-1] Explanation: The next greater element for each value of nums1 is as follows: - 2 is underlined in nums2 = [1,2,3,4]. The next greater element is 3. - 4 is underlined in nums2 = [1,2,3,4]. There is no next greater element, so the answer is -1. Constraints: 1 <= nums1.length <= nums2.length <= 1000 0 <= nums1[i], nums2[i] <= 104 All integers in nums1 and nums2 are unique. All the integers of nums1 also appear in nums2. Follow up: Could you find an O(nums1.length + nums2.length) solution? ''' class Solution(object): def nextGreaterElement(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ next_great = {} stack = [] result = [] for val in nums2: while len(stack) > 0 and stack[len(stack) - 1] < val: next_great[stack.pop()] = val stack.append(val) print next_great for val in nums1: if next_great.has_key(val): result.append(next_great[val]) else: result.append(-1) return result obj = Solution() print(obj.nextGreaterElement([4,1,2],[1,3,4,8,7,6,5,10,2])) print(obj.nextGreaterElement([137,59,92,122,52,131,79,236,94,171,141,86,169,199,248,120,196,168,77,71,5,198,215,230,176,87,189,206,115,76,13,216,197,26,183,54,250,27,109,140,147,25,96,105,30,207,241,8,217,40,0,35,221,191,83,132,9,144,12,91,175,65,170,149,174,82,102,167,62,70,44,143,10,153,160,142,188,81,146,212,15,162,103,163,123,48,245,116,192,14,211,126,63,180,88,155,224,148,134,158,119,165,130,112,166,93,125,1,11,208,150,100,106,194,124,2,184,75,113,104,18,210,202,111,84,223,173,238,41,33,154,47,244,232,249,60,164,227,253,56,157,99,179,6,203,110,127,152,252,55,185,73,67,219,22,156,118,234,37,193,90,187,181,23,220,72,255,58,204,7,107,239,42,139,159,95,45,242,145,172,209,121,24,21,218,246,49,46,243,178,64,161,117,20,214,17,114,69,182,85,229,32,129,29,226,136,39,36,233,43,240,254,57,251,78,51,195,98,205,108,61,66,16,213,19,68,237,190,3,200,133,80,177,97,74,138,38,235,135,186,89,201,4,101,151,31,228,231,34,225,28,222,128,53,50,247], [137,59,92,122,52,131,79,236,94,171,141,86,169,199,248,120,196,168,77,71,5,198,215,230,176,87,189,206,115,76,13,216,197,26,183,54,250,27,109,140,147,25,96,105,30,207,241,8,217,40,0,35,221,191,83,132,9,144,12,91,175,65,170,149,174,82,102,167,62,70,44,143,10,153,160,142,188,81,146,212,15,162,103,163,123,48,245,116,192,14,211,126,63,180,88,155,224,148,134,158,119,165,130,112,166,93,125,1,11,208,150,100,106,194,124,2,184,75,113,104,18,210,202,111,84,223,173,238,41,33,154,47,244,232,249,60,164,227,253,56,157,99,179,6,203,110,127,152,252,55,185,73,67,219,22,156,118,234,37,193,90,187,181,23,220,72,255,58,204,7,107,239,42,139,159,95,45,242,145,172,209,121,24,21,218,246,49,46,243,178,64,161,117,20,214,17,114,69,182,85,229,32,129,29,226,136,39,36,233,43,240,254,57,251,78,51,195,98,205,108,61,66,16,213,19,68,237,190,3,200,133,80,177,97,74,138,38,235,135,186,89,201,4,101,151,31,228,231,34,225,28,222,128,53,50,247]))
[ "jerinsprograms@gmail.com" ]
jerinsprograms@gmail.com