blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
281
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
6
116
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
313 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
18.2k
668M
star_events_count
int64
0
102k
fork_events_count
int64
0
38.2k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
107 values
src_encoding
stringclasses
20 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
4
6.02M
extension
stringclasses
78 values
content
stringlengths
2
6.02M
authors
listlengths
1
1
author
stringlengths
0
175
4dc5896c6a8f77eb77879a46ed38748ab3d18d6b
089a6215e04433d95e4f8af78130f79b504e94b9
/mysite/settings.py
80a612f57948a154bb72284c7f67b90212ea1fa9
[]
no_license
Bulalu/Blog
d32e3bdb162b023afeebe32e878a1d08c701098b
80911e3523b8e6ae84f94c55b633d1e1405ed292
refs/heads/master
2023-06-18T01:13:42.088370
2021-07-13T18:52:12
2021-07-13T18:52:12
369,866,555
0
0
null
null
null
null
UTF-8
Python
false
false
5,245
py
""" Django settings for mysite project. Generated by 'django-admin startproject' using Django 3.2. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-+n8%r39()9%jhj&f#tkj7zp%7ayf!!g6q_%plait_^1-ckx)dn' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] SITE_ID = 1 # Application definition INSTALLED_APPS = [ 'filebrowser', # 'jet', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'tinymce', 'marketing', 'django.contrib.sites', 'django.contrib.sitemaps', 'django.contrib.postgres', 'django.contrib.humanize' , ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR/'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'my_awesome_blog', 'USER': 'postgres', 'PASSWORD':'python2021', 'HOST': 'localhost', 'PORT': '5432' } } #DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': BASE_DIR / 'db.sqlite3', #} #} # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'elishabulalu031@gmail.com' EMAIL_HOST_PASSWORD = 'ultimateteam19' EMAIL_PORT = 587 EMAIL_USE_TLS = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/static/' MEDIA_URL = '/media/' STATICFILES_DIRS = (BASE_DIR/"static",) STATIC_ROOT = BASE_DIR/'django_static_files' MEDIA_ROOT = BASE_DIR/ "media" #FILEBROWSER_DIRECTORY = MEDIA_ROOT # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' #WYSIWG #tinymce- html text-editor TINYMCE_DEFAULT_CONFIG = { 'height': 360, 'width': 1120, 'cleanup_on_startup': True, 'custom_undo_redo_levels': 20, 'selector': 'textarea', 'theme': 'modern', 'plugins': ''' textcolor save link image media preview codesample contextmenu table code lists fullscreen insertdatetime nonbreaking contextmenu directionality searchreplace wordcount visualblocks visualchars code fullscreen autolink lists charmap print hr anchor pagebreak ''', 'toolbar1': ''' fullscreen preview bold italic underline | fontselect, fontsizeselect | forecolor backcolor | alignleft alignright | aligncenter alignjustify | indent outdent | bullist numlist table | | link image media | codesample | ''', 'toolbar2': ''' visualblocks visualchars | charmap hr pagebreak nonbreaking anchor | code | ''', 'contextmenu': 'formats | link image', 'menubar': True, 'statusbar': True, }
[ "elishabulalu031@gmail.com" ]
elishabulalu031@gmail.com
5094b9b691ae257e044c3742035823ecc3da2227
28ef7c65a5cb1291916c768a0c2468a91770bc12
/configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/crowdpose/res152_crowdpose_384x288.py
44a5db23c7771256902673f3b8449cd9471b3de7
[ "Apache-2.0" ]
permissive
bit-scientist/mmpose
57464aae1ca87faf5a4669991ae1ea4347e41900
9671a12caf63ae5d15a9bebc66a9a2e7a3ce617e
refs/heads/master
2023-08-03T17:18:27.413286
2021-09-29T03:48:37
2021-09-29T03:48:37
411,549,076
0
0
Apache-2.0
2021-09-29T06:01:27
2021-09-29T06:01:26
null
UTF-8
Python
false
false
4,087
py
_base_ = ['../../../../_base_/datasets/crowdpose.py'] log_level = 'INFO' load_from = None resume_from = None dist_params = dict(backend='nccl') workflow = [('train', 1)] checkpoint_config = dict(interval=10) evaluation = dict(interval=10, metric='mAP') optimizer = dict( type='Adam', lr=5e-4, ) optimizer_config = dict(grad_clip=None) # learning policy lr_config = dict( policy='step', warmup='linear', warmup_iters=500, warmup_ratio=0.001, step=[170, 200]) total_epochs = 210 log_config = dict( interval=50, hooks=[ dict(type='TextLoggerHook'), # dict(type='TensorboardLoggerHook') ]) channel_cfg = dict( num_output_channels=14, dataset_joints=14, dataset_channel=[ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], ], inference_channel=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]) # model settings model = dict( type='TopDown', pretrained='torchvision://resnet152', backbone=dict(type='ResNet', depth=152), keypoint_head=dict( type='TopdownHeatmapSimpleHead', in_channels=2048, out_channels=channel_cfg['num_output_channels'], loss_keypoint=dict(type='JointsMSELoss', use_target_weight=True)), train_cfg=dict(), test_cfg=dict( flip_test=True, post_process='default', shift_heatmap=True, modulate_kernel=11)) data_cfg = dict( image_size=[288, 384], heatmap_size=[72, 96], num_output_channels=channel_cfg['num_output_channels'], num_joints=channel_cfg['dataset_joints'], dataset_channel=channel_cfg['dataset_channel'], inference_channel=channel_cfg['inference_channel'], crowd_matching=False, soft_nms=False, nms_thr=1.0, oks_thr=0.9, vis_thr=0.2, use_gt_bbox=False, det_bbox_thr=0.0, bbox_file='data/crowdpose/annotations/' 'det_for_crowd_test_0.1_0.5.json', ) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='TopDownRandomFlip', flip_prob=0.5), dict( type='TopDownHalfBodyTransform', num_joints_half_body=6, prob_half_body=0.3), dict( type='TopDownGetRandomScaleRotation', rot_factor=40, scale_factor=0.5), dict(type='TopDownAffine'), dict(type='ToTensor'), dict( type='NormalizeTensor', mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), dict(type='TopDownGenerateTarget', sigma=3), dict( type='Collect', keys=['img', 'target', 'target_weight'], meta_keys=[ 'image_file', 'joints_3d', 'joints_3d_visible', 'center', 'scale', 'rotation', 'bbox_score', 'flip_pairs' ]), ] val_pipeline = [ dict(type='LoadImageFromFile'), dict(type='TopDownAffine'), dict(type='ToTensor'), dict( type='NormalizeTensor', mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), dict( type='Collect', keys=['img'], meta_keys=[ 'image_file', 'center', 'scale', 'rotation', 'bbox_score', 'flip_pairs' ]), ] test_pipeline = val_pipeline data_root = 'data/crowdpose' data = dict( samples_per_gpu=64, workers_per_gpu=2, val_dataloader=dict(samples_per_gpu=32), test_dataloader=dict(samples_per_gpu=32), train=dict( type='TopDownCrowdPoseDataset', ann_file=f'{data_root}/annotations/mmpose_crowdpose_trainval.json', img_prefix=f'{data_root}/images/', data_cfg=data_cfg, pipeline=train_pipeline, dataset_info={{_base_.dataset_info}}), val=dict( type='TopDownCrowdPoseDataset', ann_file=f'{data_root}/annotations/mmpose_crowdpose_test.json', img_prefix=f'{data_root}/images/', data_cfg=data_cfg, pipeline=val_pipeline, dataset_info={{_base_.dataset_info}}), test=dict( type='TopDownCrowdPoseDataset', ann_file=f'{data_root}/annotations/mmpose_crowdpose_test.json', img_prefix=f'{data_root}/images/', data_cfg=data_cfg, pipeline=test_pipeline))
[ "noreply@github.com" ]
noreply@github.com
3b551a4b42da17de908eb870edbeaae245b6dd19
e69b3d212eafc9e740b55a436f04e8801ade47e7
/trade/views.py
20ae5ff695772637cc1e90cbef71d4d782ec25dc
[]
no_license
hebilidu/cardgame
42eaa936f7cb38e2b1975641b304be86fd03d628
a3f608327c602ba3148535c9725b8f73bb1064fa
refs/heads/main
2023-05-27T18:51:27.388954
2021-06-16T11:45:08
2021-06-16T11:45:08
374,296,552
0
0
null
null
null
null
UTF-8
Python
false
false
705
py
from .models import Card from django.views import generic from django.shortcuts import render # Create your views here. class CardListView(generic.ListView): model = Card template_name = 'listcard.html' context_object_name = 'cards' class CardDetailView(generic.DetailView): model = Card template_name = 'viewcard.html' context_object_name = 'card' def shuffle(request): """Display for for creating a deck instance: distribution of the cards among a given group of players""" # 1. ask for number of players # 2. then display formset asking to pick the players from drop-down lists # 3. then display the hands for that deck return render(request, 'listcard')
[ "git@hebi.fr" ]
git@hebi.fr
aca404ff0b8ff3cdfd2290add7bf06d8ab8b0b22
332be7d07cf66b9f8779c164aafb6efa6d731531
/segment.py
fc319b1e489454586146e7085a041637d8ecf89b
[]
no_license
LengyHELL/ocr_ai
420565c92697ef140328c7862cb79c6323c8abcc
825c76921d823fb36c1f0bf6b297d127ad2b25b6
refs/heads/master
2022-06-22T11:24:15.138562
2020-05-06T21:08:07
2020-05-06T21:08:07
261,878,088
0
0
null
null
null
null
UTF-8
Python
false
false
4,877
py
#!/usr/bin/env python3 import numpy as np from PIL import Image, ImageOps def pad_to_height(img, ph): w, h = img.size delta_w = (ph // 2) - w delta_h = ph - h if delta_w < 0: delta_w = 0 if delta_h < 0: delta_h = 0 padding = (delta_w//2, delta_h//2, delta_w-(delta_w//2), 0) return ImageOps.expand(img, padding, fill=255) def getOverlap(a, b): return max(0, min(a[1], b[1]) - max(a[0], b[0])) def blob_detect(bin, line_sep_limit): width, height = bin.size current_label = 1 values = bin.load() labels = np.zeros((width, height), dtype=int) blobs = [] lines = [] prev_line = 0 curr_line = 0 for y in range(height): if (prev_line > curr_line) and (curr_line <= line_sep_limit): lines.append(blobs) blobs = [] prev_line = curr_line curr_line = 0 for x in range(width): if values[x, y] == 0: curr_line += 1 if (values[x, y] == 0) and (labels[x, y] == 0): labels[x, y] = current_label queue = [[x, y]] t_blobs = [[x, y]] while(len(queue) > 0): temp = queue[0] for i in range(-1, 2): for j in range(-1, 2): if (i != 0) or (j != 0): tx = i + temp[0] ty = j + temp[1] if (tx >= 0) and (tx < width) and (ty >= 0) and (ty < height): if (values[tx, ty] == 0) and (labels[tx, ty] == 0): labels[tx, ty] = current_label queue.append([tx, ty]) t_blobs.append([tx, ty]) queue.pop(0) blobs.append(t_blobs) current_label += 1 if len(blobs) > 0: lines.append(blobs) return lines def segment_image(bin, char_size_limit=(5, 200, 5, 200), resize=(0, 0), line_sep_limit=5, sp_rate=0.3, ol_rate=0.5, one_line=False, put_space=False): lines = blob_detect(bin, line_sep_limit) images = [] maxoflines = [] maxch = 0 avch = 0 avcount = 0 for l in lines: l.sort(key=lambda x: x[0]) images_l = [] skips = [] prev = "none" maxl = 0 for b in l: if b not in skips: skips.append(b) achar = np.array(b, dtype=float) cmin = np.amin(achar.T, axis=1) cmax = np.amax(achar.T, axis=1) cmax[0] += 1 cmax[1] += 1 for b2 in l: ochar = np.array(b2, dtype=float) omin = np.amin(ochar.T, axis=1) omax = np.amax(ochar.T, axis=1) omax[0] += 1 omax[1] += 1 ovl = getOverlap([cmin[0], cmax[0]], [omin[0], omax[0]]) size1 = cmax[0] - cmin[0] size2 = omax[0] - omin[0] if ((ovl / size1) >= ol_rate) or ((ovl / size2) >= ol_rate): cmin[0] = min(omin[0], cmin[0]) cmin[1] = min(omin[1], cmin[1]) cmax[0] = max(omax[0], cmax[0]) cmax[1] = max(omax[1], cmax[1]) skips.append(b2) if put_space and (type(prev) != str): omin, omax = prev sp = cmin[0] - omax[0] s_rate = sp / (((cmax[1] - cmin[1]) + (omax[1] - omin[1])) / 2) if (s_rate >= sp_rate): images_l.append("space") cw = cmax[0] - cmin[0] ch = cmax[1] - cmin[1] if ch > maxch: maxch = ch if ch > maxl: maxl = ch avch += ch avcount += 1 cwl, cwu, chl, chu = char_size_limit if (cw > cwl) and (cw <= cwu) and (ch > chl) and (ch <= chu) : images_l.append(bin.crop((cmin[0], cmin[1], cmax[0], cmax[1]))) prev = [cmin, cmax] if len(images_l) > 0: if one_line: images.extend(images_l) else: images.append(images_l) maxoflines.append(maxl) if one_line: images = [images] maxoflines.append(maxch) avch /= avcount if min(resize) > 0: for l in range(len(images)): for c in range(len(images[l])): if type(images[l][c]) != str: images[l][c] = pad_to_height(images[l][c], int(maxoflines[l])).resize((16, 32)) return images
[ "ubi19998@gmail.com" ]
ubi19998@gmail.com
1126769601d5e7319ee39abc278621ac96e499fd
09e57dd1374713f06b70d7b37a580130d9bbab0d
/data/p3BR/R1/benchmark/startCirq357.py
5a0f49a2276e3598ae1db658dd2b3b7f1d4f5362
[ "BSD-3-Clause" ]
permissive
UCLA-SEAL/QDiff
ad53650034897abb5941e74539e3aee8edb600ab
d968cbc47fe926b7f88b4adf10490f1edd6f8819
refs/heads/main
2023-08-05T04:52:24.961998
2021-09-19T02:56:16
2021-09-19T02:56:16
405,159,939
2
0
null
null
null
null
UTF-8
Python
false
false
4,236
py
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 5/15/20 4:49 PM # @File : grover.py # qubit number=3 # total number=64 import cirq import cirq.google as cg from typing import Optional import sys from math import log2 import numpy as np #thatsNoCode from cirq.contrib.svg import SVGCircuit # Symbols for the rotation angles in the QAOA circuit. def make_circuit(n: int, input_qubit): c = cirq.Circuit() # circuit begin c.append(cirq.H.on(input_qubit[0])) # number=1 c.append(cirq.rx(-0.09738937226128368).on(input_qubit[2])) # number=2 c.append(cirq.H.on(input_qubit[1])) # number=33 c.append(cirq.Y.on(input_qubit[2])) # number=56 c.append(cirq.CZ.on(input_qubit[2],input_qubit[1])) # number=34 c.append(cirq.H.on(input_qubit[1])) # number=35 c.append(cirq.H.on(input_qubit[1])) # number=3 c.append(cirq.H.on(input_qubit[0])) # number=45 c.append(cirq.CNOT.on(input_qubit[2],input_qubit[1])) # number=60 c.append(cirq.CZ.on(input_qubit[1],input_qubit[0])) # number=46 c.append(cirq.H.on(input_qubit[0])) # number=47 c.append(cirq.Y.on(input_qubit[1])) # number=15 c.append(cirq.H.on(input_qubit[0])) # number=61 c.append(cirq.CZ.on(input_qubit[1],input_qubit[0])) # number=62 c.append(cirq.H.on(input_qubit[0])) # number=63 c.append(cirq.H.on(input_qubit[1])) # number=19 c.append(cirq.CZ.on(input_qubit[0],input_qubit[1])) # number=20 c.append(cirq.rx(-0.6000441968356504).on(input_qubit[1])) # number=28 c.append(cirq.H.on(input_qubit[1])) # number=21 c.append(cirq.H.on(input_qubit[1])) # number=30 c.append(cirq.CZ.on(input_qubit[0],input_qubit[1])) # number=31 c.append(cirq.H.on(input_qubit[1])) # number=32 c.append(cirq.H.on(input_qubit[1])) # number=57 c.append(cirq.CZ.on(input_qubit[0],input_qubit[1])) # number=58 c.append(cirq.H.on(input_qubit[1])) # number=59 c.append(cirq.CNOT.on(input_qubit[0],input_qubit[1])) # number=51 c.append(cirq.X.on(input_qubit[1])) # number=52 c.append(cirq.CNOT.on(input_qubit[0],input_qubit[1])) # number=53 c.append(cirq.CNOT.on(input_qubit[0],input_qubit[1])) # number=50 c.append(cirq.H.on(input_qubit[2])) # number=29 c.append(cirq.H.on(input_qubit[1])) # number=36 c.append(cirq.CZ.on(input_qubit[0],input_qubit[1])) # number=37 c.append(cirq.Y.on(input_qubit[2])) # number=44 c.append(cirq.H.on(input_qubit[1])) # number=38 c.append(cirq.Z.on(input_qubit[1])) # number=55 c.append(cirq.CNOT.on(input_qubit[0],input_qubit[1])) # number=18 c.append(cirq.Z.on(input_qubit[1])) # number=11 c.append(cirq.rx(-1.1780972450961724).on(input_qubit[2])) # number=54 c.append(cirq.H.on(input_qubit[1])) # number=42 c.append(cirq.H.on(input_qubit[0])) # number=39 c.append(cirq.CZ.on(input_qubit[1],input_qubit[0])) # number=40 c.append(cirq.H.on(input_qubit[0])) # number=41 c.append(cirq.CNOT.on(input_qubit[2],input_qubit[1])) # number=26 c.append(cirq.Y.on(input_qubit[1])) # number=14 c.append(cirq.CNOT.on(input_qubit[1],input_qubit[0])) # number=5 c.append(cirq.X.on(input_qubit[1])) # number=6 c.append(cirq.Z.on(input_qubit[1])) # number=8 c.append(cirq.X.on(input_qubit[1])) # number=7 c.append(cirq.H.on(input_qubit[2])) # number=43 c.append(cirq.rx(-2.42845112122491).on(input_qubit[1])) # number=25 # circuit end c.append(cirq.measure(*input_qubit, key='result')) return c def bitstring(bits): return ''.join(str(int(b)) for b in bits) if __name__ == '__main__': qubit_count = 4 input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)] circuit = make_circuit(qubit_count,input_qubits) circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap') circuit_sample_count =2000 simulator = cirq.Simulator() result = simulator.run(circuit, repetitions=circuit_sample_count) frequencies = result.histogram(key='result', fold_func=bitstring) writefile = open("../data/startCirq357.csv","w+") print(format(frequencies),file=writefile) print("results end", file=writefile) print(circuit.__len__(), file=writefile) print(circuit,file=writefile) writefile.close()
[ "wangjiyuan123@yeah.net" ]
wangjiyuan123@yeah.net
400f6be9556fac62ba3aa272db6bb659e5bd2af6
8e877d994febf44a8ceb569c59a51b1f4b1bb67f
/dynamic_process/canPartition.py
5af30d59935114a03d1746facc34b239aec06bb4
[]
no_license
Adrian-Yan16/Algorithm
dc0c1f6cb193795cb064cc2a69ede0b726eb6f70
7aed70d29cd877e1f0fb9d0f2567e686f6f3cd4c
refs/heads/main
2023-04-05T20:17:05.148507
2021-04-11T05:11:54
2021-04-11T05:11:54
356,765,857
0
0
null
null
null
null
UTF-8
Python
false
false
1,094
py
# 给定一个只包含正整数的非空数组。是否可以将这个数组分割成两个子集,使得两个子集的元素和相等。 class Solution: def canPartition(self, nums) -> bool: if len(nums) <= 1: return False if sum(nums) % 2 != 0: return False mid = sum(nums) // 2 dp = [0] * (mid + 1) dp[0] = 1 if nums[0] <= mid: dp[nums[0]] = 1 for i in range(1,len(nums)): for j in range(mid,nums[i]-1,-1): dp[j] = dp[j] or dp[j - nums[i]] return dp[-1] == 1 def can2(self,nums): if len(nums) <= 1: return False if sum(nums) % 2 != 0: return False mid = sum(nums) // 2 s = set() s.add(mid) for i in nums: c = s.copy() for j in c: if j == i: return True elif j > i: s.add(j - i) return False s= Solution() print(s.can2([3,3,3,4,5]))
[ "Adrian-Yan2329@outlook.com" ]
Adrian-Yan2329@outlook.com
4fcf7340a166ecd7f45005f51cbcdd4b566ed743
ade88cd3f75e8b7c9470198f806fc7b1ac4aabf2
/fooster/console/commands.py
4d318d3e7ea961593774f8c22bcb612ff93cf54a
[ "MIT" ]
permissive
lilyinstarlight/python-fooster-console
d956fc4a57c167d4f0bd5eeee6ee76da9d8911cd
e2cd6a80298ba0c22334fdb0967b8c3f074fa49e
refs/heads/main
2022-12-30T02:43:07.884233
2020-10-18T15:06:35
2020-10-18T15:06:35
247,068,837
0
0
null
null
null
null
UTF-8
Python
false
false
2,021
py
import inspect from . import exception __all__ = ['quit', 'ping', 'help'] def quit(): raise exception.ConsoleQuit() def ping(): return def help(cmd=None, *, name, handler): if cmd is None: cmd = name cmd_func = handler.commands.get(cmd) if cmd_func is None: handler.channel.send(handler.settings['unrecognized'].format(cmd=cmd)) return cmd_spec = inspect.getfullargspec(cmd_func) if cmd_spec.varargs is not None: kwargs = {} if 'channel' in cmd_spec.kwonlyargs: kwargs['channel'] = handler.channel if 'handler' in cmd_spec.kwonlyargs: kwargs['handler'] = handler if 'name' in cmd_spec.kwonlyargs: kwargs['name'] = cmd cmd_func('-h', **kwargs) else: handler.channel.send(handler.settings['usage']) help_args = [cmd] help_args.extend(['<{}>'.format(arg) if idx < (len(cmd_spec.args) - (len(cmd_spec.defaults) if cmd_spec.defaults is not None else 0)) else '[{}]'.format(arg) for idx, arg in enumerate(cmd_spec.args)]) handler.channel.send(' '.join(help_args)) handler.channel.send('\r\n') if cmd_func.__doc__: handler.channel.send('\r\n') lines = cmd_func.__doc__.expandtabs().splitlines() indent = None for line in lines[1:]: stripped = line.lstrip() if stripped: if indent is not None: indent = min(indent, len(line) - len(stripped)) else: indent = len(line) - len(stripped) doc = [lines[0].strip()] if indent: for line in lines[1:]: doc.append(line[indent:].rstrip()) while doc and not doc[-1]: doc.pop() while doc and not doc[0]: doc.pop(0) handler.channel.send('\r\n'.join(doc)) handler.channel.send('\r\n')
[ "fkmclane@gmail.com" ]
fkmclane@gmail.com
d5cd69477fb65659ccc9e6b7b521f450a70afb7f
4ca47225b7b3f468eab9dc391aebc00485869a65
/collector/migrations/0019_auto_20180105_0123.py
0d9de3c879ab138c221841a6f16f99a8cab72608
[]
no_license
HippyFizz/conduster
cec1f972610c827ed692c4e48b06b9215ffbfac3
9d90f838da6ff44402c550934d1c323a26f29036
refs/heads/master
2020-03-08T20:29:58.126183
2018-04-06T11:02:00
2018-04-06T11:02:00
128,383,501
0
0
null
null
null
null
UTF-8
Python
false
false
980
py
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2018-01-05 01:23 from __future__ import unicode_literals import os from django.conf import settings from django.db import migrations from pyexcel_xlsx import get_data def fill_refs(apps, schema_editor): data = get_data("{0}/{1}.xlsx".format(os.path.join(settings.BASE_DIR, 'refs_data'), 'browsers')) data = data['Отчет'] BrowserFamily = apps.get_model('collector', 'BrowserFamily') BrowserVersion = apps.get_model('collector', 'BrowserVersion') other = BrowserFamily.objects.create(name="other") BrowserVersion.objects.create(version="other", family=other) for b in data[1:]: bf, created = BrowserFamily.objects.get_or_create(name=b[0].lower()) BrowserVersion.objects.create(family=bf, version=b[1].lower()) class Migration(migrations.Migration): dependencies = [ ('collector', '0018_browserfamily_browserversion'), ] operations = [ migrations.RunPython(fill_refs), ]
[ "buptyozzz@gmail.com" ]
buptyozzz@gmail.com
5ede7686f7d25d428704bb4cd43f226ffeaf9d36
a0d140dd956187c1ae45bae22b0431392c8859d0
/chapter09_class/9-2.dog_class.py
57ede29dd8dc29ed19ac85d696ee4776c8bb422a
[]
no_license
vega2k/python_basic
6fce4a049671adfb0fcfb84bcadb92431a3cad08
fd244c50142e7d1f9129b9bcb4324fa68b7295c0
refs/heads/master
2023-02-16T08:02:31.214801
2021-01-15T08:38:29
2021-01-15T08:38:29
326,850,489
2
0
null
null
null
null
UTF-8
Python
false
false
328
py
class Dog: tricks = [] def __init__(self,name): self.name = name def add_trick(self,trick): self.tricks.append(trick) fido = Dog('Fido') buddy = Dog('buddy') fido.add_trick('구르기') print(fido.tricks) buddy.add_trick('두 발로 서기') buddy.add_trick('죽은 척 하기') print(buddy.tricks)
[ "vega2k@naver.com" ]
vega2k@naver.com
e6c2e9de7f09f386a91774aa9868738ccbce1c1a
502bb02d8cfb11fa8dd47ebd7d73d3450208d3e2
/Greetings.py
c0623775c659cce88ba20a9690447c09bc023a93
[]
no_license
sairamkarthik/Python
95daddf897cbaed810223f7ec7b4f2c7d08aec66
cbbfe100a3829d6ee97fbfc45ab6130c690ad4d9
refs/heads/master
2021-01-01T05:52:34.267439
2017-07-23T07:44:47
2017-07-23T07:44:47
97,294,513
0
0
null
null
null
null
UTF-8
Python
false
false
69
py
print("Enter your name") n=raw_input()# Greetings print("Hello "+ n)
[ "noreply@github.com" ]
noreply@github.com
ad63d4633e500aaa6bffae2474fa518f40c6ba45
8eeace0a88efbfa5ff2d96d92c6f6b8587532ae3
/game/src/data.py
24ef242d8675b3abe8c835caf37821bd47cff3bf
[ "MIT" ]
permissive
mdinacci/rtw
96e7ef504820f0a3d79f755e2811fdfdb04e7726
8429d17b002435fb27f403699a23af879f14d9a1
refs/heads/master
2016-09-06T14:55:17.251012
2014-02-07T10:55:08
2014-02-07T10:55:08
null
0
0
null
null
null
null
UTF-8
Python
false
false
834
py
# -*- coding: utf-8-*- """ Author: Marco Dinacci <dev@dinointeractive.com> Copyright © 2008-2009 """ class GameMode: CHAMP_MODE = "champ" TB_MODE = "tb" NO_MODE = None class TrackResult: tid = -1 bestTime = "" attempts = 0 bid = -1 def __repr__(self): return "ID: %s\nBest time: %s\nAttempts: %d\nBall: %s\n" % \ (self.tid, self.bestTime, self.attempts, self.bid) class TrackInfo: ATTRIBUTES = ("gold", "silver", "bronze", "limit") tid = -1 order = -1 name = "" gold = -1 silver = -1 bronze = -1 limit = -1 def __repr__(self): return "ID: %s\nOrder: %s\nName: %s\nGold: %s\nSilver: %s\nBronze: \ %s\nLimit: %s\n" % \ (self.tid, self.order, self.name, self.gold, self.silver, self.bronze, self.limit)
[ "dev@dinointeractive.com" ]
dev@dinointeractive.com
bd8494dd2ce5b375a957c4296137fcc68b85487a
0035ebda58fdefbb3926b4cebd2a107c7e5c0eee
/myapp/pages/models.py
6b47115f537f320cc76ec7acc447f5e6c972908d
[]
no_license
semillastan/phdevs-flask-mongodb
6ad3990c3ed3c450153f208c0f6987e501c36ea5
d8356b22eacd4d2cfee9195ece1bb171b4593292
refs/heads/master
2021-01-10T04:57:24.616700
2016-04-01T07:35:08
2016-04-01T07:35:08
55,212,119
0
0
null
null
null
null
UTF-8
Python
false
false
63
py
import datetime from flask import url_for from myapp import db
[ "semillastan@gmail.com" ]
semillastan@gmail.com
1c833f604a6faef84412a3d4cd09eab26216a2e6
79ded53076d0bd933df5682576ec2b6320d989c6
/MainAPI.py
c602650f4779de23b7c7d50cd77e10ed0c62378f
[]
no_license
DonnaVakalis/Cool-finding-app
75fde33e6e88a90b670a3175ce55827f91a9aa32
00e9d7ba1020221637498f92fb871781dc4e6586
refs/heads/master
2021-06-04T13:14:06.929560
2020-09-15T02:06:28
2020-09-15T02:06:28
146,217,576
0
0
null
null
null
null
UTF-8
Python
false
false
4,310
py
# -*- coding: utf-8 -*- """ This finds the friends of a Twitter user, and stores them in a list; then, this list is passed back to find the friends-of-friends; The goal is to calculate overlaps and give an index of 'how much overlap' there is among your friends. ...Kind of like a quantification of how much your twitter feed is a 'bubble' Created on Fri Oct 5 14:53:20 2018 @author: Donna """ #%% Import useful files import tweepy from tweepy import API from tweepy import Cursor from tweepy.streaming import StreamListener from tweepy import OAuthHandler #%% import sys sys.path.append('../') for p in sys.path: print(p) #%% import time import numpy import pandas import utils_dnp import importlib importlib.reload(utils_dnp) #This protects keys from viewing when sharing this code # utils_do_not_post contains the following four variables: # API key CONSUMER_KEY # API secret CONSUMER_SECRET # Access token ACCESS_TOKEN # Access token secret ACCESS_TOKEN_SECRET print(utils_dnp.CONSUMER_KEY) #Erase this line later: used for checking whether utils_dnp has been reloaded #%% Create Classes class TwitAuthenticator(): """ Authentication, gets called inside TwitClient class """ def authenticate_twitter_app(self): #Connect on OAuth process, using the keys and tokens: auth = tweepy.OAuthHandler(utils_dnp.CONSUMER_KEY, utils_dnp.CONSUMER_SECRET) auth.set_access_token(utils_dnp.ACCESS_TOKEN, utils_dnp.ACCESS_TOKEN_SECRET) return auth class TwitClient(): """ Construct a client. Get authorization from Twitter API. And gets the friends list of the given twitter_user (not necessarily the same as the authorizing account!) """ #Construct a Client def __init__(self,twitter_user=None): self.auth = TwitAuthenticator().authenticate_twitter_app() self.twitter_client = API(self.auth) self.twitter_user = twitter_user print(self.twitter_user) #for debugging purposes erase later def get_twitter_client_api(self): return self.twitter_client def get_friend_list(self): friend_list=[] for friend in Cursor(self.twitter_client.friends, id=self.twitter_user).items(): friend_list.append(friend) return friend_list def on_error(self, status): if status == 420: #Kill it if rate limit is exceeded return False print(status) class FriendAnalyzer(): """ Listing and categorizing friends list """ def friends_to_data_frame(self, friend_list): df = pandas.DataFrame(data=[friend.id for friend in friend_list], columns=['Friend_ID']) df['Name'] = numpy.array([friend.name for friend in friend_list]) df['User_name'] = numpy.array([friend.screen_name for friend in friend_list]) #broke after I added this line df['Friends_count'] = numpy.array([friend.friends_count for friend in friend_list]) return df def count_ships(self): pass #%% Main part of the program if __name__ == "__main__": #Get List of 'Friends' twitter_client = TwitClient() friend_analyzer = FriendAnalyzer() api = twitter_client.get_twitter_client_api() friendList = twitter_client.get_friend_list() #print(dir(friendList[0])) #for finding attributes of object friendList (which is a list of built-in "friend" objects) MyFriends = friend_analyzer.friends_to_data_frame(friendList) print(MyFriends.head(12)) #print(MyFriends.User_name[0]) #%% #Get list of 'Friends' of 'Friends' MyFriends.Name[0] #twitter_client = TwitClient(twitter_user=MyFriends.User_name[0]) #works with twitter_user="SportIsAllOver" vvv = "TheDickCavett" print(vvv) print(MyFriends.User_name[4]) #%% twitter_client = TwitClient(twitter_user=MyFriends.User_name[4]) #%% friend_analyzer = FriendAnalyzer() #%% friendList2 = twitter_client.get_friend_list() #%% TheirFriends = friend_analyzer.friends_to_data_frame(friendList2) print(TheirFriends.head(10))
[ "noreply@github.com" ]
noreply@github.com
aeddc1d7fbf8ea26f225c60088dd41b3447c6fbe
e00186e71a1f52b394315a0cbc27162254cfffb9
/durga/full_durga/without_restm2/without_restm2/asgi.py
40491539a6ce4db3dc21ec67f0020d7ead8ce036
[]
no_license
anilkumar0470/git_practice
cf132eb7970c40d0d032520d43e6d4a1aca90742
588e7f654f158e974f9893e5018d3367a0d88eeb
refs/heads/master
2023-04-27T04:50:14.688534
2023-04-22T05:54:21
2023-04-22T05:54:21
100,364,712
0
1
null
2021-12-08T19:44:58
2017-08-15T10:02:33
Python
UTF-8
Python
false
false
405
py
""" ASGI config for without_restm2 project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'without_restm2.settings') application = get_asgi_application()
[ "anilkumar.0466@gmail.com" ]
anilkumar.0466@gmail.com
bf60664aa69ada355fc1596296b08ac4e39e32dc
bc4c1b3388b9bcc7fdab65699c5ae1f6dbc5531f
/jtVAE/prep_datasets.py
1a1432e7813210f6a9642de475d22cf558abcf1f
[ "MIT" ]
permissive
JennyW5/ComparisonsDGM
fd7235fc5a5e49424a3bc39df483fbafa0582d3d
0a26e9f9d9aba7df0525a22da6eeab376464d19d
refs/heads/master
2023-01-07T05:00:27.958540
2020-09-16T16:14:35
2020-09-16T17:15:51
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,715
py
import torch import torch.nn as nn from torch.autograd import Variable import math, random, sys from optparse import OptionParser from collections import deque import rdkit import rdkit.Chem as Chem import sys import os sys.path.append('%s/../' % os.path.dirname(os.path.realpath(__file__))) from jtnn import * sys.path.append('%s/../../_utils' % os.path.dirname(os.path.realpath(__file__))) from read_dataset import readStr_qm9 from read_dataset import read_zinc from utils import save_decoded_results, save_decoded_priors import numpy as np # constant CHUNK_SIZE = 1 def main(): torch.manual_seed(0) lg = rdkit.RDLogger.logger() lg.setLevel(rdkit.RDLogger.CRITICAL) parser = OptionParser() parser.add_option("-t", "--test", dest="test_path") parser.add_option("-v", "--vocab", dest="vocab_path") parser.add_option("-m", "--model", dest="model_path") parser.add_option("-w", "--hidden", dest="hidden_size", default=200) parser.add_option("-l", "--latent", dest="latent_size", default=56) parser.add_option("-d", "--depth", dest="depth", default=3) opts,args = parser.parse_args() vocab = [x.strip("\r\n ") for x in open(opts.vocab_path)] vocab = Vocab(vocab) hidden_size = int(opts.hidden_size) latent_size = int(opts.latent_size) depth = int(opts.depth) model = JTNNVAE(vocab, hidden_size, latent_size, depth) model.load_state_dict(torch.load(opts.model_path)) model = model.cuda() dataset_name = opts.test_path result_file = dataset_name + "_decoded_results.txt" priors_file = dataset_name + "_decoded_priors.txt" generation_fie = dataset_name + "_generation.txt" # read dataset if dataset_name == "zinc": XTE = read_zinc() else: D = readStr_qm9() # fix problem about molecule with '.' inside XTE = [] for mol in D: if "." not in mol: XTE.append(mol) # reconstruction XTE = XTE[0:5000] XTE = filter(lambda x: len(x) > 1, XTE) #needed for removing smiles with only a char. decoded_result = reconstruction(model, XTE, 20, 1) save_decoded_results(XTE, decoded_result, result_file) # prior # decoded_priors_witherrors = model.sample_prior_eval(True, 1000, 10) # decoded_priors = [] # for i in decoded_priors_witherrors: # decoded_priors.append(sanitize(i)) # save_decoded_priors(decoded_priors, priors_file) # generation generation_witherrors = model.sample_prior_eval(True, 20000, 1) generation = [] for i in generation_witherrors: generation.append(sanitize(i)) save_decoded_priors(generation, generation_fie) if __name__ == '__main__': main()
[ "davider1994@gmail.com" ]
davider1994@gmail.com
8b15217045694fb83091a6e4f46af691e62f0917
4f629bf2319616202c9abe910dcc2ebe113c8416
/arcade/python/2_slithering_in_strings/competitive_eating.py
a52be28084c0ae2a0c7ad9039d1176e0514a0807
[ "MIT" ]
permissive
jjwong/codefights
33758757b176baf966eea3ac29e32d9b8f7e3428
871f6ebf840cc36aca51da24e3f535a73e9c7567
refs/heads/master
2020-03-09T03:26:21.605456
2018-04-07T22:20:00
2018-04-07T22:20:00
128,565,376
0
0
null
null
null
null
UTF-8
Python
false
false
141
py
def permutationCipher(password, key): table = password.maketrans('abcdefghijklmnopqrstuvwxyz', key) return password.translate(table)
[ "jjwong05@gmail.com" ]
jjwong05@gmail.com
23369607195994930268cc9f71fbe59da42be6fa
7fd9dc3e0fe315349fd59d3b1b71fbb7f4bfad10
/lsits_3.py
4dc1d1a4748c96c2cdda1cedab0bbd918af4c3be
[]
no_license
17BTCS023/Addition
7834515a49547c2cf2ac6fef587411c54670574e
a48b62b4bc8d48b3f68650eaacaec1a5c776f979
refs/heads/master
2022-04-04T19:26:15.145478
2020-02-19T12:54:37
2020-02-19T12:54:37
118,342,960
0
1
null
2020-02-19T12:54:38
2018-01-21T14:39:05
Python
UTF-8
Python
false
false
135
py
#list- ordered collection of data # addition of list numbers= [1,2,3] fruit= ['banana','melon','mango',list] print(fruit+numbers)
[ "noreply@github.com" ]
noreply@github.com
f18a4f1f9257e84804660410903fd95de82ec7f1
a9ef1de9718d2c25d258f3931948396fef2fa30c
/Ejercicios/repeticiones7.py
10187242a434de915235f2b8bc3f82c9c6abf252
[ "Apache-2.0" ]
permissive
juanfcosanz/Python
fbea1fb53603662c5539e850f68eb36051ef9bd5
3d10083a8757bc729f824e57ab320a4d5d6e51ff
refs/heads/master
2021-01-17T06:33:49.189783
2014-04-01T03:51:17
2014-04-01T03:51:17
null
0
0
null
null
null
null
UTF-8
Python
false
false
160
py
tabla = 1 while tabla <= 10: n= 1 print("\nTabla del %d" %tabla) while n <= 10: print("%d x %d = %d" %(tabla,n,(tabla*n))) n = n + 1 tabla = tabla + 1
[ "slipkacho21metal@hotmail.com" ]
slipkacho21metal@hotmail.com
8def5ea4fa1b536a7d27e5ee746a0d7eef26180f
17a655d21d7ddaf8cf60e23055e107cb602bd9bc
/project/bookmarker/migrations/0001_initial.py
7739e40db601749d17b8b704a596aa005e8e6a15
[]
no_license
geofferyj/YouTubeVideoBookmarker
fedb6913a8c5118c0a51f011244233630cf6f58c
fbf10230c5184cd1479dddafbcfd3609d5ac98f1
refs/heads/master
2023-08-04T22:30:37.636957
2021-03-01T08:09:46
2021-03-01T08:09:46
278,203,783
0
0
null
2021-09-22T19:46:09
2020-07-08T22:05:00
JavaScript
UTF-8
Python
false
false
4,185
py
# Generated by Django 3.0.8 on 2020-08-09 19:13 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Video', fields=[ ('vid', models.CharField(max_length=11, primary_key=True, serialize=False)), ('timestamps', models.TextField(default='')), ('cost', models.PositiveIntegerField(default=0)), ('locked', models.BooleanField(default=False)), ('last_editor', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='VoicePause', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('has', models.BooleanField(default=False)), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='voice_pause', to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='VideoViews', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='views', to=settings.AUTH_USER_MODEL)), ('video', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='views', to='bookmarker.Video')), ], ), migrations.CreateModel( name='UserVideo', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='videos', to=settings.AUTH_USER_MODEL)), ('video', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='users', to='bookmarker.Video')), ], ), migrations.CreateModel( name='Token', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('amount', models.PositiveIntegerField(default=0)), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='tokens', to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Subscription', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('paid_until', models.DateTimeField(blank=True, null=True)), ('date_paid', models.DateTimeField(auto_now_add=True)), ('paypal_subscription_id', models.CharField(blank=True, max_length=64, null=True)), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='subscription', to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='ResetableViews', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('count', models.PositiveIntegerField(default=0)), ('video', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='rviews', to='bookmarker.Video')), ], ), migrations.AddConstraint( model_name='videoviews', constraint=models.UniqueConstraint(fields=('user', 'video'), name='video_views_constraint'), ), migrations.AddConstraint( model_name='uservideo', constraint=models.UniqueConstraint(fields=('user', 'video'), name='user_video_constraint'), ), ]
[ "geofferyjoseph1@gmail.com" ]
geofferyjoseph1@gmail.com
5a098bfd5acd5c1f57aa09045ec71dddb521f41f
14d1fa8ed5b0abbc4afd9196e24863c2fe5e0eb1
/py99.py
9f1a306c0fdb1a4733699544424ab1978f996280
[ "Unlicense" ]
permissive
riccardobl/py99
70da47c348c33b0f7cfdde7a0422f273a60a3721
0e58701fb3763df6ac58ac6f8f03af4a1e3dbf03
refs/heads/master
2020-04-05T23:14:08.360887
2017-02-10T20:44:30
2017-02-10T20:44:30
63,715,811
3
0
null
null
null
null
UTF-8
Python
false
false
5,725
py
import sys,re,os def _read_file(fin): c=None with open(fin,"r") as finf: c=finf.read() return c def _write_file(fout,content): with open(fout,"w") as foutf: foutf.write(content) fin=sys.argv[1] fout=sys.argv[2] content=_read_file(fin) strings=[] #Remove strings & comments ns_content="" is_string=False is_comment=False string_limiters=['"',"'"] binded_limiter=None skip_next=False for i,c in enumerate(content): if skip_next: skip_next=False continue if (not is_string): if(c=="/" and content[i+1]=="/" and (content[i-1]!="\\" or content[i-2]=="\\")): is_comment= not is_comment skip_next=True continue elif c=="\n": is_comment=False if is_comment: continue if ((c==string_limiters[0] or c==string_limiters[1]) if binded_limiter==None else c==binded_limiter) and (i>1 and (content[i-1]!="\\" or (i>2 and content[i-2]=="\\"))): if is_string: ns_content+="@str$"+str(len(strings)-1)+"@" is_string=False binded_limiter=None else: strings.append("") is_string=True binded_limiter=c ns_content+=c else: if not is_string: ns_content+=c else: strings[-1]+=c content=ns_content #Remove comments, we have only one type of comment that is // single line comment. #rx = re.compile(r'\/\/.*$') #lines=content.split("\n") #nl=[] #for i,l in enumerate(lines): # nl.append(rx.sub("",l)) #content="\n".join(nl) # || -> or && -> and rx = re.compile(r'\|\|', re.IGNORECASE|re.UNICODE) content=rx.sub(" or ",content) rx = re.compile(r'\&\&', re.IGNORECASE|re.UNICODE) content=rx.sub(" and ",content) # true -> True false -> False rx = re.compile(r'([^A-Z0-9]|^)(true|false)') content=rx.sub(lambda m: m.group(1)+m.group(2).title(),content) # null -> None rx = re.compile(r'([^A-Z0-9]|^)null') content=rx.sub(lambda m:m.group(1)+"None",content) # !abc -> not abc rx = re.compile(r'\!([\s]*[A-Z\(]+)',re.IGNORECASE|re.UNICODE|re.MULTILINE) content=rx.sub(lambda m:"not "+m.group(1),content) # ; - > \n rx = re.compile(r';[ ]*([A-Z0-9_])',re.IGNORECASE|re.UNICODE) content=rx.sub(lambda m:";\n "+m.group(1),content) #Clean curly brackets rx = re.compile(r'\)([\s]*)\{[ ]*\n',re.MULTILINE|re.UNICODE) content=rx.sub(lambda m:"){",content) rx = re.compile(r'\)([\s]*)\{',re.MULTILINE|re.UNICODE) content=rx.sub(lambda m:"){\n",content) rx = re.compile(r'\}([^\n\r]*[A-Z_])', re.IGNORECASE|re.MULTILINE|re.UNICODE) content=rx.sub(lambda m:"}\n"+m.group(1),content) #HACK: transform else in a function rx = re.compile(r'([^A-Z0-9]|^)else[\s]*\{',re.MULTILINE|re.UNICODE) content=rx.sub(lambda m:m.group(1)+"else(){",content) #HACK: transform try in a function rx = re.compile(r'([^A-Z0-9]|^)try[\s]*\{',re.MULTILINE|re.UNICODE) content=rx.sub(lambda m:m.group(1)+"try(){",content) #HACK: transform except in a function rx = re.compile(r'([^A-Z0-9]|^)except[\s]*\{', re.MULTILINE|re.UNICODE) content=rx.sub(lambda m:m.group(1)+"except(){",content) #Clean class rx = re.compile(r'([^A-Z0-9]|^)class([A-Z0-9 _]+)\s*\{', re.IGNORECASE|re.MULTILINE|re.UNICODE) content=rx.sub(lambda m:m.group(1)+"class"+m.group(2)+"(){",content) #Remove spaces rx = re.compile(r'^[ ]+',re.MULTILINE) content=rx.sub("",content) rx = re.compile(r'[ ]+$',re.MULTILINE) content=rx.sub("",content) #Replace curly brakets and apply correct indentation indentation_level=0 lines=content.split("\n") nl=[] is_dict=[] rx_space = re.compile("[\s\{]") for i,l in enumerate(lines): lx=l for s in range(0,indentation_level*4): lx=" "+lx ly="" for k,c in enumerate(lx): if len(is_dict)<indentation_level :is_dict.append(False) i=indentation_level if c=="{": indentation_level+=1 if k>1 and lx[k-1]==")": if len(is_dict)<indentation_level :is_dict.append(False) is_dict[indentation_level-1]=False #print("Indentation >>") ly+=":" continue else: if len(is_dict)<indentation_level :is_dict.append(False) is_dict[indentation_level-1]=True # print("Is not a block [1]") elif c=="}": # print("Indentation <<") if not is_dict[indentation_level-1]: pass else: # print("Is not a block [2]") if len(is_dict)<indentation_level :is_dict.append(False) is_dict[indentation_level-1]=False ly+="}" indentation_level-=1 continue ly+=c nl.append(ly) content="\n".join(nl) #HACK: retransform try rx = re.compile(r'([^A-Z0-9]|^)try\(\)', re.MULTILINE|re.UNICODE) content=rx.sub(lambda m:m.group(1)+"try",content) #HACK: retransform else rx = re.compile(r'([^A-Z0-9]|^)else\(\)', re.MULTILINE|re.UNICODE) content=rx.sub(lambda m:m.group(1)+"else",content) #HACK: retransform except rx = re.compile(r'([^A-Z0-9]|^)except\(\)', re.MULTILINE|re.UNICODE) content=rx.sub(lambda m:m.group(1)+"except",content) def removeForBrakets(m): out=m.group(1)+m.group(2)+" "; rx = re.compile(r'\)(\s*:)', re.UNICODE) out+=rx.sub(lambda x:x.group(1),m.group(3)) return out #HACK: Remove brackets from for rx = re.compile(r'([^A-Z0-9]|^)(for\s*)\(([^:]+\:)', re.IGNORECASE|re.MULTILINE|re.UNICODE) content=rx.sub(lambda m:removeForBrakets(m),content) #Add strings back for i in range(0,len(strings)): content=content.replace("@str$"+str(i)+"@",strings[i]) _write_file(fout,content)
[ "riccardo@forkforge.net" ]
riccardo@forkforge.net
a2447a530790f7abc4102d878fa6f75cc977ca98
964e3dd6adb1c04b9b7b6de92dd31813d2f1f075
/mysite/urls.py
7e4bc4a76e3d4cf7c2694db71cafdb3dd0c08d63
[]
no_license
Daniel-Domene/my-first-blog-
bdd669cd399ffb0452a4286db82a99278f929b0d
f1a5bf51198f52685a7fa7c6c70552a374859b82
refs/heads/master
2021-01-20T19:21:32.111102
2016-07-17T15:09:02
2016-07-17T15:09:02
63,526,804
0
0
null
null
null
null
UTF-8
Python
false
false
816
py
"""mysite URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/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 include, url from django.contrib import admin urlpatterns = [ url(r'^admin/' , admin.site.urls), url(r'', include('blog.urls')), ]
[ "daniel_domene@hotmail.com" ]
daniel_domene@hotmail.com
6bc8cd61d8967b5a2a2913543f445ebafb4b8904
4237d975945a3e8fc427bc2aca6c4df80b668d62
/Functions/calc/02-Calc.py
bd7491222cfc5a00386914d235508ca25ac8c16b
[]
no_license
ravi4all/Python_JuneMorningRegular
36af0302af382b1a94cc9efc6af2fa1a099565fa
5bd36a4be7579e65fbc862521c01042ca841e3cd
refs/heads/master
2020-03-20T04:10:32.641007
2018-07-03T06:38:41
2018-07-03T06:38:41
137,173,202
0
4
null
null
null
null
UTF-8
Python
false
false
600
py
def add(x,y): result = x + y print("Addition is",result) def sub(x,y): result = x - y print("Subtraction is", result) def mul(x,y): result = x * y print("Multiplication is", result) def div(x,y): result = x / y print("Division is", result) print(""" 1. Add 2. Sub 3. Mul 4. Div """) user_choice = input("Enter your choice : ") num_1 = int(input("Enter first number : ")) num_2 = int(input("Enter second number : ")) todo = { '1' : add, '2' : sub, '3' : mul, '4' : div } todo.get(user_choice)(num_1, num_2)
[ "noreply@github.com" ]
noreply@github.com
f4937a200488f1a80a92b5d267bdd363eb26490d
5aec9b30005a8a5cc39da3c46ce65aa3e6710cfe
/tools/delete_queues.py
d499f5f82945a5b4422e2f65b1c1c2283cca3a81
[ "MIT" ]
permissive
cloudworkstation/cloudworkstation-api
90d0726e712cd403fdbcd7c2b39ec9f1ee1890ad
661500aaaa304db13e99d8365428520c2c77f5dd
refs/heads/main
2023-04-13T07:54:47.717843
2021-04-09T20:09:57
2021-04-09T20:09:57
338,401,801
0
0
null
2021-04-06T09:05:39
2021-02-12T18:35:52
Python
UTF-8
Python
false
false
393
py
import boto3 sqs = boto3.client("sqs") def find_and_remove(): response = sqs.list_queues( QueueNamePrefix="ec2_", MaxResults=100 ) if "QueueUrls" in response: for qurl in response["QueueUrls"]: print(f"Going to delete queue @ {qurl} ...") sqs.delete_queue( QueueUrl=qurl ) print("...Deleted.") if __name__ == "__main__": find_and_remove()
[ "richard.kendall@gmail.com" ]
richard.kendall@gmail.com
d4c82c623f809d07116f9bf570439012c953ffec
d83f053cd10603ef76566f0218b0f8b390d3faea
/extendedEuclideanAlgorithm.py
88567ff61b80b55fcb8a69437838016a66b27019
[]
no_license
derekwzheng/Cryptography
9017d5fb6ff53d340c8f2920a36a9e6081e7a61c
d1bcc1f68aaaef1ff64edddf21b02790dc879526
refs/heads/master
2021-01-22T18:23:10.898654
2014-05-23T07:58:12
2014-05-23T07:58:12
null
0
0
null
null
null
null
UTF-8
Python
false
false
772
py
# An implementation of Extended Euclidean algorithm in Python """ The function takes positive integers a and b, and return a triple (g, x, y) such that ax + by = g = gcd(a, b). An iterative implementation of Extended Euclidean Algorithm """ def rec_egcd(a, b): if a == 0: return (b, 0, 1) else: g, y, x = egcd(b % a, a) return (g, x - (b // a) * y, y) """ The function takes positive integers a and b, and return a triple (g, x, y) such that ax + by = g = gcd(a, b). An iterative implementation of Extended Euclidean Algorithm """ def iter_egcd(a, b): x,y, u,v = 0,1, 1,0 while a != 0: q, r = b//a, b%a m, n = x-u*q, y-v*q b,a, x,y, u,v = a,r, u,v, m,n gcd = b return gcd, x, y
[ "derekwzheng@gmail.com" ]
derekwzheng@gmail.com
8b1ee0cd24fa9f64ad3eaa20c5eb111638e2523a
c2c2ba546f478cbd3e8ce1ca39e7275b44ae3305
/my_demo.py
1fed968d13c1f71a26482c2a05caf3be88df6acc
[]
no_license
pinkequinox/tumor-faster
931469a88d7322b24f21d4399b25da48e097d674
0771c897cfa06018b0c3d96bfde62c43fe27118a
refs/heads/master
2021-01-23T15:28:01.908309
2017-10-24T09:15:54
2017-10-24T09:15:54
102,712,548
0
0
null
null
null
null
UTF-8
Python
false
false
1,762
py
import cv2 import numpy as np from faster_rcnn import network from faster_rcnn.faster_rcnn import FasterRCNN from faster_rcnn.utils.timer import Timer def test(): import os im_name = '1015172_1015172-3' im_file = '/home/xsn/py3_faster_rcnn_pytorch/data/VOCdevkit2007/VOC2007/JPEGImages/' + im_name + '.jpg' # im_file = 'data/VOCdevkit2007/VOC2007/JPEGImages/009036.jpg' # im_file = '/media/longc/Data/data/2DMOT2015/test/ETH-Crossing/img1/000100.jpg' image = cv2.imread(im_file) model_file = '/home/xsn/py3_faster_rcnn_pytorch/models/saved_model3/faster_rcnn_100000.h5' # model_file = '/media/longc/Data/models/faster_rcnn_pytorch3/faster_rcnn_100000.h5' # model_file = '/media/longc/Data/models/faster_rcnn_pytorch2/faster_rcnn_2000.h5' detector = FasterRCNN() network.load_net(model_file, detector) detector.cuda() detector.eval() print('load model successfully!') # network.save_net(r'/media/longc/Data/models/VGGnet_fast_rcnn_iter_70000.h5', detector) # print('save model succ') t = Timer() t.tic() # image = np.zeros(shape=[600, 800, 3], dtype=np.uint8) + 255 dets, scores, classes = detector.detect(image, 0.7) runtime = t.toc() print(('total spend: {}s'.format(runtime))) im2show = np.copy(image) for i, det in enumerate(dets): det = tuple(int(x) for x in det) cv2.rectangle(im2show, det[0:2], det[2:4], (255, 205, 51), 2) cv2.putText(im2show, '%s: %.3f' % (classes[i], scores[i]), (det[0], det[1] + 15), cv2.FONT_HERSHEY_PLAIN, 1.0, (0, 0, 255), thickness=1) cv2.imwrite(os.path.join('demo', 'out.jpg'), im2show) cv2.imshow('demo', im2show) cv2.waitKey(0) if __name__ == '__main__': test()
[ "equinox.xsn@gmail.com" ]
equinox.xsn@gmail.com
f09937e2a6f27c882a55d618d69bc747f10d2e4c
11bcf60200aaf63704191205d27b52442a08212b
/demo/test_brower.py
9deee2f98d69b84e498458899d9c8ffe08a66867
[]
no_license
Timothyea/uri_pycharm
bf893748cd32a045cbaec34dae3f8dfa3a2605ff
a1dbe860ba3bcce460da4dd87ec9aebc43cf3499
refs/heads/master
2020-09-09T08:47:31.943627
2019-11-14T10:04:07
2019-11-14T10:04:07
221,404,034
0
0
null
null
null
null
UTF-8
Python
false
false
452
py
#!/user/bin/env python # -*- conding:utf-8 -*- from time import sleep from selenium import webdriver # 打开游览器 def test_brower(driver): driver.get("http://www.baidu.com") sleep(1) driver.get("http://www.jd.com") sleep(1) driver.back() sleep(1) driver.forward() sleep(1) driver.refresh() sleep(1) # 关闭浏览器,不退出driver # driver.close() # 关闭浏览器,退出driver # driver.quit()
[ "you@example.com" ]
you@example.com
0fe7abaa38ffa1edfb5cd8a605cf326ea0d105ad
b07adcac0a50f9047c4e4148c8986122ff1bb871
/spellbook/feats/apps.py
2f715e9e306a8f72a5e9ae9efb316a356423b828
[]
no_license
CharlieBliss/spellbook
f60bd93ea42c3218d8ce020b7a8cca772688d491
49938e7ea74b0317f43ec2c45fa7dd53b71b111b
refs/heads/master
2020-04-20T22:36:01.882065
2019-02-07T17:23:10
2019-02-07T17:23:10
169,145,462
0
0
null
null
null
null
UTF-8
Python
false
false
85
py
from django.apps import AppConfig class FeatsConfig(AppConfig): name = 'feats'
[ "charles.m.bliss@gmail.com" ]
charles.m.bliss@gmail.com
36d30a7d9cbf16d1354ce5449ee5eb77ef434225
33a646a6e3591b28142f7424504b32525902e8ff
/tekeite/web.py
8653088a35f520a0a1965b789eec85995f3482e7
[]
no_license
dragon77777/ProjectDragon2017
eb0abd1acce51e90868da7f4e7fc9532dcee76b2
4e0139b571a6a75ce79b6bdf298064046d86625c
refs/heads/master
2021-01-22T02:34:26.885778
2017-02-06T06:40:27
2017-02-06T06:40:27
81,055,762
0
0
null
null
null
null
UTF-8
Python
false
false
1,483
py
#-*- coding:utf-8 -*- import BaseHTTPServer class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): # 页面模板 Page = '''\ <html> <body> <table> <tr> <td>Header</td> <td>Value</td> </tr> <tr> <td>Date and time</td> <td>{date_time}</td> </tr> <tr> <td>Client host</td> <td>{client_host}</td> </tr> <tr> <td>Client port</td> <td>{client_port}</td> </tr> <tr> <td>Command</td> <td>{command}</td> </tr> <tr> <td>Path</td> <td>{path}</td> </tr> </table> </body> </html> ''' def do_GET(self): page = self.create_page() self.send_content(page) def send_content(self, page): self.send_response(200) self.send_header("Content-type", "text/html") self.send_header("Content-Length", str(len(page))) self.end_headers() self.wfile.write(page) def create_page(self): values = { 'date_time': self.date_time_string(), 'client_host': self.client_address[0], 'client_port': self.client_address[1], 'command': self.command, 'path': self.path } page = self.Page.format(**values) return page if __name__ == '__main__': serverAddress = ('', 8080) server = BaseHTTPServer.HTTPServer(serverAddress, RequestHandler) server.serve_forever()
[ "714639106@qq.com" ]
714639106@qq.com
f56b35960f5577338750959c80f4b2e5b9334c3a
2b3c657e06b395107433b5994368a704fb77c863
/ChatApp/init_db.py
579445395902eb11424bc5d37e0831244eb1b3e5
[]
no_license
Jasminmo/chat
a9e96d5daaf50b8099dbbd925c512d1a8f2fe7da
5a5c7d712856aba75ad663dda565d4b098210da1
refs/heads/master
2023-06-06T04:33:29.169459
2021-06-27T19:27:55
2021-06-27T19:27:55
367,983,612
0
0
null
null
null
null
UTF-8
Python
false
false
2,436
py
import click from flask.cli import with_appcontext from .models import * from . import get_db db = get_db() def setup_defaults(): subjects = ['Cinema', 'Viral Stories', 'Memes', 'Hobbies'] topics = ['Something...', 'What about...', 'Popular'] admin = Users(username='admin', password=generate_password_hash('password'), is_admin=True) db.session.add(admin) customer = Users(username='customer', password=generate_password_hash('password')) db.session.add(customer) user1 = Users(username='user1', password=generate_password_hash('password')) db.session.add(user1) user2 = Users(username='user2', password=generate_password_hash('password')) db.session.add(user2) default_channel = Channels(title='Default', description="This is default channel.", creator=admin) db.session.add(default_channel) secret_channel = Channels(title='Secret', description="This is secret channel.", creator=admin, is_secret=True) secret_channel.secret_users.append(user1) secret_channel.secret_users.append(user2) db.session.add(default_channel) for i in range(4): new_channel = Channels(title=subjects[i], description='This is a discussion board for the subject ' + subjects[i], creator=admin) db.session.add(new_channel) for j in range(3): thread = Threads(title=topics[j], creator=admin, channel=new_channel) db.session.add(thread) message = Messages(content='First!', sender=customer, thread=thread) db.session.add(message) message = Messages(content='Second!', sender=customer, thread=thread, reply_to=message) db.session.add(message) message = Messages(content='Hi! How are you?', sender=admin, thread=thread) db.session.add(message) message = Messages(content='Hi! I\'m fine.', sender=customer, thread=thread, reply_to=message) db.session.add(message) db.session.commit() def init_db(): """Drop and create tables.""" #db.drop_all() db.create_all() setup_defaults() @click.command("init-db") @with_appcontext def init_db_command(): """Drop and create tables.""" init_db() click.echo("The database is now initialized.") def init_app(app): """Register database functions with the Flask app. This is called by the application factory. """ app.cli.add_command(init_db_command)
[ "jasmingiire1@gmail.com" ]
jasmingiire1@gmail.com
a50fb05db2a8a67f1728f348c2d2a9a59980bb05
516a19ca0d5185d2e69c7878dedec38b156ca598
/courseschedule.py
bae6fe48f69446616d965117e6bfa8749abc34c6
[]
no_license
zpyao1996/leetcode
d766d3dbaf41e4d36089499f0e616d0f5e84c0fc
fc5f0d70ca35789600a7e1d7ec356f648d09a7bf
refs/heads/master
2020-03-07T15:35:49.972257
2018-10-27T04:57:51
2018-10-27T04:57:51
127,559,216
0
0
null
null
null
null
UTF-8
Python
false
false
1,022
py
class Solution(object): def canFinish(self, numCourses, prerequisites): """ :type numCourses: int :type prerequisites: List[List[int]] :rtype: bool """ graph=[[] for _ in range(numCourses)] for x,y in prerequisites: graph[x].append(y) visit=[0 for _ in range(numCourses)] for i in range(numCourses): if self.dfs(i,graph,visit): return False return True def dfs(self,i,graph,visit): visit[i]=-1 astack=list() astack.append(i) while astack: a=astack.pop() for j in graph[a]: if visit[j]==-1: return True elif visit[j]==0: visit[j]=-1 astack.append(j) else: continue visit[a]=0 return False sol=Solution() print(sol.canFinish(3,[[1,2],[0,1],[0,2]]))
[ "zpyao1996@gmail.com" ]
zpyao1996@gmail.com
a0bf6e814b457e88e091de90c86fc61a779dc2b4
ff4ca069f16041fd49f7c87216b9fdb5c0a5f658
/UITest/Android/DxYcUiTest/Scripts/Clue/ClueCommentJumpTest.py
f6c06ce66942e809729d9f6555dc04e9073ee951
[]
no_license
ban666/UITestForDx
cbaf86cca957d40151ae28e2dc81a3016cf778d4
5a3ccdc68651e648e7c838fc58b5a9d052a19f6b
refs/heads/master
2021-01-12T01:36:06.206477
2017-02-17T09:09:27
2017-02-17T09:09:36
78,408,551
0
0
null
null
null
null
UTF-8
Python
false
false
4,137
py
# -*- coding: utf-8 -*- __author__ = 'liaoben' import sys from appium import webdriver from time import sleep import unittest from random import randint sys.path.append('../../Lib') import time import os from appium_lib import * from dx_action import * from ui_comment import * from ChnlRequest import ChnlRequest from DbLib import DbLib from config import * from loglib import log from elements_id import * from configrw import get_case from TestlinkHandler import TestlinkHandler from ui_clue import * from BaoliaoRequest import BaoliaoRequest class SubTypeTest(unittest.TestCase): def setUp(self): #self.testcases = conf.readcfg(__file__) self.desired_caps = desired_caps print 'Test Start...................................' self.result = 'f' self.msg = '' self.tsl = TestlinkHandler() self.mode = MODE self.db = DbLib() self.clue = BaoliaoRequest() subtype_id = self.clue.get_clue_type()[0]['subtype'] self.clue.send_clue_and_review(u'报料测试'+str(randint(1,100)),1,subtype_id) self.api = ChnlRequest(MODE) self.driver = webdriver.Remote(APPIUM_URL, self.desired_caps) start_to_index(self.driver,self.mode) def tearDown(self): print 'Test End...................................' try: self.tsl.set_tc_status(self.case_id,self.result,self.msg) self.driver.quit() except Exception as e: print u'测试失败,失败环节:tear down',e def common_check(self): step = 1 sleep(WAIT_TIME) go_to_clue(self.driver) #subtype_id = self.clue.get_clue_type()[0]['subtype'] #获取第一个栏目的报料类型ID # current_time = time.strftime( ISOTIMEFORMAT, time.localtime() ) # clue_content = 'test for comment button '+str(current_time) # self.clue.send_clue(clue_content,subtype_id) #使用接口发送报料 # clue_id = self.db.get_clueid_with_content_by_db(clue_content) comment_count = get_clue_comment_count(self.driver) assert int(comment_count) == 0 #点击切换 self.driver.find_element_by_id(CLUE_LIST_COMMENT_BUTTON).click() assert self.driver.current_activity == ACTIVITY.get('clue') assert element_exsist(self.driver,'id',CLUE_LIST_DESC) print u'Step %s:报料无评论时,点击列表中评论按钮进入报料正文页:OK' % (str(step)) step+=1 return True def comment_jump_check(self): step = 1 sleep(WAIT_TIME) subtype_id = self.clue.get_clue_type()[0]['subtype'] clue_id = self.clue.get_clue_list(subtype_id)[0]['cid'] for i in range(50): self.api.send_comment(clue_id,'test for comment anchor') go_to_clue(self.driver) slide_down(self.driver) comment_count = get_clue_comment_count(self.driver) assert int(comment_count) != 0 #点击切换 self.driver.find_element_by_id(CLUE_LIST_COMMENT_BUTTON).click() assert self.driver.current_activity == ACTIVITY.get('clue') assert element_exsist(self.driver,'id',CLUE_LIST_DESC) == False print u'Step %s:报料有评论时,点击列表中报料的评论按钮,跳转到评论锚点:OK' % (str(step)) step+=1 return True #excute TestCase def test(self): self.case_id = get_case(__file__) self.result = self.common_check() def testCommentJump(self): self.case_id = get_case(__file__) self.result = self.comment_jump_check() if __name__ == '__main__': pass # a = TestLogin() # a.setUp() # a.testFunc1() # a.tearDown() #d =DbLib() import HTMLTestRunner t = unittest.TestSuite() t.addTest(unittest.makeSuite(TestComment)) #unittest.TextTestRunner.run(t) filename = 'F:\\dx_comment.html' fp = file(filename,'wb') runner = HTMLTestRunner.HTMLTestRunner( stream = fp, title ='Dx_Test', description = 'Report_discription') runner.run(t) fp.close()
[ "ban666@qq.com" ]
ban666@qq.com
d7e4dab46833f8593c369c91de80e49a98a0619e
806aee515816ea8f526275e4e4af831f38787e69
/App/urls.py
c58ba95c01112997a6c12858dc4c5e70dac788b8
[]
no_license
Easonchar/Code
baaab2877243f87231b01dc339d0abd342a46470
8ce35aa5d0966f71467e2507e862fef1aed34bf5
refs/heads/master
2020-03-31T20:35:48.504803
2018-10-29T12:39:44
2018-10-29T12:39:44
152,546,810
0
0
null
null
null
null
UTF-8
Python
false
false
433
py
from django.conf.urls import url from App import views urlpatterns = [ url(r'^$',views.index,name='index'), # url(r'^index/$',views.index,name='index'), url(r'^detail(\d+)/$',views.detail,name='detail'), url(r'^list/$',views.list,name='list'), url(r'^login/$',views.login,name='login'), url(r'^register/$',views.register,name='register'), url(r'^shoppingCar/$',views.shoppingCar,name='shoppingCar'), ]
[ "1009560311@qq.com" ]
1009560311@qq.com
faa28a123bda6210385e481d7591818ffde29967
9f837a9d5fe59c05e90f6b283f23555d5298af8a
/Infomath_root/asgi.py
e1baf48d309d897e68b21bf76e32c924028a267a
[]
no_license
alcibiadesBustillo/Infomath
8ef929b8d900e344c399e9bf9d64fd81bff19e9d
99525dd59e7a3fea0a8a2325cfe0afce296b1852
refs/heads/main
2023-04-20T11:20:53.007012
2021-05-13T07:22:24
2021-05-13T07:22:24
366,967,076
0
0
null
null
null
null
UTF-8
Python
false
false
403
py
""" ASGI config for Infomath_root project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Infomath_root.settings') application = get_asgi_application()
[ "bustillo.alcibiades@gmail.com" ]
bustillo.alcibiades@gmail.com
677a627128ff0a1f1a70ef8820e3a44a8fcb4eb8
0c8e4931426819fbd631fccca93b0159c55c8b9d
/backend/manage.py
e3f233fb08b1de2ea65130d9fba875f0ab26ace7
[ "Apache-2.0" ]
permissive
franklingu/dota2_explorer
c750d144e19239b1aa0d8ad8c47e781312fcfc05
d5c0cd03b77bb4158084f4f81cfc8073977e13a8
refs/heads/master
2020-03-22T09:08:40.338681
2018-07-12T03:53:34
2018-07-12T03:53:34
139,818,331
1
0
null
null
null
null
UTF-8
Python
false
false
541
py
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dota2site.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv)
[ "franklingujunchao@gmail.com" ]
franklingujunchao@gmail.com
4706209a5fe6f3772ac5918d1a4929cfcd459288
a7ee97c81deac19d94228920f9661cab91e527b9
/python/LeetCodeEasy/searchBST.py
f51f9786cc3bbfd513aefe1e9601fc95f8fde026
[]
no_license
Vinicoreia/AlgoRythm
70af63202798b3e4baf95521a35755a8cad81ba1
af225fb159dca551b190d6a3ec636a00f2fedc52
refs/heads/master
2020-04-22T08:08:13.893998
2019-07-26T09:32:11
2019-07-26T09:32:11
170,234,657
0
0
null
null
null
null
UTF-8
Python
false
false
293
py
class Solution: def searchBST(self, root, val): if not root: return None elif(root.val = val): return root elif(root.val>val): return self.searchBST(root.left, val) else: return self.searchBST(root.right, val)
[ "viniciusfilgf@gmail.com" ]
viniciusfilgf@gmail.com
dd83510832592a5ebeb15a94b4406cbaa3c70847
c047606b37bb1e98e0ee5ca4720cfa0b34369403
/ensemble/check_distillation.py
e77e7c2350ba132e26c28f67f1c16017472d3c61
[ "Apache-2.0" ]
permissive
shengchen-liu/yt8m
64d85431896f36b337198ec0dd93235f8b1bbece
286d7e12c58930ab9a2018ec72cf30a6cacaed75
refs/heads/master
2020-03-22T10:04:12.640307
2019-01-24T01:09:19
2019-01-24T01:09:19
139,878,882
2
0
null
null
null
null
UTF-8
Python
false
false
8,014
py
# Copyright 2016 Google Inc. 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. """Binary for evaluating Tensorflow models on the YouTube-8M dataset.""" import time import numpy as np import eval_util import losses import ensemble_level_models import readers import tensorflow as tf from tensorflow import app from tensorflow import flags from tensorflow import gfile from tensorflow import logging import utils FLAGS = flags.FLAGS if __name__ == "__main__": # Dataset flags. flags.DEFINE_string( "eval_data_patterns", "", "File globs defining the evaluation dataset in tensorflow.SequenceExample format.") flags.DEFINE_string( "input_data_pattern", None, "File globs for original model input.") flags.DEFINE_string("feature_names", "predictions", "Name of the feature " "to use for training.") flags.DEFINE_string("feature_sizes", "4716", "Length of the feature vectors.") # Model flags. flags.DEFINE_integer("batch_size", 1024, "How many examples to process per batch.") def find_class_by_name(name, modules): """Searches the provided modules for the named class and returns it.""" modules = [getattr(module, name, None) for module in modules] return next(a for a in modules if a) def get_input_evaluation_tensors(reader, data_pattern, batch_size=256): logging.info("Using batch size of " + str(batch_size) + " for evaluation.") with tf.name_scope("eval_input"): files = gfile.Glob(data_pattern) if not files: print data_pattern, files raise IOError("Unable to find the evaluation files.") logging.info("number of evaluation files: " + str(len(files))) files.sort() filename_queue = tf.train.string_input_producer( files, shuffle=False, num_epochs=1) eval_data = reader.prepare_reader(filename_queue) return tf.train.batch( eval_data, batch_size=batch_size, capacity=3 * batch_size, allow_smaller_final_batch=True, enqueue_many=True) def build_graph(all_readers, input_reader, input_data_pattern, all_eval_data_patterns, batch_size=256): original_video_id, original_input, unused_labels_batch, unused_num_frames = ( get_input_evaluation_tensors( input_reader, input_data_pattern, batch_size=batch_size)) video_id_equal_tensors = [] model_input_tensor = None input_distance_tensors = [] model_label_tensor = tf.cast(unused_labels_batch, dtype=tf.float32) label_distance_tensors = [] for reader, data_pattern in zip(all_readers, all_eval_data_patterns): video_id, model_input_raw, labels_batch, unused_num_frames = ( get_input_evaluation_tensors( reader, data_pattern, batch_size=batch_size)) video_id_equal_tensors.append(tf.reduce_sum(tf.cast(tf.not_equal(original_video_id, video_id), dtype=tf.float32))) input_distance_tensors.append(tf.reduce_mean(tf.reduce_sum(tf.square(original_input - model_input_raw), axis=1))) labels_batch = tf.cast(labels_batch, dtype=tf.float32) x = model_input_raw y = labels_batch ce = - y * tf.log(x + 1e-7) - (1.0 - y) * tf.log(1.0 + 1e-7 - x) label_distance_tensors.append(tf.reduce_mean(tf.reduce_sum(ce, axis=1))) video_id_equal_tensor = tf.stack(video_id_equal_tensors) input_distance_tensor = tf.stack(input_distance_tensors) label_distance_tensor = tf.stack(label_distance_tensors) tf.add_to_collection("model_input", model_input_tensor) tf.add_to_collection("video_id_equal", video_id_equal_tensor) tf.add_to_collection("input_distance", input_distance_tensor) tf.add_to_collection("label_distance", label_distance_tensor) def check_loop(model_input, video_id_equal, input_distance, label_distance, all_patterns): with tf.Session() as sess: sess.run([tf.local_variables_initializer()]) # Start the queue runners. coord = tf.train.Coordinator() try: threads = [] for qr in tf.get_collection(tf.GraphKeys.QUEUE_RUNNERS): threads.extend(qr.create_threads( sess, coord=coord, daemon=True, start=True)) examples_processed = 0 while not coord.should_stop(): batch_start_time = time.time() model_input_val, video_id_equal_val, input_distance_val, label_distance_val = sess.run([model_input, video_id_equal, input_distance, label_distance]) print "model_input.max", np.max(model_input_val) print "model_input.min", np.min(model_input_val) print "input_distance_val", input_distance_val print "label_distance_val", label_distance_val for i in xrange(video_id_equal_val.shape[0]): if video_id_equal_val[i] > 0: print "%d discrepancies in %s" % (int(video_id_equal_val[i]), all_patterns[i]) seconds_per_batch = time.time() - batch_start_time example_per_second = video_id_equal_val.shape[0] / seconds_per_batch examples_processed += video_id_equal_val.shape[0] logging.info("examples_processed: %d", examples_processed) except tf.errors.OutOfRangeError as e: logging.info( "Done with batched inference. Now calculating global performance " "metrics.") except Exception as e: # pylint: disable=broad-except logging.info("Unexpected exception: " + str(e)) coord.request_stop(e) coord.request_stop() coord.join(threads, stop_grace_period_secs=10) return global_step_val def check_video_id(): tf.set_random_seed(0) # for reproducibility with tf.Graph().as_default(): # convert feature_names and feature_sizes to lists of values feature_names, feature_sizes = utils.GetListOfFeatureNamesAndSizes( FLAGS.feature_names, FLAGS.feature_sizes) # prepare a reader for each single model prediction result all_readers = [] all_patterns = FLAGS.eval_data_patterns all_patterns = map(lambda x: x.strip(), all_patterns.strip().strip(",").split(",")) for i in xrange(len(all_patterns)): reader = readers.EnsembleReader( feature_names=feature_names, feature_sizes=feature_sizes) all_readers.append(reader) input_reader = None input_data_pattern = None if FLAGS.input_data_pattern is not None: input_reader = readers.EnsembleReader( feature_names=["mean_rgb","mean_audio"], feature_sizes=[1024,128]) input_data_pattern = FLAGS.input_data_pattern if FLAGS.eval_data_patterns is "": raise IOError("'eval_data_patterns' was not specified. " + "Nothing to evaluate.") build_graph( all_readers=all_readers, input_reader=input_reader, input_data_pattern=input_data_pattern, all_eval_data_patterns=all_patterns, batch_size=FLAGS.batch_size) logging.info("built evaluation graph") video_id_equal = tf.get_collection("video_id_equal")[0] model_input = tf.get_collection("model_input")[0] input_distance = tf.get_collection("input_distance")[0] label_distance = tf.get_collection("label_distance")[0] check_loop(model_input, video_id_equal, input_distance, label_distance, all_patterns) def main(unused_argv): logging.set_verbosity(tf.logging.INFO) print("tensorflow version: %s" % tf.__version__) check_video_id() if __name__ == "__main__": app.run()
[ "lawson901225@gmail.com" ]
lawson901225@gmail.com
88c21be4f213d6242825a9b5c5a762d9a07d7b2d
599caedb27dbd4573a8f717f23cd652b30aa6574
/source/events.py
8fb3941d40fb3ad65d12e74117d461f30dcb15a9
[]
no_license
Kaedenn/Kaye
d3b752409fccad96fd8c45ed105a4692d2d81a66
d57a195088b2108be24c7a97cab9dc9b7c5d87b9
refs/heads/master
2020-05-18T05:12:31.502003
2016-02-14T01:04:38
2016-02-14T01:04:38
31,037,482
0
0
null
null
null
null
UTF-8
Python
false
false
122
py
#!/usr/bin/env python class KyeKilledEvent(Exception): def __init__(self): super(KyeKilledEvent, self).__init__()
[ "kaedenn@gmail.com" ]
kaedenn@gmail.com
838b11c3e333becb37fd59b7a1c8ec5b7c84a86c
48a6a8041ab0b97d182be35d7a49c5081c6b6868
/lesson_4/HW_4_UltraPro_account.py
1d9ec40d4f186895e51c70d10ab858e66c535b06
[ "MIT" ]
permissive
ikonushok/My_studying_Python_developer
204d29ee941701e947ab1473e1cb6e29200867a4
1d4d2a40ed15ce2676147fb0e967c6fcd08dd513
refs/heads/main
2023-02-28T20:40:03.890723
2021-01-29T05:24:09
2021-01-29T05:24:09
315,576,379
0
0
MIT
2021-01-21T14:02:48
2020-11-24T09:08:22
Python
UTF-8
Python
false
false
1,932
py
# Menu def menu(num): """ :param num: :return: """ print(f'Доступная сумма: {num} руб.', end='\n\n') print('1. Пополнить счет') print('2. Совершить покупку') print('3. История покупок') print('4. Выход') ans = input('Введите номер пункта: ') return ans # Покупка def add(num, hist): """ :param num: :param hist: :return: """ sale = input('Введите сумму покупки: ') while not sale.replace('.', '', 1).isdigit(): sale = input('Введите сумму покупки: ') sale = float(sale) if sale > num: print('Сумма покупки больше наличных денег') else: name = input('Введите название покупки: ') hist.append((name, sale)) num -= sale return num, hist # Перебор условий # выбрать пункт меню # пополнить счет # проверив наличие денег, добавить расход # вывести историю операций # прерывание num = 0 history = [] while True: # меню ans = menu(num) while ans not in ['1', '2', '3', '4']: ans = menu(num) # пополнение счета if ans == '1': amount = input('Введите сумму: ') while not amount.replace('.', '', 1).isdigit(): amount = input('Введите сумму: ') num += float(amount) # покупки elif ans == '2': num, history = add(num, history) # выводим испорию покупок elif ans == '3': for name, sale in history: print(f'Было куплено {name} за {sale} руб.') else: # иначе break # выйти из основного цикла
[ "ikonushok@gmail.com" ]
ikonushok@gmail.com
82505bfe5b19290835228b477cd4b7acea97dcd6
c5046ff113dce225974a86601b7195d2ef7950a1
/FourthGen/Bprime_B2G/step1/BprimeBprimeToBHBZinc/BprimeBprimeToBHBZinc_M_500_TuneZ2star_8TeV_madgraph_cff_py_GEN_SIM_time.py
62ec3d2ee81342d9b12d94ea89acc984bf12f607
[]
no_license
dmajumder/cms-UserCode
b8c340f889a119f33be0b169c61308536a0fae78
f519a221dc0d4e8634f7eab7a1a8c802a2708210
refs/heads/master
2020-03-26T10:16:49.305776
2013-08-15T03:21:17
2013-08-15T03:21:17
13,921,973
0
0
null
null
null
null
UTF-8
Python
false
false
9,765
py
# Auto generated configuration file # using: # Revision: 1.372.2.3 # Source: /local/reps/CMSSW.admin/CMSSW/Configuration/PyReleaseValidation/python/ConfigBuilder.py,v # with command line options: Configuration/GenProduction/python/EightTeV/Bprime_B2G/BprimeBprimeToBHBZinc_M_500_TuneZ2star_8TeV_madgraph_cff.py -s GEN,SIM --filetype=LHE --filein=6147 --beamspot Realistic8TeVCollision --conditions START52_V9::All --pileup NoPileUp --datatier GEN-SIM --eventcontent RAWSIM -n 30 --no_exe import FWCore.ParameterSet.Config as cms process = cms.Process('SIM') # import of standard configurations process.load('Configuration.StandardSequences.Services_cff') process.load('SimGeneral.HepPDTESSource.pythiapdt_cfi') process.load('FWCore.MessageService.MessageLogger_cfi') process.load('Configuration.EventContent.EventContent_cff') process.load('SimGeneral.MixingModule.mixNoPU_cfi') process.load('Configuration.StandardSequences.GeometryDB_cff') process.load('Configuration.StandardSequences.MagneticField_38T_cff') process.load('Configuration.StandardSequences.Generator_cff') process.load('IOMC.EventVertexGenerators.VtxSmearedRealistic8TeVCollision_cfi') process.load('GeneratorInterface.Core.genFilterSummary_cff') process.load('Configuration.StandardSequences.SimIdeal_cff') process.load('Configuration.StandardSequences.EndOfProcess_cff') process.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff') process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(30) ) # Input source process.source = cms.Source("LHESource", fileNames = cms.untracked.vstring('6147') ) process.options = cms.untracked.PSet( ) # Production Info process.configurationMetadata = cms.untracked.PSet( version = cms.untracked.string('$Revision: 1.372.2.3 $'), annotation = cms.untracked.string('Configuration/GenProduction/python/EightTeV/Bprime_B2G/BprimeBprimeToBHBZinc_M_500_TuneZ2star_8TeV_madgraph_cff.py nevts:30'), name = cms.untracked.string('PyReleaseValidation') ) # Output definition process.RAWSIMoutput = cms.OutputModule("PoolOutputModule", splitLevel = cms.untracked.int32(0), eventAutoFlushCompressedSize = cms.untracked.int32(5242880), outputCommands = process.RAWSIMEventContent.outputCommands, fileName = cms.untracked.string('BprimeBprimeToBHBZinc_M_500_TuneZ2star_8TeV_madgraph_cff_py_GEN_SIM.root'), dataset = cms.untracked.PSet( filterName = cms.untracked.string(''), dataTier = cms.untracked.string('GEN-SIM') ), SelectEvents = cms.untracked.PSet( SelectEvents = cms.vstring('generation_step') ) ) # Additional output definition # Other statements process.GlobalTag.globaltag = 'START52_V9::All' process.generator = cms.EDFilter("Pythia6HadronizerFilter", jetMatching = cms.untracked.PSet( MEMAIN_showerkt = cms.double(0), MEMAIN_nqmatch = cms.int32(-1), MEMAIN_minjets = cms.int32(-1), MEMAIN_qcut = cms.double(-1), MEMAIN_excres = cms.string(''), MEMAIN_etaclmax = cms.double(5.0), outTree_flag = cms.int32(0), scheme = cms.string('Madgraph'), MEMAIN_maxjets = cms.int32(-1), mode = cms.string('auto') ), pythiaPylistVerbosity = cms.untracked.int32(0), pythiaHepMCVerbosity = cms.untracked.bool(False), comEnergy = cms.double(8000.0), maxEventsToPrint = cms.untracked.int32(0), PythiaParameters = cms.PSet( pythiaUESettings = cms.vstring('MSTU(21)=1 ! Check on possible errors during program execution', 'MSTJ(22)=2 ! Decay those unstable particles', 'PARJ(71)=10 . ! for which ctau 10 mm', 'MSTP(33)=0 ! no K factors in hard cross sections', 'MSTP(2)=1 ! which order running alphaS', 'MSTP(51)=10042 ! structure function chosen (external PDF CTEQ6L1)', 'MSTP(52)=2 ! work with LHAPDF', 'PARP(82)=1.921 ! pt cutoff for multiparton interactions', 'PARP(89)=1800. ! sqrts for which PARP82 is set', 'PARP(90)=0.227 ! Multiple interactions: rescaling power', 'MSTP(95)=6 ! CR (color reconnection parameters)', 'PARP(77)=1.016 ! CR', 'PARP(78)=0.538 ! CR', 'PARP(80)=0.1 ! Prob. colored parton from BBR', 'PARP(83)=0.356 ! Multiple interactions: matter distribution parameter', 'PARP(84)=0.651 ! Multiple interactions: matter distribution parameter', 'PARP(62)=1.025 ! ISR cutoff', 'MSTP(91)=1 ! Gaussian primordial kT', 'PARP(93)=10.0 ! primordial kT-max', 'MSTP(81)=21 ! multiple parton interactions 1 is Pythia default', 'MSTP(82)=4 ! Defines the multi-parton model'), processParameters = cms.vstring('PMAS(25,1)=125.00D0 !mass of Higgs', 'MSTP(1) = 4', 'MSEL=7 ! User defined processes', 'MWID(7)=2', 'MSTJ(1)=1 ! Fragmentation/hadronization on or off', 'MSTP(61)=1 ! Parton showering on or off', 'PMAS(5,1)=4.8 ! b quark mass', 'PMAS(6,1)=172.5 ! t quark mass', 'PMAS(7,1) = 500.0D0 ! bprime quarks mass', 'PMAS(7,2) = 5.000D0 ! bprime quark width', 'PMAS(7,3) = 50.00D0 ! Max value above which the BW shape is truncated', 'VCKM(1,1) = 0.97414000D0', 'VCKM(1,2) = 0.22450000D0', 'VCKM(1,3) = 0.00420000D0', 'VCKM(1,4) = 0.02500000D0', 'VCKM(2,1) = 0.22560000D0', 'VCKM(2,2) = 0.97170000D0', 'VCKM(2,3) = 0.04109000D0', 'VCKM(2,4) = 0.05700000D0', 'VCKM(3,1) = 0.00100000D0', 'VCKM(3,2) = 0.06200000D0', 'VCKM(3,3) = 0.91000000D0', 'VCKM(3,4) = 0.41000000D0', 'VCKM(4,1) = 0.01300000D0', 'VCKM(4,2) = 0.04000000D0', 'VCKM(4,3) = 0.41000000D0', 'VCKM(4,4) = 0.91000000D0', 'MDME(56,1)=0 ! g b4', 'MDME(57,1)=0 ! gamma b4', 'KFDP(58,2)=5 ! defines Z0 b', 'MDME(58,1)=1 ! Z0 b', 'MDME(59,1)=0 ! W u', 'MDME(60,1)=0 ! W c', 'MDME(61,1)=0 ! W t', 'MDME(62,1)=0 ! W t4', 'KFDP(63,2)=5 ! defines H0 b', 'MDME(63,1)=1 ! h0 b4', 'MDME(64,1)=-1 ! H- c', 'MDME(65,1)=-1 ! H- t', 'BRAT(56) = 0.0D0', 'BRAT(57) = 0.0D0', 'BRAT(58) = 0.5D0', 'BRAT(59) = 0.0D0', 'BRAT(60) = 0.0D0', 'BRAT(61) = 0.0D0', 'BRAT(62) = 0.0D0', 'BRAT(63) = 0.5D0', 'BRAT(64) = 0.0D0', 'BRAT(65) = 0.0D0', 'MDME(210,1)=1 !Higgs decay into dd', 'MDME(211,1)=1 !Higgs decay into uu', 'MDME(212,1)=1 !Higgs decay into ss', 'MDME(213,1)=1 !Higgs decay into cc', 'MDME(214,1)=1 !Higgs decay into bb', 'MDME(215,1)=1 !Higgs decay into tt', 'MDME(216,1)=1 !Higgs decay into', 'MDME(217,1)=1 !Higgs decay into Higgs decay', 'MDME(218,1)=1 !Higgs decay into e nu e', 'MDME(219,1)=1 !Higgs decay into mu nu mu', 'MDME(220,1)=1 !Higgs decay into tau nu tau', 'MDME(221,1)=1 !Higgs decay into Higgs decay', 'MDME(222,1)=1 !Higgs decay into g g', 'MDME(223,1)=1 !Higgs decay into gam gam', 'MDME(224,1)=1 !Higgs decay into gam Z', 'MDME(225,1)=1 !Higgs decay into Z Z', 'MDME(226,1)=1 !Higgs decay into W W', 'MDME(174,1)=1 !Z decay into d dbar', 'MDME(175,1)=1 !Z decay into u ubar', 'MDME(176,1)=1 !Z decay into s sbar', 'MDME(177,1)=1 !Z decay into c cbar', 'MDME(178,1)=1 !Z decay into b bbar', 'MDME(179,1)=1 !Z decay into t tbar', 'MDME(180,1)=-1 !Z decay into b4 b4bar', 'MDME(181,1)=-1 !Z decay into t4 t4bar', 'MDME(182,1)=1 !Z decay into e- e+', 'MDME(183,1)=1 !Z decay into nu_e nu_ebar', 'MDME(184,1)=1 !Z decay into mu- mu+', 'MDME(185,1)=1 !Z decay into nu_mu nu_mubar', 'MDME(186,1)=1 !Z decay into tau- tau+', 'MDME(187,1)=1 !Z decay into nu_tau nu_taubar', 'MDME(188,1)=-1 !Z decay into tau4 tau4bar', 'MDME(189,1)=-1 !Z decay into nu_tau4 nu_tau4bar'), parameterSets = cms.vstring('pythiaUESettings', 'processParameters') ) ) process.ProductionFilterSequence = cms.Sequence(process.generator) # Path and EndPath definitions process.generation_step = cms.Path(process.pgen) process.simulation_step = cms.Path(process.psim) process.genfiltersummary_step = cms.EndPath(process.genFilterSummary) process.endjob_step = cms.EndPath(process.endOfProcess) process.RAWSIMoutput_step = cms.EndPath(process.RAWSIMoutput) # Schedule definition process.schedule = cms.Schedule(process.generation_step,process.genfiltersummary_step,process.simulation_step,process.endjob_step,process.RAWSIMoutput_step) # filter all path with the production filter sequence for path in process.paths: getattr(process,path)._seq = process.ProductionFilterSequence * getattr(process,path)._seq process.Timing=cms.Service("Timing", summaryOnly=cms.untracked.bool(True))
[ "" ]
3660e339d9fac7eea9aaeaef28f1b6a38d5383ab
c8690c73bfda247b26da0548d6cf6bfe03fc15eb
/P1_chat_server/src/protocol.py
f2f25c2d955ec67a42af6b31b7d7cc304c0298ab
[]
no_license
joaoreis16/CD_projects
1fb6b600b6592aa20a38a6c3c9b65c06a6f2ac47
fda543588fddffa4d85e9761fae234471402cf4c
refs/heads/main
2023-06-16T14:21:15.606819
2021-07-17T14:05:33
2021-07-17T14:05:33
386,951,621
0
0
null
null
null
null
UTF-8
Python
false
false
4,130
py
"""Protocol for chat server - Computação Distribuida Assignment 1.""" import json from datetime import datetime from socket import socket class Message: """Message Type.""" def __init__(self, command): self.command = command def __repr__(self): return f'"command": "{self.command}"' class JoinMessage(Message): """Message to join a chat channel.""" def __init__(self, command, channel): super().__init__(command) self.channel = channel pass def __repr__(self): return f'{{{super().__repr__()}, "channel": "{self.channel}"}}' class RegisterMessage(Message): """Message to register username in the server.""" def __init__(self, command, user): super().__init__(command) self.user = user def __repr__(self): return f'{{{super().__repr__()}, "user": "{self.user}"}}' class TextMessage(Message): """Message to chat with other clients.""" def __init__(self, command, message, ts, channel = None): super().__init__(command) self.message = message self.channel = channel self.ts = ts def __repr__(self): if self.channel: return f'{{{super().__repr__()}, "message": "{self.message}", "channel": "{self.channel}", "ts": {self.ts}}}' else: return f'{{{super().__repr__()}, "message": "{self.message}", "ts": {self.ts}}}' class CDProto: """Computação Distribuida Protocol.""" @classmethod def register(cls, username: str) -> RegisterMessage: """Creates a RegisterMessage object.""" return RegisterMessage("register", username) @classmethod def join(cls, channel: str) -> JoinMessage: """Creates a JoinMessage object.""" return JoinMessage("join", channel) @classmethod def message(cls, message: str, channel: str = None) -> TextMessage: """Creates a TextMessage object.""" return TextMessage("message", message, int(datetime.now().timestamp()), channel) @classmethod def send_msg(cls, connection: socket, msg: Message): """Sends through a connection a Message object.""" if type(msg) is RegisterMessage: json_msg = json.dumps({"command": "register", "user": msg.user}).encode("UTF-8") elif type(msg) is JoinMessage: json_msg = json.dumps({"command": "join", "channel": msg.channel}).encode("UTF-8") elif type(msg) is TextMessage: json_msg = json.dumps({"command": "message", "message": msg.message, "channel": msg.channel, "ts": int(datetime.now().timestamp()) }).encode("UTF-8") header = len(json_msg).to_bytes(2, "big") connection.sendall(header + json_msg) @classmethod def recv_msg(cls, connection: socket) -> Message: """Receives through a connection a Message object.""" try: header = int.from_bytes(connection.recv(2), "big") if header == 0: return dic_msg = connection.recv(header).decode("UTF-8") dic = json.loads(dic_msg) except json.JSONDecodeError as err: raise CDProtoBadFormat(dic_msg) if dic["command"] == "register": user = dic["user"] return CDProto.register(user) elif dic["command"] == "join": channel = dic["channel"] return CDProto.join(channel) elif dic["command"] == "message": msg = dic["message"] if dic.get("channel"): # caso haja canal ou não return CDProto.message(msg, dic["channel"]) else: return CDProto.message(msg) class CDProtoBadFormat(Exception): """Exception when source message is not CDProto.""" def __init__(self, original_msg: bytes=None) : """Store original message that triggered exception.""" self._original = original_msg @property def original_msg(self) -> str: """Retrieve original message as a string.""" return self._original.decode("utf-8")
[ "joaoreis16@ua.pt" ]
joaoreis16@ua.pt
aca85ae0f0ade02fa6312a6c4f8e8e7885adb341
2a9b3bf8758c1199305a01c524be78b7287335b8
/plugins/ga/bidsaspx/riverdale.py
2693f804d7cf9e493c147f0583e28a7f4e6ca6c5
[]
no_license
thayton/bidmap
e222f34701c15d4694f1f51999ecc9d894abfe41
de279cd64f66c79b253b38101c8ccdf748e540ac
refs/heads/master
2021-01-21T17:03:14.317309
2014-09-26T18:27:45
2014-09-26T18:27:45
17,402,509
0
0
null
null
null
null
UTF-8
Python
false
false
429
py
from bidmap.bidscrapers.bidsaspx.bidsaspx import BidsAspxBidScraper GOVINFO = { 'name': 'Riverdale Georgia', 'location': 'Riverdale, GA', 'home_page_url': 'http://ga-riverdale2.civicplus.com', 'bids_page_url': 'http://ga-riverdale2.civicplus.com/bids.aspx' } def get_scraper(): return BidsAspxBidScraper(GOVINFO) if __name__ == '__main__': bid_scraper = get_scraper() bid_scraper.scrape_bids()
[ "thayton@neekanee.com" ]
thayton@neekanee.com
45d4417c4b16c0c3cdeb03b67ce5ba64431f3167
308270f357a35dd4fd45679d0938e49d225fb299
/SeaFence_Lars_Timo/antlr_files_2/QLParser.py
d61cd84834f956875355f4b6dc5e5324c6ce5807
[]
no_license
njtromp/endless-ql
47f0c98e802b398b0d220de9018c8df11a7c7f6f
7ad1cd65b52488044f9cbfb64c9b494b899df3a7
refs/heads/master
2021-04-06T01:36:31.836117
2018-03-11T17:01:25
2018-03-11T17:01:25
124,737,498
0
0
null
2018-03-11T08:31:05
2018-03-11T08:31:05
null
UTF-8
Python
false
false
32,452
py
# Generated from QL.g4 by ANTLR 4.7 # encoding: utf-8 from __future__ import print_function from antlr4 import * from io import StringIO import sys def serializedATN(): with StringIO() as buf: buf.write(u"\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\3") buf.write(u"!|\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\4") buf.write(u"\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\4\r\t\r\4\16") buf.write(u"\t\16\3\2\3\2\3\2\3\2\3\2\3\3\3\3\7\3$\n\3\f\3\16\3\'") buf.write(u"\13\3\3\3\3\3\3\4\3\4\3\4\5\4.\n\4\3\5\3\5\3\5\3\5\3") buf.write(u"\5\3\5\3\5\3\6\3\6\3\6\3\6\3\6\3\7\3\7\7\7>\n\7\f\7\16") buf.write(u"\7A\13\7\3\7\5\7D\n\7\3\b\3\b\3\b\3\b\3\b\3\b\3\b\3\b") buf.write(u"\3\b\3\b\3\b\5\bQ\n\b\3\b\3\b\3\b\3\b\3\b\3\b\3\b\3\b") buf.write(u"\3\b\3\b\3\b\3\b\3\b\3\b\3\b\7\bb\n\b\f\b\16\be\13\b") buf.write(u"\3\t\3\t\3\n\3\n\3\13\3\13\3\f\3\f\3\f\3\f\3\f\3\f\3") buf.write(u"\r\3\r\3\r\3\r\3\r\3\r\3\16\3\16\3\16\3\16\2\3\16\17") buf.write(u"\2\4\6\b\n\f\16\20\22\24\26\30\32\2\3\3\2\n\13\2}\2\34") buf.write(u"\3\2\2\2\4!\3\2\2\2\6-\3\2\2\2\b/\3\2\2\2\n\66\3\2\2") buf.write(u"\2\f;\3\2\2\2\16P\3\2\2\2\20f\3\2\2\2\22h\3\2\2\2\24") buf.write(u"j\3\2\2\2\26l\3\2\2\2\30r\3\2\2\2\32x\3\2\2\2\34\35\7") buf.write(u"\3\2\2\35\36\5\20\t\2\36\37\5\4\3\2\37 \7\2\2\3 \3\3") buf.write(u"\2\2\2!%\7\4\2\2\"$\5\6\4\2#\"\3\2\2\2$\'\3\2\2\2%#\3") buf.write(u"\2\2\2%&\3\2\2\2&(\3\2\2\2\'%\3\2\2\2()\7\5\2\2)\5\3") buf.write(u"\2\2\2*.\5\n\6\2+.\5\f\7\2,.\5\b\5\2-*\3\2\2\2-+\3\2") buf.write(u"\2\2-,\3\2\2\2.\7\3\2\2\2/\60\7 \2\2\60\61\5\22\n\2\61") buf.write(u"\62\7\6\2\2\62\63\5\24\13\2\63\64\7\7\2\2\64\65\5\16") buf.write(u"\b\2\65\t\3\2\2\2\66\67\7 \2\2\678\5\22\n\289\7\6\2\2") buf.write(u"9:\5\24\13\2:\13\3\2\2\2;?\5\26\f\2<>\5\30\r\2=<\3\2") buf.write(u"\2\2>A\3\2\2\2?=\3\2\2\2?@\3\2\2\2@C\3\2\2\2A?\3\2\2") buf.write(u"\2BD\5\32\16\2CB\3\2\2\2CD\3\2\2\2D\r\3\2\2\2EF\b\b\1") buf.write(u"\2FQ\7\17\2\2GQ\7 \2\2HQ\7\20\2\2IQ\5\22\n\2JK\7\b\2") buf.write(u"\2KL\5\16\b\2LM\7\t\2\2MQ\3\2\2\2NO\7\21\2\2OQ\5\16\b") buf.write(u"\bPE\3\2\2\2PG\3\2\2\2PH\3\2\2\2PI\3\2\2\2PJ\3\2\2\2") buf.write(u"PN\3\2\2\2Qc\3\2\2\2RS\f\7\2\2ST\7\22\2\2Tb\5\16\b\b") buf.write(u"UV\f\6\2\2VW\7\24\2\2Wb\5\16\b\7XY\f\5\2\2YZ\7\23\2\2") buf.write(u"Zb\5\16\b\6[\\\f\4\2\2\\]\7\31\2\2]b\5\16\b\5^_\f\3\2") buf.write(u"\2_`\7\32\2\2`b\5\16\b\4aR\3\2\2\2aU\3\2\2\2aX\3\2\2") buf.write(u"\2a[\3\2\2\2a^\3\2\2\2be\3\2\2\2ca\3\2\2\2cd\3\2\2\2") buf.write(u"d\17\3\2\2\2ec\3\2\2\2fg\7!\2\2g\21\3\2\2\2hi\7!\2\2") buf.write(u"i\23\3\2\2\2jk\t\2\2\2k\25\3\2\2\2lm\7\f\2\2mn\7\b\2") buf.write(u"\2no\5\16\b\2op\7\t\2\2pq\5\4\3\2q\27\3\2\2\2rs\7\r\2") buf.write(u"\2st\7\b\2\2tu\5\16\b\2uv\7\t\2\2vw\5\4\3\2w\31\3\2\2") buf.write(u"\2xy\7\16\2\2yz\5\4\3\2z\33\3\2\2\2\t%-?CPac") return buf.getvalue() class QLParser ( Parser ): grammarFileName = "QL.g4" atn = ATNDeserializer().deserialize(serializedATN()) decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ] sharedContextCache = PredictionContextCache() literalNames = [ u"<INVALID>", u"'form'", u"'{'", u"'}'", u"':'", u"'='", u"'('", u"')'", u"'int'", u"'boolean'", u"'if'", u"'elif'", u"'else'", u"<INVALID>", u"<INVALID>", u"'!'", u"<INVALID>", u"<INVALID>", u"<INVALID>", u"'+'", u"'/'", u"'-'", u"'*'", u"'&&'", u"'||'", u"'true'", u"'false'" ] symbolicNames = [ u"<INVALID>", u"<INVALID>", u"<INVALID>", u"<INVALID>", u"<INVALID>", u"<INVALID>", u"<INVALID>", u"<INVALID>", u"<INVALID>", u"<INVALID>", u"<INVALID>", u"<INVALID>", u"<INVALID>", u"BOOL", u"INT", u"NOT", u"COMPARER", u"ADDSUBOPERATOR", u"DIVMULOPERATOR", u"ADD", u"DIV", u"SUB", u"MUL", u"AND", u"OR", u"TRUE", u"FALSE", u"WS", u"COMMENT", u"NUMBER", u"STR", u"NAME" ] RULE_form = 0 RULE_block = 1 RULE_statement = 2 RULE_assignment = 3 RULE_question = 4 RULE_conditional = 5 RULE_expression = 6 RULE_form_id = 7 RULE_var = 8 RULE_vartype = 9 RULE_if_cond = 10 RULE_elif_cond = 11 RULE_else_cond = 12 ruleNames = [ u"form", u"block", u"statement", u"assignment", u"question", u"conditional", u"expression", u"form_id", u"var", u"vartype", u"if_cond", u"elif_cond", u"else_cond" ] EOF = Token.EOF T__0=1 T__1=2 T__2=3 T__3=4 T__4=5 T__5=6 T__6=7 T__7=8 T__8=9 T__9=10 T__10=11 T__11=12 BOOL=13 INT=14 NOT=15 COMPARER=16 ADDSUBOPERATOR=17 DIVMULOPERATOR=18 ADD=19 DIV=20 SUB=21 MUL=22 AND=23 OR=24 TRUE=25 FALSE=26 WS=27 COMMENT=28 NUMBER=29 STR=30 NAME=31 def __init__(self, input, output=sys.stdout): super(QLParser, self).__init__(input, output=output) self.checkVersion("4.7") self._interp = ParserATNSimulator(self, self.atn, self.decisionsToDFA, self.sharedContextCache) self._predicates = None class FormContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(QLParser.FormContext, self).__init__(parent, invokingState) self.parser = parser def form_id(self): return self.getTypedRuleContext(QLParser.Form_idContext,0) def block(self): return self.getTypedRuleContext(QLParser.BlockContext,0) def EOF(self): return self.getToken(QLParser.EOF, 0) def getRuleIndex(self): return QLParser.RULE_form def accept(self, visitor): if hasattr(visitor, "visitForm"): return visitor.visitForm(self) else: return visitor.visitChildren(self) def form(self): localctx = QLParser.FormContext(self, self._ctx, self.state) self.enterRule(localctx, 0, self.RULE_form) try: self.enterOuterAlt(localctx, 1) self.state = 26 self.match(QLParser.T__0) self.state = 27 self.form_id() self.state = 28 self.block() self.state = 29 self.match(QLParser.EOF) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class BlockContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(QLParser.BlockContext, self).__init__(parent, invokingState) self.parser = parser def statement(self, i=None): if i is None: return self.getTypedRuleContexts(QLParser.StatementContext) else: return self.getTypedRuleContext(QLParser.StatementContext,i) def getRuleIndex(self): return QLParser.RULE_block def accept(self, visitor): if hasattr(visitor, "visitBlock"): return visitor.visitBlock(self) else: return visitor.visitChildren(self) def block(self): localctx = QLParser.BlockContext(self, self._ctx, self.state) self.enterRule(localctx, 2, self.RULE_block) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 31 self.match(QLParser.T__1) self.state = 35 self._errHandler.sync(self) _la = self._input.LA(1) while _la==QLParser.T__9 or _la==QLParser.STR: self.state = 32 self.statement() self.state = 37 self._errHandler.sync(self) _la = self._input.LA(1) self.state = 38 self.match(QLParser.T__2) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class StatementContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(QLParser.StatementContext, self).__init__(parent, invokingState) self.parser = parser def question(self): return self.getTypedRuleContext(QLParser.QuestionContext,0) def conditional(self): return self.getTypedRuleContext(QLParser.ConditionalContext,0) def assignment(self): return self.getTypedRuleContext(QLParser.AssignmentContext,0) def getRuleIndex(self): return QLParser.RULE_statement def accept(self, visitor): if hasattr(visitor, "visitStatement"): return visitor.visitStatement(self) else: return visitor.visitChildren(self) def statement(self): localctx = QLParser.StatementContext(self, self._ctx, self.state) self.enterRule(localctx, 4, self.RULE_statement) try: self.state = 43 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,1,self._ctx) if la_ == 1: self.enterOuterAlt(localctx, 1) self.state = 40 self.question() pass elif la_ == 2: self.enterOuterAlt(localctx, 2) self.state = 41 self.conditional() pass elif la_ == 3: self.enterOuterAlt(localctx, 3) self.state = 42 self.assignment() pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class AssignmentContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(QLParser.AssignmentContext, self).__init__(parent, invokingState) self.parser = parser def STR(self): return self.getToken(QLParser.STR, 0) def var(self): return self.getTypedRuleContext(QLParser.VarContext,0) def vartype(self): return self.getTypedRuleContext(QLParser.VartypeContext,0) def expression(self): return self.getTypedRuleContext(QLParser.ExpressionContext,0) def getRuleIndex(self): return QLParser.RULE_assignment def accept(self, visitor): if hasattr(visitor, "visitAssignment"): return visitor.visitAssignment(self) else: return visitor.visitChildren(self) def assignment(self): localctx = QLParser.AssignmentContext(self, self._ctx, self.state) self.enterRule(localctx, 6, self.RULE_assignment) try: self.enterOuterAlt(localctx, 1) self.state = 45 self.match(QLParser.STR) self.state = 46 self.var() self.state = 47 self.match(QLParser.T__3) self.state = 48 self.vartype() self.state = 49 self.match(QLParser.T__4) self.state = 50 self.expression(0) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class QuestionContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(QLParser.QuestionContext, self).__init__(parent, invokingState) self.parser = parser def STR(self): return self.getToken(QLParser.STR, 0) def var(self): return self.getTypedRuleContext(QLParser.VarContext,0) def vartype(self): return self.getTypedRuleContext(QLParser.VartypeContext,0) def getRuleIndex(self): return QLParser.RULE_question def accept(self, visitor): if hasattr(visitor, "visitQuestion"): return visitor.visitQuestion(self) else: return visitor.visitChildren(self) def question(self): localctx = QLParser.QuestionContext(self, self._ctx, self.state) self.enterRule(localctx, 8, self.RULE_question) try: self.enterOuterAlt(localctx, 1) self.state = 52 self.match(QLParser.STR) self.state = 53 self.var() self.state = 54 self.match(QLParser.T__3) self.state = 55 self.vartype() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ConditionalContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(QLParser.ConditionalContext, self).__init__(parent, invokingState) self.parser = parser def if_cond(self): return self.getTypedRuleContext(QLParser.If_condContext,0) def elif_cond(self, i=None): if i is None: return self.getTypedRuleContexts(QLParser.Elif_condContext) else: return self.getTypedRuleContext(QLParser.Elif_condContext,i) def else_cond(self): return self.getTypedRuleContext(QLParser.Else_condContext,0) def getRuleIndex(self): return QLParser.RULE_conditional def accept(self, visitor): if hasattr(visitor, "visitConditional"): return visitor.visitConditional(self) else: return visitor.visitChildren(self) def conditional(self): localctx = QLParser.ConditionalContext(self, self._ctx, self.state) self.enterRule(localctx, 10, self.RULE_conditional) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 57 self.if_cond() self.state = 61 self._errHandler.sync(self) _la = self._input.LA(1) while _la==QLParser.T__10: self.state = 58 self.elif_cond() self.state = 63 self._errHandler.sync(self) _la = self._input.LA(1) self.state = 65 self._errHandler.sync(self) _la = self._input.LA(1) if _la==QLParser.T__11: self.state = 64 self.else_cond() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ExpressionContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(QLParser.ExpressionContext, self).__init__(parent, invokingState) self.parser = parser self.left = None # ExpressionContext self.right = None # ExpressionContext def BOOL(self): return self.getToken(QLParser.BOOL, 0) def STR(self): return self.getToken(QLParser.STR, 0) def INT(self): return self.getToken(QLParser.INT, 0) def var(self): return self.getTypedRuleContext(QLParser.VarContext,0) def expression(self, i=None): if i is None: return self.getTypedRuleContexts(QLParser.ExpressionContext) else: return self.getTypedRuleContext(QLParser.ExpressionContext,i) def NOT(self): return self.getToken(QLParser.NOT, 0) def COMPARER(self): return self.getToken(QLParser.COMPARER, 0) def DIVMULOPERATOR(self): return self.getToken(QLParser.DIVMULOPERATOR, 0) def ADDSUBOPERATOR(self): return self.getToken(QLParser.ADDSUBOPERATOR, 0) def AND(self): return self.getToken(QLParser.AND, 0) def OR(self): return self.getToken(QLParser.OR, 0) def getRuleIndex(self): return QLParser.RULE_expression def accept(self, visitor): if hasattr(visitor, "visitExpression"): return visitor.visitExpression(self) else: return visitor.visitChildren(self) def expression(self, _p=0): _parentctx = self._ctx _parentState = self.state localctx = QLParser.ExpressionContext(self, self._ctx, _parentState) _prevctx = localctx _startState = 12 self.enterRecursionRule(localctx, 12, self.RULE_expression, _p) try: self.enterOuterAlt(localctx, 1) self.state = 78 self._errHandler.sync(self) token = self._input.LA(1) if token in [QLParser.BOOL]: self.state = 68 self.match(QLParser.BOOL) pass elif token in [QLParser.STR]: self.state = 69 self.match(QLParser.STR) pass elif token in [QLParser.INT]: self.state = 70 self.match(QLParser.INT) pass elif token in [QLParser.NAME]: self.state = 71 self.var() pass elif token in [QLParser.T__5]: self.state = 72 self.match(QLParser.T__5) self.state = 73 self.expression(0) self.state = 74 self.match(QLParser.T__6) pass elif token in [QLParser.NOT]: self.state = 76 self.match(QLParser.NOT) self.state = 77 self.expression(6) pass else: raise NoViableAltException(self) self._ctx.stop = self._input.LT(-1) self.state = 97 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,6,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: if self._parseListeners is not None: self.triggerExitRuleEvent() _prevctx = localctx self.state = 95 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,5,self._ctx) if la_ == 1: localctx = QLParser.ExpressionContext(self, _parentctx, _parentState) localctx.left = _prevctx self.pushNewRecursionContext(localctx, _startState, self.RULE_expression) self.state = 80 if not self.precpred(self._ctx, 5): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 5)") self.state = 81 self.match(QLParser.COMPARER) self.state = 82 localctx.right = self.expression(6) pass elif la_ == 2: localctx = QLParser.ExpressionContext(self, _parentctx, _parentState) localctx.left = _prevctx self.pushNewRecursionContext(localctx, _startState, self.RULE_expression) self.state = 83 if not self.precpred(self._ctx, 4): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 4)") self.state = 84 self.match(QLParser.DIVMULOPERATOR) self.state = 85 localctx.right = self.expression(5) pass elif la_ == 3: localctx = QLParser.ExpressionContext(self, _parentctx, _parentState) localctx.left = _prevctx self.pushNewRecursionContext(localctx, _startState, self.RULE_expression) self.state = 86 if not self.precpred(self._ctx, 3): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 3)") self.state = 87 self.match(QLParser.ADDSUBOPERATOR) self.state = 88 localctx.right = self.expression(4) pass elif la_ == 4: localctx = QLParser.ExpressionContext(self, _parentctx, _parentState) localctx.left = _prevctx self.pushNewRecursionContext(localctx, _startState, self.RULE_expression) self.state = 89 if not self.precpred(self._ctx, 2): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 2)") self.state = 90 self.match(QLParser.AND) self.state = 91 localctx.right = self.expression(3) pass elif la_ == 5: localctx = QLParser.ExpressionContext(self, _parentctx, _parentState) localctx.left = _prevctx self.pushNewRecursionContext(localctx, _startState, self.RULE_expression) self.state = 92 if not self.precpred(self._ctx, 1): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 1)") self.state = 93 self.match(QLParser.OR) self.state = 94 localctx.right = self.expression(2) pass self.state = 99 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,6,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.unrollRecursionContexts(_parentctx) return localctx class Form_idContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(QLParser.Form_idContext, self).__init__(parent, invokingState) self.parser = parser def NAME(self): return self.getToken(QLParser.NAME, 0) def getRuleIndex(self): return QLParser.RULE_form_id def accept(self, visitor): if hasattr(visitor, "visitForm_id"): return visitor.visitForm_id(self) else: return visitor.visitChildren(self) def form_id(self): localctx = QLParser.Form_idContext(self, self._ctx, self.state) self.enterRule(localctx, 14, self.RULE_form_id) try: self.enterOuterAlt(localctx, 1) self.state = 100 self.match(QLParser.NAME) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class VarContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(QLParser.VarContext, self).__init__(parent, invokingState) self.parser = parser def NAME(self): return self.getToken(QLParser.NAME, 0) def getRuleIndex(self): return QLParser.RULE_var def accept(self, visitor): if hasattr(visitor, "visitVar"): return visitor.visitVar(self) else: return visitor.visitChildren(self) def var(self): localctx = QLParser.VarContext(self, self._ctx, self.state) self.enterRule(localctx, 16, self.RULE_var) try: self.enterOuterAlt(localctx, 1) self.state = 102 self.match(QLParser.NAME) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class VartypeContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(QLParser.VartypeContext, self).__init__(parent, invokingState) self.parser = parser def getRuleIndex(self): return QLParser.RULE_vartype def accept(self, visitor): if hasattr(visitor, "visitVartype"): return visitor.visitVartype(self) else: return visitor.visitChildren(self) def vartype(self): localctx = QLParser.VartypeContext(self, self._ctx, self.state) self.enterRule(localctx, 18, self.RULE_vartype) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 104 _la = self._input.LA(1) if not(_la==QLParser.T__7 or _la==QLParser.T__8): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class If_condContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(QLParser.If_condContext, self).__init__(parent, invokingState) self.parser = parser def expression(self): return self.getTypedRuleContext(QLParser.ExpressionContext,0) def block(self): return self.getTypedRuleContext(QLParser.BlockContext,0) def getRuleIndex(self): return QLParser.RULE_if_cond def accept(self, visitor): if hasattr(visitor, "visitIf_cond"): return visitor.visitIf_cond(self) else: return visitor.visitChildren(self) def if_cond(self): localctx = QLParser.If_condContext(self, self._ctx, self.state) self.enterRule(localctx, 20, self.RULE_if_cond) try: self.enterOuterAlt(localctx, 1) self.state = 106 self.match(QLParser.T__9) self.state = 107 self.match(QLParser.T__5) self.state = 108 self.expression(0) self.state = 109 self.match(QLParser.T__6) self.state = 110 self.block() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Elif_condContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(QLParser.Elif_condContext, self).__init__(parent, invokingState) self.parser = parser def expression(self): return self.getTypedRuleContext(QLParser.ExpressionContext,0) def block(self): return self.getTypedRuleContext(QLParser.BlockContext,0) def getRuleIndex(self): return QLParser.RULE_elif_cond def accept(self, visitor): if hasattr(visitor, "visitElif_cond"): return visitor.visitElif_cond(self) else: return visitor.visitChildren(self) def elif_cond(self): localctx = QLParser.Elif_condContext(self, self._ctx, self.state) self.enterRule(localctx, 22, self.RULE_elif_cond) try: self.enterOuterAlt(localctx, 1) self.state = 112 self.match(QLParser.T__10) self.state = 113 self.match(QLParser.T__5) self.state = 114 self.expression(0) self.state = 115 self.match(QLParser.T__6) self.state = 116 self.block() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Else_condContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(QLParser.Else_condContext, self).__init__(parent, invokingState) self.parser = parser def block(self): return self.getTypedRuleContext(QLParser.BlockContext,0) def getRuleIndex(self): return QLParser.RULE_else_cond def accept(self, visitor): if hasattr(visitor, "visitElse_cond"): return visitor.visitElse_cond(self) else: return visitor.visitChildren(self) def else_cond(self): localctx = QLParser.Else_condContext(self, self._ctx, self.state) self.enterRule(localctx, 24, self.RULE_else_cond) try: self.enterOuterAlt(localctx, 1) self.state = 118 self.match(QLParser.T__11) self.state = 119 self.block() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx def sempred(self, localctx, ruleIndex, predIndex): if self._predicates == None: self._predicates = dict() self._predicates[6] = self.expression_sempred pred = self._predicates.get(ruleIndex, None) if pred is None: raise Exception("No predicate with index:" + str(ruleIndex)) else: return pred(localctx, predIndex) def expression_sempred(self, localctx, predIndex): if predIndex == 0: return self.precpred(self._ctx, 5) if predIndex == 1: return self.precpred(self._ctx, 4) if predIndex == 2: return self.precpred(self._ctx, 3) if predIndex == 3: return self.precpred(self._ctx, 2) if predIndex == 4: return self.precpred(self._ctx, 1)
[ "timo.dobber@student.uva.nl" ]
timo.dobber@student.uva.nl
9970cc05ec8be0e31b8b1160023fceca6807f5b7
a6a375accaa73af49829203e35f7334d2b008b84
/src/coffee.py
6e14e41825952a4dd8f03373cb2896c748cb97c1
[ "Unlicense" ]
permissive
TillJohanndeiter/state-chatbot
5173f62e4ec13cd2685449fe5d32ae6b79d2a179
bd24aa6669f4d22c57883729b6d4e620b81ff602
refs/heads/main
2023-07-01T21:22:12.127686
2021-08-11T14:35:48
2021-08-11T14:35:48
395,020,002
0
0
null
null
null
null
UTF-8
Python
false
false
1,134
py
''' Example for use on_entry and on_exit callbacks. ''' from src.graph import State MILK = 'Milk' SUGAR = 'Sugar' TEA = 'Tea' COFFEE = 'Coffee' HOT_CHOCOLATE = 'Hot chocolate' class CoffeeMachine: def __init__(self): self.order = [] def add_order(self, item): self.order.append(item) def reset_order(self): self.order = [] def get_order(self): return self.order coffee_machine = CoffeeMachine() class MakeCoffee(State): def on_entry(self): coffee_machine.add_order(COFFEE) class MakeTee(State): def on_entry(self): coffee_machine.add_order(TEA) class MakeChocolate(State): def on_entry(self): coffee_machine.add_order(HOT_CHOCOLATE) class AddMilk(State): def on_entry(self): coffee_machine.add_order(MILK) class AddSugar(State): def on_entry(self): coffee_machine.add_order(SUGAR) def on_exit(self): pass class VerifyOrder(State): def on_entry(self): print(coffee_machine.get_order()) class GiveOptions(State): def on_entry(self): coffee_machine.reset_order()
[ "till.johanndeiter@web.de" ]
till.johanndeiter@web.de
7664713022dd8e26a730a02e298ae9a32456900f
4e74981f4d304817a309efe8001ef5c94bbcbcb2
/dzz_v1.2/workspace/wuxia/app/configdata/mongoconfig.py
828e90f81b40ea3d1c1090bb1784873b6b9503e5
[]
no_license
ducgt/dazhuzai
3c03992cde5b24920840149f077a3fe402c33f07
78507088582f08598bb039284c31528feeb2a5bd
refs/heads/master
2021-06-14T09:52:05.945581
2015-01-19T06:16:12
2015-01-19T06:16:12
null
0
0
null
null
null
null
UTF-8
Python
false
false
222
py
#coding:utf-8 ''' Created on 2014-7-21 Copyright 2014 www.9miao.com ''' import mongoengine def init_Mongo_Conns(): import globalconfig mongoengine.connect(globalconfig.MONGO_DB,host=globalconfig.MONGO_HOST)
[ "463473243@qq.com" ]
463473243@qq.com
ab0316cae44ee7038db16c0bf8bc60b176e23100
d5312794a641f45f02cc5de5f1704501a891ba7e
/helloWorld/redis_test/test_demo1.py
87ffa6aea59114ef2eb5c33fa87f7c3a54620dee
[]
no_license
lizhou828/python_hello_world
8769cda2ee7ef24893f010c4de6a2e07c037e351
c2239bbb8866ebb4cdc2dbf1bb65ca55f913ddf2
refs/heads/master
2022-12-22T20:44:47.276113
2019-11-21T06:33:43
2019-11-21T06:33:43
79,169,724
3
0
null
2022-12-08T05:22:37
2017-01-16T23:43:32
JavaScript
UTF-8
Python
false
false
278
py
# -*- coding:utf-8 -*- # pip install redis import redis pool = redis.ConnectionPool(host='192.168.2.122', port=6379) r = redis.Redis(connection_pool=pool) r.set('kw', 'hello world') print(r.get('kw')) r.hset("hash_test", "key1", '你好') r.hset("hash_test", "key2", '啊!')
[ "lizhou828@126.com" ]
lizhou828@126.com
79c95e6c318385baac15e1a339ea94e5901b6b4f
53345f4899573196fac31ecc28e2682155c47cf3
/currency_-converter/main.py
b7a0078c8c0c610593f067de6e6505d90f4d0e9b
[]
no_license
Johnmahama/python-projects
80deba0cd75cb2e8da9b5803df081ae35c92cfd5
db4076e5cbfb64c245ea24b53ad34031d3e69005
refs/heads/master
2022-11-22T23:52:36.455113
2020-07-20T15:11:32
2020-07-20T15:11:32
281,151,126
0
0
null
null
null
null
UTF-8
Python
false
false
700
py
from currency_converter import CurrencyConverter class Currency_Converter(object): def __init__(self,amount,c_from,c_to): self.amount = amount self.c_from = c_from self.c_to = c_to self.currency = CurrencyConverter() def __repr__(self): try: currency_result = round(self.currency.convert(self.amount,self.c_from,self.c_to), 2) return f"{self.amount} {self.c_from} = {currency_result}{self.c_to}" except ValueError: return "Need currency amount,current currency and convertion currency" if __name__=="__main__": currency = Currency_Converter(20,"USD","EUR") print(currency)
[ "mahamajohn526@gmail.com" ]
mahamajohn526@gmail.com
33fa998b0134c61d8a91afe8f58eb57cf3ac5284
09e57dd1374713f06b70d7b37a580130d9bbab0d
/data/p3BR/R1/benchmark/startQiskit_Class421.py
0402b6f229c87df1eed51ed312ab0549e1260aab
[ "BSD-3-Clause" ]
permissive
UCLA-SEAL/QDiff
ad53650034897abb5941e74539e3aee8edb600ab
d968cbc47fe926b7f88b4adf10490f1edd6f8819
refs/heads/main
2023-08-05T04:52:24.961998
2021-09-19T02:56:16
2021-09-19T02:56:16
405,159,939
2
0
null
null
null
null
UTF-8
Python
false
false
5,399
py
# qubit number=3 # total number=74 import numpy as np from qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ from qiskit.visualization import plot_histogram from typing import * from pprint import pprint from math import log2 from collections import Counter from qiskit.test.mock import FakeVigo, FakeYorktown kernel = 'circuit/bernstein' def bitwise_xor(s: str, t: str) -> str: length = len(s) res = [] for i in range(length): res.append(str(int(s[i]) ^ int(t[i]))) return ''.join(res[::-1]) def bitwise_dot(s: str, t: str) -> str: length = len(s) res = 0 for i in range(length): res += int(s[i]) * int(t[i]) return str(res % 2) def build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit: # implement the oracle O_f # NOTE: use multi_control_toffoli_gate ('noancilla' mode) # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate controls = QuantumRegister(n, "ofc") target = QuantumRegister(1, "oft") oracle = QuantumCircuit(controls, target, name="Of") for i in range(2 ** n): rep = np.binary_repr(i, n) if f(rep) == "1": for j in range(n): if rep[j] == "0": oracle.x(controls[j]) oracle.mct(controls, target[0], None, mode='noancilla') for j in range(n): if rep[j] == "0": oracle.x(controls[j]) # oracle.barrier() # oracle.draw('mpl', filename=(kernel + '-oracle.png')) return oracle def build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit: # implement the Bernstein-Vazirani circuit zero = np.binary_repr(0, n) b = f(zero) # initial n + 1 bits input_qubit = QuantumRegister(n+1, "qc") classicals = ClassicalRegister(n, "qm") prog = QuantumCircuit(input_qubit, classicals) # inverse last one (can be omitted if using O_f^\pm) prog.x(input_qubit[n]) # circuit begin prog.h(input_qubit[1]) # number=1 prog.h(input_qubit[1]) # number=70 prog.rx(-0.09738937226128368,input_qubit[2]) # number=2 prog.h(input_qubit[1]) # number=33 prog.y(input_qubit[2]) # number=56 prog.cz(input_qubit[2],input_qubit[1]) # number=34 prog.h(input_qubit[1]) # number=35 prog.h(input_qubit[1]) # number=3 # apply H to get superposition for i in range(n): prog.h(input_qubit[i]) prog.h(input_qubit[n]) prog.barrier() # apply oracle O_f oracle = build_oracle(n, f) prog.append( oracle.to_gate(), [input_qubit[i] for i in range(n)] + [input_qubit[n]]) # apply H back (QFT on Z_2^n) for i in range(n): prog.h(input_qubit[i]) prog.barrier() # measure return prog def get_statevector(prog: QuantumCircuit) -> Any: state_backend = Aer.get_backend('statevector_simulator') statevec = execute(prog, state_backend).result() quantum_state = statevec.get_statevector() qubits = round(log2(len(quantum_state))) quantum_state = { "|" + np.binary_repr(i, qubits) + ">": quantum_state[i] for i in range(2 ** qubits) } return quantum_state def evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any: # Q: which backend should we use? # get state vector quantum_state = get_statevector(prog) # get simulate results # provider = IBMQ.load_account() # backend = provider.get_backend(backend_str) # qobj = compile(prog, backend, shots) # job = backend.run(qobj) # job.result() backend = Aer.get_backend(backend_str) # transpile/schedule -> assemble -> backend.run results = execute(prog, backend, shots=shots).result() counts = results.get_counts() a = Counter(counts).most_common(1)[0][0][::-1] return { "measurements": counts, # "state": statevec, "quantum_state": quantum_state, "a": a, "b": b } def bernstein_test_1(rep: str): """011 . x + 1""" a = "011" b = "1" return bitwise_xor(bitwise_dot(a, rep), b) def bernstein_test_2(rep: str): """000 . x + 0""" a = "000" b = "0" return bitwise_xor(bitwise_dot(a, rep), b) def bernstein_test_3(rep: str): """111 . x + 1""" a = "111" b = "1" return bitwise_xor(bitwise_dot(a, rep), b) if __name__ == "__main__": n = 2 a = "11" b = "1" f = lambda rep: \ bitwise_xor(bitwise_dot(a, rep), b) prog = build_circuit(n, f) sample_shot =4000 writefile = open("../data/startQiskit_Class421.csv", "w") # prog.draw('mpl', filename=(kernel + '.png')) backend = BasicAer.get_backend('statevector_simulator') circuit1 = transpile(prog, FakeYorktown()) circuit1.h(qubit=2) circuit1.x(qubit=3) info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts() print(info, file=writefile) print("results end", file=writefile) print(circuit1.depth(), file=writefile) print(circuit1, file=writefile) writefile.close()
[ "wangjiyuan123@yeah.net" ]
wangjiyuan123@yeah.net
dd79604e064e324c9050e70571fb46da441ef806
c91775afdc25f8897c6839cf8294869f3e928083
/PythonFiles/snowmass_cfg_TTBAR_14TEV_1100_1700_Conf3_14.py
975b02de9db2d2cd0ffe7c63cb30d2b858426578
[]
no_license
Saptaparna/Miscellaneous
7e6df9cdfd10d4861e2e382b1837dbd4c26fb249
b954189d85e56a02fe257b5f5cbd779365719c00
refs/heads/master
2021-01-23T13:29:30.283308
2017-12-20T08:26:37
2017-12-20T08:26:37
42,525,018
0
0
null
null
null
null
UTF-8
Python
false
false
9,287
py
import FWCore.ParameterSet.Config as cms import FWCore.PythonUtilities.LumiList as LumiList import FWCore.ParameterSet.Types as CfgTypes # # Parameters that can be set via command line # when submitting Condor jobs # isMc_settable = True isSignalMc_settable = False def FindFile(name): fname = 'file.txt' return fname process = cms.Process("LJMetCom") ################################################################## # # All input files needed for the job to run # Specify them here, and they will automatically be correctly # transferred to Condor when needed # NOTE: you can define as many or as few entries as you wish, # names are up to you miscFiles = {} miscFiles['jec_uncertainty'] = '../cond/Summer12_V2_DATA_AK5PF_UncertaintySources.txt' miscFiles['btag_performance'] = '../cond/btag_performance_db062012.root' miscFiles['json'] = '../data/json/Cert_190456-208686_8TeV_PromptReco_Collisions12_JSON.txt' miscFiles['MCL1JetPar'] = '../data/START53_V7G_L1FastJet_AK5PFchs.txt' miscFiles['MCL2JetPar'] = '../data/START53_V7G_L2Relative_AK5PFchs.txt' miscFiles['MCL3JetPar'] = '../data/START53_V7G_L3Absolute_AK5PFchs.txt' miscFiles['DataL1JetPar'] = '../data/FT_53_V10_AN3_L1FastJet_AK5PFchs.txt' miscFiles['DataL2JetPar'] = '../data/FT_53_V10_AN3_L2Relative_AK5PFchs.txt' miscFiles['DataL3JetPar'] = '../data/FT_53_V10_AN3_L3Absolute_AK5PFchs.txt' miscFiles['DataResJetPar'] = '../data/FT_53_V10_AN3_L2L3Residual_AK5PFchs.txt' #Arguments from condor submit script which are used more than once condorIsMC = bool(True) relBase = str('/uscms_data/d2/sapta/work/LJMetCode_fromGena/Dilepton_Feb25/CMSSW_5_3_7_patch4') condorJSON = str('None') # Dilepton calculator options process.load('LJMet.Com.DileptonCalc_cfi') process.DileptonCalc.isMc = condorIsMC process.DileptonCalc.dataType = cms.string('None') ############################################################ # # FWLite application options # process.ljmet = cms.PSet( isMc = cms.bool(condorIsMC), runs = cms.vint32([]), verbosity = cms.int32(0) ) #Exclude unnecessary calculators process.ljmet.excluded_calculators = cms.vstring( 'WprimeCalc', 'LjetsTopoCalc', 'LjetsTopoCalcNew', 'StopCalc' ) ############################################################ # # common calculator options process.load('LJMet.Com.commonCalc_cfi') process.CommonCalc.dummy_parameter = cms.string('Dummy parameter value') ############################################################ # # pileup calculator options process.load('LJMet.Com.pileupCalc_cfi') process.PileUpCalc.verbosity = process.ljmet.verbosity ############################################################ # # Event selector options # process.event_selector = cms.PSet( selection = cms.string('DileptonSelector'), isMc = cms.bool(condorIsMC), # cuts #HLT trigger_cut = cms.bool(True), dump_trigger = cms.bool(False), #Can use same trigger paths for data and MC since MC is always one of the data versions trigger_path_ee = cms.vstring('HLT_Ele17_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_Ele8_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_v15', 'HLT_Ele17_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_Ele8_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_v16', 'HLT_Ele17_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_Ele8_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_v17', 'HLT_Ele17_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_Ele8_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_v18', 'HLT_Ele17_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_Ele8_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_v19'), trigger_path_em = cms.vstring('HLT_Mu8_Ele17_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_v4', 'HLT_Mu8_Ele17_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_v5', 'HLT_Mu8_Ele17_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_v6', 'HLT_Mu8_Ele17_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_v7', 'HLT_Mu8_Ele17_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_v8', 'HLT_Mu8_Ele17_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_v9', 'HLT_Mu17_Ele8_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_v4', 'HLT_Mu17_Ele8_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_v5', 'HLT_Mu17_Ele8_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_v6', 'HLT_Mu17_Ele8_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_v7', 'HLT_Mu17_Ele8_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_v8', 'HLT_Mu17_Ele8_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_v9'), trigger_path_mm = cms.vstring('HLT_Mu17_Mu8_v16', 'HLT_Mu17_Mu8_v17', 'HLT_Mu17_Mu8_v18', 'HLT_Mu17_Mu8_v19', 'HLT_Mu17_Mu8_v21', 'HLT_Mu17_Mu8_v22', 'HLT_Mu17_TkMu8_v9', 'HLT_Mu17_TkMu8_v10', 'HLT_Mu17_TkMu8_v11', 'HLT_Mu17_TkMu8_v12', 'HLT_Mu17_TkMu8_v13', 'HLT_Mu17_TkMu8_v14'), pv_cut = cms.bool(False), hbhe_cut = cms.bool(False), jet_cuts = cms.bool(False), jet_minpt = cms.double(20.0), jet_maxeta = cms.double(5), min_jet = cms.int32(0), max_jet = cms.int32(4000), muon_cuts = cms.bool(True), min_muon = cms.int32(0), muon_minpt = cms.double(10.0), muon_maxeta = cms.double(4.0), max_muon = cms.int32(20), electron_cuts = cms.bool(True), min_electron = cms.int32(0), electron_minpt = cms.double(10.0), electron_maxeta = cms.double(4.0), max_electron = cms.int32(20), min_lepton = cms.int32(2), met_cuts = cms.bool(False), min_met = cms.double(0.0), btag_cuts = cms.bool(False), btagOP = cms.string("CSVM"), btag_1 = cms.bool(True), btag_2 = cms.bool(True), btag_3 = cms.bool(False), trigger_collection = cms.InputTag('TriggerResults::HLT'), pv_collection = cms.InputTag('goodOfflinePrimaryVertices'), jet_collection = cms.InputTag('goodPatJetsPFlow'), muon_collection = cms.InputTag('selectedPatMuonsPFlowLoose'), electron_collection = cms.InputTag('selectedPatElectronsPFlowLoose'), met_collection = cms.InputTag('patMETsPFlow'), JEC_txtfile = cms.string(miscFiles['jec_uncertainty']), JECup = cms.bool(False), JECdown = cms.bool(False), JERup = cms.bool(False), JERdown = cms.bool(False), BTagUncertUp = cms.bool(False), BTagUncertDown = cms.bool(True), do53xJEC = cms.bool(True), MCL1JetPar = cms.string(miscFiles['MCL1JetPar']), MCL2JetPar = cms.string(miscFiles['MCL2JetPar']), MCL3JetPar = cms.string(miscFiles['MCL3JetPar']), DataL1JetPar = cms.string(miscFiles['DataL1JetPar']), DataL2JetPar = cms.string(miscFiles['DataL2JetPar']), DataL3JetPar = cms.string(miscFiles['DataL3JetPar']), DataResJetPar = cms.string(miscFiles['DataResJetPar']), keepFullMChistory = cms.bool(True) ) ################################################################## # # Input files # # NOTE: keep your test inputs in the python files as in # this example, and they will be correctly substituted with # specified input events when you submit to Condor # ( # # nEvents and skipEvents are for interactive use, their # values will be correctly reset when you submit Condor # input_module = 'LJMet.Com.TTBAR_14TEV_1100_1700_Conf3_14' process.load(input_module) process.inputs.nEvents = cms.int32(-1) process.inputs.skipEvents = cms.int32(0) ############################################################ # # JSON JsonFile = miscFiles['json'] myList = LumiList.LumiList(filename=JsonFile).getCMSSWString().split(',') if not condorIsMC: process.inputs.lumisToProcess.extend(myList) ####################################################### # # Output # process.outputs = cms.PSet ( outputName = cms.string('TTBAR_14TEV_1100_1700_Conf3_14'), treeName = cms.string('ljmet'), ) ####################################################### # # Object selector options # # Primary vertex process.load('PhysicsTools.SelectorUtils.pvSelector_cfi') process.pvSelector.pvSrc = cms.InputTag('goodOfflinePrimaryVertices') process.pvSelector.minNdof = cms.double(4.0) process.pvSelector.maxZ = cms.double(24.0) process.pvSelector.maxRho = cms.double(2.0) # jets process.load('PhysicsTools.SelectorUtils.pfJetIDSelector_cfi') process.pfJetIDSelector.version = cms.string('FIRSTDATA') process.pfJetIDSelector.quality = cms.string('LOOSE')
[ "saptaparna@gmail.com" ]
saptaparna@gmail.com
3d43bf8e2d3514c7ceb68e2e89ac98bd635fe78b
ef7265d85d4156ca8536814bc6d7b2f2af5f995f
/2. Naive Bayes and Online Learning/utils.py
ef64cbf47723e93edded8376338b172fdd01608c
[]
no_license
dianshan14/Machine-Learning-NCTU
516a3d1dc1b894470900c7ad11da5d77dd7bc2af
4946f8f66bc045a5a5accadf702ba697ef3ffe36
refs/heads/master
2021-01-09T16:31:48.650646
2020-04-10T16:23:21
2020-04-10T16:23:21
242,373,039
4
0
null
null
null
null
UTF-8
Python
false
false
2,215
py
import struct import os import numpy as np def get_data(filename): with open(filename, 'r') as f: data = f.read().strip() return data.split('\n') def parse_MNIST(filename, image=True): print('Processing %s' % filename) with open(filename, 'rb') as f: f.seek(0) magic = struct.unpack('>4B', f.read(4)) N = struct.unpack('>I', f.read(4))[0] if image: H = struct.unpack('>I', f.read(4))[0] W = struct.unpack('>I', f.read(4))[0] total_bytes = N * H * W * 1 # data = 255 - np.asarray(struct.unpack('>'+'B'*total_bytes, f.read(total_bytes))).reshape(N, H, W) data = np.asarray(struct.unpack('>'+'B'*total_bytes, f.read(total_bytes))).reshape(N, H, W) else: total_bytes = N * 1 data = np.asarray(struct.unpack('>'+'B'*total_bytes, f.read(total_bytes))).reshape(N) return data def get_MNIST_data(path): x_train = parse_MNIST(os.path.join(path, 'train-images.idx3-ubyte')).reshape(-1, 784) y_train = parse_MNIST(os.path.join(path, 'train-labels.idx1-ubyte'), image=False) x_test = parse_MNIST(os.path.join(path, 't10k-images.idx3-ubyte')).reshape(-1, 784) y_test = parse_MNIST(os.path.join(path, 't10k-labels.idx1-ubyte'), image=False) print('Parse MNIST dataset completed') return x_train, y_train, x_test, y_test def get_binned_MNIST(path): x_train = np.load(os.path.join(path, 'x_train.npy')) y_train = np.load(os.path.join(path, 'y_train.npy')) x_test = np.load(os.path.join(path, 'x_test.npy')) y_test = np.load(os.path.join(path, 'y_test.npy')) print('LOADING NUMPY Finish') return x_train, y_train, x_test, y_test def get_parsed_MNIST(path): x_train = np.load(os.path.join(path, 'raw_x_train.npy')) y_train = np.load(os.path.join(path, 'raw_y_train.npy')) x_test = np.load(os.path.join(path, 'raw_x_test.npy')) y_test = np.load(os.path.join(path, 'raw_y_test.npy')) print('LOADING NUMPY Finish') return x_train, y_train, x_test, y_test if __name__ == '__main__': print(get_data('testfile.txt')) data = get_MNIST_data('./data') for i in data: print(i.shape)
[ "sam851214@gmail.com" ]
sam851214@gmail.com
77e2eb665274fcfa7378c3ad4efa93bf8d2afcde
4fc01fdac7566c557e85585afc4ee0b4bf6d6f2d
/function/10-1/main.py
7a5abd833f241d1b40a45b0eef53b1b04bdd5cf9
[]
no_license
Dualic/checkpoint10
f06cc71d36537986274ecf8939d1795eaba6b696
74bbaf7fcaae7714394ad6ce85625ff2eee4df66
refs/heads/master
2023-08-16T19:09:50.597646
2021-09-03T07:14:22
2021-09-03T07:14:22
402,666,431
0
0
null
null
null
null
UTF-8
Python
false
false
84
py
def yourgreatfunction(request): return "This is your new and improved function"
[ "ilkka.o.pekkala@gmail.com" ]
ilkka.o.pekkala@gmail.com
a29928caa5fa7e88658b10c951d04856ff9a6165
56296556639f18f1bee774179756b8bbdcf84ab6
/main.py
11977846710b25840f83c6af926ef7d6af6d4996
[]
no_license
zengru001usst/Auto-encoder-with-deconvolution
4516ceb36892b695476e05f537811c3582959ee0
635a82e7559f45ea4f2db485e4a0a8b8036b4f21
refs/heads/master
2023-06-16T21:37:32.021726
2021-07-16T07:37:19
2021-07-16T07:37:19
386,542,063
0
0
null
null
null
null
UTF-8
Python
false
false
4,700
py
import torch import torch.nn as nn import torch.nn.functional as F import torchvision.utils as utils class Auto_encoder(nn.Module): """ A simple auto-encoder using deconvolution as decoder This program is designed for MNIST """ def __init__(self): super(Auto_encoder, self).__init__() ## encoder: downsample the input so its shape is shrinked by 2^3 times self.conv1 = nn.Conv2d(in_channels=1, out_channels=32, kernel_size=5, stride=1, padding=2) self.bn1 = nn.BatchNorm2d(32) self.conv2 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=2, padding=1) self.bn2 = nn.BatchNorm2d(64) self.conv3 = nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, stride=2, padding=1) self.bn3 = nn.BatchNorm2d(128) self.conv4 = nn.Conv2d(in_channels=128, out_channels=256, kernel_size=3, stride=2, padding=1) self.bn4 = nn.BatchNorm2d(256) ## decoder: upsample the feature maps so the shape is extend back to normal self.deconv1 = nn.ConvTranspose2d(256, 128, 3, stride=2, padding=1, output_padding=0) # It's recommended that padding=(kernel_size-1)/2, output_padding=stride-1 self.bn_1 = nn.BatchNorm2d(128) self.deconv2 = nn.ConvTranspose2d(128, 64, 3, stride=2, padding=1, output_padding=1) self.bn_2 = nn.BatchNorm2d(64) self.deconv3 = nn.ConvTranspose2d(64, 1, 3, stride=2, padding=1, output_padding=1) # self.bn_3=nn.BatchNorm(64) self.images_count = 0 # for images visualization self.relu = nn.ReLU() self.sigmoid = nn.Sigmoid() self.MSE = nn.MSELoss(reduction='mean') def forward(self, input): features = self.relu(self.bn1(self.conv1(input))) features = self.relu(self.bn2(self.conv2(features))) features = self.relu(self.bn3(self.conv3(features))) code = self.relu(self.bn4(self.conv4(features))) # print(code.shape) features = self.relu(self.bn_1(self.deconv1(code))) features = self.relu(self.bn_2(self.deconv2(features))) output = self.sigmoid(self.deconv3(features)) return output def reconstruction_loss(self, images, de_images): if self.images_count % 10 == 0: output_images = de_images.cpu() utils.save_image(output_images, 'reconstruction_images.png') self.images_count += 1 loss = self.MSE(images, de_images) return loss import torch.optim as optim from torchvision import datasets, transforms import torchvision device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') num_epochs = 30 batch_size = 150 learning_rate = 0.001 transform = transforms.Compose([ transforms.ToTensor(), ]) train_dataset = torchvision.datasets.MNIST(root='./mnist-torch', train=True, transform=transform, download=True) test_dataset = torchvision.datasets.MNIST(root='./mnist-torch', train=False, transform=transform, download=True) train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True) test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=False) model = Auto_encoder().to(device) # .half() optimizer = optim.Adam(model.parameters(), lr=learning_rate) # optimizer = optim.SGD(model.parameters(), lr=0.1, momentum=0.9) scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min', factor=0.1) total_p = sum([param.nelement() for param in model.parameters()]) print('Number of params: %.2fM' % (total_p / 1e6)) def train(epoch): model.train() total_step = len(train_loader) current_lr = learning_rate for i, (images, labels) in enumerate(train_loader): images = images.to(device) # .half() # labels_v=to_one_hot(labels,10).to(device) outputs = model(images) loss = model.reconstruction_loss(images, outputs) optimizer.zero_grad() loss.backward() optimizer.step() print('Epoch:{}, step[{}/{}] Loss:{:.4f}' .format(epoch, i, total_step, loss.item())) def test(epoch): model.eval() with torch.no_grad(): correct = 0 total = 0 for i, (images, labels) in enumerate(test_loader): images = images.to(device) outputs = model(images) loss = model.reconstruction_loss(images, outputs) print('Loss:{:.4f}%'.format(loss.item())) return loss temp = 0 for i in range(num_epochs): train(i) loss = test(i) scheduler.step(loss) total_p = sum([param.nelement() for param in model.parameters()]) print('Number of params: %.2fM' % (total_p / 1e6))
[ "49513015+zengru001usst@users.noreply.github.com" ]
49513015+zengru001usst@users.noreply.github.com
0b88441716587203d59c3ac7690ec6804eee990d
957592589270bf2b352f8cd2f0b1d25ac3cc04d2
/test/query_test.py
168ca0c16ee1df7aa54a6e305e0fb53c7ba75c1c
[]
no_license
Huangdu-Mental-Health-Center/MockHospitalData
d1aa513fad77ebb9212c3d907ba9f02d639502cf
0d2566069b79a4ff27acf1361b9c191c88c001ed
refs/heads/main
2023-05-06T04:34:05.057747
2021-05-27T11:59:27
2021-05-27T11:59:27
316,734,869
0
1
null
2021-05-27T11:59:28
2020-11-28T13:00:46
Python
UTF-8
Python
false
false
2,933
py
import unittest # from marshmallow.mock_hospital.mock_class import Doctor, Hospital # from marshmallow.mock_hospital.mock_xlsx import query as xlsx_query # from marshmallow.mock_hospital.mock_api import get_doctor_list as api_query class TestQuery(unittest.TestCase): def test_db_single_query_if_success(self): from marshmallow.mock_hospital.mock_db import query as db_query hospital_result = db_query("老刘") print(hospital_result.doctor_list_dict_str) self.assertTrue(len(hospital_result.doctor_list_dict_str) == 1) def test_db_multi_query_if_success(self): from marshmallow.mock_hospital.mock_db import query as db_query hospital_result = db_query("王") print(hospital_result.doctor_list_dict_str) self.assertTrue(len(hospital_result.doctor_list_dict_str) == 2) def test_db_query_if_no_match(self): from marshmallow.mock_hospital.mock_db import query as db_query hospital_result = db_query("114514") print(hospital_result.doctor_list_dict_str) self.assertTrue(len(hospital_result.doctor_list_dict_str) == 0) def test_xlsx_multi_query_if_success(self): from marshmallow.mock_hospital.mock_xlsx import query as xlsx_query hospital_result = xlsx_query("大") print(hospital_result.doctor_list_dict_str) self.assertTrue(len(hospital_result.doctor_list_dict_str) == 3) def test_xlsx_single_query_if_success(self): from marshmallow.mock_hospital.mock_xlsx import query as xlsx_query hospital_result = xlsx_query("大楹") print(hospital_result.doctor_list_dict_str) self.assertTrue(len(hospital_result.doctor_list_dict_str) == 1) def test_xlsx_query_if_no_match(self): from marshmallow.mock_hospital.mock_xlsx import query as xlsx_query hospital_result = xlsx_query("114514") print(hospital_result.doctor_list_dict_str) self.assertTrue(len(hospital_result.doctor_list_dict_str) == 0) def test_api_single_query_if_success(self): from marshmallow.mock_hospital.mock_api import query as api_query hospital_result = api_query("老邓") print(hospital_result.doctor_list_dict_str) self.assertTrue(len(hospital_result.doctor_list_dict_str) == 1) def test_api_multi_query_if_success(self): from marshmallow.mock_hospital.mock_api import query as api_query hospital_result = api_query("小") print(hospital_result.doctor_list_dict_str) self.assertTrue(len(hospital_result.doctor_list_dict_str) == 3) def test_api_single_query_if_no_match(self): from marshmallow.mock_hospital.mock_api import query as api_query hospital_result = api_query("114514") print(hospital_result.doctor_list_dict_str) self.assertTrue(len(hospital_result.doctor_list_dict_str) == 0) if __name__ == '__main__': unittest.main()
[ "noreply@github.com" ]
noreply@github.com
3a73322aa34e6b98bf0a7f659664996a4e5097c1
f94a8e7e4ce54aaf640093c095a2fc3a7309d22a
/Stream/migrations/0001_initial.py
241f00d8ba6ad61fd83bacf7327ef7df674a6427
[]
no_license
Machalkas/Oggetto
2d7688a4db30214266643a4c595ecd9ba71ee169
9892c088d3b9549313bcdbb9e5e6756d79fde744
refs/heads/main
2023-04-03T12:37:55.044138
2021-03-30T19:19:13
2021-03-30T19:19:13
349,800,054
1
0
null
null
null
null
UTF-8
Python
false
false
880
py
# Generated by Django 3.1.7 on 2021-03-19 22:53 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('Shop', '0001_initial'), ] operations = [ migrations.CreateModel( name='Stream', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('token', models.CharField(max_length=100, null=True, unique=True, verbose_name='Токен')), ('shop', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='Shop.shop', verbose_name='Магазин')), ], options={ 'verbose_name': 'Стрим', 'verbose_name_plural': 'Стримы', }, ), ]
[ "al1999dk@gmail.com" ]
al1999dk@gmail.com
ce4f926c0d9fd607823601ec9b413db31759d133
456433ac78b70cb8ae076ae166a85e349f181d7f
/systems/KURSSKLAD/KURSTERM/WORKPALLET/templates/U3S/palletFPCreate.py
41b8299e8eda2772fe58df1b34a69b642eaebc48
[]
no_license
shybkoi/WMS-Demo
854c1679b121c68323445b60f3992959f922be8d
2525559c4f56654acfbc21b41b3f5e40387b89e0
refs/heads/master
2021-01-23T01:51:20.074825
2017-03-23T11:51:18
2017-03-23T11:51:18
85,937,726
0
0
null
null
null
null
WINDOWS-1251
Python
false
false
12,048
py
#!/usr/bin/env python # -*- coding: cp1251 -*- ################################################## ## DEPENDENCIES import sys import os import os.path from os.path import getmtime, exists import time import types import __builtin__ from Cheetah.Version import MinCompatibleVersion as RequiredCheetahVersion from Cheetah.Version import MinCompatibleVersionTuple as RequiredCheetahVersionTuple from Cheetah.Template import Template from Cheetah.DummyTransaction import DummyTransaction from Cheetah.NameMapper import NotFound, valueForName, valueFromSearchList, valueFromFrameOrSearchList from Cheetah.CacheRegion import CacheRegion import Cheetah.Filters as Filters import Cheetah.ErrorCatchers as ErrorCatchers from systems.KURSSKLAD.KURSTERM.templates.main import main from systems.KURSSKLAD.cheetahutils import viewQuantity from systems.KURSSKLAD.cheetahutils import TimeStampToDate ################################################## ## MODULE CONSTANTS try: True, False except NameError: True, False = (1==1), (1==0) VFFSL=valueFromFrameOrSearchList VFSL=valueFromSearchList VFN=valueForName currentTime=time.time __CHEETAH_version__ = '2.0rc8' __CHEETAH_versionTuple__ = (2, 0, 0, 'candidate', 8) __CHEETAH_genTime__ = 1482336171.592 __CHEETAH_genTimestamp__ = 'Wed Dec 21 18:02:51 2016' __CHEETAH_src__ = 'systems\\KURSSKLAD\\KURSTERM\\WORKPALLET\\templates\\U3S\\palletFPCreate.tmpl' __CHEETAH_srcLastModified__ = 'Wed Dec 21 15:22:10 2016' __CHEETAH_docstring__ = 'Autogenerated by CHEETAH: The Python-Powered Template Engine' if __CHEETAH_versionTuple__ < RequiredCheetahVersionTuple: raise AssertionError( 'This template was compiled with Cheetah version' ' %s. Templates compiled before version %s must be recompiled.'%( __CHEETAH_version__, RequiredCheetahVersion)) ################################################## ## CLASSES class palletFPCreate(main): ################################################## ## CHEETAH GENERATED METHODS def __init__(self, *args, **KWs): main.__init__(self, *args, **KWs) if not self._CHEETAH__instanceInitialized: cheetahKWArgs = {} allowedKWs = 'searchList namespaces filter filtersLib errorCatcher'.split() for k,v in KWs.items(): if k in allowedKWs: cheetahKWArgs[k] = v self._initCheetahInstance(**cheetahKWArgs) def mainData(self, **KWS): ## CHEETAH: generated from #def mainData at line 7, col 1. trans = KWS.get("trans") if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)): trans = self.transaction # is None unless self.awake() was called if not trans: trans = DummyTransaction() _dummyTrans = True else: _dummyTrans = False write = trans.response().write SL = self._CHEETAH__searchList _filter = self._CHEETAH__currentFilter ######################################## ## START - generated method body write(''' <b>(''') _v = VFFSL(SL,"WCODE",True) # '$WCODE' on line 8, col 9 if _v is not None: write(_filter(_v, rawExpr='$WCODE')) # from line 8, col 9. write(''')</b> ''') _v = VFFSL(SL,"WNAME",True) # '$WNAME' on line 8, col 21 if _v is not None: write(_filter(_v, rawExpr='$WNAME')) # from line 8, col 21. write(''' <br><br> ''') if False: _('На паллете') _v = VFFSL(SL,"_",False)('На паллете') # "$_('\xcd\xe0 \xef\xe0\xeb\xeb\xe5\xf2\xe5')" on line 10, col 5 if _v is not None: write(_filter(_v, rawExpr="$_('\xcd\xe0 \xef\xe0\xeb\xeb\xe5\xf2\xe5')")) # from line 10, col 5. write(''': ''') _v = VFFSL(SL,"viewQuantity",False)(VFFSL(SL,"WQ",True),VFFSL(SL,"VWUFACTOR",True),VFFSL(SL,"VWUCODE",True),VFFSL(SL,"MWUFACTOR",True),VFFSL(SL,"MWUCODE",True)) # '$viewQuantity($WQ,$VWUFACTOR,$VWUCODE,$MWUFACTOR,$MWUCODE)' on line 10, col 23 if _v is not None: write(_filter(_v, rawExpr='$viewQuantity($WQ,$VWUFACTOR,$VWUCODE,$MWUFACTOR,$MWUCODE)')) # from line 10, col 23. write(''' (<b><u>''') _orig_filter_53834588 = _filter filterName = 'Quantity' if self._CHEETAH__filters.has_key("Quantity"): _filter = self._CHEETAH__currentFilter = self._CHEETAH__filters[filterName] else: _filter = self._CHEETAH__currentFilter = \ self._CHEETAH__filters[filterName] = getattr(self._CHEETAH__filtersLib, filterName)(self).filter _v = VFFSL(SL,"WQ",True) # '$WQ' on line 10, col 105 if _v is not None: write(_filter(_v, rawExpr='$WQ')) # from line 10, col 105. _filter = _orig_filter_53834588 write('''</u></b>)<br> ''') _v = VFFSL(SL,"TimeStampToDate",False)(VFFSL(SL,"PRODUCTDATE",True)) # '$TimeStampToDate($PRODUCTDATE)' on line 11, col 5 if _v is not None: write(_filter(_v, rawExpr='$TimeStampToDate($PRODUCTDATE)')) # from line 11, col 5. write(''' - ''') _v = VFFSL(SL,"TimeStampToDate",False)(VFFSL(SL,"BESTBEFOREDATE",True)) # '$TimeStampToDate($BESTBEFOREDATE)' on line 11, col 38 if _v is not None: write(_filter(_v, rawExpr='$TimeStampToDate($BESTBEFOREDATE)')) # from line 11, col 38. write(''' <hr> ''') if VFFSL(SL,"varExists",False)('$FeatureId'): # generated from line 14, col 5 if VFFSL(SL,"varExists",False)('$PFID'): # generated from line 15, col 9 write(''' <form action="uvPalletFPCreate" id=frm> <input type="hidden" name="barcode1" value="''') _v = VFFSL(SL,"barcode",True) # '$barcode' on line 17, col 61 if _v is not None: write(_filter(_v, rawExpr='$barcode')) # from line 17, col 61. write('''"> <input type="hidden" name="dt" value="''') _v = VFFSL(SL,"dbCurrentTimestamp",False)() # '$dbCurrentTimestamp()' on line 18, col 55 if _v is not None: write(_filter(_v, rawExpr='$dbCurrentTimestamp()')) # from line 18, col 55. write('''"> <input type="hidden" name="featureid" value="''') _v = VFFSL(SL,"PFID",True) # '$PFID' on line 19, col 62 if _v is not None: write(_filter(_v, rawExpr='$PFID')) # from line 19, col 62. write('''"> <a href="wpMain?barcode=''') _v = VFFSL(SL,"barcode",True) # '$barcode' on line 20, col 41 if _v is not None: write(_filter(_v, rawExpr='$barcode')) # from line 20, col 41. write('''">''') _v = VFFSL(SL,"PFNAME",True) # '$PFNAME' on line 20, col 51 if _v is not None: write(_filter(_v, rawExpr='$PFNAME')) # from line 20, col 51. write('''</a><br> ''') if False: _('Количество') _v = VFFSL(SL,"_",False)('Количество') # "$_('\xca\xee\xeb\xe8\xf7\xe5\xf1\xf2\xe2\xee')" on line 21, col 17 if _v is not None: write(_filter(_v, rawExpr="$_('\xca\xee\xeb\xe8\xf7\xe5\xf1\xf2\xe2\xee')")) # from line 21, col 17. write(''': <input type=text id="::int" size=4 name=q value="''') _orig_filter_33690919 = _filter filterName = 'Quantity' if self._CHEETAH__filters.has_key("Quantity"): _filter = self._CHEETAH__currentFilter = self._CHEETAH__filters[filterName] else: _filter = self._CHEETAH__currentFilter = \ self._CHEETAH__filters[filterName] = getattr(self._CHEETAH__filtersLib, filterName)(self).filter _v = VFFSL(SL,"WQ",True) # '$WQ' on line 21, col 100 if _v is not None: write(_filter(_v, rawExpr='$WQ')) # from line 21, col 100. _filter = _orig_filter_33690919 write('''"/><b>''') _v = VFFSL(SL,"MWUCODE",True) # '$MWUCODE' on line 21, col 121 if _v is not None: write(_filter(_v, rawExpr='$MWUCODE')) # from line 21, col 121. write('''</b><br> ''') if False: _('ШК паллета для создания') _v = VFFSL(SL,"_",False)('ШК паллета для создания') # "$_('\xd8\xca \xef\xe0\xeb\xeb\xe5\xf2\xe0 \xe4\xeb\xff \xf1\xee\xe7\xe4\xe0\xed\xe8\xff')" on line 22, col 17 if _v is not None: write(_filter(_v, rawExpr="$_('\xd8\xca \xef\xe0\xeb\xeb\xe5\xf2\xe0 \xe4\xeb\xff \xf1\xee\xe7\xe4\xe0\xed\xe8\xff')")) # from line 22, col 17. write(''': <input type="text" id=":scan:text" name="barcode2" value=""><br> <button type="submit">OK</button> </form> ''') elif VFFSL(SL,"varExists",False)('$datalist'): # generated from line 25, col 9 for item in VFFSL(SL,"datalist",True): # generated from line 26, col 13 write(''' <a href="wpMain?barcode=''') _v = VFFSL(SL,"barcode",True) # '$barcode' on line 27, col 41 if _v is not None: write(_filter(_v, rawExpr='$barcode')) # from line 27, col 41. write('''&featureid=''') _v = VFFSL(SL,"item.PFID",True) # '$item.PFID' on line 27, col 60 if _v is not None: write(_filter(_v, rawExpr='$item.PFID')) # from line 27, col 60. write('''">''') _v = VFFSL(SL,"item.PFNAME",True) # '$item.PFNAME' on line 27, col 72 if _v is not None: write(_filter(_v, rawExpr='$item.PFNAME')) # from line 27, col 72. write('''</a><br><br> ''') write(''' ''') ######################################## ## END - generated method body return _dummyTrans and trans.response().getvalue() or "" def writeBody(self, **KWS): ## CHEETAH: main method generated for this template trans = KWS.get("trans") if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)): trans = self.transaction # is None unless self.awake() was called if not trans: trans = DummyTransaction() _dummyTrans = True else: _dummyTrans = False write = trans.response().write SL = self._CHEETAH__searchList _filter = self._CHEETAH__currentFilter ######################################## ## START - generated method body write(''' ''') ######################################## ## END - generated method body return _dummyTrans and trans.response().getvalue() or "" ################################################## ## CHEETAH GENERATED ATTRIBUTES _CHEETAH__instanceInitialized = False _CHEETAH_version = __CHEETAH_version__ _CHEETAH_versionTuple = __CHEETAH_versionTuple__ _CHEETAH_genTime = __CHEETAH_genTime__ _CHEETAH_genTimestamp = __CHEETAH_genTimestamp__ _CHEETAH_src = __CHEETAH_src__ _CHEETAH_srcLastModified = __CHEETAH_srcLastModified__ _mainCheetahMethod_for_palletFPCreate= 'writeBody' ## END CLASS DEFINITION if not hasattr(palletFPCreate, '_initCheetahAttributes'): templateAPIClass = getattr(palletFPCreate, '_CHEETAH_templateClass', Template) templateAPIClass._addCheetahPlumbingCodeToClass(palletFPCreate) # CHEETAH was developed by Tavis Rudd and Mike Orr # with code, advice and input from many other volunteers. # For more information visit http://www.CheetahTemplate.org/ ################################################## ## if run from command line: if __name__ == '__main__': from Cheetah.TemplateCmdLineIface import CmdLineIface CmdLineIface(templateObj=palletFPCreate()).run()
[ "s.shybkoi@gmail.com" ]
s.shybkoi@gmail.com
8001b985f8965b283ee6356038f2c6f1b6497c22
8c45b2078b7a057e84c0411c4e5dea514bddd4c9
/jobrani1.py
4296b1ee7c5594423c7d42120a564ca3633c3aaa
[]
no_license
zmohammadi4852/solve-sudoku
98a63af5f3c6996fbb1e70aa8c98209a0effcdd4
aaa3954d550b528017c7e41ade189d5528e52b9e
refs/heads/master
2020-04-11T12:27:02.303770
2018-12-15T15:56:10
2018-12-15T15:56:10
161,780,744
1
0
null
null
null
null
UTF-8
Python
false
false
331
py
import numpy as np mat=np.matrix([[0,0,0,1],[1,0,1,1],[1,0,0,1],[0,0,1,0]]) n=int(input("number=")) def function(mat,i): for j in range(1,i): mat*=mat return mat result=np.matrix([[0,0,0,1],[1,0,1,1],[1,0,0,1],[0,0,1,0]]) for i in range(2,n+1): multiply=function(mat,i) result=result+multiply print(result)
[ "zmohammadi4852@chmail.ir" ]
zmohammadi4852@chmail.ir
dfa36a8a1cc93a46d476322d69d89592f68a9383
89db268a81314a97d5033405a01a0ffe41749e07
/beamline/upload-tag-refrun-diffuser8.py
3b23eb2699dfdddf222b16e6b45f6f38ec7ff57c
[]
no_license
durgarajaram/db-pyutils
6e3b567a12c04fb86f5f1b5737224736e03dbeff
2b338aef8de7901cdf95463bb9603b8a68f4ace5
refs/heads/master
2020-03-24T18:12:34.630738
2018-07-30T23:52:09
2018-07-30T23:52:09
142,886,442
0
0
null
null
null
null
UTF-8
Python
false
false
1,549
py
import cdb from cdb import BeamlineSuperMouse ########## MASTER CDB _MASTER_CDB = "http://172.16.246.25:8080" _BL = BeamlineSuperMouse(_MASTER_CDB) ########## PREPROD CDB #_PREPROD_CDB = "http://preprodcdb.mice.rl.ac.uk" #_BL = BeamlineSuperMouse(_PREPROD_CDB) bl_list_tags = sorted(_BL.list_tags()) print "list of existing settings" for tag in bl_list_tags: print " ", tag print "press <CR> to continue" raw_input() ############################################################## _TAG = 'Diff4Closed-PionReference-DS' if _TAG in bl_list_tags: print "Found", _TAG, "in tag list - press <CR> to continue" raw_input() _tag_data = {} _tag_data["proton_absorber_thickness"] = 29 _tag_data["diffuser_thickness"] = 8 _tag_data["beam_stop"] = "Open" _magnet_data = [\ {'name': 'Q1', 'current': 67.9}, \ {'name': 'Q2', 'current': 84.9}, \ {'name': 'Q3', 'current': 59.0}, \ {'name': 'D1', 'current': 203.0}, \ {'name': 'DS', 'current': 443.1}, \ {'name': 'D2', 'current': 104.8}, \ {'name': 'Q4', 'current': 176.8}, \ {'name': 'Q5', 'current': 237.1}, \ {'name': 'Q6', 'current': 157.2}, \ {'name': 'Q7', 'current': 157.6}, \ {'name': 'Q8', 'current': 238.5}, \ {'name': 'Q9', 'current': 203.7} \ ] print '+++++ SETTING TAG on CDB MASTER', _TAG, _tag_data, _magnet_data _BL.set_beamline_tag(_TAG, _tag_data, _magnet_data) print '++++++++++++++++++ READING BACK TAG FROM CDB', _TAG print _BL.get_beamline_for_tag(_TAG) ##############################################################
[ "durga@fermice1.fnal.gov" ]
durga@fermice1.fnal.gov
f54830fa4daddb3af4735e5c90a7dcacbfc02bdc
02ee8eb91c13123402900609ec559007617176c8
/rubik_solver/Solver/Kociemba/Search.py
198d4a995f2ef9fcdf3783024c746ae72dcde42f
[ "MIT" ]
permissive
ani4aniket/one-api-rubik-solver
990fcb855875e5faf6684fea3d45bb7afe08cf23
5a8948ef874ce6082f5ceec9898074d80b0048dc
refs/heads/master
2023-03-05T03:28:09.482446
2021-02-21T12:17:37
2021-02-21T12:17:37
340,858,446
0
1
MIT
2021-02-21T09:54:38
2021-02-21T09:01:45
Python
UTF-8
Python
false
false
14,418
py
__author__ = 'Victor' import time from rubik_solver.Enums import Color import rubik_solver.FaceCube as FaceCube import rubik_solver.CoordCube as CoordCube from rubik_solver.CubieCube import DupedEdge class DupedFacelet(Exception): pass class NoSolution(Exception): pass class SolverTimeoutError(Exception): pass class Search(object): ax = [0] * 31 # The axis of the move po = [0] * 31 # The power of the move flip = [0] * 31 # phase1 coordinates twist = [0] * 31 slice = [0] * 31 parity = [0] * 31 # phase2 coordinates URFtoDLF = [0] * 31 FRtoBR = [0] * 31 URtoUL = [0] * 31 UBtoDF = [0] * 31 URtoDF = [0] * 31 minDistPhase1 = [0] * 31 # IDA* distance do goal estimations minDistPhase2 = [0] * 31 # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # generate the solution string from the array data @staticmethod def solutionToString(length, depthPhase1=- 1): s = [] for i in range(length): step = '' if Search.ax[i] == 0: step = "U" elif Search.ax[i] == 1: step = "R" elif Search.ax[i] == 2: step = "F" elif Search.ax[i] == 3: step = "D" elif Search.ax[i] == 4: step = "L" elif Search.ax[i] == 5: step = "B" if Search.po[i] == 2: step += "2" elif Search.po[i] == 3: step += "'" if i == (depthPhase1 - 1): step = ". " s.append(step) return s @staticmethod def solution(facelets, maxDepth, timeOut, useSeparator=False): ''' * Computes the solver string for a given cube. * * @param facelets * is the cube definition string, see {@link Facelet} for the format. * * @param maxDepth * defines the maximal allowed maneuver length. For random cubes, a maxDepth of 21 usually will return a * solution in less than 0.5 seconds. With a maxDepth of 20 it takes a few seconds on average to find a * solution, but it may take much longer for specific cubes. * *@param timeOut * defines the maximum computing time of the method in seconds. If it does not return with a solution, it returns with * an error code. * * @param useSeparator * determines if a " . " separates the phase1 and phase2 parts of the solver string like in F' R B R L2 F . * U2 U D for example.<br> * @return The solution string or an error code:<br> * Error 1: There is not exactly one facelet of each colour<br> * Error 2: Not all 12 edges exist exactly once<br> * Error 3: Flip error: One edge has to be flipped<br> * Error 4: Not all corners exist exactly once<br> * Error 5: Twist error: One corner has to be twisted<br> * Error 6: Parity error: Two corners or two edges have to be exchanged<br> * Error 7: No solution exists for the given maxDepth<br> * Error 8: Timeout, no solution within given time ''' # +++++++++++++++++++++check for wrong input ++++++++++++++++++++++++++ count = [0] * 6 try: for i in range(54): count[getattr(Color, facelets[i])] += 1 except Exception as e: raise DupedFacelet( "There is not exactly one facelet of each colour") for i in range(6): if count[i] != 9: raise DupedEdge("Not all 12 edges exist exactly once") cc = FaceCube.FaceCube(facelets).toCubieCube() try: s = cc.verify() except Exception as e: raise e # +++++++++++++++++++++++ initialization ++++++++++++++++++++++++++++++ c = CoordCube.CoordCube(cc) Search.po[0] = 0 Search.ax[0] = 0 Search.flip[0] = c.flip Search.twist[0] = c.twist Search.parity[0] = c.parity Search.slice[0] = int(c.FRtoBR) // 24 Search.URFtoDLF[0] = c.URFtoDLF Search.FRtoBR[0] = c.FRtoBR Search.URtoUL[0] = c.URtoUL Search.UBtoDF[0] = c.UBtoDF Search.minDistPhase1[1] = 1 # else failure for depth=1, n=0 mv, n = 0, 0 busy = False depthPhase1 = 1 tStart = time.time() # +++++++++++++++++++ Main loop +++++++++++++++++++++++++++++++++++++++ while True: while True: if (depthPhase1 - n) > Search.minDistPhase1[n + 1] and not busy: if Search.ax[n] == 0 or Search.ax[n] == 3: # Initialize next move n += 1 Search.ax[n] = 1 else: n += 1 Search.ax[n] = 0 Search.po[n] = 1 else: Search.po[n] += 1 if Search.po[n] > 3: while True: Search.ax[n] += 1 if Search.ax[n] > 5: if time.time() - tStart > timeOut: raise SolverTimeoutError( "Timeout, no solution within given time") if n == 0: if depthPhase1 >= maxDepth: raise NoSolution( "No solution exists for the given maxDepth") else: depthPhase1 += 1 Search.ax[n] = 0 Search.po[n] = 1 busy = False break else: n -= 1 busy = True break else: Search.po[n] = 1 busy = False if not(n != 0 and (Search.ax[n - 1] == Search.ax[n] or Search.ax[n - 1] - 3 == Search.ax[n])): break else: busy = False if not busy: break # +++++++++++++ compute new coordinates and new minDistPhase1 +++++ # if minDistPhase1 =0, the H subgroup is reached mv = 3 * Search.ax[n] + Search.po[n] - 1 Search.flip[n + 1] = CoordCube.CoordCube.flipMove[Search.flip[n]][mv] Search.twist[n + 1] = CoordCube.CoordCube.twistMove[Search.twist[n]][mv] Search.slice[n + 1] = CoordCube.CoordCube.FRtoBR_Move[Search.slice[n] * 24][mv] // 24 Search.minDistPhase1[n + 1] = max( CoordCube.CoordCube.getPruning( CoordCube.CoordCube.Slice_Flip_Prun, CoordCube.CoordCube.N_SLICE1 * Search.flip[n + 1] + Search.slice[n + 1]), CoordCube.CoordCube.getPruning( CoordCube.CoordCube.Slice_Twist_Prun, CoordCube.CoordCube.N_SLICE1 * Search.twist[n + 1] + Search.slice[n + 1]) ) # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ if Search.minDistPhase1[n + 1] == 0 and n >= (depthPhase1 - 5): # instead of 10 any value >5 is possible Search.minDistPhase1[n + 1] = 10 if n == (depthPhase1 - 1): s = Search.totalDepth(depthPhase1, maxDepth) if s >= 0: if s == depthPhase1 or (Search.ax[depthPhase1 - 1] != Search.ax[depthPhase1] and Search.ax[depthPhase1 - 1] != Search.ax[depthPhase1] + 3): return Search.solutionToString(s, depthPhase1 if useSeparator else -1) @staticmethod def totalDepthPhase2(depthPhase1, depthPhase2, maxDepthPhase2, n): busy = False while True: Search.ax[n] += 1 if Search.ax[n] > 5: if n == depthPhase1: if depthPhase2 >= maxDepthPhase2: return False, busy, n, depthPhase2 else: depthPhase2 += 1 Search.ax[n] = 0 Search.po[n] = 1 busy = False break else: n -= 1 busy = True break else: if Search.ax[n] == 0 or Search.ax[n] == 3: Search.po[n] = 1 else: Search.po[n] = 2 busy = False if not (n != depthPhase1 and (Search.ax[n - 1] == Search.ax[n] or (Search.ax[n - 1]) - 3 == Search.ax[n])): break return True, busy, n, depthPhase2 # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # Apply phase2 of algorithm and return the combined phase1 and phase2 depth. In phase2, only the moves # U,D,R2,F2,L2 and B2 are allowed. @staticmethod def totalDepth(depthPhase1, maxDepth): mv, d1, d2 = 0, 0, 0 # Allow only max 10 moves in phase2 maxDepthPhase2 = min(10, maxDepth - depthPhase1) for i in range(depthPhase1): mv = 3 * Search.ax[i] + Search.po[i] - 1 Search.URFtoDLF[i + 1] = CoordCube.CoordCube.URFtoDLF_Move[Search.URFtoDLF[i]][mv] Search.FRtoBR[i + 1] = CoordCube.CoordCube.FRtoBR_Move[Search.FRtoBR[i]][mv] Search.parity[i + 1] = CoordCube.CoordCube.parityMove[Search.parity[i]][mv] d1 = CoordCube.CoordCube.getPruning( CoordCube.CoordCube.Slice_URFtoDLF_Parity_Prun, (CoordCube.CoordCube.N_SLICE2 * Search.URFtoDLF[depthPhase1] + Search.FRtoBR[depthPhase1]) * 2 + Search.parity[depthPhase1] ) if d1 > maxDepthPhase2: return -1 for i in range(depthPhase1): mv = 3 * Search.ax[i] + Search.po[i] - 1 Search.URtoUL[i + 1] = CoordCube.CoordCube.URtoUL_Move[Search.URtoUL[i]][mv] Search.UBtoDF[i + 1] = CoordCube.CoordCube.UBtoDF_Move[Search.UBtoDF[i]][mv] Search.URtoDF[depthPhase1] = CoordCube.CoordCube.MergeURtoULandUBtoDF[Search.URtoUL[depthPhase1] ][Search.UBtoDF[depthPhase1]] d2 = CoordCube.CoordCube.getPruning( CoordCube.CoordCube.Slice_URtoDF_Parity_Prun, (CoordCube.CoordCube.N_SLICE2 * Search.URtoDF[depthPhase1] + Search.FRtoBR[depthPhase1]) * 2 + Search.parity[depthPhase1] ) if d2 > maxDepthPhase2: return -1 Search.minDistPhase2[depthPhase1] = max(d1, d2) if Search.minDistPhase2[depthPhase1] == 0: # already solved return depthPhase1 # now set up search depthPhase2 = 1 n = depthPhase1 busy = False Search.po[depthPhase1] = 0 Search.ax[depthPhase1] = 0 Search.minDistPhase2[n + 1] = 1 # else failure for depthPhase2=1, n=0 # +++++++++++++++++++ end initialization ++++++++++++++++++++++++++++++ while True: while True: if (depthPhase1 + depthPhase2 - n) > (Search.minDistPhase2[n + 1]) and not busy: if Search.ax[n] == 0 or Search.ax[n] == 3: # Initialize next move n += 1 Search.ax[n] = 1 Search.po[n] = 2 else: n += 1 Search.ax[n] = 0 Search.po[n] = 1 else: execWhile = False if Search.ax[n] == 0 or Search.ax[n] == 3: Search.po[n] += 1 if Search.po[n] > 3: execWhile = True else: Search.po[n] += 2 if Search.po[n] > 3: execWhile = True if execWhile: keep_working, busy, n, depthPhase2 = Search.totalDepthPhase2(depthPhase1, depthPhase2, maxDepthPhase2, n) if not keep_working: return -1 else: busy = False if not busy: break # +++++++++++++ compute new coordinates and new minDist ++++++++++ mv = 3 * Search.ax[n] + Search.po[n] - 1 Search.URFtoDLF[n + 1] = CoordCube.CoordCube.URFtoDLF_Move[Search.URFtoDLF[n]][mv] Search.FRtoBR[n + 1] = CoordCube.CoordCube.FRtoBR_Move[Search.FRtoBR[n]][mv] Search.parity[n + 1] = CoordCube.CoordCube.parityMove[Search.parity[n]][mv] Search.URtoDF[n + 1] = CoordCube.CoordCube.URtoDF_Move[Search.URtoDF[n]][mv] Search.minDistPhase2[n + 1] = max( CoordCube.CoordCube.getPruning( CoordCube.CoordCube.Slice_URtoDF_Parity_Prun, (CoordCube.CoordCube.N_SLICE2 * Search.URtoDF[n + 1] + Search.FRtoBR[n + 1]) * 2 + Search.parity[n + 1]), CoordCube.CoordCube.getPruning( CoordCube.CoordCube.Slice_URFtoDLF_Parity_Prun, (CoordCube.CoordCube.N_SLICE2 * Search.URFtoDLF[n + 1] + Search.FRtoBR[n + 1]) * 2 + Search.parity[n + 1] ) ) # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ if Search.minDistPhase2[n + 1] == 0: break return depthPhase1 + depthPhase2
[ "u62316@s001-n001.aidevcloud" ]
u62316@s001-n001.aidevcloud
c38eebff02f12b1749be0fd139a0bc6ebc93b2c9
3a3a8b1ee8eb4a39d7ae1da53d8f815c9bb2ced8
/packs/forensics/actions/hash-identify.py
90876102f1d4ebc176351566238dfcbb2fd943d5
[]
no_license
RandomsCTF/stackstorm-forensics
727d52cedad829f088274c981d5affecce900dc0
df16306a112a8a6ffb4744c963803389e8e1f1be
refs/heads/master
2016-09-06T02:33:34.057287
2015-11-04T12:22:48
2015-11-04T12:22:48
42,409,399
8
2
null
2015-09-14T18:10:50
2015-09-13T19:20:58
Python
UTF-8
Python
false
false
260
py
#!/usr/bin/python from lib.hashtag import identify_hash from st2actions.runners.pythonrunner import Action __all__ = [ 'HashIdentifyAction', ] class HashIdentifyAction(Action): def run(self, hash): return ", ".join(identify_hash(hash)[:3])
[ "edward.medvedev@gmail.com" ]
edward.medvedev@gmail.com
1be68602f2c4a11597c9cdba1ed45d0553d2390c
5c71b930bb07c172b485e40c555dff5651602cdc
/websocket.py
e5f57f12b36a9895551dc3226367cb2ccf48ee74
[]
no_license
playsten4096/iqoption_api
e628efee5336cf9bec5db3f85e16ab4d346feaa4
ff8002a358a815a7cc03a5c92b64eb861facfaf1
refs/heads/master
2021-01-22T14:49:23.208816
2016-08-01T03:05:12
2016-08-01T03:05:12
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,242
py
# -*- coding: utf-8 -*- """Module for IQ option websocket.""" import json import logging from ws4py.client.threadedclient import WebSocketClient class Websocket(WebSocketClient): """Class for work with IQ option websocket.""" def __init__(self, url, protocols=None, extensions=None, heartbeat_freq=None, ssl_options=None, headers=None): # pylint: disable=too-many-arguments super(Websocket, self).__init__(url, protocols, extensions, heartbeat_freq, ssl_options, headers) self.message = None self.time = None self.show_value = None def received_message(self, message): """ Catch all incoming websocket messages. :param str message: Incoming websocket message. :returns: Incoming message, converted to json or None. """ logger = logging.getLogger(__name__) logger.debug(message) if message: self.message = json.loads(str(message)) # return self.message if self.message["name"] == "newChartData": self.time = self.message["msg"]["time"] self.show_value = self.message["msg"]["show_value"]
[ "Alexander Skiridomov" ]
Alexander Skiridomov
7854334959bac1ebe9ac48c0d8040972147f2819
75d9f347e3e0277777c63bd3c9e020f2d9e51598
/Implemantation/ticketsystem/ticketsystem/wsgi.py
6e032451c0fd2ea39b8450cefb891f172ccba748
[]
no_license
mertmisirlioglu/onlineticketsystem
57c1b60698dffd6c4dc5a99978e501987a8ec899
991db0fa5733b71eff86cc9b0a97a20c6a6a817c
refs/heads/master
2020-08-19T09:26:28.711707
2020-01-17T05:07:02
2020-01-17T05:07:02
215,904,512
0
1
null
2020-01-17T03:33:02
2019-10-17T23:41:53
HTML
UTF-8
Python
false
false
401
py
""" WSGI config for ticketsystem 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/2.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ticketsystem.settings') application = get_wsgi_application()
[ "mertmisirlioglu@gmail.com" ]
mertmisirlioglu@gmail.com
91b6976f97719589bd507150f4b13a4685106b55
54bc647b3789dd8b5f63948f8cf60f656352e971
/Unique_Paths.py
710dcd1c53ef57c878033d6faeaae293137c9dbe
[]
no_license
cutewindy/Leetcode
37911ce46a2ded90d9114dca80875b726c965d24
01ffb610692078637a91563e0974291337faa2c0
refs/heads/master
2021-01-22T12:12:27.449790
2015-06-10T12:17:56
2015-06-10T12:17:56
35,147,266
2
0
null
null
null
null
UTF-8
Python
false
false
676
py
# A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). # # The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). # # How many possible unique paths are there? def uniquePaths(m, n): cnt = [[1] for i in range(m)] for i in range(1, n): cnt[0].append(1) for i in range(1, m): for j in range(1, n): cnt[i].append(cnt[i][j-1] + cnt[i-1][j]) return cnt, cnt[m-1][n-1] print uniquePaths(2, 2) print uniquePaths(3, 3) print uniquePaths(4, 5) print uniquePaths(5, 4)
[ "wengwendi@gmail.com" ]
wengwendi@gmail.com
929f9c62dc239284ea660a83c74694b12e148494
2aba62d66c2c622bdc148cef451da76cae5fd76c
/exercise/crawler_python_dm1920/ch4/ch4_19.py
5dc74250957efd13c6fc8b6557fdcafa5be35fb0
[]
no_license
NTUT-109AB8011/crawler
6a76de2ab1848ebc8365e071e76c08ca7348be62
a703ec741b48d3af615a757fed7607b1f8eb66a6
refs/heads/master
2023-03-26T22:39:59.527175
2021-03-30T03:29:22
2021-03-30T03:29:22
null
0
0
null
null
null
null
UTF-8
Python
false
false
815
py
# ch4_19.py import pandas as pd import matplotlib.pyplot as plt cities = {'population':[10000000,8500000,8000000,15000000,6000000,8000000], 'area':[400, 500, 850, 300, 200, 320], 'town':['New York','Chicago','Bangkok','Tokyo', 'Singapore','HongKong']} tw = pd.DataFrame(cities, columns=['population','area'],index=cities['town']) fig, ax = plt.subplots() fig.suptitle("City Statistics") ax.set_ylabel("Population") ax.set_xlabel("City") ax2 = ax.twinx() ax2.set_ylabel("Area") tw['population'].plot(ax=ax,rot=90) # 繪製人口數線 tw['area'].plot(ax=ax2, style='g-') # 繪製面積線 ax.legend(loc=1) # 圖例位置在右上 ax2.legend(loc=2) # 圖例位置在左上 plt.show()
[ "terranandes@gmail.com" ]
terranandes@gmail.com
b44921e00185d8adba5646cfedfbd7c1c4b4164a
9520afa35bd0fde379d2de327b04e8d85d1130fb
/uiBasicWidget.py
c91253b8466ef49e16d497100ebb714d02b4efa4
[]
no_license
heber/huice
19d1013fc678eb1293635e4cbd37c14ab58d7c30
0a4d6af7e6ad527c662f67133299f4d52d10f0bd
refs/heads/master
2020-09-17T03:52:46.431199
2019-07-20T02:28:12
2019-07-20T02:28:12
null
0
0
null
null
null
null
UTF-8
Python
false
false
53,204
py
# encoding: UTF-8 import json import csv import os import platform from collections import OrderedDict from six import text_type from event import * from vtEvent import * from vtFunction import * from vtGateway import * import vtText from uiQt import QtGui, QtWidgets, QtCore, BASIC_FONT from vtFunction import jsonPathDict from vtConstant import * COLOR_RED = QtGui.QColor('red') COLOR_GREEN = QtGui.QColor('green') ######################################################################## class BasicCell(QtWidgets.QTableWidgetItem): """基础的单元格""" #---------------------------------------------------------------------- def __init__(self, text=None, mainEngine=None): """Constructor""" super(BasicCell, self).__init__() self.data = None if text: self.setContent(text) #---------------------------------------------------------------------- def setContent(self, text): """设置内容""" if text == '0' or text == '0.0': self.setText('') else: self.setText(text) ######################################################################## class NumCell(QtWidgets.QTableWidgetItem): """用来显示数字的单元格""" #---------------------------------------------------------------------- def __init__(self, text=None, mainEngine=None): """Constructor""" super(NumCell, self).__init__() self.data = None if text: self.setContent(text) #---------------------------------------------------------------------- def setContent(self, text): """设置内容""" # 考虑到NumCell主要用来显示OrderID和TradeID之类的整数字段, # 这里的数据转化方式使用int类型。但是由于部分交易接口的委托 # 号和成交号可能不是纯数字的形式,因此补充了一个try...except try: num = int(text) self.setData(QtCore.Qt.DisplayRole, num) except ValueError: self.setText(text) ######################################################################## class DirectionCell(QtWidgets.QTableWidgetItem): """用来显示买卖方向的单元格""" #---------------------------------------------------------------------- def __init__(self, text=None, mainEngine=None): """Constructor""" super(DirectionCell, self).__init__() self.data = None if text: self.setContent(text) #---------------------------------------------------------------------- def setContent(self, text): """设置内容""" if text == DIRECTION_LONG or text == DIRECTION_NET: self.setForeground(QtGui.QColor('red')) elif text == DIRECTION_SHORT: self.setForeground(QtGui.QColor('green')) self.setText(text) ######################################################################## class NameCell(QtWidgets.QTableWidgetItem): """用来显示合约中文的单元格""" #---------------------------------------------------------------------- def __init__(self, text=None, mainEngine=None): """Constructor""" super(NameCell, self).__init__() self.mainEngine = mainEngine self.data = None if text: self.setContent(text) #---------------------------------------------------------------------- def setContent(self, text): """设置内容""" if self.mainEngine: # 首先尝试正常获取合约对象 contract = self.mainEngine.getContract(text) # 如果能读取合约信息 if contract: self.setText(contract.name) ######################################################################## class BidCell(QtWidgets.QTableWidgetItem): """买价单元格""" #---------------------------------------------------------------------- def __init__(self, text=None, mainEngine=None): """Constructor""" super(BidCell, self).__init__() self.data = None self.setForeground(QtGui.QColor('black')) self.setBackground(QtGui.QColor(255,174,201)) if text: self.setContent(text) #---------------------------------------------------------------------- def setContent(self, text): """设置内容""" self.setText(text) ######################################################################## class AskCell(QtWidgets.QTableWidgetItem): """卖价单元格""" #---------------------------------------------------------------------- def __init__(self, text=None, mainEngine=None): """Constructor""" super(AskCell, self).__init__() self.data = None self.setForeground(QtGui.QColor('black')) self.setBackground(QtGui.QColor(160,255,160)) if text: self.setContent(text) #---------------------------------------------------------------------- def setContent(self, text): """设置内容""" self.setText(text) ######################################################################## class PnlCell(QtWidgets.QTableWidgetItem): """显示盈亏的单元格""" #---------------------------------------------------------------------- def __init__(self, text=None, mainEngine=None): """Constructor""" super(PnlCell, self).__init__() self.data = None self.color = '' if text: self.setContent(text) #---------------------------------------------------------------------- def setContent(self, text): """设置内容""" self.setText(text) try: value = float(text) if value >= 0 and self.color != 'red': self.color = 'red' self.setForeground(COLOR_RED) elif value < 0 and self.color != 'green': self.color = 'green' self.setForeground(COLOR_GREEN) except ValueError: pass ######################################################################## class BasicMonitor(QtWidgets.QTableWidget): """ 基础监控 headerDict中的值对应的字典格式如下 {'chinese': u'中文名', 'cellType': BasicCell} """ signal = QtCore.Signal(type(Event())) #---------------------------------------------------------------------- def __init__(self, mainEngine=None, eventEngine=None, parent=None): """Constructor""" super(BasicMonitor, self).__init__(parent) self.mainEngine = mainEngine self.eventEngine = eventEngine # 保存表头标签用 self.headerDict = OrderedDict() # 有序字典,key是英文名,value是对应的配置字典 self.headerList = [] # 对应self.headerDict.keys() # 保存相关数据用 self.dataDict = {} # 字典,key是字段对应的数据,value是保存相关单元格的字典 self.dataKey = '' # 字典键对应的数据字段 # 监控的事件类型 self.eventType = '' # 列宽调整状态(只在第一次更新数据时调整一次列宽) self.columnResized = False # 字体 self.font = None # 保存数据对象到单元格 self.saveData = False # 默认不允许根据表头进行排序,需要的组件可以开启 self.sorting = False # 初始化右键菜单 self.initMenu() #---------------------------------------------------------------------- def setHeaderDict(self, headerDict): """设置表头有序字典""" self.headerDict = headerDict self.headerList = headerDict.keys() #---------------------------------------------------------------------- def setDataKey(self, dataKey): """设置数据字典的键""" self.dataKey = dataKey #---------------------------------------------------------------------- def setEventType(self, eventType): """设置监控的事件类型""" self.eventType = eventType #---------------------------------------------------------------------- def setFont(self, font): """设置字体""" self.font = font #---------------------------------------------------------------------- def setSaveData(self, saveData): """设置是否要保存数据到单元格""" self.saveData = saveData #---------------------------------------------------------------------- def initTable(self): """初始化表格""" # 设置表格的列数 col = len(self.headerDict) self.setColumnCount(col) # 设置列表头 labels = [d['chinese'] for d in self.headerDict.values()] self.setHorizontalHeaderLabels(labels) # 关闭左边的垂直表头 self.verticalHeader().setVisible(False) # 设为不可编辑 self.setEditTriggers(self.NoEditTriggers) # 设为行交替颜色 self.setAlternatingRowColors(True) # 设置允许排序 self.setSortingEnabled(self.sorting) #---------------------------------------------------------------------- def registerEvent(self): """注册GUI更新相关的事件监听""" self.signal.connect(self.updateEvent) self.eventEngine.register(self.eventType, self.signal.emit) #---------------------------------------------------------------------- def updateEvent(self, event): """收到事件更新""" data = event.dict_['data'] self.updateData(data) #---------------------------------------------------------------------- def updateData(self, data): """将数据更新到表格中""" # 如果允许了排序功能,则插入数据前必须关闭,否则插入新的数据会变乱 if self.sorting: self.setSortingEnabled(False) # 如果设置了dataKey,则采用存量更新模式 if self.dataKey: key = data.__getattribute__(self.dataKey) # 如果键在数据字典中不存在,则先插入新的一行,并创建对应单元格 if key not in self.dataDict: self.insertRow(0) d = {} for n, header in enumerate(self.headerList): content = safeUnicode(data.__getattribute__(header)) cellType = self.headerDict[header]['cellType'] cell = cellType(content, self.mainEngine) if self.font: cell.setFont(self.font) # 如果设置了特殊字体,则进行单元格设置 if self.saveData: # 如果设置了保存数据对象,则进行对象保存 cell.data = data self.setItem(0, n, cell) d[header] = cell self.dataDict[key] = d # 否则如果已经存在,则直接更新相关单元格 else: d = self.dataDict[key] for header in self.headerList: content = safeUnicode(data.__getattribute__(header)) cell = d[header] cell.setContent(content) if self.saveData: # 如果设置了保存数据对象,则进行对象保存 cell.data = data # 否则采用增量更新模式 else: self.insertRow(0) for n, header in enumerate(self.headerList): content = safeUnicode(data.__getattribute__(header)) cellType = self.headerDict[header]['cellType'] cell = cellType(content, self.mainEngine) if self.font: cell.setFont(self.font) if self.saveData: cell.data = data self.setItem(0, n, cell) # 调整列宽 if not self.columnResized: self.resizeColumns() self.columnResized = True # 重新打开排序 if self.sorting: self.setSortingEnabled(True) #---------------------------------------------------------------------- def resizeColumns(self): """调整各列的大小""" self.horizontalHeader().resizeSections(QtWidgets.QHeaderView.ResizeToContents) #---------------------------------------------------------------------- def setSorting(self, sorting): """设置是否允许根据表头排序""" self.sorting = sorting #---------------------------------------------------------------------- def saveToCsv(self): """保存表格内容到CSV文件""" # 先隐藏右键菜单 self.menu.close() # 获取想要保存的文件名 path, fileType = QtWidgets.QFileDialog.getSaveFileName(self, vtText.SAVE_DATA, '', 'CSV(*.csv)') try: #if not path.isEmpty(): if path: with open(unicode(path), 'wb') as f: writer = csv.writer(f) # 保存标签 headers = [header.encode('gbk') for header in self.headerList] writer.writerow(headers) # 保存每行内容 for row in range(self.rowCount()): rowdata = [] for column in range(self.columnCount()): item = self.item(row, column) if item is not None: rowdata.append( text_type(item.text()).encode('gbk')) else: rowdata.append('') writer.writerow(rowdata) except IOError: pass #---------------------------------------------------------------------- def initMenu(self): """初始化右键菜单""" self.menu = QtWidgets.QMenu(self) resizeAction = QtWidgets.QAction(vtText.RESIZE_COLUMNS, self) resizeAction.triggered.connect(self.resizeColumns) saveAction = QtWidgets.QAction(vtText.SAVE_DATA, self) saveAction.triggered.connect(self.saveToCsv) self.menu.addAction(resizeAction) self.menu.addAction(saveAction) #---------------------------------------------------------------------- def contextMenuEvent(self, event): """右键点击事件""" self.menu.popup(QtGui.QCursor.pos()) ######################################################################## class MarketMonitor(BasicMonitor): """市场监控组件""" #---------------------------------------------------------------------- def __init__(self, mainEngine, eventEngine, parent=None): """Constructor""" super(MarketMonitor, self).__init__(mainEngine, eventEngine, parent) # 设置表头有序字典 d = OrderedDict() d['symbol'] = {'chinese':vtText.CONTRACT_SYMBOL, 'cellType':BasicCell} d['vtSymbol'] = {'chinese':vtText.CONTRACT_NAME, 'cellType':NameCell} d['lastPrice'] = {'chinese':vtText.LAST_PRICE, 'cellType':BasicCell} d['preClosePrice'] = {'chinese':vtText.PRE_CLOSE_PRICE, 'cellType':BasicCell} d['volume'] = {'chinese':vtText.VOLUME, 'cellType':BasicCell} d['openInterest'] = {'chinese':vtText.OPEN_INTEREST, 'cellType':BasicCell} d['openPrice'] = {'chinese':vtText.OPEN_PRICE, 'cellType':BasicCell} d['highPrice'] = {'chinese':vtText.HIGH_PRICE, 'cellType':BasicCell} d['lowPrice'] = {'chinese':vtText.LOW_PRICE, 'cellType':BasicCell} d['bidPrice1'] = {'chinese':vtText.BID_PRICE_1, 'cellType':BidCell} d['bidVolume1'] = {'chinese':vtText.BID_VOLUME_1, 'cellType':BidCell} d['askPrice1'] = {'chinese':vtText.ASK_PRICE_1, 'cellType':AskCell} d['askVolume1'] = {'chinese':vtText.ASK_VOLUME_1, 'cellType':AskCell} d['time'] = {'chinese':vtText.TIME, 'cellType':BasicCell} d['gatewayName'] = {'chinese':vtText.GATEWAY, 'cellType':BasicCell} self.setHeaderDict(d) # 设置数据键 self.setDataKey('vtSymbol') # 设置监控事件类型 self.setEventType(EVENT_TICK) # 设置字体 self.setFont(BASIC_FONT) # 设置排序 self.setSorting(False) # 初始化表格 self.initTable() # 注册事件监听 self.registerEvent() ######################################################################## class LogMonitor(BasicMonitor): """日志监控""" #---------------------------------------------------------------------- def __init__(self, mainEngine, eventEngine, parent=None): """Constructor""" super(LogMonitor, self).__init__(mainEngine, eventEngine, parent) d = OrderedDict() d['logTime'] = {'chinese':vtText.TIME, 'cellType':BasicCell} d['logContent'] = {'chinese':vtText.CONTENT, 'cellType':BasicCell} d['gatewayName'] = {'chinese':vtText.GATEWAY, 'cellType':BasicCell} self.setHeaderDict(d) self.setEventType(EVENT_LOG) self.setFont(BASIC_FONT) self.initTable() self.registerEvent() #---------------------------------------------------------------------- def updateData(self, data): """""" super(LogMonitor, self).updateData(data) self.resizeRowToContents(0) # 调整行高 ######################################################################## class ErrorMonitor(BasicMonitor): """错误监控""" #---------------------------------------------------------------------- def __init__(self, mainEngine, eventEngine, parent=None): """Constructor""" super(ErrorMonitor, self).__init__(mainEngine, eventEngine, parent) d = OrderedDict() d['errorTime'] = {'chinese':vtText.TIME, 'cellType':BasicCell} d['errorID'] = {'chinese':vtText.ERROR_CODE, 'cellType':BasicCell} d['errorMsg'] = {'chinese':vtText.ERROR_MESSAGE, 'cellType':BasicCell} d['gatewayName'] = {'chinese':vtText.GATEWAY, 'cellType':BasicCell} self.setHeaderDict(d) self.setEventType(EVENT_ERROR) self.setFont(BASIC_FONT) self.initTable() self.registerEvent() ######################################################################## class TradeMonitor(BasicMonitor): """成交监控""" #---------------------------------------------------------------------- def __init__(self, mainEngine, eventEngine, parent=None): """Constructor""" super(TradeMonitor, self).__init__(mainEngine, eventEngine, parent) d = OrderedDict() d['tradeID'] = {'chinese':vtText.TRADE_ID, 'cellType':NumCell} d['orderID'] = {'chinese':vtText.ORDER_ID, 'cellType':NumCell} d['symbol'] = {'chinese':vtText.CONTRACT_SYMBOL, 'cellType':BasicCell} d['vtSymbol'] = {'chinese':vtText.CONTRACT_NAME, 'cellType':NameCell} d['direction'] = {'chinese':vtText.DIRECTION, 'cellType':DirectionCell} d['offset'] = {'chinese':vtText.OFFSET, 'cellType':BasicCell} d['price'] = {'chinese':vtText.PRICE, 'cellType':BasicCell} d['volume'] = {'chinese':vtText.VOLUME, 'cellType':BasicCell} d['tradeTime'] = {'chinese':vtText.TRADE_TIME, 'cellType':BasicCell} d['gatewayName'] = {'chinese':vtText.GATEWAY, 'cellType':BasicCell} self.setHeaderDict(d) self.setEventType(EVENT_TRADE) self.setFont(BASIC_FONT) self.setSorting(True) self.initTable() self.registerEvent() ######################################################################## class OrderMonitor(BasicMonitor): """委托监控""" #---------------------------------------------------------------------- def __init__(self, mainEngine, eventEngine, parent=None): """Constructor""" super(OrderMonitor, self).__init__(mainEngine, eventEngine, parent) self.mainEngine = mainEngine d = OrderedDict() d['orderID'] = {'chinese':vtText.ORDER_ID, 'cellType':NumCell} d['symbol'] = {'chinese':vtText.CONTRACT_SYMBOL, 'cellType':BasicCell} d['vtSymbol'] = {'chinese':vtText.CONTRACT_NAME, 'cellType':NameCell} d['direction'] = {'chinese':vtText.DIRECTION, 'cellType':DirectionCell} d['offset'] = {'chinese':vtText.OFFSET, 'cellType':BasicCell} d['price'] = {'chinese':vtText.PRICE, 'cellType':BasicCell} d['totalVolume'] = {'chinese':vtText.ORDER_VOLUME, 'cellType':BasicCell} d['tradedVolume'] = {'chinese':vtText.TRADED_VOLUME, 'cellType':BasicCell} d['status'] = {'chinese':vtText.ORDER_STATUS, 'cellType':BasicCell} d['orderTime'] = {'chinese':vtText.ORDER_TIME, 'cellType':BasicCell} d['cancelTime'] = {'chinese':vtText.CANCEL_TIME, 'cellType':BasicCell} #d['frontID'] = {'chinese':vtText.FRONT_ID, 'cellType':BasicCell} # 考虑到在vn.trader中,ctpGateway的报单号应该是始终递增的,因此这里可以忽略 #d['sessionID'] = {'chinese':vtText.SESSION_ID, 'cellType':BasicCell} d['gatewayName'] = {'chinese':vtText.GATEWAY, 'cellType':BasicCell} self.setHeaderDict(d) self.setDataKey('vtOrderID') self.setEventType(EVENT_ORDER) self.setFont(BASIC_FONT) self.setSaveData(True) self.setSorting(True) self.initTable() self.registerEvent() self.connectSignal() #---------------------------------------------------------------------- def connectSignal(self): """连接信号""" # 双击单元格撤单 self.itemDoubleClicked.connect(self.cancelOrder) #---------------------------------------------------------------------- def cancelOrder(self, cell): """根据单元格的数据撤单""" order = cell.data req = VtCancelOrderReq() req.symbol = order.symbol req.exchange = order.exchange req.frontID = order.frontID req.sessionID = order.sessionID req.orderID = order.orderID self.mainEngine.cancelOrder(req, order.gatewayName) ######################################################################## class PositionMonitor(BasicMonitor): """持仓监控""" #---------------------------------------------------------------------- def __init__(self, mainEngine, eventEngine, parent=None): """Constructor""" super(PositionMonitor, self).__init__(mainEngine, eventEngine, parent) d = OrderedDict() d['symbol'] = {'chinese':vtText.CONTRACT_SYMBOL, 'cellType':BasicCell} d['vtSymbol'] = {'chinese':vtText.CONTRACT_NAME, 'cellType':NameCell} d['direction'] = {'chinese':vtText.DIRECTION, 'cellType':DirectionCell} d['position'] = {'chinese':vtText.POSITION, 'cellType':BasicCell} d['ydPosition'] = {'chinese':vtText.YD_POSITION, 'cellType':BasicCell} d['frozen'] = {'chinese':vtText.FROZEN, 'cellType':BasicCell} d['price'] = {'chinese':vtText.PRICE, 'cellType':BasicCell} d['positionProfit'] = {'chinese':vtText.POSITION_PROFIT, 'cellType':PnlCell} d['gatewayName'] = {'chinese':vtText.GATEWAY, 'cellType':BasicCell} self.setHeaderDict(d) self.setDataKey('vtPositionName') self.setEventType(EVENT_POSITION) self.setFont(BASIC_FONT) self.setSaveData(True) self.initTable() self.registerEvent() ######################################################################## class AccountMonitor(BasicMonitor): """账户监控""" #---------------------------------------------------------------------- def __init__(self, mainEngine, eventEngine, parent=None): """Constructor""" super(AccountMonitor, self).__init__(mainEngine, eventEngine, parent) d = OrderedDict() d['accountID'] = {'chinese':vtText.ACCOUNT_ID, 'cellType':BasicCell} d['preBalance'] = {'chinese':vtText.PRE_BALANCE, 'cellType':BasicCell} d['balance'] = {'chinese':vtText.BALANCE, 'cellType':BasicCell} d['available'] = {'chinese':vtText.AVAILABLE, 'cellType':BasicCell} d['commission'] = {'chinese':vtText.COMMISSION, 'cellType':BasicCell} d['margin'] = {'chinese':vtText.MARGIN, 'cellType':BasicCell} d['closeProfit'] = {'chinese':vtText.CLOSE_PROFIT, 'cellType':BasicCell} d['positionProfit'] = {'chinese':vtText.POSITION_PROFIT, 'cellType':BasicCell} d['gatewayName'] = {'chinese':vtText.GATEWAY, 'cellType':BasicCell} self.setHeaderDict(d) self.setDataKey('vtAccountID') self.setEventType(EVENT_ACCOUNT) self.setFont(BASIC_FONT) self.initTable() self.registerEvent() ######################################################################## class TradingWidget(QtWidgets.QFrame): """简单交易组件""" signal = QtCore.Signal(type(Event())) directionList = [DIRECTION_LONG, DIRECTION_SHORT] offsetList = [OFFSET_OPEN, OFFSET_CLOSE, OFFSET_CLOSEYESTERDAY, OFFSET_CLOSETODAY] priceTypeList = [PRICETYPE_LIMITPRICE, PRICETYPE_MARKETPRICE, PRICETYPE_FAK, PRICETYPE_FOK] exchangeList = [EXCHANGE_NONE, EXCHANGE_CFFEX, EXCHANGE_SHFE, EXCHANGE_DCE, EXCHANGE_CZCE, EXCHANGE_SSE, EXCHANGE_SZSE, EXCHANGE_SGE, EXCHANGE_HKEX, EXCHANGE_HKFE, EXCHANGE_SMART, EXCHANGE_ICE, EXCHANGE_CME, EXCHANGE_NYMEX, EXCHANGE_LME, EXCHANGE_GLOBEX, EXCHANGE_IDEALPRO] currencyList = [CURRENCY_NONE, CURRENCY_CNY, CURRENCY_HKD, CURRENCY_USD] productClassList = [PRODUCT_NONE, PRODUCT_EQUITY, PRODUCT_FUTURES, PRODUCT_OPTION, PRODUCT_FOREX, PRODUCT_SPOT] gatewayList = [''] #---------------------------------------------------------------------- def __init__(self, mainEngine, eventEngine, parent=None): """Constructor""" super(TradingWidget, self).__init__(parent) self.mainEngine = mainEngine self.eventEngine = eventEngine self.symbol = '' # 添加交易接口 l = mainEngine.getAllGatewayDetails() gatewayNameList = [d['gatewayName'] for d in l] self.gatewayList.extend(gatewayNameList) self.initUi() self.registerEvent() #---------------------------------------------------------------------- def initUi(self): """初始化界面""" self.setWindowTitle(vtText.TRADING) self.setFixedWidth(500) self.setFrameShape(self.Box) # 设置边框 self.setLineWidth(1) # 左边部分 labelSymbol = QtWidgets.QLabel(vtText.CONTRACT_SYMBOL) labelName = QtWidgets.QLabel(vtText.CONTRACT_NAME) labelDirection = QtWidgets.QLabel(vtText.DIRECTION) labelOffset = QtWidgets.QLabel(vtText.OFFSET) labelPrice = QtWidgets.QLabel(vtText.PRICE) self.checkFixed = QtWidgets.QCheckBox(u'') # 价格固定选择框 labelVolume = QtWidgets.QLabel(vtText.VOLUME) labelPriceType = QtWidgets.QLabel(vtText.PRICE_TYPE) labelExchange = QtWidgets.QLabel(vtText.EXCHANGE) labelCurrency = QtWidgets.QLabel(vtText.CURRENCY) labelProductClass = QtWidgets.QLabel(vtText.PRODUCT_CLASS) labelGateway = QtWidgets.QLabel(vtText.GATEWAY) self.lineSymbol = QtWidgets.QLineEdit() self.lineName = QtWidgets.QLineEdit() self.comboDirection = QtWidgets.QComboBox() self.comboDirection.addItems(self.directionList) self.comboOffset = QtWidgets.QComboBox() self.comboOffset.addItems(self.offsetList) validator = QtGui.QDoubleValidator() validator.setBottom(0) self.linePrice = QtWidgets.QLineEdit() self.linePrice.setValidator(validator) self.lineVolume = QtWidgets.QLineEdit() self.lineVolume.setValidator(validator) self.comboPriceType = QtWidgets.QComboBox() self.comboPriceType.addItems(self.priceTypeList) self.comboExchange = QtWidgets.QComboBox() self.comboExchange.addItems(self.exchangeList) self.comboCurrency = QtWidgets.QComboBox() self.comboCurrency.addItems(self.currencyList) self.comboProductClass = QtWidgets.QComboBox() self.comboProductClass.addItems(self.productClassList) self.comboGateway = QtWidgets.QComboBox() self.comboGateway.addItems(self.gatewayList) gridleft = QtWidgets.QGridLayout() gridleft.addWidget(labelSymbol, 0, 0) gridleft.addWidget(labelName, 1, 0) gridleft.addWidget(labelDirection, 2, 0) gridleft.addWidget(labelOffset, 3, 0) gridleft.addWidget(labelPrice, 4, 0) gridleft.addWidget(labelVolume, 5, 0) gridleft.addWidget(labelPriceType, 6, 0) gridleft.addWidget(labelExchange, 7, 0) gridleft.addWidget(labelCurrency, 8, 0) gridleft.addWidget(labelProductClass, 9, 0) gridleft.addWidget(labelGateway, 10, 0) gridleft.addWidget(self.lineSymbol, 0, 1, 1, -1) gridleft.addWidget(self.lineName, 1, 1, 1, -1) gridleft.addWidget(self.comboDirection, 2, 1, 1, -1) gridleft.addWidget(self.comboOffset, 3, 1, 1, -1) gridleft.addWidget(self.checkFixed, 4, 1) gridleft.addWidget(self.linePrice, 4, 2) gridleft.addWidget(self.lineVolume, 5, 1, 1, -1) gridleft.addWidget(self.comboPriceType, 6, 1, 1, -1) gridleft.addWidget(self.comboExchange, 7, 1, 1, -1) gridleft.addWidget(self.comboCurrency, 8, 1, 1, -1) gridleft.addWidget(self.comboProductClass, 9, 1, 1, -1) gridleft.addWidget(self.comboGateway, 10, 1, 1, -1) # 右边部分 labelBid1 = QtWidgets.QLabel(vtText.BID_1) labelBid2 = QtWidgets.QLabel(vtText.BID_2) labelBid3 = QtWidgets.QLabel(vtText.BID_3) labelBid4 = QtWidgets.QLabel(vtText.BID_4) labelBid5 = QtWidgets.QLabel(vtText.BID_5) labelAsk1 = QtWidgets.QLabel(vtText.ASK_1) labelAsk2 = QtWidgets.QLabel(vtText.ASK_2) labelAsk3 = QtWidgets.QLabel(vtText.ASK_3) labelAsk4 = QtWidgets.QLabel(vtText.ASK_4) labelAsk5 = QtWidgets.QLabel(vtText.ASK_5) self.labelBidPrice1 = QtWidgets.QLabel() self.labelBidPrice2 = QtWidgets.QLabel() self.labelBidPrice3 = QtWidgets.QLabel() self.labelBidPrice4 = QtWidgets.QLabel() self.labelBidPrice5 = QtWidgets.QLabel() self.labelBidVolume1 = QtWidgets.QLabel() self.labelBidVolume2 = QtWidgets.QLabel() self.labelBidVolume3 = QtWidgets.QLabel() self.labelBidVolume4 = QtWidgets.QLabel() self.labelBidVolume5 = QtWidgets.QLabel() self.labelAskPrice1 = QtWidgets.QLabel() self.labelAskPrice2 = QtWidgets.QLabel() self.labelAskPrice3 = QtWidgets.QLabel() self.labelAskPrice4 = QtWidgets.QLabel() self.labelAskPrice5 = QtWidgets.QLabel() self.labelAskVolume1 = QtWidgets.QLabel() self.labelAskVolume2 = QtWidgets.QLabel() self.labelAskVolume3 = QtWidgets.QLabel() self.labelAskVolume4 = QtWidgets.QLabel() self.labelAskVolume5 = QtWidgets.QLabel() labelLast = QtWidgets.QLabel(vtText.LAST) self.labelLastPrice = QtWidgets.QLabel() self.labelReturn = QtWidgets.QLabel() self.labelLastPrice.setMinimumWidth(60) self.labelReturn.setMinimumWidth(60) gridRight = QtWidgets.QGridLayout() gridRight.addWidget(labelAsk5, 0, 0) gridRight.addWidget(labelAsk4, 1, 0) gridRight.addWidget(labelAsk3, 2, 0) gridRight.addWidget(labelAsk2, 3, 0) gridRight.addWidget(labelAsk1, 4, 0) gridRight.addWidget(labelLast, 5, 0) gridRight.addWidget(labelBid1, 6, 0) gridRight.addWidget(labelBid2, 7, 0) gridRight.addWidget(labelBid3, 8, 0) gridRight.addWidget(labelBid4, 9, 0) gridRight.addWidget(labelBid5, 10, 0) gridRight.addWidget(self.labelAskPrice5, 0, 1) gridRight.addWidget(self.labelAskPrice4, 1, 1) gridRight.addWidget(self.labelAskPrice3, 2, 1) gridRight.addWidget(self.labelAskPrice2, 3, 1) gridRight.addWidget(self.labelAskPrice1, 4, 1) gridRight.addWidget(self.labelLastPrice, 5, 1) gridRight.addWidget(self.labelBidPrice1, 6, 1) gridRight.addWidget(self.labelBidPrice2, 7, 1) gridRight.addWidget(self.labelBidPrice3, 8, 1) gridRight.addWidget(self.labelBidPrice4, 9, 1) gridRight.addWidget(self.labelBidPrice5, 10, 1) gridRight.addWidget(self.labelAskVolume5, 0, 2) gridRight.addWidget(self.labelAskVolume4, 1, 2) gridRight.addWidget(self.labelAskVolume3, 2, 2) gridRight.addWidget(self.labelAskVolume2, 3, 2) gridRight.addWidget(self.labelAskVolume1, 4, 2) gridRight.addWidget(self.labelReturn, 5, 2) gridRight.addWidget(self.labelBidVolume1, 6, 2) gridRight.addWidget(self.labelBidVolume2, 7, 2) gridRight.addWidget(self.labelBidVolume3, 8, 2) gridRight.addWidget(self.labelBidVolume4, 9, 2) gridRight.addWidget(self.labelBidVolume5, 10, 2) self.labelBidVolume5.setFixedWidth(100) # 发单按钮 buttonSendOrder = QtWidgets.QPushButton(vtText.SEND_ORDER) buttonCancelAll = QtWidgets.QPushButton(vtText.CANCEL_ALL) size = buttonSendOrder.sizeHint() buttonSendOrder.setMinimumHeight(size.height()*2) # 把按钮高度设为默认两倍 buttonCancelAll.setMinimumHeight(size.height()*2) # 整合布局 hbox = QtWidgets.QHBoxLayout() hbox.addLayout(gridleft) hbox.addLayout(gridRight) vbox = QtWidgets.QVBoxLayout() vbox.addLayout(hbox) vbox.addWidget(buttonSendOrder) vbox.addWidget(buttonCancelAll) vbox.addStretch() self.setLayout(vbox) # 关联更新 buttonSendOrder.clicked.connect(self.sendOrder) buttonCancelAll.clicked.connect(self.cancelAll) self.lineSymbol.returnPressed.connect(self.updateSymbol) #---------------------------------------------------------------------- def updateSymbol(self): """合约变化""" # 读取组件数据 symbol = str(self.lineSymbol.text()) exchange = text_type(self.comboExchange.currentText()) currency = text_type(self.comboCurrency.currentText()) productClass = text_type(self.comboProductClass.currentText()) gatewayName = text_type(self.comboGateway.currentText()) # 查询合约 if exchange: vtSymbol = '.'.join([symbol, exchange]) contract = self.mainEngine.getContract(vtSymbol) else: vtSymbol = symbol contract = self.mainEngine.getContract(symbol) if contract: vtSymbol = contract.vtSymbol gatewayName = contract.gatewayName self.lineName.setText(contract.name) exchange = contract.exchange # 保证有交易所代码 # 清空价格数量 self.linePrice.clear() self.lineVolume.clear() # 清空行情显示 self.labelBidPrice1.setText('') self.labelBidPrice2.setText('') self.labelBidPrice3.setText('') self.labelBidPrice4.setText('') self.labelBidPrice5.setText('') self.labelBidVolume1.setText('') self.labelBidVolume2.setText('') self.labelBidVolume3.setText('') self.labelBidVolume4.setText('') self.labelBidVolume5.setText('') self.labelAskPrice1.setText('') self.labelAskPrice2.setText('') self.labelAskPrice3.setText('') self.labelAskPrice4.setText('') self.labelAskPrice5.setText('') self.labelAskVolume1.setText('') self.labelAskVolume2.setText('') self.labelAskVolume3.setText('') self.labelAskVolume4.setText('') self.labelAskVolume5.setText('') self.labelLastPrice.setText('') self.labelReturn.setText('') # 订阅合约 req = VtSubscribeReq() req.symbol = symbol req.exchange = exchange req.currency = currency req.productClass = productClass # 默认跟随价 self.checkFixed.setChecked(False) self.mainEngine.subscribe(req, gatewayName) # 更新组件当前交易的合约 self.symbol = vtSymbol #---------------------------------------------------------------------- def updateTick(self, event): """更新行情""" tick = event.dict_['data'] if tick.vtSymbol != self.symbol: return if not self.checkFixed.isChecked(): self.linePrice.setText(str(tick.lastPrice)) self.labelBidPrice1.setText(str(tick.bidPrice1)) self.labelAskPrice1.setText(str(tick.askPrice1)) self.labelBidVolume1.setText(str(tick.bidVolume1)) self.labelAskVolume1.setText(str(tick.askVolume1)) if tick.bidPrice2: self.labelBidPrice2.setText(str(tick.bidPrice2)) self.labelBidPrice3.setText(str(tick.bidPrice3)) self.labelBidPrice4.setText(str(tick.bidPrice4)) self.labelBidPrice5.setText(str(tick.bidPrice5)) self.labelAskPrice2.setText(str(tick.askPrice2)) self.labelAskPrice3.setText(str(tick.askPrice3)) self.labelAskPrice4.setText(str(tick.askPrice4)) self.labelAskPrice5.setText(str(tick.askPrice5)) self.labelBidVolume2.setText(str(tick.bidVolume2)) self.labelBidVolume3.setText(str(tick.bidVolume3)) self.labelBidVolume4.setText(str(tick.bidVolume4)) self.labelBidVolume5.setText(str(tick.bidVolume5)) self.labelAskVolume2.setText(str(tick.askVolume2)) self.labelAskVolume3.setText(str(tick.askVolume3)) self.labelAskVolume4.setText(str(tick.askVolume4)) self.labelAskVolume5.setText(str(tick.askVolume5)) self.labelLastPrice.setText(str(tick.lastPrice)) if tick.preClosePrice: rt = (tick.lastPrice/tick.preClosePrice)-1 self.labelReturn.setText(('%.2f' %(rt*100))+'%') else: self.labelReturn.setText('') #---------------------------------------------------------------------- def registerEvent(self): """注册事件监听""" self.signal.connect(self.updateTick) self.eventEngine.register(EVENT_TICK, self.signal.emit) #---------------------------------------------------------------------- def sendOrder(self): """发单""" symbol = str(self.lineSymbol.text()) vtSymbol = symbol exchange = text_type(self.comboExchange.currentText()) currency = text_type(self.comboCurrency.currentText()) productClass = text_type(self.comboProductClass.currentText()) gatewayName = text_type(self.comboGateway.currentText()) # 查询合约 if exchange: vtSymbol = '.'.join([symbol, exchange]) contract = self.mainEngine.getContract(vtSymbol) else: vtSymbol = symbol contract = self.mainEngine.getContract(symbol) if contract: gatewayName = contract.gatewayName exchange = contract.exchange # 保证有交易所代码 vtSymbol = contract.vtSymbol # 获取价格 priceText = self.linePrice.text() if not priceText: return price = float(priceText) # 获取数量 volumeText = self.lineVolume.text() if not volumeText: return if '.' in volumeText: volume = float(volumeText) else: volume = int(volumeText) # 委托 req = VtOrderReq() req.symbol = symbol req.exchange = exchange req.vtSymbol = vtSymbol req.price = price req.volume = volume req.direction = text_type(self.comboDirection.currentText()) req.priceType = text_type(self.comboPriceType.currentText()) req.offset = text_type(self.comboOffset.currentText()) req.currency = currency req.productClass = productClass self.mainEngine.sendOrder(req, gatewayName) #---------------------------------------------------------------------- def cancelAll(self): """一键撤销所有委托""" l = self.mainEngine.getAllWorkingOrders() for order in l: req = VtCancelOrderReq() req.symbol = order.symbol req.exchange = order.exchange req.frontID = order.frontID req.sessionID = order.sessionID req.orderID = order.orderID self.mainEngine.cancelOrder(req, order.gatewayName) #---------------------------------------------------------------------- def closePosition(self, cell): """根据持仓信息自动填写交易组件""" # 读取持仓数据,cell是一个表格中的单元格对象 pos = cell.data symbol = pos.symbol # 更新交易组件的显示合约 self.lineSymbol.setText(symbol) self.updateSymbol() # 自动填写信息 self.comboPriceType.setCurrentIndex(self.priceTypeList.index(PRICETYPE_LIMITPRICE)) self.comboOffset.setCurrentIndex(self.offsetList.index(OFFSET_CLOSE)) self.lineVolume.setText(str(pos.position)) if pos.direction == DIRECTION_LONG or pos.direction == DIRECTION_NET: self.comboDirection.setCurrentIndex(self.directionList.index(DIRECTION_SHORT)) else: self.comboDirection.setCurrentIndex(self.directionList.index(DIRECTION_LONG)) # 价格留待更新后由用户输入,防止有误操作 ######################################################################## class ContractMonitor(BasicMonitor): """合约查询""" #---------------------------------------------------------------------- def __init__(self, mainEngine, parent=None): """Constructor""" super(ContractMonitor, self).__init__(parent=parent) self.mainEngine = mainEngine d = OrderedDict() d['symbol'] = {'chinese':vtText.CONTRACT_SYMBOL, 'cellType':BasicCell} d['exchange'] = {'chinese':vtText.EXCHANGE, 'cellType':BasicCell} d['vtSymbol'] = {'chinese':vtText.VT_SYMBOL, 'cellType':BasicCell} d['name'] = {'chinese':vtText.CONTRACT_NAME, 'cellType':BasicCell} d['productClass'] = {'chinese':vtText.PRODUCT_CLASS, 'cellType':BasicCell} d['size'] = {'chinese':vtText.CONTRACT_SIZE, 'cellType':BasicCell} d['priceTick'] = {'chinese':vtText.PRICE_TICK, 'cellType':BasicCell} d['underlyingSymbol'] = {'chinese':vtText.UNDERLYING_SYMBOL, 'cellType':BasicCell} d['optionType'] = {'chinese':vtText.OPTION_TYPE, 'cellType':BasicCell} d['expiryDate'] = {'chinese':vtText.EXPIRY_DATE, 'cellType':BasicCell} d['strikePrice'] = {'chinese':vtText.STRIKE_PRICE, 'cellType':BasicCell} self.setHeaderDict(d) # 过滤显示用的字符串 self.filterContent = EMPTY_STRING self.initUi() #---------------------------------------------------------------------- def initUi(self): """初始化界面""" self.setMinimumSize(800, 800) self.setFont(BASIC_FONT) self.initTable() self.addMenuAction() #---------------------------------------------------------------------- def showAllContracts(self): """显示所有合约数据""" l = self.mainEngine.getAllContracts() d = {'.'.join([contract.exchange, contract.symbol]):contract for contract in l} l2 = list(d.keys()) l2.sort(reverse=True) self.setRowCount(len(l2)) row = 0 for key in l2: # 如果设置了过滤信息且合约代码中不含过滤信息,则不显示 if self.filterContent and self.filterContent not in key: continue contract = d[key] for n, header in enumerate(self.headerList): content = safeUnicode(contract.__getattribute__(header)) cellType = self.headerDict[header]['cellType'] cell = cellType(content) if self.font: cell.setFont(self.font) # 如果设置了特殊字体,则进行单元格设置 self.setItem(row, n, cell) row = row + 1 #---------------------------------------------------------------------- def refresh(self): """刷新""" self.menu.close() # 关闭菜单 self.clearContents() self.setRowCount(0) self.showAllContracts() #---------------------------------------------------------------------- def addMenuAction(self): """增加右键菜单内容""" refreshAction = QtWidgets.QAction(vtText.REFRESH, self) refreshAction.triggered.connect(self.refresh) self.menu.addAction(refreshAction) #---------------------------------------------------------------------- def show(self): """显示""" super(ContractMonitor, self).show() self.refresh() #---------------------------------------------------------------------- def setFilterContent(self, content): """设置过滤字符串""" self.filterContent = content ######################################################################## class ContractManager(QtWidgets.QWidget): """合约管理组件""" #---------------------------------------------------------------------- def __init__(self, mainEngine, parent=None): """Constructor""" super(ContractManager, self).__init__(parent=parent) self.mainEngine = mainEngine self.initUi() #---------------------------------------------------------------------- def initUi(self): """初始化界面""" self.setWindowTitle(vtText.CONTRACT_SEARCH) self.lineFilter = QtWidgets.QLineEdit() self.buttonFilter = QtWidgets.QPushButton(vtText.SEARCH) self.buttonFilter.clicked.connect(self.filterContract) self.monitor = ContractMonitor(self.mainEngine) self.monitor.refresh() hbox = QtWidgets.QHBoxLayout() hbox.addWidget(self.lineFilter) hbox.addWidget(self.buttonFilter) hbox.addStretch() vbox = QtWidgets.QVBoxLayout() vbox.addLayout(hbox) vbox.addWidget(self.monitor) self.setLayout(vbox) #---------------------------------------------------------------------- def filterContract(self): """显示过滤后的合约""" content = str(self.lineFilter.text()) self.monitor.setFilterContent(content) self.monitor.refresh() ######################################################################## class WorkingOrderMonitor(OrderMonitor): """活动委托监控""" STATUS_COMPLETED = [STATUS_ALLTRADED, STATUS_CANCELLED, STATUS_REJECTED] #---------------------------------------------------------------------- def __init__(self, mainEngine, eventEngine, parent=None): """Constructor""" super(WorkingOrderMonitor, self).__init__(mainEngine, eventEngine, parent) #---------------------------------------------------------------------- def updateData(self, data): """更新数据""" super(WorkingOrderMonitor, self).updateData(data) # 如果该委托已完成,则隐藏该行 if data.status in self.STATUS_COMPLETED: vtOrderID = data.vtOrderID cellDict = self.dataDict[vtOrderID] cell = cellDict['status'] row = self.row(cell) self.hideRow(row) ######################################################################## class SettingEditor(QtWidgets.QWidget): """配置编辑器""" #---------------------------------------------------------------------- def __init__(self, mainEngine, parent=None): """Constructor""" super(SettingEditor, self).__init__(parent) self.mainEngine = mainEngine self.currentFileName = '' self.initUi() #---------------------------------------------------------------------- def initUi(self): """初始化界面""" self.setWindowTitle(vtText.EDIT_SETTING) self.comboFileName = QtWidgets.QComboBox() self.comboFileName.addItems(jsonPathDict.keys()) buttonLoad = QtWidgets.QPushButton(vtText.LOAD) buttonSave = QtWidgets.QPushButton(vtText.SAVE) buttonLoad.clicked.connect(self.loadSetting) buttonSave.clicked.connect(self.saveSetting) self.editSetting = QtWidgets.QTextEdit() self.labelPath = QtWidgets.QLabel() hbox = QtWidgets.QHBoxLayout() hbox.addWidget(self.comboFileName) hbox.addWidget(buttonLoad) hbox.addWidget(buttonSave) hbox.addStretch() vbox = QtWidgets.QVBoxLayout() vbox.addLayout(hbox) vbox.addWidget(self.editSetting) vbox.addWidget(self.labelPath) self.setLayout(vbox) #---------------------------------------------------------------------- def loadSetting(self): """加载配置""" self.currentFileName = str(self.comboFileName.currentText()) filePath = jsonPathDict[self.currentFileName] self.labelPath.setText(filePath) with open(filePath) as f: self.editSetting.clear() for line in f: line = line.replace('\n', '') # 移除换行符号 line = line.decode('UTF-8') self.editSetting.append(line) #---------------------------------------------------------------------- def saveSetting(self): """保存配置""" if not self.currentFileName: return filePath = jsonPathDict[self.currentFileName] with open(filePath, 'w') as f: content = self.editSetting.toPlainText() content = content.encode('UTF-8') f.write(content) #---------------------------------------------------------------------- def show(self): """显示""" # 更新配置文件下拉框 self.comboFileName.clear() self.comboFileName.addItems(jsonPathDict.keys()) # 显示界面 super(SettingEditor, self).show()
[ "524266571@qq.com" ]
524266571@qq.com
f4f65a3d9ef04cdc455c3f1c5fe646ea8b5ff2fc
9281c60554544f8d8cc21683cb828df987635c6f
/script.py
df620497a7a8e65953b738abfa938e4669c4cb04
[]
no_license
mannb986/a_sorted_tale
1ec9b2742bc510e29b8801f5b0a9dec4abb3a314
d75debb4814252fcab4172f77b895c4c60040cc1
refs/heads/main
2023-04-02T03:00:46.961953
2021-04-08T18:30:47
2021-04-08T18:30:47
356,012,206
0
0
null
null
null
null
UTF-8
Python
false
false
1,306
py
import utils import sorts bookshelf = utils.load_books('books_small.csv') long_bookshelf = utils.load_books('books_large.csv') bookshelf_v1 = bookshelf.copy() bookshelf_v2 = bookshelf.copy() # Defining different comparison sort function def by_title_ascending(book_a, book_b): if book_a['title_lower'] > book_b['title_lower']: return True else: return False def by_author_ascending(book_a, book_b): if book_a["author_lower"] > book_b['author_lower']: return True else: return False def by_total_length(book_a, book_b): if len(book_a["author_lower"]) + len(book_a['title_lower']) > len(book_b['author_lower']) + len(['title_lower']): return True else: return False # Running the different sort alogrithms with different comparison functions sort_1 = sorts.bubble_sort(bookshelf, by_title_ascending) for book in sort_1: print(book['title_lower']) sort_2 = sorts.bubble_sort(bookshelf_v1, by_author_ascending) for book in sort_2: print(book['author_lower']) sorts.quicksort(bookshelf_v2, 0, len(bookshelf_v2)-1, by_author_ascending) for book in bookshelf_v2: print(book['author_lower']) sorts.quicksort(long_bookshelf, 0, len(long_bookshelf)-1, by_total_length) for book in long_bookshelf: print(book['title'])
[ "mannb986@gmail.com" ]
mannb986@gmail.com
e52f9b51e3d81ba789212afe78fcbdf6a9833225
5278942e917295a7ec6febfb45cd42273f193b05
/code/old_file/entity_embedding/t.py
b8c5723b26358b81f5e4d1234c2a51509b7599ab
[]
no_license
luke-feng/advancedTM_Red
eab78c37983fe414e84aa91b7e3d7b8283e4648a
84392dc692e1a5251eaaca8becafff501d0f08d7
refs/heads/master
2021-04-03T00:23:02.142868
2021-02-19T09:17:14
2021-02-19T09:17:14
248,340,466
0
1
null
null
null
null
UTF-8
Python
false
false
1,846
py
# -*- coding: utf-8 -*- '''import gensim from gensim.models import KeyedVectors from gensim.test.utils import datapath from gensim import utils wordvector_path = '/Users/chaofeng/Downloads/2014_tudarmstadt_german_5mincount.vocab' with open() def load_model(wordvector_path): model = KeyedVectors.load_word2vec_format(wordvector_path, binary=False) word_num = len(model.vocab) print('loaded {} words to model'.format(word_num)) return model load_model(wordvector_path)''' in_filepath = '/Users/chaofeng/end2end_neural_el/data/basic_data/test_datasets/HIPE/' infiles = ['HIPE-data-v1.0-train-de.tsv','HIPE-data-v1.0-dev-de.tsv'] out_filepath = '/Users/chaofeng/end2end_neural_el/deep-ed/basic_data/QID_HIPE.txt' mapping_path ='/Users/chaofeng/end2end_neural_el/deep-ed/basic_data/wikidata_nameid_map.txt' q_file= '/Users/chaofeng/end2end_neural_el/deep-ed/basic_data/QID.txt' q_not_file= '/Users/chaofeng/end2end_neural_el/deep-ed/basic_data/QID_NotInWiki.txt' def load_ID_mapping(mapping_path): mapping = {} with open(mapping_path, 'r') as tsvfile: for line in tsvfile: tokens = line.split('\t') if len(tokens) == 2: mapping[tokens[0]] = tokens[1] row_len = len(mapping) print("load {} wiki mapping IDs".format(row_len)) return mapping qid = load_ID_mapping(mapping_path) print(len(qid)) count_in = 0 count_not_in = 0 hipe_qid = {} for file in infiles: with open(in_filepath+file, 'r') as infs, open(out_filepath, 'w') as outs: for line in infs: li = line.split('\t') if len(li) == 10 and 'Q' in li[7]: hipe_qid[li[7]] = '' with open(q_not_file,'w') as notin: for hq in hipe_qid: if hq not in qid: count_not_in += 1 notin.write(hq+'\n') print(count_not_in)
[ "luke-feng@outlook.com" ]
luke-feng@outlook.com
24c5440afcb1d02d3cded6a8f447b90c7edc1335
baa24e885d043c9d87874d8950c56dbaec7aaae3
/testData/settingData.py
616745a5a5378f2f22e43a8871abd9446a56c63c
[]
no_license
dreamsql/TransactionServerTestScript
7ed08a9422725f79326490f897ed75a80b5a8394
58166e8fe5c23a87128b6010f63facb86f356922
refs/heads/master
2021-05-30T19:25:42.637873
2016-03-23T00:42:41
2016-03-23T00:42:41
null
0
0
null
null
null
null
UTF-8
Python
false
false
8,533
py
# -*- coding: utf-8 -*- import xml.etree.ElementTree as ET from Test.util import singleton import re from Test import xmlHelper import os import abc import settingAccount import entity from Test.common import dbDataParser class TradePolicyDetail(entity.Entity): def __init__(self, headerDict, cols): super(TradePolicyDetail, self).__init__(headerDict, cols) def getXmlTagName(self): return 'TradePolicyDetail' def getAttrDict(self): return { 'TradePolicyID': self.getColumnValue('TradePolicyID'), 'InstrumentID': self.getColumnValue('InstrumentID'), 'ContractSize': self.getColumnValue('ContractSize') } class TradePolicy(entity.Entity): def __init__(self, headerDict, cols): super(TradePolicy, self).__init__(headerDict, cols) def getXmlTagName(self): return 'TradePolicy' def getAttrDict(self): return { 'ID': self.getColumnValue('ID'), 'Code': self.getColumnValue('Code') } class Currency(entity.Entity): def __init__(self, headerDict, cols): super(Currency, self).__init__(headerDict, cols); self.id = self.getColumnValue('ID') self.code = self.getColumnValue('Code') self.decimals = self.getColumnValue('Decimals') def getXmlTagName(self): return 'Currency' def getAttrDict(self): return { 'ID': self.id, 'Code': self.code, 'Decimals': self.decimals } class SystemParameter(entity.Entity): def __init__(self, headerDict, cols): super(SystemParameter, self).__init__(headerDict, cols); def getXmlTagName(self): return 'SystemParameter' def getAttrDict(self): return { 'TradeDayBeginTime': self.getColumnValue('TradeDayBeginTime'), 'MooMocAcceptDuration': self.getColumnValue('MooMocAcceptDuration'), 'MooMocCancelDuration': self.getColumnValue('MooMocCancelDuration'), 'DQDelayTimeOption': self.getColumnValue('DQDelayTimeOption'), 'PlaceCheckType': self.getColumnValue('PlaceCheckType'), 'NeedsFillCheck': self.getColumnValue('NeedsFillCheck'), 'CanDealerViewAccountInfo': self.getColumnValue('CanDealerViewAccountInfo'), 'UseNightNecessaryWhenBreak': self.getColumnValue('UseNightNecessaryWhenBreak'), 'BalanceDeficitAllowPay': self.getColumnValue('BalanceDeficitAllowPay'), 'IncludeFeeOnRiskAction': self.getColumnValue('IncludeFeeOnRiskAction'), 'IncludeFeeOnRiskAction': self.getColumnValue('IncludeFeeOnRiskAction'), 'EnableExportOrder': self.getColumnValue('EnableExportOrder'), 'EnableEmailNotify': self.getColumnValue('EnableEmailNotify'), 'EmailNotifyChangePassword': self.getColumnValue('EmailNotifyChangePassword'), 'CurrencyRateUpdateDuration': self.getColumnValue('CurrencyRateUpdateDuration'), # 'DefaultQuotePolicyId': self.getColumnValue('DefaultQuotePolicyId'), 'MaxPriceDelayForSpotOrder': self.getColumnValue('MaxPriceDelayForSpotOrder'), 'RiskActionOnPendingConfirmLimit': self.getColumnValue('RiskActionOnPendingConfirmLimit'), 'LmtQuantityOnMaxLotChange': self.getColumnValue('LmtQuantityOnMaxLotChange'), 'STPAtHitPriceOption': self.getColumnValue('STPAtHitPriceOption'), 'EvaluateIfDonePlacingOnStpConfirm': self.getColumnValue('EvaluateIfDonePlacingOnStpConfirm') } class CurrencyRate(entity.Entity): def __init__(self, headerDict, cols): super(CurrencyRate, self).__init__(headerDict, cols) self.sourceCurrency = self.getColumnValue('SourceCurrencyID') self.targetCurrency = self.getColumnValue('TargetCurrencyID') self.rateIn = self.getColumnValue('RateIn') self.rateOut = self.getColumnValue('RateOut') def getXmlTagName(self): return 'CurrencyRate' def getAttrDict(self): return { 'SourceCurrencyID': self.sourceCurrency, 'TargetCurrencyID': self.targetCurrency, 'RateIn': self.rateIn, 'RateOut': self.rateOut } class Customer(entity.Entity): def __init__(self, headerDict, cols): super(Customer, self).__init__(headerDict, cols) self.id = self.getColumnValue('ID') self.name = self.getColumnValue('Name') self.publicQuotePolicyId = self.getColumnValue('PublicQuotePolicyID') self.privateQuotePolicyId = self.getColumnValue('PrivateQuotePolicyID') def getXmlTagName(self): return 'Customer' def getAttrDict(self): return { 'ID': self.id, 'Name': self.name, 'PublicQuotePolicyID': self.publicQuotePolicyId, 'PrivateQuotePolicyID': self.privateQuotePolicyId } class Instrument(entity.Entity): def __init__(self, headerDict, cols): super(Instrument, self).__init__(headerDict, cols) self.id = self.getColumnValue('ID') self.code = self.getColumnValue('Code') self.category = self.getColumnValue('Category') self.beginTime = self.getColumnValue('BeginTime') self.endTime = self.getColumnValue('EndTime') self.numeratorUnit = self.getColumnValue('NumeratorUnit') self.denominator = self.getColumnValue('Denominator') self.category = self.getColumnValue('Category') def getXmlTagName(self): return "Instrument" def getAttrDict(self): return { 'ID': self.id, 'Code': self.code, 'Category': self.category, 'NumeratorUnit': self.numeratorUnit, 'Denominator': self.denominator, 'DayOpenTime': self.beginTime, 'DayCloseTime': self.endTime, 'CurrencyID': self.getColumnValue('CurrencyID'), 'IsActive': self.getColumnValue('IsActive'), 'Category': self.category } class SettingParameter(object): """docstring for SettingParameter""" def __init__(self, fileName, modelClass): super(SettingParameter, self).__init__() self.fileName = fileName self.modelClass = modelClass self.models = [] class SettingRepository(dbDataParser.Parser): def __init__(self, parameters): super(SettingRepository, self).__init__(os.path.dirname(__file__)) self.settingParameters = self.loadSettingParameters(parameters) self.loadEntities() def loadSettingParameters(self, parameters): result = [] for eachParameter in parameters: fileName, modelClass = eachParameter result.append(SettingParameter(fileName,modelClass)) return result def loadEntities(self): for eachParameter in self.settingParameters: self.buildEntitiesCommon(eachParameter.fileName, eachParameter.models, eachParameter.modelClass) def toXml(self): root = ET.Element('Settings') addMethodRoot = ET.SubElement(root, 'Add') for eachParameter in self.settingParameters: for eachModel in eachParameter.models: eachModel.toXml(addMethodRoot) return xmlHelper.toXml(root) class Setting(object): '''产生组装SettingManager所需要的数据''' def __init__(self): self.root = ET.Element('Setting') self.instrumentId = '33C4C6E2-E33C-4A21-A01A-35F4EC647890' self.tradePolicyId = '99A5FE24-D8B7-42A2-9DBE-BF1608F82F96' self.customerId = 'CB58B47D-A705-42DD-9308-6C6B26CE79A7' self.IsMultiCurrency = True self.accountCurrencyId = 'F940A509-4ED6-4A92-A6F0-CD9A60601084' self.instrumentCurrencyId = '0DA665B5-9AA5-49D7-A301-048F1428CA4A' def generateInstrumentData(self): node = self.createNode('Instrument') attrs = { 'ID': self.instrumentId, 'CurrencyID': '0DA665B5-9AA5-49D7-A301-048F1428CA4A', 'Code': 'AUD', 'Category': '10', 'NumeratorUnit': '1', 'Denominator': '10000' } self.setAttrsToNode(node, attrs) def generateCustomerData(self): node = self.createNode('Customer') attrs = { 'ID': self.customerId, 'PublicQuotePolicyID': 'AD0BEE1C-7E75-4C80-B8FD-920B6B0B0EF2', 'PrivateQuotePolicyID': 'AD0BEE1C-7E75-4C80-B8FD-920B6B0B0EF2', 'Name': 'XD02' } self.setAttrsToNode(node,attrs) def generateTradePolicyData(self): node = self.createNode('TradePolicy') attrs = { 'ID': self.tradePolicyId, } self.setAttrsToNode(node,attrs) detailNode = this.createNodeWithParent(node,'TradePolicyDetail') detailAttrs = { 'InstrumentID': self.instrumentId, 'BOPolicyID': '6E0591DD-0F08-4CF3-9336-63A6D7261AE2' } self.setAttrsToNode(detailNode, detailAttrs) def generateAccountData(self): node = self.createNode("Account") attrs = { 'ID': 'B940D4B7-4A4E-46DF-8EA4-77B0C3CC1A6B', 'TradePolicyID': self.tradePolicyId, 'CustomerID': self.customerId, 'CurrencyID': 'F940A509-4ED6-4A92-A6F0-CD9A60601084', 'IsMultiCurrency': 'true' } self.setAttrsToNode(node, attrs) def generateCurrencyRateData(self): node = self.createNode('CurrencyRate') attrs = { '' } def createNode(self, name): return ET.SubElement(self.root, name) def createNodeWithParent(self, parent, name): return ET.SubElement(parent, name) def setAttrsToNode(self, node, attrs): for k, v in attrs.items(): node.set(k, v)
[ "Robert@WS0210.Omnicare.com" ]
Robert@WS0210.Omnicare.com
6656d4495d332a47f3155f8bf90f35477c40a17e
980eb65535a6d685c1961e745a994fa4981c1809
/Bot_Functions.py
275c41be0fbe452ea35921699668fa6432dbb947
[]
no_license
Yggdrasil1/TelegRPG
e82cfef328b94c22c4c926f06d26167aae5ac435
9cd079602ccc7f23ba5411c5712f3954750491e3
refs/heads/main
2023-03-26T10:34:53.318313
2021-03-29T12:56:23
2021-03-29T12:56:23
351,115,986
0
0
null
null
null
null
UTF-8
Python
false
false
5,629
py
import Character import global_variables as gv from Messages import * from Keyboards import * import Gear import Create_Images as ci import numpy as np import random import Monster_Spawn import Useable import telegram import time from telegram import ReplyKeyboardMarkup, ReplyKeyboardRemove def start_new_game(update, context): """ Function to create a new character, add it to the dict of characters and lead the game to the class selection :param update: standard button argument :param context: standard button argument """ query = update.callback_query chatid = chatID(query) # gv.player_dict.update({chatid: str(chatid)}) character = Character.Character(chatid) gv.character_dict.update({chatid: character}) inventory = Gear.Inventory(chatid, Gear.initial_gear(chatid)) gv.inventory_dict.update({chatid: inventory}) query.answer() query.edit_message_text(class_selection_msg(), reply_markup=class_selection_keyboard()) def class_selection(update, context): query = update.callback_query chatid = chatID(query) character = gv.character_dict[chatid] character.klasse = query.data character.main_stat_increase(5) query.edit_message_text(name_selection_msg(), reply_markup=name_selection_keyboard()) def chatID(query): return str(query.message.chat.id) def evaluate_movement(character, direction): new_coord_x, new_coord_y = list(np.array(gv.direction_dict[direction]) + np.array([character.coord_x, character.coord_y])) old_region = gv.world_map[character.coord_x][character.coord_y] new_region = gv.world_map[new_coord_x][new_coord_y] if new_coord_x in [-1, gv.world_max_x + 1] or new_coord_y in [-1, gv.world_max_y - 1]: return world_border_reached_msg(), False, "boring" elif gv.world_map[new_coord_x][new_coord_y] == 'water': return water_reached_msg(), False, "boring" else: return movement_msg(direction, new_region, old_region, new_coord_x, new_coord_y), True, new_region def print_inventory(update, context): query = update.callback_query chatid = chatID(query) inventory = gv.inventory_dict[chatid].inv string = inventory_msg(inventory) query.edit_message_text(text=string) gv.bot.send_message(query.message.chat.id, text="Was willst du als nächstes tun?", reply_markup=inventory_keyboard()) def show_useables(update, context): query = update.callback_query chatid = chatID(query) inventory = gv.inventory_dict[chatid] query.edit_message_text(text="Das sind die Items die du nicht trägst oder benutzen kannst.") gv.bot.send_message(query.message.chat.id, text="Klick auf ein Item um es zu benutzen oder anzulegen.", reply_markup=useable_inventory(inventory)) def delete_item(update, context): query = update.callback_query chatid = chatID(query) inventory = gv.inventory_dict[chatid] if not query.data == 'pass': item_name = "not_equipped" + query.data[1:] inventory[item_name] = '-' gv.destroy_item_dict[chatid] = True else: gv.destroy_item_dict[chatid] = False return def store_data(): for character in gv.character_dict: gv.character_dict[character].store_character() for inventory in gv.inventory_dict: gv.inventory_dict[inventory].store_inventory() def send_item(chatid, item): image_path = ci.create_item_image(f"{item.geartype.capitalize()}_{item.rarity}", item.stats(), chatid) ci.send_image(gv.bot, chatid, image_path, False) return def monster_encounter(character, chatid): pre_lvl = character.lvl x = character.coord_x y = character.coord_y region_lvl = gv.monster_lvl_dict[x][y] monster = Monster_Spawn.spawn_monster(region_lvl, character.lvl) print(monster) gv.bot.send_message(chatid, text=monster_spawn_msg(monster.name)) winner = Monster_Spawn.monster_fight(character, monster) if winner == character: character.hp = round(character.hp) character.exp += monster.exp character.update_exp() gv.bot.send_message(chatid, text=f"Du hast {character.hp} leben übrig") if character.lvl > pre_lvl: gv.bot.send_message(chatid, text=lvl_up_msg(character)) item_drop = random.random() gear_type = random.choice(["Helmet", "Chest", "Pants", "Boots", "Weapon"]) item = "bla" if 0.7 < item_drop < 0.85: item = Gear.Gear(character.lvl, gear_type, 'common', chatid) elif 0.85 < item_drop < 0.95: item = Gear.Gear(character.lvl, gear_type, 'rare', chatid) elif 0.95 < item_drop: item = Gear.Gear(character.lvl, gear_type, 'epic', chatid) if not item == 'bla': gv.bot.send_message(chatid, text=f"Du hast ein Item gefunden!") send_item(chatid, item) gv.inventory_dict[chatid].add_item(item) else: character.hp = 0 kill_player(character, chatid) return def kill_player(character, chatid): character.update_max_hp() character.hp = character.max_hp character.coord_x = 50 character.coord_y = 67 gv.bot.send_message(chatid, text=you_died_msg()) bread = Useable.HealConsumable(chatid, "Brot", "heilt Leben (30%)", 3) if not gv.inventory_dict[chatid].item_in_inventory('Brot'): gv.inventory_dict[chatid].add_item(bread) return
[ "k.a.i.winkler@gmx.de" ]
k.a.i.winkler@gmx.de
d78ec5d375a61d39378e1c786f504671a0bcd4d4
954c493a9105a464bee744c6c78a6d06bf8d531c
/simfoni_task/urls.py
c513fe902a316543936fb9ae3266b67fefa3af6b
[]
no_license
sandeepsajan0/suppliers-api
d235bb1e1e632cbd12e4b39ffb73e6b4be9e22f1
5b911471a4e02954296cfd2151f96480052d4a70
refs/heads/master
2023-02-26T01:57:03.408628
2021-01-24T12:39:34
2021-01-24T12:39:34
332,411,678
0
0
null
2021-01-24T12:12:52
2021-01-24T09:38:56
Python
UTF-8
Python
false
false
1,302
py
"""simfoni_task URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/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, include from drf_yasg.views import get_schema_view from drf_yasg import openapi from django.conf.urls.static import static from django.conf import settings schema_view = get_schema_view( openapi.Info(title="Supplier Module Backend API DOCS", default_version="v1"), public=True, ) urlpatterns = [ path('admin/', admin.site.urls), path( "", schema_view.with_ui("swagger", cache_timeout=0), name="schema-swagger-ui", ), path('api/suppliers/', include("suppliers.urls")) ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATICFILES_DIRS)
[ "sandeepsajan0@gmail.com" ]
sandeepsajan0@gmail.com
a16fd3bc38021a1cbd05f2155ca066692604dadd
fb82ff30fba273eb4a30b5b2e1aceef6bd44ef16
/labs/lab1/test_something.py
d8df569aa211c392b5b3c346276505cba1175110
[ "LicenseRef-scancode-public-domain-disclaimer" ]
permissive
jpchauvel/python-tdd-lab
f882e7684f2793e70064fd45b09928b56a81521f
2a2e0ee4da15e36e809cdded56cffb6e2b97d90f
refs/heads/master
2021-10-10T12:11:53.765289
2013-05-31T00:30:20
2013-05-31T00:30:20
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,240
py
#!/usr/bin/env python import unittest from mockito import * from something import Something, Operand class SomethingTestCase(unittest.TestCase): def test_init_should_assign_what(self): # setup # action something = Something("what") # assert self.assertTrue("what", something.attribute) def test_doing_something_should_return_string_something(self): # setup something = Something("what") # action ret = something.doing_something() # assert self.assertTrue("something", ret) def test_doing_something_should_return_string_something_else(self): # setup something = Something(any(unicode)) # action ret = something.doing_something() # assert self.assertTrue("something else", ret) def test_send_result_should_add_op2_to_op1(self): # setup something, op1, op2 = self.getSomething() # action something.send_result() # assert verify(op1).add(op2) def test_send_result_should_first_sum_op1_op2_then_send_op1(self): # setup something, op1, op2 = self.getSomething() # action something.send_result() # assert inorder.verify(op1, times=1).add(op2) inorder.verify(op1, times=2).send() def test_send_result_should_raise_network_problem_exception_when_op1_is_None(self): # setup something, op1, op2 = self.getSomething() something.op1 = None # assert with self.assertRaises(Something.NetworkProblemException): # action something.send_result() def test_send_result_should_execute_catch_handler_when_send_raises_exception(self): # setup something, op1, op2 = self.getSomething() when(op1).send().thenRaise(Operand.AException) # action something.send_result() # assert verify(op1, times=1).rollback() def getSomething(self): op1 = mock() op2 = mock() something = Something(any()) something.op1 = op1 something.op2 = op2 return (something, op1, op2) if __name__ == "__main__": unittest.main()
[ "jchauvel@gmail.com" ]
jchauvel@gmail.com
b6ac1b30f2e2945d3614065769acc51d93c141e1
5417e1346bd280746c5b64501370af6b4f040fd3
/data/make_hdf5.py
9c27323c466bf9a5e71ea1a20d52659d1b23c552
[ "Apache-2.0" ]
permissive
shirgur/ACDRNet
3fa03620acd1b45a6fcef8c0ea18fa0fc600f999
bf7e5a93149dd1e71a42669f2463212e7bb82bd3
refs/heads/master
2020-09-22T09:05:18.522704
2019-12-01T09:01:33
2019-12-01T09:01:33
225,132,296
80
14
null
null
null
null
UTF-8
Python
false
false
1,009
py
import h5py import os from glob import glob import numpy as np from imageio import imread from tqdm import tqdm import argparse parser = argparse.ArgumentParser(description='Convert Cityscapes to HDF5') parser.add_argument('--images-path', type=str, default='/path/to/leftImg8bit', help='Path to <leftImg8bit> Cityscapes dataset') parser.add_argument('--outdir', type=str, default='/path/to/cityscapes_instances', help='Save path (should be the same as the output path of generate_cityscapes_instances.py') args = parser.parse_args() images_path = glob(os.path.join(args.images_path, '**/**/*.png')) short_path = [s[55:] for s in images_path] file_name = 'all_images.hdf5' with h5py.File(os.path.join(args.outdir, file_name), 'a') as f: for i, path in enumerate(tqdm(images_path)): image = imread(path) data_seg = f.create_dataset(short_path[i], image.shape, data=image, compression="gzip", dtype=np.uint8)
[ "me@gurshir.com" ]
me@gurshir.com
707fd5dd8d9b2dc50e94704045899f6ca054ae81
8c02ab9a04290ffd5402de443599492d1fa6c606
/holbertonschool-higher_level_programming/0x03-python-data_structures/0-print_list_integer.py
3eea513e5bbbdd98e4099924c288417c7e4d39d0
[]
no_license
Syssos/Holberton_School
87149d86f245e23f3efbe794b8cb60c4b5ce52ef
734c6c25167983593accdeffd30c3d9831ffebd8
refs/heads/main
2023-04-10T05:46:02.418480
2021-05-03T07:26:40
2021-05-03T07:26:40
363,835,101
0
0
null
null
null
null
UTF-8
Python
false
false
135
py
#!/usr/bin/python3 def print_list_integer(my_list=[]): for i in range(0, len(my_list)): print('{:d}'.format(my_list[i]))
[ "paral.cody98@gmail.com" ]
paral.cody98@gmail.com
f25f2801e7e085cce4ae334f1f668228f407c6d9
803bfc6a5eaa5791b0fdf939a87811f3334d0458
/tests/test_room_freeze.py
3eb13df4d90aa80123d7628615d74b9a1f300fb9
[ "Apache-2.0" ]
permissive
matrix-org/synapse-freeze-room
09c845cfacf7ebb6426ebca1692984e0a401a46c
f5e614a68ea223263e1adf42c8b78dabaa379814
refs/heads/main
2023-08-11T17:01:19.715389
2021-09-21T13:50:08
2021-09-21T13:50:08
389,677,698
3
2
Apache-2.0
2021-09-21T13:50:08
2021-07-26T15:17:32
Python
UTF-8
Python
false
false
17,495
py
# -*- coding: utf-8 -*- # Copyright 2021 The Matrix.org Foundation C.I.C. # # 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. import copy # From Python 3.8 onwards, aiounittest.AsyncTestCase can be replaced by # unittest.IsolatedAsyncioTestCase, so we'll be able to get rid of this dependency when # we stop supporting Python < 3.8 in Synapse. import aiounittest from synapse.api.room_versions import RoomVersions from synapse.events import FrozenEventV3 from freeze_room import FROZEN_STATE_TYPE, EventTypes, Membership, FreezeRoom from tests import create_module class RoomFreezeTest(aiounittest.AsyncTestCase): def setUp(self): self.user_id = "@alice:example.com" self.left_user_id = "@nothere:example.com" self.mod_user_id = "@mod:example.com" self.room_id = "!someroom:example.com" self.state = { (EventTypes.PowerLevels, ""): FrozenEventV3( { "sender": self.user_id, "type": EventTypes.PowerLevels, "state_key": "", "content": { "ban": 50, "events": { "m.room.avatar": 50, "m.room.canonical_alias": 50, "m.room.encryption": 100, "m.room.history_visibility": 100, "m.room.name": 50, "m.room.power_levels": 100, "m.room.server_acl": 100, "m.room.tombstone": 100, }, "events_default": 0, "invite": 0, "kick": 50, "redact": 50, "state_default": 50, "users": { self.user_id: 100, self.left_user_id: 75, self.mod_user_id: 50, }, "users_default": 0 }, "room_id": self.room_id, }, RoomVersions.V7, ), (EventTypes.JoinRules, ""): FrozenEventV3( { "sender": self.user_id, "type": EventTypes.JoinRules, "state_key": "", "content": {"join_rule": "public"}, "room_id": self.room_id, }, RoomVersions.V7, ), (EventTypes.Member, self.mod_user_id): FrozenEventV3( { "sender": self.mod_user_id, "type": EventTypes.Member, "state_key": self.mod_user_id, "content": {"membership": Membership.JOIN}, "room_id": self.room_id, }, RoomVersions.V7, ), (EventTypes.Member, self.left_user_id): FrozenEventV3( { "sender": self.left_user_id, "type": EventTypes.Member, "state_key": self.left_user_id, "content": {"membership": Membership.LEAVE}, "room_id": self.room_id, }, RoomVersions.V7, ), } async def test_send_frozen_state(self): """Tests that the module allows frozen state change, and that users on the unfreeze blacklist are forbidden from unfreezing it. """ module = create_module( config_override={"unfreeze_blacklist": ["evil.com"]}, ) # Test that an event with a valid value is allowed. freeze_event = self._build_frozen_event(sender=self.user_id, frozen=True) allowed, replacement = await module.check_event_allowed(freeze_event, self.state) self.assertTrue(allowed) # Make sure the replacement data we've got is the same event; we send it to force # Synapse to rebuild it because we've changed the state. self.assertEqual(replacement, freeze_event.get_dict()) # Test that an unfreeze sent from a forbidden server isn't allowed. allowed, _ = await module.check_event_allowed( self._build_frozen_event(sender="@alice:evil.com", frozen=False), self.state, ) self.assertFalse(allowed) # Test that a freeze sent from a forbidden server is allowed. allowed, _ = await module.check_event_allowed( self._build_frozen_event(sender="@alice:evil.com", frozen=True), self.state, ) self.assertTrue(allowed) # Test that an event sent with an non-boolean value isn't allowed. allowed, _ = await module.check_event_allowed( self._build_frozen_event(sender=self.user_id, frozen="foo"), self.state, ) self.assertFalse(allowed) async def test_power_levels_sent_when_freezing(self): """Tests that the module sends the right power levels update when it sees a room being unfrozen. """ module = create_module() pl_event_dict = await self._send_frozen_event_and_get_pl_update(module, True) self.assertEqual(pl_event_dict["content"]["users_default"], 100) for user, pl in pl_event_dict["content"]["users"].items(): self.assertEqual(pl, 100, user) async def test_power_levels_sent_when_unfreezing(self): """Tests that the module sends the right power levels update when it sees a room being unfrozen, and that the resulting power levels update is allowed when the room is frozen (since we persist it before finishing to process the unfreeze). """ module = create_module() pl_event_dict = await self._send_frozen_event_and_get_pl_update(module, False) self.assertEqual(pl_event_dict["content"]["users_default"], 0) self.assertEqual(pl_event_dict["content"]["users"][self.user_id], 100) # Make sure the power level event is allowed when the room is frozen (since it # will be sent before the frozen event finishes persisting). self.state[(FROZEN_STATE_TYPE, "")] = self._build_frozen_event(self.user_id, True) pl_event = FrozenEventV3(pl_event_dict, RoomVersions.V7) allowed, replacement = await module.check_event_allowed(pl_event, self.state) self.assertTrue(allowed) self.assertIsNone(replacement) async def test_join_rules_sent_when_freezing(self): """Tests that the module resets the join rules to "invite" if the room gets frozen. """ module = create_module() allowed, _ = await module.check_event_allowed( self._build_frozen_event(sender=self.user_id, frozen=True), self.state, ) self.assertTrue(allowed) # Test that two events have been sent (the join rules change and the PL change) # and that one of them is the correct join rules change. self.assertTrue(module._api.create_and_send_event_into_room.called) args = module._api.create_and_send_event_into_room.call_args_list self.assertEqual(len(args), 2) join_rules_dict, _ = args[0] self.assertEqual(join_rules_dict[0]["content"]["join_rule"], "invite") async def test_cannot_send_messages_when_frozen(self): """Tests that users can't send messages when the room is frozen. Also tests that the power levels can't be updated in a different way than how it would happen with an unfreeze of the room. """ self.state[(FROZEN_STATE_TYPE, "")] = self._build_frozen_event(self.user_id, True) module = create_module() # Test that a normal message event isn't allowed when the room is frozen. allowed, _ = await module.check_event_allowed( FrozenEventV3( { "sender": self.user_id, "type": EventTypes.Message, "content": {"msgtype": "m.text", "body": "hello world"}, "room_id": self.room_id, }, RoomVersions.V7, ), self.state, ) self.assertFalse(allowed) # Check that, when the room is frozen, sending a PL update that sets the users # default back to 0 without naming a new admin isn't allowed. new_pl_event = copy.deepcopy(self.state[(EventTypes.PowerLevels, "")].get_dict()) new_pl_event["content"]["users"] = {} new_pl_event["content"]["users_default"] = 0 allowed, _ = await module.check_event_allowed( FrozenEventV3(new_pl_event, RoomVersions.V7), self.state, ) self.assertFalse(allowed) # Check that, when the room is frozen, sending a PL update that explictly # prevents someone from unfreezing the room isn't allowed. new_pl_event = copy.deepcopy(self.state[(EventTypes.PowerLevels, "")].get_dict()) new_pl_event["content"]["users"] = {} new_pl_event["content"]["users"]["@bob:example.com"] = 50 allowed, _ = await module.check_event_allowed( FrozenEventV3(new_pl_event, RoomVersions.V7), self.state, ) self.assertFalse(allowed) # Check that, when the room is frozen, sending a PL update that sets the users # default back to 0 while naming someone else admin isn't allowed. new_pl_event = copy.deepcopy(self.state[(EventTypes.PowerLevels, "")].get_dict()) new_pl_event["content"]["users"] = {} new_pl_event["content"]["users"]["@bob:example.com"] = 100 new_pl_event["content"]["users_default"] = 0 allowed, _ = await module.check_event_allowed( FrozenEventV3(new_pl_event, RoomVersions.V7), self.state, ) self.assertFalse(allowed) async def test_can_leave_room_when_frozen(self): """Tests that users can still leave a room when it's frozen.""" self.state[(FROZEN_STATE_TYPE, "")] = self._build_frozen_event(self.user_id, True) module = create_module() # Test that leaving the room is allowed. allowed, replacement = await module.check_event_allowed( FrozenEventV3( { "sender": self.user_id, "type": EventTypes.Member, "content": {"membership": Membership.LEAVE}, "room_id": self.room_id, "state_key": self.user_id, }, RoomVersions.V7, ), self.state, ) self.assertTrue(allowed) self.assertIsNone(replacement) # Test that kicking a user is not allowed. allowed, _ = await module.check_event_allowed( FrozenEventV3( { "sender": self.user_id, "type": EventTypes.Member, "content": {"membership": Membership.LEAVE}, "room_id": self.room_id, "state_key": "@bob:example.com", }, RoomVersions.V7, ), self.state, ) self.assertFalse(allowed) async def test_auto_freeze_when_last_admin_leaves(self): """Tests that the module freezes the room when it sees its last admin leave.""" module = create_module() leave_event = FrozenEventV3( { "sender": self.user_id, "type": EventTypes.Member, "content": {"membership": Membership.LEAVE}, "room_id": self.room_id, "state_key": self.user_id, }, RoomVersions.V7, ) allowed, replacement = await module.check_event_allowed(leave_event, self.state) self.assertTrue(allowed) self.assertEqual(replacement, None) # Test that the leave triggered a freeze of the room. self.assertTrue(module._api.create_and_send_event_into_room.called) args, _ = module._api.create_and_send_event_into_room.call_args self.assertEqual(len(args), 1) expected_dict = self._build_frozen_event(self.user_id, True).get_dict() del expected_dict["unsigned"] del expected_dict["signatures"] self.assertEqual(args[0], expected_dict) async def test_promote_when_last_admin_leaves(self): """Tests that the module promotes whoever has the highest non-default PL to admin when the last admin leaves, if the config allows it. """ # Set the config flag to allow promoting custom PLs before freezing the room. module = create_module(config_override={"promote_moderators": True}) # Make the last admin leave. leave_event = FrozenEventV3( { "sender": self.user_id, "type": EventTypes.Member, "content": {"membership": Membership.LEAVE}, "room_id": self.room_id, "state_key": self.user_id, }, RoomVersions.V7, ) # Check that we get the right result back from the callback. allowed, replacement = await module.check_event_allowed(leave_event, self.state) self.assertTrue(allowed) self.assertEqual(replacement, None) # Test that a new event was sent into the room. self.assertTrue(module._api.create_and_send_event_into_room.called) args, _ = module._api.create_and_send_event_into_room.call_args self.assertEqual(len(args), 1) # Test that: # * the event is a power levels update # * the user who is PL 75 but left the room didn't get promoted # * the user who was PL 50 and is still in the room got promoted evt_dict: dict = args[0] self.assertEqual(evt_dict["type"], EventTypes.PowerLevels, evt_dict) self.assertIsNotNone(evt_dict.get("state_key")) self.assertEqual(evt_dict["content"]["users"][self.left_user_id], 75, evt_dict) self.assertEqual(evt_dict["content"]["users"][self.mod_user_id], 100, evt_dict) # Now we push both the leave event and the power levels update into the state of # the room. self.state[(EventTypes.Member, self.user_id)] = leave_event self.state[(EventTypes.PowerLevels, "")] = FrozenEventV3( evt_dict, RoomVersions.V7, ) # Make the mod (newly admin) leave the room. new_leave_event = FrozenEventV3( { "sender": self.mod_user_id, "type": EventTypes.Member, "content": {"membership": Membership.LEAVE}, "room_id": self.room_id, "state_key": self.mod_user_id, }, RoomVersions.V7, ) # Check that we get the right result back from the callback. allowed, replacement = await module.check_event_allowed( new_leave_event, self.state, ) self.assertTrue(allowed) self.assertEqual(replacement, None) # Test that a new event was sent into the room. self.assertTrue(module._api.create_and_send_event_into_room.called) args, _ = module._api.create_and_send_event_into_room.call_args self.assertEqual(len(args), 1) # Test that now that there's no user to promote anymore, the room gets frozen. expected_dict = self._build_frozen_event(self.mod_user_id, True).get_dict() del expected_dict["unsigned"] del expected_dict["signatures"] self.assertEqual(args[0], expected_dict) async def _send_frozen_event_and_get_pl_update( self, module: FreezeRoom, frozen: bool, ) -> dict: """Sends a frozen state change and get the dict for the power level update it triggered. """ allowed, _ = await module.check_event_allowed( self._build_frozen_event(sender=self.user_id, frozen=frozen), self.state, ) self.assertTrue(allowed) self.assertTrue(module._api.create_and_send_event_into_room.called) args, _ = module._api.create_and_send_event_into_room.call_args self.assertEqual(len(args), 1) self.assertEqual(args[0]["type"], EventTypes.PowerLevels) return args[0] def _build_frozen_event(self, sender: str, frozen: bool) -> FrozenEventV3: """Build a new org.matrix.room.frozen event with the given sender and value.""" event_dict = { "sender": sender, "type": FROZEN_STATE_TYPE, "content": {"frozen": frozen}, "room_id": self.room_id, "state_key": "", } return FrozenEventV3(event_dict, RoomVersions.V7)
[ "babolivier@matrix.org" ]
babolivier@matrix.org
ec654eb8283a3e2a92081b84490302b0b09eda85
49f29b239e981d94bd08d3e2632a6cd4450dd75c
/recipes/migrations/0010_recipe_total_time.py
522a182fc0b8435c9bb6803daa95d3a94872978b
[]
no_license
gabrielajohnson/Recipeas
7c29eb0d297f7f24b3e51a44edff8dc4814d8ad3
5b6cfe73886368e4b13367adf25ca064d568483a
refs/heads/master
2023-07-11T18:45:02.549926
2021-08-31T20:44:51
2021-08-31T20:44:51
261,852,308
0
0
null
null
null
null
UTF-8
Python
false
false
420
py
# Generated by Django 3.0.3 on 2020-04-30 22:41 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('recipes', '0009_category_custom'), ] operations = [ migrations.AddField( model_name='recipe', name='total_time', field=models.IntegerField(default=0), preserve_default=False, ), ]
[ "gabrielagj23@gmail.com" ]
gabrielagj23@gmail.com
a1198ac966cef0a943705adff33dfca92da2c9de
30d5c4e7935675afeb206a61e55aad17971b3759
/venv/bin/wheel
76aa0ec357728ef29610c86f5f84871e087f4c0a
[]
no_license
ChrisGk89/recommendation
e959f4a0ddd59e46672598645f8220c4206e4104
147157fcce04dcd2acef300514d5a0da45bb3ab4
refs/heads/master
2020-04-05T14:17:46.731278
2019-01-30T21:19:53
2019-01-30T21:19:53
156,922,585
0
1
null
null
null
null
UTF-8
Python
false
false
265
#!/Users/christosgkalfas/PycharmProjects/recommendation/venv/bin/python # -*- coding: utf-8 -*- import re import sys from wheel.cli import main if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit(main())
[ "info@chrisgkalfas.com" ]
info@chrisgkalfas.com
f7b044026539ece804e5bf8f53bc93fe058cc84d
44ea306fd23a031b16fddb0de30bc8f6c0e37d3c
/backend/api/urls.py
3d9aa829352a05a767f93d8e18f1375f8e02215b
[]
no_license
tushar34/flip-backup
e1cfc1374d7da044a29ba4b63d86970a10f6059b
8cc24648101683ec9ab060f8548a6aaf4739390f
refs/heads/master
2023-08-01T04:25:40.009413
2021-09-14T13:49:07
2021-09-14T13:49:07
406,385,610
1
0
null
null
null
null
UTF-8
Python
false
false
1,882
py
from django.contrib import admin from django.urls import path, include from .views import * urlpatterns = [ path('login/', LoginView.as_view(), name="login"), path('register/', RegisterView.as_view(), name="register"), path('getallproduct/', GetallproductView.as_view(), name="getallproduct"), path('getproduct/', ProductView.as_view(), name="product"), path('addtocart/', AddtocartView.as_view(), name="cart"), path('removetocart/', RemovetocartView.as_view(), name="remove-cart"), path('usercartlist/', UsercartlistView.as_view(), name="cart-list"), path('getuser/', GetuserView.as_view(), name="user"), path('deletecartitem/', DeletecartitemView.as_view(), name="deletecartitem"), path('city/', CityView.as_view(), name="city"), path('address/', AddressView.as_view(), name="address"), path('get-address/<int:id>', AddressView.as_view(), name="get-address"), path('edit-address/<int:id>', AddressView.as_view(), name="edit-address"), path('payment', PaymentView.as_view(), name="payment"), path('mobile-data/', Fetchproductofmobile.as_view(), name="mobile-data"), path('sub_category_data/', Fetchproduct_by_sub_category_id.as_view(), name="get-data-by-sub_ca_id"), path('backpack-data/', Fetchproductofbackpack.as_view(), name="backpack-data"), path('watch-data/', Fetchproductofwatch.as_view(), name="watch-data"), path('sound-data/', Fetchproductofsound.as_view(), name="sound-data"), path('update-username/', Update_username.as_view(), name="update_username"), path('get-user/', Getuserdetail.as_view(), name="getuser"), path('update-phonenumber/', Update_phonenumber.as_view(), name="update-phonenumber"), path('update-password/', Update_password.as_view(), name="update-password"), path('get-ordered-item/', User_ordered_item.as_view(), name="get-order-data"), ]
[ "tushar.paradva@dignizant.com" ]
tushar.paradva@dignizant.com
c3eb42d47d98220ce96e97caded22f4c220dc513
f6fb2b14bddedadd39ae8a060cd11ff7fd1effe4
/Web Tools/jinja_tools.py
ed1947adbc1a6098bc500c84a0cc1e80741aa842
[]
no_license
naveenailawadi/2020
f3c9794df3fcb179f8c3f602590ee54b8bca204c
b535f554bd382910174af844e24a5c7f0f16f727
refs/heads/master
2021-09-08T20:26:39.932025
2021-08-30T21:56:50
2021-08-30T21:56:50
250,462,727
0
0
null
null
null
null
UTF-8
Python
false
false
403
py
from pyperclip import copy def format_static(file): formatted_string = f"url_for('static', filename='{file}')" formatted_string = '{{' + formatted_string + '}}' return formatted_string def format_on_input(): while True: some_file = input('Filename: ') formatted_string = format_static(some_file) print('\n') # copy it copy(formatted_string)
[ "naveen.ailawadi91@gmail.com" ]
naveen.ailawadi91@gmail.com
82ce214ec32bea3e95a8df26a76b709fbb336f96
afa211d7161b59414149fbde4f55af95e9e0ba25
/setup.py
71fd02ebf1dc1508ae7fc5e0cee36d0584e27f95
[]
no_license
aniqueazhar/GPcrawler
79830af4da47f6be97d84ae6f8550341124a3d5f
523ce6476cc0d68bc91d7c392fd4c591ea5a8226
refs/heads/main
2023-07-16T10:12:43.056872
2021-08-24T07:40:17
2021-08-24T07:40:17
null
0
0
null
null
null
null
UTF-8
Python
false
false
166
py
#!/usr/bin/python3 from setuptools import setup, find_packages setup( name='GPcrawler', classifiers=['Programming Language :: Python :: 3.8'] )
[ "dolphin222@daum.net" ]
dolphin222@daum.net
516fe6d919ac4f281d58d62191e17b1d1b0915db
45f7a9b44ea1c45448703707da793d51151c0527
/ui_tests/examples/examples_03.py
6cbe239e09666abb076794312777347c51028740
[]
no_license
basdijkstra/python-for-testers
a40d30432c31712c6d0eadbca9de73056ff10535
50bfbabfb2b8426eed8d048b0448959c34f71b61
refs/heads/master
2023-05-24T18:48:58.557924
2023-05-23T05:44:11
2023-05-23T05:44:11
219,865,075
7
4
null
2023-05-23T05:44:13
2019-11-05T22:47:09
Python
UTF-8
Python
false
false
1,047
py
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as ec import pytest @pytest.fixture def browser(): driver = webdriver.Chrome() driver.maximize_window() yield driver driver.quit() def test_successful_google_search(browser): browser.get("https://www.google.com") send_keys(browser, By.NAME, "q", "Maserati") click(browser, By.NAME, "btnK") assert browser.title == "Maserati - Google zoeken" assert browser.find_element_by_id("resultStats").is_displayed() is True def send_keys(driver, locator_strategy, locator, text_to_type): element = WebDriverWait(driver, 10).until( ec.element_to_be_clickable((locator_strategy, locator)) ) element.send_keys(text_to_type) def click(driver, locator_strategy, locator): element = WebDriverWait(driver, 10).until( ec.element_to_be_clickable((locator_strategy, locator)) ) element.click()
[ "bas@ontestautomation.com" ]
bas@ontestautomation.com
350eea22b8d26438f7aa51844ec20b50f9fe940d
ddd03d701afdf89820ac58e28469460569951d8d
/wedding/pages/migrations/0004_auto__add_field_rsvp_email__add_field_rsvp_response.py
e76abaa52637a544bb16a755e3f20eb729e4cf59
[]
no_license
sunnyar/wedding
c8bb8d0fc0d1f323eb5463682f310c5a21c34f9c
b15d58f06dfc51afe1e8bf40588d892b924aaeb6
refs/heads/master
2018-12-28T02:38:43.327951
2014-11-03T22:51:18
2014-11-03T22:51:18
null
0
0
null
null
null
null
UTF-8
Python
false
false
10,443
py
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Rsvp.email' db.add_column(u'pages_rsvp', 'email', self.gf('django.db.models.fields.EmailField')(default=None, max_length=75), keep_default=False) # Adding field 'Rsvp.response' db.add_column(u'pages_rsvp', 'response', self.gf('django.db.models.fields.CharField')(default=None, max_length=15), keep_default=False) def backwards(self, orm): # Deleting field 'Rsvp.email' db.delete_column(u'pages_rsvp', 'email') # Deleting field 'Rsvp.response' db.delete_column(u'pages_rsvp', 'response') models = { u'auth.group': { 'Meta': {'object_name': 'Group'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, u'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'pages.address': { 'Meta': {'object_name': 'Address'}, 'city': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'event': ('django.db.models.fields.CharField', [], {'max_length': '20'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'state': ('django.db.models.fields.CharField', [], {'max_length': '20'}), 'street': ('django.db.models.fields.TextField', [], {}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}), 'zip_code': ('django.db.models.fields.CharField', [], {'max_length': '10'}) }, u'pages.page': { 'Meta': {'object_name': 'Page'}, 'body': ('django.db.models.fields.TextField', [], {}), 'created': ('django.db.models.fields.DateTimeField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}) }, u'pages.photocontent': { 'Meta': {'ordering': "['-date_added']", 'object_name': 'PhotoContent', '_ormbases': [u'photologue.Photo']}, u'photo_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['photologue.Photo']", 'unique': 'True', 'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}) }, u'pages.rsvp': { 'Meta': {'object_name': 'Rsvp'}, 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '15'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '15'}), 'response': ('django.db.models.fields.CharField', [], {'max_length': '15'}) }, u'pages.wedding': { 'Meta': {'object_name': 'Wedding'}, 'bride_first_name': ('django.db.models.fields.CharField', [], {'max_length': '20'}), 'bride_last_name': ('django.db.models.fields.CharField', [], {'max_length': '20'}), 'groom_first_name': ('django.db.models.fields.CharField', [], {'max_length': '20'}), 'groom_last_name': ('django.db.models.fields.CharField', [], {'max_length': '20'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'location': ('django.db.models.fields.CharField', [], {'max_length': '20'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}), 'wedding_date': ('django.db.models.fields.DateField', [], {}) }, u'photologue.photo': { 'Meta': {'ordering': "['-date_added']", 'object_name': 'Photo'}, 'caption': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'crop_from': ('django.db.models.fields.CharField', [], {'default': "'center'", 'max_length': '10', 'blank': 'True'}), 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'date_taken': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'effect': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'photo_related'", 'null': 'True', 'to': u"orm['photologue.PhotoEffect']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'}), 'is_public': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'sites': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['sites.Site']", 'null': 'True', 'blank': 'True'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50'}), 'tags': ('tagging.fields.TagField', [], {}), 'title': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50'}), 'view_count': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}) }, u'photologue.photoeffect': { 'Meta': {'object_name': 'PhotoEffect'}, 'background_color': ('django.db.models.fields.CharField', [], {'default': "'#FFFFFF'", 'max_length': '7'}), 'brightness': ('django.db.models.fields.FloatField', [], {'default': '1.0'}), 'color': ('django.db.models.fields.FloatField', [], {'default': '1.0'}), 'contrast': ('django.db.models.fields.FloatField', [], {'default': '1.0'}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'filters': ('django.db.models.fields.CharField', [], {'max_length': '200', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}), 'reflection_size': ('django.db.models.fields.FloatField', [], {'default': '0'}), 'reflection_strength': ('django.db.models.fields.FloatField', [], {'default': '0.6'}), 'sharpness': ('django.db.models.fields.FloatField', [], {'default': '1.0'}), 'transpose_method': ('django.db.models.fields.CharField', [], {'max_length': '15', 'blank': 'True'}) }, u'sites.site': { 'Meta': {'ordering': "(u'domain',)", 'object_name': 'Site', 'db_table': "u'django_site'"}, 'domain': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) } } complete_apps = ['pages']
[ "sunnyarora07@ip-10-120-219-139.ec2.internal" ]
sunnyarora07@ip-10-120-219-139.ec2.internal
7273bb0df3bdc0d5af594a9b832e7630eb3129aa
7081389c8e83a47221ca8e9af2914a2644471d5b
/test.py
cf38bcc2ad4561f4a4485195caba40fed2303458
[]
no_license
allenfishkuo/DataScience_project
253d9efe91c9058d117ca434d6df5610d5f310ca
d2c19c24c2eb12c5a92675a4c4c538328a8810ec
refs/heads/main
2023-02-16T02:37:40.368945
2020-12-30T11:57:26
2020-12-30T11:57:26
324,945,375
0
0
null
null
null
null
UTF-8
Python
false
false
13,165
py
# -*- coding: utf-8 -*- """ Created on Tue Mar 3 16:23:13 2020 @author: allen """ import torch import torch.nn as nn import numpy as np import new_dataloader import trading_period_by_gate_mean_new #import matrix_trading import os import pandas as pd import torch import torch.utils.data as Data import matplotlib.pyplot as plt import time path_to_image = "C:/Users/Allen/pair_trading DL/negative profit of 2018/" path_to_average = "./2017/averageprice/" ext_of_average = "_averagePrice_min.csv" path_to_minprice = "./2017/minprice/" ext_of_minprice = "_min_stock.csv" path_to_2015compare = "./newstdcompare2015/" path_to_2016compare = "./newstdcompare2016/" path_to_2017compare = "./newstdcompare2017/" path_to_2018compare = "./newstdcompare2018/" ext_of_compare = "_table.csv" path_to_python ="C:/Users/Allen/pair_trading DL4" path_to_half = "C:/Users/Allen/pair_trading DL2/2016/2016_half/" path_to_2017half = "./2017_halfmin/" path_to_2018half = "./2018_halfmin/" ext_of_half = "_half_min.csv" path_to_profit = "./profit/wavenet2018/" max_posion = 5 def test_reward(): total_reward = 0 total_num = 0 total_trade =[0,0,0] action_list=[] check = 0 #actions =[[0.5000000000001013, 1.6058835588357105], [1.1231567674441643, 3.009226460170205], [1.6774656461992412, 8.482170812315225], [2.434225143491954, 5.0301795963708305], [3.838786213786223, 7.405844155844149], [50, 100]] #actions =[[0.5000000000001013, 1.6058835588357105], [0.8422529644270367, 2.7302766798420457], [1.42874957000333, 3.312693498451958], [1.681668686169194, 8.472736714557769], [2.054041204437417, 4.680031695721116], [3.1352641629535314, 5.810311903246376], [4.378200155159055, 8.429014740108636], [5.632843137254913, 16.43431372549023], [6.8013888888889005, 13.081481481481516], [50,100]] #actions = [[0.5000000000002669, 2.500000000000112], [0.7288428324698772, 4.0090056748083995], [1.1218344155846804, 3.0000000000002496], [1.2162849872773496, 7.4631043256997405], [1.4751902346226717, 3.9999999999997113], [1.749999999999973, 3.4999999999998117], [2.086678832116794, 6.2883211678832325], [2.193017888055368, 4.018753606462444], [2.2499999999999822, 7.500000000000021], [2.6328389830508536, 8.9762711864407], [2.980046948356806, 13.515845070422579], [3.2499999999999982, 5.500000000000034], [3.453852327447829, 11.505617977528125], [3.693027210884357, 6.0739795918367605], [4.000000000000004, 12.500000000000034], [4.151949541284411, 10.021788990825703], [4.752819548872187, 15.016917293233117], [4.8633603238866225, 7.977058029689605], [5.7367647058823605, 13.470588235294136], [6.071428571428564, 16.47435897435901], [6.408839779005503, 10.95488029465933], [7.837962962962951, 12.745370370370392], [8.772727272727282, 18.23295454545456], [9.242088607594926, 14.901898734177237], [100,200]] # actions = [[0.5000000000001132, 2.9999999999999174], [0.5000000000001159, 1.4999999999998659], [0.5011026964048937, 5.057090545938981], [0.5997656402578979, 1.9999999999999885], [0.7450101488498877, 2.500000000000264], [0.9957274202272546, 3.5038669551108814], [0.9986299023806298, 3.00000000000035], [0.9989438479141635, 6.000440063369089], [1.2502992817239085, 7.499301675977626], [1.3748807883861818, 5.499999999999963], [1.4714078698027613, 5.000000000000162], [1.6540920096852696, 4.3137046004844875], [1.7331017056222244, 8.988629185091602], [1.9997078301519378, 10.003506038176837], [2.131133083912334, 6.300320684126101], [2.2702554744525623, 7.199270072992672], [2.6956923890063442, 7.93093727977449], [2.9601038145823297, 8.740704973442782], [3.4156698564593317, 10.223684210526311], [4.180390032502709, 11.496208017334773], [4.475710508922673, 13.83311302048908], [5.686262376237629, 16.102103960396033], [7.189858490566042, 19.562500000000004], [9.489123012389175, 23.9905618964017], [100, 200]] #1-82013-2016#actions = [[1.0971083893545064, 12.780734874297824], [1.1227439921530564, 5.0000000000002025], [1.2335853575094577, 9.677591515566052], [1.2511041713139057, 15.999999999999872], [1.5038041133323725, 19.282755645045146], [1.686532170119944, 17.458312679686593], [1.9264175557936942, 7.2370125331967], [2.02304897137745, 5.627124329159388], [2.4325072358900095, 10.699589966232447], [2.5779913972888493, 13.130344108446305], [2.8119307692307682, 20.224307692307548], [2.852625298329354, 15.483160965261133], [3.2014590979045794, 9.185272877944676], [3.2373171223892623, 7.566037735848912], [3.6211730801830813, 22.306323105610964], [4.00415665989285, 11.104008867541099], [4.726152954808812, 20.078099652375336], [4.864921154418321, 12.499553704254689], [4.930584600760447, 17.123811787072206], [5.793574014481093, 14.29042638777153], [6.2467695620962, 23.51040918880109], [7.439736399326975, 19.99691531127306], [7.49569402228977, 17.16548463356975], [9.417529752331845, 23.923769700868746], [100, 2000]] #actions = [[0.5002033307514231, 9.999612703330783], [0.6802278275020894, 6.970301057770593], [1.1979313380281675, 14.240316901408438], [1.238262527233124, 11.421023965141616], [1.3402498377676804, 16.44159636599612], [1.4550034387895419, 22.414030261348046], [1.7906383921974274, 19.403576178513426], [1.8334690074539046, 6.07659866614364], [1.9509871600165671, 9.182797183487537], [1.9844808743169393, 5.00000000000005], [2.263022959183676, 7.842091836734736], [2.7651543942992896, 14.789548693586722], [3.1221539283805497, 16.213254943880298], [3.350909570261011, 12.044819404165569], [3.3748820754717013, 22.837853773584932], [3.5011228070175466, 6.6417543859649335], [3.6605886116442767, 9.704414587332057], [4.388342585249806, 8.21570182394924], [4.752295918367349, 14.082417582417579], [5.4250279329609, 17.403351955307247], [6.023128205128209, 23.252307692307696], [6.186773199845984, 11.237581825182907], [7.178633217993089, 15.37456747404844], [7.83320148331276, 20.010383189122425], [100, 2000]] #2015-2016_op #actions =[[0.5, 10.0], [1.3000000000000007, 23.0], [1.3500000000000008, 6.0], [1.4000000000000008, 20.0], [1.600000000000001, 12.0], [1.6500000000000008, 16.0], [1.7500000000000009, 9.0], [1.8000000000000012, 9.0], [1.9000000000000008, 19.0], [1.9500000000000013, 5.0], [2.0000000000000013, 6.0], [2.1000000000000014, 9.0], [2.200000000000001, 6.0], [2.4000000000000017, 10.0], [2.650000000000002, 12.0], [2.7500000000000018, 15.0], [2.9000000000000017, 20.0], [3.3500000000000023, 16.0], [7.900000000000008, 20.0], [100, 2000]] # number of >800 label actions = [[0.5,2.5],[1.0,3.0],[1.5,3.5],[2.0,4.0],[2.5,4.5],[3.0,5.0]] #actions = [[0.49999999999998446, 3.5000000000000355], [0.5000000000002669, 2.500000000000112], [0.7499999999999689, 3.9999999999997025], [0.8255813953488285, 4.6886304909561005], [0.9999999999999694, 2.9999999999995994], [1.2174744897959144, 7.459183673469383], [1.24999999999997, 2.9999999999996234], [1.4751902346226717, 3.9999999999997113], [1.749999999999973, 3.4999999999998117], [1.7500000000000058, 6.499999999999994], [1.8023648648648616, 8.797297297297295], [1.9999999999999754, 4.030545112781948], [2.2499999999999822, 7.500000000000021], [2.499999999999994, 4.000000000000044], [2.4999999999999973, 6.028455284552839], [2.7500000000000036, 9.00193610842209], [2.980046948356806, 13.515845070422579], [3.2499999999999982, 5.500000000000034], [3.453852327447829, 11.505617977528125], [3.693027210884357, 6.0739795918367605], [4.000000000000004, 12.500000000000034], [4.1462703962704035, 10.038461538461554], [4.500000000000006, 7.499999999999996], [4.752819548872187, 15.016917293233117], [5.0904605263157805, 8.298245614035086], [5.526881720430115, 16.478494623655948], [5.71363636363637, 13.500000000000018], [5.964062500000008, 11.496874999999998], [6.593427835051529, 10.751288659793836], [7.252808988764048, 16.44382022471911], [7.830188679245271, 12.721698113207568], [8.8031914893617, 16.978723404255312], [8.826086956521737, 19.304347826086953], [9.22258064516128, 14.825806451612925], [100,200]] #print(actions[0][0]) #Net = CNN_classsification1() #print(Net) Net = torch.load('2016-2016_6action.pkl') Net.eval() #print(Net) whole_year = new_dataloader.test_data() whole_year = torch.FloatTensor(whole_year).cuda() #print(whole_year) torch_dataset_train = Data.TensorDataset(whole_year) whole_test = Data.DataLoader( dataset=torch_dataset_train, # torch TensorDataset format batch_size = 128, # mini batch size shuffle = False, ) for step, (batch_x,) in enumerate(whole_test): #print(batch_x) output = Net(batch_x) # cnn output _, predicted = torch.max(output, 1) action_choose = predicted.cpu().numpy() action_choose = action_choose.tolist() action_list.append(action_choose) # action_choose = predicted.cpu().numpy() action_list =sum(action_list, []) print(len(action_list)) total_table = 0 count_test = 0 datelist = [f.split('_')[0] for f in os.listdir(path_to_2017compare)] #print(datelist[167:]) profit_count = 0 for date in sorted(datelist[:]): #決定交易要從何時開始 table = pd.read_csv(path_to_2017compare+date+ext_of_compare) mindata = pd.read_csv(path_to_average+date+ext_of_average) total_table += len(table) print(total_table) #try: tickdata = pd.read_csv(path_to_minprice+date+ext_of_minprice)#.drop([266, 267, 268, 269, 270]) #except: #continue #halfmin = pd.read_csv(path_to_half+date+ext_of_half) #print(tickdata.shape) tickdata = tickdata.iloc[166:] tickdata.index = np.arange(0,len(tickdata),1) num = np.arange(0,len(table),1) print(date) for pair in num: #看table有幾列配對 依序讀入 #action_choose = 0 #try : # spread = table.w1[pair] * np.log(mindata[ str(table.stock1[pair]) ]) + table.w2[pair] * np.log(mindata[ str(table.stock2[pair]) ]) ## continue for i in range(6): # print(action_list[count_test]) #print(count_test) if action_list[count_test] == i : open, loss = actions[i][0], actions[i][1] #open, loss = 0.75, 2.5# profit,opennum,trade_capital,trading = trading_period_by_gate_mean_new.pairs( pair ,166, table , mindata , tickdata , open ,open, loss ,mindata, max_posion , 0.0015, 0.0015 , 300000000 ) #print(trading) if profit > 0 and opennum == 1 : profit_count +=1 #print("有賺錢的pair",profit) """ flag = os.path.isfile(path_to_profit+str(date)+'_profit.csv') if not flag : df = pd.DataFrame({"stock1":[table.stock1[pair]],"stock2":[table.stock2[pair]],"trade_capital":[trade_capital],"open":[open],"loss":[loss],"reward":[profit],"open_num":[opennum]}) df.to_csv(path_to_profit+str(date)+'_profit.csv', mode='w',index=False) else : df = pd.DataFrame({"stock1":[table.stock1[pair]],"stock2":[table.stock2[pair]],"trade_capital":[trade_capital],"open":[open],"loss":[loss],"reward":[profit],"open_num":[opennum]}) df.to_csv(path_to_profit+str(date)+'_profit.csv', mode='a', header=False,index=False) """ elif opennum ==1 and profit < 0 : #print("賠錢的pair :", profit) """ flag = os.path.isfile(path_to_profit+str(date)+'_profit.csv') if not flag : df = pd.DataFrame({"stock1":[table.stock1[pair]],"stock2":[table.stock2[pair]],"trade_capital":[trade_capital],"open":[open],"loss":[loss],"reward":[profit],"open_num":[opennum]}) df.to_csv(path_to_profit+str(date)+'_profit.csv', mode='w',index=False) else : df = pd.DataFrame({"stock1":[table.stock1[pair]],"stock2":[table.stock2[pair]],"trade_capital":[trade_capital],"open":[open],"loss":[loss],"reward":[profit],"open_num":[opennum]}) df.to_csv(path_to_profit+str(date)+'_profit.csv', mode='a', header=False,index=False) """ #print("開倉次數 :",opennum) if opennum == 1 or opennum == 0: check += 1 total_reward += profit total_num += opennum count_test +=1 total_trade[0] += trading[0] total_trade[1] += trading[1] total_trade[2] += trading[2] print("contest",count_test) print("total :",check) #print(count_test) print("利潤 and 開倉次數 and 開倉有賺錢的次數/開倉次數:",total_reward ,total_num, profit_count/total_num) print("開倉有賺錢次數 :",profit_count) print("正常平倉 停損平倉 強迫平倉 :",total_trade[0],total_trade[1],total_trade[2]) #test()
[ "allenlike20@gmail.com" ]
allenlike20@gmail.com
bbce0488f3266680f4aa4368584031c16a2d255b
020524d293e3dd2c4258bd56f055f4898ce6d922
/DM550 - Introduction to Programming/Python_examples/MandelbrötColour.py
b142c9e7c4d3b460035324f9f318f29a22be2989
[ "MIT" ]
permissive
andjo16/course-help
8c7fc0c35bed3dfe3396e60a0f3b26f0f96ed60d
440595ff1b0d8a6b3f7db78eb710ac7aacd51066
refs/heads/master
2020-08-27T10:34:28.429072
2019-10-31T12:17:08
2019-10-31T12:17:08
217,335,147
0
0
MIT
2019-10-24T15:43:09
2019-10-24T15:43:09
null
UTF-8
Python
false
false
3,786
py
"""Messy, but fairly optimized code for drawing the mandelbrot set using turtle graphics""" import turtle """These values can be modyfied to change the rendering""" width = 200 #Size in max distance from 0,0. Medium performance impact #width = 500 fits a maximized window on a 1080p screen height = width #Needs to be a square to render properly maxiterations = 255 #Precision or sharpness. Higher values needed when zooming.Low performance impact #A value of 255 gives good colours at 100% zoom spacing = 1 #Only check every x pixels. Use 1 for perfect image. High performance impact. #Use a higher value to test rendering. Usefull when zooming zoompercent = 100 / 100 #How zoomed in. Modyfies performance of maxiterations zoomx = 0 #Offset x and y to zoom in on. zoomy = 0 #These two are supposed to be coordinates on the mandelbrot set, but it changes with zoom. updatetime = 5 #number of lines to update at a time. Changeging performance impact """Global variables, not supposed to be changed""" updatecount = 0 xoffset = 0.75 * width #Approxymately centers the set on canavas tu = turtle.Turtle() #Prepares the turtle tu.speed(0) tu.hideturtle() tu.up() turtle.tracer(0, 0) turtle.Screen().colormode(255) escaped = prevesc = 0 """Methods""" def draw(x, y): """Draws a single pixel at x,y""" tu.up() tu.setpos(x,y) tu.down() tu.setpos(x + 1,y) def maprangex(val): """Maps a pixel x-coordinate to be rendered to be between -1 and 1""" tomax = 1 tomin = -1 valnorm = (val + width) / (width + width) return (tomin + valnorm * (tomax - tomin) + zoomx) / zoompercent def maprangey(val): """Maps a pixel y-coordinate to be rendered to be between -1 and 1""" tomax = 1 tomin = -1 valnorm = (val + height) / (height + height) return (tomin + valnorm * (tomax - tomin) + zoomy) / zoompercent def mandelbrot(x, y): """Returns true if pixel at x,y is in the (approxemated) mandelbrot set""" normx = maprangex(x) normy = maprangey(y) xcalc = 0.0 ycalc = 0.0 iteration = 0 expon = 2 while (xcalc**expon + ycalc**expon < 2**expon and iteration < maxiterations): temp = xcalc**expon - ycalc**expon + normx ycalc = 2*xcalc*ycalc + normy xcalc = temp iteration += 1 if (xcalc**expon + ycalc**expon < 2**expon): return iteration return iteration def mapcolor(val, maxval): """This sets the turtle pen colour based on how many iterations out of the maximum iterations have been reached""" norm = val / maxval #Red, green and blue components r = int(193.80370873*norm**2+61.19629127*norm) g = int(-1020*norm**2+1020*norm) b = int(193.80370873*norm**2-448.80370873*norm+255) #Forces colours to be withing 0-255 r = forcerange(r) g = forcerange(g) b = forcerange(b) tu.pencolor(r, g, b) def forcerange(colval): """Caps a value at 0 and 255""" if colval > 255: return 255 elif colval < 0: return 0 else: return colval """Main code""" for y in range(-height, height + 1, spacing): #For every line prevesc = escape = 0 #Reset variables for x in range(int(-width*2.5), width + 1, spacing): #For every pixel in line escape = mandelbrot(x, y) #Checks if pixel escaped if escape != prevesc: if tu.ycor() != y: tu.up() else: tu.down() tu.setpos(x + xoffset,y) if escape != maxiterations: mapcolor(escape, maxiterations) else: tu.pencolor(0,0,0) prevesc = escaped updatecount += 1 if updatecount > updatetime: #Updates the drawing every updatetime lines turtle.update() updatecount = 0 turtle.update() #Final update turtle.mainloop() #mainloop prevents the window from freezing
[ "bjoernak@gmail.com" ]
bjoernak@gmail.com
7464469387a198c2e33482e9162c0f5e81330d11
5ead79f9fd922fbd5c9ca43d5fb1230644deb477
/synthetic_data.py
aec5bd6e0ed304603cc32c0f81c6dab9afac0640
[]
no_license
yang0110/Graph-Learning
32791a33729946978b5338390d99b83eb9c0bf6e
a660c3ac9f5ad9a1828df49d8781c511be8371b3
refs/heads/master
2020-03-26T10:03:25.954895
2018-09-20T17:16:56
2018-09-20T17:16:56
144,778,779
0
0
null
null
null
null
UTF-8
Python
false
false
8,477
py
import numpy as np import random from random import choice import networkx as nx import os os.chdir('C:/Kaige_Research/Graph Learning/graph_learning_code/') import pandas as pd from sklearn.metrics.pairwise import cosine_similarity, rbf_kernel from sklearn.preprocessing import StandardScaler, Normalizer, MinMaxScaler from scipy.sparse import csgraph from sklearn.datasets import make_blobs from utils import * from knn_models import * from sklearn.preprocessing import normalize def RGG(node_num, dimension=2): RS=np.random.RandomState(seed=100) features=RS.uniform(low=0, high=1, size=(node_num, dimension)) adj_matrix=rbf_kernel(features, gamma=(1)/(2*(0.5)**2)) np.fill_diagonal(adj_matrix,0) laplacian=csgraph.laplacian(adj_matrix, normed=False) return adj_matrix, laplacian, features def generate_rbf_graph(node_num, pos, threshold=0.75): RS=np.random.RandomState(seed=100) adj_matrix=rbf_kernel(pos, gamma=(1)/(2*(0.5)**2)) adj_matrix[adj_matrix<threshold]=0.0 np.fill_diagonal(adj_matrix,0) laplacian=csgraph.laplacian(adj_matrix, normed=False) return adj_matrix, laplacian def knn_graph(node_num, dimension=2, k=5): RS=np.random.RandomState(seed=100) features=RS.uniform(low=0, high=1, size=(node_num, dimension)) adj_matrix=rbf_kernel(features, gamma=(1)/(2*(0.5)**2)) for i in range(node_num): rbf_row=adj_matrix[i,:] neighbors=np.argsort(rbf_row)[:node_num-k] adj_matrix[i, neighbors]=0 adj_matrix[neighbors,i]=0 np.fill_diagonal(adj_matrix,0) laplacian=csgraph.laplacian(adj_matrix, normed=False) return adj_matrix, laplacian, features def generate_er_graph(node_num, prob=0.2, seed=2018): graph=nx.erdos_renyi_graph(node_num, prob, seed=seed) adj_matrix=nx.to_numpy_array(graph) np.fill_diagonal(adj_matrix,0) laplacian=nx.laplacian_matrix(graph).toarray() return adj_matrix, laplacian def generate_ba_graph(node_num, seed=2018): graph=nx.barabasi_albert_graph(node_num, m=1, seed=seed) adj_matrix=nx.to_numpy_array(graph) np.fill_diagonal(adj_matrix,0) laplacian=nx.laplacian_matrix(graph).toarray() return adj_matrix, laplacian def generate_signal_gl_siprep(signal_num, node_num, laplacian, error_sigma): mean=np.zeros(node_num) normed_lap=normalized_trace(laplacian, node_num) pinv_lap=np.linalg.pinv(normed_lap) cov=pinv_lap signal=np.random.multivariate_normal(mean, cov, size=signal_num) noisy_cov=pinv_lap+error_sigma*np.identity(node_num) noisy_signal=np.random.multivariate_normal(mean, noisy_cov, size=signal_num) return noisy_signal, signal def generate_signal(signal_num, node_num, node_pos): # linear combination of item feature and node feature RS=np.random.RandomState(seed=100) item_f=RS.normal(size=(signal_num, node_pos.shape[1])) signals=np.dot(node_pos, item_f.T).T return signals def f1(x,y): return np.sin((2-x-y)**2) def f2(x,y): return np.cos((x+y)**2) def f3(x,y): return (x-0.5)**2+(y-0.5)**3+x-y def f4(x,y): return np.sin(3*(x-0.5)**2+(y-0.5)**2) def f5(x,y): return (x-0.5)+(y-0.5) def Tikhonov_filter(x, alpha=10): return 1/(1+alpha*x) def Heat_diffusion_filter(x, t=10): return np.exp(-t*x) def Generative_model_filter(x): if x>0: y=1/np.sqrt(x) else: y=0 return y def original_signal(signal_num, node_num): signal=np.random.normal(loc=1.0, size=(signal_num, node_num)) return signal def Tikhonov_signal(original_signal, adj_matrix): laplacian=csgraph.laplacian(adj_matrix, normed=False) laplacian=laplacian/np.linalg.norm(laplacian) eigenvalues, eigenvectors=np.linalg.eig(laplacian) filtered_signal=[] for j in range(len(original_signal)): a=0 for i in range(len(eigenvalues)): a+=eigenvectors[i]*Generative_model_filter(eigenvalues[i])*np.dot(eigenvectors[i], original_signal[j]) filtered_signal.append(a) return np.array(filtered_signal) def Heat_diffusion_signal(original_signal, adj_matrix): laplacian=csgraph.laplacian(adj_matrix, normed=False) laplacian=laplacian/np.linalg.norm(laplacian) eigenvalues, eigenvectors=np.linalg.eig(laplacian) resulted_signal=[] for j in range(len(original_signal)): a=0 for i in range(len(eigenvalues)): a+=eigenvectors[i]*Heat_diffusion_filter(eigenvalues[i])*np.dot(eigenvectors[i], original_signal[j]) resulted_signal.append(a) return np.array(resulted_signal) def Generative_model_signal(original_signal, adj_matrix): laplacian=csgraph.laplacian(adj_matrix, normed=False) laplacian=laplacian/np.linalg.norm(laplacian) eigenvalues, eigenvectors=np.linalg.eig(laplacian) filtered_signal=[] for j in range(len(original_signal)): a=0 for i in range(len(eigenvalues)): a+=eigenvectors[i]*Generative_model_filter(eigenvalues[i])*np.dot(eigenvectors[i], original_signal[j]) filtered_signal.append(a) return np.array(filtered_signal) def find_corrlation_matrix(signals): corr_matrix=np.corrcoef(signals.T) return corr_matrix def create_networkx_graph(node_num, adj_matrix): G=nx.Graph() G.add_nodes_from(list(range(node_num))) for i in range(node_num): for j in range(node_num): if adj_matrix[i,j]!=0: G.add_edge(i,j, weight=adj_matrix[i,j]) else: pass return G def find_eigenvalues_matrix(eigen_values): eigenvalues_matrix=np.diag(np.sort(eigen_values)) return eigenvalues_matrix def normalized_trace(matrix, target_trace): normed_matrix=target_trace*matrix/np.trace(matrix) return normed_matrix def learn_knn_graph_from_node_features(node_features, node_num, k=5): adj=rbf_kernel(node_features) np.fill_diagonal(adj,0) knn_adj=filter_graph_to_knn(adj, node_num, k=k) knn_lap=csgraph.laplacian(knn_adj, normed=False) return knn_adj, knn_lap def learn_knn_graph(signals, node_num, k=5, gamma=0.2): #print('Learning KNN Graph') adj=rbf_kernel(signals.T, gamma=gamma) np.fill_diagonal(adj,0) knn_adj=filter_graph_to_knn(adj, node_num, k=k) knn_lap=csgraph.laplacian(knn_adj, normed=False) return knn_adj, knn_lap def learn_knn_signal(adj, signals, signal_num, node_num): #print('Learning KNN Signals') new_signals=np.zeros((signal_num, node_num)) for i in range(signal_num): for j in range(node_num): rbf_row=adj[j,:] neighbors=rbf_row>0 weights=rbf_row[rbf_row>0] if len(weights)==0: new_signals[i,j]=signals[i,j] else: new_signals[i,j]=np.average(signals[i][neighbors], weights=weights) return new_signals def signal_noise(signal_num, node_num, scale): RS=np.random.RandomState(seed=100) noise=RS.normal(scale=scale, size=(signal_num, node_num)) return noise def blob_data(node_num, signal_num, dimension, cluster_num, cluster_std, noise_scale): x, y=make_blobs(n_samples=node_num, n_features=dimension, centers=cluster_num, cluster_std=cluster_std, center_box=(0,1.0), shuffle=False) x=MinMaxScaler().fit_transform(x) #item_f, item_y=make_blobs(n_samples=signal_num, n_features=dimension, centers=cluster_num, cluster_std=cluster_std, center_box=(0, 1.0), shuffle=False) item_f=np.random.uniform(size=(signal_num, dimension)) #item_f=MinMaxScaler().fit_transform(item_f) #item_f=generate_item_features(signal_num, dimension) signal=np.dot(item_f, x.T) noise=np.random.normal(size=(signal_num, node_num), scale=noise_scale) noisy_signal=signal+noise return noisy_signal, signal, item_f, x, y def generate_item_features(item_num, dimension): item_features=np.empty([item_num, dimension]) for i in range(dimension): item_features[:,i]=np.random.normal(0, np.sqrt(1.0*(dimension-1)/dimension), item_num) item_features=MinMaxScaler().fit_transform(item_features) return item_features def generate_all_random_users(iterations, user_num): random_users=np.random.choice(np.arange(user_num), size=iterations, replace=True) return random_users def generate_all_article_pool(iterations, pool_size, article_num): all_article_pool=[] for i in range(iterations): pool=np.random.choice(np.arange(article_num), size=pool_size, replace=True) all_article_pool.append(pool) all_article_pool=np.array(all_article_pool) return all_article_pool # adj, f=RGG(10) # laplacian=csgraph.laplacian(adj, normed=False) # laplacian=laplacian/np.linalg.norm(laplacian) # eigenvalues, eigenvectors=np.linalg.eig(laplacian) # y=Tikhonov_signal(x, adj) # y=Generative_model_signal(x, adj) # y=Heat_diffusion_signal(x, adj)
[ "noreply@github.com" ]
noreply@github.com
353064e8a7d7337af50b295e09ea72a8b875c2ad
d1055160c237c54e9d8988ab3f7950a8b6d4446f
/routes/routesApi.py
d036c0f21d0f64c4cec59894f2ad20bcb136e82c
[]
no_license
dclavijo45/api-cars
e31efc7c2c47138745890bd8aaa9d54ac4b4be68
42c95232c1cb64ef01d3a637129440aa1645e167
refs/heads/main
2023-05-09T09:56:40.413574
2021-06-08T06:00:20
2021-06-08T06:00:20
null
0
0
null
null
null
null
UTF-8
Python
false
false
412
py
from controllers.apiCarsController import ApiCars from controllers.apiCarsGetByIdController import ApiCarsById api_v1 = { "api_GPPD": "/api/v1/cars/", "api_cars_controller": ApiCars.as_view("api_cars_api"), # ---------------------------------------------------------------- "api_GPPD_byId": "/api/v1/cars/<string:id>/", "api_cars_byId_controller": ApiCarsById.as_view("api_cars_byId_api"), }
[ "danielclavijo19380@gmail.com" ]
danielclavijo19380@gmail.com
ba238c5a584e1bd752ac009997ffc5b7b851ed43
5e20392dc4487c75e1e3061c1416a895317ca7c2
/examples/simple_menu.py
37b7bd17c1ffc5b613306c1301a0a27d22a2540e
[ "MIT" ]
permissive
rashidsh/navmenu
7072f3cee55469ccbe7f79eb5ce81c86a3aab4bb
ec67b820462cc102417e214cd74eb7b1b97ad1f1
refs/heads/master
2023-08-18T02:20:26.021801
2021-10-03T16:56:54
2021-10-03T16:56:54
366,816,317
0
0
null
null
null
null
UTF-8
Python
false
false
1,477
py
from navmenu import MenuManager from navmenu.actions import MessageAction, SubmenuAction, GoBackAction, ExecuteAction, FunctionAction from navmenu.contents import Content from navmenu.io import ConsoleIO from navmenu.item_contents import TextItemContent from navmenu.items import Item, LineBreakItem from navmenu.menus import Menu from navmenu.state import MemoryStateHandler from navmenu.responses import Message, Response def go_back_func(msg): return Response(Message(Content('Going back...')), go_back_count=1) main_menu = Menu(Content('Main menu'), ( Item('print', TextItemContent('print text'), MessageAction('Text message')), LineBreakItem(), Item('open', TextItemContent('open submenu'), SubmenuAction('submenu')), LineBreakItem(), Item('quit', TextItemContent('quit the program'), ExecuteAction('import sys; sys.exit()')), ), default_action=MessageAction('Please type "print" or "open" to navigate')) submenu = Menu(Content('Submenu'), ( Item('calc', TextItemContent('calculate 2 + 2'), ExecuteAction('f"2 + 2 = {2 + 2}"', return_text=True)), Item('func', TextItemContent('run function'), FunctionAction(go_back_func)), LineBreakItem(), Item('back', TextItemContent('go back'), GoBackAction()), )) menu_manager = MenuManager({ 'main_menu': main_menu, 'submenu': submenu, }, MemoryStateHandler('main_menu')) def main(): io = ConsoleIO(menu_manager) io.start_loop() if __name__ == '__main__': main()
[ "42511322+rashidsh@users.noreply.github.com" ]
42511322+rashidsh@users.noreply.github.com
9ea6dc86463d7d983d2fae71124122e1543afcf9
9124cb80e0a9b84443e03d762542e046027fddc9
/fiano/apps/project/migrations/0009_auto_20210216_0444.py
ca0ee82108184ba450aa2821339f1268a32355a4
[]
no_license
adylanrff/fiano-monitoring-v2
5c4a3c74922087ad18535658257783c0ddfde82d
0a0911b3f6446296c5a7f81713b2353ba126c7be
refs/heads/main
2023-03-04T20:37:55.773536
2021-02-16T16:46:50
2021-02-16T16:46:50
339,174,392
0
0
null
null
null
null
UTF-8
Python
false
false
887
py
# Generated by Django 3.1.6 on 2021-02-16 04:44 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('project', '0008_auto_20210216_0415'), ] operations = [ migrations.AddIndex( model_name='project', index=models.Index(fields=['id'], name='project_pro_id_b481b4_idx'), ), migrations.AddIndex( model_name='projectdeliverable', index=models.Index(fields=['project_id'], name='project_pro_project_ab4f38_idx'), ), migrations.AddIndex( model_name='projectdeliverable', index=models.Index(fields=['id'], name='project_pro_id_6a7333_idx'), ), migrations.AddIndex( model_name='worker', index=models.Index(fields=['id'], name='project_wor_id_6adab3_idx'), ), ]
[ "adylan.dev@gmail.com" ]
adylan.dev@gmail.com
d28793a13d94e66adb0a928107c6cc62c918c359
f21d3ef9eedaeaa4c3b84a288ef799b19df6f669
/FilmAudioProgram/images/plot.py
d98d3aa01a5e63d05b0e2da1b5f5b84da655f555
[]
no_license
mitali/fmp
84f57344def0787e32cd26806500b0bd4960e7a9
0c1c678da5609a9091c263eb9074a53e216d386f
refs/heads/master
2020-04-14T14:20:19.749836
2015-06-22T02:04:38
2015-06-22T02:04:38
null
0
0
null
null
null
null
UTF-8
Python
false
false
320
py
''' Created on May 5, 2015 @author: Mitali ''' import cv2 from matplotlib import pyplot as plt img = cv2.imread('/Users/Mitali/Desktop/IndividualProject/InterimReport/img1.jpg', 0) plt.imshow(img, cmap = 'gray', interpolation = 'bicubic') plt.xticks([]), plt.yticks([]) # hide tick values on X and Y axis plt.show()
[ "mitalidargani@gmail.com" ]
mitalidargani@gmail.com
546d5f3d75b16204af7150c593a018202f289b72
dc9b0ea6714c29651cfd8b494862f31f07d85f28
/project13_Poem_application_v_1_1/venv/Scripts/easy_install-3.7-script.py
3ffe0822b1c606782a31dc123f99a0e6002cc984
[]
no_license
Papashanskiy/PythonProjects
c228269f0aef1677758cb6e2f1acdfa522da0a02
cf999867befa7d8213b2b6675b723f2b9f392fd7
refs/heads/master
2022-12-12T15:23:56.234339
2019-02-10T09:14:56
2019-02-10T09:14:56
148,336,536
0
0
null
2022-12-08T03:01:04
2018-09-11T15:10:44
Python
WINDOWS-1251
Python
false
false
505
py
#!C:\Users\Игорь\Desktop\Python\PythonProjects\project13_Poem_application_v_1_1\venv\Scripts\python.exe -x # EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==39.1.0','console_scripts','easy_install-3.7' __requires__ = 'setuptools==39.1.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==39.1.0', 'console_scripts', 'easy_install-3.7')() )
[ "apashanskiy@gmail.com" ]
apashanskiy@gmail.com
ab9df98e59d1a7e7d0481a0ede26e8090d4cd311
e3d6f803beece2ecc2cde8de795fdd20291213ff
/nova/api/openstack/compute/views/flavors.py
fcdd6fcf4ca4d94a039a3ee90651b0c5c0ac1266
[ "Apache-2.0" ]
permissive
panguan737/nova
437c1adb81f3e9ef82c28ad957144623db13ba52
0d177185a439baa228b42c948cab4e934d6ac7b8
refs/heads/main
2023-01-07T00:08:44.069599
2020-11-01T14:00:42
2020-11-01T14:00:42
309,332,719
0
0
Apache-2.0
2020-11-02T10:17:13
2020-11-02T10:17:13
null
UTF-8
Python
false
false
6,492
py
# Copyright 2010-2011 OpenStack Foundation # 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. from nova.api.openstack import api_version_request from nova.api.openstack import common from nova.policies import flavor_access as fa_policies from nova.policies import flavor_rxtx as fr_policies FLAVOR_DESCRIPTION_MICROVERSION = '2.55' class ViewBuilder(common.ViewBuilder): _collection_name = "flavors" def basic(self, request, flavor, include_description=False, update_is_public=None, update_rxtx_factor=None): # update_is_public & update_rxtx_factor are placeholder param # which are not used in this method as basic() method is used by # index() (GET /flavors) which does not return those keys in response. flavor_dict = { "flavor": { "id": flavor["flavorid"], "name": flavor["name"], "links": self._get_links(request, flavor["flavorid"], self._collection_name), }, } if include_description: flavor_dict['flavor']['description'] = flavor.description return flavor_dict def show(self, request, flavor, include_description=False, update_is_public=None, update_rxtx_factor=None): flavor_dict = { "flavor": { "id": flavor["flavorid"], "name": flavor["name"], "ram": flavor["memory_mb"], "disk": flavor["root_gb"], "swap": flavor["swap"] or "", "OS-FLV-EXT-DATA:ephemeral": flavor["ephemeral_gb"], "OS-FLV-DISABLED:disabled": flavor["disabled"], "vcpus": flavor["vcpus"], "links": self._get_links(request, flavor["flavorid"], self._collection_name), }, } if include_description: flavor_dict['flavor']['description'] = flavor.description # TODO(gmann): 'update_is_public' & 'update_rxtx_factor' are policies # checks. Once os-flavor-access & os-flavor-rxtx policies are # removed, 'os-flavor-access:is_public' and 'rxtx_factor' need to be # added in response without any check. # Evaluate the policies when using show method directly. context = request.environ['nova.context'] if update_is_public is None: update_is_public = context.can(fa_policies.BASE_POLICY_NAME, fatal=False) if update_rxtx_factor is None: update_rxtx_factor = context.can(fr_policies.BASE_POLICY_NAME, fatal=False) if update_is_public: flavor_dict['flavor'].update({ "os-flavor-access:is_public": flavor['is_public']}) if update_rxtx_factor: flavor_dict['flavor'].update( {"rxtx_factor": flavor['rxtx_factor'] or ""}) return flavor_dict def index(self, request, flavors): """Return the 'index' view of flavors.""" coll_name = self._collection_name include_description = api_version_request.is_supported( request, FLAVOR_DESCRIPTION_MICROVERSION) return self._list_view(self.basic, request, flavors, coll_name, include_description=include_description) def detail(self, request, flavors): """Return the 'detail' view of flavors.""" coll_name = self._collection_name + '/detail' include_description = api_version_request.is_supported( request, FLAVOR_DESCRIPTION_MICROVERSION) context = request.environ['nova.context'] update_is_public = context.can(fa_policies.BASE_POLICY_NAME, fatal=False) update_rxtx_factor = context.can(fr_policies.BASE_POLICY_NAME, fatal=False) return self._list_view(self.show, request, flavors, coll_name, include_description=include_description, update_is_public=update_is_public, update_rxtx_factor=update_rxtx_factor) def _list_view(self, func, request, flavors, coll_name, include_description=False, update_is_public=None, update_rxtx_factor=None): """Provide a view for a list of flavors. :param func: Function used to format the flavor data :param request: API request :param flavors: List of flavors in dictionary format :param coll_name: Name of collection, used to generate the next link for a pagination query :param include_description: If the flavor.description should be included in the response dict. :param update_is_public: If the flavor.is_public field should be included in the response dict. :param update_rxtx_factor: If the flavor.rxtx_factor field should be included in the response dict. :returns: Flavor reply data in dictionary format """ flavor_list = [func(request, flavor, include_description, update_is_public, update_rxtx_factor)["flavor"] for flavor in flavors] flavors_links = self._get_collection_links(request, flavors, coll_name, "flavorid") flavors_dict = dict(flavors=flavor_list) if flavors_links: flavors_dict["flavors_links"] = flavors_links return flavors_dict
[ "147360410@qq.com" ]
147360410@qq.com
ec2cadeb66e67d4e79bc5fd3c5442916d74ec88b
fa0eac5b96fc46ebf8e31a7ccd7fa39f2e200bfc
/backend/home/migrations/0002_load_initial_data.py
95b530a428d8a00e98272abc6771579b60ad009f
[]
no_license
crowdbotics-apps/mobile-7-dec-dev-16399
be33b8eb17957c9b8a75b3d089114631f27b9109
ab2cbc3e11dfbf709883b3cf49f4be109d779028
refs/heads/master
2023-06-27T20:39:09.405282
2020-12-07T11:38:48
2020-12-07T11:38:48
319,207,493
0
0
null
2021-08-03T20:05:57
2020-12-07T04:51:46
JavaScript
UTF-8
Python
false
false
1,306
py
from django.db import migrations def create_customtext(apps, schema_editor): CustomText = apps.get_model("home", "CustomText") customtext_title = "mobile 7 dec" CustomText.objects.create(title=customtext_title) def create_homepage(apps, schema_editor): HomePage = apps.get_model("home", "HomePage") homepage_body = """ <h1 class="display-4 text-center">mobile 7 dec</h1> <p class="lead"> This is the sample application created and deployed from the Crowdbotics app. You can view list of packages selected for this application below. </p>""" HomePage.objects.create(body=homepage_body) def create_site(apps, schema_editor): Site = apps.get_model("sites", "Site") custom_domain = "mobile-7-dec-dev-16399.botics.co" site_params = { "name": "mobile 7 dec", } if custom_domain: site_params["domain"] = custom_domain Site.objects.update_or_create(defaults=site_params, id=1) class Migration(migrations.Migration): dependencies = [ ("home", "0001_initial"), ("sites", "0002_alter_domain_unique"), ] operations = [ migrations.RunPython(create_customtext), migrations.RunPython(create_homepage), migrations.RunPython(create_site), ]
[ "team@crowdbotics.com" ]
team@crowdbotics.com
816b2e7d8f4f5f355216f735e9bac2bb4a2ffb46
6105907134507a8b93613ba632f81d157722de1a
/trident/napps/snlab/trident_server/trident/convertformat.py
c8e8006c4229873178eafc10bf00974a59e1bbf6
[]
no_license
snlab/afm2018-demo-unified-control
71ce6200debfa73d7e29e07f12dcc045a9acc641
8ec3e12265f53afb97dd76df9c4daa432018cf21
refs/heads/master
2020-03-28T07:27:54.912895
2018-09-11T14:44:17
2018-09-11T14:44:17
147,903,005
0
0
null
null
null
null
UTF-8
Python
false
false
871
py
#[(2, {'sip': '10.0.0.2', 'dip': '10.0.0.1', 'sport': 4, 'dport': 80, 'proto': 22}, [('00:00:00:00:00:00:00:01', 1), ('00:00:00:00:00:00:00:02', 4)]), (2, {'sip': '10.0.0.1', 'dip': '10.0.0.2', 'sport': 80, 'dport': 4, 'proto': 22}, [('00:00:00:00:00:00:00:02', 1), ('00:00:00:00:00:00:00:01', 4)])] def convert_format(table): rules = table.rules # print(table) field = ['sip','dip','sport','dport','proto'] ret = [] for item in rules: priority = int(item[0]) match = {} for i in range(5): if item[i+1]!='*': match[field[i]] = item[i+1] path = [] for ff in item[6]: if len(ff[0])==23: outputs = ff[2] for output in outputs: path.append((ff[0],int(output))) ret.append((priority, match, path)) return ret
[ "yuta_o@outlook.com" ]
yuta_o@outlook.com
7641f3fd1a8545b6084529b6cf40803dd3d1f69f
c35ea5ba5796c5792f05ee3809f7f6f7cb1dedea
/src/convert_to_chart.py
dc47a105885f4f946e3bac6f0f1ec07037a0cfed
[]
no_license
ermasavior/Seleksi-2018-Tugas-2
805838d3bf8bab72c937af9ff386ee852d083c6a
6278c895d47a7bd552f4a4a44ac9f642164b7c10
refs/heads/master
2021-09-21T02:12:25.227982
2018-08-19T13:55:54
2018-08-19T13:55:54
null
0
0
null
null
null
null
UTF-8
Python
false
false
8,377
py
import main import random import json def getCategories(): path = main.baseFilePath + 'categories.json' with open(path, 'r') as f: categories = json.load(f) return categories def toChart1(summary): categories = getCategories() series = [{}] drilldownseries = [] series[0]['name'] = summary['title'] series[0]['colorByPoint'] = True series[0]['data'] = [] foodgroups = summary['food_groups'] for cat in categories: data = {} drilldown = {} drilldowndatalist = [] data['name'] = cat['category'] drilldown['name'] = data['name'] drilldown['id'] = data['name'] sum = 0 subcategories = cat['subcategories'] for group in foodgroups: if group['name'] in subcategories: sum += group['count'] data['y'] = sum/summary['count_data']*100 data['drilldown'] = data['name'] series[0]['data'].append(data) for group in foodgroups: if group['name'] in subcategories: presentage = group['count']/sum*100 drilldowndata = [group['name'], presentage] drilldowndatalist.append(drilldowndata) drilldown['data'] = drilldowndatalist drilldownseries.append(drilldown) main.saveJSONObject("chartdata/chart1.json", [series, drilldownseries]) def toChart2(summary, dataset): series = [] food_groups = ['Fruits and Fruit Juices', 'Vegetables and Vegetable Products', 'Beef Products'] for group in summary['food_groups']: if group['name'] in food_groups: category = {} category['name'] = group['name'] indices = group['food_indices'] r = random.randint(0,255) g = random.randint(0,255) b = random.randint(0,255) category['color'] = 'rgba(' + str(r) + ', '+ str(g) +', '+ str(b) +', .5)' category['data'] = [] for i in indices: nutrientlist = dataset[i]['nutrients'] x = -1 y = -1 for nutrient in nutrientlist: if nutrient['nutrient_name'] == 'Energy': y = nutrient['value'] elif nutrient['nutrient_name'] == 'Protein': x = nutrient['value'] if x != -1 and y != -1: coor = [x, y] category['data'].append(coor) series.append(category) return series def toChart3(summary, dataset): categories = getCategories() categdata = [] subcategdata = [] nutrientdata = ['Carbohydrate, by difference', 'Protein', 'Total lipid ', 'Sugars, total'] categnutrientdata = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] for cat in categories: categdata.append(cat['category']) subcategdata.append(cat['subcategories']) numdata = [0, 0, 0, 0, 0, 0] for group in summary['food_groups']: for i in range(0, len(categdata)): if group['name'] in subcategdata[i]: numdata[i] += group['count'] print(numdata) for food in dataset: for i in range(0, len(categdata)): if food['food_group'] in subcategdata[i]: for nutrient in food['nutrients']: if nutrient['nutrient_name'] in nutrientdata: j = nutrientdata.index(nutrient['nutrient_name']) categnutrientdata[i][j] += nutrient['value'] print(categnutrientdata) for i in range(0, len(categnutrientdata)): for j in range(0, len(nutrientdata)): categnutrientdata[i][j] = round(categnutrientdata[i][j]/numdata[i], 2) series = [] for i in range(0, len(nutrientdata)): seri = {} seri['name'] = nutrientdata[i] seri['data'] = [] for j in range(0, len(categnutrientdata)): seri['data'].append(categnutrientdata[j][i]) series.append(seri) return [categdata, series] def getFoodGroupCount(summary, groupname): for group in summary['food_groups']: if group['name'] == groupname: return group['count'] def toChart4(dataset, summary): categories = getCategories() foodwaterlist = main.getWaterStats(dataset, 2395, summary) print(foodwaterlist) series = [{}] drilldownseries = [] series[0]['name'] = summary['title'] series[0]['colorByPoint'] = True series[0]['data'] = [] for cat in categories: data = {} drilldown = {} drilldowndatalist = [] data['name'] = cat['category'] drilldown['name'] = data['name'] drilldown['id'] = data['name'] sum = 0 count = 0 subcategories = cat['subcategories'] for food in foodwaterlist: if food['name'] in subcategories: sum += food['Water'] count += getFoodGroupCount(summary, food['name']) meanvalue = food['Water']/getFoodGroupCount(summary, food['name']) drilldowndata = [food['name'], meanvalue] drilldowndatalist.append(drilldowndata) data['y'] = sum/count data['drilldown'] = data['name'] series[0]['data'].append(data) drilldown['data'] = drilldowndatalist drilldownseries.append(drilldown) def chartPerGroup(dataset, summary, idx): # half chart categories = getCategories() subcategories = [] categories = [] proximates = ['Carbohydrate, by difference', 'Protein', 'Total lipid ', 'Sugars, total'] for cat in categories: categories.append(cat['category']) subcategories.append(cat['subcategories']) indices = summary['food_groups'][idx]['food_indices'] #for i in indices: def toChart5(dataset, summary): #count cholesterol, fat rate, per category categlist = ['Fast Foods', 'Beef Products', 'Dairy and Egg Products', 'Vegetables and Vegetable Products', 'Restaurant Foods', 'Cereal Grains and Pasta','Finfish and Shellfish Products'] nutrientlist = ['Fatty acids, total saturated', 'Cholesterol', 'Fiber, total dietary'] nutrientrate = [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] numdata = [0, 0, 0, 0, 0, 0, 0] for group in summary['food_groups']: if group['name'] in categlist: idx = categlist.index(group['name']) numdata[idx] = group['count'] print(numdata) for group in summary['food_groups']: if group['name'] in categlist: i = categlist.index(group['name']) indices = group['food_indices'] for k in indices: food = dataset[k] for nutrient in nutrientlist: sum, j = getNutrientValue(food, nutrient, nutrientlist) if (j != -1): nutrientrate[i][j] += sum print(nutrientrate) for i in range(0, len(nutrientrate)): for j in range(0, len(nutrientlist)): nutrientrate[i][j] = round(nutrientrate[i][j]/numdata[i], 2) series = [] for i in range(0, len(nutrientlist)): seri = {} seri['name'] = nutrientlist[i] seri['data'] = [] for j in range(0, len(nutrientrate)): seri['data'].append(nutrientrate[j][i]) series.append(seri) return [categlist, series] def getNutrientValue(food, nutrientdata, nutrientlist): for nutrient in food['nutrients']: l = len(nutrientdata) if nutrient['nutrient_name'][:l] == nutrientdata: return nutrient['value'], nutrientlist.index(nutrient['nutrient_name']) return 0, -1 if __name__ == '__main__': # Read Dataset dataset = main.readJSONDataSet() # Overall Summary (DONE) summary = main.overallSummary(dataset) # toChart1(summary) #series = toChart2(summary, dataset) #main.saveJSONObject("chartdata/chart2.json", series) #obj = toChart3(summary, dataset) obj = toChart5(dataset, summary) main.saveJSONObject("chartdata/chart5.json", obj)
[ "erma.safira@gmail.com" ]
erma.safira@gmail.com
e115f8c58f3ff28e31c03e8612eb5e185f42c21d
e71ef27385b364f5465717271dc6bc1baf6fd8ac
/Merge.py
47bcdf770248a1b12362689d40472a43a4e0506c
[]
no_license
EspressoCake/Etc
1e8d7955af5ae5a6b227d7ca02295df0a202f3ed
6cfb8ad2ee76b868736a5601e615d098dfb8b06f
refs/heads/master
2020-06-11T06:50:34.464719
2016-12-19T17:24:15
2016-12-19T17:24:15
75,742,653
0
0
null
null
null
null
UTF-8
Python
false
false
1,894
py
import os import ctypes import webbrowser from PyPDF2 import PdfFileReader, PdfFileMerger, PdfFileWriter ctypes.windll.kernel32.SetConsoleTitleA(b"PDF Merger") def PdfMerger(): files_Directory = input('\n' + 'What directory are the files in?:' + '\n').replace('\\', '/') upside_User = str(input('\n' + 'Did your dumbass import the files upside down? (Yes or No)' + '\n').lower()) pdf_Files = [f for f in os.listdir(files_Directory) if f.endswith("pdf")] merger = PdfFileMerger() initialization = '\n The following items will be merged:' print(initialization) print('=' * len(initialization)) for filename in pdf_Files: print(filename) proceed = str(input('\nWould you like to continue?: (Yes or No): \n').lower()) if proceed == "yes": for filename in pdf_Files: merger.append(PdfFileReader(os.path.join(files_Directory, filename), 'rb')) merger.write(os.path.join(files_Directory, "merged_full.pdf")) if upside_User == 'no': print('\n' + 'Files have been merged, and stored within', os.path.join(files_Directory)) elif upside_User == 'yes': pdf_In = open(os.path.join(files_Directory, "merged_full.pdf"), 'rb') pdf_Reader = PdfFileReader(pdf_In) pdf_Writer = PdfFileWriter() for pagenum in range(pdf_Reader.numPages): page = pdf_Reader.getPage(pagenum) page.rotateClockwise(180) pdf_Writer.addPage(page) pdf_Output = open(os.path.join(files_Directory, "rotated.pdf"), 'wb') pdf_Writer.write(pdf_Output) pdf_Output.close() pdf_In.close() print('\n' + 'Files have been rotated, and stored within', os.path.join(files_Directory)) navigate_to_Directory = str(input('\nWould you like to navigate to the directory? (Yes or No)\n')).lower() if navigate_to_Directory == 'yes': webbrowser.open(files_Directory) else: print("\nAll done!\n") else: print("\nLet's try this again...\n") PdfMerger() PdfMerger()
[ "lucas.justin.k@gmail.com" ]
lucas.justin.k@gmail.com
9e43aee2e811d9932c1cd2b48861db79f76806dc
fc32b3538bcb29b1ba4dcdfac2d453fd341117a2
/5.文件和IO/2.dict2xml.py
28e166aa132a97d6ef80bdbe989fe1171f2e5c57
[ "Apache-2.0" ]
permissive
weicunheng/gulu
17cfac759ae0a97cee699cf73f1e844ccd8b4d50
c37bbe489a00fd2a6bddd8e662e350baf580aed9
refs/heads/master
2020-07-22T13:22:48.759870
2019-10-22T07:46:19
2019-10-22T07:46:19
207,215,836
0
0
null
null
null
null
UTF-8
Python
false
false
666
py
# -*- coding:utf-8 _*- def dict2xml(data): xml_data = [] for key, value in data.items(): if isinstance(value, dict): xml_str = dict2xml(value) s = "<{key}>{value}</{key}>".format(key=key, value=xml_str) elif isinstance(value, list): s = "" for dic in value: xml_str = dict2xml(dic) s += "<{key}>{value}</{key}>".format(key=key, value=xml_str) elif value is None: s = "<{key}></{key}>".format(key=key) else: s = "<{key}>{value}</{key}>".format(key=key, value=value) xml_data.append(s) return ''.join(xml_data)
[ "weicunheng@gmail.com" ]
weicunheng@gmail.com
1e383611800f2515fcceda57e892b933499034c2
36d980710f95506b71df4be76c6589ad094a1926
/Package_example2/images.py
952ca9047a9a53c02ea300b584e020c3f79938a5
[]
no_license
GabrielBlancoM/Tarea3V2.0
cf46449825945a3d7076bbe4bf1f63c24012c0c3
074ee4fb7849eb787c5925838c9d37fdf51bddc8
refs/heads/master
2022-12-28T01:17:36.947758
2020-10-16T03:44:35
2020-10-16T03:44:35
304,466,826
0
0
null
null
null
null
UTF-8
Python
false
false
2,723
py
# Se deben instalar las librería, ya que estas no la traen # se pueden instalr con los comandos: "pip install opencv-python" en phyton 2 # o "pip3 install opencv-python" Phyton 3 # y "pip install matplotlib" import cv2 import matplotlib.pyplot as plt import argparse import time # digite 1 si quiere ver la imagen a escala 1:1 # digite 2 si quiere ver la imagen a escala 1:2 # digite 3 si quiere ver la imagen a escala 2:1 # Presentador_de_imagenes def Presentador_de_imágenes(archivo, escala): # se carga la imagen: im = cv2.imread(archivo+".jpg") # A continuacion se pondran los posibles errores de este metodo # Si los números ingresados al método no son entero if isinstance(escala, int) is False: # revisa que escala sea entero return "Error no es un entero" if ((escala > 3) | (escala < 1)): # revisa que el primer dato este entre 3 y 1 return "Error dato fuera de rango" # en el caso de no existir un error if escala == 1: # acontinuación se define el tamaño de la imagen im_resized = cv2.resize(im, (224, 224), interpolation=cv2.INTER_LINEAR) # acontinuación se muestra la imagen con la escala seleccionada plt.imshow(cv2.cvtColor(im_resized, cv2.COLOR_BGR2RGB)) plt.show() if escala == 2: # acontinuación se define el tamaño de la imagen im_resized = cv2.resize(im, (224, 448), interpolation=cv2.INTER_LINEAR) # acontinuación se muestra la imagen con la escala seleccionada plt.imshow(cv2.cvtColor(im_resized, cv2.COLOR_BGR2RGB)) plt.show() if escala == 3: # acontinuación se define el tamaño de la imagen im_resized = cv2.resize(im, (448, 224), interpolation=cv2.INTER_LINEAR) # acontinuación se muestra la imagen con la escala seleccionada plt.imshow(cv2.cvtColor(im_resized, cv2.COLOR_BGR2RGB)) plt.show() ### Para probar con argparser poner esto como comentario #Presentador_de_imágenes(r"C:\Users\edghb\Pictures\Saved Pictures\space-walk-nasa-796x457",2) parser = argparse.ArgumentParser(description = 'Presenta una imagen') parser.add_argument('escala' , type = int, help = 'Ingrese un entero para la Escala 1: para escala 1:1, 2: para escala 1:2 , 3: para escala 2:1') parser.add_argument('archivo', type = str, help = 'Ingrese el Nombre de la imagen') group = parser.add_mutually_exclusive_group() group.add_argument('-t', '--time', action= 'store_true', help= 'Muestra tiempo de ejecución') args = parser.parse_args() t0= time.time() Presentador_de_imágenes(args.archivo,args.escala) t1= time.time() - t0 if args.time: print ('Tiempo de ejecución: ', round(t1, 6), 'segundos.')
[ "gaboblanco25@icloud.com" ]
gaboblanco25@icloud.com
7ef8f4ec72f930eb88693061e793ec74b5cc19a3
19666396c4d56f4dcd2790b6c8a6b18745767f90
/task.py
cb5e139ed740c0339e517e50b0c4cff7b318fb27
[]
no_license
himdhiman/taskpy
5504b461f4ae161cfabc3f552752dd2641eabf6f
2d343da545bb20b8c30c8d7d6bde83e241ca5493
refs/heads/master
2023-03-29T09:07:35.797755
2021-04-08T07:05:15
2021-04-08T07:05:15
355,798,080
0
0
null
null
null
null
UTF-8
Python
false
false
5,680
py
from celery import shared_task from api import models, serializers from rest_framework.response import Response import os from pathlib import Path from api.models import Problem, Submission from asgiref.sync import async_to_sync from channels.layers import get_channel_layer import json from django.core import serializers as djSerializer BASE_DIR = Path(__file__).resolve().parent.parent channel_layer = get_channel_layer() @shared_task def runCode(body, uid): response = serializers.SubmissionSerializer(data = body) if(response.is_valid()): inst = response.save() if(inst.inputGiven != ""): data = {'id' : inst.id, 'code' : inst.code, 'lang' : inst.language, 'inp' : inst.inputGiven, 'problemId' : inst.problemId} else: data = {'id' : inst.id, 'code' : inst.code, 'lang' : inst.language, 'problemId' : inst.problemId} probId = data['problemId'] totaltc = Problem.objects.get(id = probId).totalTC tempPath = os.path.join(BASE_DIR, "Codes", str(uid)) os.system(f"mkdir {tempPath}") inpPath = tempPath+"/"+"input.txt" os.system(f"touch {inpPath}") outPath = tempPath+"/"+"output.txt" os.system(f"touch {outPath}") logPath = tempPath+"/"+"output.log" os.system(f"touch {logPath}") progPath = None bashPath = tempPath+"/"+"a.out" if data['lang'] == "CP": progPath = tempPath+"/"+"main.cpp" os.system(f"touch {progPath}") f = open(os.path.join(tempPath, 'main.cpp'), "w") f.write(data['code']) f.close() if data['lang'] == "P3": progPath = tempPath+"/"+"main.py" os.system(f"touch {progPath}") f = open(os.path.join(tempPath, 'main.py'), "w") f.write(data['code']) f.close() isInputGiven = False if('inp' in data.keys() and data['inp'] != None): isInputGiven = True f = open(inpPath, "w") f.write(data['inp']) f.close() os.chdir(tempPath) if data['lang'] == "CP": os.system(f'g++ {progPath}') cnt = 0 if(isInputGiven == False): for i in range(1, totaltc+1): isSame = True inpPath = os.path.join(BASE_DIR, "media", 'TestCases', str(probId), 'input'+str(i)+'.txt') os.system(f'{bashPath} < {inpPath} > {outPath}') with open(os.path.join(BASE_DIR, "media", 'TestCases', str(probId), 'output'+str(i)+'.txt')) as f1, open(outPath) as f2: for line1, line2 in zip(f1, f2): if line1 != line2: isSame = False break if(isSame): cnt += 1 async_to_sync(channel_layer.group_send)("user_"+str(uid), {'type': 'sendStatus', 'text' : f"1/{i}/{totaltc}"}) else: async_to_sync(channel_layer.group_send)("user_"+str(uid), {'type': 'sendStatus', 'text' : f"0/{i}/{totaltc}"}) os.system(f"rm -rf {outPath}") os.system(f"touch {outPath}") else: os.system(f'{bashPath} < {inpPath} > {outPath}') os.system(f'g++ {progPath} 2> {logPath}') if data['lang'] == "P3": if(isInputGiven == False): for i in range(1, totaltc+1): isSame = True inpPath = os.path.join(BASE_DIR, "media", 'TestCases', str(probId), 'input'+str(i)+'.txt') os.system(f'python main.py < {inpPath} > {outPath}') with open(os.path.join(BASE_DIR, "media", 'TestCases', str(probId), 'output'+str(i)+'.txt')) as f1, open(outPath) as f2: for line1, line2 in zip(f1, f2): if line1 != line2: isSame = False break if(isSame): cnt += 1 async_to_sync(channel_layer.group_send)("user_"+str(uid), {'type': 'sendStatus', 'text' : f"1/{i}/{totaltc}"}) else: async_to_sync(channel_layer.group_send)("user_"+str(uid), {'type': 'sendStatus', 'text' : f"0/{i}/{totaltc}"}) os.system(f"rm -rf {outPath}") os.system(f"touch {outPath}") else: os.system('python main.py < input.txt > output.txt 2>"output.log"') os.chdir(BASE_DIR) out = open(os.path.join(tempPath, 'output.txt'), "r") code_output = out.read() out.close() os.system(f"rm -rf {inpPath}") os.system(f"touch {inpPath}") tcString = str(cnt) + "/" + str(totaltc) if os.stat(os.path.join(tempPath, "output.log")).st_size != 0: f = open(os.path.join(tempPath, "output.log"), "r") error = f.read() f.close() os.system(f"rm -rf {tempPath}") Submission.objects.filter(pk = data['id']).update(error = error, status = "CE", testCasesPassed = tcString) else: os.system(f"rm -rf {tempPath}") Submission.objects.filter(pk = data['id']).update(outputGen = code_output, status = "AC", testCasesPassed = tcString) response = models.Submission.objects.filter(id = inst.id) async_to_sync(channel_layer.group_send)("user_"+str(uid), {'type': 'sendResult', 'text' : djSerializer.serialize('json', response)})
[ "himanshudhiman9313@gmail.com" ]
himanshudhiman9313@gmail.com
a502321e2690c313b4b7b13406aa5fcba1c2b341
369e0cbddf3cf698f6fc923aa05f74f7f45829d6
/notice_of_appearence_into_db.py
5718242b7b988e4d4c540f9690139058e4b073f3
[]
no_license
iamkhush/boondoh
70de9d2b9c50f8a46fc2bc663b641f3d068f061c
2f07779ab94e723e6749cb37ff470046699443e6
refs/heads/master
2016-09-06T19:43:56.626932
2011-10-21T16:02:23
2011-10-21T16:02:23
2,360,107
0
0
null
null
null
null
UTF-8
Python
false
false
904
py
import xlrd, sys import MySQLdb sh = xlrd.open_workbook(sys.argv[1]) sheet = sh.sheet_by_index(0) db = MySQLdb.connect(user="root",passwd="12345",db="ITC") c = db.cursor() for rownum in range(25,sheet.nrows): print rownum c.execute(""" INSERT INTO `ITC`.`IP_cases_n` (`id`, `doc_id`, `invoice_number`, `sec`, `F`, `offcial_recieve`, `firm__or_organisation`, `filled_on_behalf`, `office`, `state`, `attorney_first_name`, `attorney_last_name`, `notes`) VALUES (%d,'%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s') """ %(rownum,sheet.row_values(rownum)[1],sheet.row_values(rownum)[2],sheet.row_values(rownum)[3],sheet.row_values(rownum)[4],sheet.row_values(rownum)[5],sheet.row_values(rownum)[6],sheet.row_values(rownum)[7],sheet.row_values(rownum)[8],sheet.row_values(rownum)[9],sheet.row_values(rownum)[10],sheet.row_values(rownum)[11]))
[ "ankush.chadda@gmail.com" ]
ankush.chadda@gmail.com
fa2f2d62c4bced5baccc042351fc881dfc5da08b
6361a0807ee3970f59d1689aa4af922dcc40e262
/ui/pages/extra_window.py
ea5e694d7f5156a7d9474777d21fe1295b80ceb2
[]
no_license
laKostin951/BazePodatakaProjekat-G2-S1
e38a404c22fd699372b29b2efd95205d398ee653
b223ffdd07255de9506f677b790f181351ca5cd6
refs/heads/main
2023-03-28T01:41:29.946228
2021-03-27T14:00:23
2021-03-27T14:00:23
331,755,818
0
0
null
null
null
null
UTF-8
Python
false
false
6,198
py
from PySide2 import QtWidgets, QtGui from PySide2.QtCore import QCoreApplication from PySide2.QtWidgets import QLineEdit, QPushButton, QCheckBox, QLabel, QTableWidget, \ QTableWidgetItem, QFrame class ExtraWindow(QtWidgets.QDialog): def __init__(self, parent): super().__init__(parent) self.setWindowTitle("customer - Table") self.setWindowIcon(QtGui.QIcon("assets/img/icons8-edit-file-64.png")) self.resize(662, 438) self.save_talble_changes = QPushButton("Save table changes",self) self.save_talble_changes.setGeometry(390, 290, 251, 31) self.add_table_main = QPushButton("Add Column ",self) self.add_table_main.setGeometry(390, 260, 251, 28) #self.add_table_main.clicked.connect(self.add_column) self.delet_table_column = QPushButton("Delet table column",self) self.delet_table_column.setGeometry(390, 330, 251, 31) self.not_null_box = QCheckBox("Not Null",self) self.not_null_box.setGeometry(220, 330, 81, 61) self.colm_name_label = QLabel("Column Name:",self) self.colm_name_label.setGeometry(10, 250, 111, 41) self.table_name_label_2 = QLabel("Table Name",self) self.table_name_label_2.setGeometry(10, 10, 91, 21) self.comn_name_line_edit = QLineEdit(self) self.comn_name_line_edit.setGeometry(110, 260, 151, 22) self.data_type_label = QLabel("Data Type",self) self.data_type_label.setGeometry(10, 300, 61, 16) self.data_type_line_edit = QLineEdit(self) self.data_type_line_edit.setGeometry(110, 300, 151, 22) self.table_name_line_edit = QLineEdit(self) self.table_name_line_edit.setGeometry(110, 10, 391, 22) self.foreign_key_box = QCheckBox("Foreign Key",self) self.foreign_key_box.setGeometry(120, 330, 91, 61) self.primary_key_box = QCheckBox("Primary Key",self) self.primary_key_box.setGeometry(20, 330, 111, 61) self.table_widget = QTableWidget(self) if (self.table_widget.columnCount() < 6): self.table_widget.setColumnCount(6) __qtablewidgetitem = QTableWidgetItem() self.table_widget.setHorizontalHeaderItem(0, __qtablewidgetitem) __qtablewidgetitem1 = QTableWidgetItem() self.table_widget.setHorizontalHeaderItem(1, __qtablewidgetitem1) __qtablewidgetitem2 = QTableWidgetItem() self.table_widget.setHorizontalHeaderItem(2, __qtablewidgetitem2) __qtablewidgetitem3 = QTableWidgetItem() self.table_widget.setHorizontalHeaderItem(3, __qtablewidgetitem3) __qtablewidgetitem4 = QTableWidgetItem() self.table_widget.setHorizontalHeaderItem(4, __qtablewidgetitem4) __qtablewidgetitem5 = QTableWidgetItem() self.table_widget.setHorizontalHeaderItem(5, __qtablewidgetitem5) self.table_widget.setGeometry(0, 40, 661, 201) self.table_widget.setColumnWidth(2,85) self.table_widget.setColumnWidth(3,85) self.table_widget.setColumnWidth(4,85) self.frame = QFrame(self) self.frame.setGeometry(0, 390, 661, 51) self.frame.setStyleSheet(u"background-color: rgb(45,45,45);") self.frame.setFrameShape(QFrame.StyledPanel) self.frame.setFrameShadow(QFrame.Raised) self.cancel_button = QPushButton("Cancel button",self.frame) self.cancel_button.setGeometry(550, 10, 111, 28) self.cancel_button.setStyleSheet(u"background-color: rgb(255,255,255);") self.add_table_button = QPushButton("Add table",self.frame) self.add_table_button.setGeometry(442, 10, 101, 28) self.add_table_button.setStyleSheet(u"background-color: rgb(255,255,255);") self.tables() self.show() def tables(self): ''' self.setWindowTitle(QCoreApplication.translate("ExtraWindow", u"Dialog", None)) self.save_talble_changes.setText(QCoreApplication.translate("ExtraWindow", u"Save Table Changes", None)) self.add_table_main.setText(QCoreApplication.translate("ExtraWindow", u"Add Table", None)) self.delet_table_column.setText(QCoreApplication.translate("ExtraWindow", u"Delete Table Column", None)) self.not_null_box.setText(QCoreApplication.translate("ExtraWindow", u"Not null", None)) self.colm_name_label.setText(QCoreApplication.translate("ExtraWindow", u"Colomn Name", None)) self.table_name_label_2.setText(QCoreApplication.translate("ExtraWindow", u"Table Name", None)) self.data_type_label.setText(QCoreApplication.translate("ExtraWindow", u"Data Type", None)) self.foreign_key_box.setText(QCoreApplication.translate("ExtraWindow", u"Foreign key", None)) self.primary_key_box.setText(QCoreApplication.translate("ExtraWindow", u"Primary key", None)) ''' ___qtablewidgetitem = self.table_widget.horizontalHeaderItem(0) ___qtablewidgetitem.setText(QCoreApplication.translate("ExtraWindow", u"Column Name", None)) ___qtablewidgetitem1 = self.table_widget.horizontalHeaderItem(1) ___qtablewidgetitem1.setText(QCoreApplication.translate("ExtraWindow", u"Data Type", None)) ___qtablewidgetitem2 = self.table_widget.horizontalHeaderItem(2) ___qtablewidgetitem2.setText(QCoreApplication.translate("ExtraWindow", u"Primary key", None)) ___qtablewidgetitem3 = self.table_widget.horizontalHeaderItem(3) ___qtablewidgetitem3.setText(QCoreApplication.translate("ExtraWindow", u"Foreign key", None)) ___qtablewidgetitem4 = self.table_widget.horizontalHeaderItem(4) ___qtablewidgetitem4.setText(QCoreApplication.translate("ExtraWindow", u"Not Null", None)) ___qtablewidgetitem5 = self.table_widget.horizontalHeaderItem(5) ___qtablewidgetitem5.setText(QCoreApplication.translate("ExtraWindow", u"Default", None)) ''' self.cancel_button.setText(QCoreApplication.translate("ExtraWindow", u"Cancel", None)) self.add_table_button.setText(QCoreApplication.translate("ExtraWindow", u"Add table", None)) '''
[ "kostiigi@gmail.com" ]
kostiigi@gmail.com
6d0505bddaca68f2ca35c031d9afc346c7ee6be3
2d04af9d1fb27263a9c78afe265995d31696eb6f
/meter.py
fae6934ae055a56b8552751ff2865acf3894287a
[]
no_license
DVMix/mobilenet
b2122517324677b3549104de162e79efdc942ce0
d8016056e63f517f7da9a1b0f30c0d8b925fbb9b
refs/heads/main
2023-03-24T01:51:49.098153
2021-03-14T06:28:13
2021-03-14T06:28:13
347,560,929
0
0
null
null
null
null
UTF-8
Python
false
false
325
py
class AverageMeter: def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, num): self.val = val self.sum += val * num self.count += num self.avg = self.sum / self.count
[ "noreply@github.com" ]
noreply@github.com
523ea788cae3900a804b02dacb17fc1fb8428fc7
e19bb63df55d32f7cb699665e142d8c025a01ae3
/rospy-builder/setup.py
6effa870ba7b877801667f1a82d7053588154ef3
[ "Apache-2.0" ]
permissive
otamachan/rospy-index
fb5486a1a4854983a120e4f21604d35d58a471a1
5e1023e938e191a241ff220a35a9e67001552bb8
refs/heads/master
2020-07-05T23:32:11.617360
2019-10-19T07:50:03
2019-10-19T07:50:03
202,817,212
2
0
null
null
null
null
UTF-8
Python
false
false
557
py
from setuptools import setup setup( name='rospy-builder', version='1.0', description='rospy package build tool', author='Tamamki Nishino', author_email='otamachan@gmail.com', url='https://otamachan.github.io/rospy-index', packages=['rospy_builder'], install_requires=[ 'catkin_pkg', 'genmsg', 'genpy<2000', 'pyyaml', 'setuptools', 'gitpython', ], entry_points={ 'console_scripts': [ 'rospy-build = rospy_builder.build:main', ], }, )
[ "otamachan@gmail.com" ]
otamachan@gmail.com
ce44234617dd05ad5c3e05d20508e558a516f35a
6ff46960fc88f3d64ce371d12c76144121346a14
/venv/Lib/site-packages/nnfs/core.py
b7247eed4e3f538842d65ca67d1796ad93ed024c
[ "MIT" ]
permissive
BLTowsen/NeuralNetworkFromScratch
e84017c11af18d07fad2103f475add7ea67fbe9f
fe222a2142f66c9bab5a4ff8539e9c4b46d4e597
refs/heads/master
2022-11-24T05:00:46.892421
2020-07-30T08:56:59
2020-07-30T08:56:59
280,445,501
1
0
null
null
null
null
UTF-8
Python
false
false
1,847
py
import numpy as np import inspect # Initializes NNFS def init(dot_precision_workaround=True, default_dtype='float32', random_seed=0): # Numpy methods to be replaced for a workaround methods_to_enclose = [ [np, 'zeros', False], [np.random, 'randn', True], ] # https://github.com/numpy/numpy/issues/15591 # np.dot() is not consistent between machines # This workaround raises consistency # we make computations using float64, but return float32 data if dot_precision_workaround: orig_dot = np.dot def dot(*args, **kwargs): return orig_dot(*[a.astype('float64') for a in args], **kwargs).astype('float32') np.dot = dot else: methods_to_enclose.append([np, 'dot', False]) # https://github.com/numpy/numpy/issues/6860 # It is not possible to set default datatype with numpy # To make it able to enable and disable above workaround and set dtype # we'll enclose numpy method's with own one which will force different datatype if default_dtype: for method in methods_to_enclose: enclose(method, default_dtype) # Set seed to the given value (0 by default) if random_seed is not None: np.random.seed(random_seed) # Encloses numpy method def enclose(method, default_dtype): # Save a handler to original method method.append(getattr(*method)) def enclosed_method(*args, **kwargs): # If flag is True - use .astype() if method[2]: return method[3](*args, **kwargs).astype(default_dtype) # Else pass dtype in kwargs else: if 'dtype' not in kwargs: kwargs['dtype'] = default_dtype return method[3](*args, **kwargs) # Replace numpy method with enclosed one setattr(*method[:2], enclosed_method)
[ "lawrancetowsen@gmail.com" ]
lawrancetowsen@gmail.com