blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
616
content_id
stringlengths
40
40
detected_licenses
listlengths
0
69
license_type
stringclasses
2 values
repo_name
stringlengths
5
118
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
63
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
2.91k
686M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
220 values
src_encoding
stringclasses
30 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
2
10.3M
extension
stringclasses
257 values
content
stringlengths
2
10.3M
authors
listlengths
1
1
author_id
stringlengths
0
212
f245a2875e0e0e125ad75acf12d16ca8f3246ea2
7fe37d93195229dd7e3d3daeaa5f0343459cc27e
/blogs/migrations/0004_auto_20180611_0749.py
e027019fe0349f662de0a0bad249e57349ac3b11
[]
no_license
jrba0001/Wordplease_django
d4416688a2439401d3b4843c9d1efc9eb4202f58
e8a022022141e4ec431ee6d899282a06d280e98d
refs/heads/master
2020-03-22T13:17:08.949254
2018-07-07T15:49:00
2018-07-07T15:49:00
135,888,722
0
0
null
null
null
null
UTF-8
Python
false
false
407
py
# Generated by Django 2.0.6 on 2018-06-11 07:49 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blogs', '0003_auto_20180610_2056'), ] operations = [ migrations.AlterField( model_name='blog', name='imagen', field=models.ImageField(blank=True, null=True, upload_to='./'), ), ]
[ "jrba0001@gmail.com" ]
jrba0001@gmail.com
e10d1553d2755affe6bf4b991461cc4e95568bda
c5332a1203d523842b3a1e5ee8a9e1dc28f843c2
/PDT/PDT/PDT/settings.py
5da25fef5857ee5a274053e51528c4dc1a6cbf72
[ "Apache-2.0" ]
permissive
mimanshagupta/PDT
c363b298302121c9e10333d168dbb52373a30dd3
14b95c71630b731cc9f5875c804c7505acae8bfe
refs/heads/master
2021-01-10T06:39:21.618552
2015-11-30T12:47:57
2015-11-30T12:47:57
46,543,656
1
3
null
2015-11-30T12:47:57
2015-11-20T06:22:06
Python
UTF-8
Python
false
false
5,302
py
""" Django settings for PDT project. """ from os import path PROJECT_ROOT = path.dirname(path.abspath(path.dirname(__file__))) DEBUG = True TEMPLATE_DEBUG = DEBUG ALLOWED_HOSTS = ( 'localhost', ) ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': path.join(PROJECT_ROOT, 'db.sqlite3'), 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } LOGIN_URL = '/login' # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # On Unix systems, a value of None will cause Django to use the same # timezone as the operating system. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale. USE_L10N = True # If you set this to False, Django will not use timezone-aware datetimes. USE_TZ = True # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = '' # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = path.join(PROJECT_ROOT, 'static').replace('\\', '/') # URL prefix for static files. # Example: "http://media.lawrence.com/static/" STATIC_URL = '/static/' # Additional locations of static files STATICFILES_DIRS = ( # Put strings here, like "/home/html/static" or "C:/www/django/static". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # Make this unique, and don't share it with anybody. SECRET_KEY = 'n(bd1f1c%e8=_xad02x5qtfn%wgwpi492e$8_erx+d)!tpeoim' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', # Uncomment the next line for simple clickjacking protection: # 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'PDT.urls' # Python dotted path to the WSGI application used by Django's runserver. WSGI_APPLICATION = 'PDT.wsgi.application' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or # "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'app', # Uncomment the next line to enable the admin: # 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', ) # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error when DEBUG=False. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } } # Specify the default test runner. TEST_RUNNER = 'django.test.runner.DiscoverRunner'
[ "mimansha_gupta@hotmail.com" ]
mimansha_gupta@hotmail.com
8544f9a4d96ac62953d4f6973fe2d5be7e4d9845
7b2e08a4c262b7a67149edaae495d5036b553d95
/pyrk/neutronics.py
a7126aef8ba9e8b9d4f138aab3be6c71a46cefda
[]
no_license
archphy/pyrk
9ffaba557b3d9871fd4e86393b6af1f58e4f8e93
9d3a8fa504e5d66f23371578923ed8f887a5a6c9
refs/heads/master
2021-01-17T21:30:02.274139
2015-08-25T19:07:47
2015-08-25T19:07:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,468
py
# Licensed under a 3-clause BSD-style license import numpy as np from inp import validation as v from data import precursors as pr from data import decay_heat as dh from reactivity_insertion import ReactivityInsertion from timer import Timer class Neutronics(object): """This class handles calculations and data related to the neutronics subblock """ def __init__(self, iso="u235", e="thermal", n_precursors=6, n_decay=11, timer=Timer(), rho_ext=None, feedback=False): """ Creates a Neutronics object that holds the neutronics simulation information. :param iso: The fissioning isotope. 'u235' or 'pu239' are supported. :type iso: str. :param e: The energy spectrum 'thermal' or 'fast' are supported. :type e: str. :param n_precursors: Number of neutron precursor groups. 6 is supported. :type n_precursors: int. :param n_decay: The number of decay heat groups. 11 is supported. :type n_decay: int. :param rho_ext: External reactivity, a function of time :type rho_ext: function :returns: A Neutronics object that holds neutronics simulation info """ self._iso = v.validate_supported("iso", iso, ['u235', 'pu239', 'sfr']) """_iso (str): Fissioning isotope. 'u235', 'pu239', or 'sfr' are supported.""" self._e = v.validate_supported("e", e, ['thermal', 'fast']) """_e (str): Energy spectrum 'thermal' or 'fast' are supported.""" self._npg = v.validate_supported("n_precursors", n_precursors, [6, 0]) """_npg (int): Number of neutron precursor groups. 6 is supported.""" self._ndg = v.validate_supported("n_decay", n_decay, [11, 0]) """_ndg (int): Number of decay heat groups. 11 is supported.""" self._pd = pr.PrecursorData(iso, e, n_precursors) """_pd (PrecursorData): A data.precursors.PrecursorData object""" self._dd = dh.DecayData(iso, e, n_decay) """_dd (DecayData): A data.decay_heat.DecayData object""" self._timer = timer """_timer: the time instance object""" self._rho = np.zeros(self._timer.timesteps()) """_rho (ndarray): An array of reactivity values for each timestep.""" self._rho_ext = self.init_rho_ext(rho_ext).reactivity """_rho_ext (ReactivityInsertion): Reactivity function from the reactivity insertion model""" self.feedback = feedback """feedback (bool): False if no reactivity feedbacks, true otherwise""" def init_rho_ext(self, rho_ext): if rho_ext is None: rho_ext = ReactivityInsertion(self._timer) return rho_ext def dpdt(self, t_idx, components, power, zetas): """Calculates the power term. The first in the neutronics block. :param t: the time :type t: float. :param dt: the timestep :type dt: float. :param components: the THComponents making up this reactor :type components: list of THComponent objects :param power: the current reactor power in Watts (timestep t-1 ?) :type power: float. :param zetas: the current delayed neutron precursor populations, zeta_i :type zetas: np.ndarray. """ rho = self.reactivity(t_idx, components) beta = self._pd.beta() lams = self._pd.lambdas() Lambda = self._pd.Lambda() precursors = 0 for j in range(0, len(lams)): precursors += lams[j]*zetas[j] dp = power*(rho - beta)/Lambda + precursors return dp def dzetadt(self, t, power, zeta, j): """ :param t: time :type t: float, units of seconds :param power: the reactor power at this timestep :type power: float, in units of watts :param zeta: $\zeta_j$, the concentration for precursor group j :type zeta: float #TODO units? :param j: the precursor group index :type j: int """ Lambda = self._pd.Lambda() lambda_j = self._pd.lambdas()[j] beta_j = self._pd.betas()[j] return beta_j*power/Lambda - lambda_j*zeta def dwdt(self, power, omega, k): """Returns the change in decay heat for $\omega_k$ at a certain power :param power: the reactor power at this timestep :type power: float, in units of watts :param omega: $\omega_k$ for fission product decay heat group k :type omega: float, in units of watts #TODO check :param k: the fission product decay heat group index :type k: int """ kappa = self._dd.kappas()[k] p = power lam = self._dd.lambdas()[k] return kappa*p-lam*omega def reactivity(self, t_idx, components): """Returns the reactivity, in $\Delta k$, at time t :param t: time :type t: float, units of seconds :param dt: timestep size, units of seconds :type dt: float, units of seconds :param components: thermal hydraulic component objects :type components: list of THComponent objects """ rho = {} if self.feedback: for component in components: rho[component.name] = component.temp_reactivity() rho["external"] = self._rho_ext(t_idx=t_idx).to('delta_k') to_ret = sum(rho.values()).magnitude self._rho[t_idx] = to_ret return to_ret
[ "katyhuff@gmail.com" ]
katyhuff@gmail.com
321383aac6ddb384a5de4743a8d8fba4a11a44cc
a6d36a861c156e9dd9c3f4733978f194bcc62c2c
/api/serializers.py
b284259aa9cd0eee350124e29334949953db0bd5
[]
no_license
wjaccck/upfile
091f3ba132748cef348ff8a9973eba009e5423fa
2721cc29ca394ddcf9f415e4fba7e2b422e87701
refs/heads/master
2021-01-01T04:30:18.024584
2016-05-26T02:25:51
2016-05-26T02:25:51
57,368,745
0
0
null
null
null
null
UTF-8
Python
false
false
1,960
py
from rest_framework import serializers from api.models import Up_file,Status,Azure_key,Dirs,Recode_dirs class Up_fileSerializer(serializers.ModelSerializer): status = serializers.SlugRelatedField(queryset=Status.objects.all(), slug_field='alias') base_dir = serializers.SlugRelatedField(queryset=Dirs.objects.all(), slug_field='name') class Meta: model = Up_file fields = ('url', 'id', 'base_dir','blob_name', 'blob_url','file_name', 'file_md5', 'file_location', 'department','status', 'modified_date', 'created_date') class StatusSerializer(serializers.ModelSerializer): class Meta: model = Status class Azure_keySerializer(serializers.ModelSerializer): class Meta: model = Azure_key class DirsSerializer(serializers.ModelSerializer): class Meta: model = Dirs class Recode_dirsSerializer(serializers.ModelSerializer): base_dir=serializers.SlugRelatedField(queryset=Dirs.objects.all(), slug_field='name') sub_dir = serializers.SlugRelatedField(queryset=Dirs.objects.all(), slug_field='name',many=True) sub_files=serializers.SerializerMethodField() class Meta: model = Recode_dirs fields = ('url', 'id', 'base_dir', 'sub_dir', 'sub_files') def get_sub_files(self,obj): base_dir=obj.base_dir result=[] for m in Up_file.objects.filter(base_dir=base_dir): status = m.status.alias if status == 'upload': sig = Azure_key.objects.get(name='azure').sig url = m.blob_url + '?' + sig else: url = '' data = {} data['status'] = status data['file'] = m.file_name data['url'] = url data['created_date']=m.created_date data['department']=m.department result.append(data) total={"total":len(result)} result.append(total) return result
[ "wjaccck@163.com" ]
wjaccck@163.com
dc85f4e57771b9a1113c5e7258faa1ad077c74af
2b8c88dfee5c5a784357515eafe8cd5f997c8774
/learnexception.py
f1dc92b31c5498dbe9fc76f140297c7e83727968
[]
no_license
archenRen/learnpy
e060f3aa2f77c35fc1b12345720af6c8b528da57
934ef76b97297f746a722a48c76672c7bc744cd9
refs/heads/master
2022-04-28T20:25:59.114036
2020-05-03T02:16:03
2020-05-03T02:16:14
null
0
0
null
null
null
null
UTF-8
Python
false
false
701
py
# -*- coding: utf-8 -*- try: print('start...') r = 10 / int('2') print('result', r) except ValueError as e: print('ValueError:', e) except ZeroDivisionError as e: print('ZeroDivisionError', e) else: print('No Error!') finally: print('finally...') print('End') # %% # err_logging.py import logging def foo(s): return 10 / int(s) def bar(s): return foo(s) * 2 def main(): try: bar('0') except Exception as e: logging.exception(e) main() print('END') # %% # err_raise.py class FooError(ValueError): pass def foo(s): n = int(s) if n == 0: raise FooError('invalid value: %s' % s) return 10 / n foo('0')
[ "757441884@qq.com" ]
757441884@qq.com
aefeeca82a58f3cbbf93ff7aa83f226bd40a75fd
6812eee0806e41398fab185f7a08453d07678bbf
/method/greedy_algorithms/greedy_algorithm.py
334ce0c21d9d64a8fc8cb67c20a9a482481b6285
[]
no_license
Waynehfut/MatrixFactorization
4769d30fbf00f5221dbffc20bb255f604d1d5473
866e55b31334a0af06ca546d8890e2bffe32c16b
refs/heads/master
2022-12-10T12:42:03.008513
2020-09-13T12:06:27
2020-09-13T12:06:27
295,142,906
2
0
null
null
null
null
UTF-8
Python
false
false
3,989
py
# -*- coding: utf-8 -*- """ Created on 2018/1/24 21:55 @file: greedy_algorithms.py @author: Administrator """ from __future__ import division import random def greedy_one(ls_sort,doc_info,doc_id_dict,hos_type_sum,sim_matrix,r,k): """ 贪心算法一,返回一维数组,包含doc_info对应的index :param ls_sort:[index...] :param doc_info: :param sim_matrix:相识度矩阵 :param r: 阈值 :param k: 取前k个医生 :return: [index,...,index] """ length = len(ls_sort) #记录的是doc_info 对应的index doc_recommend = [] #先添加第一个,第二个 doc_recommend.append(ls_sort[0]) doc_recommend.append(ls_sort[1]) i = 2 hos_sum = len(hos_type_sum) while i < length: prefore_diversity = single_diversity(doc_recommend,sim_matrix,doc_id_dict,doc_info,hos_sum) doc_recommend.append(ls_sort[i]) present_diversity = single_diversity(doc_recommend,sim_matrix,doc_id_dict,doc_info,hos_sum) #添加条件 if (present_diversity-prefore_diversity)> r: pass else: doc_recommend.pop(len(doc_recommend)-1) if len(doc_recommend) == k: break return doc_recommend def greedy_two(ls_sort,doc_info,doc_id_dict,hos_type_sum,sim_matrix,r,k): """ 置换算法二,返回一维数组,包含doc_info对应的index :param ls_sort: [index...] :param doc_info: :param doc_id_dict: :param hos_type_sum: :param sim_matrix: :param r: 阈值 :param k: 取前k个医生 :return: """ recommend_list = ls_sort[:k] ls_sort_copy = list(ls_sort[k:]) hos_sum = len(hos_type_sum) #判断是否连续达到平稳状态,即多样性的数值达到稳定 steady_time = 0 while len(ls_sort_copy) != 0 or steady_time < 4: prefore_diversity = single_diversity(recommend_list,sim_matrix,doc_id_dict,doc_info,hos_sum) random_num = random.randint(0, k) origin_index = recommend_list[random_num] recommend_list[random_num] = ls_sort_copy[0] present_diversity = single_diversity(recommend_list,sim_matrix,doc_id_dict,doc_info,hos_sum) #置换条件 if (present_diversity-prefore_diversity)> r: recommend_list[random_num] = origin_index steady_time += 1 else: steady_time = 0 pass ls_sort_copy.pop(0) return recommend_list def single_diversity(doc_recommend,sim_matrix,doc_id_dict,doc_info,hos_sum): """ 计算单个个体推荐的多样性 :param doc_recommend: :param sim_matrix: 相似度矩阵 :param doc_info: 医生信息 :return: """ temp = sort_by_matrix(doc_recommend,doc_id_dict,doc_info) c = z_score(temp,sim_matrix)*cover_rate(doc_recommend,doc_info,hos_sum) diversity = pow(c,0.5) return diversity def sort_by_matrix(doc_recommend,doc_id_dict,doc_info): """ 将doc_recommend中的index与sim_matrix中的对应起来 :param doc_recommend:[index...] :param doc_id_dict:{"doc_id":id} :param doc_info: :return:[index_id] """ temp = [] for doc in doc_recommend: temp.append(doc_id_dict[doc_info[doc][0]]) return temp def z_score(temp,sim_matrix): """ 返回列表的z-score的值 :param temp: [index...],与sim_matrix中相对应 :param sim_matrix:相识度矩阵 :return: """ sum = 0 for i in temp: for j in temp: if i < j: sum += sim_matrix[i][j] else: break k = len(temp) result = 1-2*sum/(k*(k-1)) return result def cover_rate(doc_recommend,doc_info,hos_type_sum): """ 返回医院覆盖率 :param doc_recommend:[index...] :param doc_info: :param hos_type_sum:医院总数 :return: """ d = set() for doc in doc_recommend: d.add(doc_info[doc]) result = len(d)/hos_type_sum return result
[ "waynehfut@outlook.com" ]
waynehfut@outlook.com
d4c1a1417f9103be588075550d6bf1d2ad0c858a
bad74e9f2a5c4af80077d926a1f2a43d2d0f63e5
/mai.py
2249041a4d94b7bd7ab3b450c323c1504985d65c
[]
no_license
Namemai/m
6e1036094717c708884d5ab2ffebeaf11bf5177f
f405a6cd05cff69407fa61d41dd992ac53f3f35b
refs/heads/master
2020-03-20T18:30:43.327684
2019-03-29T14:10:44
2019-03-29T14:10:44
137,591,499
6
8
null
null
null
null
UTF-8
Python
false
false
124,836
py
# -*- coding: utf-8 -*- from gyevha import * from datetime import datetime from time import sleep from bs4 import BeautifulSoup from humanfriendly import format_timespan, format_size, format_number, format_length import time, random, sys, json, codecs, threading, glob, re, string, os, requests, subprocess, six, ast, pytz, urllib, urllib.parse from gtts import gTTS from googletrans import Translator # Ini Untuk Login Via Lik Dan Via Emal #gye = LINE() #gye = LINE("Email","Password") #gye.log("Auth Token : " + str(gye.authToken)) #channelToken = gye.getChannelResult() #gye.log("Channel Token : " + str(channelToken)) # Silahkan Edit Sesukamu # Asalkan Rapih Dan Respon # jika ingin login Via qr Ganti Saja # Atau Login Via Emal # Mudeng Orang kalo Ra Mudeng # Sungguh Terlalu # Jangan Lupa Add Admin # id Line ( aisyagye ) #==============================================================================# botStart = time.time() #kalo mau login code qr disini pake gye = LINE() gye.log("Auth Token : " + str(gye.authToken)) channelToken = gye.getChannelResult() gye.log("Channel Token : " + str(channelToken)) ais = LINE() ais.log("Auth Token : " + str(ais.authToken)) channelToken = ais.getChannelResult() ais.log("Channel Token : " + str(channelToken)) ki2 = LINE() ki2.log("Auth Token : " + str(ki2.authToken)) channelToken = ki2.getChannelResult() ki2.log("Channel Token : " + str(channelToken)) ki3 = LINE() ki3.log("Auth Token : " + str(ki3.authToken)) channelToken = ki3.getChannelResult() ki3.log("Channel Token : " + str(channelToken)) ki4 = LINE() ki4.log("Auth Token : " + str(gye.authToken)) channelToken = ki4.getChannelResult() ki4.log("Channel Token : " + str(channelToken)) ki5 = LINE() ki5.log("Auth Token : " + str(gye.authToken)) channelToken = ki5.getChannelResult() ki5.log("Channel Token : " + str(channelToken)) ki6 = LINE() ki6.log("Auth Token : " + str(gye.authToken)) channelToken = ki6.getChannelResult() ki6.log("Channel Token : " + str(channelToken)) #kalo mau login menggunakan token #gunakan disini hapus tanda pagarnya #yg atas dinpagar atau bisa juga token di atas #di dalam tanda LINE ("TOKEN MU ") #gye = LINE("Et6qM8UeTce5bGsZG4te.ee6vQU/1ppqr93nt9QLUZG.b5fsCbuxW7zZRtrK5U/74k/53Abd5dWPxfdtLy9bL9I=") #ais = LINE("Etska0dbjsHvPgZKwmj9.EikS5M3O+L4fOqxjjVgLsq.KlWfvmGVaXdM0yvKM8WGKARpcbAbiKVF9yORPt8QBJw=") #ki2 = LINE("EtQsqzdJMWn73m72Gup0.OdjJmVnqXLeaZxpJzxDMOa.Z+6ApCht+0H1NeyX50QMD0Yq8oIhYyJ14Yg2yoM/tfc=") #ki3 = LINE("EtDOOeYj4Rvl5PVfOEaa.ETpCu8czFapUIJQDqIA82G.tcOaI+VmHhWwMbyDL/7yXupWfdIvUJh80yWzu/UJXp8=") #ki4 = LINE("EtWyu42OHWKSaxPHY3yd.jTri3xzV4E2Z1xvWxjTrRq.s1oy5gbYMT2haZV7l6yzV0bp5gONcnu+bGSSJ1mbT0c=") KAC = [gye,ais,ki2,ki3,ki4,ki5,ki6] GUE = [ais,ki2,ki3,ki4,ki5,ki6] # ini jangan luh hapus peak ini fungsi Ciak alias kick #maksudnya agar bot sb/induk gak ikutan nge kick Mudeng ora gyeMID = gye.profile.mid aisMID = ais.profile.mid ki2MID = ki2.profile.mid ki3MID = ki3.profile.mid ki4MID = ki4.profile.mid ki5MID = ki5.profile.mid ki6MID = ki6.profile.mid Bots = [gyeMID,aisMID,ki2MID,ki3MID,ki4MID,ki5MID,ki6MID] #ini jangan dinrubah Gunanya agar bot tidak saling kick creator = ["u104e95aaefb53cf411f77353f6a96ece"] Owner = ["u104e95aaefb53cf411f77353f6a96ece"] admin = ["u104e95aaefb53cf411f77353f6a96ece"] gyeProfile = gye.getProfile() aisProfile = ais.getProfile() ki2Profile = ki2.getProfile() ki2Profile = ki3.getProfile() ki2Profile = ki4.getProfile() ki2Profile = ki5.getProfile() ki2Profile = ki6.getProfile() lineSettings = gye.getSettings() aisSettings = ais.getSettings() ki2Settings = ki2.getSettings() ki3Settings = ki3.getSettings() ki4Settings = ki4.getSettings() ki5Settings = ki6.getSettings() ki5Settings = ki6.getSettings() oepoll = OEPoll(gye) oepoll1 = OEPoll(ais) oepoll2 = OEPoll(ki2) oepoll3 = OEPoll(ki3) oepoll4 = OEPoll(ki4) oepoll5 = OEPoll(ki5) oepoll6 = OEPoll(ki6) responsename = gye.getProfile().displayName responsename2 = ais.getProfile().displayName responsename3 = ki2.getProfile().displayName responsename2 = ki3.getProfile().displayName responsename3 = ki4.getProfile().displayName responsename2 = ki5.getProfile().displayName responsename3 = ki6.getProfile().displayName #==============================================================================# with open('Owner.json', 'r') as fp: Owner = json.load(fp) with open('admin.json', 'r') as fp: admin = json.load(fp) myProfile = { "displayName": "", "statusMessage": "", "pictureStatus": "" } myProfile["displayName"] = gyeProfile.displayName myProfile["statusMessage"] = gyeProfile.statusMessage myProfile["pictureStatus"] = gyeProfile.pictureStatus readOpen = codecs.open("read.json","r","utf-8") settingsOpen = codecs.open("temp.json","r","utf-8") #==============================================================================# read = json.load(readOpen) settings = json.load(settingsOpen) def restartBot(): print ("[ INFO ] BOT RESETTED") backupData() python = sys.executable os.execl(python, python, *sys.argv) def logError(text): gye.log("[ ERROR ] " + str(text)) time_ = datetime.now() with open("errorLog.txt","a") as error: error.write("\n[%s] %s" % (str(time), text)) def sendMessageWithMention(to, mid): try: aa = '{"S":"0","E":"3","M":'+json.dumps(mid)+'}' text_ = '@x ' gye.sendMessage(to, text_, contentMetadata={'MENTION':'{"MENTIONEES":['+aa+']}'}, contentType=0) except Exception as error: logError(error) def helpmessage(): helpMessage = " Help1" + "\n" + \ "╭════════╬♥╬════════╮" + "\n" + \ "║͜͡☆➣ Help1 " + "\n" + \ "║͜͡☆➣ Help2 " + "\n" + \ "║͜͡☆➣ Help3 " + "\n" + \ "╰════════╬♥╬════════╯" + "\n" + \ "╭════════╬♥╬════════╮" + "\n" + \ "║͜͡☆➣ แทค (แทคทั้งห้อง)" + "\n" + \ "║͜͡☆➣ เข้ามา. ( สั่งบอทเข้าห้อง ) " + "\n" + \ "║͜͡☆➣ ออก. (สั่งบอทออก) " + "\n" + \ "║͜͡☆➣ บาย.(ออกหมดทั้งคนทั้งบอท) " + "\n" + \ "║͜͡☆➣ เตะ @ (สั่งบอทเตะออก)" + "\n" + \ "║͜͡☆➣ เตะดึง @ (สั่งบอทเตะออก)" + "\n" + \ "║͜͡☆➣ คท " + "\n" + \ "║͜͡☆➣ Sp " + "\n" + \ "║͜͡☆➣ เชคค่า " + "\n" + \ "║͜͡☆➣ บอท " + "\n" + \ "║͜͡☆➣ รีบอท " + "\n" + \ "║͜͡☆➣ พูด (ใส่ข้อคาม)" + "\n" + \ "║͜͡☆➣ เขียน (ใส่ข้อคาม)" + "\n" + \ "║͜͡☆➣ เรา " + "\n" + \ "║͜͡☆➣ รายชื่อคนในห้อง " + "\n" + \ "║͜͡☆➣ เชคบอท " + "\n" + \ "╰════════╬♥╬════════╯" + "\n" + \ "╭════════╬♥╬════════╮" + "\n" + \ "║͜͡☆➣ Maibotline " + "\n" + \ "╰════════╬♥╬════════╯" return helpMessage def helptexttospeech(): helpTextToSpeech = " Help2 " + "\n" + \ "╭════════╬♥╬════════╮" + "\n" + \ "║͜͡☆➣ Pro on/off" + "\n" + \ "║͜͡☆➣ Pt on/off" + "\n" + \ "║͜͡☆➣ Qr on/off" + "\n" + \ "║͜͡☆➣ Iv on/off" + "\n" + \ "║͜͡☆➣ Cc on/off" + "\n" + \ "║͜͡☆➣ Add on/off" + "\n" + \ "║͜͡☆➣ Join on/off" + "\n" + \ "║͜͡☆➣ Leave on/off" + "\n" + \ "║͜͡☆➣ Sticker on/off" + "\n" + \ "║͜͡☆➣ Read on/off" + "\n" + \ "║͜͡☆➣ Dm on/off" + "\n" + \ "║͜͡☆➣ link on/off" + "\n" + \ "╰════════╬♥╬════════╯" + "\n" + \ "╭════════╬♥╬════════╮" + "\n" + \ "║͜͡☆➣ คนสร้างห้อง" + "\n" + \ "║͜͡☆➣ ไอดีห้อง" + "\n" + \ "║͜͡☆➣ ชื่อห้อง" + "\n" + \ "║͜͡☆➣ รายชื่อห้อง" + "\n" + \ "║͜͡☆➣ เชคห้อง" + "\n" + \ "║͜͡☆➣ ลิ้งห้อง" + "\n" + \ "║͜͡☆➣ #เปิดลิ้ง" + "\n" + \ "║͜͡☆➣ #ปิดลิ้ง" + "\n" + \ "║͜͡☆➣ พิมตาม on/off " + "\n" + \ "║͜͡☆➣ รายชื่อพิมตาม " + "\n" + \ "║͜͡☆➣ เพิ่มพิมตาม" + "\n" + \ "║͜͡☆➣ ลบพิมตาม" + "\n" + \ "║͜͡☆➣ เปิดอ่าน " + "\n" + \ "║͜͡☆➣ ปิดอ่าน " + "\n" + \ "║͜͡☆➣ ลบเวลาอ่าน " + "\n" + \ "║͜͡☆➣ คนอ่าน" + "\n" + \ "╰════════╬♥╬════════╯" + "\n" + \ "╭════════╬♥╬════════╮" + "\n" + \ "║͜͡☆➣ Maibotline " + "\n" + \ "╰════════╬♥╬════════╯" return helpTextToSpeech def helptranslate(): helpTranslate = " Help3 " + "\n" + \ "╭════════╬♥╬════════╮" + "\n" + \ "║͜͡☆➣ แบน(ลงคอนแทคที่จะแบน)" + "\n" + \ "║͜͡☆➣ เชคแบน" + "\n" + \ "║͜͡☆➣ ล้างแบน" + "\n" + \ "║͜͡☆➣ รีบอท" + "\n" + \ "║͜͡☆➣ บอท " + "\n" + \ "║͜͡☆➣ มี " + "\n" + \ "║͜͡☆➣ มิด" + "\n" + \ "║͜͡☆➣ มิด @" + "\n" + \ "║͜͡☆➣ ชื่อ" + "\n" + \ "║͜͡☆➣ ตัส" + "\n" + \ "║͜͡☆➣ รูป" + "\n" + \ "║͜͡☆➣ รูปวีดีโอ" + "\n" + \ "║͜͡☆➣ รูปปก" + "\n" + \ "║͜͡☆➣ คท @" + "\n" + \ "║͜͡☆➣ มิด @" + "\n" + \ "║͜͡☆➣ ชื่อ @「Mention」" + "\n" + \ "║͜͡☆➣ ตัส @" + "\n" + \ "║͜͡☆➣ รูป @" + "\n" + \ "║͜͡☆➣ รูปวีดีโอ @" + "\n" + \ "║͜͡☆➣ รูปปก @" + "\n" + \ "║͜͡☆➣ คนสร้างห้อง" + "\n" + \ "║͜͡☆➣ ไอดีห้อง" + "\n" + \ "║͜͡☆➣ ชื่อห้อง" + "\n" + \ "║͜͡☆➣ รูปห้อง" + "\n" + \ "║͜͡☆➣ ลิ้งห้อง" + "\n" + \ "║͜͡☆➣ #เปิดลิ้ง" + "\n" + \ "║͜͡☆➣ รายชื่อห้อง" + "\n" + \ "║͜͡☆➣ #ปิดลิ้ง" + "\n" + \ "║͜͡☆➣ เชคห้อง" + "\n" + \ "║͜͡☆➣ เตะ @" + "\n" + \ "╰════════╬♥╬════════╯" + "\n" + \ "╭════════╬♥╬════════╮" + "\n" + \ "║͜͡☆➣ Maibotline " + "\n" + \ "╰════════╬♥╬════════╯" return helpTranslate #==============================================================================# def backupData(): try: backup = settings f = codecs.open('temp.json','w','utf-8') json.dump(backup, f, sort_keys=True, indent=4, ensure_ascii=False) backup = read f = codecs.open('read.json','w','utf-8') json.dump(backup, f, sort_keys=True, indent=4, ensure_ascii=False) return True except Exception as error: logError(error) return False def command(text): pesan = text.lower() if pesan.startswith(settings["keyCommand"]): cmd = pesan.replace(settings["keyCommand"],"") else: cmd = "Undefined command" return cmd def lineBot(op): try: if op.type == 0: print ("[ 0 ] GYEVHA BOTS SATU") return #------------------------------------------------------------------------------- if op.type == 25: msg = op.message if msg.contentType == 13: if settings["wblack"] == True: if msg.contentMetadata["mid"] in settings["commentBlack"]: gye.sendMessage(msg.to,"sudah masuk daftar hitam") settings["wblack"] = False else: settings["commentBlack"][msg.contentMetadata["mid"]] = True settings["wblack"] = False gye.sendMessage(msg.to,"Itu tidak berkomentar") elif settings["dblack"] == True: if msg.contentMetadata["mid"] in settings["commentBlack"]: del settings["commentBlack"][msg.contentMetadata["mid"]] gye.sendMessage(msg.to,"Done") settings["dblack"] = False else: settings["dblack"] = False gye.sendMessage(msg.to,"Tidak ada dalam daftar hitam") #------------------------------------------------------------------------------- elif settings["wblacklist"] == True: if msg.contentMetadata["mid"] in settings["blacklist"]: gye.sendMessage(msg.to,"sudah masuk daftar hitam") settings["wblacklist"] = False else: settings["blacklist"][msg.contentMetadata["mid"]] = True settings["wblacklist"] = False gye.sendMessage(msg.to,"Done") elif settings["dblacklist"] == True: if msg.contentMetadata["mid"] in settings["blacklist"]: del settings["blacklist"][msg.contentMetadata["mid"]] gye.sendMessage(msg.to,"Done") settings["dblacklist"] = False else: settings["dblacklist"] = False gye.sendMessage(msg.to,"Done") #------------------------------------------------------------------------------- if op.type == 25: print ("[ 25 ] GYEVHA BOTS TIGA") msg = op.message text = msg.text msg_id = msg.id receiver = msg.to sender = msg._from if msg.toType == 0: if sender != gye.profile.mid: to = sender else: to = receiver else: to = receiver if msg.contentType == 0: if text is None: return #==============================================================================# if text.lower() == 'h1': helpMessage = helpmessage() gye.sendMessage(to, str(helpMessage)) gye.sendContact(to,) gye.sendMessage(to,) elif text.lower() == 'h2': helpTextToSpeech = helptexttospeech() gye.sendMessage(to, str(helpTextToSpeech)) gye.sendMessage(to,) elif text.lower() == 'h3': helpTranslate = helptranslate() gye.sendMessage(to, str(helpTranslate)) gye.sendMessage(to,) #==============================================================================# elif text.lower() == 'sp': start = time.time() gye.sendMessage(to, "Cek Speed...") elapsed_time = time.time() - start gye.sendMessage(to,format(str(elapsed_time))) elif text.lower() == 'รีบอท': gye.sendMessage(to, "Please Wait...") time.sleep(5) gye.sendMessage(to, "Restart Sukses") restartBot() elif text.lower() == 'ออน': timeNow = time.time() runtime = timeNow - botStart runtime = format_timespan(runtime) gye.sendMessage(to, "login bot selama {}".format(str(runtime))) elif text.lower() == 'เรา': try: arr = [] owner = "u104e95aaefb53cf411f77353f6a96ece" creator = gye.getContact(owner) contact = gye.getContact(gyeMID) grouplist = gye.getGroupIdsJoined() contactlist = gye.getAllContactIds() blockedlist = gye.getBlockedContactIds() ret_ = "╭════════╬♥╬════════╮\n" ret_ += "\n╠ akun : {}".format(contact.displayName) ret_ += "\n╠ group : {}".format(str(len(grouplist))) ret_ += "\n╠ teman : {}".format(str(len(contactlist))) ret_ += "\n╠ Blokir : {}".format(str(len(blockedlist))) ret_ += "\n╠══[ About Selfbot ]" ret_ += "\n╠ Version : Premium" ret_ += "\n╰════════╬♥╬════════╯\n" gye.sendMessage(to, str(ret_)) except Exception as e: gye.sendMessage(msg.to, str(e)) #==============================================================================# elif text.lower() == 'เชคค่า': try: ret_ = "♥ Status Bots ♥\n ╭════════╬♥╬════════╮\n" if settings["protect"] == True: ret_ += "║͜͡☆➣ Protect ✅" else: ret_ += "║͜͡☆➣ Protect ❌" if settings["qrprotect"] == True: ret_ += "\n║͜͡☆➣ Qr Protect ✅" else: ret_ += "\n║͜͡☆➣ Qr Protect ❌" if settings["inviteprotect"] == True: ret_ += "\n║͜͡☆➣ Invite Protect ✅" else: ret_ += "\n║͜͡☆➣ Invite Protect ❌" if settings["cancelprotect"] == True: ret_ += "\n║͜͡☆➣ Cancel Protect ✅" else: ret_ += "\n║͜͡☆➣ Cancel Protect ❌" if settings["autoAdd"] == True: ret_ += "\n║͜͡☆➣ Auto Add ✅" else: ret_ += "\n║͜͡☆➣ Auto Add ❌" if settings["autoJoin"] == True: ret_ += "\n║͜͡☆➣ Auto Join ✅" else: ret_ += "\n║͜͡☆➣ Auto Join ❌" if settings["autoLeave"] == True: ret_ += "\n║͜͡☆➣ Auto Leave ✅" else: ret_ += "\n║͜͡☆➣ Auto Leave ❌" if settings["autoRead"] == True: ret_ += "\n║͜͡☆➣ Auto Read ✅" else: ret_ += "\n║͜͡☆➣ Auto Read ❌" if settings["checkSticker"] == True: ret_ += "\n║͜͡☆➣ Check Sticker ✅" else: ret_ += "\n║͜͡☆➣ Check Sticker ❌" if settings["detectMention"] == True: ret_ += "\n║͜͡☆➣ Detect Mention ✅" else: ret_ += "\n║͜͡☆➣ Detect Mention ❌" ret_ += "\n╰════════╬♥╬════════╯\n" gye.sendMessage(to, str(ret_)) except Exception as e: gye.sendMessage(msg.to, str(e)) elif msg.text.lower().startswith("spaminvite "): #if msg._from in admin: dan = text.split("|") userid = dan[0] namagrup = dan[0] jumlah = int(dan[0]) grups = gye.groups tgb = gye.findContactsByUserid(userid) if jumlah <= 10000000: for var in range(0,jumlah): try: gye.createGroup(str(namagrup), [tgb.mid]) for i in grups: grup = gye.getGroup(i) if grup.name == namagrup: gye.inviteIntoGroup(grup.id, [tgb.mid]) gye.sendMessage(to, "@! sukses spam grup!\n\nkorban: @!\njumlah: {}\nnama grup: {}".format(jumlah, str(namagrup)), [sender, tgb.mid]) except Exception as Nigga: gye.sendMessage(to, str(Nigga)) #else: gye.sendMessage(to, "@! kebanyakan njer!!", [sender]) #------------------------------------------------------------------------------- elif msg.text.lower().startswith("owneradd "): key = eval(msg.contentMetadata["MENTION"]) key["MENTIONEES"][0]["M"] targets = [] for x in key["MENTIONEES"]: targets.append(x["M"]) for target in targets: try: Owner[target] = True f=codecs.open('Owner.json','w','utf-8') json.dump(Owner, f, sort_keys=True, indent=4,ensure_ascii=False) gye.sendMessage(msg.to,"Owner ☢-Bot-☢\nAdd\nExecuted") except: pass elif msg.text.lower().startswith("ownerdel "): key = eval(msg.contentMetadata["MENTION"]) key["MENTIONEES"][0]["M"] targets = [] for x in key["MENTIONEES"]: targets.append(x["M"]) for target in targets: try: del Owner[target] f=codecs.open('Owner.json','w','utf-8') json.dump(Owner, f, sort_keys=True, indent=4,ensure_ascii=False) gye.sendMessage(msg.to,"Owner ☢-Bot-☢\nRemove\nExecuted") except: pass #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- elif text.lower() == 'pt on': if settings["protect"] == True: if settings["lang"] == "JP": gye.sendMessage(msg.to,"➲ Protection Already On") else: settings["protect"] = True if settings["lang"] == "JP": gye.sendMessage(msg.to,"➲ Protection Set To On") elif text.lower() == 'pt off': if settings["protect"] == False: if settings["lang"] == "JP": gye.sendMessage(msg.to,"➲ Protection Already Off") else: settings["protect"] = False if settings["lang"] == "JP": gye.sendMessage(msg.to,"➲ Protection Set To Off") #---------------------------------------------------------------------------------------- elif text.lower() == 'qr on': if settings["qrprotect"] == True: if settings["lang"] == "JP": gye.sendMessage(msg.to,"➲ Protection Qr Already On") else: gye.sendMessage(msg.to,"➲ Protection Qr Set To On") else: settings["qrprotect"] = True if settings["lang"] == "JP": gye.sendMessage(msg.to,"➲ Protection Qr Set To On") else: gye.sendMessage(msg.to,"➲ Protection Qr Already On") elif text.lower() == 'qr off': if settings["qrprotect"] == False: if settings["lang"] == "JP": gye.sendMessage(msg.to,"➲ Protection Qr Already Off") else: gye.sendMessage(msg.to,"➲ Protection Qr Set To Off") else: settings["qrprotect"] = False if settings["lang"] == "JP": gye.sendMessage(msg.to,"➲ Protection Qr Set To Off") else: gye.sendMessage(msg.to,"➲ Protection Qr Already Off") #------------------------------------------------------------------------------- elif text.lower() == 'iv on': if settings["inviteprotect"] == True: if settings["lang"] == "JP": gye.sendMessage(msg.to,"➲ Protection Invite Already On") else: gye.sendMessage(msg.to,"➲ Protection Invite Set To On") else: settings["inviteprotect"] = True if settings["lang"] == "JP": gye.sendMessage(msg.to,"➲ Protection Invite Set To On") else: gye.sendMessage(msg.to,"➲ Protection Invite Already On") elif text.lower() == 'iv off': if settings["inviteprotect"] == False: if settings["lang"] == "JP": gye.sendMessage(msg.to,"➲ Protection Invite Already Off") else: gye.sendMessage(msg.to,"➲ Protection Invite Set To Off") else: settings["inviteprotect"] = False if settings["lang"] == "JP": gye.sendMessage(msg.to,"➲ Protection Invite Set To Off") else: gye.sendMessage(msg.to,"➲ Protection Invite Already Off") #------------------------------------------------------------------------------- elif text.lower() == 'cc on': if settings["cancelprotect"] == True: if settings["lang"] == "JP": gye.sendMessage(msg.to,"➲ Protection Cancel Invite Already On") else: gye.sendMessage(msg.to,"➲ Protection Cancel Invite Set To On") else: settings["cancelprotect"] = True if settings["lang"] == "JP": gye.sendMessage(msg.to,"➲ Protection Cancel Invite Set To On") else: gye.sendMessage(msg.to,"➲ Protection Cancel Invite Already On") elif text.lower() == 'cc off': if settings["cancelprotect"] == False: if settings["lang"] == "JP": gye.sendMessage(msg.to,"➲ Protection Cancel Invite Already Off") else: gye.sendMessage(msg.to,"➲ Protection Cancel Invite Set To Off") else: settings["cancelprotect"] = False if settings["lang"] == "JP": gye.sendMessage(msg.to,"➲ Protection Cancel Invite Set To Off") else: gye.sendMessage(msg.to,"➲ Protection Cancel Invite Already Off") #------------------------------------------------------------------------------- elif text.lower() == 'pro on': settings["protect"] = True settings["qrprotect"] = True settings["inviteprotect"] = True settings["cancelprotect"] = True settings["join link"] = True gye.sendMessage(msg.to,"Join link on") gye.sendMessage(msg.to,"Qrprotect on") gye.sendMessage(msg.to,"Protect on") gye.sendMessage(msg.to,"Inviteprotect on") gye.sendMessage(msg.to,"Cancelprotect on") gye.sendMessage(msg.to,"➲ เปิดระบบป้องกันทั้งหมดแล้วครับเจ้านาย") elif text.lower() == 'pro off': # if msg._from in Owner: settings["protect"] = False settings["qrprotect"] = False settings["inviteprotect"] = False settings["cancelprotect"] = False gye.sendMessage(msg.to,"Qrprotect Off") gye.sendMessage(msg.to,"Protect Off") gye.sendMessage(msg.to,"Inviteprotect Off") gye.sendMessage(msg.to,"Cancelprotect Off") gye.sendMessage(msg.to,"➲ ปิดระบบป้องกันทั้งหมดแล้วครับเจ้านาย") # else: # gye.sendMessage(msg.to,"Just for Owner") #------------------------------------------------------------------------------- elif text.lower() == 'add on': settings["autoAdd"] = True gye.sendMessage(to, "Berhasil mengaktifkan Auto Add") elif text.lower() == 'add off': settings["autoAdd"] = False gye.sendMessage(to, "Berhasil menonaktifkan Auto Add") elif text.lower() == 'join on': # if msg._from in Owner: settings["autoJoin"] = True gye.sendMessage(to, "Berhasil mengaktifkan Auto Join") elif text.lower() == 'join off': # if msg._from in Owner: settings["autoJoin"] = False gye.sendMessage(to, "Berhasil menonaktifkan Auto Join") elif text.lower() == 'leave on': # if msg._from in Owner: settings["autoLeave"] = True gye.sendMessage(to, "Berhasil mengaktifkan Auto Leave") elif text.lower() == 'leave off': # if msg._from in Owner: settings["autoLeave"] = False gye.sendMessage(to, "Berhasil menonaktifkan Auto Leave") elif text.lower() == 'read on': settings["autoRead"] = True gye.sendMessage(to, "Berhasil mengaktifkan Auto Read") elif text.lower() == 'read off': settings["autoRead"] = False gye.sendMessage(to, "Berhasil menonaktifkan Auto Read") elif text.lower() == 'sticker on': settings["checkSticker"] = True gye.sendMessage(to, "Berhasil mengaktifkan Check Details Sticker") elif text.lower() == 'sticker off': settings["checkSticker"] = False gye.sendMessage(to, "Berhasil menonaktifkan Check Details Sticker") elif text.lower() == 'dm on': settings["datectMention"] = True gye.sendMessage(to, "Berhasil mengaktifkan Detect Mention") elif text.lower() == 'dm off': settings["datectMention"] = False gye.sendMessage(to, "Berhasil menonaktifkan Detect Mention") elif text.lower() == 'link on': settings["autoJoinTicket"] = True gye.sendMessage(to, "Berhasil mengaktifkan Auto Join Link") elif text.lower() == 'link off': settings["autoJoinTicket"] = False gye.sendMessage(to, "Berhasil menonaktifkan Auto Join Link") #==============================================================================# elif msg.text.lower() == 'บอท': gye.sendContact(to, gyeMID) ais.sendContact(to, aisMID) ki2.sendContact(to, ki2MID) ki3.sendContact(to, ki3MID) ki4.sendContact(to, ki4MID) ki5.sendContact(to, ki5MID) ki6.sendContact(to, ki6MID) elif text.lower() in ["ออก."]: #gye.leaveGroup(msg.to) ais.leaveGroup(msg.to) ki2.leaveGroup(msg.to) ki3.leaveGroup(msg.to) ki4.leaveGroup(msg.to) ki5.leaveGroup(msg.to) ki6.leaveGroup(msg.to) elif text.lower() in ["บาย."]: gye.leaveGroup(msg.to) ais.leaveGroup(msg.to) ki2.leaveGroup(msg.to) ki3.leaveGroup(msg.to) ki4.leaveGroup(msg.to) ki5.leaveGroup(msg.to) ki6.leaveGroup(msg.to) elif text.lower() in ["เข้ามา."]: G = gye.getGroup(msg.to) ginfo = gye.getGroup(msg.to) G.preventedJoinByTicket = False gye.updateGroup(G) invsend = 0 Ticket = gye.reissueGroupTicket(msg.to) ais.acceptGroupInvitationByTicket(msg.to,Ticket) ki2.acceptGroupInvitationByTicket(msg.to,Ticket) ki3.acceptGroupInvitationByTicket(msg.to,Ticket) ki4.acceptGroupInvitationByTicket(msg.to,Ticket) ki5.acceptGroupInvitationByTicket(msg.to,Ticket) ki6.acceptGroupInvitationByTicket(msg.to,Ticket) G = gye.getGroup(msg.to) G.preventedJoinByTicket = True gye.updateGroup(G) G.preventedJoinByTicket(G) gye.updateGroup(G) elif text.lower() == 'คท': sendMessageWithMention(to, gyeMID) gye.sendContact(to, gyeMID) elif text.lower() == 'มิด': gye.sendMessage(msg.to,"[MID]\n" + gyeMID) elif text.lower() == 'ชื่ิอ': me = gye.getContact(gyeMID) gye.sendMessage(msg.to,"[DisplayName]\n" + me.displayName) elif text.lower() == 'ตัส': me = gye.getContact(gyeMID) gye.sendMessage(msg.to,"[StatusMessage]\n" + me.statusMessage) elif text.lower() == 'รูป': me = gye.getContact(gyeMID) gye.sendImageWithURL(msg.to,"http://dl.profile.line-cdn.net/" + me.pictureStatus) elif text.lower() == 'รูปวีดีโอ': me = gye.getContact(gyeMID) gye.sendVideoWithURL(msg.to,"http://dl.profile.line-cdn.net/" + me.pictureStatus + "/vp") elif text.lower() == 'รูปปก': me = gye.getContact(gyeMID) cover = gye.getProfileCoverURL(gyeMID) gye.sendImageWithURL(msg.to, cover) elif msg.text.lower().startswith("คท "): if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] lists = [] for mention in mentionees: if mention["M"] not in lists: lists.append(mention["M"]) for ls in lists: contact = gye.getContact(ls) mi_d = contact.mid gye.sendContact(msg.to, mi_d) elif msg.text.lower().startswith("มิด "): if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] lists = [] for mention in mentionees: if mention["M"] not in lists: lists.append(mention["M"]) ret_ = "[ Mid User ]" for ls in lists: ret_ += "\n{}" + ls gye.sendMessage(msg.to, str(ret_)) elif msg.text.lower().startswith("ชื่อ "): if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] lists = [] for mention in mentionees: if mention["M"] not in lists: lists.append(mention["M"]) for ls in lists: contact = gye.getContact(ls) gye.sendMessage(msg.to, "[ Display Name ]\n" + contact.displayName) elif msg.text.lower().startswith("ตัส "): if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] lists = [] for mention in mentionees: if mention["M"] not in lists: lists.append(mention["M"]) for ls in lists: contact = gye.getContact(ls) gye.sendMessage(msg.to, "[ Status Message ]\n{}" + contact.statusMessage) elif msg.text.lower().startswith("รูป "): if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] lists = [] for mention in mentionees: if mention["M"] not in lists: lists.append(mention["M"]) for ls in lists: path = "http://dl.profile.gye.naver.jp/" + gye.getContact(ls).pictureStatus gye.sendImageWithURL(msg.to, str(path)) elif msg.text.lower().startswith("รูปวีดีโอ "): if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] lists = [] for mention in mentionees: if mention["M"] not in lists: lists.append(mention["M"]) for ls in lists: path = "http://dl.profile.gye.naver.jp/" + gye.getContact(ls).pictureStatus + "/vp" gye.sendImageWithURL(msg.to, str(path)) elif msg.text.lower().startswith("รูปปก "): if line != None: if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] lists = [] for mention in mentionees: if mention["M"] not in lists: lists.append(mention["M"]) for ls in lists: path = gye.getProfileCoverURL(ls) gye.sendImageWithURL(msg.to, str(path)) elif msg.text.lower().startswith("cloneprofile "): if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\w+)', text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] for mention in mentionees: contact = mention["M"] break try: gye.cloneContactProfile(contact) gye.sendMessage(msg.to, "Berhasil clone member tunggu beberapa saat sampai profile berubah") except: gye.sendMessage(msg.to, "Gagal clone member") elif text.lower() == 'restoreprofile': try: gyeProfile.displayName = str(myProfile["displayName"]) gyeProfile.statusMessage = str(myProfile["statusMessage"]) gyeProfile.pictureStatus = str(myProfile["pictureStatus"]) gye.updateProfileAttribute(8, gyeProfile.pictureStatus) gye.updateProfile(gyeProfile) gye.sendMessage(msg.to, "Berhasil restore profile tunggu beberapa saat sampai profile berubah") except: gye.sendMessage(msg.to, "Gagal restore profile") #==============================================================================# elif msg.text.lower().startswith("เพิ่มพิมตาม "): targets = [] key = eval(msg.contentMetadata["MENTION"]) key["MENTIONEES"][0]["M"] for x in key["MENTIONEES"]: targets.append(x["M"]) for target in targets: try: settings["mimic"]["target"][target] = True gye.sendMessage(msg.to,"Target ditambahkan!") break except: gye.sendMessage(msg.to,"Added Target Fail !") break elif msg.text.lower().startswith("ลบพิมตาม "): targets = [] key = eval(msg.contentMetadata["MENTION"]) key["MENTIONEES"][0]["M"] for x in key["MENTIONEES"]: targets.append(x["M"]) for target in targets: try: del settings["mimic"]["target"][target] gye.sendMessage(msg.to,"Target dihapuskan!") break except: gye.sendMessage(msg.to,"Deleted Target Fail !") break elif text.lower() == 'รายชื่อพิมตาม': if settings["mimic"]["target"] == {}: gye.sendMessage(msg.to,"Tidak Ada Target") else: mc = "╔══[ Mimic List ]" for mi_d in settings["mimic"]["target"]: mc += "\n╠ "+gye.getContact(mi_d).displayName gye.sendMessage(msg.to,mc + "\n╚══[ Finish ]") elif "พิมตาม" in msg.text.lower(): sep = text.split(" ") mic = text.replace(sep[0] + " ","") if mic == "on": if settings["mimic"]["status"] == False: settings["mimic"]["status"] = True gye.sendMessage(msg.to,"Reply Message on") elif mic == "off": if settings["mimic"]["status"] == True: settings["mimic"]["status"] = False gye.sendMessage(msg.to,"Reply Message off") #==============================================================================# elif msg.text.lower().startswith("พูด "): sep = text.split(" ") say = text.replace(sep[0] + " ","") lang = 'th' tts = gTTS(text=say, lang=lang) tts.save("hasil.mp3") gye.sendAudio(msg.to,"hasil.mp3") elif msg.text.lower().startswith("เขียน "): sep = msg.text.split(" ") textnya = msg.text.replace(sep[0] + " ","") urlnya = "http://chart.apis.google.com/chart?chs=480x80&cht=p3&chtt=" + textnya + "&chts=FFFFFF,70&chf=bg,s,000000" gye.sendImageWithURL(msg.to, urlnya) #==============================================================================# elif text.lower() == 'คนสร้างห้อง': group = gye.getGroup(to) GS = group.creator.mid gye.sendContact(to, GS) elif text.lower() == 'ไอดีห้อง': gid = gye.getGroup(to) gye.sendMessage(to, "[ID Group : ]\n" + gid.id) elif text.lower() == 'grouppicture': group = gye.getGroup(to) path = "http://dl.profile.line-cdn.net/" + group.pictureStatus gye.sendImageWithURL(to, path) elif text.lower() == 'ชื่อห้อง': gid = gye.getGroup(to) gye.sendMessage(to, "[Nama Group : ]\n" + gid.name) elif text.lower() == 'ลิ้งห้อง': if msg.toType == 2: group = gye.getGroup(to) if group.preventedJoinByTicket == False: ticket = gye.reissueGroupTicket(to) gye.sendMessage(to, "[ ลิ้งกลุ่มนี้ครับเจ้านาย ]\nhttps://line.me/R/ti/g/{}".format(str(ticket))) else: gye.sendMessage(to, "Grup qr tidak terbuka silahkan buka terlebih dahulu dengan perintah {}openqr".format(str(settings["keyCommand"]))) elif text.lower() == '#เปิดลิ้ง': if msg.toType == 2: group = gye.getGroup(to) if group.preventedJoinByTicket == False: gye.sendMessage(to, "Grup qr sudah terbuka") else: group.preventedJoinByTicket = False gye.updateGroup(group) gye.sendMessage(to, "เปิดลิ้งห้องให้แล้วครับเจ้านาย") elif text.lower() == '#ปิดลิ้ง': if msg.toType == 2: group = gye.getGroup(to) if group.preventedJoinByTicket == True: gye.sendMessage(to, "ปิดลิ้งห้องให้แล้วครับเจ้านาย") else: group.preventedJoinByTicket = True gye.updateGroup(group) gye.sendMessage(to, "Berhasil menutup grup qr") elif text.lower() == 'เชคห้อง': group = gye.getGroup(to) try: gCreator = group.creator.displayName except: gCreator = "Tidak ditemukan" if group.invitee is None: gPending = "0" else: gPending = str(len(group.invitee)) if group.preventedJoinByTicket == True: gQr = "Tertutup" gTicket = "Tidak ada" else: gQr = "Terbuka" gTicket = "https://line.me/R/ti/g/{}".format(str(gye.reissueGroupTicket(group.id))) path = "http://dl.profile.line-cdn.net/" + group.pictureStatus ret_ = "╔══[ ข้อมูลห้อง ]" ret_ += "\n╠ Nama Group : {}".format(str(group.name)) ret_ += "\n╠ ID Group : {}".format(group.id) ret_ += "\n╠ คนสร้างห้อง : {}".format(str(gCreator)) ret_ += "\n╠ Jumlah Member : {}".format(str(len(group.members))) ret_ += "\n╠ Jumlah Pending : {}".format(gPending) ret_ += "\n╠ Group Qr : {}".format(gQr) ret_ += "\n╠ Group Ticket : {}".format(gTicket) ret_ += "\n╚══[ by,maibotline ]" gye.sendMessage(to, str(ret_)) gye.sendImageWithURL(to,) elif text.lower() == 'รายชื่อคนในห้อง': if msg.toType == 2: group = gye.getGroup(to) ret_ = "╔══[ รายชื่อคนในห้อง ]" no = 0 + 1 for mem in group.members: ret_ += "\n╠ {}. {}".format(str(no), str(mem.displayName)) no += 1 ret_ += "\n╚══[ มี {} คนครับเจ้านาย ]".format(str(len(group.members))) gye.sendMessage(to, str(ret_)) elif text.lower() == 'รายชื่อห้อง': groups = gye.groups ret_ = "╔══[ Group List ]" no = 0 + 1 for gid in groups: group = gye.getGroup(gid) ret_ += "\n╠ {}. {} | {}".format(str(no), str(group.name), str(len(group.members))) no += 1 ret_ += "\n╚══[ Total {} Groups ]".format(str(len(groups))) gye.sendMessage(to, str(ret_)) #------------------------------------------------------------------------------- elif text.lower() == 'ล้างแบน': settings["blacklist"] = {} gye.sendMessage(msg.to,"➲ Done") ais.sendMessage(msg.to,"➲ Done") ki2.sendMessage(msg.to,"➲ Done") ki3.sendMessage(msg.to,"➲ Done") ki4.sendMessage(msg.to,"➲ Done") ki5.sendMessage(msg.to,"➲ Done") ki6.sendMessage(msg.to,"➲ Done") ki6.sendMessage(msg.to,"➲ ล้างหมดแล้วครับเจ้านาย") elif text.lower() == 'เชคบอท': gye.sendMessage(msg.to,"➲ Mai 1 มาครับเจ้านาย") ais.sendMessage(msg.to,"➲ Mai 2 มาครับเจ้านาย") ki2.sendMessage(msg.to,"➲ Mai 3 มาครับเจ้านาย") ki3.sendMessage(msg.to,"➲ Mai 4 มาครับเจ้านาย") ki4.sendMessage(msg.to,"➲ Mai 5 มาครับเจ้านาย") ki5.sendMessage(msg.to,"➲ Mai 6 มาครับเจ้านาย") ki6.sendMessage(msg.to,"➲ Mai 7 มาครับเจ้านาย") ki6.sendMessage(msg.to,"➲ ครบครับเจ้านาย") elif text.lower() == 'แบน': settings["wblacklist"] = True gye.sendMessage(msg.to,"ลง Contact") elif msg.text in ["unbancontact"]: settings["dblacklist"] = True gye.sendMessage(msg.to,"ลง Contact") #------------------------------------------------------------------------------- elif text.lower() == 'เชคแบน': if settings["blacklist"] == {}: gye.sendMessage(msg.to,"Tidak Ada Banlist") else: gye.sendMessage(msg.to,"Daftar Banlist") num=1 msgs="═══T E R S A N G K A═══" for mi_d in settings["blacklist"]: msgs+="\n[%i] %s" % (num, gye.getContact(mi_d).displayName) num=(num+1) msgs+="\n═══T E R S A N G K A═══\n\nTotal Tersangka : %i" % len(settings["blacklist"]) gye.sendMessage(msg.to, msgs) #======================================================================================= elif msg.text.lower().startswith("เตะ "): targets = [] key = eval(msg.contentMetadata["MENTION"]) key["MENTIONEES"][0]["M"] for x in key["MENTIONEES"]: targets.append(x["M"]) for target in targets: try: random.choice(GUE).kickoutFromGroup(msg.to,[target]) except: random.choice(GUE).sendText(msg.to,"Error") elif "เตะดึง " in msg.text: vkick0 = msg.text.replace("เตะดึง ","") vkick1 = vkick0.rstrip() vkick2 = vkick1.replace("@","") vkick3 = vkick2.rstrip() _name = vkick3 gs = gye.getGroup(msg.to) targets = [] for s in gs.members: if _name in s.displayName: targets.append(s.mid) if targets == []: pass else: for target in targets: try: gye.kickoutFromGroup(msg.to,[target]) gye.findAndAddContactsByMid(target) gye. inviteIntoGroup(msg.to,[target]) except: pass #------------------------------------------------------------------------------- elif text.lower() == 'ciak all member': # if msg._from in Owner: if msg.toType == 2: print ("[ 19 ] KICK ALL MEMBER") _name = msg.text.replace("kickallmember","") #gs = gye.getGroup(msg.to) gs = ais.getGroup(msg.to) gs = ki2.getGroup(msg.to) gs = ki3.getGroup(msg.to) gs = ki4.getGroup(msg.to) gs = ki5.getGroup(msg.to) gs = ki6.getGroup(msg.to) #gye.sendMessage(msg.to,"「 Bye All 」") #gye.sendMessage(msg.to,"「 Sory guys 」") targets = [] for g in gs.members: if _name in g.displayName: targets.append(g.mid) if targets == []: gye.sendMessage(msg.to,"Not Found") else: for target in targets: if not target in Bots: if not target in Owner: if not target in admin: try: klist=[line,ais,ki2,ki3,ki4,ki5,ki6] kicker=random.choice(klist) kicker.kickoutFromGroup(msg.to,[target]) print (msg.to,[g.mid]) except: gye.sendMessage(msg.to,"") #==============================================================================# elif text.lower() == 'แทค': group = gye.getGroup(msg.to) nama = [contact.mid for contact in group.members] k = len(nama)//100 for a in range(k+1): txt = u'' s=0 b=[] for i in group.members[a*100 : (a+1)*100]: b.append({"S":str(s), "E" :str(s+6), "M":i.mid}) s += 7 txt += u'@Alin \n' gye.sendMessage(to, text=txt, contentMetadata={u'MENTION': json.dumps({'MENTIONEES':b})}, contentType=0) gye.sendMessage(to, "จำนวลสมาชิกในกลุ่ม {} คนครับเจ้านาย".format(str(len(nama)))) elif text.lower() == 'เปิดอ่าน': tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] hr = timeNow.strftime("%A") bln = timeNow.strftime("%m") for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] readTime = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]" if msg.to in read['readPoint']: try: del read['readPoint'][msg.to] del read['readMember'][msg.to] del read['readTime'][msg.to] except: pass read['readPoint'][msg.to] = msg.id read['readMember'][msg.to] = "" read['readTime'][msg.to] = datetime.now().strftime('%H:%M:%S') read['ROM'][msg.to] = {} with open('read.json', 'w') as fp: json.dump(read, fp, sort_keys=True, indent=4) gye.sendMessage(msg.to,"Lurking already on") else: try: del read['readPoint'][msg.to] del read['readMember'][msg.to] del read['readTime'][msg.to] except: pass read['readPoint'][msg.to] = msg.id read['readMember'][msg.to] = "" read['readTime'][msg.to] = datetime.now().strftime('%H:%M:%S') read['ROM'][msg.to] = {} with open('read.json', 'w') as fp: json.dump(read, fp, sort_keys=True, indent=4) gye.sendMessage(msg.to, "Set reading point:\n" + readTime) gye.sendMessage(msg.to,"➲ Jangan Songong Pake Sc Orang") elif text.lower() == 'ปิดอ่าน': tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] hr = timeNow.strftime("%A") bln = timeNow.strftime("%m") for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] readTime = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]" if msg.to not in read['readPoint']: gye.sendMessage(msg.to,"Lurking already off") else: try: del read['readPoint'][msg.to] del read['readMember'][msg.to] del read['readTime'][msg.to] except: pass gye.sendMessage(msg.to, "Delete reading point:\n" + readTime) elif text.lower() == 'ลบเวลาอ่าน': tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] hr = timeNow.strftime("%A") bln = timeNow.strftime("%m") for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] readTime = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]" if msg.to in read["readPoint"]: try: del read["readPoint"][msg.to] del read["readMember"][msg.to] del read["readTime"][msg.to] except: pass gye.sendMessage(msg.to, "Reset reading point:\n" + readTime) else: gye.sendMessage(msg.to, "Lurking belum diaktifkan ngapain di reset?") elif text.lower() == 'คนอ่าน': tz = pytz.timezone("Asia/Jakarta") timeNow = datetime.now(tz=tz) day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"] hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"] hr = timeNow.strftime("%A") bln = timeNow.strftime("%m") for i in range(len(day)): if hr == day[i]: hasil = hari[i] for k in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] readTime = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]" if receiver in read['readPoint']: if read["ROM"][receiver].items() == []: gye.sendMessage(receiver,"[ Reader ]:\nNone") else: chiya = [] for rom in read["ROM"][receiver].items(): chiya.append(rom[1]) cmem = gye.getContacts(chiya) zx = "" zxc = "" zx2 = [] xpesan = '[ Reader ]:\n' for x in range(len(cmem)): xname = str(cmem[x].displayName) pesan = '' pesan2 = pesan+"@c\n" xlen = str(len(zxc)+len(xpesan)) xlen2 = str(len(zxc)+len(pesan2)+len(xpesan)-1) zx = {'S':xlen, 'E':xlen2, 'M':cmem[x].mid} zx2.append(zx) zxc += pesan2 text = xpesan+ zxc + "\n[ Lurking time ]: \n" + readTime try: gye.sendMessage(receiver, text, contentMetadata={'MENTION':str('{"MENTIONEES":'+json.dumps(zx2).replace(' ','')+'}')}, contentType=0) except Exception as error: print (error) pass else: gye.sendMessage(receiver,"Lurking has not been set.") #===============================================================================[gyeMID - kiMID] if op.type == 19: print ("[ 19 ] GYEVHA BOTS KICK") try: if op.param3 in gyeMID: if op.param2 in aisMID: G = ais.getGroup(op.param1) # ginfo = ki.getGroup(op.param1) G.preventedJoinByTicket = False ais.updateGroup(G) invsend = 0 Ticket = ais.reissueGroupTicket(op.param1) gye.acceptGroupInvitationByTicket(op.param1,Ticket) ais.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = ais.getGroup(op.param1) G.preventedJoinByTicket = True ais.updateGroup(G) G.preventedJoinByTicket(G) ais.updateGroup(G) else: G = ais.getGroup(op.param1) # ginfo = ais.getGroup(op.param1) ais.kickoutFromGroup(op.param1,[op.param2]) G.preventedJoinByTicket = False ais.updateGroup(G) invsend = 0 Ticket = ais.reissueGroupTicket(op.param1) gye.acceptGroupInvitationByTicket(op.param1,Ticket) ais.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = ki.getGroup(op.param1) G.preventedJoinByTicket = True ais.updateGroup(G) G.preventedJoinByTicket(G) ais.updateGroup(G) settings["blacklist"][op.param2] = True #-------------------------------------------------------------------------------[gyeMID - ki2MID] elif op.param3 in gyeMID: if op.param2 in ki2MID: G = ki2.getGroup(op.param1) G.preventedJoinByTicket = False ki2.updateGroup(G) invsend = 0 Ticket = ki2.reissueGroupTicket(op.param1) gye.acceptGroupInvitationByTicket(op.param1,Ticket) ais.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = ki2.getGroup(op.param1) G.preventedJoinByTicket = True ki2.updateGroup(G) G.preventedJoinByTicket(G) ki2.updateGroup(G) else: G = ki2.getGroup(op.param1) ki2.kickoutFromGroup(op.param1,[op.param2]) G.preventedJoinByTicket = False ki2.updateGroup(G) invsend = 0 Ticket = ki2.reissueGroupTicket(op.param1) gye.acceptGroupInvitationByTicket(op.param1,Ticket) ais.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = ki2.getGroup(op.param1) G.preventedJoinByTicket = True ki2.updateGroup(G) G.preventedJoinByTicket(G) ki2.updateGroup(G) settings["blacklist"][op.param2] = True #-------------------------------------------------------------------------------[gyeMID - ki3MID] elif op.param3 in gyeMID: if op.param2 in ki3MID: G = ki3.getGroup(op.param1) G.preventedJoinByTicket = False ki3.updateGroup(G) invsend = 0 Ticket = ki3.reissueGroupTicket(op.param1) gye.acceptGroupInvitationByTicket(op.param1,Ticket) ais.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = ki3.getGroup(op.param1) G.preventedJoinByTicket = True ki3.updateGroup(G) G.preventedJoinByTicket(G) ki3.updateGroup(G) else: G = ki3.getGroup(op.param1) ki3.kickoutFromGroup(op.param1,[op.param2]) G.preventedJoinByTicket = False ki3.updateGroup(G) invsend = 0 Ticket = ki3.reissueGroupTicket(op.param1) gye.acceptGroupInvitationByTicket(op.param1,Ticket) ais.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = ki3.getGroup(op.param1) G.preventedJoinByTicket = True ki3.updateGroup(G) G.preventedJoinByTicket(G) ki3.updateGroup(G) settings["blacklist"][op.param2] = True #-------------------------------------------------------------------------------[gyeMID - ki4MID] elif op.param3 in gyeMID: if op.param2 in ki4MID: G = ki4.getGroup(op.param1) G.preventedJoinByTicket = False ki4.updateGroup(G) invsend = 0 Ticket = ki4.reissueGroupTicket(op.param1) gye.acceptGroupInvitationByTicket(op.param1,Ticket) ki.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = ki4.getGroup(op.param1) G.preventedJoinByTicket = True ki4.updateGroup(G) G.preventedJoinByTicket(G) ki4.updateGroup(G) else: G = ki4.getGroup(op.param1) ki4.kickoutFromGroup(op.param1,[op.param2]) G.preventedJoinByTicket = False ki4.updateGroup(G) invsend = 0 Ticket = ki4.reissueGroupTicket(op.param1) gye.acceptGroupInvitationByTicket(op.param1,Ticket) ais.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = ki4.getGroup(op.param1) G.preventedJoinByTicket = True ki4.updateGroup(G) G.preventedJoinByTicket(G) ki4.updateGroup(G) settings["blacklist"][op.param2] = True #===============================================================================[kiMID gyeMID] if op.param3 in aisMID: if op.param2 in gyeMID: G = gye.getGroup(op.param1) G.preventedJoinByTicket = False gye.updateGroup(G) invsend = 0 Ticket = gye.reissueGroupTicket(op.param1) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ais.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = gye.getGroup(op.param1) G.preventedJoinByTicket = True gye.updateGroup(G) G.preventedJoinByTicket(G) gye.updateGroup(G) else: G = gye.getGroup(op.param1) gye.kickoutFromGroup(op.param1,[op.param2]) G.preventedJoinByTicket = False gye.updateGroup(G) invsend = 0 Ticket = gye.reissueGroupTicket(op.param1) gye.acceptGroupInvitationByTicket(op.param1,Ticket) ais.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = gye.getGroup(op.param1) G.preventedJoinByTicket = True gye.updateGroup(G) G.preventedJoinByTicket(G) gye.updateGroup(G) settings["blacklist"][op.param2] = True #-------------------------------------------------------------------------------[kiMID ki2MID] elif op.param3 in aisMID: if op.param2 in ki2MID: G = ki2.getGroup(op.param1) G.preventedJoinByTicket = False ki2.updateGroup(G) invsend = 0 Ticket = ki2.reissueGroupTicket(op.param1) gye.acceptGroupInvitationByTicket(op.param1,Ticket) ais.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = ki2.getGroup(op.param1) G.preventedJoinByTicket = True ki2.updateGroup(G) G.preventedJoinByTicket(G) ki2.updateGroup(G) else: G = ki2.getGroup(op.param1) # ginfo = ki2.getGroup(op.param1) ki2.kickoutFromGroup(op.param1,[op.param2]) G.preventedJoinByTicket = False ki2.updateGroup(G) invsend = 0 Ticket = ki2.reissueGroupTicket(op.param1) gye.acceptGroupInvitationByTicket(op.param1,Ticket) ais.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = ki2.getGroup(op.param1) G.preventedJoinByTicket = True ki2.updateGroup(G) G.preventedJoinByTicket(G) ki2.updateGroup(G) settings["blacklist"][op.param2] = True #-------------------------------------------------------------------------------[kiMID ki3MID] elif op.param3 in aisMID: if op.param2 in ki3MID: G = ki3.getGroup(op.param1) # ginfo = ki3.getGroup(op.param1) G.preventedJoinByTicket = False ki3.updateGroup(G) invsend = 0 Ticket = ki3.reissueGroupTicket(op.param1) gye.acceptGroupInvitationByTicket(op.param1,Ticket) ki.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = ki3.getGroup(op.param1) G.preventedJoinByTicket = True ki3.updateGroup(G) G.preventedJoinByTicket(G) ki3.updateGroup(G) else: G = ki3.getGroup(op.param1) # ginfo = ki3.getGroup(op.param1) ki3.kickoutFromGroup(op.param1,[op.param2]) G.preventedJoinByTicket = False ki3.updateGroup(G) invsend = 0 Ticket = ki3.reissueGroupTicket(op.param1) gye.acceptGroupInvitationByTicket(op.param1,Ticket) ais.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = ki3.getGroup(op.param1) G.preventedJoinByTicket = True ki3.updateGroup(G) G.preventedJoinByTicket(G) ki3.updateGroup(G) settings["blacklist"][op.param2] = True #-------------------------------------------------------------------------------[kiMID ki4MID] elif op.param3 in aisMID: if op.param2 in ki4MID: G = ki4.getGroup(op.param1) # ginfo = ki4.getGroup(op.param1) G.preventedJoinByTicket = False ki4.updateGroup(G) invsend = 0 Ticket = ki4.reissueGroupTicket(op.param1) gye.acceptGroupInvitationByTicket(op.param1,Ticket) ais.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = ki4.getGroup(op.param1) G.preventedJoinByTicket = True ki4.updateGroup(G) G.preventedJoinByTicket(G) ki4.updateGroup(G) else: G = ki4.getGroup(op.param1) # ginfo = ki4.getGroup(op.param1) ki4.kickoutFromGroup(op.param1,[op.param2]) G.preventedJoinByTicket = False ki4.updateGroup(G) invsend = 0 Ticket = ki4.reissueGroupTicket(op.param1) gye.acceptGroupInvitationByTicket(op.param1,Ticket) ais.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = ki4.getGroup(op.param1) G.preventedJoinByTicket = True ki4.updateGroup(G) G.preventedJoinByTicket(G) ki4.updateGroup(G) settings["blacklist"][op.param2] = True #===============================================================================[ki2MID gyeMID] if op.param3 in ki2MID: if op.param2 in gyeMID: G = gye.getGroup(op.param1) # ginfo = gye.getGroup(op.param1) G.preventedJoinByTicket = False gye.updateGroup(G) invsend = 0 Ticket = gye.reissueGroupTicket(op.param1) gye.acceptGroupInvitationByTicket(op.param1,Ticket) ais.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = gye.getGroup(op.param1) G.preventedJoinByTicket = True gye.updateGroup(G) G.preventedJoinByTicket(G) gye.updateGroup(G) else: G = gye.getGroup(op.param1) # ginfo = gye.getGroup(op.param1) gye.kickoutFromGroup(op.param1,[op.param2]) G.preventedJoinByTicket = False gye.updateGroup(G) invsend = 0 Ticket = gye.reissueGroupTicket(op.param1) gye.acceptGroupInvitationByTicket(op.param1,Ticket) ais.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = gye.getGroup(op.param1) G.preventedJoinByTicket = True gye.updateGroup(G) G.preventedJoinByTicket(G) gye.updateGroup(G) settings["blacklist"][op.param2] = True #-------------------------------------------------------------------------------[ki2MID kiMID] elif op.param3 in ki2MID: if op.param2 in aisMID: G = ais.getGroup(op.param1) # ginfo = ais.getGroup(op.param1) G.preventedJoinByTicket = False ais.updateGroup(G) invsend = 0 Ticket = ais.reissueGroupTicket(op.param1) gye.acceptGroupInvitationByTicket(op.param1,Ticket) ais.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = ais.getGroup(op.param1) G.preventedJoinByTicket = True ais.updateGroup(G) G.preventedJoinByTicket(G) ki.updateGroup(G) else: G = ais.getGroup(op.param1) # ginfo = ki.getGroup(op.param1) ais.kickoutFromGroup(op.param1,[op.param2]) G.preventedJoinByTicket = False ais.updateGroup(G) invsend = 0 Ticket = ki.reissueGroupTicket(op.param1) gye.acceptGroupInvitationByTicket(op.param1,Ticket) ais.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = ais.getGroup(op.param1) G.preventedJoinByTicket = True ais.updateGroup(G) G.preventedJoinByTicket(G) ki.updateGroup(G) settings["blacklist"][op.param2] = True #-------------------------------------------------------------------------------[ki2MID ki3MID] elif op.param3 in ki2MID: if op.param2 in ki3MID: G = ki3.getGroup(op.param1) # ginfo = ki3.getGroup(op.param1) G.preventedJoinByTicket = False ki3.updateGroup(G) invsend = 0 Ticket = ki3.reissueGroupTicket(op.param1) gye.acceptGroupInvitationByTicket(op.param1,Ticket) ais.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = ki3.getGroup(op.param1) G.preventedJoinByTicket = True ki3.updateGroup(G) G.preventedJoinByTicket(G) ki3.updateGroup(G) else: G = ki3.getGroup(op.param1) # ginfo = ki3.getGroup(op.param1) ki3.kickoutFromGroup(op.param1,[op.param2]) G.preventedJoinByTicket = False ki3.updateGroup(G) invsend = 0 Ticket = ki3.reissueGroupTicket(op.param1) gye.acceptGroupInvitationByTicket(op.param1,Ticket) ais.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = ki3.getGroup(op.param1) G.preventedJoinByTicket = True ki3.updateGroup(G) G.preventedJoinByTicket(G) ki3.updateGroup(G) settings["blacklist"][op.param2] = True #-------------------------------------------------------------------------------[ki2MID ki4MID] elif op.param3 in ki2MID: if op.param2 in ki4MID: G = ki4.getGroup(op.param1) # ginfo = ki4.getGroup(op.param1) G.preventedJoinByTicket = False ki4.updateGroup(G) invsend = 0 Ticket = ki4.reissueGroupTicket(op.param1) gye.acceptGroupInvitationByTicket(op.param1,Ticket) ais.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = ki4.getGroup(op.param1) G.preventedJoinByTicket = True ki4.updateGroup(G) G.preventedJoinByTicket(G) ki4.updateGroup(G) else: G = ki4.getGroup(op.param1) # ginfo = ki4.getGroup(op.param1) ki4.kickoutFromGroup(op.param1,[op.param2]) G.preventedJoinByTicket = False ki4.updateGroup(G) invsend = 0 Ticket = ki4.reissueGroupTicket(op.param1) gye.acceptGroupInvitationByTicket(op.param1,Ticket) ais.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = ki4.getGroup(op.param1) G.preventedJoinByTicket = True ki4.updateGroup(G) G.preventedJoinByTicket(G) ki4.updateGroup(G) settings["blacklist"][op.param2] = True #===============================================================================[ki3MID gyeMID] if op.param3 in ki3MID: if op.param2 in gyeMID: G = gye.getGroup(op.param1) # ginfo = gye.getGroup(op.param1) G.preventedJoinByTicket = False gye.updateGroup(G) invsend = 0 Ticket = gye.reissueGroupTicket(op.param1) gye.acceptGroupInvitationByTicket(op.param1,Ticket) ais.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = gye.getGroup(op.param1) G.preventedJoinByTicket = True gye.updateGroup(G) G.preventedJoinByTicket(G) gye.updateGroup(G) else: G = gye.getGroup(op.param1) # ginfo = gye.getGroup(op.param1) gye.kickoutFromGroup(op.param1,[op.param2]) G.preventedJoinByTicket = False gye.updateGroup(G) invsend = 0 Ticket = gye.reissueGroupTicket(op.param1) gye.acceptGroupInvitationByTicket(op.param1,Ticket) ais.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = gye.getGroup(op.param1) G.preventedJoinByTicket = True gye.updateGroup(G) G.preventedJoinByTicket(G) gye.updateGroup(G) settings["blacklist"][op.param2] = True #-------------------------------------------------------------------------------[ki3MID kiMID] elif op.param3 in ki3MID: if op.param2 in aisMID: G = ais.getGroup(op.param1) # ginfo = ais.getGroup(op.param1) G.preventedJoinByTicket = False ais.updateGroup(G) invsend = 0 Ticket = ais.reissueGroupTicket(op.param1) gye.acceptGroupInvitationByTicket(op.param1,Ticket) ais.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = ais.getGroup(op.param1) G.preventedJoinByTicket = True ki.updateGroup(G) G.preventedJoinByTicket(G) ais.updateGroup(G) else: G = ais.getGroup(op.param1) # ginfo = ais.getGroup(op.param1) ais.kickoutFromGroup(op.param1,[op.param2]) G.preventedJoinByTicket = False ais.updateGroup(G) invsend = 0 Ticket = ais.reissueGroupTicket(op.param1) gye.acceptGroupInvitationByTicket(op.param1,Ticket) ais.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = ais.getGroup(op.param1) G.preventedJoinByTicket = True ki.updateGroup(G) G.preventedJoinByTicket(G) ais.updateGroup(G) settings["blacklist"][op.param2] = True #-------------------------------------------------------------------------------[ki3MID ki2MID] elif op.param3 in ki3MID: if op.param2 in ki2MID: G = ki2.getGroup(op.param1) # ginfo = ki2.getGroup(op.param1) G.preventedJoinByTicket = False ki2.updateGroup(G) invsend = 0 Ticket = ki2.reissueGroupTicket(op.param1) gye.acceptGroupInvitationByTicket(op.param1,Ticket) ais.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = ki2.getGroup(op.param1) G.preventedJoinByTicket = True ki2.updateGroup(G) G.preventedJoinByTicket(G) ki2.updateGroup(G) else: G = ki2.getGroup(op.param1) # ginfo = ki2.getGroup(op.param1) ki2.kickoutFromGroup(op.param1,[op.param2]) G.preventedJoinByTicket = False ki2.updateGroup(G) invsend = 0 Ticket = ki2.reissueGroupTicket(op.param1) gye.acceptGroupInvitationByTicket(op.param1,Ticket) ais.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = ki2.getGroup(op.param1) G.preventedJoinByTicket = True ki2.updateGroup(G) G.preventedJoinByTicket(G) ki2.updateGroup(G) settings["blacklist"][op.param2] = True #-------------------------------------------------------------------------------[ki3MID ki4MID] elif op.param3 in ki3MID: if op.param2 in ki4MID: G = ki4.getGroup(op.param1) # ginfo = ki4.getGroup(op.param1) G.preventedJoinByTicket = False ki4.updateGroup(G) invsend = 0 Ticket = ki4.reissueGroupTicket(op.param1) gye.acceptGroupInvitationByTicket(op.param1,Ticket) ais.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = ki4.getGroup G.preventedJoinByTicket = True ki4.updateGroup(G) G.preventedJoinByTicket(G) ki4.updateGroup(G) else: G = ki4.getGroup(op.param1) # ginfo = ki4.getGroup(op.param1) ki4.kickoutFromGroup(op.param1,[op.param2]) G.preventedJoinByTicket = False ki4.updateGroup(G) invsend = 0 Ticket = ki4.reissueGroupTicket(op.param1) gye.acceptGroupInvitationByTicket(op.param1,Ticket) ais.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = ki4.getGroup(op.param1) G.preventedJoinByTicket = True ki4.updateGroup(G) G.preventedJoinByTicket(G) ki4.updateGroup(G) settings["blacklist"][op.param2] = True #===============================================================================[ki4MID gyeMID] if op.param3 in ki4MID: if op.param2 in gyeMID: G = gye.getGroup(op.param1) # ginfo = gye.getGroup(op.param1) G.preventedJoinByTicket = False gye.updateGroup(G) invsend = 0 Ticket = gye.reissueGroupTicket(op.param1) gye.acceptGroupInvitationByTicket(op.param1,Ticket) ais.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = gye.getGroup(op.param1) G.preventedJoinByTicket = True gye.updateGroup(G) G.preventedJoinByTicket(G) gye.updateGroup(G) else: G = gye.getGroup(op.param1) # ginfo = gye.getGroup(op.param1) gye.kickoutFromGroup(op.param1,[op.param2]) G.preventedJoinByTicket = False gye.updateGroup(G) invsend = 0 Ticket = gye.reissueGroupTicket(op.param1) gye.acceptGroupInvitationByTicket(op.param1,Ticket) ais.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = gye.getGroup(op.param1) G.preventedJoinByTicket = True gye.updateGroup(G) G.preventedJoinByTicket(G) gye.updateGroup(G) settings["blacklist"][op.param2] = True #-------------------------------------------------------------------------------[ki4MID kiMID] elif op.param3 in ki4MID: if op.param2 in aisMID: G = ais.getGroup(op.param1) # ginfo = ki.getGroup(op.param1) G.preventedJoinByTicket = False ais.updateGroup(G) invsend = 0 Ticket = ais.reissueGroupTicket(op.param1) gye.acceptGroupInvitationByTicket(op.param1,Ticket) ais.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = ais.getGroup(op.param1) G.preventedJoinByTicket = True ki.updateGroup(G) G.preventedJoinByTicket(G) ais.updateGroup(G) else: G = ais.getGroup(op.param1) # ginfo = ais.getGroup(op.param1) ais.kickoutFromGroup(op.param1,[op.param2]) G.preventedJoinByTicket = False ais.updateGroup(G) invsend = 0 Ticket = ais.reissueGroupTicket(op.param1) gye.acceptGroupInvitationByTicket(op.param1,Ticket) ais.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = ais.getGroup(op.param1) G.preventedJoinByTicket = True ais.updateGroup(G) G.preventedJoinByTicket(G) ais.updateGroup(G) settings["blacklist"][op.param2] = True #-------------------------------------------------------------------------------[ki4MID ki2MID] elif op.param3 in ki4MID: if op.param2 in ki2MID: G = ki2.getGroup(op.param1) # ginfo = ki2.getGroup(op.param1) G.preventedJoinByTicket = False ki2.updateGroup(G) invsend = 0 Ticket = ki2.reissueGroupTicket(op.param1) gye.acceptGroupInvitationByTicket(op.param1,Ticket) ais.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = ki2.getGroup(op.param1) G.preventedJoinByTicket = True ki2.updateGroup(G) G.preventedJoinByTicket(G) ki2.updateGroup(G) else: G = ki2.getGroup(op.param1) # ginfo = ki2.getGroup(op.param1) ki2.kickoutFromGroup(op.param1,[op.param2]) G.preventedJoinByTicket = False ki2.updateGroup(G) invsend = 0 Ticket = ki2.reissueGroupTicket(op.param1) gye.acceptGroupInvitationByTicket(op.param1,Ticket) ais.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = ki2.getGroup(op.param1) G.preventedJoinByTicket = True ki2.updateGroup(G) G.preventedJoinByTicket(G) ki2.updateGroup(G) settings["blacklist"][op.param2] = True #-------------------------------------------------------------------------------[ki4MID ki3MID] elif op.param3 in ki4MID: if op.param2 in ki3MID: G = ki3.getGroup(op.param1) # ginfo = ki3.getGroup(op.param1) G.preventedJoinByTicket = False ki3.updateGroup(G) invsend = 0 Ticket = ki3.reissueGroupTicket(op.param1) gye.acceptGroupInvitationByTicket(op.param1,Ticket) ais.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = ki3.getGroup(op.param1) G.preventedJoinByTicket = True ki3.updateGroup(G) G.preventedJoinByTicket(G) ki3.updateGroup(G) else: G = ki3.getGroup(op.param1) # ginfo = ki3.getGroup(op.param1) ki3.kickoutFromGroup(op.param1,[op.param2]) G.preventedJoinByTicket = False ki3.updateGroup(G) invsend = 0 Ticket = ki3.reissueGroupTicket(op.param1) gye.acceptGroupInvitationByTicket(op.param1,Ticket) ais.acceptGroupInvitationByTicket(op.param1,Ticket) ki2.acceptGroupInvitationByTicket(op.param1,Ticket) ki3.acceptGroupInvitationByTicket(op.param1,Ticket) ki4.acceptGroupInvitationByTicket(op.param1,Ticket) ki5.acceptGroupInvitationByTicket(op.param1,Ticket) ki6.acceptGroupInvitationByTicket(op.param1,Ticket) G = ki3.getGroup(op.param1) G.preventedJoinByTicket = True ki3.updateGroup(G) G.preventedJoinByTicket(G) ki3.updateGroup(G) settings["blacklist"][op.param2] = True elif op.param2 not in Bots: if op.param2 in admin: pass elif settings["protect"] == True: settings["blacklist"][op.param2] = True random.choice(KAC).kickoutFromGroup(op.param1,[op.param2]) random.choice(KAC).inviteIntoGroup(op.param1,[op.param3]) random.choice(KAC).sendText(op.param1,"Don't Play bro...!") else: pass except: pass #==============================================================================# #==============================================================================# if op.type == 13: if op.param2 not in Bots: if op.param2 in admin: pass elif settings["inviteprotect"] == True: settings["blacklist"][op.param2] = True random.choice(KAC).cancelGroupInvitation(op.param1,[op.param3]) random.choice(KAC).kickoutFromGroup(op.param1,[op.param2]) if op.param2 not in Bots: if op.param2 in admin: pass elif settings["cancelprotect"] == True: settings["blacklist"][op.param2] = True random.choice(KAC).cancelGroupInvitation(op.param1,[op.param3]) #------------------------------------------------------------------------------- if op.type == 11: if op.param2 not in Bots: if op.param2 in admin and Bots and Owner: pass elif settings["qrprotect"] == True: settings["blacklist"][op.param2] = True G = ais.getGroup(op.param1) G.preventedJoinByTicket = True ais.updateGroup(G) random.choice(KAC).kickoutFromGroup(op.param1,[op.param2]) else: gye.sendMessage(op.param1,"Jangan Buka Qr") else: gye.sendMessage(op.param1,"") #==============================================================================# # if op.type == 55: # print ("[ 55 ] GYEVHA BOTS EMPAT") # if op.param1 in read["readPoint"]: # _name = gye.getContact(op.param2).displayName # tz = pytz.timezone("Asia/Jakarta") # timeNow = datetime.now(tz=tz) # timeHours = datetime.strftime(timeNow," (%H:%M)") # read["readMember"][op.param1][op.param2] = str(_name) + str(timeHours) # backupData() #except Exception as error: # logError(error) #==============================================================================# if op.type == 25: msg = op.message if text.lower() == '/ti/g/': if settings["join ticket"] == True: link_re = re.compile('(?:line\:\/|line\.me\/R)\/ti\/g\/([a-zA-Z0-9_-]+)?') links = link_re.findall(text) n_links = [] for l in links: if l not in n_links: n_links.append(l) for ticket_id in n_links: group = gye.findGroupByTicket(ticket_id) gye.acceptGroupInvitationByTicket(group.id,ticket_id) gye.sendMessage(to, "Berhasil masuk ke group %s" % str(group.name)) except Exception as error: logError(error) #==============================================================================# # Auto join if BOT invited to group def NOTIFIED_INVITE_INTO_GROUP(op): try: gye.acceptGroupInvitation(op.param1) ais.acceptGroupInvitation(op.param1) ki2.acceptGroupInvitation(op.param1) ki3.acceptGroupInvitation(op.param1) ki4.acceptGroupInvitation(op.param1) ki5.acceptGroupInvitation(op.param1) ki6.acceptGroupInvitation(op.param1) except Exception as e: gye.log("[NOTIFIED_INVITE_INTO_GROUP] ERROR : " + str(e)) # Auto kick if BOT out to group def NOTIFIED_KICKOUT_FROM_GROUP(op): try: if op.param2 not in Bots: random.choice(KAC).kickoutFromGroup(op.param1,op.param2) else: pass except Exception as e: gye.log("[NOTIFIED_KICKOUT_FROM_GROUP] ERROR : " + str(e)) while True: try: ops = oepoll.singleTrace(count=50) if ops is not None: for op in ops: lineBot(op) oepoll.setRevision(op.revision) except Exception as e: logError(e)
[ "noreply@github.com" ]
Namemai.noreply@github.com
6b307266c03ec45f6004645eac1d4985b1bfbb4c
d5a5ff1ed1f508c47e9506a552bf44844bcdc071
/payroll/apps.py
8313bd0aaa30a056f07efb95e1823ad6458d08af
[]
no_license
sintaxyzcorp/prometeus
5c9dc20e3c2f33ea6b257b850ff9505621302c47
2508603b6692023e0a9e40cb6cd1f08465a33f1c
refs/heads/master
2021-09-01T09:31:36.868784
2017-12-26T07:58:27
2017-12-26T07:58:27
113,787,842
0
1
null
2017-12-18T08:25:31
2017-12-10T22:16:28
JavaScript
UTF-8
Python
false
false
182
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.apps import AppConfig class PayrollConfig(AppConfig): name = 'payroll' verbose_name = 'Nomina'
[ "carloxdev@gmail.com" ]
carloxdev@gmail.com
68f0de4dc1cfafcd16fd2b64c1709661f6dc605d
01ff31cc9c39821852b7522a4c78b551f3d269e4
/Murali/arrayreverse.py
71361e9c01b7da4ebe2c338bdf6de986846f7601
[]
no_license
tactlabs/numpyvil
aa3fd11a2ceb60a862d939316fd02caeef0aff6e
749532acccbbacf55888e1cb87bfa166936cbb85
refs/heads/master
2022-09-12T16:45:22.831335
2020-05-30T02:14:55
2020-05-30T02:14:55
267,981,322
0
0
null
null
null
null
UTF-8
Python
false
false
405
py
#!/usr/bin/env python # -*- coding: utf-8 -*- # the above line is to avoid 'SyntaxError: Non-UTF-8 code starting with' error ''' Created on Course work: @author: krish Source: ''' # Import necessary modules import numpy as np def startpy(): a = np.array([ [1, 2], [3, 4] ]) inverse_a = np.linalg.inv(a) print(inverse_a) if __name__ == '__main__': startpy()
[ "krishnan806@gmail.com" ]
krishnan806@gmail.com
b20a068f0cfd8e5a3c549401b5af9d56a7aa0192
747dc77b95788a8bc7d2ab9bf280d92035ca0d33
/controllers/pr.py
67897833762a42acc8d5bc8ecb9e2b09f08feb69
[ "MIT" ]
permissive
taufikh/sahana-eden-madpub
ca4a09f32a92e3712e6670af60581ce7e5b1277f
b16418b36d0fb781fd045f7e7edd1a30259a1f35
refs/heads/master
2021-05-26T21:01:23.804680
2011-02-20T10:37:26
2011-02-20T10:37:26
null
0
0
null
null
null
null
UTF-8
Python
false
false
18,841
py
# -*- coding: utf-8 -*- """ VITA Person Registry, Controllers @author: nursix @see: U{http://eden.sahanafoundation.org/wiki/BluePrintVITA} """ prefix = request.controller resourcename = request.function # ----------------------------------------------------------------------------- # Options Menu (available in all Functions' Views) def shn_menu(): response.menu_options = [ [T("Home"), False, URL(r=request, f="index")], [T("Search for a Person"), False, URL(r=request, f="person", args="search")], [T("Persons"), False, URL(r=request, f="person"), [ [T("List"), False, URL(r=request, f="person")], [T("Add"), False, URL(r=request, f="person", args="create")], ]], [T("Groups"), False, URL(r=request, f="group"), [ [T("List"), False, URL(r=request, f="group")], [T("Add"), False, URL(r=request, f="group", args="create")], ]]] #De-activating until fixed: #if s3_has_role(1): #response.menu_options.append([T("De-duplicator"), False, URL(r=request, f="person_duplicates")]) menu_selected = [] if session.rcvars and "pr_group" in session.rcvars: group = db.pr_group query = (group.id == session.rcvars["pr_group"]) record = db(query).select(group.id, group.name, limitby=(0, 1)).first() if record: name = record.name menu_selected.append(["%s: %s" % (T("Group"), name), False, URL(r=request, f="group", args=[record.id])]) if session.rcvars and "pr_person" in session.rcvars: person = db.pr_person query = (person.id == session.rcvars["pr_person"]) record = db(query).select(person.id, limitby=(0, 1)).first() if record: name = shn_pr_person_represent(record.id) menu_selected.append(["%s: %s" % (T("Person"), name), False, URL(r=request, f="person", args=[record.id])]) if menu_selected: menu_selected = [T("Open recent"), True, None, menu_selected] response.menu_options.append(menu_selected) shn_menu() # ----------------------------------------------------------------------------- def index(): """ Module's Home Page """ try: module_name = deployment_settings.modules[prefix].name_nice except: module_name = T("Person Registry") def prep(r): if r.representation == "html": if not r.id: r.method = "search" else: redirect(URL(r=request, f="person", args=[r.id])) return True response.s3.prep = prep def postp(r, output): if isinstance(output, dict): gender = [] for g_opt in pr_gender_opts: count = db((db.pr_person.deleted == False) & \ (db.pr_person.gender == g_opt)).count() gender.append([str(pr_gender_opts[g_opt]), int(count)]) age = [] for a_opt in pr_age_group_opts: count = db((db.pr_person.deleted == False) & \ (db.pr_person.age_group == a_opt)).count() age.append([str(pr_age_group_opts[a_opt]), int(count)]) total = int(db(db.pr_person.deleted == False).count()) output.update(module_name=module_name, gender=gender, age=age, total=total) if r.representation in shn_interactive_view_formats: if not r.component: label = READ else: label = UPDATE linkto = r.resource.crud._linkto(r)("[id]") response.s3.actions = [ dict(label=str(label), _class="action-btn", url=str(linkto)) ] r.next = None return output response.s3.postp = postp if auth.s3_logged_in(): add_btn = A(T("Add Person"), _class="action-btn", _href=URL(r=request, f="person", args="create")) else: add_btn = None output = s3_rest_controller("pr", "person", add_btn=add_btn) response.view = "pr/index.html" response.title = module_name shn_menu() return output # ----------------------------------------------------------------------------- def person(): """ RESTful CRUD controller """ def prep(r): if r.component_name == "config": _config = db.gis_config defaults = db(_config.id == 1).select(limitby=(0, 1)).first() for key in defaults.keys(): if key not in ["id", "uuid", "mci", "update_record", "delete_record"]: _config[key].default = defaults[key] if r.representation == "popup": # Hide "pe_label" and "missing" fields in person popups r.table.pe_label.readable = False r.table.pe_label.writable = False r.table.missing.readable = False r.table.missing.writable = False return True response.s3.prep = prep s3xrc.model.configure(db.pr_group_membership, list_fields=["id", "group_id", "group_head", "description"]) table = db.pr_person s3xrc.model.configure(table, listadd = False, insertable = True) output = s3_rest_controller(prefix, resourcename, main="first_name", extra="last_name", rheader=lambda r: shn_pr_rheader(r, tabs = [(T("Basic Details"), None), (T("Images"), "image"), (T("Identity"), "identity"), (T("Address"), "address"), (T("Contact Data"), "pe_contact"), (T("Memberships"), "group_membership"), (T("Presence Log"), "presence"), (T("Subscriptions"), "pe_subscription"), (T("Map Settings"), "config") ])) shn_menu() return output # ----------------------------------------------------------------------------- def group(): """ RESTful CRUD controller """ tablename = "%s_%s" % (prefix, resourcename) table = db[tablename] response.s3.filter = (db.pr_group.system == False) # do not show system groups s3xrc.model.configure(db.pr_group_membership, list_fields=["id", "person_id", "group_head", "description"]) output = s3_rest_controller(prefix, resourcename, rheader=lambda r: shn_pr_rheader(r, tabs = [(T("Group Details"), None), (T("Address"), "address"), (T("Contact Data"), "pe_contact"), (T("Members"), "group_membership")])) shn_menu() return output # ----------------------------------------------------------------------------- def image(): """ RESTful CRUD controller """ return s3_rest_controller(prefix, resourcename) # ----------------------------------------------------------------------------- def pe_contact(): """ RESTful CRUD controller """ table = db.pr_pe_contact table.pe_id.label = T("Person/Group") table.pe_id.readable = True table.pe_id.writable = True return s3_rest_controller(prefix, resourcename) # ----------------------------------------------------------------------------- #def group_membership(): #""" RESTful CRUD controller """ #return s3_rest_controller(prefix, resourcename) # ----------------------------------------------------------------------------- def pentity(): """ RESTful CRUD controller """ return s3_rest_controller(prefix, resourcename) # ----------------------------------------------------------------------------- def download(): """ Download a file. @todo: deprecate? (individual download handler probably not needed) """ return response.download(request, db) # ----------------------------------------------------------------------------- def tooltip(): """ Ajax tooltips """ if "formfield" in request.vars: response.view = "pr/ajaxtips/%s.html" % request.vars.formfield return dict() #------------------------------------------------------------------------------------------------------------------ def person_duplicates(): """ Handle De-duplication of People @todo: permissions, audit, update super entity, PEP8, optimization? @todo: check for component data! @todo: user accounts, subscriptions? """ # Shortcut persons = db.pr_person table_header = THEAD(TR(TH(T("Person 1")), TH(T("Person 2")), TH(T("Match Percentage")), TH(T("Resolve")))) # Calculate max possible combinations of records # To handle the AJAX requests by the dataTables jQuery plugin. totalRecords = db(persons.id > 0).count() item_list = [] if request.vars.iDisplayStart: end = int(request.vars.iDisplayLength) + int(request.vars.iDisplayStart) records = db((persons.id > 0) & \ (persons.deleted == False) & \ (persons.first_name != None)).select(persons.id, # Should this be persons.ALL? persons.pe_label, persons.missing, persons.first_name, persons.middle_name, persons.last_name, persons.preferred_name, persons.local_name, persons.age_group, persons.gender, persons.date_of_birth, persons.nationality, persons.country, persons.religion, persons.marital_status, persons.occupation, persons.tags, persons.comments) # Calculate the match percentage using Jaro wrinkler Algorithm count = 1 i = 0 for onePerson in records: #[:len(records)/2]: soundex1= soundex(onePerson.first_name) array1 = [] array1.append(onePerson.pe_label) array1.append(str(onePerson.missing)) array1.append(onePerson.first_name) array1.append(onePerson.middle_name) array1.append(onePerson.last_name) array1.append(onePerson.preferred_name) array1.append(onePerson.local_name) array1.append(pr_age_group_opts.get(onePerson.age_group, T("None"))) array1.append(pr_gender_opts.get(onePerson.gender, T("None"))) array1.append(str(onePerson.date_of_birth)) array1.append(pr_nations.get(onePerson.nationality, T("None"))) array1.append(pr_nations.get(onePerson.country, T("None"))) array1.append(pr_religion_opts.get(onePerson.religion, T("None"))) array1.append(pr_marital_status_opts.get(onePerson.marital_status, T("None"))) array1.append(onePerson.occupation) # Format tags into an array if onePerson.tags != None: tagname = [] for item in onePerson.tags: tagname.append(pr_impact_tags.get(item, T("None"))) array1.append(tagname) else: array1.append(onePerson.tags) array1.append(onePerson.comments) i = i + 1 j = 0 for anotherPerson in records: #[len(records)/2:]: soundex2 = soundex(anotherPerson.first_name) if j >= i: array2 =[] array2.append(anotherPerson.pe_label) array2.append(str(anotherPerson.missing)) array2.append(anotherPerson.first_name) array2.append(anotherPerson.middle_name) array2.append(anotherPerson.last_name) array2.append(anotherPerson.preferred_name) array2.append(anotherPerson.local_name) array2.append(pr_age_group_opts.get(anotherPerson.age_group, T("None"))) array2.append(pr_gender_opts.get(anotherPerson.gender, T("None"))) array2.append(str(anotherPerson.date_of_birth)) array2.append(pr_nations.get(anotherPerson.nationality, T("None"))) array2.append(pr_nations.get(anotherPerson.country, T("None"))) array2.append(pr_religion_opts.get(anotherPerson.religion, T("None"))) array2.append(pr_marital_status_opts.get(anotherPerson.marital_status, T("None"))) array2.append(anotherPerson.occupation) # Format tags into an array if anotherPerson.tags != None: tagname = [] for item in anotherPerson.tags: tagname.append(pr_impact_tags.get(item, T("None"))) array2.append(tagname) else: array2.append(anotherPerson.tags) array2.append(anotherPerson.comments) if count > end and request.vars.max != "undefined": count = int(request.vars.max) break; if onePerson.id == anotherPerson.id: continue else: mpercent = jaro_winkler_distance_row(array1, array2) # Pick all records with match percentage is >50 or whose soundex values of first name are equal if int(mpercent) > 50 or (soundex1 == soundex2): count = count + 1 item_list.append([onePerson.first_name, anotherPerson.first_name, mpercent, "<a href=\"../pr/person_resolve?perID1=%i&perID2=%i\", class=\"action-btn\">Resolve</a>" % (onePerson.id, anotherPerson.id) ]) else: continue j = j + 1 item_list = item_list[int(request.vars.iDisplayStart):end] # Convert data to JSON result = [] result.append({ "sEcho" : request.vars.sEcho, "iTotalRecords" : count, "iTotalDisplayRecords" : count, "aaData" : item_list }) output = json.dumps(result) # Remove unwanted brackets output = output[1:] output = output[:-1] return output else: # Don't load records except via dataTables (saves duplicate loading & less confusing for user) items = DIV((TABLE(table_header, TBODY(), _id="list", _class="display"))) return(dict(items=items)) #---------------------------------------------------------------------------------------------------------- def delete_person(): """ To delete references to the old record and replace it with the new one. @todo: components??? cannot simply be re-linked! @todo: user accounts? @todo: super entity not updated! """ # @ToDo: Error gracefully if conditions not satisfied old = request.vars.old new = request.vars.new # Find all tables which link to the pr_person table tables = shn_table_links("pr_person") for table in tables: for count in range(len(tables[table])): field = tables[str(db[table])][count] query = db[table][field] == old db(query).update(**{field:new}) # Remove the record db(db.pr_person.id == old).update(deleted=True) return "Other Record Deleted, Linked Records Updated Successfully" #------------------------------------------------------------------------------------------------------------------ def person_resolve(): """ This opens a popup screen where the de-duplication process takes place. @todo: components??? cannot simply re-link! @todo: user accounts linked to these records? @todo: update the super entity! @todo: use S3Resources, implement this as a method handler """ # @ToDo: Error gracefully if conditions not satisfied perID1 = request.vars.perID1 perID2 = request.vars.perID2 # Shortcut persons = db.pr_person count = 0 for field in persons: id1 = str(count) + "Right" # Gives a unique number to each of the arrow keys id2 = str(count) + "Left" count = count + 1; # Comment field filled with buttons field.comment = DIV(TABLE(TR(TD(INPUT(_type="button", _id=id1, _class="rightArrows", _value="-->")), TD(INPUT(_type="button", _id=id2, _class="leftArrows", _value="<--"))))) record = persons[perID1] myUrl = URL(r=request, c="pr", f="person") form1 = SQLFORM(persons, record, _id="form1", _action=("%s/%s" % (myUrl, perID1))) # For the second record remove all the comments to save space. for field in persons: field.comment = None record = persons[perID2] form2 = SQLFORM(persons, record, _id="form2", _action=("%s/%s" % (myUrl, perID2))) return dict(form1=form1, form2=form2, perID1=perID1, perID2=perID2) # -----------------------------------------------------------------------------
[ "ptressel@myuw.net" ]
ptressel@myuw.net
9465b0882beab1df4db386e4f4799e08edec62ef
82f449cc405b8379a30b228a15682bbd70d1b09d
/venv/Scripts/easy_install-3.7-script.py
2250af4830cd4597cb878cb4f8a2dce11b83487c
[]
no_license
neo-talen/QuickCmdBtnSet
82dd18e070e285ba752f9bd3586201cc8c174f78
4781a5c44a4022b6f014bd8ca513b89983f6a309
refs/heads/master
2022-05-06T08:29:10.993183
2022-05-05T11:07:04
2022-05-05T11:07:04
183,062,524
1
1
null
null
null
null
UTF-8
Python
false
false
437
py
#!K:\QuickCmdBtnSet\venv\Scripts\python.exe # EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==40.8.0','console_scripts','easy_install-3.7' __requires__ = 'setuptools==40.8.0' import re import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit( load_entry_point('setuptools==40.8.0', 'console_scripts', 'easy_install-3.7')() )
[ "hongtianlong@corp.netease.com" ]
hongtianlong@corp.netease.com
039f8e759d7d7c500007c87252e26a1df913ac2a
1850e5468c6df447573d5fb1cc4166481f1c16f6
/test_rest/migrations/0006_auto_20160510_1640.py
5f24463e038b7062dbf4948d881ddb56505c037f
[]
no_license
MaliRobot/test_geodjango
8045bba317dc7fd7ff6a4b90ccf7d199f735b848
dcd439df45c2bd76b03645e1a311b6385277e8b3
refs/heads/master
2016-09-13T03:02:48.935060
2016-05-14T15:57:58
2016-05-14T15:57:58
58,746,440
0
0
null
null
null
null
UTF-8
Python
false
false
481
py
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-05-10 14:40 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('test_rest', '0005_auto_20160510_1629'), ] operations = [ migrations.AlterField( model_name='geos_multi', name='raw', field=models.CharField(blank=True, max_length=1000000, null=True), ), ]
[ "milos.trifunovic@gmail.com" ]
milos.trifunovic@gmail.com
ceebfdcd7b7a8bf8d3899260717faa5d830056e7
906ee4e73a670125b4cf7d284ef0435f02976b44
/trie/python3/test_trie.py
b38191033648e49f2c9a3a9f9d9db7ac52f1ff41
[]
no_license
aberer/exercises
c07079ce6841da5b3d18cd1aa823312160368dd4
cb42f9c4e58b8e28a97cf075e5dc6d7c12046ef9
refs/heads/master
2020-03-18T19:55:28.957848
2018-06-01T13:22:17
2018-06-01T13:22:17
135,185,577
0
0
null
null
null
null
UTF-8
Python
false
false
2,448
py
#! /usr/bin/python3 from trie import Trie from unittest import TestCase from copy import deepcopy import pdb class TrieTest(TestCase): # __________________________________________________________________________ def setUp(self): self._testTrie = Trie("", [Trie("a", [Trie("bl"), Trie("c")]), Trie("b", [Trie("ca"), Trie("a")])]) # __________________________________________________________________________ def testGetNumberOfLeaves(self): self.assertEqual(self._testTrie.getNumberOfLeaves(), 4) self.assertEqual(Trie().getNumberOfLeaves(), 1) # __________________________________________________________________________ def testFind(self): self.assertEqual(self._testTrie.find("ab"), 1) self.assertEqual(self._testTrie.find("a"), 2) # __________________________________________________________________________ def testAddToExisting(self): return() trie = deepcopy(self._testTrie) trie.add("cd") self.assertEqual(trie.find("cd"), 1) trie.add("ce") self.assertEqual(trie.find("ce"), 1) self.assertEqual(trie.find("c"), 2) trie.add("bcad") # __________________________________________________________________________ def testAddDeNovo(self): trie = Trie() trie.add("abl") trie.add("ac") trie.add("bca") trie.add("baa") self.assertEqual(trie.find("b"), 2) self.assertEqual(trie.find("a"), 2) self.assertEqual(trie.find("abl"), 1) self.assertEqual(trie.find("ac"), 1) self.assertEqual(trie.find("bca"), 1) self.assertEqual(trie.find("baa"), 1) # __________________________________________________________________________ def testAddSubstring(self): trie = Trie() trie.add("aberer") trie.add("ab") trie.add("a") self.assertEqual(trie.find("a"), 3) self.assertEqual(trie.find("ab"), 2) self.assertEqual(trie.find("aberer"), 1) trie.add("abe") self.assertEqual(trie.find("abe"), 2) # __________________________________________________________________________ def testExample(self): trie = Trie() trie.add("hack") trie.add("hackerrank") self.assertEqual(trie.find("hac"), 2) self.assertEqual(trie.find("hak"), 0)
[ "andre.aberer@googlemail.com" ]
andre.aberer@googlemail.com
cbfd8743fcd5e667b03eed5cbbdea0a35d1f9203
5cdbc060741d646bad6df30ad9f560c0da81e2d1
/empty_files.py
fe75d50370f5d8ef0e249df330a07bb97d9782b2
[]
no_license
wveulemans/project_ITH
9bb1f4f01582d1e99f548820bf6bc8be80942137
436c2f85768941d70c3a8f6a92167c81e5798f84
refs/heads/master
2021-01-20T07:31:37.541005
2017-06-22T14:55:33
2017-06-22T14:55:33
90,009,095
0
0
null
null
null
null
UTF-8
Python
false
false
642
py
#!/usr/bin/python import logging def empty_files(name, files): """ Input: preprocessed pyclone files (ex: pyclone_ith_run3_a_1_3_pt_filter1_indel.vcf.tsv) ---------- Function: check if files are empty and write log ---------- Output: if file empty ==> state = False """ global pyclone_file pyclone_file = 1 # find all preprocessed pyclone files if 'pyclone_ith' in files: r = open(files, 'rb') # amount of bytes if only header is present in file EOH = r.seek(97) if len(r.read()) == 0: pyclone_file = 0 logging.info("Patient %s: file: "% name +files.split('/', 6)[6]+" empty!") return pyclone_file
[ "wveulemans@research-desktop-1.biomina.be" ]
wveulemans@research-desktop-1.biomina.be
2bcecea0d16f3086ea5a672cb18c33faaad88ef8
871775171633543c9f9d37fbc7ab022fec2c434e
/my_cars.py
e1cd729224ee444785e1cd21e1d9851ab8fc1684
[]
no_license
ToddCombs/Phenomenon
886e9da9154c14a298887dd65fabe61db4c2f2ee
d5f656156e05eed7df19e51b22ee7567319eb59a
refs/heads/master
2020-07-04T14:50:40.482186
2020-01-09T02:36:31
2020-01-09T02:36:31
202,316,829
0
0
null
null
null
null
UTF-8
Python
false
false
285
py
# author:ToddCombs # 在一个文件/模块中导入多个类 from electric_car import Car, ElectricCar my_beetle = Car('volkswagen','beetle',2016) print(my_beetle.get_descriptive_name()) my_tesla = ElectricCar('tesla', 'model s', 2022) print(my_tesla.get_descriptive_name())
[ "noreply@github.com" ]
ToddCombs.noreply@github.com
8d8a98d12cda3412affb4d67256bc922343908d0
eb90f82d0fea6075f51ba4f4a7fa1a54768f022e
/tiny_spider/core/webspider.py
5b71e52ba7cb6675e451ef01b0d7e460547ec9fe
[]
no_license
jiegerl/DTS
095ced2b5714a6d41f2c0a9274cd2100976b445b
195f61095430e8b3737c95adc3493bfcc13d1fdd
refs/heads/master
2021-04-29T13:30:46.210492
2018-03-19T06:07:09
2018-03-19T06:07:09
120,190,462
0
0
null
null
null
null
UTF-8
Python
false
false
1,203
py
from tiny_spider.base.common import Global from tiny_spider.base.logger import Logger from tiny_spider.base.decorator import singleton from tiny_spider.core.req_webspider.req_downloader import ReqDownloader from tiny_spider.core.req_webspider.req_preprocessor import ReqPreprocessor from tiny_spider.core.req_webspider.req_recevier import ReqReceiver from tiny_spider.core.req_webspider.msg_processor import MsgProcessor from tiny_spider.model.data import WebSpiderNode @singleton class WebSpider: def __new__(cls): return object.__new__(cls) def __init__(self): self.__instance = 0 def start(self): if self.__instance: print("Spider is already running...") else: print("Spider is already starting...") self.__instance = 1 cn_logger = Logger('c') cn_logger.execute() mp = MsgProcessor() node = WebSpiderNode('127.0.0.1', Global.get_status_active()) mp.send_node_msg(node) rp = ReqReceiver('127.0.0.1') rp.start() # rc = ReqPreprocessor() # rc.start() rd = ReqDownloader() rd.start()
[ "841917374@qq.com" ]
841917374@qq.com
da837fb82085ba56a201b6894220c72ba25ea444
38182d45f0b1f6228aeec03a876ee8213404d171
/questionnaire/admin.py
be8327b50af90b1628c99da556843bb64cf84a85
[]
no_license
alexzinoviev/MobileDoc
1283ec5cd52d27510e54f22522b9e1a01b65d8f8
66c22f1b8fe96ad5630c3d33bcc26e5d815f48db
refs/heads/master
2020-06-24T05:29:41.366198
2017-08-03T16:37:10
2017-08-03T16:37:10
96,920,344
0
0
null
null
null
null
UTF-8
Python
false
false
448
py
from django.contrib import admin from .models import Questionnaire # Register your models here. @admin.register(Questionnaire) class QuestionAdmin(admin.ModelAdmin): list_display = ('question', 'category') #admin.site.register(Questionnaire, QuestionAdmin) # @admin.register(Product) # class ProductAdmin(admin.ModelAdmin): # #pass # prepopulated_fields = {'slug': ('name',)} # list_display = ('name','desc', 'cost', 'active')
[ "shurik.zinovyev@gmail.com" ]
shurik.zinovyev@gmail.com
a07e5ac90e69d7541087f392852696e2193489ca
3afc8f590634df176510cdfe0aecf337ecf5adb8
/parallel.py
d212992668ef3b38a4ffc19593e7cb5064ca69bd
[]
no_license
randomstylez/CDA4101
1d139594e2645e8774c28bf1c24d8cf2bbaddda8
c956d4313eed8728b5cff1940ce36527da9e2f2b
refs/heads/master
2022-12-13T23:58:00.866246
2020-09-10T02:06:17
2020-09-10T02:06:17
294,276,790
0
0
null
null
null
null
UTF-8
Python
false
false
5,185
py
import requests import time from bs4 import BeautifulSoup from mpi4py import MPI class scoredUrl: def __init__(self, url, score): self.url = url self.score = score self.articleArray = self.getAsArray(url) def getAsArray(self, url): response = requests.get(url) responseText = response.text.encode('UTF-8') soup = BeautifulSoup(response.text, "html.parser") s = soup.find_all('p') string1 = str(s) arrayS = string1.split(' ') arrayS = [word.replace('<p', '').replace('</p>', '').replace('<code>', '').replace('</code>', '') .replace('class=', '').replace('href=', '').replace('>', '').replace('<p', '') .replace('\"', '').replace('\"', '').replace(',','') for word in arrayS] arrayS = list(filter(None, arrayS)) return arrayS def getUrl(self): return self.url def getScore(self): return self.score def getList(self): return self.articleArray def compare(firstArticle, secondArticle): totalCounter = float(len(secondArticle)) matchCounter = 0.0 for i in firstArticle: for j in secondArticle: if j == i: matchCounter = matchCounter + 1 return matchCounter / totalCounter def listComparison(userArray, listOfArticles, cpu): firstMostSimilar = 0 firstMostName = None secondMostSimilar = 0 secondMostName = None for i in listOfArticles: n = compare(userArray, i.getList()) if n > firstMostSimilar: if firstMostSimilar > secondMostSimilar: secondMostSimilar = firstMostSimilar secondMostName = firstMostName firstMostSimilar = n firstMostName = i print("Article ", listOfArticles.index(i) + 1, "From CPU",cpu,"is", n, "% similar") if secondMostName == None: secondMostName = firstMostName averageScore = (firstMostName.getScore() + secondMostName.getScore()) / 2 #print("User article average rating of:",averageScore) return averageScore def starttime(): return time.time() def endtime(): return time.time() def mpi(): if cpu == 0: for slave in range(1, numcpus): comm.send(articleList[slave*numeach:(2*slave*numeach)], dest=slave) masterAverage = listComparison(arrayS, articleList[0:(numeach)], cpu) totalFromSlaves = masterAverage for slave in range(1, numcpus): receivedValue = comm.recv(source=slave) totalFromSlaves = totalFromSlaves + receivedValue totalAverage = totalFromSlaves / comm.Get_size() print("Total Average", totalAverage) else: slaveList = comm.recv(source=0) slaveAverage = listComparison(arrayS, slaveList, cpu) comm.send(slaveAverage, dest=0) if __name__ == "__main__": comm = MPI.COMM_WORLD cpu = comm.Get_rank() numcpus = comm.Get_size() #print(numcpus) userUrl = 'https://www.nytimes.com/2018/06/10/world/canada/g-7-justin-trudeau-trump.html' response = requests.get(userUrl) responseText = response.text.encode('UTF-8') soup = BeautifulSoup(response.text, "html.parser") s = soup.find_all('p') string1 = str(s) arrayS = string1.split(' ') arrayS = [word.replace('<p', '').replace('</p>', '').replace('<code>', '').replace('</code>', '') .replace('class=', '').replace('href=', '').replace('>', '').replace('<p', '') .replace('\"', '').replace('\"', '').replace(',','') for word in arrayS] arrayS = list(filter(None, arrayS)) article1 = scoredUrl('https://www.foxnews.com/media/trudeau-johnson-macron-appear-to-be-mocking-trump-at-nato-summit-in-surfaced-video', 6.5) article2 = scoredUrl('https://www.nbcnews.com/politics/donald-trump/trump-calls-trudeau-two-faced-after-hot-mic-catches-nato-n1095351', 8.0) article3 = scoredUrl('https://www.dailymail.co.uk/news/article-7753821/Justin-Trudeau-Emmanuel-Macron-Boris-Johnson-caught-appearing-gossip-Trump.html', 5.0) article4 = scoredUrl('https://www.theguardian.com/us-news/2019/dec/04/trump-describes-trudeau-as-two-faced-over-nato-hot-mic-video', 7.0) article5 = scoredUrl('https://abcnews.go.com/Politics/trudeau-washington-move-past-feud-trump-lobby-usmca/story?id=63820427', 6.0) article6 = scoredUrl('https://www.usatoday.com/story/news/politics/2018/11/01/trade-wars-canada-not-ready-forgive-trumps-insulting/1648045002/', 8.5) article7 = scoredUrl('https://www.scmp.com/news/world/article/2150067/trump-tweets-he-instructed-us-representatives-not-endorse-g7-joint', 2.4) article8 = scoredUrl('https://thehill.com/homenews/administration/472972-trump-caught-on-hot-mic-criticizing-media-talking-about-two-faced', 9.0) articleList = [article1, article2, article3, article4, article5, article6, article7, article8] #print(len(articleList)) numeach = len(articleList)/numcpus #print("Num each", numeach) start = starttime() mpi() end = endtime() print(end - start)
[ "noreply@github.com" ]
randomstylez.noreply@github.com
a04ca00a34def210f98b0d9d753932995806ceee
c28ccac2daa674df07470a85d13552639a98e323
/generators2.py
8ba42d91337a4eb7f66a42759dfa3c4c08880ca1
[]
no_license
jnprogrammer/basic_python
69f2ff356ebf1da120789884f99aea197856e6c0
99fe4d6bb8c6aafd3701cc725e511e9967d9b0ca
refs/heads/master
2022-09-26T00:39:32.347757
2020-06-02T02:43:04
2020-06-02T02:43:04
261,020,958
2
0
null
null
null
null
UTF-8
Python
false
false
370
py
def oddnumbers(): n = 1 while True: yield n n += 2 def pi_series(): odds = oddnumbers() apprx = 0 while True: apprx += (4 / next(odds)) yield apprx apprx -= (4 / next(odds)) yield apprx if __name__ == '__main__': approx_pi = pi_series() for x in range(194): print(next(approx_pi))
[ "joshuanparker@gmail.com" ]
joshuanparker@gmail.com
27c54b473ba3124a7e869263fc294f9f1a3696db
570337818eaafd71370368dc28b5244784e9879d
/Assignment 3/ass3-2.py
1a31a65fb1e0908eaf2eeb22a3b9b97e12c260b4
[]
no_license
rajatgarg2/rajatcode
be89f3ae4d74adebb45caf538594539b97553249
e3c8077fc9e7da18f4fb9d7428a7c9ca72aca6ee
refs/heads/master
2023-01-03T14:17:50.627678
2020-10-25T13:48:14
2020-10-25T13:48:14
284,300,449
0
0
null
null
null
null
UTF-8
Python
false
false
346
py
def lesser_of_two_evens(a,b): if a%2==0 and b%2==0: if a<b: return a else: return b if a%2!=0 or b%2!=0: if a>b: return a else: return b a=int(input('Enter 1st no. : ')) b=int(input('Enter 2nd no. : ')) print(lesser_of_two_evens(a, b))
[ "noreply@github.com" ]
rajatgarg2.noreply@github.com
0d90c5c51a8ae8c2b13d012c22b04da8c58a8ca9
07929b06f109c10a667e7349c4ed8ddb146a1a75
/codeportal/migrations/0031_auto_20200415_0247.py
5861b44b6f5c453529bcd34de606e02862f453fd
[]
no_license
kaizen-cmd/aces-website
9f1272818ba9181530a606e7b77a444324bace10
48d1a17ad43692c4f570dae10eefdd716c103b94
refs/heads/master
2022-04-23T12:27:21.671301
2020-04-19T05:32:34
2020-04-19T05:32:34
256,455,075
0
0
null
null
null
null
UTF-8
Python
false
false
469
py
# Generated by Django 3.0.4 on 2020-04-14 21:17 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('codeportal', '0030_auto_20200414_1911'), ] operations = [ migrations.AlterField( model_name='problem_statements', name='date_added', field=models.DateTimeField(default=datetime.datetime(2020, 4, 15, 2, 46, 58, 595696)), ), ]
[ "tejasmandre0306@gmail.com" ]
tejasmandre0306@gmail.com
350d5f4964c7f6eaa0d60ab178395e20190df518
9785a256cd2d69a532aab7a4a70f4f116d8b7774
/shape_matching.py
94929ae18084d2eef7ac494af6cbc7be2c24cde6
[]
no_license
jaswanthrk/CV
ffebf9d1e2a232217c7e9d21944897b18acf4942
9924b7f478dafd5ed4a98dd2c4bf3b2659d41b31
refs/heads/master
2020-11-24T22:26:44.131382
2019-12-17T05:16:24
2019-12-17T05:16:24
228,364,525
0
0
null
null
null
null
UTF-8
Python
false
false
1,796
py
# cv2.matchShapes(contour template, contour, method, method parameter) # OUTPUT : MATCH VALUE - lower the better # CONTOUR TEMPLATE : REFERENCE CONTOUR # CONTOUR : THE INDIVIDUAL CONTOUR WE ARE CHECKING AGAINST # METHOD : TYPE OF CONTOUR MATCHING (1, 2, 3) # http://docs.opencv.org/2.4/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html # METHOD PARAMETER : LEAVE ALONE AS 0.0 (NOT FULLY UTILIZED IN PYTHON OPENCV) import cv2 import numpy as np # Load the template or reference image template = cv2.imread('images/4star,jpg', 0) cv2.imshow('Template', template) cv2.waitKey() # Load the target image with the shapes we're trying to match target = cv2.imread('images/shapes_to_match.jpg') target_gray = cv2.cvtColor(target, cv2.COLOR_BGR2GRAY) # Threshold both images first before using cv2.findContours ret, thresh1 = cv2.threshold(template, 127, 255, 0) ret, thresh2 = cv2.threshold(target_gray, 127, 255, 0) # Find contours in template contours, hierarchy = cv2.findContours(thresh1, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) # SORT CONTOURS SO THAT THE WE CAN REMOVE THE LARGEST CONTOUR WHICH IS THE IMAGE OUTLINE sorted_contours = sorted(contours, key = cv2.contourArea, reverse = True) template_contour = contours[1] # Find contours in target contours, hierarchy = cv2.findContours(thresh2, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) for c in contours: # iterate through each contour in the target image and use cv2.matchShapes to compare contour shapes match = cv2.matchShapes(template_contour, c, 1, 0.0) print(match) if match < 0.15 : closest_contour = c else : closest_contour = [] cv2.drawContours(target, [closest_contour], -1, (0, 255, 0), 3) cv2.imshow('Output', target) cv2.waitKey() cv2.destroyAllWindows()
[ "noreply@github.com" ]
jaswanthrk.noreply@github.com
94fe58505998793b4549481b06ceb94f09a57ecb
903710fc497e23fabaf777fe61b932506b07d92c
/experiment_10_2/bayesian_v2/phase1_read_data.py
66b5ebf81e928f9e2c5547bcdd9a299cd8e45a8e
[ "Apache-2.0" ]
permissive
julio-navarro-lara/thesis_scripts
222da4e57bbe5c5bd1dc439df19d450220d63bfa
dab1faabd6004389aadb082d63b10bae848bf1c8
refs/heads/master
2022-12-16T12:17:09.196278
2020-09-23T14:43:29
2020-09-23T14:43:29
297,955,466
4
0
null
null
null
null
UTF-8
Python
false
false
2,664
py
#Copyright 2018 Julio Navarro #Built at the University of Strasbourg (France). CSTB team @ ICube laboratory #12/06/2018 from library import * def read_logs(input_filepath): #list_logs = extract_csv_file(input_filepath) list_logs = extract_csv_pandas(input_filepath) return list_logs def read_aasg_set(input_filepath): aasg_set = read_json(input_filepath) return aasg_set["aasgs"] #Para mirar la consistencia de un arbol: #- El id se corresponde con la posicion del nodo en la lista #- Las pheromonas van sumandose hasta la raiz (esto se podria comprobar y forzar) #- Luego ya ver que los caminos esten bien hechos y que sea un DAG #we need to transform the Morwilog aasgs in a Bayesian aasg # print("Transforming aasg to Bayesian") # new_aasg_set = from_morwilog_aasg_to_bayesian(aasg_set) # for aasg in new_aasg_set["aasgs"]: # for node in aasg["nodes"]: # if node["prob"]: # print str(node["id"])+" - "+str(node["ph"])+" - "+str(node["prob"]) # else: # print "NO PROB "+str(node["id"]) # # return new_aasg_set["aasgs"] def initialization_probabilities(aasg_set): for aasg in aasg_set: for arc_set in aasg["arcs"]: num_children = len(arc_set["children"]) for child in arc_set["children"]: child["prob"] = 1.0/float(num_children) return aasg_set def adding_arcs_optional_nodes(aasg_set): for aasg in aasg_set: list_optional_nodes = [] for node in aasg["nodes"]: if "optional" in node and node["optional"]: list_optional_nodes.append(node["id"]) #print "LIST OPTIONALS" #print list_optional_nodes for optional_node_id in list_optional_nodes: #We need to look for the arcs going in and out of that node list_children = [] for arc_set in aasg["arcs"]: if arc_set["start"] == optional_node_id: for child in arc_set["children"]: list_children.append(child["id"]) if len(list_children) > 0: #We add new arcs, directly from parents to children for arc_set in aasg["arcs"]: for child in arc_set["children"]: if child["id"] == optional_node_id: for element in list_children: arc_set["children"].append({"id":element}) break #print list_children return aasg_set def read_parameters(input_filepath): print "Hola"
[ "julio@Julios-MacBook-Air.local" ]
julio@Julios-MacBook-Air.local
9a7d895f2c6bc54344dbcc6750596016612f6474
2831e673f82ee9826db4ba4d82a57c3f2385efa2
/main_app/migrations/0004_remove_profile_picture.py
670a751bf2654057093a834bf061bdffb8cbbc6b
[]
no_license
eag58914/milo_app
2ad181acc4d412138fe821c2728cb1e25e631040
d56e3cb316c2bd6006dc5e4e201cc8ac2e593f32
refs/heads/master
2022-12-11T04:17:04.790085
2019-09-29T23:14:17
2019-09-29T23:14:17
208,075,944
0
0
null
2022-06-21T22:50:57
2019-09-12T14:52:32
Python
UTF-8
Python
false
false
318
py
# Generated by Django 2.2.3 on 2019-09-18 16:45 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('main_app', '0003_photo'), ] operations = [ migrations.RemoveField( model_name='profile', name='picture', ), ]
[ "garciaelco18@gmail.com" ]
garciaelco18@gmail.com
f3614a2279ab77b16499e213168132f1ee24e56e
29937ed4e8df0d512956e3a9fbe2629e805557cf
/betcenter_backend_helper/bet_record/migrations/0006_betrecord_main_contract_txhash.py
c6cc195084cdb7055599ea0d711d12af90efbe0e
[]
no_license
OriginSport/betcenter_backend_helper
8f9ca425852911f9ab59a16735824a09f47f6932
46dc07912260ab244074a935d0b220c3d17b5185
refs/heads/master
2022-12-14T21:03:40.024679
2018-11-09T01:18:21
2018-11-09T01:18:21
136,296,530
0
1
null
2022-11-22T02:31:46
2018-06-06T08:20:19
Python
UTF-8
Python
false
false
482
py
# -*- coding: utf-8 -*- # Generated by Django 1.11.13 on 2018-06-26 17:24 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('bet_record', '0005_auto_20180626_0950'), ] operations = [ migrations.AddField( model_name='betrecord', name='main_contract_txhash', field=models.CharField(default='', max_length=88), ), ]
[ "ywt13639397661@gmail.com" ]
ywt13639397661@gmail.com
11d8170b63de9af3a3b69f40b0315a7120b9b811
005374356757a1cfcbf07ad46fd9e60be1c9dede
/python-django/alıştırmalar/alistirma-3-calculator.py
5d418e175435b50765fce257c79cb123fa6f377a
[]
no_license
teaddict/lyk-2014
e0a76561ad7e620211d2d6931cff38d8f3b4bddd
541d7a45e2b27d8d54941f9bd812cfa96585ae61
refs/heads/master
2020-12-25T19:26:25.453139
2014-08-17T10:54:11
2014-08-17T10:54:11
null
0
0
null
null
null
null
UTF-8
Python
false
false
230
py
__author__ = 'schwappkopf' print"3+5: ",3+5 print"3-5: ",3-5 print"3*5: ",3*5 print"3/5: ",3/5 print"6/4 :", 6/4 #tam sayı girersen tam sayı çıktı verir print"6.0/4.0", 6.0/4.0 #floating point girersen floating point yapar
[ "cyberasker@gmail.com" ]
cyberasker@gmail.com
6713a71ae9b0c94fcd108a4297bc34c3a48cc07c
db1c92b38332a1fc85aa42a6eb9ca6c7fd71288d
/assign2/15.py
ecf22320765202ad0b47af8c3531ef5980633380
[]
no_license
Lishat/Basic-Python-Programming
9edb6cf009bd2ab68e1bc30878cc7f056866c4b1
7561bf9b1e141123768d623745a5a9c8ce76fa9b
refs/heads/master
2020-04-27T10:42:12.511932
2019-03-12T20:30:04
2019-03-12T20:30:04
174,265,897
1
0
null
null
null
null
UTF-8
Python
false
false
238
py
print(sum([i for i in range(int(input())+1)])) print(sum([i for i in range(1, 2*int(input()), 2)])) n = list(map(int, input().split()));print(sum([int(n[i]) for i in range(n.index(999))])) print(sum([1 for x in bin(int(input()))[2:]])-1)
[ "noreply@github.com" ]
Lishat.noreply@github.com
dab29c1e37f7f38a6abff91804a50893a7920802
996193d5abd7df0a52976f4516473b85d98f394f
/weather_display/rain.py
13ac8656e049c8d027bcfd5f13c45ad9e8106b11
[]
no_license
lakomovadiana/weather_lamp
a5d28064b101a051221bfd3c24158db59ae3ee02
ecd23b0a009c70f85340927b72e5b719d8e2f6c4
refs/heads/master
2020-04-09T03:01:11.426613
2018-12-20T06:47:09
2018-12-20T06:47:09
159,965,384
0
0
null
null
null
null
UTF-8
Python
false
false
1,183
py
COLOR_FOREGROUND = 10 def get_frames(): return[[ [0,1,0,0,0,1,0,0], [0,1,0,1,0,1,0,1], [0,0,0,1,0,0,0,1], [1,0,0,0,0,0,0,0], [1,0,1,0,0,0,1,0], [0,0,1,0,1,0,1,0], [0,0,0,0,1,0,0,0], [1,0,0,0,0,0,0,1] ], [ [0,0,1,0,0,0,0,1], [0,1,0,0,0,1,0,0], [0,1,0,1,0,1,0,1], [0,0,0,1,0,0,0,1], [1,0,0,0,0,0,1,0], [1,0,1,0,0,0,1,0], [0,0,1,0,1,0,0,0], [1,0,0,0,1,0,0,0] ], [ [0,0,1,0,1,0,0,1], [0,0,1,0,0,0,0,1], [0,0,0,0,0,1,0,0], [0,1,0,1,0,1,0,1], [0,1,0,1,0,0,0,1], [1,0,1,0,0,0,1,0], [1,0,1,0,0,0,1,0], [0,0,0,0,1,0,0,0] ], [ [1,0,0,0,1,0,0,0], [0,0,1,0,1,0,0,1], [0,0,1,0,0,0,0,1], [0,0,0,0,0,1,0,0], [0,1,0,1,0,1,0,1], [0,1,0,1,0,0,0,1], [1,0,1,0,0,0,1,0], [1,0,1,0,0,0,1,0] ], [ [1,0,0,0,0,0,0,1], [0,0,0,0,1,0,0,0], [1,0,1,0,1,0,0,1], [1,0,1,0,0,0,0,1], [0,0,0,0,0,1,0,0], [0,1,0,1,0,1,0,1], [0,1,0,1,0,0,0,1], [1,0,1,0,0,0,1,0] ]]
[ "diana.lakomova@gmail.com" ]
diana.lakomova@gmail.com
21f2632e0d6d516474ffbb03ac186849c78eb620
f4d6365cb41c14f7a917c6d039fe9b5fb32754cb
/django/crashreport/base/tests.py
96657b8bbf879023f5263a5a95c9c860900688cf
[]
no_license
aybuke/crash
1fb218599155e376d6f619292996e13f087d93c2
2eb9d822012ab96be611f0a3d5718805a198e4d8
refs/heads/master
2021-01-17T11:57:03.015050
2016-05-04T10:06:15
2016-05-04T10:06:15
58,042,119
0
0
null
2016-05-04T10:02:37
2016-05-04T10:02:36
Python
UTF-8
Python
false
false
1,799
py
# -*- Mode: python; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # from django.test import TestCase from .models import Version class VersionModelTest(TestCase): def setUp(self): self.version = Version(major_version=1, minor_version=2, micro_version=3, patch_version=4) def test_version_string(self): self.assertEqual(str(self.version), "Version: 1.2.3.4") def test_version_string_without_product(self): self.assertEqual(self.version.str_without_product(), "1.2.3.4") class VersionManagerTest(TestCase): def setUp(self): self.version = Version(major_version=1, minor_version=2, micro_version=3, patch_version=4) self.version.save() def test_wrong_version_string(self): res = Version.objects.get_by_version_string("2.3.4.5") self.assertEqual(len(res), 0) def test_short_version_string(self): res = Version.objects.get_by_version_string("1.2.3") self.assertEqual(len(res), 1) def test_full_version_string(self): res = Version.objects.get_by_version_string("1.2.3.4") self.assertEqual(len(res), 1) class VersionTest(TestCase): def test_get_filter_params(self): filter_params = Version.get_filter_params('1.2.3', prefix='test_') self.assertEqual(filter_params['test_major_version'], '1') self.assertEqual(filter_params['test_minor_version'], '2') self.assertEqual(filter_params['test_micro_version'], '3') # vim:set shiftwidth=4 softtabstop=4 expandtab: */
[ "markus.mohrhard@googlemail.com" ]
markus.mohrhard@googlemail.com
69aee3c751d9b73cdd1a20bf1ed25acc45f03c86
5c5c87c0649d5e04be760eb4bf4523b794561300
/compra/urls.py
bd659999d6576bc3591868d2e95c229daec704a3
[]
no_license
luisenriquef060/proyf
016d703ac1f8b345e537899d207e68045d4b5696
dffeecd7adbea83f4036b4562f4f01171388139c
refs/heads/master
2021-08-07T19:20:48.387530
2017-11-08T20:47:00
2017-11-08T20:47:00
110,028,228
0
0
null
null
null
null
UTF-8
Python
false
false
420
py
from django.conf.urls import url from . import views urlpatterns = [ url(r'^producto/', views.nuevo, name ="nuevo"), url(r'^vendedor/', views.nuevoU, name ="nuevoU"), url(r'^$', views.home_view, name='home_view'), url(r'^upload$', views.upload_image_view, name='upload_image_view'), #url(r'^media/(?P<path>.*)$', 'django.views.static.serve', { # 'document_root': settings.MEDIA_ROOT}), ]
[ "luisenriquef0609@gmail.com" ]
luisenriquef0609@gmail.com
f2ff8844f555d6d0049b552d80a60b6fccdae90c
efe8ea078ccac8f2a3ba435f239e23492fe5ab3a
/sft/db/sft_meta.py
c1ebe549462d5fb33ce5653a49bb4f021f4c8606
[]
no_license
placiflury/gridmonitor-sft
4cb675c231e943e2ffa3fb5806ca368c230cba2e
f2a3e4295728b71965838fb59360c63e3d485f5e
refs/heads/master
2016-08-05T05:53:13.568210
2012-09-25T11:37:33
2012-09-25T11:37:33
33,272,299
0
0
null
null
null
null
UTF-8
Python
false
false
488
py
""" SQLAlchemy Metadata and Session object """ from sqlalchemy import MetaData __all__ = ['engine', 'metadata', 'Session'] # does not make much sense here... # SQLAlchemy database engine. Updated by ch.smscg.sft.init_model(). engine = None # SQLAlchemy session manager. Updated by ch.smscg.sft.init_model(). Session = None # Global metadata. If you have multiple databases with overlapping table # names, you'll need a metadata for each database. metadata = MetaData()
[ "placi.flury@switch.ch" ]
placi.flury@switch.ch
51f34c3e0287e316f0918f7bae364df3289de792
966ea314bcd64f40bfaea457f914fcedbe26426a
/March-week3/testconversion.py
be419779776866290ed22ba1214ccc83499f7eda
[]
no_license
vandanasen/Python-Projects
30caa85cf87ba712e1307b0441fed2d7fa9298a0
9b24a9f6af0374bb0d6a3a15c05099f49edfd581
refs/heads/master
2020-03-26T00:26:06.067905
2019-03-11T22:58:25
2019-03-11T22:58:25
144,320,263
1
0
null
null
null
null
UTF-8
Python
false
false
480
py
a_list=[1,1,2,3,3] a = tuple(a_list) print(a) b = list(a) print(len(b)) c = set(b) print(len(c)) d=list(c) print(len(d)) e=list(range(1, 11, 1)) print(e) dict = dict([(1,2),(3,4),(5,6),(7,8),(9,10)]) print(dict) t= tuple(list(dict.items())) print(t) v = tuple(dict.keys()) print(v) k = tuple(dict.values()) print(k) s = "antidisestablishmentarianism" print(s) s = sorted(s) print(s) s2="".join(s) print(s2) w = "the quick brown fox jumped over the lazy dog" w = w.split() print(w)
[ "vandy_senthil@yahoo.com" ]
vandy_senthil@yahoo.com
7f9cf2b44780a6c73735f0b55eb8a5f232bd2098
88e2c87d087e30dedda11cad8a2665e89f6ac32c
/tests/contrib/operators/test_opsgenie_alert_operator.py
1b4467bc5a523be4b00ce8c701d2f578da10ece5
[ "Apache-2.0", "BSD-3-Clause", "Python-2.0", "MIT", "BSD-2-Clause" ]
permissive
bigo-sg/airflow
690805b782d3490c5d01047203ee4766f9695cf0
e2933fc90d8fd9aeb61402f7a237778553762a17
refs/heads/master
2020-05-30T19:25:36.289802
2019-07-15T10:14:34
2019-07-15T10:14:34
189,924,188
2
1
Apache-2.0
2019-10-18T06:30:14
2019-06-03T02:50:51
Python
UTF-8
Python
false
false
4,788
py
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. # import unittest from airflow import DAG, configuration from airflow.contrib.operators.opsgenie_alert_operator import OpsgenieAlertOperator from airflow.utils import timezone DEFAULT_DATE = timezone.datetime(2017, 1, 1) class TestOpsgenieAlertOperator(unittest.TestCase): _config = { 'message': 'An example alert message', 'alias': 'Life is too short for no alias', 'description': 'Every alert needs a description', 'responders': [ {'id': '4513b7ea-3b91-438f-b7e4-e3e54af9147c', 'type': 'team'}, {'name': 'NOC', 'type': 'team'}, {'id': 'bb4d9938-c3c2-455d-aaab-727aa701c0d8', 'type': 'user'}, {'username': 'trinity@opsgenie.com', 'type': 'user'}, {'id': 'aee8a0de-c80f-4515-a232-501c0bc9d715', 'type': 'escalation'}, {'name': 'Nightwatch Escalation', 'type': 'escalation'}, {'id': '80564037-1984-4f38-b98e-8a1f662df552', 'type': 'schedule'}, {'name': 'First Responders Schedule', 'type': 'schedule'} ], 'visibleTo': [ {'id': '4513b7ea-3b91-438f-b7e4-e3e54af9147c', 'type': 'team'}, {'name': 'rocket_team', 'type': 'team'}, {'id': 'bb4d9938-c3c2-455d-aaab-727aa701c0d8', 'type': 'user'}, {'username': 'trinity@opsgenie.com', 'type': 'user'} ], 'actions': ['Restart', 'AnExampleAction'], 'tags': ['OverwriteQuietHours', 'Critical'], 'details': {'key1': 'value1', 'key2': 'value2'}, 'entity': 'An example entity', 'source': 'Airflow', 'priority': 'P1', 'user': 'Jesse', 'note': 'Write this down' } expected_payload_dict = { 'message': _config['message'], 'alias': _config['alias'], 'description': _config['description'], 'responders': _config['responders'], 'visibleTo': _config['visibleTo'], 'actions': _config['actions'], 'tags': _config['tags'], 'details': _config['details'], 'entity': _config['entity'], 'source': _config['source'], 'priority': _config['priority'], 'user': _config['user'], 'note': _config['note'] } def setUp(self): configuration.load_test_config() args = { 'owner': 'airflow', 'start_date': DEFAULT_DATE } self.dag = DAG('test_dag_id', default_args=args) def test_build_opsgenie_payload(self): # Given / When operator = OpsgenieAlertOperator( task_id='opsgenie_alert_job', dag=self.dag, **self._config ) payload = operator._build_opsgenie_payload() # Then self.assertEqual(self.expected_payload_dict, payload) def test_properties(self): # Given / When operator = OpsgenieAlertOperator( task_id='opsgenie_alert_job', dag=self.dag, **self._config ) self.assertEqual('opsgenie_default', operator.opsgenie_conn_id) self.assertEqual(self._config['message'], operator.message) self.assertEqual(self._config['alias'], operator.alias) self.assertEqual(self._config['description'], operator.description) self.assertEqual(self._config['responders'], operator.responders) self.assertEqual(self._config['visibleTo'], operator.visibleTo) self.assertEqual(self._config['actions'], operator.actions) self.assertEqual(self._config['tags'], operator.tags) self.assertEqual(self._config['details'], operator.details) self.assertEqual(self._config['entity'], operator.entity) self.assertEqual(self._config['source'], operator.source) self.assertEqual(self._config['priority'], operator.priority) self.assertEqual(self._config['user'], operator.user) self.assertEqual(self._config['note'], operator.note) if __name__ == '__main__': unittest.main()
[ "ash_github@firemirror.com" ]
ash_github@firemirror.com
52809f4b7ab6f0a809ae211b984d338a391be351
59ef2e40d83befce9eb7b839b9b78c61d99fb772
/class_exercises/class_ex3.py
3b79a624735e9bca5a14f0fa7ce3ffcf490cec9c
[]
no_license
ofircohen205/ImageProcessing
039c8b9aa4b113d839a264eba3f5a69b8ef7fe80
b1d69c1cc3c732ac684163813ecfc882a419e456
refs/heads/master
2022-11-27T03:36:53.695827
2020-07-31T17:29:14
2020-07-31T17:29:14
284,092,842
0
0
null
null
null
null
UTF-8
Python
false
false
1,008
py
# Name: Ofir Cohen # ID: 312255847 # Date: 10/11/2019 import cv2 import numpy as np from matplotlib import pyplot as plt def class_histogram(file): img = cv2.imread(file,0) if (img is None): print("faild to read the image") exit plt.imshow(img,cmap='gray') plt.title("Orig Image") plt.show() hist,bins = np.histogram(img.flatten(),256,[0,256]) cdf = hist.cumsum() cdf_normalized = cdf * hist.max()/ cdf.max() plt.plot(cdf_normalized, color = 'b') plt.hist(img.flatten(),256,[0,256], color = 'r') plt.xlim([0,256]) plt.legend(('cdf','histogram'), loc = 'upper left') plt.show() cdf_m = np.ma.masked_equal(cdf,0) cdf_m = (cdf_m - cdf_m.min())*255/(cdf_m.max()-cdf_m.min()) cdf = np.ma.filled(cdf_m,0).astype('uint8') img2 = cdf[img] plt.imshow(img2,cmap='gray') plt.show() def main(): class_histogram('good_image.jpg') class_histogram('bad_image.jpg') if __name__ == "__main__": main()
[ "ofircohen2005@gmail.com" ]
ofircohen2005@gmail.com
206b83e4eef4c8576287a9cd2ab0d85729ac751e
b9aa246866847541704780941c37d4b865454182
/PY/excel_python/excel_py.py
b8ae4b8b2a859b09d3c8d37ba34104b95a56dfc8
[]
no_license
Warmcloud1/python
2c73ef422a7ba49a20a82ae731d9a544a4d2a70f
6928c0a4c445f7f742d9f730149388bbb72c3d0f
refs/heads/master
2020-09-16T19:26:36.629705
2019-11-25T05:30:15
2019-11-25T05:30:15
223,867,774
0
0
null
null
null
null
UTF-8
Python
false
false
4,199
py
'''將ab檔資料做整理成3種 皆有ab存在、只存在a的、只存在b的''' import csv import pandas as pd import numpy as np import time input_file1="a.csv" input_file2="b.csv" write_data='' result_title =[] result_titlea=[] result_titleb=[] same=[] diffa=[] diffb=[] IDb=[] #read two files file1=pd.read_csv(input_file1,encoding='utf8') file2=pd.read_csv(input_file2,encoding='utf8') with open(input_file1,'r',newline = '',encoding='utf8') as filex1: filereadera=csv.reader(filex1) headera=next(filereadera) #counting header and write geadercontent titlea =[n for n in headera if n!=''] titlea[0]=titlea[0].strip('\ufeff') count_headera=len(titlea) with open(input_file2,'r',newline = '',encoding='utf8') as filex2: filereaderb=csv.reader(filex2) headerb=next(filereaderb) #counting header and write geadercontent titleb =[n for n in headerb if n!=''] titleb[0]=titleb[0].strip('\ufeff') count_headerb=len(titleb) l_a=len(file1[titlea[0]]) l_b=len(file2[titleb[0]]) count_a=0 count_b=0 #diffb檔案的title for b in titleb: result_titleb.append(b) diffb.append(result_titleb) #a跟b title若重複,刪除重複者 for a in titlea: n=0 for b in titleb: if a==b: del titleb[n] n += 1 #ab相同檔案title,diffa檔案title for a in titlea: result_title.append(a) result_titlea.append(a) diffa.append(result_titlea) for b in titleb: if b=='身分證號'or b=='身分證' or b =='身份證' or b=='身份證號' or b=='id' or b=='身分證字號' or b=='身份證字號': pass else: result_title.append(b) for a in titlea: if a=='身分證號'or a=='身分證' or a =='身份證' or a=='身份證號' or a=='id' or a=='身分證字號' or a=='身份證字號': IDa =[content for content in file1[a]] break count_a+=1 for b in result_titleb: if b=='身分證號'or b=='身分證' or b =='身份證' or b=='身份證號' or b=='id' or b=='身分證字號' or b=='身份證字號': IDb =[content for content in file2[b]] break count_b+=1 same.append(result_title) count_ac=0 for a in IDa: count_bc=0 same_temp=[] diff_temp=[] for b in IDb: if a==b: for ta in titlea: if type(file1[ta][count_ac])!= str and np.isnan(float(file1[ta][count_ac])): same_temp.append('none') else: same_temp.append(str(file1[ta][count_ac])) bc=0 for tb in titleb: if type(file2[tb][count_bc]) != str and np.isnan(float(file2[tb][count_bc])): same_temp.append('none') else: same_temp.append(str(file2[tb][count_bc])) bc += 1 same.append(same_temp) break elif a!=b and count_bc+1 ==l_b: for ta in titlea: diff_temp.append(str(file1[ta][count_ac])) diffa.append(diff_temp) count_bc += 1 count_ac += 1 count_bc = 0 for b in IDb: count_ac =0 same_temp=[] diff_temp=[] for a in IDa: if a==b: break elif a!=b and count_ac+1 ==l_a: for tb in result_titleb: diff_temp.append(str(file2[tb][count_bc])) diffb.append(diff_temp) count_ac +=1 count_bc += 1 #same diffa diffb with open('ab檔案皆存在者.csv','w',newline='',encoding='utf8') as file: filewriter=csv.writer(file) #filewriter.writerow(write_title(filename)) for row in same: filewriter.writerow(row) with open('僅存在a檔案者.csv','w',newline='',encoding='utf8') as file2: filewriter=csv.writer(file2) #filewriter.writerow(write_title(filename)) for row in diffa: filewriter.writerow(row) with open('僅存在b檔案者.csv','w',newline='',encoding='utf8') as file3: filewriter=csv.writer(file3) #filewriter.writerow(write_title(filename)) for row in diffb: filewriter.writerow(row) print('感謝seafood 讚嘆seafood') time.sleep(3)
[ "noreply@github.com" ]
Warmcloud1.noreply@github.com
a0083cab532c5db426c3e4e1e0041d4f1d5ec536
0cfb5831a748ebd46e438e3ad7e7a09c1d196499
/com/chapter_09/section_04/task_9.4.5_importAllClass.py
92d4e7f85081ee09dbfc6731f3670ef472dcf5a0
[]
no_license
StevenGeGe/pythonFromIntroductionToPractice01
7cfe8cdb4bc5c0ddbe25b44976231d72d9e10108
9d2ba499056b30ded14180e6c4719ee48edd9772
refs/heads/master
2023-02-15T04:08:59.878711
2020-12-28T13:27:55
2020-12-28T13:27:55
310,980,820
0
0
null
null
null
null
UTF-8
Python
false
false
330
py
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2020/11/25 20:34 # @Author : Yong # @Email : Yong_GJ@163.com # @File : task_9.4.5_importAllClass.py # @Software: PyCharm # 导入模块中所有的类 # from module_name import * # 不推荐这样使用。 # 推荐使用:module_name.class_name 语法来访问类
[ "Yong_GJ@163.com" ]
Yong_GJ@163.com
e50c4b25915b37b912a00056ba04f61069c84a16
d641ae55bf417db082dd1236478b1d52a55b149c
/classifier/decode_data.py
db7e46daf21012dfb606c88125c499e5b7e582c8
[ "MIT" ]
permissive
stephichau/qr-file-classifier
cb079e61ccd2e150149faccce9e412940454f846
9525ed01c569603bd42ecb00e579b15e2e4b4c2a
refs/heads/master
2020-03-22T10:25:42.261183
2019-01-14T20:44:48
2019-01-14T20:44:48
139,901,889
0
0
null
null
null
null
UTF-8
Python
false
false
1,859
py
from PIL import Image, ImageDraw, ImageFont, ImageFilter from pyzbar.pyzbar import decode, ZBarSymbol from wand.image import Image as WImage import cv2 import os import numpy as np from .cool_prints import cool_print_decoration QR_RESULTS_DIRECTORY = './Results-{}-{}' """ Based on code found in: https://www.pyimagesearch.com/2018/05/21/an-opencv-barcode-and-qr-code-scanner-with-zbar/ https://github.com/NaturalHistoryMuseum/pyzbar/blob/master/bounding_box_and_polygon.py """ def save_data(image, qr_data): data_split = qr_data.split('_') output_directory = QR_RESULTS_DIRECTORY.format(data_split[0], data_split[-2]) if not os.path.isdir(output_directory): os.mkdir(output_directory) output_path = "{}/{}.png".format(output_directory, qr_data.split('_')[-1]) if not os.path.exists(output_path): print("Saving in {}".format(output_path)) image.save(output_path) def find_and_decode_qr_from_image(path = None, image = None, *args, **kwargs): """ :param path: Represents absolute path of image with qr :return qr_data: Represents data extracted from QR """ kernel = np.ones((2,2),np.uint8) img = cv2.imread(path, cv2.IMREAD_GRAYSCALE) image = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel) # image = cv2.erode(img, kernel, iterations = 1) # image = cv2.dilate(img, kernel, iterations=2) # if not image: # image = Image.open(path).convert('RGB') # draw = ImageDraw.Draw(image) qr_data = '' for qr in decode(image, symbols=[ZBarSymbol.QRCODE]): # print(qr) qr_data = qr.data.decode('utf-8') cool_print_decoration('Decoding:\n{}'.format(qr_data), style='info') return qr_data if __name__ == '__main__': pass # path = 'results/MT/midterm-p4/dalal.png' # print(path) # print(find_and_decode_qr_from_image(path))
[ "schau@uc.cl" ]
schau@uc.cl
c90d5fef2abadfa61948bd5f220b166084bcf0d3
90e3c798716c3671d05bcbdbc3328dc317bd6e34
/18-4Sum/solution.py
a5219621b59a78a7a90a479bae1d696505823b7d
[]
no_license
Shuang0420/LeetCode
d2547b8fc93e8f4e9073982275e69e274649d48c
6d59dd07323cdd8898474d058d1ae9b196910185
refs/heads/master
2020-12-24T08:08:38.082163
2016-10-12T15:33:53
2016-10-12T15:33:53
59,400,754
2
1
null
null
null
null
UTF-8
Python
false
false
1,363
py
class Solution(object): def fourSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[List[int]] """ if len(nums)<4: return [] res=[] nums=sorted(nums) for i in range(len(nums)-3): if i>0 and nums[i]==nums[i-1]: continue res+=self.sum_3(nums[i:],target-nums[i]) return res def sum_3(self,nums,target): if len(nums)<4: return [] res=[] cur=nums[0] nums=nums[1:] for i in range(len(nums)-2): if i>0 and nums[i]==nums[i-1]: continue new_target=target-nums[i] start=i+1 end=len(nums)-1 while start<end: cur_sum=nums[start]+nums[end] if cur_sum>new_target: end-=1 elif cur_sum<new_target: start+=1 else: res.append([cur,nums[i],nums[start],nums[end]]) start+=1 end-=1 while start<end and nums[start]==nums[start-1]: start+=1 while start<end and nums[end]==nums[end+1]: end-=1 return res
[ "252618408@qq.com" ]
252618408@qq.com
0fdaf48fbd50cc85de571a13f3d1ebbe496f2b0a
8f71454f79857b48c89758844b05cdbd361b071f
/tools/run_iter_counts.py
54d53f20b6efa5bc8ed8efd47d6890624e94d4a3
[]
no_license
travisbrady/ocaml-order-book
3c535cc83c8604414684fafbdab90a90a1cb93ae
3cc1dbe435a05608e8cf2fc1d70909b8201ab6a7
refs/heads/master
2020-03-15T02:37:11.610067
2018-05-03T00:58:24
2018-05-03T00:58:24
131,922,084
3
0
null
null
null
null
UTF-8
Python
false
false
971
py
# Script to run a bunch of target sizes through # both the array-based and tree-based implementations # and collect the number of iterations each call to compute_txn # makes through its price_to_size data structure # This requires that both src/ordergrid.ml and experiments/ordermap/ordermap.ml # were compiled to print the iteration counts to stderr import os from commands import getoutput TARGETS = [1, 200] + range(500, 10000+1, 500) OUT_FN = 'iter_counts.csv' def main(): if os.path.exists(OUT_FN): os.unlink(OUT_FN) for target in TARGETS: grid_cmd = "./pricer %d < input_data/pricer.in > output_data/pricer.out.%d 2>>%s" % (target, target, OUT_FN) print grid_cmd out = getoutput(grid_cmd) map_cmd = "experiments/ordermap/pricer %d < input_data/pricer.in > output_data/map.pricer.out.%d 2>>%s" % (target, target, OUT_FN) print map_cmd out = getoutput(map_cmd) if __name__ == '__main__': main()
[ "travis.brady@gmail.com" ]
travis.brady@gmail.com
d8e6b1547489575e6c963f7190627fff521567cc
cac2c04fa7e0a9bc1fbd4fca5be00030f07e01c0
/fundamentals/adv_python/generators/generator_example.py
091ba00daf0fa62a3b4cf341bb2716ab23f83166
[ "Apache-2.0" ]
permissive
davjohnst/fundamentals
b5d27286531f54eb082a98d30dfa5c138bf3dc51
f8aff4621432c3187305dd04563425f54ea08495
refs/heads/master
2021-01-01T16:39:35.315050
2015-11-15T00:32:53
2015-11-15T00:32:53
32,647,134
0
0
null
null
null
null
UTF-8
Python
false
false
188
py
#!/usr/bin/env python class GeneratorExample(object): @classmethod def integer_generator(self, max): i = 0 while i < max: yield i i += 1
[ "dajohnston@ucdavis.edu" ]
dajohnston@ucdavis.edu
8dd37c6432cc16f7168f6f4bc46dfe13e7ba3da3
52a42582f986c6d65db864066400c7143018e42f
/customers/urls.py
912ed6516e5d8ad30645678492c206cd86368d5d
[]
no_license
GokulKrishna091098/MobileProject
bde8fbfa45c19ad8586df2a34d5beeaef3cf79b5
49bed5d01a4692974df77882c3b923d4d8cfe2c3
refs/heads/master
2023-05-02T21:11:43.278594
2021-05-15T13:22:28
2021-05-15T13:22:28
365,950,491
0
0
null
null
null
null
UTF-8
Python
false
false
1,596
py
"""mobileproject URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from .views import user_home,user_list_all_mobiles,user_login,user_logout,user_mobile_details,user_registration,add_to_cart,view_mycart,remove_cart_item,cart_order,user_list_all_orders,cancel_order urlpatterns = [ path('home/',user_home,name="userhome"), path('',user_list_all_mobiles,name="userlist"), path('login',user_login,name="userlogin"), path('logout',user_logout,name="userlogout"), path('mobiledetails/<int:id>',user_mobile_details,name="usermobiledetails"), path('registration',user_registration,name="userregistration"), path('addcart/<int:id>',add_to_cart,name='addcart'), path('mycart',view_mycart,name='mycart'), path('remove/<int:id>',remove_cart_item,name='remove'), path('order/<int:id>',cart_order,name='placeorder'), path('myorders/',user_list_all_orders,name='myorders'), path('cancelorders/<int:id>',cancel_order,name='cancelorders'), ]
[ "gokulkrishnaparavur@gmail.com" ]
gokulkrishnaparavur@gmail.com
17e05a6e57b15e83b5ba009dd6f004f5eefb26ec
2af366df535a7361341df6b138412f1a7f05f0ca
/pgd_splicer/management/commands/crosscheck.py
c62e5dcb784a62cbd257c306bdfbd239d5358df3
[ "Apache-2.0" ]
permissive
GiriB/pgd
c21b4678e1a59b2227f814ebb6fc6abd09570aed
28a23096aca4d669a351a9943dcc06828a2c24c7
refs/heads/master
2021-01-22T01:04:45.442118
2015-06-03T17:50:11
2015-06-03T17:50:11
65,021,565
0
0
null
2016-09-26T13:34:48
2016-08-05T13:42:22
Python
UTF-8
Python
false
false
4,794
py
from django.core.management.base import BaseCommand, CommandError from optparse import make_option from pgd_core.models import Protein, Chain import sys import os class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option('--selection', default=False, help='write selections to FILE'), make_option('--verbose', action='store_true', default=False, help='display verbose output'), ) help = 'Cross-checks database against selection file.' def handle(self, *args, **options): selection = options['selection'] if not selection: raise CommandError('Selection file required!') if not os.path.exists(selection): raise CommandError('Selection file does not exist!') # List of protein codes in database. indb = set(Protein.objects.all().values_list('code', flat=True)) # List of proteins found in file. infile = set([]) # Dict of proteins in database with settings that differ from # those in the selection file. # Key = protein code # Value = Tuple of two elements: file and database settings wrong = {} # Dict of proteins in database with missing chains. # Key = protein code # Value = List of missing chains chains = {} # Iterate through selection file. f = open(selection, 'r') for line in f: try: elems = line.split(' ') code = elems[0] selchains = elems[1] threshold = int(elems[2]) resolution = float(elems[3]) rfactor = float(elems[4]) rfree = float(elems[5]) except ValueError: # Version line only has two entries, we can skip it continue # Append code to list found in file infile.add(code) # If protein found in database, perform remaining checks. if code in indb: protein = Protein.objects.get(code=code) fileset = (code, threshold, resolution, rfactor, rfree) dbset = (protein.code, protein.threshold, protein.resolution, protein.rfactor, protein.rfree) if fileset != dbset: wrong[code] = (fileset, dbset) # Check chains. badchains = [] for selchain in list(selchains): try: chainid = '%s%s' % (code, selchain) chain = protein.chains.get(id=chainid) except Chain.DoesNotExist: badchains.append(selchain) if badchains != []: chains[code] = badchains f.close() # Proteins found in one place but not in the other. notfile = indb.difference(infile) notdb = infile.difference(indb) # Generate report. if len(notfile) == 0: sys.stdout.write('All proteins in the database are in the file.\n') else: sys.stdout.write('Proteins found in the database ' + 'but not in the file: %d\n' % len(notfile)) if options['verbose']: sys.stdout.write(', '.join(sorted(notfile)) + '\n') if len(notdb) == 0: sys.stdout.write('All proteins in the file are in the database.\n') else: sys.stdout.write('Proteins found in the file ' + 'but not in the database: %d\n' % len(notdb)) if options['verbose']: sys.stdout.write(', '.join(sorted(notdb)) + '\n') if len(wrong) == 0: sys.stdout.write('All proteins in the database ' + 'have settings which match the selection file.\n') else: sys.stdout.write('Proteins found in the database ' + 'with incorrect settings: %d\n' % len(wrong)) if options['verbose']: for key in sorted(wrong.iterkeys()): sys.stdout.write(' %s: %s\n' % (key, wrong[key])) if len(chains) == 0: sys.stdout.write('All proteins in the database ' + 'have all chains listed in the selection file.\n') else: sys.stdout.write('Proteins found in the database ' + 'missing chains: %d\n' % len(chains)) if options['verbose']: for key in sorted(chains.iterkeys()): sys.stdout.write(' %s: %s\n' % (key, chains[key]))
[ "jmt@osuosl.org" ]
jmt@osuosl.org
c0db11e07c4ce0f6d9e35bc00596ef41cc7b3d86
6835fce8c9f43f2394c90b50f786214330de9881
/Python-Examples/requests/sync2.py
91d443ec65c006f1186f5d1f517905642ea8aa70
[]
no_license
flufy3d/Code_Snippets
f52a3d6d53596688e6258316089faf73b3f11ee8
6459d41b8e3b55edad3914fcfb75adb5c084a8bd
refs/heads/master
2021-01-22T13:47:03.056217
2014-05-20T22:39:00
2014-05-20T22:39:00
38,432,099
1
1
null
2015-07-02T12:42:54
2015-07-02T12:42:54
null
UTF-8
Python
false
false
424
py
from requests import Session import time session = Session() start_timer = start_of_prog_time = time.time() time_dict = {} for num in xrange(1, 100): response = session.get('http://httpbin.org/get') time_dict[str(num)] = time.time() - start_timer start_timer = time.time() end_time = time.time() for num, t in time_dict.items(): print num, "-->", t print "Total time:", end_time - start_of_prog_time
[ "sd@serdardalgic.org" ]
sd@serdardalgic.org
babdbff65d7df7830fbc35159f977fcaebc87b48
7be7190aeceef43841274518d260bcd92e04e5a7
/Mahouo-Account/sever/app/__init__.py
a0d44f9b8c1ba491d8fa05edb03452397aa3f1ee
[]
no_license
weivis/Mahouo
078c440b41a686d355a49e3fc29175bc225dff2c
81fd6919a884b97cb53ac3e97f1e48d78ddd4e63
refs/heads/master
2020-04-20T16:56:44.813853
2019-02-03T18:47:11
2019-02-03T18:47:11
168,974,099
10
1
null
null
null
null
UTF-8
Python
false
false
956
py
__author__ = 'Ran' from flask import Flask # flask from flask_cache import Cache # cache from flask_login import LoginManager from flask_cors import * from flask_sqlalchemy import SQLAlchemy # sql from datetime import timedelta from app import config # config #实例化app app = Flask(__name__, template_folder='templates', #指定模板路径,可以是相对路径,也可以是绝对路径。 static_folder='static', #指定静态文件前缀,默认静态文件路径同前缀 ) #引入全局配置 app.config.from_object(config) app.permanent_session_lifetime = timedelta(days=7) #跨域密匙 app.secret_key = '\x12my\x0bVO\xeb\xf8\x18\x15\xc5_?\x91\xd7h\x06AC' #配置flasklogin login_manager = LoginManager() login_manager.session_protection = 'strong' login_manager.login_view = 'auth.account_login' login_manager.init_app(app=app) #绑定对象 db = SQLAlchemy(app) cache = Cache(app) cache.init_app(app)
[ "yvban@outlook.com" ]
yvban@outlook.com
703dc8683d7f928f96e719bf5febd0627d683364
9a9e0398f26cee9864d48c4618c0a482e5475e83
/Python/code/top_k_frequent_elements.py
1e0b45c6c2186a3d5aa1760acecb875e104754cb
[]
no_license
CNife/leetcode
92693c653bb41780ee431293286c3e909009e9b0
7cdd61692ecb52dd1613169e80b924dd39d35996
refs/heads/main
2021-06-22T21:22:12.997253
2021-03-18T07:07:15
2021-03-18T07:07:15
206,955,329
0
0
null
null
null
null
UTF-8
Python
false
false
677
py
from collections import defaultdict from heapq import heappush, heapreplace from typing import List, Tuple from leetcode import test, sorted_list def top_k_frequent(nums: List[int], k: int) -> List[int]: counter = defaultdict(lambda: 0) for num in nums: counter[num] += 1 heap: List[Tuple[int, int]] = [] for num, count in counter.items(): if len(heap) < k: heappush(heap, (count, num)) elif heap[0][0] < count: heapreplace(heap, (count, num)) return [t[1] for t in heap] test( top_k_frequent, [ ([1, 1, 1, 2, 2, 3], 2, [1, 2]), ([1], 1, [1]), ], map_func=sorted_list, )
[ "CNife@vip.qq.com" ]
CNife@vip.qq.com
3a28cb12de058506fbf4db14e1d913ed467793ee
de984d43747376d9e18b414037cf278c04ec0bfb
/services/productcategory_service.py
0ac40ed3029f0049312185f7bfc0957c3d4d1cbd
[]
no_license
vaq130/FrameworkApplication
060251845be979b3a91c4c09b90e50dcd2c03df9
473b6da4a3973840300bc1ec83fb740f500ec9de
refs/heads/main
2023-05-31T08:05:33.860428
2021-06-04T22:11:28
2021-06-04T22:11:28
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,801
py
import urllib.parse import uuid from datetime import datetime from py2neo.ogm import GraphObject, Property from data.db_session import db_auth graph = db_auth() class ProductCategory(GraphObject): __primarykey__ = "name" name = Property() shortname = Property() description = Property() created_date = Property() created_by = Property() guid = Property() def __init__(self): self.created_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S') self.guid = str(uuid.uuid4()) def create_product_category(name, shortname, description, guid): productcategory = ProductCategory() productcategory.name = name productcategory.shortname = shortname productcategory.description = description productcategory.created_by = guid graph.create(productcategory) def get_product_categories(): productcategories = graph.run( "MATCH (x:ProductCategory) " "RETURN x.name as name, " "x.shortname as shortname, " "x.description as description" ).data() return productcategories def get_category_products(): products = graph.run( "MATCH (x:Product)-[r:BELONGS_TO]-(y:ProductCategory) " "RETURN x.name as name, " "x.creator as creator, " "x.logo as logo, " "y.name as productcategory" ).data() return products def product_categories(): prod_cat_list = [] pcat = graph.run("MATCH (x:ProductCategory) RETURN x.name as name").data() for p in pcat: prod_cat_list.append(p['name']) return prod_cat_list def belongs_to(guid, category): graph.run(f"MATCH (x:Product), (y:ProductCategory)" f"WHERE x.guid='{guid}'" f"AND y.name='{category}'" f"MERGE (x)-[r:belongs_to]->(y)")
[ "36908151+josh-thurston@users.noreply.github.com" ]
36908151+josh-thurston@users.noreply.github.com
cc19c917d01a11ed1820d6c3d90cd206c1a86770
e5cd16f1260b5f6042af47bf23476ee87ff2c09f
/rlschool/liftsim/tests/qa_test.py
113281188c3f3643bef553bfc2324799e4c6cea4
[ "Apache-2.0" ]
permissive
TuMing/RLSchool
10b1a98f5faf87da40083e9f73fb2a2fd8a79574
1799de1ad0056adf385c5e5dd34be9155e9063e7
refs/heads/master
2020-11-26T04:22:17.225880
2019-12-18T11:13:09
2019-12-18T11:13:09
null
0
0
null
null
null
null
UTF-8
Python
false
false
15,698
py
# Copyright (c) 2018 PaddlePaddle 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. """ qa test for elevators Authors: likejiao(likejiao@baidu.com) Date: 2019/06/16 19:30:16 """ import sys import time import copy import traceback from rlschool.liftsim.environment.env import LiftSim from rlschool.liftsim.environment.mansion.person_generators.generator_proxy import PersonGenerator from rlschool.liftsim.environment.mansion.mansion_config import MansionConfig from rlschool.liftsim.environment.mansion.utils import ElevatorState, MansionState, ElevatorAction from rlschool.liftsim.environment.mansion.mansion_manager import MansionManager from rule_benchmark.dispatcher import Rule_dispatcher fail_flag = False stop_count = 10 def state_check(state, next_state, action): global fail_flag global stop_count try: assert isinstance(state, MansionState) # for e in state.ElevatorStates: for i in range(len(state.ElevatorStates)): ele = copy.deepcopy(state.ElevatorStates[i]) assert isinstance(ele, ElevatorState) next_ele = copy.deepcopy(next_state.ElevatorStates[i]) assert isinstance(next_ele, ElevatorState) act = copy.deepcopy(action[i]) assert isinstance(act, ElevatorAction) # type ele_Floor = ele.Floor ele_Velocity = ele.Velocity ele_LoadWeight = ele.LoadWeight next_ele_Floor = next_ele.Floor next_ele_Velocity = next_ele.Velocity next_ele_LoadWeight = next_ele.LoadWeight assert isinstance(ele_Floor, float) assert isinstance(ele.MaximumFloor, int) assert isinstance(ele_Velocity, float) assert isinstance(ele.MaximumSpeed, float) assert isinstance(ele.Direction, int) assert isinstance(ele.CurrentDispatchTarget, int) assert isinstance(ele.DispatchTargetDirection, int) assert isinstance(ele_LoadWeight, float) assert isinstance(ele.MaximumLoad, int) assert isinstance(ele.OverloadedAlarm, float) assert isinstance(ele.DoorIsOpening, bool) assert isinstance(ele.DoorIsClosing, bool) assert isinstance(ele.ReservedTargetFloors, list) # change ele_Floor = round(ele_Floor, 2) ele_Velocity = round(ele_Velocity, 2) ele_LoadWeight = round(ele_LoadWeight, 2) next_ele_Velocity = round(next_ele_Velocity, 2) ele_Velocity = round(ele_Velocity, 2) next_ele_LoadWeight = round(next_ele_LoadWeight, 2) # range assert ele_Floor > 0 and ele_Floor <= ele.MaximumFloor assert ele_Velocity >= (0 - ele.MaximumSpeed) and ele_Velocity <= ele.MaximumSpeed assert ele.Direction in [-1, 0, 1] assert ele.CurrentDispatchTarget >= -1 and ele.CurrentDispatchTarget <= ele.MaximumFloor assert ele.DispatchTargetDirection in [-1, 1] assert ele_LoadWeight >= 0 and ele_LoadWeight <= ele.MaximumLoad assert ele.OverloadedAlarm >= 0 and ele.OverloadedAlarm <= 2.0 assert ele.DoorState >= 0 and ele.DoorState <= 1 assert ele.DoorIsClosing in [True, False] assert ele.DoorIsOpening in [True, False] for t in ele.ReservedTargetFloors: assert t >= 1 and t <= ele.MaximumFloor #relation if(ele_Velocity == 0 and ele.Direction != 0): assert (ele_Floor % 1) == 0 or \ (ele_Floor % 1 != 0 and next_ele.Direction == 0) if(round(ele_Floor, 1) % 1 != 0 and ele.Direction != 0): assert ele_Velocity != 0 or next_ele_Velocity != 0 or\ next_ele.Direction == 0 or ele_Floor == ele.CurrentDispatchTarget assert (ele.DoorIsClosing and ele.DoorIsOpening) == False if(ele.DoorState < 1 and ele.DoorState > 0): assert (ele.DoorIsClosing or ele.DoorIsOpening) == True assert ele_Floor % 1 == 0 # if(ele.DoorState in [0.0, 1.0]): # assert (ele.DoorIsClosing or ele.DoorIsOpening) == False # ignore if(ele.DoorState in [0.0, 1.0]): if((ele.DoorIsClosing or ele.DoorIsOpening) == True): if(next_ele.DoorState in [0.0, 1.0]): assert (next_ele.DoorIsClosing or next_ele.DoorIsOpening) == False if((ele_Floor % 1 != 0) or ((ele.DoorIsClosing and ele.DoorIsOpening) == True)): assert ele.DoorState == 0.0 assert ele.DoorIsClosing == False or next_ele.DoorIsClosing == False assert ele.DoorIsOpening == False if(ele_Velocity != 0.0 and ele.Direction != 0): assert ele.DoorState == 0.0 if(ele_Velocity != 0.0 and len(ele.ReservedTargetFloors) > 0): assert ele_LoadWeight > 0 if(ele_Velocity != 0.0 and ele_LoadWeight > 0): assert len(ele.ReservedTargetFloors) > 0 if(next_ele.OverloadedAlarm > 0 and ele.OverloadedAlarm == 0): assert next_ele_LoadWeight >= ele.MaximumLoad - 200 if(len(ele.ReservedTargetFloors) != 0): assert ele_LoadWeight >= 20 # dynamic check delta_Floor = round(next_ele_Floor - ele_Floor, 2) assert delta_Floor * next_ele_Velocity >= 0 or delta_Floor * ele_Velocity >= 0 target_list = ele.ReservedTargetFloors[:] # if(ele.CurrentDispatchTarget != 0): # target_list.append(ele.CurrentDispatchTarget) if(delta_Floor > 0 and ele_Velocity != 0.0 and ele_Floor % 1 != 0): # going up min_target = min(target_list) if len(target_list) > 0 else ele.MaximumFloor + 1 assert ele_Floor <= min_target assert next_ele_Velocity > 0 or ele_Velocity > 0 or ele.Direction == 0 if(delta_Floor < 0 and ele_Velocity != 0.0 and ele_Floor % 1 != 0): # going down max_target = max(target_list) if len(target_list) > 0 else 0 assert ele_Floor >= max_target assert next_ele_Velocity < 0 or ele_Velocity < 0 or ele.Direction == 0 # if(delta_Floor == 0): # assert next_ele_Velocity == 0 or ele_Velocity * next_ele_Velocity <= 0 if((next_ele_LoadWeight - ele_LoadWeight) > 0.01): assert ele.DoorState > 0 or ele.DoorIsOpening or ele.DoorIsClosing if((next_ele_LoadWeight - ele_LoadWeight) < -0.01): assert ele.DoorState > 0 or ele.DoorIsOpening or ele.DoorIsClosing if(ele.OverloadedAlarm < next_ele.OverloadedAlarm): assert ele.DoorState > 0 or ele.DoorIsOpening or ele.DoorIsClosing assert len(next_ele.ReservedTargetFloors) == len(ele.ReservedTargetFloors) #????? # assert next_ele_LoadWeight >= ele_LoadWeight # not right if(len(next_ele.ReservedTargetFloors) > len(ele.ReservedTargetFloors)): assert (next_ele_LoadWeight - ele_LoadWeight) >= 0 #!!! assert ele.DoorState > 0 or ele.DoorIsOpening or ele.DoorIsClosing if(len(next_ele.ReservedTargetFloors) < len(ele.ReservedTargetFloors)): # assert (next_ele_LoadWeight - ele_LoadWeight) < 0 # not right assert ele.DoorState > 0 or ele.DoorIsOpening or ele.DoorIsClosing # if(ele.OverloadedAlarm > 0): # assert ele.ReservedTargetFloors == next_ele.ReservedTargetFloors # assert ele_LoadWeight == next_ele_LoadWeight # assert ele.DoorState > 0 or ele.DoorIsOpening or ele.DoorIsClosing if(fail_flag): stop_count -= 1 if(stop_count == 0): print('\n\nSome error appear before several steps, please check\n\n') exit(1) except AssertionError: _, _, tb = sys.exc_info() traceback.print_tb(tb) # Fixed format tb_info = traceback.extract_tb(tb) filename, line, func, text = tb_info[-1] print('An error occurred on line {} in statement {}'.format(line, text)) print('\n========================== ele num: ', i) print('\nlast: ', ele) print('\nthis: ', next_ele) print('\n========================== please check\n\n') fail_flag = True # print('==========================next state') # print_next_state(next_state) # exit(1) def print_state(state, action): assert isinstance(state, MansionState) print('Num\tact\tact.dir\tFloor\t\tMaxF\tV\t\tMaxV\tDir\tTarget\tTDir\tLoad\tMaxL\tOver\tDoor\topening\tclosing\tReservedTargetFloors') i = 0 for i in range(len(state.ElevatorStates)): ele = state.ElevatorStates[i] act = action[i] assert isinstance(ele, ElevatorState) assert isinstance(act, ElevatorAction) print(i,"\t|",act.TargetFloor,"\t|",act.DirectionIndicator,"\t|", '%2.4f'%ele.Floor,"\t|",ele.MaximumFloor,"\t|", '%2.7f'%ele.Velocity,"\t|",ele.MaximumSpeed,"\t|", ele.Direction,"\t|",ele.CurrentDispatchTarget,"\t|",ele.DispatchTargetDirection,"\t|", int(ele.LoadWeight),"\t|",ele.MaximumLoad,"\t|",'%.2f'%ele.OverloadedAlarm,"\t|", ele.DoorState,"\t|",int(ele.DoorIsOpening),"\t|",int(ele.DoorIsClosing),"\t|",ele.ReservedTargetFloors) i += 1 print('------------------RequiringUpwardFloors', state.RequiringUpwardFloors) print('------------------RequiringDownwardFloors', state.RequiringDownwardFloors) print('') # time.sleep(2) def print_next_state(state): assert isinstance(state, MansionState) print('Num\tact\tact.dir\tFloor\t\tMaxF\tV\tMaxV\tDir\tTarget\tTDir\tLoad\tMaxL\tOver\tDoor\topening\tclosing\tRT') i = 0 for i in range(len(state.ElevatorStates)): ele = state.ElevatorStates[i] # act = action[i] assert isinstance(ele, ElevatorState) # assert isinstance(act, ElevatorAction) i += 1 print(i,"\t|",' ',"\t|",' ',"\t|", '%.2f'%ele.Floor,"\t|",ele.MaximumFloor,"\t|", '%.1f'%ele.Velocity,"\t|",ele.MaximumSpeed,"\t|", ele.Direction,"\t|",ele.CurrentDispatchTarget,"\t|",ele.DispatchTargetDirection,"\t|", '%.1f'%ele.LoadWeight,"\t|",ele.MaximumLoad,"\t|",ele.OverloadedAlarm,"\t|", ele.DoorState,"\t|",int(ele.DoorIsOpening),"\t|",int(ele.DoorIsClosing),"\t|",ele.ReservedTargetFloors) print('------------------RequiringUpwardFloors', state.RequiringUpwardFloors) print('------------------RequiringDownwardFloors', state.RequiringDownwardFloors) print('') # time.sleep(2) def run_mansion_main(mansion_env, policy_handle, iteration): last_state = mansion_env.reset() # policy_handle.link_mansion(mansion_env.attribute) # policy_handle.load_settings() i = 0 acc_reward = 0.0 # = copy.deepcopy(mansion_env.state) while i < iteration: i += 1 # state = mansion_env.state action = policy_handle.policy(last_state) state, r, _, _ = mansion_env.step(elevatoraction_to_list(action)) # output_info = policy_handle.feedback(last_state, action, r) acc_reward += r # if(isinstance(output_info, dict) and len(output_info) > 0): # mansion_env.log_notice("%s", output_info) if(i % 3600 == 0): print( "Accumulated Reward: %f, Mansion Status: %s", acc_reward, mansion_env.statistics) acc_reward = 0.0 print_state(state, action) print('reward: %f' % r) state_check(last_state, state, action) last_state = copy.deepcopy(state) # run main program with args def run_qa_test(configfile, iterations, controlpolicy, set_seed=None): print('configfile:', configfile) # configuration file for running elevators print('iterations:', iterations) # total number of iterations print('controlpolicy:', controlpolicy) # policy type: rule_benchmark or others mansion_env = LiftSim(configfile) if(set_seed): mansion_env.seed(set_seed) if controlpolicy == 'rule_benchmark': dispatcher = Rule_dispatcher(mansion_env, iterations) elif controlpolicy == 'rl_benchmark': pass run_mansion_main(mansion_env, dispatcher, iterations) return 0 def run_time_step_abnormal_test(configfile, iterations, controlpolicy, set_seed=None): try: run_qa_test(configfile, iterations, controlpolicy, set_seed=set_seed) except AssertionError: print('run_time_step_abnormal_test pass') def run_action_abnormal_test(action_target_floor, action_target_direction, set_seed): flag = True try: env = LiftSim() if(set_seed): env.seed(set_seed) state = env.reset() action = [ElevatorAction(action_target_floor, action_target_direction) for i in range(4)] next_state, reward, _, _ = env.step(elevatoraction_to_list(action)) except AssertionError: flag = False print('abnormal action: ', action_target_floor, type(action_target_floor) \ , action_target_direction, type(action_target_direction)) print('run_action_abnormal_test pass') if (flag): print('abnormal action: ', action_target_floor, type(action_target_floor) \ , action_target_direction, type(action_target_direction)) print('run_action_abnormal_test fail') assert False def elevatoraction_to_list(action): action_list = [] for a in action: action_list.append(a.TargetFloor) action_list.append(a.DirectionIndicator) return action_list if __name__ == "__main__": if (len(sys.argv) == 2): set_seed = int(sys.argv[1]) else: set_seed = None run_time_step_abnormal_test('rlschool/liftsim/tests/conf/config_time_step_more_than_1.ini', 100, 'rule_benchmark', set_seed) run_action_abnormal_test(-2, 1, set_seed) run_action_abnormal_test(10000, -1, set_seed) run_action_abnormal_test(5.0, 1, set_seed) run_action_abnormal_test('5', 1, set_seed) run_action_abnormal_test(5, 4, set_seed) run_action_abnormal_test(5, '-1', set_seed) run_qa_test('rlschool/liftsim/config.ini', 4000, 'rule_benchmark', set_seed) run_qa_test('rlschool/liftsim/tests/conf/config1.ini', 4000, 'rule_benchmark', set_seed) # 1 elevator run_qa_test('rlschool/liftsim/tests/conf/config2.ini', 4000, 'rule_benchmark', set_seed) # 100 floors 20 elevator 0.3 time_step run_qa_test('rlschool/liftsim/tests/conf/config3.ini', 4000, 'rule_benchmark', set_seed) # quick person generator run_qa_test('rlschool/liftsim/tests/conf/config4.ini', 4000, 'rule_benchmark', set_seed) # 1.0 time_step
[ "1718613239banma@gmail.com" ]
1718613239banma@gmail.com
90970f3d48fde21227c0bd94f0f21861bc28f9aa
c48763cc27bec7a3a5c2a914ad7b045021253d70
/usr/lib64/python2.7/pydoc.py
34a50fa3ef89753ea5ffd9cc97e1d510fa5d1ab1
[]
no_license
ManaWorks/linux-sysroot-aws
4b9b9cdaa22193e5ad411a0fd594c0b0f46c7a9d
d4ca6a8aa9c45a276430865d377cc41387b75272
refs/heads/master
2021-04-03T13:02:07.709400
2020-03-18T22:22:12
2020-03-18T22:22:12
248,356,093
0
0
null
null
null
null
UTF-8
Python
false
false
95,740
py
#! /usr/bin/env python # -*- coding: latin-1 -*- """Generate Python documentation in HTML or text for interactive use. In the Python interpreter, do "from pydoc import help" to provide online help. Calling help(thing) on a Python object documents the object. Or, at the shell command line outside of Python: Run "pydoc <name>" to show documentation on something. <name> may be the name of a function, module, package, or a dotted reference to a class or function within a module or module in a package. If the argument contains a path segment delimiter (e.g. slash on Unix, backslash on Windows) it is treated as the path to a Python source file. Run "pydoc -k <keyword>" to search for a keyword in the synopsis lines of all available modules. Run "pydoc -p <port>" to start an HTTP server on a given port on the local machine to generate documentation web pages. Port number 0 can be used to get an arbitrary unused port. Run "pydoc -w <name>" to write out the HTML documentation for a module to a file named "<name>.html". Module docs for core modules are assumed to be in https://docs.python.org/library/ This can be overridden by setting the PYTHONDOCS environment variable to a different URL or to a local directory containing the Library Reference Manual pages. """ __author__ = "Ka-Ping Yee <ping@lfw.org>" __date__ = "26 February 2001" __version__ = "$Revision: 88564 $" __credits__ = """Guido van Rossum, for an excellent programming language. Tommy Burnette, the original creator of manpy. Paul Prescod, for all his work on onlinehelp. Richard Chamberlain, for the first implementation of textdoc. """ # Known bugs that can't be fixed here: # - imp.load_module() cannot be prevented from clobbering existing # loaded modules, so calling synopsis() on a binary module file # changes the contents of any existing module with the same name. # - If the __file__ attribute on a module is a relative path and # the current directory is changed with os.chdir(), an incorrect # path will be displayed. import sys, imp, os, re, types, inspect, __builtin__, pkgutil, warnings from repr import Repr from string import expandtabs, find, join, lower, split, strip, rfind, rstrip from traceback import extract_tb try: from collections import deque except ImportError: # Python 2.3 compatibility class deque(list): def popleft(self): return self.pop(0) # --------------------------------------------------------- common routines def pathdirs(): """Convert sys.path into a list of absolute, existing, unique paths.""" dirs = [] normdirs = [] for dir in sys.path: dir = os.path.abspath(dir or '.') normdir = os.path.normcase(dir) if normdir not in normdirs and os.path.isdir(dir): dirs.append(dir) normdirs.append(normdir) return dirs def getdoc(object): """Get the doc string or comments for an object.""" result = inspect.getdoc(object) or inspect.getcomments(object) result = _encode(result) return result and re.sub('^ *\n', '', rstrip(result)) or '' def splitdoc(doc): """Split a doc string into a synopsis line (if any) and the rest.""" lines = split(strip(doc), '\n') if len(lines) == 1: return lines[0], '' elif len(lines) >= 2 and not rstrip(lines[1]): return lines[0], join(lines[2:], '\n') return '', join(lines, '\n') def classname(object, modname): """Get a class name and qualify it with a module name if necessary.""" name = object.__name__ if object.__module__ != modname: name = object.__module__ + '.' + name return name def isdata(object): """Check if an object is of a type that probably means it's data.""" return not (inspect.ismodule(object) or inspect.isclass(object) or inspect.isroutine(object) or inspect.isframe(object) or inspect.istraceback(object) or inspect.iscode(object)) def replace(text, *pairs): """Do a series of global replacements on a string.""" while pairs: text = join(split(text, pairs[0]), pairs[1]) pairs = pairs[2:] return text def cram(text, maxlen): """Omit part of a string if needed to make it fit in a maximum length.""" if len(text) > maxlen: pre = max(0, (maxlen-3)//2) post = max(0, maxlen-3-pre) return text[:pre] + '...' + text[len(text)-post:] return text _re_stripid = re.compile(r' at 0x[0-9a-f]{6,16}(>+)$', re.IGNORECASE) def stripid(text): """Remove the hexadecimal id from a Python object representation.""" # The behaviour of %p is implementation-dependent in terms of case. return _re_stripid.sub(r'\1', text) def _is_some_method(obj): return inspect.ismethod(obj) or inspect.ismethoddescriptor(obj) def allmethods(cl): methods = {} for key, value in inspect.getmembers(cl, _is_some_method): methods[key] = 1 for base in cl.__bases__: methods.update(allmethods(base)) # all your base are belong to us for key in methods.keys(): methods[key] = getattr(cl, key) return methods def _split_list(s, predicate): """Split sequence s via predicate, and return pair ([true], [false]). The return value is a 2-tuple of lists, ([x for x in s if predicate(x)], [x for x in s if not predicate(x)]) """ yes = [] no = [] for x in s: if predicate(x): yes.append(x) else: no.append(x) return yes, no def visiblename(name, all=None, obj=None): """Decide whether to show documentation on a variable.""" # Certain special names are redundant. _hidden_names = ('__builtins__', '__doc__', '__file__', '__path__', '__module__', '__name__', '__slots__', '__package__') if name in _hidden_names: return 0 # Private names are hidden, but special names are displayed. if name.startswith('__') and name.endswith('__'): return 1 # Namedtuples have public fields and methods with a single leading underscore if name.startswith('_') and hasattr(obj, '_fields'): return 1 if all is not None: # only document that which the programmer exported in __all__ return name in all else: return not name.startswith('_') def classify_class_attrs(object): """Wrap inspect.classify_class_attrs, with fixup for data descriptors.""" def fixup(data): name, kind, cls, value = data if inspect.isdatadescriptor(value): kind = 'data descriptor' return name, kind, cls, value return map(fixup, inspect.classify_class_attrs(object)) # ----------------------------------------------------- Unicode support helpers try: _unicode = unicode except NameError: # If Python is built without Unicode support, the unicode type # will not exist. Fake one that nothing will match, and make # the _encode function that do nothing. class _unicode(object): pass _encoding = 'ascii' def _encode(text, encoding='ascii'): return text else: import locale _encoding = locale.getpreferredencoding() def _encode(text, encoding=None): if isinstance(text, unicode): return text.encode(encoding or _encoding, 'xmlcharrefreplace') else: return text def _binstr(obj): # Ensure that we have an encoded (binary) string representation of obj, # even if it is a unicode string. if isinstance(obj, _unicode): return obj.encode(_encoding, 'xmlcharrefreplace') return str(obj) # ----------------------------------------------------- module manipulation def ispackage(path): """Guess whether a path refers to a package directory.""" if os.path.isdir(path): for ext in ('.py', '.pyc', '.pyo'): if os.path.isfile(os.path.join(path, '__init__' + ext)): return True return False def source_synopsis(file): line = file.readline() while line[:1] == '#' or not strip(line): line = file.readline() if not line: break line = strip(line) if line[:4] == 'r"""': line = line[1:] if line[:3] == '"""': line = line[3:] if line[-1:] == '\\': line = line[:-1] while not strip(line): line = file.readline() if not line: break result = strip(split(line, '"""')[0]) else: result = None return result def synopsis(filename, cache={}): """Get the one-line summary out of a module file.""" mtime = os.stat(filename).st_mtime lastupdate, result = cache.get(filename, (None, None)) if lastupdate is None or lastupdate < mtime: info = inspect.getmoduleinfo(filename) try: file = open(filename) except IOError: # module can't be opened, so skip it return None if info and 'b' in info[2]: # binary modules have to be imported try: module = imp.load_module('__temp__', file, filename, info[1:]) except: return None result = module.__doc__.splitlines()[0] if module.__doc__ else None del sys.modules['__temp__'] else: # text modules can be directly examined result = source_synopsis(file) file.close() cache[filename] = (mtime, result) return result class ErrorDuringImport(Exception): """Errors that occurred while trying to import something to document it.""" def __init__(self, filename, exc_info): exc, value, tb = exc_info self.filename = filename self.exc = exc self.value = value self.tb = tb def __str__(self): exc = self.exc if type(exc) is types.ClassType: exc = exc.__name__ return 'problem in %s - %s: %s' % (self.filename, exc, self.value) def importfile(path): """Import a Python source file or compiled file given its path.""" magic = imp.get_magic() file = open(path, 'r') if file.read(len(magic)) == magic: kind = imp.PY_COMPILED else: kind = imp.PY_SOURCE file.close() filename = os.path.basename(path) name, ext = os.path.splitext(filename) file = open(path, 'r') try: module = imp.load_module(name, file, path, (ext, 'r', kind)) except: raise ErrorDuringImport(path, sys.exc_info()) file.close() return module def safeimport(path, forceload=0, cache={}): """Import a module; handle errors; return None if the module isn't found. If the module *is* found but an exception occurs, it's wrapped in an ErrorDuringImport exception and reraised. Unlike __import__, if a package path is specified, the module at the end of the path is returned, not the package at the beginning. If the optional 'forceload' argument is 1, we reload the module from disk (unless it's a dynamic extension).""" try: # If forceload is 1 and the module has been previously loaded from # disk, we always have to reload the module. Checking the file's # mtime isn't good enough (e.g. the module could contain a class # that inherits from another module that has changed). if forceload and path in sys.modules: if path not in sys.builtin_module_names: # Avoid simply calling reload() because it leaves names in # the currently loaded module lying around if they're not # defined in the new source file. Instead, remove the # module from sys.modules and re-import. Also remove any # submodules because they won't appear in the newly loaded # module's namespace if they're already in sys.modules. subs = [m for m in sys.modules if m.startswith(path + '.')] for key in [path] + subs: # Prevent garbage collection. cache[key] = sys.modules[key] del sys.modules[key] module = __import__(path) except: # Did the error occur before or after the module was found? (exc, value, tb) = info = sys.exc_info() if path in sys.modules: # An error occurred while executing the imported module. raise ErrorDuringImport(sys.modules[path].__file__, info) elif exc is SyntaxError: # A SyntaxError occurred before we could execute the module. raise ErrorDuringImport(value.filename, info) elif exc is ImportError and extract_tb(tb)[-1][2]=='safeimport': # The import error occurred directly in this function, # which means there is no such module in the path. return None else: # Some other error occurred during the importing process. raise ErrorDuringImport(path, sys.exc_info()) for part in split(path, '.')[1:]: try: module = getattr(module, part) except AttributeError: return None return module # ---------------------------------------------------- formatter base class class Doc: def document(self, object, name=None, *args): """Generate documentation for an object.""" args = (object, name) + args # 'try' clause is to attempt to handle the possibility that inspect # identifies something in a way that pydoc itself has issues handling; # think 'super' and how it is a descriptor (which raises the exception # by lacking a __name__ attribute) and an instance. if inspect.isgetsetdescriptor(object): return self.docdata(*args) if inspect.ismemberdescriptor(object): return self.docdata(*args) try: if inspect.ismodule(object): return self.docmodule(*args) if inspect.isclass(object): return self.docclass(*args) if inspect.isroutine(object): return self.docroutine(*args) except AttributeError: pass if isinstance(object, property): return self.docproperty(*args) return self.docother(*args) def fail(self, object, name=None, *args): """Raise an exception for unimplemented types.""" message = "don't know how to document object%s of type %s" % ( name and ' ' + repr(name), type(object).__name__) raise TypeError, message docmodule = docclass = docroutine = docother = docproperty = docdata = fail def getdocloc(self, object, basedir=os.path.join(sys.exec_prefix, "lib", "python"+sys.version[0:3])): """Return the location of module docs or None""" try: file = inspect.getabsfile(object) except TypeError: file = '(built-in)' docloc = os.environ.get("PYTHONDOCS", "https://docs.python.org/library") basedir = os.path.normcase(basedir) if (isinstance(object, type(os)) and (object.__name__ in ('errno', 'exceptions', 'gc', 'imp', 'marshal', 'posix', 'signal', 'sys', 'thread', 'zipimport') or (file.startswith(basedir) and not file.startswith(os.path.join(basedir, 'site-packages')))) and object.__name__ not in ('xml.etree', 'test.pydoc_mod')): if docloc.startswith(("http://", "https://")): docloc = "%s/%s" % (docloc.rstrip("/"), object.__name__.lower()) else: docloc = os.path.join(docloc, object.__name__.lower() + ".html") else: docloc = None return docloc # -------------------------------------------- HTML documentation generator class HTMLRepr(Repr): """Class for safely making an HTML representation of a Python object.""" def __init__(self): Repr.__init__(self) self.maxlist = self.maxtuple = 20 self.maxdict = 10 self.maxstring = self.maxother = 100 def escape(self, text): return replace(text, '&', '&amp;', '<', '&lt;', '>', '&gt;') def repr(self, object): return Repr.repr(self, object) def repr1(self, x, level): if hasattr(type(x), '__name__'): methodname = 'repr_' + join(split(type(x).__name__), '_') if hasattr(self, methodname): return getattr(self, methodname)(x, level) return self.escape(cram(stripid(repr(x)), self.maxother)) def repr_string(self, x, level): test = cram(x, self.maxstring) testrepr = repr(test) if '\\' in test and '\\' not in replace(testrepr, r'\\', ''): # Backslashes are only literal in the string and are never # needed to make any special characters, so show a raw string. return 'r' + testrepr[0] + self.escape(test) + testrepr[0] return re.sub(r'((\\[\\abfnrtv\'"]|\\[0-9]..|\\x..|\\u....)+)', r'<font color="#c040c0">\1</font>', self.escape(testrepr)) repr_str = repr_string def repr_instance(self, x, level): try: return self.escape(cram(stripid(repr(x)), self.maxstring)) except: return self.escape('<%s instance>' % x.__class__.__name__) repr_unicode = repr_string class HTMLDoc(Doc): """Formatter class for HTML documentation.""" # ------------------------------------------- HTML formatting utilities _repr_instance = HTMLRepr() repr = _repr_instance.repr escape = _repr_instance.escape def page(self, title, contents): """Format an HTML page.""" return _encode(''' <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html><head><title>Python: %s</title> <meta charset="utf-8"> </head><body bgcolor="#f0f0f8"> %s </body></html>''' % (title, contents), 'ascii') def heading(self, title, fgcol, bgcol, extras=''): """Format a page heading.""" return ''' <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading"> <tr bgcolor="%s"> <td valign=bottom>&nbsp;<br> <font color="%s" face="helvetica, arial">&nbsp;<br>%s</font></td ><td align=right valign=bottom ><font color="%s" face="helvetica, arial">%s</font></td></tr></table> ''' % (bgcol, fgcol, title, fgcol, extras or '&nbsp;') def section(self, title, fgcol, bgcol, contents, width=6, prelude='', marginalia=None, gap='&nbsp;'): """Format a section with a heading.""" if marginalia is None: marginalia = '<tt>' + '&nbsp;' * width + '</tt>' result = '''<p> <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section"> <tr bgcolor="%s"> <td colspan=3 valign=bottom>&nbsp;<br> <font color="%s" face="helvetica, arial">%s</font></td></tr> ''' % (bgcol, fgcol, title) if prelude: result = result + ''' <tr bgcolor="%s"><td rowspan=2>%s</td> <td colspan=2>%s</td></tr> <tr><td>%s</td>''' % (bgcol, marginalia, prelude, gap) else: result = result + ''' <tr><td bgcolor="%s">%s</td><td>%s</td>''' % (bgcol, marginalia, gap) return result + '\n<td width="100%%">%s</td></tr></table>' % contents def bigsection(self, title, *args): """Format a section with a big heading.""" title = '<big><strong>%s</strong></big>' % title return self.section(title, *args) def preformat(self, text): """Format literal preformatted text.""" text = self.escape(expandtabs(text)) return replace(text, '\n\n', '\n \n', '\n\n', '\n \n', ' ', '&nbsp;', '\n', '<br>\n') def multicolumn(self, list, format, cols=4): """Format a list of items into a multi-column list.""" result = '' rows = (len(list)+cols-1)//cols for col in range(cols): result = result + '<td width="%d%%" valign=top>' % (100//cols) for i in range(rows*col, rows*col+rows): if i < len(list): result = result + format(list[i]) + '<br>\n' result = result + '</td>' return '<table width="100%%" summary="list"><tr>%s</tr></table>' % result def grey(self, text): return '<font color="#909090">%s</font>' % text def namelink(self, name, *dicts): """Make a link for an identifier, given name-to-URL mappings.""" for dict in dicts: if name in dict: return '<a href="%s">%s</a>' % (dict[name], name) return name def classlink(self, object, modname): """Make a link for a class.""" name, module = object.__name__, sys.modules.get(object.__module__) if hasattr(module, name) and getattr(module, name) is object: return '<a href="%s.html#%s">%s</a>' % ( module.__name__, name, classname(object, modname)) return classname(object, modname) def modulelink(self, object): """Make a link for a module.""" return '<a href="%s.html">%s</a>' % (object.__name__, object.__name__) def modpkglink(self, data): """Make a link for a module or package to display in an index.""" name, path, ispackage, shadowed = data if shadowed: return self.grey(name) if path: url = '%s.%s.html' % (path, name) else: url = '%s.html' % name if ispackage: text = '<strong>%s</strong>&nbsp;(package)' % name else: text = name return '<a href="%s">%s</a>' % (url, text) def markup(self, text, escape=None, funcs={}, classes={}, methods={}): """Mark up some plain text, given a context of symbols to look for. Each context dictionary maps object names to anchor names.""" escape = escape or self.escape results = [] here = 0 pattern = re.compile(r'\b((http|ftp)://\S+[\w/]|' r'RFC[- ]?(\d+)|' r'PEP[- ]?(\d+)|' r'(self\.)?(\w+))') while True: match = pattern.search(text, here) if not match: break start, end = match.span() results.append(escape(text[here:start])) all, scheme, rfc, pep, selfdot, name = match.groups() if scheme: url = escape(all).replace('"', '&quot;') results.append('<a href="%s">%s</a>' % (url, url)) elif rfc: url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc) results.append('<a href="%s">%s</a>' % (url, escape(all))) elif pep: url = 'http://www.python.org/dev/peps/pep-%04d/' % int(pep) results.append('<a href="%s">%s</a>' % (url, escape(all))) elif selfdot: # Create a link for methods like 'self.method(...)' # and use <strong> for attributes like 'self.attr' if text[end:end+1] == '(': results.append('self.' + self.namelink(name, methods)) else: results.append('self.<strong>%s</strong>' % name) elif text[end:end+1] == '(': results.append(self.namelink(name, methods, funcs, classes)) else: results.append(self.namelink(name, classes)) here = end results.append(escape(text[here:])) return join(results, '') # ---------------------------------------------- type-specific routines def formattree(self, tree, modname, parent=None): """Produce HTML for a class tree as given by inspect.getclasstree().""" result = '' for entry in tree: if type(entry) is type(()): c, bases = entry result = result + '<dt><font face="helvetica, arial">' result = result + self.classlink(c, modname) if bases and bases != (parent,): parents = [] for base in bases: parents.append(self.classlink(base, modname)) result = result + '(' + join(parents, ', ') + ')' result = result + '\n</font></dt>' elif type(entry) is type([]): result = result + '<dd>\n%s</dd>\n' % self.formattree( entry, modname, c) return '<dl>\n%s</dl>\n' % result def docmodule(self, object, name=None, mod=None, *ignored): """Produce HTML documentation for a module object.""" name = object.__name__ # ignore the passed-in name try: all = object.__all__ except AttributeError: all = None parts = split(name, '.') links = [] for i in range(len(parts)-1): links.append( '<a href="%s.html"><font color="#ffffff">%s</font></a>' % (join(parts[:i+1], '.'), parts[i])) linkedname = join(links + parts[-1:], '.') head = '<big><big><strong>%s</strong></big></big>' % linkedname try: path = inspect.getabsfile(object) url = path if sys.platform == 'win32': import nturl2path url = nturl2path.pathname2url(path) filelink = '<a href="file:%s">%s</a>' % (url, path) except TypeError: filelink = '(built-in)' info = [] if hasattr(object, '__version__'): version = _binstr(object.__version__) if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': version = strip(version[11:-1]) info.append('version %s' % self.escape(version)) if hasattr(object, '__date__'): info.append(self.escape(_binstr(object.__date__))) if info: head = head + ' (%s)' % join(info, ', ') docloc = self.getdocloc(object) if docloc is not None: docloc = '<br><a href="%(docloc)s">Module Docs</a>' % locals() else: docloc = '' result = self.heading( head, '#ffffff', '#7799ee', '<a href=".">index</a><br>' + filelink + docloc) modules = inspect.getmembers(object, inspect.ismodule) classes, cdict = [], {} for key, value in inspect.getmembers(object, inspect.isclass): # if __all__ exists, believe it. Otherwise use old heuristic. if (all is not None or (inspect.getmodule(value) or object) is object): if visiblename(key, all, object): classes.append((key, value)) cdict[key] = cdict[value] = '#' + key for key, value in classes: for base in value.__bases__: key, modname = base.__name__, base.__module__ module = sys.modules.get(modname) if modname != name and module and hasattr(module, key): if getattr(module, key) is base: if not key in cdict: cdict[key] = cdict[base] = modname + '.html#' + key funcs, fdict = [], {} for key, value in inspect.getmembers(object, inspect.isroutine): # if __all__ exists, believe it. Otherwise use old heuristic. if (all is not None or inspect.isbuiltin(value) or inspect.getmodule(value) is object): if visiblename(key, all, object): funcs.append((key, value)) fdict[key] = '#-' + key if inspect.isfunction(value): fdict[value] = fdict[key] data = [] for key, value in inspect.getmembers(object, isdata): if visiblename(key, all, object): data.append((key, value)) doc = self.markup(getdoc(object), self.preformat, fdict, cdict) doc = doc and '<tt>%s</tt>' % doc result = result + '<p>%s</p>\n' % doc if hasattr(object, '__path__'): modpkgs = [] for importer, modname, ispkg in pkgutil.iter_modules(object.__path__): modpkgs.append((modname, name, ispkg, 0)) modpkgs.sort() contents = self.multicolumn(modpkgs, self.modpkglink) result = result + self.bigsection( 'Package Contents', '#ffffff', '#aa55cc', contents) elif modules: contents = self.multicolumn( modules, lambda key_value, s=self: s.modulelink(key_value[1])) result = result + self.bigsection( 'Modules', '#ffffff', '#aa55cc', contents) if classes: classlist = map(lambda key_value: key_value[1], classes) contents = [ self.formattree(inspect.getclasstree(classlist, 1), name)] for key, value in classes: contents.append(self.document(value, key, name, fdict, cdict)) result = result + self.bigsection( 'Classes', '#ffffff', '#ee77aa', join(contents)) if funcs: contents = [] for key, value in funcs: contents.append(self.document(value, key, name, fdict, cdict)) result = result + self.bigsection( 'Functions', '#ffffff', '#eeaa77', join(contents)) if data: contents = [] for key, value in data: contents.append(self.document(value, key)) result = result + self.bigsection( 'Data', '#ffffff', '#55aa55', join(contents, '<br>\n')) if hasattr(object, '__author__'): contents = self.markup(_binstr(object.__author__), self.preformat) result = result + self.bigsection( 'Author', '#ffffff', '#7799ee', contents) if hasattr(object, '__credits__'): contents = self.markup(_binstr(object.__credits__), self.preformat) result = result + self.bigsection( 'Credits', '#ffffff', '#7799ee', contents) return result def docclass(self, object, name=None, mod=None, funcs={}, classes={}, *ignored): """Produce HTML documentation for a class object.""" realname = object.__name__ name = name or realname bases = object.__bases__ contents = [] push = contents.append # Cute little class to pump out a horizontal rule between sections. class HorizontalRule: def __init__(self): self.needone = 0 def maybe(self): if self.needone: push('<hr>\n') self.needone = 1 hr = HorizontalRule() # List the mro, if non-trivial. mro = deque(inspect.getmro(object)) if len(mro) > 2: hr.maybe() push('<dl><dt>Method resolution order:</dt>\n') for base in mro: push('<dd>%s</dd>\n' % self.classlink(base, object.__module__)) push('</dl>\n') def spill(msg, attrs, predicate): ok, attrs = _split_list(attrs, predicate) if ok: hr.maybe() push(msg) for name, kind, homecls, value in ok: try: value = getattr(object, name) except Exception: # Some descriptors may meet a failure in their __get__. # (bug #1785) push(self._docdescriptor(name, value, mod)) else: push(self.document(value, name, mod, funcs, classes, mdict, object)) push('\n') return attrs def spilldescriptors(msg, attrs, predicate): ok, attrs = _split_list(attrs, predicate) if ok: hr.maybe() push(msg) for name, kind, homecls, value in ok: push(self._docdescriptor(name, value, mod)) return attrs def spilldata(msg, attrs, predicate): ok, attrs = _split_list(attrs, predicate) if ok: hr.maybe() push(msg) for name, kind, homecls, value in ok: base = self.docother(getattr(object, name), name, mod) if (hasattr(value, '__call__') or inspect.isdatadescriptor(value)): doc = getattr(value, "__doc__", None) else: doc = None if doc is None: push('<dl><dt>%s</dl>\n' % base) else: doc = self.markup(getdoc(value), self.preformat, funcs, classes, mdict) doc = '<dd><tt>%s</tt>' % doc push('<dl><dt>%s%s</dl>\n' % (base, doc)) push('\n') return attrs attrs = filter(lambda data: visiblename(data[0], obj=object), classify_class_attrs(object)) mdict = {} for key, kind, homecls, value in attrs: mdict[key] = anchor = '#' + name + '-' + key try: value = getattr(object, name) except Exception: # Some descriptors may meet a failure in their __get__. # (bug #1785) pass try: # The value may not be hashable (e.g., a data attr with # a dict or list value). mdict[value] = anchor except TypeError: pass while attrs: if mro: thisclass = mro.popleft() else: thisclass = attrs[0][2] attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass) if thisclass is __builtin__.object: attrs = inherited continue elif thisclass is object: tag = 'defined here' else: tag = 'inherited from %s' % self.classlink(thisclass, object.__module__) tag += ':<br>\n' # Sort attrs by name. try: attrs.sort(key=lambda t: t[0]) except TypeError: attrs.sort(lambda t1, t2: cmp(t1[0], t2[0])) # 2.3 compat # Pump out the attrs, segregated by kind. attrs = spill('Methods %s' % tag, attrs, lambda t: t[1] == 'method') attrs = spill('Class methods %s' % tag, attrs, lambda t: t[1] == 'class method') attrs = spill('Static methods %s' % tag, attrs, lambda t: t[1] == 'static method') attrs = spilldescriptors('Data descriptors %s' % tag, attrs, lambda t: t[1] == 'data descriptor') attrs = spilldata('Data and other attributes %s' % tag, attrs, lambda t: t[1] == 'data') assert attrs == [] attrs = inherited contents = ''.join(contents) if name == realname: title = '<a name="%s">class <strong>%s</strong></a>' % ( name, realname) else: title = '<strong>%s</strong> = <a name="%s">class %s</a>' % ( name, name, realname) if bases: parents = [] for base in bases: parents.append(self.classlink(base, object.__module__)) title = title + '(%s)' % join(parents, ', ') doc = self.markup(getdoc(object), self.preformat, funcs, classes, mdict) doc = doc and '<tt>%s<br>&nbsp;</tt>' % doc return self.section(title, '#000000', '#ffc8d8', contents, 3, doc) def formatvalue(self, object): """Format an argument default value as text.""" return self.grey('=' + self.repr(object)) def docroutine(self, object, name=None, mod=None, funcs={}, classes={}, methods={}, cl=None): """Produce HTML documentation for a function or method object.""" realname = object.__name__ name = name or realname anchor = (cl and cl.__name__ or '') + '-' + name note = '' skipdocs = 0 if inspect.ismethod(object): imclass = object.im_class if cl: if imclass is not cl: note = ' from ' + self.classlink(imclass, mod) else: if object.im_self is not None: note = ' method of %s instance' % self.classlink( object.im_self.__class__, mod) else: note = ' unbound %s method' % self.classlink(imclass,mod) object = object.im_func if name == realname: title = '<a name="%s"><strong>%s</strong></a>' % (anchor, realname) else: if (cl and realname in cl.__dict__ and cl.__dict__[realname] is object): reallink = '<a href="#%s">%s</a>' % ( cl.__name__ + '-' + realname, realname) skipdocs = 1 else: reallink = realname title = '<a name="%s"><strong>%s</strong></a> = %s' % ( anchor, name, reallink) if inspect.isfunction(object): args, varargs, varkw, defaults = inspect.getargspec(object) argspec = inspect.formatargspec( args, varargs, varkw, defaults, formatvalue=self.formatvalue) if realname == '<lambda>': title = '<strong>%s</strong> <em>lambda</em> ' % name argspec = argspec[1:-1] # remove parentheses else: argspec = '(...)' decl = title + argspec + (note and self.grey( '<font face="helvetica, arial">%s</font>' % note)) if skipdocs: return '<dl><dt>%s</dt></dl>\n' % decl else: doc = self.markup( getdoc(object), self.preformat, funcs, classes, methods) doc = doc and '<dd><tt>%s</tt></dd>' % doc return '<dl><dt>%s</dt>%s</dl>\n' % (decl, doc) def _docdescriptor(self, name, value, mod): results = [] push = results.append if name: push('<dl><dt><strong>%s</strong></dt>\n' % name) if value.__doc__ is not None: doc = self.markup(getdoc(value), self.preformat) push('<dd><tt>%s</tt></dd>\n' % doc) push('</dl>\n') return ''.join(results) def docproperty(self, object, name=None, mod=None, cl=None): """Produce html documentation for a property.""" return self._docdescriptor(name, object, mod) def docother(self, object, name=None, mod=None, *ignored): """Produce HTML documentation for a data object.""" lhs = name and '<strong>%s</strong> = ' % name or '' return lhs + self.repr(object) def docdata(self, object, name=None, mod=None, cl=None): """Produce html documentation for a data descriptor.""" return self._docdescriptor(name, object, mod) def index(self, dir, shadowed=None): """Generate an HTML index for a directory of modules.""" modpkgs = [] if shadowed is None: shadowed = {} for importer, name, ispkg in pkgutil.iter_modules([dir]): modpkgs.append((name, '', ispkg, name in shadowed)) shadowed[name] = 1 modpkgs.sort() contents = self.multicolumn(modpkgs, self.modpkglink) return self.bigsection(dir, '#ffffff', '#ee77aa', contents) # -------------------------------------------- text documentation generator class TextRepr(Repr): """Class for safely making a text representation of a Python object.""" def __init__(self): Repr.__init__(self) self.maxlist = self.maxtuple = 20 self.maxdict = 10 self.maxstring = self.maxother = 100 def repr1(self, x, level): if hasattr(type(x), '__name__'): methodname = 'repr_' + join(split(type(x).__name__), '_') if hasattr(self, methodname): return getattr(self, methodname)(x, level) return cram(stripid(repr(x)), self.maxother) def repr_string(self, x, level): test = cram(x, self.maxstring) testrepr = repr(test) if '\\' in test and '\\' not in replace(testrepr, r'\\', ''): # Backslashes are only literal in the string and are never # needed to make any special characters, so show a raw string. return 'r' + testrepr[0] + test + testrepr[0] return testrepr repr_str = repr_string def repr_instance(self, x, level): try: return cram(stripid(repr(x)), self.maxstring) except: return '<%s instance>' % x.__class__.__name__ class TextDoc(Doc): """Formatter class for text documentation.""" # ------------------------------------------- text formatting utilities _repr_instance = TextRepr() repr = _repr_instance.repr def bold(self, text): """Format a string in bold by overstriking.""" return join(map(lambda ch: ch + '\b' + ch, text), '') def indent(self, text, prefix=' '): """Indent text by prepending a given prefix to each line.""" if not text: return '' lines = split(text, '\n') lines = map(lambda line, prefix=prefix: prefix + line, lines) if lines: lines[-1] = rstrip(lines[-1]) return join(lines, '\n') def section(self, title, contents): """Format a section with a given heading.""" return self.bold(title) + '\n' + rstrip(self.indent(contents)) + '\n\n' # ---------------------------------------------- type-specific routines def formattree(self, tree, modname, parent=None, prefix=''): """Render in text a class tree as returned by inspect.getclasstree().""" result = '' for entry in tree: if type(entry) is type(()): c, bases = entry result = result + prefix + classname(c, modname) if bases and bases != (parent,): parents = map(lambda c, m=modname: classname(c, m), bases) result = result + '(%s)' % join(parents, ', ') result = result + '\n' elif type(entry) is type([]): result = result + self.formattree( entry, modname, c, prefix + ' ') return result def docmodule(self, object, name=None, mod=None): """Produce text documentation for a given module object.""" name = object.__name__ # ignore the passed-in name synop, desc = splitdoc(getdoc(object)) result = self.section('NAME', name + (synop and ' - ' + synop)) try: all = object.__all__ except AttributeError: all = None try: file = inspect.getabsfile(object) except TypeError: file = '(built-in)' result = result + self.section('FILE', file) docloc = self.getdocloc(object) if docloc is not None: result = result + self.section('MODULE DOCS', docloc) if desc: result = result + self.section('DESCRIPTION', desc) classes = [] for key, value in inspect.getmembers(object, inspect.isclass): # if __all__ exists, believe it. Otherwise use old heuristic. if (all is not None or (inspect.getmodule(value) or object) is object): if visiblename(key, all, object): classes.append((key, value)) funcs = [] for key, value in inspect.getmembers(object, inspect.isroutine): # if __all__ exists, believe it. Otherwise use old heuristic. if (all is not None or inspect.isbuiltin(value) or inspect.getmodule(value) is object): if visiblename(key, all, object): funcs.append((key, value)) data = [] for key, value in inspect.getmembers(object, isdata): if visiblename(key, all, object): data.append((key, value)) modpkgs = [] modpkgs_names = set() if hasattr(object, '__path__'): for importer, modname, ispkg in pkgutil.iter_modules(object.__path__): modpkgs_names.add(modname) if ispkg: modpkgs.append(modname + ' (package)') else: modpkgs.append(modname) modpkgs.sort() result = result + self.section( 'PACKAGE CONTENTS', join(modpkgs, '\n')) # Detect submodules as sometimes created by C extensions submodules = [] for key, value in inspect.getmembers(object, inspect.ismodule): if value.__name__.startswith(name + '.') and key not in modpkgs_names: submodules.append(key) if submodules: submodules.sort() result = result + self.section( 'SUBMODULES', join(submodules, '\n')) if classes: classlist = map(lambda key_value: key_value[1], classes) contents = [self.formattree( inspect.getclasstree(classlist, 1), name)] for key, value in classes: contents.append(self.document(value, key, name)) result = result + self.section('CLASSES', join(contents, '\n')) if funcs: contents = [] for key, value in funcs: contents.append(self.document(value, key, name)) result = result + self.section('FUNCTIONS', join(contents, '\n')) if data: contents = [] for key, value in data: contents.append(self.docother(value, key, name, maxlen=70)) result = result + self.section('DATA', join(contents, '\n')) if hasattr(object, '__version__'): version = _binstr(object.__version__) if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': version = strip(version[11:-1]) result = result + self.section('VERSION', version) if hasattr(object, '__date__'): result = result + self.section('DATE', _binstr(object.__date__)) if hasattr(object, '__author__'): result = result + self.section('AUTHOR', _binstr(object.__author__)) if hasattr(object, '__credits__'): result = result + self.section('CREDITS', _binstr(object.__credits__)) return result def docclass(self, object, name=None, mod=None, *ignored): """Produce text documentation for a given class object.""" realname = object.__name__ name = name or realname bases = object.__bases__ def makename(c, m=object.__module__): return classname(c, m) if name == realname: title = 'class ' + self.bold(realname) else: title = self.bold(name) + ' = class ' + realname if bases: parents = map(makename, bases) title = title + '(%s)' % join(parents, ', ') doc = getdoc(object) contents = doc and [doc + '\n'] or [] push = contents.append # List the mro, if non-trivial. mro = deque(inspect.getmro(object)) if len(mro) > 2: push("Method resolution order:") for base in mro: push(' ' + makename(base)) push('') # Cute little class to pump out a horizontal rule between sections. class HorizontalRule: def __init__(self): self.needone = 0 def maybe(self): if self.needone: push('-' * 70) self.needone = 1 hr = HorizontalRule() def spill(msg, attrs, predicate): ok, attrs = _split_list(attrs, predicate) if ok: hr.maybe() push(msg) for name, kind, homecls, value in ok: try: value = getattr(object, name) except Exception: # Some descriptors may meet a failure in their __get__. # (bug #1785) push(self._docdescriptor(name, value, mod)) else: push(self.document(value, name, mod, object)) return attrs def spilldescriptors(msg, attrs, predicate): ok, attrs = _split_list(attrs, predicate) if ok: hr.maybe() push(msg) for name, kind, homecls, value in ok: push(self._docdescriptor(name, value, mod)) return attrs def spilldata(msg, attrs, predicate): ok, attrs = _split_list(attrs, predicate) if ok: hr.maybe() push(msg) for name, kind, homecls, value in ok: if (hasattr(value, '__call__') or inspect.isdatadescriptor(value)): doc = getdoc(value) else: doc = None push(self.docother(getattr(object, name), name, mod, maxlen=70, doc=doc) + '\n') return attrs attrs = filter(lambda data: visiblename(data[0], obj=object), classify_class_attrs(object)) while attrs: if mro: thisclass = mro.popleft() else: thisclass = attrs[0][2] attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass) if thisclass is __builtin__.object: attrs = inherited continue elif thisclass is object: tag = "defined here" else: tag = "inherited from %s" % classname(thisclass, object.__module__) # Sort attrs by name. attrs.sort() # Pump out the attrs, segregated by kind. attrs = spill("Methods %s:\n" % tag, attrs, lambda t: t[1] == 'method') attrs = spill("Class methods %s:\n" % tag, attrs, lambda t: t[1] == 'class method') attrs = spill("Static methods %s:\n" % tag, attrs, lambda t: t[1] == 'static method') attrs = spilldescriptors("Data descriptors %s:\n" % tag, attrs, lambda t: t[1] == 'data descriptor') attrs = spilldata("Data and other attributes %s:\n" % tag, attrs, lambda t: t[1] == 'data') assert attrs == [] attrs = inherited contents = '\n'.join(contents) if not contents: return title + '\n' return title + '\n' + self.indent(rstrip(contents), ' | ') + '\n' def formatvalue(self, object): """Format an argument default value as text.""" return '=' + self.repr(object) def docroutine(self, object, name=None, mod=None, cl=None): """Produce text documentation for a function or method object.""" realname = object.__name__ name = name or realname note = '' skipdocs = 0 if inspect.ismethod(object): imclass = object.im_class if cl: if imclass is not cl: note = ' from ' + classname(imclass, mod) else: if object.im_self is not None: note = ' method of %s instance' % classname( object.im_self.__class__, mod) else: note = ' unbound %s method' % classname(imclass,mod) object = object.im_func if name == realname: title = self.bold(realname) else: if (cl and realname in cl.__dict__ and cl.__dict__[realname] is object): skipdocs = 1 title = self.bold(name) + ' = ' + realname if inspect.isfunction(object): args, varargs, varkw, defaults = inspect.getargspec(object) argspec = inspect.formatargspec( args, varargs, varkw, defaults, formatvalue=self.formatvalue) if realname == '<lambda>': title = self.bold(name) + ' lambda ' argspec = argspec[1:-1] # remove parentheses else: argspec = '(...)' decl = title + argspec + note if skipdocs: return decl + '\n' else: doc = getdoc(object) or '' return decl + '\n' + (doc and rstrip(self.indent(doc)) + '\n') def _docdescriptor(self, name, value, mod): results = [] push = results.append if name: push(self.bold(name)) push('\n') doc = getdoc(value) or '' if doc: push(self.indent(doc)) push('\n') return ''.join(results) def docproperty(self, object, name=None, mod=None, cl=None): """Produce text documentation for a property.""" return self._docdescriptor(name, object, mod) def docdata(self, object, name=None, mod=None, cl=None): """Produce text documentation for a data descriptor.""" return self._docdescriptor(name, object, mod) def docother(self, object, name=None, mod=None, parent=None, maxlen=None, doc=None): """Produce text documentation for a data object.""" repr = self.repr(object) if maxlen: line = (name and name + ' = ' or '') + repr chop = maxlen - len(line) if chop < 0: repr = repr[:chop] + '...' line = (name and self.bold(name) + ' = ' or '') + repr if doc is not None: line += '\n' + self.indent(str(doc)) return line # --------------------------------------------------------- user interfaces def pager(text): """The first time this is called, determine what kind of pager to use.""" global pager pager = getpager() pager(text) def getpager(): """Decide what method to use for paging through text.""" if type(sys.stdout) is not types.FileType: return plainpager if not hasattr(sys.stdin, "isatty"): return plainpager if not sys.stdin.isatty() or not sys.stdout.isatty(): return plainpager if 'PAGER' in os.environ: if sys.platform == 'win32': # pipes completely broken in Windows return lambda text: tempfilepager(plain(text), os.environ['PAGER']) elif os.environ.get('TERM') in ('dumb', 'emacs'): return lambda text: pipepager(plain(text), os.environ['PAGER']) else: return lambda text: pipepager(text, os.environ['PAGER']) if os.environ.get('TERM') in ('dumb', 'emacs'): return plainpager if sys.platform == 'win32' or sys.platform.startswith('os2'): return lambda text: tempfilepager(plain(text), 'more <') if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0: return lambda text: pipepager(text, 'less') import tempfile (fd, filename) = tempfile.mkstemp() os.close(fd) try: if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0: return lambda text: pipepager(text, 'more') else: return ttypager finally: os.unlink(filename) def plain(text): """Remove boldface formatting from text.""" return re.sub('.\b', '', text) def pipepager(text, cmd): """Page through text by feeding it to another program.""" pipe = os.popen(cmd, 'w') try: pipe.write(_encode(text)) pipe.close() except IOError: pass # Ignore broken pipes caused by quitting the pager program. def tempfilepager(text, cmd): """Page through text by invoking a program on a temporary file.""" import tempfile filename = tempfile.mktemp() file = open(filename, 'w') file.write(_encode(text)) file.close() try: os.system(cmd + ' "' + filename + '"') finally: os.unlink(filename) def ttypager(text): """Page through text on a text terminal.""" lines = plain(_encode(plain(text), getattr(sys.stdout, 'encoding', _encoding))).split('\n') try: import tty fd = sys.stdin.fileno() old = tty.tcgetattr(fd) tty.setcbreak(fd) getchar = lambda: sys.stdin.read(1) except (ImportError, AttributeError): tty = None getchar = lambda: sys.stdin.readline()[:-1][:1] try: try: h = int(os.environ.get('LINES', 0)) except ValueError: h = 0 if h <= 1: h = 25 r = inc = h - 1 sys.stdout.write(join(lines[:inc], '\n') + '\n') while lines[r:]: sys.stdout.write('-- more --') sys.stdout.flush() c = getchar() if c in ('q', 'Q'): sys.stdout.write('\r \r') break elif c in ('\r', '\n'): sys.stdout.write('\r \r' + lines[r] + '\n') r = r + 1 continue if c in ('b', 'B', '\x1b'): r = r - inc - inc if r < 0: r = 0 sys.stdout.write('\n' + join(lines[r:r+inc], '\n') + '\n') r = r + inc finally: if tty: tty.tcsetattr(fd, tty.TCSAFLUSH, old) def plainpager(text): """Simply print unformatted text. This is the ultimate fallback.""" sys.stdout.write(_encode(plain(text), getattr(sys.stdout, 'encoding', _encoding))) def describe(thing): """Produce a short description of the given thing.""" if inspect.ismodule(thing): if thing.__name__ in sys.builtin_module_names: return 'built-in module ' + thing.__name__ if hasattr(thing, '__path__'): return 'package ' + thing.__name__ else: return 'module ' + thing.__name__ if inspect.isbuiltin(thing): return 'built-in function ' + thing.__name__ if inspect.isgetsetdescriptor(thing): return 'getset descriptor %s.%s.%s' % ( thing.__objclass__.__module__, thing.__objclass__.__name__, thing.__name__) if inspect.ismemberdescriptor(thing): return 'member descriptor %s.%s.%s' % ( thing.__objclass__.__module__, thing.__objclass__.__name__, thing.__name__) if inspect.isclass(thing): return 'class ' + thing.__name__ if inspect.isfunction(thing): return 'function ' + thing.__name__ if inspect.ismethod(thing): return 'method ' + thing.__name__ if type(thing) is types.InstanceType: return 'instance of ' + thing.__class__.__name__ return type(thing).__name__ def locate(path, forceload=0): """Locate an object by name or dotted path, importing as necessary.""" parts = [part for part in split(path, '.') if part] module, n = None, 0 while n < len(parts): nextmodule = safeimport(join(parts[:n+1], '.'), forceload) if nextmodule: module, n = nextmodule, n + 1 else: break if module: object = module else: object = __builtin__ for part in parts[n:]: try: object = getattr(object, part) except AttributeError: return None return object # --------------------------------------- interactive interpreter interface text = TextDoc() html = HTMLDoc() class _OldStyleClass: pass _OLD_INSTANCE_TYPE = type(_OldStyleClass()) def resolve(thing, forceload=0): """Given an object or a path to an object, get the object and its name.""" if isinstance(thing, str): object = locate(thing, forceload) if object is None: raise ImportError, 'no Python documentation found for %r' % thing return object, thing else: name = getattr(thing, '__name__', None) return thing, name if isinstance(name, str) else None def render_doc(thing, title='Python Library Documentation: %s', forceload=0): """Render text documentation, given an object or a path to an object.""" object, name = resolve(thing, forceload) desc = describe(object) module = inspect.getmodule(object) if name and '.' in name: desc += ' in ' + name[:name.rfind('.')] elif module and module is not object: desc += ' in module ' + module.__name__ if type(object) is _OLD_INSTANCE_TYPE: # If the passed object is an instance of an old-style class, # document its available methods instead of its value. object = object.__class__ elif not (inspect.ismodule(object) or inspect.isclass(object) or inspect.isroutine(object) or inspect.isgetsetdescriptor(object) or inspect.ismemberdescriptor(object) or isinstance(object, property)): # If the passed object is a piece of data or an instance, # document its available methods instead of its value. object = type(object) desc += ' object' return title % desc + '\n\n' + text.document(object, name) def doc(thing, title='Python Library Documentation: %s', forceload=0): """Display text documentation, given an object or a path to an object.""" try: pager(render_doc(thing, title, forceload)) except (ImportError, ErrorDuringImport), value: print value def writedoc(thing, forceload=0): """Write HTML documentation to a file in the current directory.""" try: object, name = resolve(thing, forceload) page = html.page(describe(object), html.document(object, name)) file = open(name + '.html', 'w') file.write(page) file.close() print 'wrote', name + '.html' except (ImportError, ErrorDuringImport), value: print value def writedocs(dir, pkgpath='', done=None): """Write out HTML documentation for all modules in a directory tree.""" if done is None: done = {} for importer, modname, ispkg in pkgutil.walk_packages([dir], pkgpath): writedoc(modname) return class Helper: # These dictionaries map a topic name to either an alias, or a tuple # (label, seealso-items). The "label" is the label of the corresponding # section in the .rst file under Doc/ and an index into the dictionary # in pydoc_data/topics.py. # # CAUTION: if you change one of these dictionaries, be sure to adapt the # list of needed labels in Doc/tools/pyspecific.py and # regenerate the pydoc_data/topics.py file by running # make pydoc-topics # in Doc/ and copying the output file into the Lib/ directory. keywords = { 'and': 'BOOLEAN', 'as': 'with', 'assert': ('assert', ''), 'break': ('break', 'while for'), 'class': ('class', 'CLASSES SPECIALMETHODS'), 'continue': ('continue', 'while for'), 'def': ('function', ''), 'del': ('del', 'BASICMETHODS'), 'elif': 'if', 'else': ('else', 'while for'), 'except': 'try', 'exec': ('exec', ''), 'finally': 'try', 'for': ('for', 'break continue while'), 'from': 'import', 'global': ('global', 'NAMESPACES'), 'if': ('if', 'TRUTHVALUE'), 'import': ('import', 'MODULES'), 'in': ('in', 'SEQUENCEMETHODS2'), 'is': 'COMPARISON', 'lambda': ('lambda', 'FUNCTIONS'), 'not': 'BOOLEAN', 'or': 'BOOLEAN', 'pass': ('pass', ''), 'print': ('print', ''), 'raise': ('raise', 'EXCEPTIONS'), 'return': ('return', 'FUNCTIONS'), 'try': ('try', 'EXCEPTIONS'), 'while': ('while', 'break continue if TRUTHVALUE'), 'with': ('with', 'CONTEXTMANAGERS EXCEPTIONS yield'), 'yield': ('yield', ''), } # Either add symbols to this dictionary or to the symbols dictionary # directly: Whichever is easier. They are merged later. _strprefixes = tuple(p + q for p in ('b', 'r', 'u') for q in ("'", '"')) _symbols_inverse = { 'STRINGS' : ("'", "'''", '"""', '"') + _strprefixes, 'OPERATORS' : ('+', '-', '*', '**', '/', '//', '%', '<<', '>>', '&', '|', '^', '~', '<', '>', '<=', '>=', '==', '!=', '<>'), 'COMPARISON' : ('<', '>', '<=', '>=', '==', '!=', '<>'), 'UNARY' : ('-', '~'), 'AUGMENTEDASSIGNMENT' : ('+=', '-=', '*=', '/=', '%=', '&=', '|=', '^=', '<<=', '>>=', '**=', '//='), 'BITWISE' : ('<<', '>>', '&', '|', '^', '~'), 'COMPLEX' : ('j', 'J') } symbols = { '%': 'OPERATORS FORMATTING', '**': 'POWER', ',': 'TUPLES LISTS FUNCTIONS', '.': 'ATTRIBUTES FLOAT MODULES OBJECTS', '...': 'ELLIPSIS', ':': 'SLICINGS DICTIONARYLITERALS', '@': 'def class', '\\': 'STRINGS', '_': 'PRIVATENAMES', '__': 'PRIVATENAMES SPECIALMETHODS', '`': 'BACKQUOTES', '(': 'TUPLES FUNCTIONS CALLS', ')': 'TUPLES FUNCTIONS CALLS', '[': 'LISTS SUBSCRIPTS SLICINGS', ']': 'LISTS SUBSCRIPTS SLICINGS' } for topic, symbols_ in _symbols_inverse.iteritems(): for symbol in symbols_: topics = symbols.get(symbol, topic) if topic not in topics: topics = topics + ' ' + topic symbols[symbol] = topics topics = { 'TYPES': ('types', 'STRINGS UNICODE NUMBERS SEQUENCES MAPPINGS ' 'FUNCTIONS CLASSES MODULES FILES inspect'), 'STRINGS': ('strings', 'str UNICODE SEQUENCES STRINGMETHODS FORMATTING ' 'TYPES'), 'STRINGMETHODS': ('string-methods', 'STRINGS FORMATTING'), 'FORMATTING': ('formatstrings', 'OPERATORS'), 'UNICODE': ('strings', 'encodings unicode SEQUENCES STRINGMETHODS ' 'FORMATTING TYPES'), 'NUMBERS': ('numbers', 'INTEGER FLOAT COMPLEX TYPES'), 'INTEGER': ('integers', 'int range'), 'FLOAT': ('floating', 'float math'), 'COMPLEX': ('imaginary', 'complex cmath'), 'SEQUENCES': ('typesseq', 'STRINGMETHODS FORMATTING xrange LISTS'), 'MAPPINGS': 'DICTIONARIES', 'FUNCTIONS': ('typesfunctions', 'def TYPES'), 'METHODS': ('typesmethods', 'class def CLASSES TYPES'), 'CODEOBJECTS': ('bltin-code-objects', 'compile FUNCTIONS TYPES'), 'TYPEOBJECTS': ('bltin-type-objects', 'types TYPES'), 'FRAMEOBJECTS': 'TYPES', 'TRACEBACKS': 'TYPES', 'NONE': ('bltin-null-object', ''), 'ELLIPSIS': ('bltin-ellipsis-object', 'SLICINGS'), 'FILES': ('bltin-file-objects', ''), 'SPECIALATTRIBUTES': ('specialattrs', ''), 'CLASSES': ('types', 'class SPECIALMETHODS PRIVATENAMES'), 'MODULES': ('typesmodules', 'import'), 'PACKAGES': 'import', 'EXPRESSIONS': ('operator-summary', 'lambda or and not in is BOOLEAN ' 'COMPARISON BITWISE SHIFTING BINARY FORMATTING POWER ' 'UNARY ATTRIBUTES SUBSCRIPTS SLICINGS CALLS TUPLES ' 'LISTS DICTIONARIES BACKQUOTES'), 'OPERATORS': 'EXPRESSIONS', 'PRECEDENCE': 'EXPRESSIONS', 'OBJECTS': ('objects', 'TYPES'), 'SPECIALMETHODS': ('specialnames', 'BASICMETHODS ATTRIBUTEMETHODS ' 'CALLABLEMETHODS SEQUENCEMETHODS1 MAPPINGMETHODS ' 'SEQUENCEMETHODS2 NUMBERMETHODS CLASSES'), 'BASICMETHODS': ('customization', 'cmp hash repr str SPECIALMETHODS'), 'ATTRIBUTEMETHODS': ('attribute-access', 'ATTRIBUTES SPECIALMETHODS'), 'CALLABLEMETHODS': ('callable-types', 'CALLS SPECIALMETHODS'), 'SEQUENCEMETHODS1': ('sequence-types', 'SEQUENCES SEQUENCEMETHODS2 ' 'SPECIALMETHODS'), 'SEQUENCEMETHODS2': ('sequence-methods', 'SEQUENCES SEQUENCEMETHODS1 ' 'SPECIALMETHODS'), 'MAPPINGMETHODS': ('sequence-types', 'MAPPINGS SPECIALMETHODS'), 'NUMBERMETHODS': ('numeric-types', 'NUMBERS AUGMENTEDASSIGNMENT ' 'SPECIALMETHODS'), 'EXECUTION': ('execmodel', 'NAMESPACES DYNAMICFEATURES EXCEPTIONS'), 'NAMESPACES': ('naming', 'global ASSIGNMENT DELETION DYNAMICFEATURES'), 'DYNAMICFEATURES': ('dynamic-features', ''), 'SCOPING': 'NAMESPACES', 'FRAMES': 'NAMESPACES', 'EXCEPTIONS': ('exceptions', 'try except finally raise'), 'COERCIONS': ('coercion-rules','CONVERSIONS'), 'CONVERSIONS': ('conversions', 'COERCIONS'), 'IDENTIFIERS': ('identifiers', 'keywords SPECIALIDENTIFIERS'), 'SPECIALIDENTIFIERS': ('id-classes', ''), 'PRIVATENAMES': ('atom-identifiers', ''), 'LITERALS': ('atom-literals', 'STRINGS BACKQUOTES NUMBERS ' 'TUPLELITERALS LISTLITERALS DICTIONARYLITERALS'), 'TUPLES': 'SEQUENCES', 'TUPLELITERALS': ('exprlists', 'TUPLES LITERALS'), 'LISTS': ('typesseq-mutable', 'LISTLITERALS'), 'LISTLITERALS': ('lists', 'LISTS LITERALS'), 'DICTIONARIES': ('typesmapping', 'DICTIONARYLITERALS'), 'DICTIONARYLITERALS': ('dict', 'DICTIONARIES LITERALS'), 'BACKQUOTES': ('string-conversions', 'repr str STRINGS LITERALS'), 'ATTRIBUTES': ('attribute-references', 'getattr hasattr setattr ' 'ATTRIBUTEMETHODS'), 'SUBSCRIPTS': ('subscriptions', 'SEQUENCEMETHODS1'), 'SLICINGS': ('slicings', 'SEQUENCEMETHODS2'), 'CALLS': ('calls', 'EXPRESSIONS'), 'POWER': ('power', 'EXPRESSIONS'), 'UNARY': ('unary', 'EXPRESSIONS'), 'BINARY': ('binary', 'EXPRESSIONS'), 'SHIFTING': ('shifting', 'EXPRESSIONS'), 'BITWISE': ('bitwise', 'EXPRESSIONS'), 'COMPARISON': ('comparisons', 'EXPRESSIONS BASICMETHODS'), 'BOOLEAN': ('booleans', 'EXPRESSIONS TRUTHVALUE'), 'ASSERTION': 'assert', 'ASSIGNMENT': ('assignment', 'AUGMENTEDASSIGNMENT'), 'AUGMENTEDASSIGNMENT': ('augassign', 'NUMBERMETHODS'), 'DELETION': 'del', 'PRINTING': 'print', 'RETURNING': 'return', 'IMPORTING': 'import', 'CONDITIONAL': 'if', 'LOOPING': ('compound', 'for while break continue'), 'TRUTHVALUE': ('truth', 'if while and or not BASICMETHODS'), 'DEBUGGING': ('debugger', 'pdb'), 'CONTEXTMANAGERS': ('context-managers', 'with'), } def __init__(self, input=None, output=None): self._input = input self._output = output input = property(lambda self: self._input or sys.stdin) output = property(lambda self: self._output or sys.stdout) def __repr__(self): if inspect.stack()[1][3] == '?': self() return '' return '<pydoc.Helper instance>' _GoInteractive = object() def __call__(self, request=_GoInteractive): if request is not self._GoInteractive: self.help(request) else: self.intro() self.interact() self.output.write(''' You are now leaving help and returning to the Python interpreter. If you want to ask for help on a particular object directly from the interpreter, you can type "help(object)". Executing "help('string')" has the same effect as typing a particular string at the help> prompt. ''') def interact(self): self.output.write('\n') while True: try: request = self.getline('help> ') if not request: break except (KeyboardInterrupt, EOFError): break request = strip(request) # Make sure significant trailing quotation marks of literals don't # get deleted while cleaning input if (len(request) > 2 and request[0] == request[-1] in ("'", '"') and request[0] not in request[1:-1]): request = request[1:-1] if lower(request) in ('q', 'quit'): break self.help(request) def getline(self, prompt): """Read one line, using raw_input when available.""" if self.input is sys.stdin: return raw_input(prompt) else: self.output.write(prompt) self.output.flush() return self.input.readline() def help(self, request): if type(request) is type(''): request = request.strip() if request == 'help': self.intro() elif request == 'keywords': self.listkeywords() elif request == 'symbols': self.listsymbols() elif request == 'topics': self.listtopics() elif request == 'modules': self.listmodules() elif request[:8] == 'modules ': self.listmodules(split(request)[1]) elif request in self.symbols: self.showsymbol(request) elif request in self.keywords: self.showtopic(request) elif request in self.topics: self.showtopic(request) elif request: doc(request, 'Help on %s:') elif isinstance(request, Helper): self() else: doc(request, 'Help on %s:') self.output.write('\n') def intro(self): self.output.write(''' Welcome to Python %s! This is the online help utility. If this is your first time using Python, you should definitely check out the tutorial on the Internet at http://docs.python.org/%s/tutorial/. Enter the name of any module, keyword, or topic to get help on writing Python programs and using Python modules. To quit this help utility and return to the interpreter, just type "quit". To get a list of available modules, keywords, or topics, type "modules", "keywords", or "topics". Each module also comes with a one-line summary of what it does; to list the modules whose summaries contain a given word such as "spam", type "modules spam". ''' % tuple([sys.version[:3]]*2)) def list(self, items, columns=4, width=80): items = items[:] items.sort() colw = width / columns rows = (len(items) + columns - 1) / columns for row in range(rows): for col in range(columns): i = col * rows + row if i < len(items): self.output.write(items[i]) if col < columns - 1: self.output.write(' ' + ' ' * (colw-1 - len(items[i]))) self.output.write('\n') def listkeywords(self): self.output.write(''' Here is a list of the Python keywords. Enter any keyword to get more help. ''') self.list(self.keywords.keys()) def listsymbols(self): self.output.write(''' Here is a list of the punctuation symbols which Python assigns special meaning to. Enter any symbol to get more help. ''') self.list(self.symbols.keys()) def listtopics(self): self.output.write(''' Here is a list of available topics. Enter any topic name to get more help. ''') self.list(self.topics.keys()) def showtopic(self, topic, more_xrefs=''): try: import pydoc_data.topics except ImportError: self.output.write(''' Sorry, topic and keyword documentation is not available because the module "pydoc_data.topics" could not be found. ''') return target = self.topics.get(topic, self.keywords.get(topic)) if not target: self.output.write('no documentation found for %s\n' % repr(topic)) return if type(target) is type(''): return self.showtopic(target, more_xrefs) label, xrefs = target try: doc = pydoc_data.topics.topics[label] except KeyError: self.output.write('no documentation found for %s\n' % repr(topic)) return pager(strip(doc) + '\n') if more_xrefs: xrefs = (xrefs or '') + ' ' + more_xrefs if xrefs: import StringIO, formatter buffer = StringIO.StringIO() formatter.DumbWriter(buffer).send_flowing_data( 'Related help topics: ' + join(split(xrefs), ', ') + '\n') self.output.write('\n%s\n' % buffer.getvalue()) def showsymbol(self, symbol): target = self.symbols[symbol] topic, _, xrefs = target.partition(' ') self.showtopic(topic, xrefs) def listmodules(self, key=''): if key: self.output.write(''' Here is a list of matching modules. Enter any module name to get more help. ''') apropos(key) else: self.output.write(''' Please wait a moment while I gather a list of all available modules... ''') modules = {} def callback(path, modname, desc, modules=modules): if modname and modname[-9:] == '.__init__': modname = modname[:-9] + ' (package)' if find(modname, '.') < 0: modules[modname] = 1 def onerror(modname): callback(None, modname, None) ModuleScanner().run(callback, onerror=onerror) self.list(modules.keys()) self.output.write(''' Enter any module name to get more help. Or, type "modules spam" to search for modules whose descriptions contain the word "spam". ''') help = Helper() class Scanner: """A generic tree iterator.""" def __init__(self, roots, children, descendp): self.roots = roots[:] self.state = [] self.children = children self.descendp = descendp def next(self): if not self.state: if not self.roots: return None root = self.roots.pop(0) self.state = [(root, self.children(root))] node, children = self.state[-1] if not children: self.state.pop() return self.next() child = children.pop(0) if self.descendp(child): self.state.append((child, self.children(child))) return child class ModuleScanner: """An interruptible scanner that searches module synopses.""" def run(self, callback, key=None, completer=None, onerror=None): if key: key = lower(key) self.quit = False seen = {} for modname in sys.builtin_module_names: if modname != '__main__': seen[modname] = 1 if key is None: callback(None, modname, '') else: desc = split(__import__(modname).__doc__ or '', '\n')[0] if find(lower(modname + ' - ' + desc), key) >= 0: callback(None, modname, desc) for importer, modname, ispkg in pkgutil.walk_packages(onerror=onerror): if self.quit: break if key is None: callback(None, modname, '') else: loader = importer.find_module(modname) if hasattr(loader,'get_source'): import StringIO desc = source_synopsis( StringIO.StringIO(loader.get_source(modname)) ) or '' if hasattr(loader,'get_filename'): path = loader.get_filename(modname) else: path = None else: module = loader.load_module(modname) desc = module.__doc__.splitlines()[0] if module.__doc__ else '' path = getattr(module,'__file__',None) if find(lower(modname + ' - ' + desc), key) >= 0: callback(path, modname, desc) if completer: completer() def apropos(key): """Print all the one-line module summaries that contain a substring.""" def callback(path, modname, desc): if modname[-9:] == '.__init__': modname = modname[:-9] + ' (package)' print modname, desc and '- ' + desc def onerror(modname): pass with warnings.catch_warnings(): warnings.filterwarnings('ignore') # ignore problems during import ModuleScanner().run(callback, key, onerror=onerror) # --------------------------------------------------- web browser interface def serve(port, callback=None, completer=None): import BaseHTTPServer, mimetools, select # Patch up mimetools.Message so it doesn't break if rfc822 is reloaded. class Message(mimetools.Message): def __init__(self, fp, seekable=1): Message = self.__class__ Message.__bases__[0].__bases__[0].__init__(self, fp, seekable) self.encodingheader = self.getheader('content-transfer-encoding') self.typeheader = self.getheader('content-type') self.parsetype() self.parseplist() class DocHandler(BaseHTTPServer.BaseHTTPRequestHandler): def send_document(self, title, contents): try: self.send_response(200) self.send_header('Content-Type', 'text/html') self.end_headers() self.wfile.write(html.page(title, contents)) except IOError: pass def do_GET(self): path = self.path if path[-5:] == '.html': path = path[:-5] if path[:1] == '/': path = path[1:] if path and path != '.': try: obj = locate(path, forceload=1) except ErrorDuringImport, value: self.send_document(path, html.escape(str(value))) return if obj: self.send_document(describe(obj), html.document(obj, path)) else: self.send_document(path, 'no Python documentation found for %s' % repr(path)) else: heading = html.heading( '<big><big><strong>Python: Index of Modules</strong></big></big>', '#ffffff', '#7799ee') def bltinlink(name): return '<a href="%s.html">%s</a>' % (name, name) names = filter(lambda x: x != '__main__', sys.builtin_module_names) contents = html.multicolumn(names, bltinlink) indices = ['<p>' + html.bigsection( 'Built-in Modules', '#ffffff', '#ee77aa', contents)] seen = {} for dir in sys.path: indices.append(html.index(dir, seen)) contents = heading + join(indices) + '''<p align=right> <font color="#909090" face="helvetica, arial"><strong> pydoc</strong> by Ka-Ping Yee &lt;ping@lfw.org&gt;</font>''' self.send_document('Index of Modules', contents) def log_message(self, *args): pass class DocServer(BaseHTTPServer.HTTPServer): def __init__(self, port, callback): host = 'localhost' self.address = (host, port) self.callback = callback self.base.__init__(self, self.address, self.handler) def serve_until_quit(self): import select self.quit = False while not self.quit: rd, wr, ex = select.select([self.socket.fileno()], [], [], 1) if rd: self.handle_request() def server_activate(self): self.base.server_activate(self) self.url = 'http://%s:%d/' % (self.address[0], self.server_port) if self.callback: self.callback(self) DocServer.base = BaseHTTPServer.HTTPServer DocServer.handler = DocHandler DocHandler.MessageClass = Message try: try: DocServer(port, callback).serve_until_quit() except (KeyboardInterrupt, select.error): pass finally: if completer: completer() # ----------------------------------------------------- graphical interface def gui(): """Graphical interface (starts web server and pops up a control window).""" class GUI: def __init__(self, window, port=7464): self.window = window self.server = None self.scanner = None import Tkinter self.server_frm = Tkinter.Frame(window) self.title_lbl = Tkinter.Label(self.server_frm, text='Starting server...\n ') self.open_btn = Tkinter.Button(self.server_frm, text='open browser', command=self.open, state='disabled') self.quit_btn = Tkinter.Button(self.server_frm, text='quit serving', command=self.quit, state='disabled') self.search_frm = Tkinter.Frame(window) self.search_lbl = Tkinter.Label(self.search_frm, text='Search for') self.search_ent = Tkinter.Entry(self.search_frm) self.search_ent.bind('<Return>', self.search) self.stop_btn = Tkinter.Button(self.search_frm, text='stop', pady=0, command=self.stop, state='disabled') if sys.platform == 'win32': # Trying to hide and show this button crashes under Windows. self.stop_btn.pack(side='right') self.window.title('pydoc') self.window.protocol('WM_DELETE_WINDOW', self.quit) self.title_lbl.pack(side='top', fill='x') self.open_btn.pack(side='left', fill='x', expand=1) self.quit_btn.pack(side='right', fill='x', expand=1) self.server_frm.pack(side='top', fill='x') self.search_lbl.pack(side='left') self.search_ent.pack(side='right', fill='x', expand=1) self.search_frm.pack(side='top', fill='x') self.search_ent.focus_set() font = ('helvetica', sys.platform == 'win32' and 8 or 10) self.result_lst = Tkinter.Listbox(window, font=font, height=6) self.result_lst.bind('<Button-1>', self.select) self.result_lst.bind('<Double-Button-1>', self.goto) self.result_scr = Tkinter.Scrollbar(window, orient='vertical', command=self.result_lst.yview) self.result_lst.config(yscrollcommand=self.result_scr.set) self.result_frm = Tkinter.Frame(window) self.goto_btn = Tkinter.Button(self.result_frm, text='go to selected', command=self.goto) self.hide_btn = Tkinter.Button(self.result_frm, text='hide results', command=self.hide) self.goto_btn.pack(side='left', fill='x', expand=1) self.hide_btn.pack(side='right', fill='x', expand=1) self.window.update() self.minwidth = self.window.winfo_width() self.minheight = self.window.winfo_height() self.bigminheight = (self.server_frm.winfo_reqheight() + self.search_frm.winfo_reqheight() + self.result_lst.winfo_reqheight() + self.result_frm.winfo_reqheight()) self.bigwidth, self.bigheight = self.minwidth, self.bigminheight self.expanded = 0 self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight)) self.window.wm_minsize(self.minwidth, self.minheight) self.window.tk.willdispatch() import threading threading.Thread( target=serve, args=(port, self.ready, self.quit)).start() def ready(self, server): self.server = server self.title_lbl.config( text='Python documentation server at\n' + server.url) self.open_btn.config(state='normal') self.quit_btn.config(state='normal') def open(self, event=None, url=None): url = url or self.server.url try: import webbrowser webbrowser.open(url) except ImportError: # pre-webbrowser.py compatibility if sys.platform == 'win32': os.system('start "%s"' % url) else: rc = os.system('netscape -remote "openURL(%s)" &' % url) if rc: os.system('netscape "%s" &' % url) def quit(self, event=None): if self.server: self.server.quit = 1 self.window.quit() def search(self, event=None): key = self.search_ent.get() self.stop_btn.pack(side='right') self.stop_btn.config(state='normal') self.search_lbl.config(text='Searching for "%s"...' % key) self.search_ent.forget() self.search_lbl.pack(side='left') self.result_lst.delete(0, 'end') self.goto_btn.config(state='disabled') self.expand() import threading if self.scanner: self.scanner.quit = 1 self.scanner = ModuleScanner() def onerror(modname): pass threading.Thread(target=self.scanner.run, args=(self.update, key, self.done), kwargs=dict(onerror=onerror)).start() def update(self, path, modname, desc): if modname[-9:] == '.__init__': modname = modname[:-9] + ' (package)' self.result_lst.insert('end', modname + ' - ' + (desc or '(no description)')) def stop(self, event=None): if self.scanner: self.scanner.quit = 1 self.scanner = None def done(self): self.scanner = None self.search_lbl.config(text='Search for') self.search_lbl.pack(side='left') self.search_ent.pack(side='right', fill='x', expand=1) if sys.platform != 'win32': self.stop_btn.forget() self.stop_btn.config(state='disabled') def select(self, event=None): self.goto_btn.config(state='normal') def goto(self, event=None): selection = self.result_lst.curselection() if selection: modname = split(self.result_lst.get(selection[0]))[0] self.open(url=self.server.url + modname + '.html') def collapse(self): if not self.expanded: return self.result_frm.forget() self.result_scr.forget() self.result_lst.forget() self.bigwidth = self.window.winfo_width() self.bigheight = self.window.winfo_height() self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight)) self.window.wm_minsize(self.minwidth, self.minheight) self.expanded = 0 def expand(self): if self.expanded: return self.result_frm.pack(side='bottom', fill='x') self.result_scr.pack(side='right', fill='y') self.result_lst.pack(side='top', fill='both', expand=1) self.window.wm_geometry('%dx%d' % (self.bigwidth, self.bigheight)) self.window.wm_minsize(self.minwidth, self.bigminheight) self.expanded = 1 def hide(self, event=None): self.stop() self.collapse() import Tkinter try: root = Tkinter.Tk() # Tk will crash if pythonw.exe has an XP .manifest # file and the root has is not destroyed explicitly. # If the problem is ever fixed in Tk, the explicit # destroy can go. try: gui = GUI(root) root.mainloop() finally: root.destroy() except KeyboardInterrupt: pass # -------------------------------------------------- command-line interface def ispath(x): return isinstance(x, str) and find(x, os.sep) >= 0 def cli(): """Command-line interface (looks at sys.argv to decide what to do).""" import getopt class BadUsage: pass # Scripts don't get the current directory in their path by default # unless they are run with the '-m' switch if '' not in sys.path: scriptdir = os.path.dirname(sys.argv[0]) if scriptdir in sys.path: sys.path.remove(scriptdir) sys.path.insert(0, '.') try: opts, args = getopt.getopt(sys.argv[1:], 'gk:p:w') writing = 0 for opt, val in opts: if opt == '-g': gui() return if opt == '-k': apropos(val) return if opt == '-p': try: port = int(val) except ValueError: raise BadUsage def ready(server): print 'pydoc server ready at %s' % server.url def stopped(): print 'pydoc server stopped' serve(port, ready, stopped) return if opt == '-w': writing = 1 if not args: raise BadUsage for arg in args: if ispath(arg) and not os.path.exists(arg): print 'file %r does not exist' % arg break try: if ispath(arg) and os.path.isfile(arg): arg = importfile(arg) if writing: if ispath(arg) and os.path.isdir(arg): writedocs(arg) else: writedoc(arg) else: help.help(arg) except ErrorDuringImport, value: print value except (getopt.error, BadUsage): cmd = os.path.basename(sys.argv[0]) print """pydoc - the Python documentation tool %s <name> ... Show text documentation on something. <name> may be the name of a Python keyword, topic, function, module, or package, or a dotted reference to a class or function within a module or module in a package. If <name> contains a '%s', it is used as the path to a Python source file to document. If name is 'keywords', 'topics', or 'modules', a listing of these things is displayed. %s -k <keyword> Search for a keyword in the synopsis lines of all available modules. %s -p <port> Start an HTTP server on the given port on the local machine. Port number 0 can be used to get an arbitrary unused port. %s -w <name> ... Write out the HTML documentation for a module to a file in the current directory. If <name> contains a '%s', it is treated as a filename; if it names a directory, documentation is written for all the contents. """ % (cmd, os.sep, cmd, cmd, cmd, os.sep) if __name__ == '__main__': cli()
[ "brett@beevik.com" ]
brett@beevik.com
68b5fbfd70ebf9d20d9cb182f8ae450b3d3ecd4b
046b03f5fd851e44cff2b082ca827a9deeb97673
/helpers/jpgCombinate/jpg_combinate.py
55f8b50a20a50feb1baff9d36949296a76c46444
[ "MIT" ]
permissive
bartlomiejszozda/handwrittenPairsGenerator
3f7ab4050d0d849f54e20a76e1689017a55e5bbc
d961ba50c7dbd2dca2b927a909ec3a0319b0ef19
refs/heads/master
2022-12-26T19:40:21.150632
2020-10-13T22:53:58
2020-10-13T22:53:58
302,763,200
0
0
null
null
null
null
UTF-8
Python
false
false
1,453
py
import os import sys from PIL import Image def combinateImages(pathToRead, pathToSave, maxNumOfImages): for dir1 in range(0, 9, 2): dir2 = dir1 + 1 if not os.path.exists(pathToSave + "/%d_%d" % (dir1, dir2)): os.makedirs(pathToSave + "/%d_%d" % (dir1, dir2)) for num in range(1,(maxNumOfImages+1)): images = map(Image.open, [pathToRead + r"/%d/ (%d).png" % (dir1, num), pathToRead + r"/%d/ (%d).png" % (dir2, num)]) widths, heights = zip(*(i.size for i in images)) total_width = sum(widths) max_height = max(heights) new_im = Image.new('L', (total_width, max_height)) x_offset = 0 for im in images: new_im.paste(im, (x_offset,0)) x_offset += im.size[0] new_im.save(pathToSave + "/%d_%d/ (%d).png" % (dir1, dir2, num)) pathToBaseDir = r"C:/Users/szozda/thesis/newGans/gans/png_mnist_png_converter" pathToRead = pathToBaseDir + r"/mnist_png-master/mnist_png/testing" pathToSave = pathToBaseDir + r"/mnist_png-master/mnist_png/testing_combined" maxNumOfImages = 892 combinateImages(pathToRead, pathToSave, maxNumOfImages) pathToRead = pathToBaseDir + r"/mnist_png-master/mnist_png/training" pathToSave = pathToBaseDir + r"/mnist_png-master/mnist_png/training_combined" maxNumOfImages = 5421 combinateImages(pathToRead, pathToSave, maxNumOfImages)
[ "bartekszozda19@gmail.com" ]
bartekszozda19@gmail.com
75da804ca07696000eef7093285146f5674f7c8d
fd8e515371e8559db0e1d07c15af3e955b61794e
/airbnb/1_Airbnb_WebScraping.py
c97d9f78836700e0e4f167e70b4f2a94c5e43227
[]
no_license
Mitoflyboy/scraping
8458a9fd9d01e0fc2118fc80260635051935dbe9
1819268760ddbe21b72ae1eb8da1484ee0f8bf8f
refs/heads/master
2021-04-28T17:10:38.968041
2018-06-28T11:53:30
2018-06-28T11:53:30
121,847,168
0
0
null
null
null
null
UTF-8
Python
false
false
12,164
py
# coding: utf-8 # In[1]: import sysconfig import os import numpy as np import pandas as pd import json import distutils import scrapy import datetime import requests import json import logging import string import re from scrapy.crawler import CrawlerProcess from scrapy.selector import Selector from requests import Request from math import sin, cos, sqrt, atan2, radians from decimal import Decimal import math from collections import Counter # approximate radius of earth in km R = 6373.0 # In[2]: class Airbnb_Listing(scrapy.Item): property_id = scrapy.Field() lat = scrapy.Field() lng = scrapy.Field() init_price = scrapy.Field() guests = scrapy.Field() heading = scrapy.Field() description_full = scrapy.Field() description_wc = scrapy.Field() url = scrapy.Field() bedrooms = scrapy.Field() beds = scrapy.Field() bathrooms = scrapy.Field() property_type = scrapy.Field() reviews = scrapy.Field() #rating = scrapy.Field() #suburb = scrapy.Field() #postcode = scrapy.Field() #google_addr = scrapy.Field() #house_specs = scrapy.Field() scraped_date = scrapy.Field() syd_brg_deg = scrapy.Field() syd_brg = scrapy.Field() syd_dist_km = scrapy.Field() # In[3]: # In[4]: # http://www.thecodeknight.com/post_categories/search/posts/scrapy_python class AirbnbSpider(scrapy.Spider): name = 'airbnb_crawler' # Full scrape - NSW start_urls = ['https://www.airbnb.com.au/s/NSW/'] custom_settings = { 'LOG_LEVEL': logging.WARNING, #'ITEM_PIPELINES': {'__main__.JsonWriterPipeline': 1}, #Used for pipeline 1 'FEED_FORMAT':'json', # Used for pipeline 2 'FEED_URI': '/Users/taj/GitHub/scraping/airbnb/WebData/nsw_extract/airbnb_nsw_extract_' + datetime.datetime.now().strftime("%Y-%m-%d") + '.json' #Used for pipeline 2 } url_pages = [] # Filter the description and get the word count def description_word_count(self, text): # Cleaning text for char in '-.,\n': text=text.replace(char,' ') # All words lower case text = text.lower() # split returns a list of words delimited by sequences of whitespace (including tabs, newlines, etc, like re's \s) word_list = text.split() cn = Counter(word_list).most_common() tot = sum(Counter(cn).values()) return tot def calculate_initial_compass_bearing(self, pointA, pointB): """ Calculates the bearing between two points. The formulae used is the following: θ = atan2(sin(Δlong).cos(lat2), cos(lat1).sin(lat2) − sin(lat1).cos(lat2).cos(Δlong)) :Parameters: - `pointA: The tuple representing the latitude/longitude for the first point. Latitude and longitude must be in decimal degrees - `pointB: The tuple representing the latitude/longitude for the second point. Latitude and longitude must be in decimal degrees :Returns: The bearing in degrees :Returns Type: float """ if (type(pointA) != tuple) or (type(pointB) != tuple): raise TypeError("Only tuples are supported as arguments") lat1 = math.radians(pointA[0]) lat2 = math.radians(pointB[0]) lon1 = math.radians(pointA[1]) lon2 = math.radians(pointB[1]) diffLong = math.radians(pointB[1] - pointA[1]) x = math.sin(diffLong) * math.cos(lat2) y = math.cos(lat1) * math.sin(lat2) - (math.sin(lat1) * math.cos(lat2) * math.cos(diffLong)) initial_bearing = math.atan2(x, y) # Now we have the initial bearing but math.atan2 return values # from -180° to + 180° which is not what we want for a compass bearing # The solution is to normalize the initial bearing as shown below initial_bearing = math.degrees(initial_bearing) compass_bearing = (initial_bearing + 360) % 360 # Calculate the straight line distance in km dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2 c = 2 * atan2(sqrt(a), sqrt(1 - a)) syd_distance_km = int(R * c) if compass_bearing >= 0.00 and compass_bearing < 22.50: compass_dir = 'N' elif compass_bearing >= 22.50 and compass_bearing < 67.5: compass_dir = 'NE' elif compass_bearing >= 67.5 and compass_bearing < 112.50: compass_dir = 'E' elif compass_bearing >= 112.5 and compass_bearing < 157.50: compass_dir = 'SE' elif compass_bearing >= 157.5 and compass_bearing < 202.50: compass_dir = 'S' elif compass_bearing >= 202.5 and compass_bearing < 247.50: compass_dir = 'SW' elif compass_bearing >= 247.5 and compass_bearing < 292.50: compass_dir = 'W' elif compass_bearing >= 292.5 and compass_bearing < 337.50: compass_dir = 'NW' elif compass_bearing >= 337.5 and compass_bearing <= 360.00: compass_dir = 'N' else: compass_dir = 'UN' return (int(compass_bearing), compass_dir, int(syd_distance_km)) def parse(self, response): sel = Selector(response) urls = sel.xpath('//section[@class="c-search-results__main"]/div/article/div/div/div/h3/a/@href').extract() for u in urls: request = scrapy.Request('https://www.airbnb.com.au/'+ u, callback=self.parse_results ) yield request # Get the link to the 'Next' page of listings url_pages = sel.xpath('/html/body/div/main/div/section/div/nav/ul/li/a/@href').extract() if len(url_pages) > 0: nextPage = url_pages[-1] nextPageURL = 'https://www.airbnb.com.au/'+ nextPage print("Next URL: " + str(nextPage)) yield(scrapy.Request(nextPageURL, callback=self.parse)) def strip_whitespace(self, st): st1 = re.sub('\n','',st.string() ) st2 = re.sub(' +',' ', st1.string() ) return st2 def parse_results(self, response): # Property ID - unique for each property p_id1 = response.selector.xpath('//*[@id="site-content"]/div/div[2]/div/div/div/div[3]/div/div[2]/div/div/div').extract_first() p_id2 = re.sub('\n','',p_id1) p_id3 = re.sub(' +',' ', p_id2) p_id4 = re.search('\d+',p_id3) p_id = p_id4.group(0) # Geographic location - not exact location, within a block of actual # Error handling - if no lat/lon specified place in middle of Botany Harbour p_lat = response.selector.xpath('//*[@class="c-map__container"]/@lat').extract_first() if p_lat is None: p_lat = '-33.990' p_lng = response.selector.xpath('//*[@class="c-map__container"]/@lng').extract_first() if p_lng is None: p_lng = '151.180' #print("Distance to Sydney: {0} km" .format(p_syd_distance_km)) p_compass_bearing, p_dir, p_syd_distance_km = self.calculate_initial_compass_bearing((Decimal(-33.990),Decimal(151.180)),(Decimal(p_lat),Decimal(p_lng))) #print("Distance: {2} Compass: {0} Heading: {1}" .format(p_compass_bearing, p_dir, p_syd_distance_km)) # House configuration - number of guests p_configuration = response.css(".c-facet__label.u-display--block::text").extract_first() p_configuration = re.sub('\n','',p_configuration) p_configuration = re.sub(' +',' ', p_configuration) p_group = re.search('\d+', p_configuration) p_guests = p_group.group(0) p_heading = response.css(".c-heading--brand.u-h2::text").extract_first() # Property type from the sub-heading - 'House, Mudgee' p_pt_1 = response.selector.xpath('///html/body/main/section/div/article/header/p/small/text()').extract_first() if p_pt_1 is not None: p_pt_1 = re.sub('\n','', p_pt_1) p_pt_1 = re.sub(' +',' ', p_pt_1) if re.search('B&B', p_pt_1): p_property_type = 'B&B' else: p_pt_2 = re.search('\w+',p_pt_1) p_property_type = p_pt_2.group(0) else: p_property_type = 'Unknown' p_house_specs = response.selector.xpath('//div[@class="c-facets c-facets--inline"]/div/span/span/text()').extract() # Initialize variables n_bedrooms = 0 n_beds = 0 n_bathrooms = 0 for j in p_house_specs: if re.search('bedroom',j): # Extract number of guests n_br = re.search('\d+',j) n_bedrooms = n_br.group(0) if re.search('bed[s]?$',j): # Extract number of guests n_bd = re.search('\d+',j) n_beds = n_bd.group(0) if re.search('bathroom',j): # Extract number of guests n_bath = re.search('\d+',j) n_bathrooms = n_bath.group(0) # The basic price - 'From $xxx per night' p_ip_1 = response.selector.xpath('//header[@class="c-quote__header"]/p/span/span/span[@class="u-h1"]/text()').extract_first() p_init_price = 0 if p_ip_1 is not None: p_ip_3 = p_ip_1.replace(',','') p_ip_4 = re.search('\d+',p_ip_3) p_init_price = p_ip_4.group(0) else: p_init_price = 0 # Ratings and reviews p_rating = response.selector.xpath('//header[@class="c-reviews__header"]/span/span/span[@class="c-facet__label"]/span/text()').extract_first() p_r1 = response.selector.xpath('//html/body/main/section/div/article/header/p[2]/span/span[2]/small/text()').extract_first() # Initialise p_reviews = 0 if p_r1 is not None: p_r2 = re.sub('\n','',p_r1) p_r2 = re.sub(' +',' ',p_r2) p_r3 = re.search('\d+', p_r2) p_reviews = p_r3.group(0) else: p_reviews = 0 # Full text of property details p_description_full = response.xpath('//div[@id="property-description-body"]/p/text()').extract() p_description_text = '\n'.join(p_description_full) # Do a word count of the description p_description_wc = self.description_word_count(p_description_text) # Reverse geocoding on Google API for street address: latlng = "" + p_lat + "," + p_lng print("Scanning Property ID: " + p_id + "-" + response.url) p = Airbnb_Listing() p['property_id'] = p_id p['lat'] = p_lat p['lng'] = p_lng p['guests'] = p_guests p['heading'] = p_heading p['url'] = response.url p['init_price'] = p_init_price p['bedrooms'] = n_bedrooms p['beds'] = n_beds p['bathrooms'] = n_bathrooms p['description_full'] = p_description_full p['description_wc'] = p_description_wc p['property_type'] = p_property_type #p['rating'] = p_rating p['reviews'] = p_reviews #p['suburb'] = p_suburb #p['postcode'] = p_postcode #p['house_specs'] = p_house_specs #p['google_addr'] = google_addr.text p['syd_dist_km'] = p_syd_distance_km p['syd_brg_deg'] = p_compass_bearing p['syd_brg'] = p_dir p['scraped_date'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") yield p # In[5]: process = CrawlerProcess({ 'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)' }) process.crawl(AirbnbSpider) process.start()
[ "tim.jelliffe@cbigconsulting.com.au" ]
tim.jelliffe@cbigconsulting.com.au
9c68c1a48ea5e7f1c1e9b39fb95197c685595749
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p02260/s279877008.py
38cfba9d040e317dbba645db4cba4794e44c61a4
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
601
py
input() num_list = raw_input().split() num_list = map(int, num_list) def selection_sort(num_list, count): for i in range(0, len(num_list)): minj = i for j in range(i, len(num_list)): if num_list[j] < num_list[minj]: minj = j temp = num_list[minj] if minj != i: num_list[minj] = num_list[i] num_list[i]= temp count += 1 i += 1 return count, num_list count = 0 count, num_list = selection_sort(num_list, count) num_list = map(str, num_list) print " ".join(num_list) print count
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
39b8c01806e7f01b801d077e55cdbe99b11dd5a9
0883188e1648f982e3a27bf0b89c4c09dac3d3ef
/nmigen/test/compat/test_fifo.py
bc6b81cdee56cf3921aa32628db05c3a8a6097be
[ "BSD-2-Clause" ]
permissive
pbsds/nmigen
b44c0b212ddd2d88a6641243efbb632baacb66f7
d964ba9cc45490b141c8c4c4c3d8add1a26a739d
refs/heads/master
2022-12-04T10:32:52.573521
2020-07-31T13:17:39
2020-07-31T18:41:59
286,076,534
0
0
BSD-2-Clause
2020-08-08T16:12:24
2020-08-08T16:12:23
null
UTF-8
Python
false
false
1,272
py
import unittest from itertools import count from ...compat import * from ...compat.genlib.fifo import SyncFIFO from .support import SimCase class SyncFIFOCase(SimCase, unittest.TestCase): class TestBench(Module): def __init__(self): self.submodules.dut = SyncFIFO(64, 2) self.sync += [ If(self.dut.we & self.dut.writable, self.dut.din[:32].eq(self.dut.din[:32] + 1), self.dut.din[32:].eq(self.dut.din[32:] + 2) ) ] def test_run_sequence(self): seq = list(range(20)) def gen(): for cycle in count(): # fire re and we at "random" yield self.tb.dut.we.eq(cycle % 2 == 0) yield self.tb.dut.re.eq(cycle % 3 == 0) # the output if valid must be correct if (yield self.tb.dut.readable) and (yield self.tb.dut.re): try: i = seq.pop(0) except IndexError: break self.assertEqual((yield self.tb.dut.dout[:32]), i) self.assertEqual((yield self.tb.dut.dout[32:]), i*2) yield self.run_with(gen())
[ "whitequark@whitequark.org" ]
whitequark@whitequark.org
ec0ca45a66c021f66879744dd2ce4e1d0aa3a1cd
a79d30723c1718be859896ac2219df9c85a8de08
/code/03A_stack.py
b1b4d88e21b9926e6853dd14225895e77d5f2997
[ "MIT" ]
permissive
okuchap/ProCon_practice
90d67813eb487d166eb5fd4b889e70f6997bac7f
b98f0ac6ea52c5a1b5d9146ba2a9e2620fe67027
refs/heads/master
2020-08-18T15:25:00.107128
2020-03-24T14:20:16
2020-03-24T14:20:16
215,806,503
0
0
null
null
null
null
UTF-8
Python
false
false
810
py
# %% class Stack: def __init__(self, size): self.size = size self.stack = [None] * self.size self.tail = 0 def push(self, new): self.stack[self.tail] = new self.tail += 1 def pop(self): self.tail -= 1 return self.stack[self.tail] max_size = 105 # li = list(map(str, input().split())) li = ['1', '2', '+', '3', '4', '-', '*'] N = len(li) stack = Stack(max_size) for i in range(N): ch = li[i] if ch in ['+', '-', '*']: num_2 = stack.pop() num_1 = stack.pop() if ch == '+': stack.push(num_1 + num_2) elif ch == '-': stack.push(num_1 - num_2) else: stack.push(num_1 * num_2) else: stack.push(int(ch)) print('{}'.format(stack.stack[0])) # %%
[ "kyohei.okumura@gmail.com" ]
kyohei.okumura@gmail.com
0d6bf526fcc135ca7f156726c43622f99a0c3269
53fab060fa262e5d5026e0807d93c75fb81e67b9
/backup/user_053/ch160_2020_06_19_19_49_19_966261.py
0eb7281b995c2be04327db8c79ad0fcf74f9446d
[]
no_license
gabriellaec/desoft-analise-exercicios
b77c6999424c5ce7e44086a12589a0ad43d6adca
01940ab0897aa6005764fc220b900e4d6161d36b
refs/heads/main
2023-01-31T17:19:42.050628
2020-12-16T05:21:31
2020-12-16T05:21:31
306,735,108
0
0
null
null
null
null
UTF-8
Python
false
false
503
py
import math resultados = {} valores = [] i = 0 for x in range(91): # Aplica fórmula y = 4*x*(180 - x)/(40500 - x*(180 - x)) # Converte para rad x = x*math.pi/180 # Verifica diferença dif = abs(y - math.sin(x)) # Adiciona na lista de diferenças valores.append(dif) # Adiciona diferença com índice no dicionário resultados[i] = dif i += 1 for indice, diferenca in resultados.items(): if diferenca == max(valores): print(indice) break
[ "you@example.com" ]
you@example.com
f04720409bf09077c5e90574bbab79459831f81f
6d42c34787d0dca36ebcbb54fc6aa581c1652946
/moteur_r/utils.py
0073da8cc13f4c754026a7139e455ae3b8135bf4
[]
no_license
Miosse/test1
84e3a8b29490b5484805be2249539e0e20890796
cd65a712d32d42c0de13ebe2ffcb8ada2b528af0
refs/heads/master
2022-12-20T17:59:57.021323
2019-02-04T15:35:27
2019-02-04T15:35:27
139,535,266
0
0
null
2022-11-22T01:49:00
2018-07-03T05:58:24
Jupyter Notebook
UTF-8
Python
false
false
2,755
py
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import pandas as pd #import matplotlib.pyplot as plt import json import os from pygments import highlight, lexers, formatters import pprint basedir = os.path.abspath(os.path.dirname(__file__)) #from .models import charge_df # Pour afficher les graphiques inline #%matplotlib inline def charge_df(): #FILE = os.path.join(basedir, 'datas/movie_metadata.csv') FILE = os.path.join(basedir, 'datas/movie_metadata_nettoye_1.csv') #FILE = 'datas/movie_metadata.csv' df = pd.read_csv(FILE) return df MA_BASE = charge_df() ''' def get_df_value(mon_id): #u = MA_BASE.loc[nb,['director_name','movie_title']] #return resultat(MA_BASE, 1) #colorful_json = highlight(unicode(formatted_json, 'UTF-8'), lexers.JsonLexer(), formatters.TerminalFormatter()) formatted_json = json.dumps(resultat(MA_BASE, mon_id), indent=4) colorful_json = highlight(formatted_json, lexers.JsonLexer(), formatters.TerminalFormatter()) print(colorful_json) #return json.dumps(resultat(MA_BASE, 1), indent=4) return pprint.pformat(formatted_json) ''' '''def get_df_value(mon_id): ma_recherche = resultat(MA_BASE, mon_id) return ma_recherche ''' def get_df_value(mon_id): ma_recherche = resultat(MA_BASE, mon_id) return str(ma_recherche) def get_df_value2(mon_id): ma_recherche = resultat(MA_BASE, mon_id) #colorful_json = highlight(unicode(formatted_json, 'UTF-8'), lexers.JsonLexer(), formatters.TerminalFormatter()) formatted_json = json.dumps(str(ma_recherche), indent=4) colorful_json = highlight(formatted_json, lexers.JsonLexer(), formatters.TerminalFormatter()) print(colorful_json) return pprint.pformat(formatted_json) ''' def retourne_resultat_fichier(m_dataframe, id): film_name = m_dataframe[m_dataframe['id']==id]['movie_title'].values[0] return {"id": id, "name":film_name} ''' ''' def resultat(m_dataframe, id): res = [] for i in [1, 2, 3, 4, 5]: res.append(retourne_resultat_fichier(m_dataframe, i)) return { "_results": res} ''' def retourne_resultat_fichier(m_dataframe, id): film_name = m_dataframe[m_dataframe['id']==id]['movie_title'].values[0] return {"id": id, "name":film_name} def resultat(m_dataframe, id): film_label = m_dataframe[m_dataframe['id']==id]['label'].values[0] res = [] # On recherche les données ayant le même label m_df_tmp = m_dataframe[m_dataframe['label']==film_label]\ .sort_values('imdb_score',ascending=False).head(5) for i in m_df_tmp['id'].get_values(): res.append(retourne_resultat_fichier(m_dataframe, i)) return { "_results": res}
[ "seb@imac-de-sebastien.home" ]
seb@imac-de-sebastien.home
5e2ed0acc6bbf0c146e9f042886d7884c6fa5ef8
bb9f9d024c7eb340f9254b48fc7f1983edbb9be3
/VirtualTour/migrations/0003_remove_images_graph_cost.py
9a235fd62d47260fd8965ed3789c06d8e2b60ab4
[]
no_license
anushagoswami21/Virtual-Tour-Of-IIIT-H-Campus
c9e341195468a80626005aeaba4e5bf344519424
e83a0557cc87fd98fde3935b3f67b5d462875ba3
refs/heads/master
2020-12-02T07:54:55.846992
2017-07-10T20:07:26
2017-07-10T20:07:26
96,747,232
0
0
null
null
null
null
UTF-8
Python
false
false
395
py
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-06-13 09:37 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('VirtualTour', '0002_images_graph'), ] operations = [ migrations.RemoveField( model_name='images_graph', name='cost', ), ]
[ "anushagoswami10@gmail.com" ]
anushagoswami10@gmail.com
cee5b8650269efe733b6f7b95dcc8366a0fa8d3b
ba919c512e131de90427b1a6bfd29e1d7a2e22c8
/debug/verification_test.py
a509b9d96a2cf195f0bfa7b8082cccaa8b3446a1
[]
no_license
qq183727918/influence
7d3b0106db55402630979b86455e4b82ebed2e98
75cb04453278d13dd82a6f319d6f9ecdfad5fb88
refs/heads/master
2023-01-22T23:00:51.979543
2020-12-08T11:12:12
2020-12-08T11:12:12
317,783,196
0
0
null
null
null
null
UTF-8
Python
false
false
1,078
py
# _*_ coding: UTF-8 _*_ # @Time : 2020/12/4 17:01 # @Author : LiuXiaoQiang # @Site : http:www.cdtest.cn/ # @File : verification_test.py # @Software : PyCharm def verification(): from PIL import Image # 转换灰度 # 使用路径导入图片 imgName = '13.png' im = Image.open(imgName) # 使用 byte 流导入图片 # im = Image.open(io.BytesIO(b)) # 转化到灰度图 imgry = im.convert('L') # 保存图像 imgry.save('gray-' + imgName) # 二值化降噪的过程 from PIL import Image, ImageEnhance, ImageFilter im = Image.open('../verification/gray-13.png') im = im.filter(ImageFilter.MedianFilter()) enhancer = ImageEnhance.Contrast(im) im = enhancer.enhance(2) im = im.convert('1') im.show() im.save('./1213.png') verification() from PIL import Image import pytesseract # pytesseract.pytesseract.tesseract_cmd = r'D:\Tools\tesseract\Tesseract-OCR/tesseract.exe' image = Image.open("../verification/gray-13.png") code = pytesseract.image_to_string(image, None) print(code)
[ "lxq13925731395@163.com" ]
lxq13925731395@163.com
e47646cee5473ace6ef61c5e42b405d5c1bc95e9
2091cbb905b8d7bce2c2dde258bfb8e1e9f96810
/PycharmProjects/awsdemoproject/venv/Lib/site-packages/pyathena/pandas/result_set.py
f72f34a928c9d46cf4c644b9218c19eb2350f675
[]
no_license
pradosh2008/cloudproject
bd2dce445b9b14ac636134d866702c2e47b8d5cc
9ea9edccd1acf9d5a0c2928e3a0ccb44f9e79675
refs/heads/main
2023-03-17T05:12:28.772761
2021-03-07T12:17:50
2021-03-07T12:17:50
339,829,010
0
0
null
null
null
null
UTF-8
Python
false
false
6,147
py
# -*- coding: utf-8 -*- import logging from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Optional, Type from pyathena.converter import Converter from pyathena.error import OperationalError, ProgrammingError from pyathena.model import AthenaQueryExecution from pyathena.result_set import AthenaResultSet from pyathena.util import RetryConfig, parse_output_location, retry_api_call if TYPE_CHECKING: from pandas import DataFrame from pyathena.connection import Connection _logger = logging.getLogger(__name__) # type: ignore class AthenaPandasResultSet(AthenaResultSet): _parse_dates: List[str] = [ "date", "time", "time with time zone", "timestamp", "timestamp with time zone", ] def __init__( self, connection: "Connection", converter: Converter, query_execution: AthenaQueryExecution, arraysize: int, retry_config: RetryConfig, keep_default_na: bool = False, na_values: Optional[Iterable[str]] = ("",), quoting: int = 1, ) -> None: super(AthenaPandasResultSet, self).__init__( connection=connection, converter=converter, query_execution=query_execution, arraysize=1, # Fetch one row to retrieve metadata retry_config=retry_config, ) self._arraysize = arraysize self._keep_default_na = keep_default_na self._na_values = na_values self._quoting = quoting self._client = connection.session.client( "s3", region_name=connection.region_name, **connection._client_kwargs ) if ( self.state == AthenaQueryExecution.STATE_SUCCEEDED and self.output_location and self.output_location.endswith((".csv", ".txt")) ): self._df = self._as_pandas() else: import pandas as pd self._df = pd.DataFrame() self._iterrows = self._df.iterrows() @property def dtypes(self) -> Dict[Optional[Any], Type[Any]]: description = self.description if self.description else [] return { d[0]: self._converter.types[d[1]] for d in description if d[1] in self._converter.types } @property def converters( self, ) -> Dict[Optional[Any], Callable[[Optional[str]], Optional[Any]]]: description = self.description if self.description else [] return { d[0]: self._converter.mappings[d[1]] for d in description if d[1] in self._converter.mappings } @property def parse_dates(self) -> List[Optional[Any]]: description = self.description if self.description else [] return [d[0] for d in description if d[1] in self._parse_dates] def _trunc_date(self, df: "DataFrame") -> "DataFrame": description = self.description if self.description else [] times = [d[0] for d in description if d[1] in ("time", "time with time zone")] if times: df.loc[:, times] = df.loc[:, times].apply(lambda r: r.dt.time) return df def _fetch(self): try: row = next(self._iterrows) except StopIteration: return None else: self._rownumber = row[0] + 1 description = self.description if self.description else [] return tuple([row[1][d[0]] for d in description]) def fetchone(self): return self._fetch() def fetchmany(self, size: Optional[int] = None): if not size or size <= 0: size = self._arraysize rows = [] for _ in range(size): row = self.fetchone() if row: rows.append(row) else: break return rows def fetchall(self): rows = [] while True: row = self.fetchone() if row: rows.append(row) else: break return rows def _as_pandas(self) -> "DataFrame": import pandas as pd if not self.output_location: raise ProgrammingError("OutputLocation is none or empty.") bucket, key = parse_output_location(self.output_location) try: response = retry_api_call( self._client.get_object, config=self._retry_config, logger=_logger, Bucket=bucket, Key=key, ) except Exception as e: _logger.exception("Failed to download csv.") raise OperationalError(*e.args) from e else: length = response["ContentLength"] if length: if self.output_location.endswith(".txt"): sep = "\t" header = None description = self.description if self.description else [] names: Optional[Any] = [d[0] for d in description] else: # csv format sep = "," header = 0 names = None df = pd.read_csv( response["Body"], sep=sep, header=header, names=names, dtype=self.dtypes, converters=self.converters, parse_dates=self.parse_dates, infer_datetime_format=True, skip_blank_lines=False, keep_default_na=self._keep_default_na, na_values=self._na_values, quoting=self._quoting, ) df = self._trunc_date(df) else: # Allow empty response df = pd.DataFrame() return df def as_pandas(self) -> "DataFrame": return self._df def close(self) -> None: import pandas as pd super(AthenaPandasResultSet, self).close() self._df = pd.DataFrame() self._iterrows = None
[ "PradoshKumar.Jena@ascenaretail.com" ]
PradoshKumar.Jena@ascenaretail.com
ca61e25676f7f4d7904bd94e994b416e5b2cbd2d
ea5121cddcd8e084dd940221309dba720f78825e
/src/views/course_themes.py
8dd0e9bed2cc315973840379e9c95e56a1ac8f73
[]
no_license
festelm8/telegram_IS
ec772e82147240a3a30845b65218d9c2309eb357
63e4bf5ee14b441f12dbedd2604a00534c2b1d33
refs/heads/master
2021-05-11T13:27:30.056091
2018-02-11T21:33:37
2018-02-11T21:33:37
117,679,893
0
0
null
null
null
null
UTF-8
Python
false
false
10,557
py
from flask import render_template, request, redirect, url_for, flash from flask_login import login_user, logout_user, login_required, current_user from webargs.flaskparser import parser, use_args from src.schemas.web import course_theme_create_post, course_number_create_post, course_group_create_post from src.db import session, db from src.db.models import CourseTheme, CourseNumber, CourseGroup, Subject from . import bp_web @bp_web.route('/course_themes') @login_required def course_themes(): course_themes = CourseTheme.query.all(); course_themes_list = dict() if course_themes: course_themes_list = [{ 'id': course_theme.id, 'name': course_theme.name } for course_theme in course_themes] return render_template('course_themes.html', course_themes_list=course_themes_list) @bp_web.route('/course_themes/create', methods=['GET', 'POST']) @login_required def course_theme_create(): if request.method == 'POST': data = parser.parse(course_theme_create_post, request) course_theme = CourseTheme() if data: for item in data.items(): if item[0] == 'name': course_theme.name = item[1] session.add(course_theme) session.commit() return redirect(url_for('bp_web.course_themes')) return render_template('course_themes_edit.html') @bp_web.route('/course_themes/<course_theme_id>', methods=['GET', 'POST']) @login_required def course_theme_edit(course_theme_id): course_theme = CourseTheme.query.get(course_theme_id) if not course_theme: return redirect(url_for('bp_web.course_themes')) if request.method == 'POST': data = parser.parse(course_theme_create_post, request) if data: for item in data.items(): if item[0] == 'name': course_theme.name = item[1] session.commit() return redirect(url_for('bp_web.course_themes')) course_theme_data = { 'id': course_theme.id, 'name': course_theme.name, 'course_numbers_list': dict() } if course_theme.course_number: course_theme_data['course_numbers_list'] = [{ 'id': course_number.id, 'number': course_number.number } for course_number in course_theme.course_number] return render_template('course_themes_edit.html', course_theme_data=course_theme_data) @bp_web.route('/course_themes/<course_theme_id>/delete') @login_required def course_theme_delete(course_theme_id): course_theme = CourseTheme.query.get(course_theme_id) if not course_theme: return redirect(url_for('bp_web.course_themes')) if course_theme.course_number.__len__() > 0: flash('Вы не можете удалить это направление подготовки пока у него есть активные курсы подготовки!') return redirect(url_for('bp_web.course_theme_edit', course_theme_id=course_theme_id)) session.delete(course_theme) session.commit() return redirect(url_for('bp_web.course_themes')) @bp_web.route('/course_themes/<course_theme_id>/course_numbers/create', methods=['GET', 'POST']) @login_required def course_number_create(course_theme_id): course_theme = CourseTheme.query.get(course_theme_id) if not course_theme: return redirect(url_for('bp_web.course_theme_edit', course_theme_id=course_theme_id)) reserved_courses = list() if course_theme.course_number: for course_number in course_theme.course_number: reserved_courses.append(course_number.number) subjects = Subject.query.all() subjects_list = dict() if subjects: subjects_list = [{ 'id': subject.id, 'name': subject.name } for subject in subjects] if request.method == 'POST': data = parser.parse(course_number_create_post, request) course_number = CourseNumber() if data: for item in data.items(): if item[0] == 'number': course_number.number = int(item[1]) if item[0] == 'subjects[]': for subj in item[1]: course_number_subject = Subject.query.get(subj) if course_number_subject: course_number.subjects.append(course_number_subject) course_number.course_theme = course_theme session.add(course_number) session.commit() return redirect(url_for('bp_web.course_theme_edit', course_theme_id=course_theme_id)) return render_template('course_numbers_edit.html', reserved_courses=reserved_courses, subjects_list=subjects_list) @bp_web.route('/course_themes/<course_theme_id>/course_numbers/<course_number_id>', methods=['GET', 'POST']) @login_required def course_number_edit(course_theme_id, course_number_id): course_theme = CourseTheme.query.get(course_theme_id) if not course_theme: return redirect(url_for('bp_web.course_theme_edit', course_theme_id=course_theme_id)) course_number = course_theme.course_number_lazy.filter_by(id=course_number_id).first() if not course_number: return redirect(url_for('bp_web.course_theme_edit', course_theme_id=course_theme_id)) course_number_data = { 'id': course_number.id, 'course_theme_id': course_theme.id, 'number': course_number.number, 'reserved_subjects': list(), 'reserved_groups': dict() } if course_number.subjects: reserved_subjects = course_number.subjects.all() if reserved_subjects: for reserved_subject in reserved_subjects: course_number_data['reserved_subjects'].append(reserved_subject.id) if course_number.course_group: course_number_data['reserved_groups'] = [{ 'id': reserved_group.id, 'gid': reserved_group.gid } for reserved_group in course_number.course_group] reserved_courses = list() if course_theme.course_number: for course_number in course_theme.course_number: reserved_courses.append(course_number.number) subjects = Subject.query.all() subjects_list = dict() if subjects: subjects_list = [{ 'id': subject.id, 'name': subject.name } for subject in subjects] if request.method == 'POST': data = parser.parse(course_number_create_post, request) if data: for item in data.items(): if item[0] == 'number': course_number.number = int(item[1]) if item[0] == 'subjects[]': reserved_subjects = course_number.subjects.all() if reserved_subjects: for reserved_subject in reserved_subjects: course_number.subjects.remove(reserved_subject) for subj in item[1]: course_number_subject = Subject.query.get(subj) if course_number_subject: course_number.subjects.append(course_number_subject) session.commit() return redirect(url_for('bp_web.course_theme_edit', course_theme_id=course_theme_id)) return render_template('course_numbers_edit.html', course_number_data=course_number_data, reserved_courses=reserved_courses, subjects_list=subjects_list) @bp_web.route('/course_themes/<course_theme_id>/course_numbers/<course_number_id>/delete') @login_required def course_number_delete(course_theme_id, course_number_id): course_theme = CourseTheme.query.get(course_theme_id) if not course_theme: return redirect(url_for('bp_web.course_theme_edit', course_theme_id=course_theme_id)) course_number = course_theme.course_number_lazy.filter_by(id=course_number_id).first() if not course_number: return redirect(url_for('bp_web.course_theme_edit', course_theme_id=course_theme_id)) if course_number.course_group.__len__() > 0 or course_number.subjects.count() > 0: flash('Вы не можете удалить этот номер курса, пока у него есть используемые группы или курс привязан к предметам!') return redirect(url_for('bp_web.course_theme_edit', course_theme_id=course_theme_id)) session.delete(course_theme) session.commit() return redirect(url_for('bp_web.course_themes')) @bp_web.route('/course_themes/<course_theme_id>/course_numbers/<course_number_id>/create_group', methods=['POST']) @login_required def course_group_create(course_theme_id, course_number_id): course_theme = CourseTheme.query.get(course_theme_id) if not course_theme: return redirect(url_for('bp_web.course_theme_edit', course_theme_id=course_theme_id)) course_number = course_theme.course_number_lazy.filter_by(id=course_number_id).first() if not course_number: return redirect(url_for('bp_web.course_theme_edit', course_theme_id=course_theme_id)) course_group = CourseGroup() data = parser.parse(course_group_create_post, request) if data: for item in data.items(): if item[0] == 'gid': course_group.gid = int(item[1]) course_group.course_number = course_number session.add(course_group) session.commit() return redirect(url_for('bp_web.course_number_edit', course_theme_id=course_theme_id, course_number_id=course_number_id)) @bp_web.route('/course_themes/<course_theme_id>/course_numbers/<course_number_id>/<course_group_id>') @login_required def course_group_delete(course_theme_id, course_number_id, course_group_id): course_group = CourseGroup.query.get(course_group_id) if not course_group: return redirect(url_for('bp_web.course_number_edit', course_theme_id=course_theme_id, course_number_id=course_number_id)) if course_group.class_schedule.count() > 0: flash('Вы не можете удалить эту группу пока у она числиться в расписании!') return redirect(url_for('bp_web.course_number_edit', course_theme_id=course_theme_id, course_number_id=course_number_id)) session.delete(course_group) session.commit() return redirect(url_for('bp_web.course_number_edit', course_theme_id=course_theme_id, course_number_id=course_number_id))
[ "s.nikulin@damprodam.ru" ]
s.nikulin@damprodam.ru
05881bf793aa55eee51c75d99cdbe7a1085333a9
86fc644c327a8d6ea66fd045d94c7733c22df48c
/scripts/managed_cpe_services/customer/qos_service/policy_class_map_update/update_policy_class_map/update_policy_class_map.py
d79055588ad5e2c89764db215cca6b39ed2e3bd7
[]
no_license
lucabrasi83/anutacpedeployment
bfe703657fbcf0375c92bcbe7560051817f1a526
96de3a4fd4adbbc0d443620f0c53f397823a1cad
refs/heads/master
2021-09-24T16:44:05.305313
2018-10-12T02:41:18
2018-10-12T02:41:18
95,190,459
0
0
null
null
null
null
UTF-8
Python
false
false
6,843
py
# # This computer program is the confidential information and proprietary trade # secret of Anuta Networks, Inc. Possessions and use of this program must # conform strictly to the license agreement between the user and # Anuta Networks, Inc., and receipt or possession does not convey any rights # to divulge, reproduce, or allow others to use this program without specific # written authorization of Anuta Networks, Inc. # # Copyright (c) 2015-2016 Anuta Networks, Inc. All Rights Reserved. # # #DO NOT EDIT THIS FILE ITS AUTOGENERATED ONE #ALL THE CUSTOMIZATIONS REGARDING DATAPROCESSING SHOULD BE WRITTEN INTO service_customization.py FILE # """ Tree Structure of Handled XPATH: services | managed-cpe-services | customer | qos-service | policy-class-map-update | update-policy-class-map Schema Representation: /services/managed-cpe-services/customer/qos-service/policy-class-map-update/update-policy-class-map """ from servicemodel import util from servicemodel import yang from servicemodel import devicemgr from cpedeployment.cpedeployment_lib import getLocalObject from cpedeployment.cpedeployment_lib import getDeviceObject from cpedeployment.cpedeployment_lib import getCurrentObjectConfig from cpedeployment.cpedeployment_lib import ServiceModelContext from cpedeployment.cpedeployment_lib import getParentObject from cpedeployment.cpedeployment_lib import log import service_customization class UpdatePolicyClassMap(yang.AbstractYangServiceHandler): _instance = None def __init__(self): self.delete_pre_processor = service_customization.DeletePreProcessor() self.create_pre_processor = service_customization.CreatePreProcessor() def create(self, id, sdata): sdata.getSession().addYangSessionPreReserveProcessor(self.create_pre_processor) #Fetch Local Config Object config = getCurrentObjectConfig(id, sdata, 'update_policy_class_map') #Fetch Service Model Context Object smodelctx = None #Fetch Parent Object parentobj = None dev = [] devbindobjs={} inputdict = {} # START OF FETCHING THE LEAF PARAMETERS inputdict['name'] = config.get_field_value('name') inputdict['policy_name'] = config.get_field_value('policy_name') inputdict['update_profile'] = config.get_field_value('update_profile') inputdict['apply_to_sites'] = config.get_field_value('apply_to_sites') inputdict['apply_to_device_group'] = config.get_field_value('apply_to_device_group') inputdict['device_group'] = config.get_field_value('device_group') inputdict['class1'] = config.get_field_value('class') inputdict['packet_handling'] = config.get_field_value('packet_handling') inputdict['percentage'] = config.get_field_value('percentage') inputdict['queue_limit'] = config.get_field_value('queue_limit') inputdict['packets'] = config.get_field_value('packets') inputdict['qos_group'] = config.get_field_value('qos_group') inputdict['single_cpe_site'] = config.get_field_value('single_cpe_site') inputdict['single_cpe_sites'] = config.get_field_value('single_cpe_sites') if inputdict['single_cpe_sites'] is None: inputdict['single_cpe_sites'] = '[]' inputdict['dual_cpe_site'] = config.get_field_value('dual_cpe_site') inputdict['dual_cpe_sites'] = config.get_field_value('dual_cpe_sites') if inputdict['dual_cpe_sites'] is None: inputdict['dual_cpe_sites'] = '[]' inputdict['single_cpe_dual_wan_site'] = config.get_field_value('single_cpe_dual_wan_site') inputdict['single_cpe_dual_wan_sites'] = config.get_field_value('single_cpe_dual_wan_sites') if inputdict['single_cpe_dual_wan_sites'] is None: inputdict['single_cpe_dual_wan_sites'] = '[]' inputdict['triple_cpe_site'] = config.get_field_value('triple_cpe_site') inputdict['triple_cpe_sites'] = config.get_field_value('triple_cpe_sites') if inputdict.get('triple_cpe_sites') is None: inputdict['triple_cpe_sites'] = '[]' inputdict['dual_cpe_dual_wan_site'] = config.get_field_value('dual_cpe_dual_wan_site') inputdict['dual_cpe_dual_wan_sites'] = config.get_field_value('dual_cpe_dual_wan_sites') if inputdict.get('dual_cpe_dual_wan_sites') is None: inputdict['dual_cpe_dual_wan_sites'] = '[]' # END OF FETCHING THE LEAF PARAMETERS inputkeydict = {} # START OF FETCHING THE PARENT KEY LEAF PARAMETERS inputkeydict['managed_cpe_services_customer_name'] = sdata.getRcPath().split('/')[-4].split('=')[1] # END OF FETCHING THE PARENT KEY LEAF PARAMETERS #Use the custom methods to process the data service_customization.ServiceDataCustomization.process_service_create_data(smodelctx, sdata, dev, device=dev, parentobj=parentobj, inputdict=inputdict, config=config) def update(self, id, sdata): #Fetch Local Config Object config = getCurrentObjectConfig(id, sdata, 'update_policy_class_map') #Fetch Service Model Context Object smodelctx = None #Fetch Parent Object parentobj = None dev = [] #Use the custom method to process the data service_customization.ServiceDataCustomization.process_service_update_data(smodelctx, sdata, dev=dev, parentobj=parentobj, config=config) def delete(self, id, sdata): sdata.getSession().addYangSessionPreReserveProcessor(self.delete_pre_processor) #Fetch Local Config Object config = getCurrentObjectConfig(id, sdata, 'update_policy_class_map') #Fetch Service Model Context Object smodelctx = None #Fetch Parent Object parentobj = None dev = [] #Use the custom method to process the data service_customization.ServiceDataCustomization.process_service_delete_data(smodelctx, sdata, dev=dev, parentobj=parentobj, config=config) @staticmethod def getInstance(): if(UpdatePolicyClassMap._instance == None): UpdatePolicyClassMap._instance = UpdatePolicyClassMap() return UpdatePolicyClassMap._instance #def rollbackCreate(self, id, sdata): # log('rollback: id = %s, sdata = %s' % (id, sdata)) # self.delete(id,sdata)
[ "sebastien.pouplin@tatacommunications.com" ]
sebastien.pouplin@tatacommunications.com
05738ed6bbb6162be5ee46923d010c5149dea801
425e523ba9218ad79c6f18cab5060015fe9938a7
/kimura/tests/TestBasic.py
94c93db1a55846cf6b3807144c816e00d5fc0ad7
[]
no_license
lbozhilova/Kimura-Distribution
8db458a1d8acc9e16fefe19e3e8a5badc7bceac1
3487f3bb3e51bb42d03dd4d71dd2bb5bc9bfdb2b
refs/heads/master
2023-02-21T16:22:59.141025
2021-01-22T18:54:02
2021-01-22T18:54:02
435,932,673
1
0
null
2021-12-07T15:28:52
2021-12-07T15:28:51
null
UTF-8
Python
false
false
1,169
py
import unittest, os, shutil import kimura #Original input file TESTDATA_FILENAME = os.path.join(os.path.dirname(__file__), 'oocyte.txt') OUTPUT_TEMP_DIR = os.path.join(os.path.dirname(__file__), 'temp/') class TestBasic(unittest.TestCase): try: os.mkdir(OUTPUT_TEMP_DIR) except OSError as err: print("OS error: {0}".format(err)) else: print ("Successfully created the directory %s " % OUTPUT_TEMP_DIR) p = kimura.run(TESTDATA_FILENAME, OUTPUT_TEMP_DIR + 'test', 10, 10, 100) #set number of simulated dataset in each run 1000, p-value can't be below 0.001 def test_p_value(self): self.assertTrue(self.p >= 0.001) def test_check_output_files(self): self.assertTrue(os.path.isfile(OUTPUT_TEMP_DIR + 'test.kimura.comp.csv')) self.assertTrue(os.path.isfile(OUTPUT_TEMP_DIR + 'test.kimura.simu.csv')) self.assertTrue(os.path.isfile(OUTPUT_TEMP_DIR + 'test.monte_carlo.tsv')) self.assertTrue(os.path.isfile(OUTPUT_TEMP_DIR + 'test.observed.comp.csv')) self.assertTrue(os.path.isfile(OUTPUT_TEMP_DIR + 'test.summary.txt')) if __name__ == '__main__': unittest.main()
[ "wei.wei@mogrify.co.uk" ]
wei.wei@mogrify.co.uk
1bc864f2766f25ba6da9bdb18c33c914f4310381
fc484bfe16097e0801cec3720d9c5c2292c0beaf
/miRi/Scripts/pisa-script.py
54bdee9d036fe87322fbc2b0819d635cc1dc428e
[]
no_license
AkhilATC/miri_app
dd2257695291b6e7637792732a0bb42fc3502619
e816ed5d4bf82f9c24b45732100dff37280466e3
refs/heads/main
2023-08-29T20:48:26.697497
2021-11-14T06:32:04
2021-11-14T06:32:04
384,651,892
0
0
null
null
null
null
UTF-8
Python
false
false
431
py
#!c:\users\akhil\desktop\miri_app\miri_app\miri\scripts\python3.exe # EASY-INSTALL-ENTRY-SCRIPT: 'xhtml2pdf==0.2.5','console_scripts','pisa' __requires__ = 'xhtml2pdf==0.2.5' import re import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit( load_entry_point('xhtml2pdf==0.2.5', 'console_scripts', 'pisa')() )
[ "akhil.cheriyan@cognicor.com" ]
akhil.cheriyan@cognicor.com
27a2f1147b18c0c6298ca7f084000e7a60b0286d
af8ee3a30a76fcc49131475709e16d209e85d08b
/L3/p2/tl3/src/backend/trabajos.py
f9fe1a9cbd6de817084bea626f89f0f8359670f9
[]
no_license
mbarja/SistemasDistribuidos
99a3abee199d1ea14e3a483f3c3f96dfb3393868
e67da3f022613df0039fbc0ddb44854adb6c6b24
refs/heads/main
2023-01-30T13:50:08.284777
2020-12-14T21:54:42
2020-12-14T21:54:42
300,089,459
0
0
null
null
null
null
UTF-8
Python
false
false
3,421
py
#!/usr/bin/python3 import os import cgi import cgitb import json from http import cookies from sqlalchemy import * from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker import logging import datetime from db_handler import Database cgitb.enable() logger = logging.getLogger() database = Database.instance() print("Content-Type: application/json;charset=utf-8") print() class Trabajo(declarative_base()): __tablename__ = 'trabajos' id = Column(Integer, primary_key=True) id_usuario = Column(Integer) lugar = Column(String) fecha_inicio = Column(Date) fecha_fin = Column(Date) cargo = Column(String) observacion = Column(String) def __init__(self, id_usuario, lugar, fecha_inicio, fecha_fin, cargo, observacion): self.id_usuario = id_usuario self.lugar = lugar self.fecha_inicio = fecha_inicio self.fecha_fin = fecha_fin self.cargo = cargo self.observacion = observacion def query_trabajos(id_usuario): trabajos = [] for trabajo in database.get_trabajos(id_usuario): fechaInicio = trabajo.get('fecha_inicio').strftime("%d/%m/%Y") fechaFin = trabajo.get('fecha_fin').strftime("%d/%m/%Y") trabajo.pop('_sa_instance_state', None) trabajo.pop('fecha_inicio') trabajo['fecha_inicio'] = fechaInicio trabajo.pop('fecha_fin') trabajo['fecha_fin'] = fechaFin trabajos.append(trabajo) return trabajos def create_trabajo(id_usuario): try: form = cgi.FieldStorage() fechaFin = datetime.datetime.strptime(form.getvalue('fecha_fin'), "%d/%m/%Y").strftime("%Y-%m-%d") fechaInicio = datetime.datetime.strptime(form.getvalue('fecha_inicio'), "%d/%m/%Y").strftime("%Y-%m-%d") trabajo = Trabajo( id_usuario, form.getvalue('lugar'), fechaInicio, fechaFin, form.getvalue('cargo'), form.getvalue('observacion') ) logger.error(trabajo.lugar) logger.error(trabajo.fecha_inicio) logger.error(trabajo.fecha_fin) logger.error(trabajo.cargo) logger.error(trabajo.observacion) database.insert_trabajo(trabajo) return {'error': False} except: return {'error': True} if 'HTTP_COOKIE' in os.environ: cookie = cookies.SimpleCookie(os.environ['HTTP_COOKIE']) logger.error('HAY COOKIES') if cookie is None: logger.error('COOKIE IS NONE') response = {'error': True, 'credenciales': True} key = cookie.get('session_key').value value = cookie.get('session_value').value logger.error("key: " + key) logger.error("value: " + value) if not database.exists_cookie(key): logger.error('Error cookie not in database') response = {'error': True, 'credenciales': True} else: id_usuario = database.get_id_usuario(key) if os.environ['REQUEST_METHOD'] == 'GET': logger.error("get trabajos") response = query_trabajos(id_usuario) if os.environ['REQUEST_METHOD'] == 'POST': response = create_trabajo(id_usuario) if not response: response = {} else: logger.exception('el environment no tiene la cookie') response = {'error': True, 'credenciales': True} logger.error(response) print(json.JSONEncoder().encode(response))
[ "mmbarja@gmail.com" ]
mmbarja@gmail.com
9fd29221a17085e923fe0e3496a327328610a73b
7be77821174c49d972fd8709bacf8520f9bb5b80
/single_wind_change_animation.py
ab1433a28c2d47ce2f83ff9c3a64f5b028f860df
[]
no_license
nathangs6/firespread
67428677f6bbc00a5a3eaa675ee938165350d67a
23f404fbfe404f29f7aa36e8441f7d40caf965e1
refs/heads/main
2023-08-29T22:05:30.394400
2021-09-30T23:30:27
2021-09-30T23:30:27
410,591,370
0
0
null
null
null
null
UTF-8
Python
false
false
1,833
py
""" Title: single_wind_change_animation.py Author: Nathan Gurrin-Smith Description: Animation for a single wind change """ import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation import fire a = 1 f_old = 2 g_old = 0.5 h_old = 1 t_0 = 4 f_new = 5 g_new = 3 h_new = 2 beta = np.pi / 4 t = 0.5 theta = theta = np.linspace(0, 2 * np.pi, num=500, endpoint=True) num_huygen = 1000 huygen_theta = np.linspace(0, 2 * np.pi, num=num_huygen, endpoint=False) # Generate Data initial_fireline = fire.compute_fireline(a, f_old, g_old, h_old, theta, t_0) expected_fireline = fire.compute_fireline_single(a, [f_old, f_new], [g_old, g_new], [h_old, h_new], [0, beta], theta, [t_0, t]) xmin = np.amin(expected_fireline[0]) xmax = np.amax(expected_fireline[0]) ymin = np.amin(expected_fireline[1]) ymax = np.amax(expected_fireline[1]) data = [] for theta_0 in huygen_theta: initial_point = fire.compute_fireline_local(a, f_old, g_old, h_old, 0, theta_0, t_0) fireline_t = fire.compute_fireline_local(a, f_new, g_new, h_new, beta, theta, t, initial_point) data.append(fireline_t) # Generate initial plot fig, ax = plt.subplots() ax.set_xlim([xmin - 1, xmax + 1]) ax.set_ylim([ymin - 1, ymax + 1]) ax.set_title("Single Wind Change") ax.set_xlabel("x") ax.set_ylabel("y") ax.legend() ax.plot(initial_fireline[0], initial_fireline[1], 'b', label="First Fireline") ax.plot(expected_fireline[0], expected_fireline[1], 'r', label="Second Fireline") # Make animation xdata, ydata = [], [] ln, = ax.plot([], [], 'g', label="Huygen Spread") def init(): return ln, def update(frame): xdata = frame[0] ydata = frame[1] ln.set_data(xdata, ydata) return ln, ax.legend() ani = FuncAnimation(fig, update, frames=data, init_func = init, blit=True, interval=10)
[ "nathan.gurrinsmith@outlook.com" ]
nathan.gurrinsmith@outlook.com
79e92cc29b86832701a7f6f8f7988dc7c140fc18
bfbf5a47b4c8cc28d8f9d48867b4a12aea5a6210
/phaseOne/manage.py
40cc9358775e58a5443e03ce11056abe9aaeaff6
[]
no_license
ShoeShine9/phaseOne
7ab5450e336186a204ef901168bc9bf20c75144e
3ea06863127916bfb11157c1be3d82d691d1dd94
refs/heads/master
2020-05-27T02:29:30.510611
2017-02-21T04:06:26
2017-02-21T04:06:26
82,513,648
0
0
null
null
null
null
UTF-8
Python
false
false
806
py
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "phaseOne.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: 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?" ) raise execute_from_command_line(sys.argv)
[ "jknot7172068@C02Q9CTUG8WN.local" ]
jknot7172068@C02Q9CTUG8WN.local
e162fcea367639fdb66635de3d615f834ca418da
f5efe75f34e27b7dba482906c5212ff7a1717d5f
/square.py
8fcb4658da13c5dae613f3ae6af9620af0621de2
[]
no_license
MorEye/Python-Codes
bf5d78590995f43a33e4a3a6000d6589ad5e4ff4
2fda38c6d5cc75e6387a80ddc6ee7545b13c3b91
refs/heads/main
2023-08-18T20:28:37.304726
2021-09-12T07:06:56
2021-09-12T07:06:56
405,385,058
0
1
null
2021-09-30T17:06:18
2021-09-11T13:21:40
Python
UTF-8
Python
false
false
185
py
While true: i = input('Please enter an integer(0 to exit):\n') i = int(i) if i = 0: print("Exiting the Program") break print(f'{i} square is {i ** 2}')
[ "noreply@github.com" ]
MorEye.noreply@github.com
7b424aa4ed06c6b879a35d61c674eb9e76d2e32d
194f895390965fdf77be10c1cdcf49f7551d208e
/catalog_output.py
8ad696287c2f5afa946fedd18dcb08a6be643eae
[ "MIT" ]
permissive
low-sky/gbsh2co
24a801fe5882a7de20007de127220d5a37d9f32d
92cf1ab7e1275decfceb2e0c16fb1940b49c21b3
refs/heads/master
2021-01-22T12:12:29.634326
2015-01-07T20:52:48
2015-01-07T20:52:48
26,287,956
1
0
null
null
null
null
UTF-8
Python
false
false
1,401
py
import astropy.io.fits as fits from astropy.table import Table,Column from astropy.coordinates import SkyCoord import astropy.units as u import pyregion import numpy as np t=Table.read('s2_450.fits',format='fits') t.add_column(Column(data=(['SCIENCE']*len(t)),name='type')) t.add_column(Column(name='Name',data=([' ']*len(t)))) t.add_column(Column(name='RAString',data=([' ']*len(t)))) t.add_column(Column(name='DECString',data=([' ']*len(t)))) t.add_column(Column(data=(['circle point']*len(t)),name='shape')) t.add_column(Column(data=np.sqrt((t['FLUX_450']/0.1)/600.),name='radius')) for idx,source in enumerate(t): c = SkyCoord(ra=source['RA']*u.degree, dec=source['DEC']*u.degree, frame='icrs') t['RAString'][idx] = c.ra.to_string(sep=':',pad='True',alwayssign=True,precision=2,unit=u.hourangle) t['DECString'][idx] = c.dec.to_string(sep=':',pad='True',alwayssign=True,precision=2) strval = c.galactic.to_string('decimal') if c.galactic.b.value<0: t['Name'][idx] = 'G{0}{1}'.format(*strval.split(' ')) else: t['Name'][idx] = 'G{0}+{1}'.format(*strval.split(' ')) t['Type'] = 'SCIENCE' t2 = t['Type','Name','RAString','DECString'] t2.write('h2cocat.txt',format='ascii') t3 = t['shape','RAString','DECString'] t3.write('h2co.reg',format='ascii')
[ "rosolowsky@ualberta.ca" ]
rosolowsky@ualberta.ca
735a53264c0de93745cb73c68eaf2dbfdfa9f7c1
6997bac611cbfbbffa13727758935d397190f8fc
/episode_3_iris.py
a982b7eac0e317c72454dc39d53ea95e966a238f
[ "MIT" ]
permissive
sohmc/machine-learning-google-dev
7d2eabc214e8ba625e146905aad77a06c97047bf
10ba93048f6da42875170e96c44f83b4a1643286
refs/heads/master
2021-05-06T05:01:38.538869
2017-12-22T20:03:41
2017-12-22T20:03:41
115,038,352
0
0
null
null
null
null
UTF-8
Python
false
false
771
py
from sklearn import datasets iris = datasets.load_iris() X = iris.data y = iris.target from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = .5) from sklearn import tree my_classifier = tree.DecisionTreeClassifier() my_classifier.fit(X_train, y_train) predictions = my_classifier.predict(X_test) from sklearn.metrics import accuracy_score print "Prediction score using DecisionTreeClassifier" print accuracy_score(y_test, predictions) # Repeat using KNeighborClassifier from sklearn.neighbors import KNeighborsClassifier my_classifier.fit(X_train, y_train) predictions = my_classifier.predict(X_test) print "Prediction score using KNeighbor classifer" print accuracy_score(y_test, predictions)
[ "devnull@mikesoh.com" ]
devnull@mikesoh.com
0ba90ce97ac6b3d5bacbbf804012a22d87f02230
42536445f31e2f3c10effe63636e56a27b125b5e
/HashCode2020.py
07c6de6f9f152531f08632639b11d81240540366
[]
no_license
Giitto/HashCode2020
dc481f6c885475c4bbd51b314ce5995287f76fc7
91daf80a08f7a6bfe008f9aad82af73b01bece73
refs/heads/master
2021-01-08T06:50:11.754426
2020-02-26T07:54:51
2020-02-26T07:54:51
241,946,810
0
0
null
null
null
null
UTF-8
Python
false
false
2,738
py
import os import itertools import time import numpy as np dirpath = os.getcwd() file_name = 'b_read_on.txt' file_name ='c_incunabula.txt' books__ = [] def read_file(file_name): return [line.rstrip('\n') for line in open(file_name) if len(line) and line[0] != '#'] def get_int(file): init = file[0] D = init.split(" ")[2] L = init.split(" ")[1] B = init.split(" ")[0] return B,L,D def books__scores(B, file): line1 = file[1].split(" ") scores = list(line1) book_index = [i for i in range(int(B))] book_scores = {ind:score_ for ind,score_ in zip(book_index,scores)} return book_scores def get_lib(file, L): i=4 a = np.array([int(x) for x in file[2].split(" ")]) while i<len(file) : a = np.vstack((a, np.array([int(x) for x in file[i].split(" ")]))) i=i+2 index = np.array([2]) for i in range(4,int(L)*2+2,2) : ind = np.array([i]) index = np.vstack((index,ind)) a = np.hstack((index,a)) #index = index.transpose() #print(len(a)) #print(len(index)) #a = a.sort(axis=2) #print(index) return a def get_books(file, book_i): return file[book_i+1] def min_temp(x): min_ = x[0,2] ligne = x[0,0] ligne = 0 res = x[0] for e in x: if e[2] <=min_: min_ = e[2] #ligne = e[0] res = e l = ligne ligne +=1 index__ = int(l/2)-1 x = np.delete(x,l,0) return res, x def prend_books(books,nbr_book_prise): for b in books : a="s" return a def get_good(file,a , D): duree_consome= 0 days_nbr = int(D) libraries_restante = a libraries = [] text = "" cpt = 0 while duree_consome < days_nbr : x,libraries_restante = min_temp(libraries_restante) #print(x) #print(len(libraries_restante)) duree_signature = x[2] duree_consome = duree_consome + duree_signature #len(lib) nbr de bib prise libraries.append(int(x[0]/2)-1) lib_i = x[0] #print(book_i) books = get_books(file, lib_i) nb_livre = x[1] nb_envoie = x[3] div = int(nb_livre/nb_envoie) TempMax = days_nbr - duree_consome nbr_book_prise = TempMax if div > TempMax else div nbr_book_prise = nbr_book_prise if nbr_book_prise>0 else 0 lib__ = int(x[0]/2)-1 second_line = str(lib__)+' '+str(nbr_book_prise) books = books.split(" ") #books_prise= prend_books(books,nbr_book_prise) books_prise = books[:nbr_book_prise] #get_score(file,books,nbr_book_prise) if nbr_book_prise >0 : text = text + '\n'+ second_line text = text + '\n'+ ' '.join([str(elem) for elem in books_prise]) cpt = cpt +1 text = str(cpt) + text print(text) file2 = open(r"output.txt","w+") file2.write(text) def main(): file = read_file(file_name) file = file[:len(file)-1] B,L,D = get_int(file) books_scores = books__scores(B, file) a = get_lib(file, L) get_good(file, a , D) main()
[ "32240824+Giitto@users.noreply.github.com" ]
32240824+Giitto@users.noreply.github.com
ceea7cc2f0a579a232005ba70d10da6c7bea11bc
60fd23c13fffbe36af18a12b09ffdedce588302b
/test_servers.py
510f4bf1452bc59790532cd3be29bc287f609b18
[]
no_license
OUCS4263-SoftBearEngineering/RNG
9ac12d3dfb79da3fe9a807f0e4da7cec2743b558
8474871d6485eeda61d9278d74da8e041421f0ad
refs/heads/master
2020-07-26T00:32:11.121096
2020-01-27T02:02:06
2020-01-27T02:02:06
208,470,250
0
1
null
null
null
null
UTF-8
Python
false
false
892
py
import requests import unittest import yaml from datetime import datetime class TestResponseTime(unittest.TestCase): """ Outputs response time for single request for each server """ def test_response_time(self): with open("test.yaml", "r") as f: data = yaml.load(f, Loader=yaml.FullLoader) for group in data.values(): for region in group.values(): for server_data in region.values(): print(server_data.get('server')) num = requests.get(server_data.get('server')) server_data['time'] = str(num.elapsed) server_data['random_number'] = num with open("test.yaml", "w") as f: yaml.dump(data, f, default_flow_style=False) if __name__ == '__main__': unittest.main()
[ "hopeanderson@Hopes-MacBook-Pro.local" ]
hopeanderson@Hopes-MacBook-Pro.local
60ab3392564ed2b34cd4e2194fd1c38bfcfd07c0
e0e6888bd1961ff7d1b585f7ebae0e050afac8c0
/nodes/yaml/__init__.py
419d1f3cac189a63ce7b1db4e118d88009e38e66
[]
no_license
mpdehaan/virt-factory
2c3827603b18faf8eca1d41ba470dbc0f9f08496
d5e880b132857d30501c750b90511bfeab01224d
refs/heads/master
2016-09-05T20:52:12.784908
2007-10-22T19:09:59
2007-10-22T19:09:59
143,106
3
0
null
null
null
null
UTF-8
Python
false
false
551
py
__version__ = "0.32" from load import loadFile, load, Parser, l from dump import dump, dumpToFile, Dumper, d from stream import YamlLoaderException, StringStream, FileStream from timestamp import timestamp import sys if sys.hexversion >= 0x02020000: from redump import loadOrdered try: from ypath import ypath except NameError: def ypath(expr,target='',cntx=''): raise NotImplementedError("ypath requires Python 2.2") if sys.hexversion < 0x02010000: raise 'YAML is not tested for pre-2.1 versions of Python'
[ "root@mdehaan.rdu.redhat.com" ]
root@mdehaan.rdu.redhat.com
d127203968e42abc05066342b92f8c62d9e3c4ea
bba5157f0390b23a1efda0786f24267d55fedd5c
/Textures.py
b1cfd928ae0fc20afb121e9780c3e92b381d0105
[]
no_license
Jagoslav/Platforming-Game---Level-Editor
d6174c923ef3492f8f7b9f675d14f25828f93971
87a3ae43cec1e25cb4f5c45b258810d78f9b46fe
refs/heads/master
2020-06-05T12:06:23.687055
2019-06-18T00:02:48
2019-06-18T00:02:48
192,433,426
1
0
null
null
null
null
UTF-8
Python
false
false
3,760
py
from Window import * import pygame import sys from tkinter import messagebox def load_texture(file_name): """ loads the texture and creates a surface with a texture blitted on top of it :param file_name: name of the file to load :return: surface if created properly, None otherwise """ try: bit_map = pygame.image.load(file_name).convert_alpha() surface = pygame.Surface(bit_map.get_size(), pygame.HWSURFACE | pygame.SRCALPHA) surface.blit(bit_map, (0, 0)) return surface except pygame.error: return None class Textures: def __init__(self): self.tile_size = 16 self.textures_dict = {} # checkerboard alike styled set of tiles is stored in this file. self.refill_tile_dictionary("images/sprite_sheets/default.png") # texture representing an idle (not clicked or focused) button self.button_idle = load_texture("images/icons/button_idle.png") # texture representing a button that is either pressed, or focused self.button_focused = load_texture("images/icons/button_focused.png") # texture of an icon that represents player's starting point in editor self.starting_position = load_texture("images/icons/start_position.png") # texture (supposedly) holding frames for player's movement animation, currently only 1 frame self.player_tiles = load_texture("images/sprite_sheets/temp_player.png") missing_files = [] if self.button_idle is None: missing_files.append("images/icons/button_idle.png") if self.button_focused is None: missing_files.append("images/icons/button_focused.png") if self.starting_position is None: missing_files.append("images/icons/start_position.png") if not self.player_tiles: missing_files.append("images/sprite_sheets/player.png") if len(self.textures_dict) is 0: missing_files.append("images/sprite_sheets/default.png") if len(missing_files) > 0: tkinter.messagebox.showinfo("", "Important files could not be loaded") pygame.quit() sys.exit() def refill_tile_dictionary(self, file_name): """ loads picture and splits it into several smaller pieces, which are then stored in texture_rep with their id's based on placement in original file :param file_name: name of a file to load :return: True if split were successful, False otherwise """ try: bit_map = pygame.image.load(file_name).convert_alpha() if not bit_map: return False image_width, image_height = bit_map.get_size() if image_width < self.tile_size and image_height < self.tile_size: return False tile_table = [] for tile_y in range(0, int(image_height / self.tile_size)): row = [] for tile_x in range(0, int(image_width / self.tile_size)): tile_rect = (tile_x * self.tile_size, tile_y * self.tile_size, self.tile_size, self.tile_size) row.append(bit_map.subsurface(tile_rect)) tile_table.append(row) self.textures_dict.clear() temp_id = 0 for row in tile_table: for tile in row: self.textures_dict[str(temp_id)] = tile temp_id += 1 return True except pygame.error: return False textures_rep = Textures()
[ "jaankugrzeszczak@gmail.com" ]
jaankugrzeszczak@gmail.com
3d8c7d5d770afbabc37c26b2b4f7087815730720
aa191ccd50cda37337b1fa3429e7c4be994a50ae
/adafruit_midi/note_off.py
3e8382d559c70938dcf753de65b97905ef29e7d6
[ "MIT" ]
permissive
foozmeat/Adafruit_CircuitPython_MIDI
40b1ca1c9df78f54d3f773de2b1714e44bbc2579
ee30921e95fde2f0c5b56041a2ef37414bcd05df
refs/heads/master
2021-02-09T02:44:02.340914
2020-03-01T21:56:41
2020-03-01T21:56:41
244,229,805
0
0
MIT
2020-03-01T21:55:29
2020-03-01T21:55:28
null
UTF-8
Python
false
false
2,473
py
# The MIT License (MIT) # # Copyright (c) 2019 Kevin J. Walters # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """ `adafruit_midi.note_off` ================================================================================ Note Off Change MIDI message. * Author(s): Kevin J. Walters Implementation Notes -------------------- """ from .midi_message import MIDIMessage, note_parser __version__ = "0.0.0-auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_MIDI.git" class NoteOff(MIDIMessage): """Note Off Change MIDI message. :param note: The note (key) number either as an ``int`` (0-127) or a ``str`` which is parsed, e.g. "C4" (middle C) is 60, "A4" is 69. :param int velocity: The release velocity, 0-127, defaults to 0. """ _STATUS = 0x80 _STATUSMASK = 0xf0 LENGTH = 3 def __init__(self, note, velocity=0, *, channel=None): self.note = note_parser(note) self.velocity = velocity super().__init__(channel=channel) if not 0 <= self.note <= 127 or not 0 <= self.velocity <= 127: raise self._EX_VALUEERROR_OOR def __bytes__(self): return bytes([self._STATUS | (self.channel & self.CHANNELMASK), self.note, self.velocity]) @classmethod def from_bytes(cls, msg_bytes): return cls(msg_bytes[1], msg_bytes[2], channel=msg_bytes[0] & cls.CHANNELMASK) NoteOff.register_message_type()
[ "kjw.github@gmail.com" ]
kjw.github@gmail.com
7d1b61dc8d3700ed9b7482fdcdca7d06ddf849f0
a6fc4ccb433648e9c9179bf788ad256a0f2a92cf
/src/rlipp_helper.py
aa1f3272abc9c4089f42c4fc7f1459e3c845d64a
[]
no_license
paultianzeguo/nest_drugcell_sdp
9edc7f4a1060de5105f240c0821882236988c10f
ff6f1478e9cd0d15cc277343622a16c00a7bcaeb
refs/heads/master
2023-08-29T13:38:58.109522
2021-10-29T17:52:39
2021-10-29T17:52:39
423,262,480
0
0
null
null
null
null
UTF-8
Python
false
false
1,276
py
import argparse from rlipp_calculator import * def main(): parser = argparse.ArgumentParser(description = 'RLIPP score calculation') parser.add_argument('-hidden', help = 'Hidden folders path', type = str) parser.add_argument('-ontology', help = 'Ontology file', type = str) parser.add_argument('-test', help = 'Test file', type = str) parser.add_argument('-predicted', help = 'Predicted result file', type = str) parser.add_argument('-drug_index', help = 'Drug-index file', type = str) parser.add_argument('-gene_index', help = 'Gene-index file', type = str) parser.add_argument('-cell_index', help = 'Cell-index file', type = str) parser.add_argument('-cell_mutation', help = 'Cell line mutation file', type = str) parser.add_argument('-output', help = 'Output file', type = str) parser.add_argument('-cpu_count', help = 'No of available cores', type = int, default = 1) parser.add_argument('-drug_count', help = 'No of top performing drugs', type = int, default = 0) parser.add_argument('-genotype_hiddens', help = 'Mapping for the number of neurons in each term in genotype parts', type = int, default = 6) cmd_args = parser.parse_args() rlipp_calculator = RLIPPCalculator(cmd_args) rlipp_calculator.calc_scores() if __name__ == "__main__": main()
[ "a2singhal@ucsd.edu" ]
a2singhal@ucsd.edu
ba006fc6e918649026dc09c0e93be3ee8e94b3fb
ad55ce7a2bba6fa7019b09e9794aa4c404978223
/models_test.py
d1ab9cf1e40a95cd848235c343a8f812a3fd727b
[]
no_license
SongJae/SELD
0cb39d56f20dbd7d43307894ce113536a83fc384
e3e813495e68250513bd79d87af34daf8c3bcaa7
refs/heads/main
2023-03-15T05:26:59.554335
2021-03-09T00:40:31
2021-03-09T00:40:31
345,834,527
0
0
null
2021-03-09T00:28:19
2021-03-09T00:28:18
null
UTF-8
Python
false
false
1,051
py
import os import tensorflow as tf from models import * class ModelsTest(tf.test.TestCase): def setUp(self): self.batch = 32 self.freq = 257 self.time = 60 self.chan = 2 self.n_classes = 2 self.x = tf.zeros((self.batch, self.freq, self.time, self.chan)) def test_seldnet_architecture(self): model = seldnet_architecture( self.x.shape, hlfr=lambda x: x, tcr=lambda x: tf.reduce_mean(x, axis=1), sed=lambda x: tf.keras.layers.Dense(self.n_classes)(x), doa=lambda x: tf.keras.layers.Dense(self.n_classes*3)(x)) y = model.predict(self.x) # SED self.assertAllEqual(y[0].shape, [self.batch, self.time, self.n_classes]) # DOA self.assertAllEqual(y[1].shape, [self.batch, self.time, self.n_classes*3]) if __name__ == '__main__': os.environ['CUDA_VISIBLE_DEVICES'] = '-1' tf.test.main()
[ "daniel03c195@gmail.com" ]
daniel03c195@gmail.com
eceb63dd7c16d972d345b43acd7ca8ff2bd8aa2e
667af8c92c5053c6dfc2ecd50806a5583bcf89d4
/class3_files/memorycheat3.py
bfb280c8ed41d529a3469cf9f49cc1fa183f48ef
[]
no_license
pygame2018/spring18
e5f166db3ecdaf9b499739902c84aca8034cea52
e556a62fb0dc81b999cc307676980d8877c363c7
refs/heads/master
2018-08-30T17:52:45.321773
2018-06-17T15:01:10
2018-06-17T15:01:10
119,594,818
0
0
null
null
null
null
UTF-8
Python
false
false
12,784
py
# Memory Puzzle # By Al Sweigart al@inventwithpython.com # http://inventwithpython.com/pygame # Released under a "Simplified BSD" license import random, pygame, sys from pygame.locals import * FPS = 30 # frames per second, the general speed of the program WINDOWWIDTH = 640 # size of window's width in pixels WINDOWHEIGHT = 480 # size of windows' height in pixels REVEALSPEED = 8 # speed boxes' sliding reveals and covers BOXSIZE = 40 # size of box height & width in pixels GAPSIZE = 10 # size of gap between boxes in pixels BOARDWIDTH = 10 # number of columns of icons BOARDHEIGHT = 7 # number of rows of icons assert (BOARDWIDTH * BOARDHEIGHT) % 2 == 0, 'Board needs to have an even number of boxes for pairs of matches.' XMARGIN = int((WINDOWWIDTH - (BOARDWIDTH * (BOXSIZE + GAPSIZE))) / 2) YMARGIN = int((WINDOWHEIGHT - (BOARDHEIGHT * (BOXSIZE + GAPSIZE))) / 2) # R G B GRAY = (100, 100, 100) NAVYBLUE = ( 60, 60, 100) WHITE = (255, 255, 255) RED = (255, 0, 0) GREEN = ( 0, 255, 0) BLUE = ( 0, 0, 255) YELLOW = (255, 255, 0) ORANGE = (255, 128, 0) PURPLE = (255, 0, 255) CYAN = ( 0, 255, 255) BGCOLOR = NAVYBLUE LIGHTBGCOLOR = GRAY BOXCOLOR = WHITE HIGHLIGHTCOLOR = BLUE DONUT = 'donut' SQUARE = 'square' DIAMOND = 'diamond' LINES = 'lines' OVAL = 'oval' ALLCOLORS = (RED, GREEN, BLUE, YELLOW, ORANGE, PURPLE, CYAN) ALLSHAPES = (DONUT, SQUARE, DIAMOND, LINES, OVAL) assert len(ALLCOLORS) * len(ALLSHAPES) * 2 >= BOARDWIDTH * BOARDHEIGHT, "Board is too big for the number of shapes/colors defined." def main(): global FPSCLOCK, DISPLAYSURF pygame.init() useCheat = False cheatType = 'None' cheatCode = 'CHEATS ON! ' fontObj = pygame.font.Font('freesansbold.ttf', 16) FPSCLOCK = pygame.time.Clock() DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT)) mousex = 0 # used to store x coordinate of mouse event mousey = 0 # used to store y coordinate of mouse event pygame.display.set_caption('Memory Game') mainBoard = getRandomizedBoard() revealedBoxes = generateRevealedBoxesData(False) firstSelection = None # stores the (x, y) of the first box clicked. DISPLAYSURF.fill(BGCOLOR) startGameAnimation(mainBoard) while True: # main game loop mouseClicked = False DISPLAYSURF.fill(BGCOLOR) # drawing the window drawBoard(mainBoard, revealedBoxes) for event in pygame.event.get(): # event handling loop if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE): pygame.quit() sys.exit() elif event.type == MOUSEMOTION: mousex, mousey = event.pos elif event.type == MOUSEBUTTONUP: mousex, mousey = event.pos mouseClicked = True elif event.type == KEYDOWN: if (event.key == K_RETURN): if (useCheat): useCheat = False else: useCheat = True elif (event.key == K_UP): cheatType = 'RevealAll' elif (event.key == K_DOWN): cheatType = 'RevealOne' boxx, boxy = getBoxAtPixel(mousex, mousey) if boxx != None and boxy != None: # The mouse is currently over a box. if not revealedBoxes[boxx][boxy]: drawHighlightBox(boxx, boxy) if not revealedBoxes[boxx][boxy] and mouseClicked: revealBoxesAnimation(mainBoard, [(boxx, boxy)]) revealedBoxes[boxx][boxy] = True # set the box as "revealed" if firstSelection == None: # the current box was the first box clicked firstSelection = (boxx, boxy) else: # the current box was the second box clicked # Check if there is a match between the two icons. icon1shape, icon1color = getShapeAndColor(mainBoard, firstSelection[0], firstSelection[1]) icon2shape, icon2color = getShapeAndColor(mainBoard, boxx, boxy) if icon1shape != icon2shape or icon1color != icon2color: # Icons don't match. Re-cover up both selections. pygame.time.wait(1000) # 1000 milliseconds = 1 sec coverBoxesAnimation(mainBoard, [(firstSelection[0], firstSelection[1]), (boxx, boxy)]) revealedBoxes[firstSelection[0]][firstSelection[1]] = False revealedBoxes[boxx][boxy] = False elif hasWon(revealedBoxes): # check if all pairs found gameWonAnimation(mainBoard) pygame.time.wait(2000) # Reset the board mainBoard = getRandomizedBoard() revealedBoxes = generateRevealedBoxesData(False) # Show the fully unrevealed board for a second. drawBoard(mainBoard, revealedBoxes) pygame.display.update() pygame.time.wait(1000) # Replay the start game animation. startGameAnimation(mainBoard) firstSelection = None # reset firstSelection variable # Redraw the screen and wait a clock tick. if (useCheat): textSurfaceObj = fontObj.render(cheatCode + cheatType, True, GREEN, BLUE) textRectObj = textSurfaceObj.get_rect() textRectObj.center = (320, 20) DISPLAYSURF.blit(textSurfaceObj, textRectObj) if (cheatType == 'RevealAll'): startGameAnimation(mainBoard) useCheat = False elif (cheatType == 'RevealOne'): matchedBoxes = [] for x in range(BOARDWIDTH): for y in range(BOARDHEIGHT): if ((x,y) != (boxx, boxy) and boxx != None and boxy != None and getShapeAndColor(mainBoard, x,y) == getShapeAndColor(mainBoard, boxx, boxy)): matchedBoxes.append( (x, y) ) revealBoxesAnimation(mainBoard, matchedBoxes) useCheat = False pygame.display.update() FPSCLOCK.tick(FPS) def generateRevealedBoxesData(val): revealedBoxes = [] for i in range(BOARDWIDTH): revealedBoxes.append([val] * BOARDHEIGHT) return revealedBoxes def getRandomizedBoard(): # Get a list of every possible shape in every possible color. icons = [] for color in ALLCOLORS: for shape in ALLSHAPES: icons.append( (shape, color) ) random.shuffle(icons) # randomize the order of the icons list numIconsUsed = int(BOARDWIDTH * BOARDHEIGHT / 2) # calculate how many icons are needed icons = icons[:numIconsUsed] * 2 # make two of each random.shuffle(icons) # Create the board data structure, with randomly placed icons. board = [] for x in range(BOARDWIDTH): column = [] for y in range(BOARDHEIGHT): column.append(icons[0]) del icons[0] # remove the icons as we assign them board.append(column) return board def splitIntoGroupsOf(groupSize, theList): # splits a list into a list of lists, where the inner lists have at # most groupSize number of items. result = [] for i in range(0, len(theList), groupSize): result.append(theList[i:i + groupSize]) return result def leftTopCoordsOfBox(boxx, boxy): # Convert board coordinates to pixel coordinates left = boxx * (BOXSIZE + GAPSIZE) + XMARGIN top = boxy * (BOXSIZE + GAPSIZE) + YMARGIN return (left, top) def getBoxAtPixel(x, y): for boxx in range(BOARDWIDTH): for boxy in range(BOARDHEIGHT): left, top = leftTopCoordsOfBox(boxx, boxy) boxRect = pygame.Rect(left, top, BOXSIZE, BOXSIZE) if boxRect.collidepoint(x, y): return (boxx, boxy) return (None, None) def drawIcon(shape, color, boxx, boxy): quarter = int(BOXSIZE * 0.25) # syntactic sugar half = int(BOXSIZE * 0.5) # syntactic sugar left, top = leftTopCoordsOfBox(boxx, boxy) # get pixel coords from board coords # Draw the shapes if shape == DONUT: pygame.draw.circle(DISPLAYSURF, color, (left + half, top + half), half - 5) pygame.draw.circle(DISPLAYSURF, BGCOLOR, (left + half, top + half), quarter - 5) elif shape == SQUARE: pygame.draw.rect(DISPLAYSURF, color, (left + quarter, top + quarter, BOXSIZE - half, BOXSIZE - half)) elif shape == DIAMOND: pygame.draw.polygon(DISPLAYSURF, color, ((left + half, top), (left + BOXSIZE - 1, top + half), (left + half, top + BOXSIZE - 1), (left, top + half))) elif shape == LINES: for i in range(0, BOXSIZE, 4): pygame.draw.line(DISPLAYSURF, color, (left, top + i), (left + i, top)) pygame.draw.line(DISPLAYSURF, color, (left + i, top + BOXSIZE - 1), (left + BOXSIZE - 1, top + i)) elif shape == OVAL: pygame.draw.ellipse(DISPLAYSURF, color, (left, top + quarter, BOXSIZE, half)) def getShapeAndColor(board, boxx, boxy): # shape value for x, y spot is stored in board[x][y][0] # color value for x, y spot is stored in board[x][y][1] return board[boxx][boxy][0], board[boxx][boxy][1] def drawBoxCovers(board, boxes, coverage): # Draws boxes being covered/revealed. "boxes" is a list # of two-item lists, which have the x & y spot of the box. for box in boxes: left, top = leftTopCoordsOfBox(box[0], box[1]) pygame.draw.rect(DISPLAYSURF, BGCOLOR, (left, top, BOXSIZE, BOXSIZE)) shape, color = getShapeAndColor(board, box[0], box[1]) drawIcon(shape, color, box[0], box[1]) if coverage > 0: # only draw the cover if there is an coverage pygame.draw.rect(DISPLAYSURF, BOXCOLOR, (left, top, coverage, BOXSIZE)) pygame.display.update() FPSCLOCK.tick(FPS) def revealBoxesAnimation(board, boxesToReveal): # Do the "box reveal" animation. for coverage in range(BOXSIZE, (-REVEALSPEED) - 1, -REVEALSPEED): drawBoxCovers(board, boxesToReveal, coverage) def coverBoxesAnimation(board, boxesToCover): # Do the "box cover" animation. for coverage in range(0, BOXSIZE + REVEALSPEED, REVEALSPEED): drawBoxCovers(board, boxesToCover, coverage) def drawBoard(board, revealed): # Draws all of the boxes in their covered or revealed state. for boxx in range(BOARDWIDTH): for boxy in range(BOARDHEIGHT): left, top = leftTopCoordsOfBox(boxx, boxy) if not revealed[boxx][boxy]: # Draw a covered box. pygame.draw.rect(DISPLAYSURF, BOXCOLOR, (left, top, BOXSIZE, BOXSIZE)) else: # Draw the (revealed) icon. shape, color = getShapeAndColor(board, boxx, boxy) drawIcon(shape, color, boxx, boxy) def drawHighlightBox(boxx, boxy): left, top = leftTopCoordsOfBox(boxx, boxy) pygame.draw.rect(DISPLAYSURF, HIGHLIGHTCOLOR, (left - 5, top - 5, BOXSIZE + 10, BOXSIZE + 10), 4) def startGameAnimation(board): # Randomly reveal the boxes 8 at a time. coveredBoxes = generateRevealedBoxesData(False) boxes = [] for x in range(BOARDWIDTH): for y in range(BOARDHEIGHT): boxes.append( (x, y) ) random.shuffle(boxes) boxGroups = splitIntoGroupsOf(8, boxes) drawBoard(board, coveredBoxes) for boxGroup in boxGroups: revealBoxesAnimation(board, boxGroup) coverBoxesAnimation(board, boxGroup) def gameWonAnimation(board): # flash the background color when the player has won coveredBoxes = generateRevealedBoxesData(True) color1 = LIGHTBGCOLOR color2 = BGCOLOR for i in range(13): color1, color2 = color2, color1 # swap colors DISPLAYSURF.fill(color1) drawBoard(board, coveredBoxes) pygame.display.update() pygame.time.wait(300) def hasWon(revealedBoxes): # Returns True if all the boxes have been revealed, otherwise False for i in revealedBoxes: if False in i: return False # return False if any boxes are covered. return True if __name__ == '__main__': main()
[ "acls2018python@gmail.com" ]
acls2018python@gmail.com
d2156cfa96568ef6ca9b5824e5646df35f852c61
f614884c67ed1578574405673ceb726d0eb9a717
/cloudmesh-exercises/E.Cloudmesh.Common.2.py
31e6e0790dd9fd24541602bc8c70e3fd8fac2093
[ "Apache-2.0" ]
permissive
cloudmesh-community/fa19-516-171
5ff9a5ca667948f45b92a663748bb6a7638c5645
1dba8cde09f7b05c80557ea7ae462161c590568b
refs/heads/master
2021-06-26T12:34:22.063922
2020-07-30T12:38:15
2020-07-30T12:38:15
206,808,219
0
2
Apache-2.0
2021-02-08T20:37:15
2019-09-06T14:12:31
Python
UTF-8
Python
false
false
307
py
# E.Cloudmesh.Common.2 ## Develop a program that demonstartes the use of dotdict from cloudmesh.common.dotdict import dotdict from pprint import pprint Jagadeesh = { "Name" : "Jagadeesh", "Class" : "Cloud Computing" } Jagadeesh = dotdict(Jagadeesh) pprint(Jagadeesh.Class)
[ "jkandimaedu@gmail.com" ]
jkandimaedu@gmail.com
b2df8f27cd5d4d14b5223a244f2bcd6cf2720ddc
f64aaa4b0f78774464033148290a13453c96528e
/generated/intermediate/ansible-module-rest/azure_rm_frontdoorroutingrule.py
f59ed875aad2cbda07790fb752d5abdc38e7cce3
[ "MIT" ]
permissive
audevbot/autorest.cli.debug
e8996270a6a931f243532f65782c7f8fbb1b55c6
a507fb6e2dd7826212537f27d583f203aac1c28f
refs/heads/master
2020-06-04T05:25:17.018993
2019-08-27T21:57:18
2019-08-27T21:57:18
191,876,321
0
0
MIT
2019-08-28T05:57:19
2019-06-14T04:35:39
Python
UTF-8
Python
false
false
16,885
py
#!/usr/bin/python # # Copyright (c) 2019 Zim Kalinowski, (@zikalino) # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: azure_rm_frontdoorroutingrule version_added: '2.9' short_description: Manage Azure RoutingRule instance. description: - 'Create, update and delete instance of Azure RoutingRule.' options: resource_group: description: - Name of the Resource group within the Azure subscription. required: true type: str front_door_name: description: - Name of the Front Door which is globally unique. required: true type: str name: description: - Resource name. type: str id: description: - Resource ID. type: str frontend_endpoints: description: - Frontend endpoints associated with this rule type: list suboptions: id: description: - Resource ID. type: str accepted_protocols: description: - Protocol schemes to match for this rule type: list patterns_to_match: description: - The route patterns of the rule. type: list enabled_state: description: - >- Whether to enable use of this rule. Permitted values are 'Enabled' or 'Disabled' type: str route_configuration: description: - A reference to the routing configuration. type: dict resource_state: description: - Resource status. type: str type: description: - Resource type. type: str state: description: - Assert the state of the RoutingRule. - >- Use C(present) to create or update an RoutingRule and C(absent) to delete it. default: present choices: - absent - present extends_documentation_fragment: - azure author: - Zim Kalinowski (@zikalino) ''' EXAMPLES = ''' - name: Create or update specific Forwarding Routing Rule azure_rm_frontdoorroutingrule: resource_group: myResourceGroup front_door_name: myFrontDoor name: myRoutingRule routing_rule_parameters: name: routingRule1 properties: frontendEndpoints: - id: >- /subscriptions/{{ subscription_id }}/resourceGroups/{{ resource_group }}/providers/Microsoft.Network/frontDoors/{{ front_door_name }}/frontendEndpoints/{{ frontend_endpoint_name }} - id: >- /subscriptions/{{ subscription_id }}/resourceGroups/{{ resource_group }}/providers/Microsoft.Network/frontDoors/{{ front_door_name }}/frontendEndpoints/{{ frontend_endpoint_name }} acceptedProtocols: - Http patternsToMatch: - /* routeConfiguration: '@odata.type': '#Microsoft.Azure.FrontDoor.Models.FrontdoorForwardingConfiguration' backendPool: id: >- /subscriptions/{{ subscription_id }}/resourceGroups/{{ resource_group }}/providers/Microsoft.Network/frontDoors/{{ front_door_name }}/backendPools/{{ backend_pool_name }} enabledState: Enabled - name: Create or update specific Redirect Routing Rule azure_rm_frontdoorroutingrule: resource_group: myResourceGroup front_door_name: myFrontDoor name: myRoutingRule routing_rule_parameters: name: redirectRoutingRule1 properties: frontendEndpoints: - id: >- /subscriptions/{{ subscription_id }}/resourceGroups/{{ resource_group }}/providers/Microsoft.Network/frontDoors/{{ front_door_name }}/frontendEndpoints/{{ frontend_endpoint_name }} - id: >- /subscriptions/{{ subscription_id }}/resourceGroups/{{ resource_group }}/providers/Microsoft.Network/frontDoors/{{ front_door_name }}/frontendEndpoints/{{ frontend_endpoint_name }} acceptedProtocols: - Https patternsToMatch: - /* routeConfiguration: '@odata.type': '#Microsoft.Azure.FrontDoor.Models.FrontdoorRedirectConfiguration' redirectType: Moved redirectProtocol: HttpsOnly customHost: www.bing.com customPath: /api customFragment: fragment customQueryString: a=b enabledState: Enabled - name: Delete Routing Rule azure_rm_frontdoorroutingrule: resource_group: myResourceGroup front_door_name: myFrontDoor name: myRoutingRule state: absent ''' RETURN = ''' id: description: - Resource ID. returned: always type: str sample: null properties: description: - Properties of the Front Door Routing Rule returned: always type: dict sample: null contains: frontend_endpoints: description: - Frontend endpoints associated with this rule returned: always type: dict sample: null contains: id: description: - Resource ID. returned: always type: str sample: null accepted_protocols: description: - Protocol schemes to match for this rule returned: always type: str sample: null patterns_to_match: description: - The route patterns of the rule. returned: always type: str sample: null enabled_state: description: - >- Whether to enable use of this rule. Permitted values are 'Enabled' or 'Disabled' returned: always type: str sample: null route_configuration: description: - A reference to the routing configuration. returned: always type: dict sample: null resource_state: description: - Resource status. returned: always type: str sample: null name: description: - Resource name. returned: always type: str sample: null type: description: - Resource type. returned: always type: str sample: null ''' import time import json import re from ansible.module_utils.azure_rm_common_ext import AzureRMModuleBaseExt from ansible.module_utils.azure_rm_common_rest import GenericRestClient from copy import deepcopy try: from msrestazure.azure_exceptions import CloudError except ImportError: # this is handled in azure_rm_common pass class Actions: NoAction, Create, Update, Delete = range(4) class AzureRMRoutingRules(AzureRMModuleBaseExt): def __init__(self): self.module_arg_spec = dict( resource_group=dict( type='str', updatable=False, disposition='resourceGroupName', required=true ), front_door_name=dict( type='str', updatable=False, disposition='frontDoorName', required=true ), name=dict( type='str', updatable=False, disposition='routingRuleName', required=true ), id=dict( type='str', updatable=False, disposition='/' ), frontend_endpoints=dict( type='list', disposition='/properties/frontendEndpoints', options=dict( id=dict( type='str' ) ) ), accepted_protocols=dict( type='list', disposition='/properties/acceptedProtocols', choices=['Http', 'Https'] ), patterns_to_match=dict( type='list', disposition='/properties/patternsToMatch' ), enabled_state=dict( type='str', disposition='/properties/enabledState', choices=['Enabled', 'Disabled'] ), route_configuration=dict( type='dict', disposition='/properties/routeConfiguration' ), resource_state=dict( type='str', disposition='/properties/resourceState', choices=['Creating', 'Enabling', 'Enabled', 'Disabling', 'Disabled', 'Deleting'] ), name=dict( type='str', updatable=False, disposition='/' ), state=dict( type='str', default='present', choices=['present', 'absent'] ) ) self.resource_group = None self.front_door_name = None self.name = None self.type = None self.results = dict(changed=False) self.mgmt_client = None self.state = None self.url = None self.status_code = [200, 201, 202] self.to_do = Actions.NoAction self.body = {} self.query_parameters = {} self.query_parameters['api-version'] = '2019-04-01' self.header_parameters = {} self.header_parameters['Content-Type'] = 'application/json; charset=utf-8' super(AzureRMRoutingRules, self).__init__(derived_arg_spec=self.module_arg_spec, supports_check_mode=True, supports_tags=True) def exec_module(self, **kwargs): for key in list(self.module_arg_spec.keys()): if hasattr(self, key): setattr(self, key, kwargs[key]) elif kwargs[key] is not None: self.body[key] = kwargs[key] self.inflate_parameters(self.module_arg_spec, self.body, 0) old_response = None response = None self.mgmt_client = self.get_mgmt_svc_client(GenericRestClient, base_url=self._cloud_environment.endpoints.resource_manager) resource_group = self.get_resource_group(self.resource_group) self.url = ('/subscriptions' + '/{{ subscription_id }}' + '/resourceGroups' + '/{{ resource_group }}' + '/providers' + '/Microsoft.Network' + '/frontDoors' + '/{{ front_door_name }}' + '/routingRules' + '/{{ routing_rule_name }}') self.url = self.url.replace('{{ subscription_id }}', self.subscription_id) self.url = self.url.replace('{{ resource_group }}', self.resource_group) self.url = self.url.replace('{{ front_door_name }}', self.front_door_name) self.url = self.url.replace('{{ routing_rule_name }}', self.name) old_response = self.get_resource() if not old_response: self.log("RoutingRule instance doesn't exist") if self.state == 'absent': self.log("Old instance didn't exist") else: self.to_do = Actions.Create else: self.log('RoutingRule instance already exists') if self.state == 'absent': self.to_do = Actions.Delete else: modifiers = {} self.create_compare_modifiers(self.module_arg_spec, '', modifiers) self.results['modifiers'] = modifiers self.results['compare'] = [] self.create_compare_modifiers(self.module_arg_spec, '', modifiers) if not self.default_compare(modifiers, self.body, old_response, '', self.results): self.to_do = Actions.Update if (self.to_do == Actions.Create) or (self.to_do == Actions.Update): self.log('Need to Create / Update the RoutingRule instance') if self.check_mode: self.results['changed'] = True return self.results response = self.create_update_resource() # if not old_response: self.results['changed'] = True # else: # self.results['changed'] = old_response.__ne__(response) self.log('Creation / Update done') elif self.to_do == Actions.Delete: self.log('RoutingRule instance deleted') self.results['changed'] = True if self.check_mode: return self.results self.delete_resource() # make sure instance is actually deleted, for some Azure resources, instance is hanging around # for some time after deletion -- this should be really fixed in Azure while self.get_resource(): time.sleep(20) else: self.log('RoutingRule instance unchanged') self.results['changed'] = False response = old_response if response: self.results["id"] = response["id"] self.results["properties"] = response["properties"] self.results["name"] = response["name"] self.results["type"] = response["type"] return self.results def create_update_resource(self): # self.log('Creating / Updating the RoutingRule instance {0}'.format(self.)) try: response = self.mgmt_client.query(self.url, 'PUT', self.query_parameters, self.header_parameters, self.body, self.status_code, 600, 30) except CloudError as exc: self.log('Error attempting to create the RoutingRule instance.') self.fail('Error creating the RoutingRule instance: {0}'.format(str(exc))) try: response = json.loads(response.text) except Exception: response = {'text': response.text} pass return response def delete_resource(self): # self.log('Deleting the RoutingRule instance {0}'.format(self.)) try: response = self.mgmt_client.query(self.url, 'DELETE', self.query_parameters, self.header_parameters, None, self.status_code, 600, 30) except CloudError as e: self.log('Error attempting to delete the RoutingRule instance.') self.fail('Error deleting the RoutingRule instance: {0}'.format(str(e))) return True def get_resource(self): # self.log('Checking if the RoutingRule instance {0} is present'.format(self.)) found = False try: response = self.mgmt_client.query(self.url, 'GET', self.query_parameters, self.header_parameters, None, self.status_code, 600, 30) found = True self.log("Response : {0}".format(response)) # self.log("RoutingRule instance : {0} found".format(response.name)) except CloudError as e: self.log('Did not find the RoutingRule instance.') if found is True: return response return False def main(): AzureRMRoutingRules() if __name__ == '__main__': main()
[ "audevbot@microsoft.com" ]
audevbot@microsoft.com
c370f52d687214be35f297780c6357699c071400
6ef78d888bf0940645e47237cd9e5214d254aa80
/course_selection_model/src/core.py
e75ac3e79c0546c5a741eddb0c2720b68682d60f
[]
no_license
EnochMeng/exercise_library
ae477d246eee2c252dcd516c006fc68b588c750b
e041619787c9045947366166deb7c4d001b0020c
refs/heads/master
2021-09-07T17:04:39.630195
2018-02-26T14:59:22
2018-02-26T14:59:22
115,167,496
0
0
null
null
null
null
UTF-8
Python
false
false
13,057
py
#! /usr/bin/env python # -*- coding: utf-8 -*- # __author__ = "Sam" # Date: 2017/7/4 from src import models from conf import settings import pickle import os s1 = models.School('北京校区', '中国北京') s2 = models.School('上海校区', '中国上海') python = s1.create_course('Python', 19800, '6mons') linux = s1.create_course('Linux', 17800, '4mons') go = s2.create_course('Go', 9000, '4mons') school_obj = None def func(): while True: print('欢迎进入老男孩选课系统'.center(30, '*'), '\n1.北京校区\n' '2.上海校区\n' '3.退出程序') res = input('请选择学校: ').strip() global school_obj if res == '1': school_obj = s1 elif res == '2': school_obj = s2 elif res == '3': break else: print('输入错误') continue while True: print('请选择视图'.center(30, '*')) cmd = input('1.学生视图\n' '2.老师视图\n' '3.管理员视图\n' '4.返回上一级\n' '5.退出选课系统: ').strip() if cmd == '1': student_view() elif cmd == '2': teacher_view() elif cmd == '3': admin_viwe() elif cmd == '4': break elif cmd == '5': exit() else: print('输入错误,请重新输入!') continue return school_obj def student_view(): '''学生视图''' while True: tag = True print('欢迎进入学生视图,请选择功能'.center(30, '*')) cmd = input('1.注册信息\n' '2.登录\n' # 循环选择功能 '3.返回上级\n' '4.退出程序: ').strip() if cmd == '1': while True: print('欢迎注册学生信息'.center(30, '-')) name = input('name: ').strip() name_id = input('name_id: ').strip() # 注册信息 age = input('age: ').strip() sex = input('sex: ').strip() if not name: print('姓名必填') continue break student_obj = models.Student(name, name_id, age, sex) student_obj.save() elif cmd == '2': while tag: print('请登录'.center(30, '-')) name = input('请输入用户名: ') name_id = input('请输入用户id: ') # 登录,如果数据库中有这个人的文件,继续,否则打印用户不存在 res = os.listdir(settings.STUDENTDB_PATH) for item in res: file_path = r'%s\%s' % (settings.STUDENTDB_PATH, item) with open(file_path, 'rb') as f: student_obj = pickle.load(f) if name == student_obj.name and name_id == student_obj.user_id: while tag: cmd = input('登录成功\n' '1.交学费\n' '2.选择班级\n' '3.返回上级\n' '4.退出程序\n' '请选择功能: ').strip() if cmd == '1': # 交学费 money = int(input('请输入缴纳金额: ')) student_obj.tuition += money print('缴纳成功,学费余额为%s' % student_obj.tuition) student_obj.save() elif cmd == '2': # 选择班级 res = os.listdir(settings.CLASS_PATH) for item in res: file_path = r'%s\%s' % (settings.CLASS_PATH, item) with open(file_path, 'rb') as f: class_obj = pickle.load(f) print('班级名称:<%s> 班级所学课程<%s>' % (class_obj.name, class_obj.course)) course_cmd = input('请选择班级:') res = os.listdir(settings.CLASS_PATH) for item in res: file_path = r'%s\%s' % (settings.CLASS_PATH, item) with open(file_path, 'rb') as f: class_obj = pickle.load(f) if course_cmd == class_obj.name: for i in class_obj.student: if student_obj.id == i.id: print('班级已有此人') # 如果班级里已有此人,则结束村换 tag = False else: class_obj.student.append(student_obj) student_obj.student_class.append(class_obj) student_obj.save() class_obj.save() print('班级添加成功') student_obj.tell_info() elif cmd == '3': tag = False elif cmd == '4': exit() else: continue else: print('用户不存在') tag = False elif cmd == '3': return elif cmd == '4': exit() else: continue def teacher_view(): '''讲师视图''' tag = True # 添加一个标志位 while tag: print('请登录'.center(30, '-')) name = input('请输入用户名: ').strip() name_id = input('请输入用户id: ').strip() res = os.listdir(settings.TEACHERDB_PATH) for item in res: file_path = r'%s\%s' % (settings.TEACHERDB_PATH, item) with open(file_path, 'rb') as f: teacher_obj = pickle.load(f) if name == teacher_obj.name and name_id == teacher_obj.user_id: while tag: print('欢迎进入讲师视图'.center(30, '*')) cmd = input('1.管理班级\n' '2.选择上课班级\n' '3.查看班级学员列表\n' '4.修改学员成绩\n' '5.返回上一级\n' '6.退出选课系统\n' '请选择功能: ').strip() if cmd == '1': for i in teacher_obj.teacher_class: i.tell_info() elif cmd == '2': res = os.listdir(settings.CLASS_PATH) for item in res: file_path = r'%s\%s' % (settings.CLASS_PATH, item) with open(file_path, 'rb') as f: class_obj = pickle.load(f) print('班级名称:<%s> 班级所学课程<%s>' % (class_obj.name, class_obj.course)) class_cmd = input('请选择班级:') res = os.listdir(settings.CLASS_PATH) for item in res: file_path = r'%s\%s' % (settings.CLASS_PATH, item) with open(file_path, 'rb') as f: class_obj = pickle.load(f) if class_obj.name == class_cmd: class_obj.teacher.append(teacher_obj) teacher_obj.teacher_class.append(class_obj) teacher_obj.save() class_obj.save() teacher_obj.tell_info() elif cmd == '3': for i in teacher_obj.teacher_class: for j in i.student: j.tell_info() elif cmd == '4': name = input('请输入想要修改的学生姓名:').strip() name_id = input('请输入学生id: ').strip() num = int(input('请输入要修改的成绩: ').strip()) res = os.listdir(settings.STUDENTDB_PATH) for item in res: file_path = r'%s\%s' % (settings.STUDENTDB_PATH, item) with open(file_path, 'rb') as f: student_obj = pickle.load(f) if name == student_obj.name and name_id == student_obj.user_id: student_obj.grade += num print('%s 的成绩已修改为 %s' % (student_obj.name, num)) student_obj.save() elif cmd == '5': tag = False elif cmd == '6': exit() else: continue def admin_viwe(): '''管理员视图''' print('请用管理员的身份登录,用户名:sam,密码:666'.center(30, '*')) # 管理员有固定的用户名密码 name = input('请输入用户名: ') password = input('请输入密码: ') if name == 'sam' and password == '666': while True: print('欢迎进入管理员视图'.center(30, '-')) cmd = input('1.创建讲师\n' '2.创建班级\n' '3.创建课程\n' '4.返回\n' '5.退出选课系统\n' '请选择功能: ') if cmd == '1': name = input('请输入讲师姓名: ').strip() user_id = input('请输入讲师id: ').strip() age = input('请输入讲师年纪: ').strip() sex = input('请输入讲师性别: ').strip() salary = input('请输入讲师薪资: ').strip() if not name: print('名字不能为空') continue teacher = school_obj.create_teacher(name, user_id, age, sex, salary) teacher.save() school_obj.save() print('%s 老师的信息创建成功' % teacher.name) teacher.tell_info() elif cmd == '2': name = input('请输入班级名: ').strip() course = input('请输入班级课程: ').strip() if not name or not course: print('输入错误') continue class_obj = school_obj.create_class(name, course) class_obj.save() school_obj.save() print('%s 班级创建成功' % class_obj.name) class_obj.tell_info() elif cmd == '3': course = input('请输入课程名字: ').strip() price = input('请输入课程价钱: ').strip() period = input('请输入课程周期: ').strip() if not course or not price or not period: print('输入错误') continue course_obj = school_obj.create_course(course, price, period) course_obj.save() school_obj.save() print('%s 课程创建成功' % course_obj.course) course_obj.tell_course() elif cmd == '4': return elif cmd == '5': exit() else: continue else: print('用户名密码错误') if __name__ == '__main__': func()
[ "lingchuanmeng@foxmail" ]
lingchuanmeng@foxmail
a1d530110266afe81a9bbd327cde526441ccc73b
b79bce0cf363d2b6dd11371d378d78d48e973270
/tests/test_custom_multi_output_classification.py
d9959a3efafdab09cb105e8eec4ea79477e7dcfa
[ "Apache-2.0" ]
permissive
CharlotteSean/Kashgari
2d9338761b16d9804fb81ff92ce2ab1d256c80a7
ab9970ecf6c0164416bfbbec1378c690b0f00d76
refs/heads/master
2022-01-22T03:52:12.284458
2019-07-17T03:48:04
2019-07-17T03:48:04
197,900,673
2
0
Apache-2.0
2019-07-20T08:15:03
2019-07-20T08:15:03
null
UTF-8
Python
false
false
4,917
py
# encoding: utf-8 # author: BrikerMan # contact: eliyar917@gmail.com # blog: https://eliyar.biz # file: test_custom_multi_output_classification.py # time: 2019-05-22 13:36 import unittest import numpy as np import tensorflow as tf import kashgari from typing import Tuple, List, Optional, Dict, Any from kashgari.layers import L from kashgari.processors.classification_processor import ClassificationProcessor from kashgari.tasks.classification.base_model import BaseClassificationModel from kashgari.corpus import SMP2018ECDTCorpus from tensorflow.python.keras.utils import to_categorical train_x, train_y = SMP2018ECDTCorpus.load_data('valid') output_1_raw = np.random.randint(3, size=len(train_x)) output_2_raw = np.random.randint(3, size=len(train_x)) output_1 = to_categorical(output_1_raw, 3) output_2 = to_categorical(output_2_raw, 3) print(train_x[:5]) print(output_1[:5]) print(output_2[:5]) print(len(train_x)) print(output_1.shape) print(output_2.shape) class MultiOutputProcessor(ClassificationProcessor): def process_y_dataset(self, data: Tuple[List[List[str]], ...], maxlens: Optional[Tuple[int, ...]] = None, subset: Optional[List[int]] = None) -> Tuple[np.ndarray, ...]: # Data already converted to one-hot # Only need to get the subset result = [] for index, dataset in enumerate(data): if subset is not None: target = kashgari.utils.get_list_subset(dataset, subset) else: target = dataset result.append(np.array(target)) if len(result) == 1: return result[0] else: return tuple(result) def _build_label_dict(self, labels: List[str]): # Data already converted to one-hot # No need to build label dict self.label2idx = {1: 1, 0: 0} self.idx2label = dict([(value, key) for key, value in self.label2idx.items()]) self.dataset_info['label_count'] = len(self.label2idx) class MultiOutputModel(BaseClassificationModel): @classmethod def get_default_hyper_parameters(cls) -> Dict[str, Dict[str, Any]]: return { 'layer_bi_lstm': { 'units': 256, 'return_sequences': False } } def build_model_arc(self): config = self.hyper_parameters embed_model = self.embedding.embed_model layer_bi_lstm = L.Bidirectional(L.LSTM(**config['layer_bi_lstm']), name='layer_bi_lstm') layer_output_1 = L.Dense(3, activation='sigmoid', name='layer_output_1') layer_output_2 = L.Dense(3, activation='sigmoid', name='layer_output_2') tensor = layer_bi_lstm(embed_model.output) output_tensor_1 = layer_output_1(tensor) output_tensor_2 = layer_output_2(tensor) self.tf_model = tf.keras.Model(embed_model.inputs, [output_tensor_1, output_tensor_2]) def predict(self, x_data, batch_size=None, debug_info=False, threshold=0.5): tensor = self.embedding.process_x_dataset(x_data) pred = self.tf_model.predict(tensor, batch_size=batch_size) output_1 = pred[0] output_2 = pred[1] output_1[output_1 >= threshold] = 1 output_1[output_1 < threshold] = 0 output_2[output_2 >= threshold] = 1 output_2[output_2 < threshold] = 0 return output_1, output_2 class TestCustomMultiOutputModel(unittest.TestCase): def test_build_and_fit(self): from kashgari.embeddings import BareEmbedding processor = MultiOutputProcessor() embedding = BareEmbedding(processor=processor) m = MultiOutputModel(embedding=embedding) m.build_model(train_x, (output_1, output_2)) m.fit(train_x, (output_1, output_2), epochs=2) res = m.predict(train_x[:10]) assert len(res) == 2 assert res[0].shape == (10, 3) def test_build_with_BERT_and_fit(self): from kashgari.embeddings import BERTEmbedding from tensorflow.python.keras.utils import get_file from kashgari.macros import DATA_PATH sample_bert_path = get_file('bert_sample_model', "http://s3.bmio.net/kashgari/bert_sample_model.tar.bz2", cache_dir=DATA_PATH, untar=True) processor = MultiOutputProcessor() embedding = BERTEmbedding( model_folder=sample_bert_path, processor=processor) m = MultiOutputModel(embedding=embedding) m.build_model(train_x, (output_1, output_2)) m.fit(train_x, (output_1, output_2), epochs=2) res = m.predict(train_x[:10]) assert len(res) == 2 assert res[0].shape == (10, 3)
[ "eliyar917@gmail.com" ]
eliyar917@gmail.com
3c689db02683734bbd8d2366bb7ce24d2d8b02cb
22378261a582276ebb60f23d92271230da2d48e4
/tmp/cut_text.py
7c031f565a7a338f14847c37a1229c8763e9e6e2
[]
no_license
incliff/scraping_shunfeng_order
6cb854a074aac42841a17582388cb4f880da55a9
7240396bb2c80b94eecad6574f968846217cfb26
refs/heads/master
2021-02-26T23:13:34.297589
2020-09-10T05:09:20
2020-09-10T05:09:20
245,558,328
0
0
null
null
null
null
UTF-8
Python
false
false
3,229
py
from selenium import webdriver from selenium.webdriver import ActionChains from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException import time driver = webdriver.Chrome(executable_path="D:\DEV\chromedriver.exe") # driver.get("https://www.sf-express.com/cn/sc/dynamic_function/waybill/#search/bill-number/291305897906") driver.get("https://www.sf-express.com/cn/sc/dynamic_function/waybill/#search/bill-number/SF1071817875791,SF1071817875904,SF1071817875861,SF1071817875959,288218304352,SF1071817875898,SF1071817875782,288218304264,SF1071817875870,SF1071817875825,SF1071817876025,SF1071817876016,SF1071817876034,SF1071817876122,SF1071817876061,SF1071817876140,SF1071817876104,SF1071817876186,SF1071817876201,288313684364") try: deliveries = WebDriverWait(driver, 15).until( EC.presence_of_all_elements_located((By.XPATH, "//div[@class='delivery-wrapper']/div[@class='delivery']")) ) # open_map_checkbox = WebDriverWait(driver, 3).until( # EC.presence_of_element_located((By.XPATH, "//div[@class='fr openMapModel']/input")) # ) # open_map_checkbox.click() driver.find_element_by_xpath("//div[@class='fr openMapModel']/input").click() for index, delivery in enumerate(deliveries): bill_num = delivery.find_element_by_xpath(".//div[@class='bill-num']/span[@class='number']").text print("===================={}、{}==================".format(index + 1, bill_num)) print(bill_num) text = delivery.find_element_by_xpath(".//div[@class='route-list']/ul[1]/li[1]/span").text time = delivery.find_element_by_xpath(".//div[@class='route-list']/ul[1]/li[@class='route-date-time']/span").text print({"text": text, "time": time}) text = delivery.find_element_by_xpath(".//div[@class='route-list']/ul[last()]/li[1]/span").text time = delivery.find_element_by_xpath(".//div[@class='route-list']/ul[last()]/li[@class='route-date-time']/span").text print({"text": text, "time": time}) print("打印完毕") except TimeoutException as e: print("等待超时") finally: print("准备退出") driver.quit() # time.sleep(10) # deliveries = driver.find_elements_by_xpath("//div[@class='delivery-wrapper']/div[@class='delivery']") # for index, delivery in enumerate(deliveries): # bill_num = delivery.find_element_by_xpath(".//div[@class='bill-num']/span[@class='number']").text # print("===================={}、{}==================".format(index + 1, bill_num)) # print(bill_num) # text = delivery.find_element_by_xpath(".//div[@class='route-list']/ul[1]/li[1]/span").text # time = delivery.find_element_by_xpath(".//div[@class='route-list']/ul[1]/li[@class='route-date-time']/span").text # print({"text": text, "time": time}) # text = delivery.find_element_by_xpath(".//div[@class='route-list']/ul[last()]/li[1]/span").text # time = delivery.find_element_by_xpath(".//div[@class='route-list']/ul[last()]/li[@class='route-date-time']/span").text # print({"text": text, "time": time})
[ "inciff@163.com" ]
inciff@163.com
18d541bcedfebd54f615819d9f463f9a4f5d577f
22c457aa0a8617d75ade0695490fe4bb9f54922a
/storyBegins.py
d8d106c68c3db5aa81db2b9cf4e58103a29bd959
[]
no_license
skimaxedout/old-Chris-Adventure
459659269640668df7bfb81f5d0983f869b266f6
a550e55885f22fe5e8440acd9389357914a0d546
refs/heads/master
2021-06-20T14:31:11.805737
2017-07-19T01:14:39
2017-07-19T01:14:39
null
0
0
null
null
null
null
UTF-8
Python
false
false
848
py
import time #story begins, scene is set print "It's Friday at 4:48pm, the office is almost empty." time.sleep(2) print "You've been checking your watch every minute for the past hour." time.sleep(2) print "5 o'clock can't come fast enough." time.sleep(2) print "You see your new boss waddling down the hall." time.sleep(2) print "Shit. You make eye contact." time.sleep(2) print "He calls out, 'What the hell's your name again?'" #user establishes his/her name userName = raw_input("> ") time.sleep(1) print "'Ah right... %s'" % userName time.sleep(1) print "'I'm gonna need you to stay until six tonight.'" time.sleep(1) #decision making begins print "Do you say 'yes' or 'no'?" workLate = raw_input("> ") if workLate == "yes": execfile('workLateYes.py') elif workLate == "no": execfile('workLateNo.py')
[ "linkspitfire@yahoo.com" ]
linkspitfire@yahoo.com
64205a81dbe8d90601fab9c1baae0cb7ebf55939
34cd8c42bac69e81cec6e61c280db2ca0891e3e9
/platform/streaming_platform/wsgi.py
9e8ba9688b875d749042ddb834604c33ca90774d
[]
no_license
petrichbg/JustAnotherTwitchClone
8040abc3cd754ed44f08a8473934c41134685a6f
b85639603a82760485436e82383aa397ddfc575e
refs/heads/master
2021-10-20T14:52:51.133945
2019-02-28T12:32:13
2019-02-28T12:32:13
null
0
0
null
null
null
null
UTF-8
Python
false
false
413
py
""" WSGI config for streaming_platform project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "streaming_platform.settings") application = get_wsgi_application()
[ "suxinjke@gmail.com" ]
suxinjke@gmail.com
2bb3d78de34f01eb1c772aad34792e4282d2cbbd
e4ffe7fe6a2bb437717db4f6a33d73bce378c887
/TimerTrigger1/__init__.py
f1d20e18245bfe0533ea252f63f0d51eada52764
[]
no_license
TONYRYANWORLDWIDE/GoogleCalendar
f3fa1b8c01992d8b347ceb953831f196ae95e9a8
3cc99111a092fca41cfa0767786a75f9c25eb63d
refs/heads/master
2023-02-26T20:01:45.573855
2021-01-09T13:03:05
2021-01-09T13:03:05
327,047,211
0
0
null
null
null
null
UTF-8
Python
false
false
397
py
import datetime import logging import azure.functions as func from . import app def main(mytimer: func.TimerRequest) -> None: utc_timestamp = datetime.datetime.utcnow().replace( tzinfo=datetime.timezone.utc).isoformat() app.main() if mytimer.past_due: logging.info('The timer is past due!') logging.info('Python timer trigger function ran at %s', utc_timestamp)
[ "aryan@masseyservices.com" ]
aryan@masseyservices.com
76ca764461a356281e93bef498c748c763889d90
e8137a851a4f78d3e280b3873b13e4038f2c5f6c
/Hex.py
a7f9a2c3443a57db736d9547250ccbb0e61a15a4
[]
no_license
Miccaldo/2048-HEX
48b1938d4820a1364c0f6b97fe83fc388670d7a9
94c3a7236f8a8edde83790446626054d4b1c38fe
refs/heads/master
2022-10-18T13:58:37.614103
2019-04-25T15:38:02
2019-04-25T15:38:02
null
0
0
null
null
null
null
UTF-8
Python
false
false
8,799
py
from PyQt5 import QtCore from PyQt5.QtWidgets import QGraphicsItem from PyQt5.QtGui import QPolygonF, QPen, QFont, QBrush from PyQt5.QtCore import Qt, QRectF, QPointF import pyautogui class Hex(QGraphicsItem): def __init__(self, x, y, value, parent=None): super(Hex, self).__init__() self.setFlag(QGraphicsItem.ItemIsMovable, True) self.setFlag(QGraphicsItem.ItemIsSelectable, True) self.setFlag(QGraphicsItem.ItemIsFocusable, True) self.x = x self.y = y self.size = 75 self.gesturesX = [] self.gesturesY = [] self.startX = 0 self.startY = 0 self.startFlag = False self.moveX = 0 self.moveY = 0 self.value = value self.setAcceptHoverEvents(True) self.up = False self.down = False self.upLeft = False self.upRight = False self.downLeft = False self.downRight = False self.cntX = x self.cntY = y self.newIndexColumn = 0 self.newIndexRow = 5 self.valueBuf = self.value self.paintFlag = True self.pen = QPen(Qt.black) self.pen.setWidth(5) self.brush = QBrush(QtCore.Qt.blue) self.parent = parent self.toleranceX = 20 self.toleranceY = 20 self.verticalRange = 50 self.horizontalRange = 100 self.rect = QtCore.QRectF(self.x, self.y, self.size, self.size) def boundingRect(self): return self.rect def paint(self, painter, option, widget=None): painter.setBrush(self.brush) painter.setPen(self.pen) painter.drawPolygon(QPolygonF([QPointF(self.x + 60, self.y + 5), QPointF(self.x + 75, self.y + 40), QPointF(self.x + 60, self.y + 70), QPointF(self.x + 15, self.y + 70), QPointF(self.x + 0, self.y + 40), QPointF(self.x + 15, self.y + 5)])) self.drawText(painter) def drawText(self, painter): brush = QBrush(Qt.black) pencil = QPen() pencil.setColor(Qt.black) pencil.setBrush(brush) painter.setPen(pencil) font = QFont("Impact", 16) painter.setFont(font) painter.drawText(QRectF(self.x - 62, self.y + 17, 200, 40), Qt.AlignCenter, str(self.value)) def mouseMoveEvent(self, event): self.saveCoordinates() QGraphicsItem.mouseMoveEvent(self, event) def saveCoordinates(self): self.moveX, self.moveY = pyautogui.position() valX = self.startX - self.moveX valY = self.startY - self.moveY self.gesturesX.append(valX) self.gesturesY.append(valY) def mousePressEvent(self, event): self.startX, self.startY = pyautogui.position() QGraphicsItem.mousePressEvent(self, event) def hoverEnterEvent(self, event): self.pen.setColor(Qt.green) QGraphicsItem.hoverEnterEvent(self, event) def hoverLeaveEvent(self, event): self.pen.setStyle(QtCore.Qt.SolidLine) self.pen.setColor(Qt.black) QGraphicsItem.hoverLeaveEvent(self, event) def mouseReleaseEvent(self, event): self.checkDir() self.setX(0) self.setY(0) QGraphicsItem.mouseReleaseEvent(self, event) def checkDir(self): self.moveX, self.moveY = pyautogui.position() gesturesXBuf = [] gesturesYBuf = [] upLeft = Flags() upRight = Flags() downLeft = Flags() downRight = Flags() verticalBuf = 0 length = len(self.gesturesX) # *********************** UP LEFT *************************** # GESTURE: # <--- for x in range(length): # | gesturesXBuf.append(self.gesturesX[x]) # | gesturesYBuf.append((self.gesturesY[x])) left = max(gesturesXBuf) right = abs(min(gesturesXBuf)) down = abs(min(gesturesYBuf)) up = max(gesturesYBuf) if upLeft.flag is False: if left > self.toleranceX or up < self.verticalRange: upLeft.flag = False else: upLeft.flag = True if upLeft.flag is True: if upLeft.flag2 is False: if left > self.toleranceX: verticalBuf = up gesturesXBuf.clear() gesturesYBuf.clear() upLeft.flag2 = True if upLeft.flag2 is True: if up - verticalBuf > self.toleranceY or verticalBuf - down > self.toleranceY or left < self.horizontalRange: upLeft.flag3 = False else: upLeft.flag3 = True # *********************** UP RIGHT *************************** if upRight.flag is False: # GESTURE: if right > self.toleranceX or up < self.verticalRange: # ---> upRight.flag = False # | else: # | upRight.flag = True if upRight.flag is True: if upRight.flag2 is False: if right > self.toleranceX: verticalBuf = up gesturesXBuf.clear() gesturesYBuf.clear() upRight.flag2 = True if upRight.flag2 is True: if up - verticalBuf > self.toleranceY or verticalBuf - down > self.toleranceY or right < self.horizontalRange: upRight.flag3 = False else: upRight.flag3 = True # *********************** DOWN RIGHT *************************** if downRight.flag is False: # GESTURE: if right > self.toleranceX or down < self.verticalRange: # | downRight.flag = False # | else: # <--- downRight.flag = True if downRight.flag is True: if downRight.flag2 is False: if right > self.toleranceX: verticalBuf = down gesturesXBuf.clear() gesturesYBuf.clear() downRight.flag2 = True if downRight.flag2 is True: if down - verticalBuf > self.toleranceY or verticalBuf - abs(up) > self.toleranceY or right < self.horizontalRange: downRight.flag3 = False else: downRight.flag3 = True # *********************** DOWN LEFT *************************** if downLeft.flag is False: # GESTURE: if left > self.toleranceX or down < self.verticalRange: # | downLeft.flag = False # | else: # ---> downLeft.flag = True if downLeft.flag is True: if downLeft.flag2 is False: if left > self.toleranceX: verticalBuf = down gesturesXBuf.clear() gesturesYBuf.clear() downLeft.flag2 = True if downLeft.flag2 is True: if down - verticalBuf > self.toleranceY or verticalBuf - abs( up) > self.toleranceY or left < self.horizontalRange: downLeft.flag3 = False else: downLeft.flag3 = True if upRight.flag is True and upRight.flag2 is False and upRight.flag3 is False: self.up = True elif downRight.flag is True and downRight.flag2 is False and downRight.flag3 is False: self.down = True elif upRight.flag3 is True: self.upRight = True elif upLeft.flag3 is True: self.upLeft = True elif downRight.flag3 is True: self.downRight = True elif downLeft.flag3 is True: self.downLeft = True self.gesturesX.clear() self.gesturesY.clear() self.gesturesX.append(0) self.gesturesY.append(0) class Flags: def __init__(self): self.flag = False self.flag2 = False self.flag3 = False
[ "miccaldo@gmail.com" ]
miccaldo@gmail.com
b6db08130173918bab964091422606ec2957af39
a34ec07c3464369a88e68c9006fa1115f5b61e5f
/A_Basic/String/L0_1684_Count_the_Number_of_Consistent_Strings.py
802755735771f634df680bf789b44d5b52ac935f
[]
no_license
824zzy/Leetcode
9220f2fb13e03d601d2b471b5cfa0c2364dbdf41
93b7f4448a366a709214c271a570c3399f5fc4d3
refs/heads/master
2023-06-27T02:53:51.812177
2023-06-16T16:25:39
2023-06-16T16:25:39
69,733,624
14
3
null
2022-05-25T06:48:38
2016-10-01T10:56:07
Python
UTF-8
Python
false
false
213
py
class Solution: def countConsistentStrings(self, allowed: str, words: List[str]) -> int: ans = 0 for word in words: if all([w in allowed for w in word]): ans += 1 return ans
[ "zhengyuan.zhu@mavs.uta.edu" ]
zhengyuan.zhu@mavs.uta.edu
c24f43d9102e4fae62fbde613135b74b8f456375
c79914628f03a0202031c8a0d207ba2618b1e084
/app.py
4c20716d95de6a6ea628e9f72cb535cfebfd9876
[]
no_license
7in14/pk-python
6aaa926b4491e298b25bebeeb73ccf88c7b562f1
8cf4f50f8444dd863d8bda83eee27b110aacec5b
refs/heads/master
2021-04-28T20:15:50.155384
2018-03-22T01:38:06
2018-03-22T01:38:06
121,920,666
5
0
null
2018-02-26T19:13:54
2018-02-18T05:15:35
Python
UTF-8
Python
false
false
89
py
from app import app if __name__ == '__main__': app.run(debug=False, host='0.0.0.0')
[ "karpik.pl@gmail.com" ]
karpik.pl@gmail.com
375461a85f4ed14690ae5cbd02eca16e5f68beb0
1c1edb210f6b5ed606fb36369cd212497fa66f20
/jobeet_py/settings.py
482712db242e963131a32abe86334aebbb4629dc
[]
no_license
calina-c/jobeet-py
9298dabdd28bc46f609781b5349d46686e4676d4
50d43032476c20db5507c7e870329afcee83bd19
refs/heads/master
2021-01-01T03:52:56.039130
2016-05-09T09:49:49
2016-05-09T09:49:49
56,233,153
0
0
null
null
null
null
UTF-8
Python
false
false
2,122
py
""" Django settings for jobeet_py project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'm$!^-n$_v8(sy4t5ybz^n+%v)bboq#)ppd+-hiva6)4bcj@p%+' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_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', 'jobeet' ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'jobeet_py.urls' WSGI_APPLICATION = 'jobeet_py.wsgi.application' # Database # https://docs.djangoproject.com/en/1.7/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'jobeet_2', 'USER': 'root' } } # Internationalization # https://docs.djangoproject.com/en/1.7/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/1.7/howto/static-files/ STATIC_URL = '/static/' FIXTURE_DIRS = ( os.path.join(BASE_DIR, "fixtures",), )
[ "ioana-calina.tutunaru@linkscreens.com" ]
ioana-calina.tutunaru@linkscreens.com
a96115a87a7ef16fcb4b6d4c224154e946389464
b2856e57a8293f56f2d1e8914a48dd1871fb94e7
/user/migrations/0005_auto_20200504_1549.py
412d493b96ff0904bf2a18e834db3fdbe5665fef
[]
no_license
Moson-Z/blog
eac1bae287f24efeefe738dc9e911ac58fbc664e
6e444f9a766cd728004cbbc7175b9d045403567b
refs/heads/master
2022-12-20T23:45:42.132784
2020-05-20T18:02:35
2020-05-20T18:02:35
251,606,531
0
0
null
2022-04-22T23:12:17
2020-03-31T13:11:33
JavaScript
UTF-8
Python
false
false
367
py
# Generated by Django 2.2.3 on 2020-05-04 07:49 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('user', '0004_auto_20200504_1546'), ] operations = [ migrations.RenameField( model_name='user', old_name='user_password', new_name='password', ), ]
[ "514939920@qq.com" ]
514939920@qq.com
e35937205e8d3e1959bb14e5709326f5e0f99946
0cdafa1af88c86eb584950a132447e7962053bbc
/scripts/plot_sensor_values.py
a1747a6d098484a3ffa8de053a6532c627486217
[]
no_license
thomasarmstrong98/mifarm
d370125990477dd5e49ee3265d12a870a39a7774
5ad24d82c3ff9d0edf66c70471367453f675258f
refs/heads/main
2023-03-30T23:10:57.753453
2021-04-11T17:21:52
2021-04-11T17:48:41
356,650,430
0
0
null
null
null
null
UTF-8
Python
false
false
368
py
import argparse from src.plot_sensor_values import generate_plot_from_logs if __name__ == "__main__": # parser = argparse.ArgumentParser(description='log filepath for serial output.') # parser.add_argument('-path', type=str, # help='filepath used to read serial output') # args = parser.parse_args() generate_plot_from_logs()
[ "thomasarmstrong98@gmail.com" ]
thomasarmstrong98@gmail.com
299773ba81b57afaa0dd21d8f35e2b7992a40201
3e49ee73a7a36f61cf75da45db071afc8f07012e
/Main.py
c182dade5bff3d8f9d4b7dbae97372437edc0823
[]
no_license
bbartek92/MP3_Player
89757487f2727c1d2f1d572b520deeac7160662d
9db2921f64e695a6b20c29d7e927b436c43a66f2
refs/heads/master
2020-08-19T06:18:44.767753
2019-10-17T21:27:01
2019-10-17T21:27:01
215,887,823
0
0
null
null
null
null
UTF-8
Python
false
false
10,535
py
import wx import glob import eyed3 import pygame import threading class Mp3Frame(wx.Frame): #main class which will start the program def __init__(self): super().__init__(parent=None, title='BeBe MP3 Player', size=(500, 300)) self.panel = Mp3Panel(self) self.create_menu() self.Bind(wx.EVT_CLOSE, self.onClose) self.Show() def onClose(self, event): self.panel.stop_music('event') self.Destroy() def create_menu(self): menu_bar = wx.MenuBar() #File menu setup file_manu = wx.Menu() open_folder_menu_item = file_manu.Append( wx.ID_ANY, 'Open Folder', 'Open a folder with MP3s') self.Bind(event=wx.EVT_MENU, handler=self.on_open_folder, source=open_folder_menu_item) open_file_menu_item = file_manu.Append( wx.ID_ANY, 'Open File', 'Open MP3 File') self.Bind(event=wx.EVT_MENU, handler=self.on_open_file, source=open_file_menu_item) add_folder_menu_item = file_manu.Append( wx.ID_ANY, 'Add Folder', 'Add a folder with MP3s') self.Bind(event=wx.EVT_MENU, handler=self.on_add_folder, source=add_folder_menu_item) add_file_menu_item = file_manu.Append( wx.ID_ANY, 'Add File', 'Add MP3 File') self.Bind(event=wx.EVT_MENU, handler=self.on_add_file, source=add_file_menu_item) menu_bar.Append(file_manu, '&File') #Edit menu setup edit_menu = wx.Menu() clear_menu_item = edit_menu.Append( wx.ID_ANY, 'Clear list', 'Clear the list of MP3s') self.Bind(event=wx.EVT_MENU, handler=self.on_clear_menu, source=clear_menu_item) menu_bar.Append(edit_menu, '&Edit') #View menu setup view_menu = wx.Menu() mp3_list_menu_hide = view_menu.Append( wx.ID_ANY, 'Hide track list', 'Hide the list of MP3s') self.Bind(event=wx.EVT_MENU, handler=self.on_hide, source=mp3_list_menu_hide) mp3_list_menu_show = view_menu.Append( wx.ID_ANY, 'Show track list', 'Show the list of MP3s') self.Bind(event=wx.EVT_MENU, handler=self.on_show, source=mp3_list_menu_show) menu_bar.Append(view_menu, '&View') self.SetMenuBar(menu_bar) #method to open get mp3 files def on_open_folder(self, event): title = 'Choose a directory' self._open_add(title, wx.DirDialog, 'open_folder') def on_open_file(self, event): title = 'Choose a file' self._open_add(title, wx.FileDialog, 'open_file') def on_add_folder(self, event): title = 'Choose a directory to add' self._open_add(title, wx.DirDialog, 'add_folder') def on_add_file(self, event): title = 'Choose a file to add' self._open_add(title, wx.FileDialog, 'add_file') def _open_add(self, title, dialog, mode): dlg = dialog(self, title, style=wx.DD_DEFAULT_STYLE) if dlg.ShowModal() == wx.ID_OK: self.panel.update_mp3_listing(dlg.GetPath(), mode) dlg.Destroy() def on_clear_menu(self, event): self.panel.update_mp3_listing(None, 'clear') def on_hide(self, event): self.panel.list_ctrl.Hide() def on_show(self, event): self.panel.list_ctrl.Show() class Mp3Panel(wx.Panel): #main body of the mp3 player def __init__(self, parent): super().__init__(parent) super().SetBackgroundColour(wx.WHITE) main_sizer = wx.BoxSizer(wx.VERTICAL) top_sizer = wx.BoxSizer(wx.HORIZONTAL) #add stop button stop_bt = self.create_bitmap_button('stop.png', self.stop_music) top_sizer.Add(stop_bt, 0, wx.ALL, 0) #add play button play_bt = self.create_bitmap_button('play.png', self.start_music) top_sizer.Add(play_bt, 0, wx.ALL, 0) #add pasue button pause_bt = self.create_bitmap_button('pause.png', self.pause_music) top_sizer.Add(pause_bt, 0, wx.ALL, 0) #add back button back_bt = self.create_bitmap_button('rewind.png', self.rewind_music) top_sizer.Add(back_bt, 0, wx.ALL, 0) #add forward button forward_bt = self.create_bitmap_button('forward.png', self.forward_music) top_sizer.Add(forward_bt, 0, wx.ALL, 0) #add volume slider self.current_volume = 50 self.volume_slider = wx.Slider(self, value=self.current_volume, minValue=0, maxValue=100) self.volume_slider.Bind(wx.EVT_SLIDER, self.on_volume_slider) top_sizer.Add(self.volume_slider, 0, wx.ALL, 0) #add info label info_font = wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.ITALIC, wx.NORMAL) self.info_label = wx.StaticText(self, label="Choose MP3", size=(200, 36), style=wx.ALIGN_LEFT) self.info_label.SetFont(info_font) self.info_label.SetBackgroundColour(wx.BLACK) self.info_label.SetForegroundColour(wx.GREEN) self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.update_info, self.timer) self.timer.Start(100) top_sizer.Add(self.info_label, 0, wx.ALL, 0) #init info self.init_info() #add top sizer to main sizer main_sizer.Add(top_sizer, 0, wx.ALL, 0) bottom_sizer = wx.BoxSizer(wx.HORIZONTAL) #add MP3 info self.row_obj_dict = {} self.mp3s = [] self.list_ctrl = wx.ListCtrl(self, size=(-1, 200), style=wx.LC_REPORT | wx.BORDER_SUNKEN) self.list_ctrl.InsertColumn(0, 'Artist', width=140) self.list_ctrl.InsertColumn(1, 'Album', width=140) self.list_ctrl.InsertColumn(2, 'Title', width=200) bottom_sizer.Add(self.list_ctrl, 0, wx.ALL, 5) #add bottom sizer to main sizer main_sizer.Add(bottom_sizer, 0, wx.ALL, 0) self.SetSizer(main_sizer) #init the pygame mixer pygame.mixer.init() def create_bitmap_button(self, filepath, my_handler): bmp = wx.Bitmap(filepath, wx.BITMAP_TYPE_PNG) bmp_bt = wx.BitmapButton( self, id=wx.ID_ANY, bitmap=bmp, size=(bmp.GetWidth()+5, bmp.GetHeight()+5)) bmp_bt.Bind(wx.EVT_BUTTON, my_handler) return bmp_bt def on_volume_slider(self, event): self.current_volume = self.volume_slider.GetValue() / 100 pygame.mixer.music.set_volume(self.current_volume) def init_info(self): self.playing_mp3_tag = '-' * 15 + 'BeBe MP3 Player --- set your music' + '-' * 10 self.len_tag = len(self.playing_mp3_tag) self.slice_1 = 0 self.slice_2 = 28 def update_info(self, event): self.info_label.SetLabel(f' {self.playing_mp3_tag[self.slice_1:self.slice_2]}') self.slice_1 += 1 self.slice_2 += 1 if self.slice_1 == self.len_tag: self.slice_1 = 0 self.slice_2 = 28 def update_mp3_listing(self, folder_path, mode): self.list_ctrl.ClearAll() self.list_ctrl.InsertColumn(0, 'Artist', width=140) self.list_ctrl.InsertColumn(1, 'Album', width=140) self.list_ctrl.InsertColumn(2, 'Title', width=200) if mode == 'open_folder': # self.current_folder_path = folder_path self.mp3s = glob.glob(folder_path + '/*.mp3') elif mode == 'open_file': self.mp3s = [folder_path] elif self.mp3s and mode == 'add_folder': # self.current_folder_path = folder_path new_mp3s = glob.glob(folder_path + '/*.mp3') self.mp3s += new_mp3s elif self.mp3s and mode == 'add_file': print('inn add file') self.mp3s.append(folder_path) else: self.mp3s = [] mp3_objects = [] index = 0 for mp3 in self.mp3s: mp3_object = eyed3.load(mp3) self.list_ctrl.InsertItem(index, mp3_object.tag.artist) self.list_ctrl.SetItem(index, 1, mp3_object.tag.album) self.list_ctrl.SetItem(index, 2, mp3_object.tag.title) mp3_objects.append(mp3_object) self.row_obj_dict[index] = mp3, mp3_object.tag.artist + '-' + mp3_object.tag.album + '-' + mp3_object.tag.title index += 1 def stop_music(self, event): self.stop_playing = True pygame.mixer.music.stop() def start_music(self, event): self.stop_playing = False self.selection = self.list_ctrl.GetFocusedItem() if self.selection >= 0: if pygame.mixer.music.get_busy() == 0: self.new_thread = threading.Thread(target=self._play_music_thread) self.new_thread.start() else: pygame.mixer.music.unpause() def _play_music_thread(self): play_list = self.row_obj_dict.keys() for _ in range(len(play_list)): mp3 = self.row_obj_dict[self.selection][0] self.playing_mp3_tag = '-' * 15 + self.row_obj_dict[self.selection][1] + '-' * 10 pygame.mixer.music.load(mp3) pygame.time.Clock() try: pygame.mixer.music.play() except pygame.error: break while pygame.mixer.music.get_busy(): pygame.time.Clock().tick(5) if self.stop_playing: break self.selection += 1 def pause_music(self, event): pygame.mixer.music.pause() def rewind_music(self, event): try: if self.selection >= 1: self.selection -= 1 mp3 = self.row_obj_dict[self.selection][0] self.playing_mp3_tag = '-' * 15 + self.row_obj_dict[self.selection][1] + '-' * 10 pygame.mixer.music.load(mp3) pygame.mixer.music.play() except AttributeError: print('Not playing yet') except pygame.error: print('click play') def forward_music(self, event): try: if self.selection >= 0: self.selection += 1 # try: mp3 = self.row_obj_dict[self.selection][0] self.playing_mp3_tag = self.row_obj_dict[self.selection][1] pygame.mixer.music.load(mp3) pygame.mixer.music.play() except AttributeError: print('Not playing yet') except KeyError: print('Out of track list') except pygame.error: print('click play') if __name__ == '__main__': app = wx.App() frame = Mp3Frame() app.MainLoop()
[ "b.bujak@vp.pl" ]
b.bujak@vp.pl
e9b847a535c377115ef14db827572dee406d0f1b
55200b87bcb1ecc6c8425336570e8f16096dc548
/TF/test_mnist.py
466bc6f14bbb38569c9f50435592b9f55241077c
[]
no_license
OWEN-JUN/Study_DL
f6ec25b6a2a9eea90204dba3a3c38c593d809643
557c8d823be033aea318e6401c5b95e9d94e3df3
refs/heads/master
2021-06-20T17:51:23.936105
2021-03-15T09:02:42
2021-03-15T09:02:42
198,536,845
1
1
null
null
null
null
UTF-8
Python
false
false
3,034
py
import tensorflow as tf import matplotlib.pyplot as plt import random from tensorflow.examples.tutorials.mnist import input_data tf.set_random_seed(777) # read data mnist = input_data.read_data_sets("/~/deep_learning_zeroToAll/", one_hot=True) nb_classes = 10 keep_prob = tf.placeholder(tf.float32) X = tf.placeholder(tf.float32,[None,784]) Y = tf.placeholder(tf.float32,[None,nb_classes]) # W = tf.Variable(tf.random_normal([784,nb_classes])) # b = tf.Variable(tf.random_normal([nb_classes])) W1 = tf.get_variable("W1",shape=[784,512], initializer=tf.contrib.layers.xavier_initializer()) b1 = tf.Variable(tf.random_normal([512])) L1 = tf.nn.relu(tf.matmul(X, W1) + b1) L1 = tf.nn.dropout(L1, keep_prob=keep_prob) W2 = tf.get_variable("W2",shape=[512,512], initializer=tf.contrib.layers.xavier_initializer()) b2 = tf.Variable(tf.random_normal([512])) L2 = tf.nn.relu(tf.matmul(L1, W2) + b2) L2 = tf.nn.dropout(L2, keep_prob=keep_prob) W3 = tf.get_variable("W3",shape=[512,512], initializer=tf.contrib.layers.xavier_initializer()) b3 = tf.Variable(tf.random_normal([512])) L3 = tf.nn.relu(tf.matmul(L2, W3) + b3) L3 = tf.nn.dropout(L3, keep_prob=keep_prob) W4 = tf.get_variable("W4",shape=[512,512], initializer=tf.contrib.layers.xavier_initializer()) b4 = tf.Variable(tf.random_normal([512])) L4 = tf.nn.relu(tf.matmul(L3, W4) + b4) L4 = tf.nn.dropout(L4, keep_prob=keep_prob) W5 = tf.get_variable("W5",shape=[512,10], initializer=tf.contrib.layers.xavier_initializer()) b5 = tf.Variable(tf.random_normal([10])) hypothesis = tf.matmul(L4, W5) + b5 cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = hypothesis, labels=Y)) optimizer = tf.train.AdamOptimizer(learning_rate = 0.001).minimize(cost) is_correct = tf.equal(tf.arg_max(hypothesis,1), tf.arg_max(Y, 1)) accuracy = tf.reduce_mean(tf.cast(is_correct,tf.float32)) training_epochs = 15 batch_size = 100 with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for epoch in range(training_epochs): avg_cost = 0 total_batch = int(mnist.train.num_examples / batch_size) for i in range(total_batch): batch_xs, batch_ys = mnist.train.next_batch(batch_size) c, _= sess.run([cost,optimizer], feed_dict={X: batch_xs, Y: batch_ys, keep_prob: 0.7}) avg_cost += c / total_batch print('Epoch:', '%04d' % (epoch + 1), 'cost = ', '{:.9f}'.format(avg_cost)) print("Learning finished") print("Accuracy: ", accuracy.eval(session=sess, feed_dict={X: mnist.test.images, Y: mnist.test.labels, keep_prob: 1})) # Get one and predict using matplotlib r = random.randint(0, mnist.test.num_examples - 1) print("Label: ", sess.run(tf.argmax(mnist.test.labels[r:r + 1], 1))) print("Prediction: ", sess.run( tf.argmax(hypothesis, 1), feed_dict={X: mnist.test.images[r:r + 1], keep_prob: 1})) plt.imshow( mnist.test.images[r:r + 1].reshape(28, 28), cmap='Greys', interpolation='nearest') plt.show()
[ "49712113+OWEN-JUN@users.noreply.github.com" ]
49712113+OWEN-JUN@users.noreply.github.com
905c22e72fab6cce3f2d827c24366e735408b64b
f5674cf2fe1be543d7ea6419943054a6f48c4f26
/CheckMate.py
10869cfd9e0d03d8e2913ddfebabef4682472be2
[]
no_license
jmazrimas/ms-cmm
5d277c850a5aad9ef6bb61b07b86dd7ff7c05852
0971a1aa520c273e61430f7099503e5051c124c0
refs/heads/master
2020-12-07T13:34:21.092792
2017-06-27T20:52:29
2017-06-27T20:52:29
95,573,310
0
0
null
null
null
null
UTF-8
Python
false
false
1,052
py
# # Run CheckMate # #import subprocess import os import sys def main(): """Main function """ run_checkmate('C:\\tmp\\test2.qif', 'C:\\tmp\\test2.dmi') def run_checkmate(input_file, output_file): """Runs CheckMate to generate DMIS from the given input QIF file """ ## f = open(output_file, 'w') ## f.write('<Placeholder for auto-generated CheckMate DMIS program>'); ## f.close() # #define some paths cm_exefile = 'C:\\Program Files\\Origin International Inc\\CMEngine\\CMEngine.exe' # # Call CMEngine #subprocess.call([cm_exefile, 'CMEngine.exe', 'CMEQIF2QIF', input_file]) os.spawnl(os.P_WAIT, cm_exefile, 'CMEngine.exe', 'CMEQIF2QIF', 'SILENT', input_file) # CMEngine creates a DMIS file with name based on input file dmis_file = os.path.splitext(input_file)[0] + '.DMI' # rename DMIS file to output_file if necessary if(dmis_file != output_file): os.rename(dmis_file, output_file) if (__name__ == "__main__"): """Initial function called by interpreter at command line """ main()
[ "joe.mazrimas@uilabs.org" ]
joe.mazrimas@uilabs.org
9207c9cab23edfac359cbc19c3db823e8b193cb9
84d2efd222fa190c8b3efcad083dcf2c7ab30047
/linRegNoSTD.py
34a9e45c64ae6545a196ca7279c57aa4acfd4220
[]
no_license
webclinic017/Capstone-2
aedfc8692647f2e84114da5b2e32856d0de80586
d476723f7893c7c5da14e24f28736a8f0ba7ff55
refs/heads/master
2023-01-23T06:44:36.868373
2020-12-03T19:44:51
2020-12-03T19:44:51
null
0
0
null
null
null
null
UTF-8
Python
false
false
655
py
import pandas as pd import matplotlib.pyplot as plt import numpy as np import sklearn.linear_model from alpha_vantage.timeseries import TimeSeries api_key = '8FIYTT49ZEZT2GV5' ts = TimeSeries(key=api_key, output_format='pandas') data, meta_data = ts.get_daily_adjusted(symbol='SPY', outputsize = 'full') data = data.reset_index() data.plot(x = 'date', y = '4. close') data['date'] = data['date'].values.astype(float) X = np.c_[data['date']] Y = np.c_[data['4. close']] model = sklearn.linear_model.LinearRegression() model.fit(X, Y) date = [[1736208000000000000.0]] print(model.predict(date)) plt.show() #standard deviation
[ "noreply@github.com" ]
webclinic017.noreply@github.com
8a7cd0f08b68dc4057ee10d189ebc2f3904b215f
8d903308c79a8e8cc18a2d788f3a5113f18d7f25
/Day 8_2.py
ac6c99ebf03689cf09214fe2214dd6398f3cef6b
[]
no_license
Ace314159/AoC-2018
fb10382b5bc5e8a7be670f7d00527e49e4868091
c8b1e4aee85a61f60f52a59cc91284fe325fb5fe
refs/heads/master
2020-04-09T03:37:07.275807
2019-01-06T06:48:23
2019-01-06T06:48:23
159,989,590
0
0
null
null
null
null
UTF-8
Python
false
false
528
py
import pathlib data = map(int, pathlib.Path("inputs/8.txt").read_text().splitlines()[0].split(" ")) metadataSum = 0 def buildNode(): global metadataSum node = {"children": [], "metadata": [], "metadataSum": 0} numChildren = next(data) numMetadata = next(data) for _ in range(numChildren): node["children"].append(buildNode()) for _ in range(numMetadata): node["metadata"].append(next(data)) metadataSum += node["metadata"][-1] return node buildNode() print(metadataSum)
[ "akash.munagala@gmail.com" ]
akash.munagala@gmail.com
3f209c133fd7f4bda9cd7f2691937376771e0997
13102a790732ddd3cedb9d6cf0cb813d6f2a895c
/20201211/14.python힙구현.py
b73858a71c9365ef6eba0fa49fcd6a2ccb71a4e0
[]
no_license
MsSeonge/infrun-C-CodingTest
72d3769189b8124de13c11af678a459e348b52d2
2cb5e6b96bb1a4aa527c15ed58eef4340a5e8976
refs/heads/main
2023-01-23T22:35:26.726890
2020-12-10T23:33:31
2020-12-10T23:33:31
319,673,505
0
0
null
null
null
null
UTF-8
Python
false
false
1,011
py
# i 레벨 왼쪽 자식노드는 (2i+1) 오른쪽 자식노드는 (2i+2) # i번째 부모노드의 위치는(i-1/2) class MaxHeap(object): def __init__(self): self.queue = [] def insert(self,n): self.queue.append(n) last_index = len(self.queue)-1 while 0 <= last_index: parent_index = self.parent(last_index) if 0 <= parent_index and self.queue[parent_index] < self.queue[last_index]: last_index = parent_index else: break def delete(self): last_index = len(self.queue) if last_index < 0: return -1 self.swap(0,last_index) maxv = self.queue.pop() self.maxHeapify(0) print(maxv) return maxv # 비교해나가며 재정렬 def maxHeapify(self,i): left_index = self.leftchild(i) right_index = self.rightchild(i) max_index =right_index
[ "srkim0371@gmail.com" ]
srkim0371@gmail.com
295c7ff7ef0cbbfce1f65cde6f4f04de53a5d4b5
f33306933b3880fb30580b1cf1a1b57eb7fbb9c7
/Dojo-Secrets/myServer/myServer/urls.py
7aa7d122be49830aa1ffc79264746de3befe2aaa
[]
no_license
quincyadamo/django-homework
69aaed0aec045a8952d42366718ed5482ca42ece
49af49d3634df6883f60f9d2255d572ab15d4be1
refs/heads/master
2021-01-01T16:03:56.321066
2017-07-19T22:41:32
2017-07-19T22:41:32
null
0
0
null
null
null
null
UTF-8
Python
false
false
852
py
"""Dojo Secrets URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include urlpatterns = [ url(r'^', include('apps.loginApp.urls', namespace='users')), url(r'^secrets/', include('apps.secretsApp.urls', namespace="secretsApp")) ]
[ "quincyadamo@gmail.com" ]
quincyadamo@gmail.com
ba10ed31f00d72fcec61ada9fe8e91cda79da8b5
923daaa56d689c0c3d197f0461334ad560e4d8b1
/day05/day05/urls.py
e59ed0eda41ac980f436f5e4440ca0cce27d8d79
[]
no_license
kunata928/django_piscine
1b0b76cb1df525753f2ca061b524754539e9bfcd
aab9caaa837197d57f8fc03bbb59221ef2c6b6ee
refs/heads/master
2023-07-16T14:38:54.213261
2021-08-20T13:01:42
2021-08-20T13:01:42
398,274,987
0
0
null
null
null
null
UTF-8
Python
false
false
139
py
from django.urls import path, include urlpatterns = [ path('ex00/', include('ex00.urls')), path('ex02/', include('ex02.urls')), ]
[ "natalikuntso@gmail.com" ]
natalikuntso@gmail.com
b2b99afce1313d1e0037e4df7da176c2b7806bce
99c5c883e0138c95d1bdfbfd1ea5ddb5107fd0e0
/_javascript.py
b182c984224dcbf8cdb80fb9287be0bb70bfc379
[]
no_license
maxxiimo/voice-commands
b508b2620861ecf0cc41b1d7fec5effd6d1552b4
71b6ebba683aa5bb9b9d72c6b1eacecbd9adfbd0
refs/heads/master
2021-03-22T01:12:26.870596
2017-12-18T16:59:52
2017-12-18T16:59:52
109,174,897
1
0
null
null
null
null
UTF-8
Python
false
false
19,618
py
""" This module is for coding JavaScript. """ from dragonfly import (Grammar, AppContext, MappingRule, Dictation, IntegerRef, Key, Text) sublime_context = AppContext(executable="sublime_text") grammar = Grammar("javascript", context=(sublime_context)) javascript_rule = MappingRule( name="javascript", mapping={ # JavaScript --------------------------------------------------------------------------------- "javascript alert": Text("alert(\'\');") + Key("left:2"), # alert("<alert_message>"); "javascript console log": Text("console.log();") + Key("left:2"), # console.log(); "javascript prevent default": Text("event.preventDefault();"), # event.preventDefault(); # Objects "javascript object [literal]": Text("var object = {}"), # var <object_name> = {} | To create an object. "[javascript] inline object": Text("var object = {}") + Key("left, enter, tab") # var <object_name> = { ... name: '', ... } | To create an object and set properties inline. + Text("name: \'\',") + Key("left:2"), "[javascript] object (definition | dot assignment)": Text("object.name = \'\'") + Key("left"), # <object_name>.<property_name> = '<property>' | To set property on an object. "[javascript] object definition brackets": Text("object[\'name\'] = \'\'") + Key("left"), # <object_name>['<property_name>'] = '<property>' | To set property on an object. "[javascript] object retrieve": Text("object.name"), # <object_name>.<property_name> | To retrieve property of an object. "[javascript] object retrieve brackets": Text("object[\'name\']"), # <object_name>['<property_name>'] | To retrieve property of an object. # Arrays "javascript array [literal]": Text("var array = []") + Key("left"), # var <array_name> = [] | To create an array. "javascript push": Text(".push()") + Key("left"), # .push() | Add additional values to an array. "javascript slice": Text(".slice()") + Key("left"), # .slice() | Copy an array at a particular index value. "javascript splice": Text(".splice()") + Key("left"), # .splice(<index>, <# of items to remove>) | To remove an item from an array. "javascript for each": Text(".forEach(function(item){\n\n})") + Key("up, tab:2"), # .forEach(function(){ ... }) | Iterate over an array. Receives as an argument the callback function, which will be called for each item in the array while iterating over the array. "javascript map": Text(".map(function(item){ return item })"), # .map(function(item){ return item }) | Will iterate over each item in the array using a callback function, bbut each value your return from that function wwill be collected inside a new array and returned by the map method. "javascript filter": Text(".filter(function(item){ return item })"), # .filter(function(item){ return item }) | Applies filter on a rainy and only returns items that return true. # Functions "javascript function [declaration]": Text("function () {\n}") + Key("up, end, enter, tab") # function <name>(<arg1, arg2, argN>){ ... return } + Text("return ") + Key("up, end, left:4"), "javascript function expression [<text>]": Text(".%(text)s = function(){\n\n}") + Key("up, tab") # <object>.<method> = function(<arg1, arg2, argN>){ ... return } | Used for storing a function in a variable or property. + Text("return ") + Key("up, end, left:2"), "var self equals this": Text("var self = this"), # var self = this | Trick to use "this" inside callback function: Freeze "this" in a local variable, then use local variable inside callback function. "javascript function shorthand": Text("(, () => {") + Key("enter") + Text("})") # (, () => { ... }) + Key("up, end, enter"), # Control Structure "javascript if": Text("if () {}") + Key("left, enter, tab"), # if () { ... } "javascript else": Text(" else () {}") + Key("left, enter, tab"), # else () { ... } # Methods # For Functions "javascript call": Text(".call()") + Key("left"), # .call(<object>, 'arg1', 'arg2', 'argN') | Can be used on any JavaScript function to call the function. The first argument of the method will be the value assigned to "this", and then you can pass any number of arguments. "javascript apply": Text(".apply()") + Key("left"), # .apply(<object>, ['arg1', 'arg2', 'argN']) | Same as previous, the only difference is receives arguments as an array versus a simple list. # Jquery ------------------------------------------------------------------------------------- "jquery add class": Text(".addClass(\'\')"), # .addClass('<class>') "jquery after": Text(".after(\'\')"), # .after | Places content after selected element. "jquery alert": Text("alert(\"\");"), # alert("<alert_message>"); "jquery and": Text(".end()"), # .end() "jquery append": Text(".append(\'\')"), # .append | Places content at bottom, for top use .prepend. "jquery append to": Text(".appendTo(\'\')"), # .appendTo('<element>') | Content to be created and placed precedes method, placed on bottom. use . prependTo to place on top. if element already exists moves element to bottom of <element>. "jquery ater": Text(".attr(\'\')"), # .attr('<attribute>') | One attribute returns the value, two attributes sets the value. "jquery attribute": Text(".attr(\'\')"), # .attr('<attribute>') | One attribute returns the value, two attributes sets the value. "jquery before": Text(".after(\'\')"), # .before | Places content before selected element. "jquery cache variable": Text("var = $(\'\');"), # var <variable> = $('<element>'); "jquery change": Text(".change() "), # .change() "jquery children": Text(".children(\'\')"), # .children('<direct child>') "jquery click": Text(".click() "), # .click() "jquery clone": Text(".clone() "), # .clone() "jquery clone true": Text(".clone(true)"), # .clone(true) | Retain event handlers, defaults to false. "jquery closest": Text(".closest(\'\')"), # .closest('<first_matching_parent_element>') "jquery console log": Text("console.log();"), # console.log(); "jquery css": Text(".css(', ')"), # .css('<attribute>', '<value>') "jquery data": Text(".data(\'\')"), # .data('<custom_data_attribute_minus_the_data>') "jquery delay": Text(".delay()"), # .delay(<value>) "jquery each": Text(".each()"), # .each() "jquery end": Text(".end() "), # .end() "jquery eq": Text(".eq() %"), # .eq(<integer>) | n-1, where n = the numerical position of element desired. "jquery fade in": Text(".fadeIn() "), # .fadeIn() "jquery fade out": Text(".fadeOut() "), # .fadeOut() "jquery fade toggle": Text(".fadeToggle()"), # .fadeToggle(<value>) "jquery filter": Text(".criteria(\'\')"), # .filter('<criteria>') | Filters based on criteria and applies to next element in chain. "jquery find": Text(".find(\'\')"), # .find('<descendent element>') "jquery first": Text(".first() "), # .first() "jquery function": Text("function() {}"), # Basic function. "jquery function anonymous": Text("(function() {})(); "), # Function that will execute when page loads. "jquery function callback": Text("function() {}"), # Basic function. "jquery function document ready": Text("$(document).ready(function() {});"), # $(document).ready(function() { <code> }); "jquery function shorthand": Text("$(function() {});"), # Document ready shorthand --> $(function() { <code> }); "jquery height": Text(".height()"), # .height() "jquery hide": Text(".hide()"), # .hide() "jquery hover": Text(".hover()"), # .hover() "jquery html": Text(".html()"), # .html() "jquery if": Text("if() {}"), # if() {} "jquery init": Text("init:"), # Constructor method, gets the ball rolling. "jquery init call": Text(".init();"), # <variable>.init(); "jquery initialize": Text("init:"), # Constructor method, gets the ball rolling. "jquery initialize call": Text(".init();"), # <variable>.init(); "jquery insert after": Text(".insertAfter(\'\')"), # .insertAfter('') | "Here's some content I want to insert it after" the specified element. "jquery insert before": Text(".insertBefore(\'\')"), # .insertBefore('') | "Here's some content I want to insert it before" the specified element. "jquery next": Text(".next()"), # .next() "jquery object literal": Text("var = {};"), # var <variable> = {}; "jquery on click": Text(".on('click', function() {})"), # .on('click', <can_specify_target>, <function>) "jquery on event": Text(".on('', function() {})"), # .on('<event>', <can_specify_target>, <function>) "jquery on function": Text(".on('', function() {})"), # .on('<event>', <can_specify_target>, <function>) "jquery on hover": Text(".on('hover', function() {})"), # .on('hover', <can_specify_target>, <function>) "jquery on mouse event": Text(".on('mouseevent', function() {})"), # .on('mouseevent', <can_specify_target>, <function>) "jquery outer height": Text(".outerHeight()"), # .outerHeight() "jquery parent": Text(".parent(\'\')"), # .parent('<direct parent>') "jquery parent object": Text("var = {};"), # var <variable> = {}; "jquery parents": Text(".parents(\'\')"), # .parents('<parent element/s>') "jquery prepend": Text(".prepend(\'\')"), # .prepend('') | Places content at top, for bottom use .append. "jquery prevent default": Text("e.preventDefault();"), # e.preventDefault(); | Prevents events default action using "e" as the name. "jquery prepend to": Text(".prependTo (\'\')"), # .prependTo('<element>') | Content to be placed proceeds method, placed on top. Use .appendTo to place on bottom. If element already exists moves element to top of <element>. "jquery previous": Text(".prev()"), # .prev() "jquery proxy": Text("$.proxy(,)"), # $.proxy(<method called>, <this refers to?>); | To state exactly what should be treated as this. "jquery query": Text("$(\'\');"), # $('<element>'); "jquery remove ater": Text(".removeAttr(\'\')"), # .removeAttr('<attribute>') "jquery remove attribute": Text(".removeAttr(\'\')"), # .removeAttr('<attribute>') "jquery remove class": Text(".removeClass(\'\')"), # .removeClass('<class>') "jquery reset": Text(".reset()"), # .reset() "jquery search": Text("$(\'\');"), # $('<element>'); "jquery show": Text(".show()"), # .show() "jquery siblings": Text(".siblings(\'\')"), # .siblings('<other elements on same level>') "jquery slide down": Text(".slideDown()"), # .slideDown(<value>) "jquery slide toggle": Text(".slideToggle()"), # .slideToggle(<value>) "jquery slide up": Text(".slideUp()"), # .slideUp(<value>) "jquery text": Text(".text(\'\')"), # .text('<text>') "jquery this": Text("$(this)"), # $(this) "jquery to lowercase": Text(".toLowerCase()"), # .toLowerCase() "jquery toggle": Text(".toggle()"), # .toggle() "jquery val": Text(".val()"), # .val() "jquery variable": Text("var = $(\'\');"), # var <variable> = $('<element>'); }, extras=[ Dictation("text"), IntegerRef("n", 1, 100) ], defaults = { "text": "", "n": 1 } ) grammar.add_rule(javascript_rule) grammar.load() def unload(): global grammar if grammar: grammar.unload() grammar = None
[ "cmaxwell@viewthought.com" ]
cmaxwell@viewthought.com
b70fdd3991ea949c890cd265bfad70b30a2ea4a5
b35bf29de6123f4ea438d8cd6dea100be9cd250e
/RemoteLaunch.py
94939b1d5a1b9576e3f829f7ba1c44be5fac0e45
[]
no_license
kunal2991/Cloud-Computing
81711ee78b282dae953bb5cd84188043c8382909
fd3b7607687db22ff85003f946d0263cbb7bcee0
refs/heads/master
2021-01-15T14:28:49.324450
2016-09-19T19:28:37
2016-09-19T19:28:37
68,638,599
0
0
null
null
null
null
UTF-8
Python
false
false
926
py
import boto.ec2 import sys import time noOfInstances = int(sys.argv[1]) #Storing the number of instances to be launched from the command line print "No of instances to be launched------->"+str(noOfInstances)+'\n' conn = boto.ec2.connect_to_region(sys.argv[2],aws_access_key_id='Your ACCESS KEY goes here',aws_secret_access_key='Your SECRET ACCESS KEY goes here') #myInstances = ["" for x in range(noOfInstances)] myInstances = [] for i in range(0,noOfInstances): reservation = conn.run_instances("ami-9ff7e8af", instance_type='t2.micro') myInstances.append(reservation.instances[0]) print myInstances time.sleep(10) print "Do you want to delete the instances? - Press Y or N\n" response = raw_input() if response.lower() in ['y','yes']: for instance in myInstances: instance.terminate() else: sys.exit(0) """ for instance in myInstances instance.instances[0].terminate() print myInstances.instances[0] """
[ "kunalbarde@Kunals-MacBook-Pro.local" ]
kunalbarde@Kunals-MacBook-Pro.local