blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
616
content_id
stringlengths
40
40
detected_licenses
listlengths
0
69
license_type
stringclasses
2 values
repo_name
stringlengths
5
118
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
63
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
2.91k
686M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
213 values
src_encoding
stringclasses
30 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
2
10.3M
extension
stringclasses
246 values
content
stringlengths
2
10.3M
authors
listlengths
1
1
author_id
stringlengths
0
212
1faf1347cd1525f165138cd7f899bab919343c52
37a0d47e4ffe57277333012ba36ceea4b4c2685f
/backend/call/api/v1/viewsets.py
14b5ef46b8100bd251adc74882d742df902743d4
[]
no_license
crowdbotics-apps/nonprofitscreenapp-22237
bbe5c1dc7ab1f4cae6860a671741b488a4e3e9f3
fe5a55b917cb5cd166d3a91a5ba758e97e9f0286
refs/heads/master
2023-01-04T19:26:59.802350
2020-11-04T22:27:12
2020-11-04T22:27:12
309,513,430
0
0
null
null
null
null
UTF-8
Python
false
false
395
py
from rest_framework import authentication from call.models import Phone from .serializers import PhoneSerializer from rest_framework import viewsets class PhoneViewSet(viewsets.ModelViewSet): serializer_class = PhoneSerializer authentication_classes = ( authentication.SessionAuthentication, authentication.TokenAuthentication, ) queryset = Phone.objects.all()
[ "team@crowdbotics.com" ]
team@crowdbotics.com
91645f9825d06a79d1e9adbbb45c1628dcaef7db
bc441bb06b8948288f110af63feda4e798f30225
/cmdb_sdk/api/instance_tree/instance_tree_anchor_v2_pb2.pyi
f8a06a06187f0c3f7230e5e651967797e0f62fa0
[ "Apache-2.0" ]
permissive
easyopsapis/easyops-api-python
23204f8846a332c30f5f3ff627bf220940137b6b
adf6e3bad33fa6266b5fa0a449dd4ac42f8447d0
refs/heads/master
2020-06-26T23:38:27.308803
2020-06-16T07:25:41
2020-06-16T07:25:41
199,773,131
5
0
null
null
null
null
UTF-8
Python
false
false
4,176
pyi
# @generated by generate_proto_mypy_stubs.py. Do not edit! import sys from cmdb_sdk.model.cmdb.instance_tree_root_node_pb2 import ( InstanceTreeRootNode as cmdb_sdk___model___cmdb___instance_tree_root_node_pb2___InstanceTreeRootNode, ) from google.protobuf.descriptor import ( Descriptor as google___protobuf___descriptor___Descriptor, ) from google.protobuf.internal.containers import ( RepeatedScalarFieldContainer as google___protobuf___internal___containers___RepeatedScalarFieldContainer, ) from google.protobuf.message import ( Message as google___protobuf___message___Message, ) from google.protobuf.struct_pb2 import ( Struct as google___protobuf___struct_pb2___Struct, ) from typing import ( Iterable as typing___Iterable, Optional as typing___Optional, Text as typing___Text, Union as typing___Union, ) from typing_extensions import ( Literal as typing_extensions___Literal, ) builtin___bool = bool builtin___bytes = bytes builtin___float = float builtin___int = int if sys.version_info < (3,): builtin___buffer = buffer builtin___unicode = unicode class InstanceTreeAnchorV2Request(google___protobuf___message___Message): DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... ignore_single = ... # type: builtin___bool object_id = ... # type: typing___Text instanceIdList = ... # type: google___protobuf___internal___containers___RepeatedScalarFieldContainer[typing___Text] @property def tree(self) -> cmdb_sdk___model___cmdb___instance_tree_root_node_pb2___InstanceTreeRootNode: ... def __init__(self, *, tree : typing___Optional[cmdb_sdk___model___cmdb___instance_tree_root_node_pb2___InstanceTreeRootNode] = None, ignore_single : typing___Optional[builtin___bool] = None, object_id : typing___Optional[typing___Text] = None, instanceIdList : typing___Optional[typing___Iterable[typing___Text]] = None, ) -> None: ... if sys.version_info >= (3,): @classmethod def FromString(cls, s: builtin___bytes) -> InstanceTreeAnchorV2Request: ... else: @classmethod def FromString(cls, s: typing___Union[builtin___bytes, builtin___buffer, builtin___unicode]) -> InstanceTreeAnchorV2Request: ... def MergeFrom(self, other_msg: google___protobuf___message___Message) -> None: ... def CopyFrom(self, other_msg: google___protobuf___message___Message) -> None: ... def HasField(self, field_name: typing_extensions___Literal[u"tree",b"tree"]) -> builtin___bool: ... def ClearField(self, field_name: typing_extensions___Literal[u"ignore_single",b"ignore_single",u"instanceIdList",b"instanceIdList",u"object_id",b"object_id",u"tree",b"tree"]) -> None: ... class InstanceTreeAnchorV2ResponseWrapper(google___protobuf___message___Message): DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... code = ... # type: builtin___int codeExplain = ... # type: typing___Text error = ... # type: typing___Text @property def data(self) -> google___protobuf___struct_pb2___Struct: ... def __init__(self, *, code : typing___Optional[builtin___int] = None, codeExplain : typing___Optional[typing___Text] = None, error : typing___Optional[typing___Text] = None, data : typing___Optional[google___protobuf___struct_pb2___Struct] = None, ) -> None: ... if sys.version_info >= (3,): @classmethod def FromString(cls, s: builtin___bytes) -> InstanceTreeAnchorV2ResponseWrapper: ... else: @classmethod def FromString(cls, s: typing___Union[builtin___bytes, builtin___buffer, builtin___unicode]) -> InstanceTreeAnchorV2ResponseWrapper: ... def MergeFrom(self, other_msg: google___protobuf___message___Message) -> None: ... def CopyFrom(self, other_msg: google___protobuf___message___Message) -> None: ... def HasField(self, field_name: typing_extensions___Literal[u"data",b"data"]) -> builtin___bool: ... def ClearField(self, field_name: typing_extensions___Literal[u"code",b"code",u"codeExplain",b"codeExplain",u"data",b"data",u"error",b"error"]) -> None: ...
[ "service@easyops.cn" ]
service@easyops.cn
15d82001b2d22e0b0bf25b220d0b11a954eab139
2680093864e7590185ab8b7178f21352d6d257a5
/factorial.py
5c8ae69eccfac0f029e0772e9cff3e11caa94185
[]
no_license
BarnabasK/fizzbuzz
157cb6fb94997c697f393a68bd235460511a7ca1
973f2ec39a8c3e2721a3ee668f9453e272a377f4
refs/heads/master
2021-01-11T06:54:20.342775
2016-10-30T16:25:26
2016-10-30T16:25:26
72,357,145
0
0
null
null
null
null
UTF-8
Python
false
false
314
py
#Have a function factorial(number), take the number parameter been passed and return the factorial of it. #For example: if number is 4, it should return (4 * 3 * 2 * 1) which is 24. def factorial(num): factorial = 1 for i in range(1, num+1): factorial = factorial * i return factorial print(factorial(10))
[ "kariukibarnabas@gmail.com" ]
kariukibarnabas@gmail.com
15f568242d6f174e8eaff829accce8f270d94282
3400b44c17b4366d66536338ea8dee08d58c926f
/generateinfo/views.py
837f190714630121e143b6e622e22e0187ff8da6
[]
no_license
DonSaik/pollsDjango
c01915de69238d02c4d40267d8bb12ca59ffc884
5ee8c70e85b375eea666dbb188c89d5ca37c8f4c
refs/heads/master
2020-09-24T08:58:33.991534
2019-12-04T17:19:27
2019-12-04T17:19:27
225,720,921
0
0
null
null
null
null
UTF-8
Python
false
false
2,996
py
from django.shortcuts import get_object_or_404 from polls.models import Question import io from django.http import HttpResponse, FileResponse from xlwt import Borders from django.template.loader import get_template from django.utils import timezone import xhtml2pdf.pisa as pisa import xlwt import datetime # Create your views here. def pdf_view(request, question_id): datalist = get_object_or_404(Question, pk=question_id) today = timezone.now() params = { 'today': today, 'data': datalist, } template = get_template('generateinfo/generatepdf.html') html = template.render(params) buffer = io.BytesIO() pdf = pisa.pisaDocument(io.BytesIO(html.encode("UTF-8")), buffer) buffer.seek(0) return FileResponse(buffer, as_attachment=True, filename=str(datalist.id)+".pdf") def excel_view(request, question_id): datalist = get_object_or_404(Question, pk=question_id) today = datetime.datetime.now() response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="data.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Question') # Sheet header, first row date_format = xlwt.XFStyle() date_format.num_format_str = 'Mmm dd, yyyy, h:mm AM/PM' row_num = 1 ws.write(row_num, 0, today, date_format) row_num = 3 columns = ['ID', 'Question text', 'Created at', 'Groups', ] font_style = xlwt.XFStyle() font_style.font.bold = True for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # Sheet body, remaining rows font_style = xlwt.XFStyle() borders = Borders() borders.top = Borders.THIN borders.bottom = Borders.THIN font_style.borders = borders date_format.borders = borders data = Question.objects.all().values_list('id', 'question_text', 'created_at') row_num += 1 ws.write (row_num, 0, datalist.id, font_style) ws.write(row_num, 1, datalist.question_text, font_style) ws.write(row_num , 2, datalist.created_at.replace(tzinfo=None), date_format) for row in datalist.groups.all(): ws.write(row_num, 3, row.name, font_style) row_num += 1 # xlwt.easyxf("borders: left thin, right thin, top thin, bottom thin;") row_num += 1 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['Choices', 'Votes', ] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) font_style = xlwt.XFStyle() borders = Borders() borders.top = Borders.THIN borders.bottom = Borders.THIN font_style.borders = borders for row in datalist.choice_set.all(): row_num += 1 ws.write(row_num, 0, row.choice_text, font_style) ws.write(row_num, 1, row.vote_set.count(), font_style) for colx in range(0, 5): width = 10000 ws.col(colx).width = width wb.save(response) return response
[ "ds32204@gmail.com" ]
ds32204@gmail.com
1d4913ccb5c729773c440c70c0f177451d1d9578
2b28759d02601c21d8506ee9f45abe9f763c8d35
/deivani9.py
22a7dbb00aa29f6d5656833d8aac919388541dd9
[]
no_license
Rajadeivani/deivani9
da612e39f89d7db1abca09a94bd147c6f9505908
ed2ac449f9652c6dd7e3b3df58c12abd83b23e29
refs/heads/master
2020-06-24T02:38:59.831762
2019-07-25T12:23:30
2019-07-25T12:23:30
198,825,400
0
0
null
null
null
null
UTF-8
Python
false
false
151
py
num = ch(input()) if((num>='a' and num<= 'z') or (num>='A' and num<='Z')): print(num, "is an Alphabet") else: print(num, "is not an Alphabet")
[ "noreply@github.com" ]
Rajadeivani.noreply@github.com
41ecb0fe0bdf87b0c1ebc4493930a2d22f00a45e
a438adc4bdceb4acbb4d5a4cff48c05c720349c5
/Lesson_12/shoppinglistparse.py
04b9b74d6595aa867b821a4d003b2d6cdc9e9244
[]
no_license
anneharris4/Hackbright-Intro-to-Programming-Assignments
d2f53e278cf0f39823aa6a87499440cf657d3844
a35216499a199277158d335f477c1da52e492145
refs/heads/master
2016-09-13T06:58:39.237514
2016-05-22T22:43:33
2016-05-22T22:43:33
57,790,518
0
0
null
null
null
null
UTF-8
Python
false
false
352
py
shop1 = "item : apples, quantity : 4, price : 1.50\n" shop2 = shop1.split(',') quantity_list = shop2[1].split(":")[1] price_list=shop2[2].split(':')[1] quantity_list = float(quantity_list) price_list =float(price_list) def calculate_bill (quantity_list,price_list): return quantity_list * price_list print calculate_bill (quantity_list,price_list)
[ "anneharris4@gmail.com" ]
anneharris4@gmail.com
4cd2b717a6df5a7b3bf7eca581c8a162ae1bbbe3
66c3ff83c3e3e63bf8642742356f6c1817a30eca
/.vim/tmp/neocomplete/include_cache/=+home=+abel=+.virtualenvs=+django=+lib=+python2.7=+site-packages=+django=+core=+urlresolvers.py
2a8512bf3f996b861a1f42b58f05eb423f8c92c1
[]
no_license
pacifi/vim
0a708e8bc741b4510a8da37da0d0e1eabb05ec83
22e706704357b961acb584e74689c7080e86a800
refs/heads/master
2021-05-20T17:18:10.481921
2020-08-06T12:38:58
2020-08-06T12:38:58
30,074,530
0
0
null
null
null
null
UTF-8
Python
false
false
4,613
py
[{'word': 'LocaleRegexProvider', 'menu': '[I]', 'kind': 'c', 'abbr': 'LocaleRegexProvider(object): <class>'}, {'word': 'LocaleRegexURLResolver', 'menu': '[I]', 'kind': 'c', 'abbr': 'LocaleRegexURLResolver(RegexURLResolver): <class>'}, {'word': 'NoReverseMatch', 'menu': '[I]', 'kind': 'c', 'abbr': 'NoReverseMatch(Exception): <class>'}, {'word': 'RegexURLPattern', 'menu': '[I]', 'kind': 'c', 'abbr': 'RegexURLPattern(LocaleRegexProvider): <class>'}, {'word': 'RegexURLResolver', 'menu': '[I]', 'kind': 'c', 'abbr': 'RegexURLResolver(LocaleRegexProvider): <class>'}, {'word': 'Resolver404', 'menu': '[I]', 'kind': 'c', 'abbr': 'Resolver404'}, {'word': 'ResolverMatch', 'menu': '[I]', 'kind': 'c', 'abbr': 'ResolverMatch(object): <class>'}, {'word': '__init__', 'menu': 'ResolverMatch', 'kind': 'm', 'abbr': 'def __init__(self, func, args, kwargs, url_name=None, app_name=None, namespaces=None):'}, {'word': '_callable_cache', 'menu': '[I]', 'kind': 'v', 'abbr': '_callable_cache = {} # Maps view and url pattern names to their view functions.'}, {'word': '_ns_resolver_cache', 'menu': '[I]', 'kind': 'v', 'abbr': '_ns_resolver_cache = {} # Maps namespaces to RegexURLResolver instances.'}, {'word': '_populate', 'menu': 'RegexURLResolver', 'kind': 'm', 'abbr': 'def _populate(self):'}, {'word': '_prefixes', 'menu': '[I]', 'kind': 'v', 'abbr': '_prefixes = local()'}, {'word': '_resolve_special', 'menu': 'RegexURLResolver', 'kind': 'm', 'abbr': 'def _resolve_special(self, view_type):'}, {'word': '_resolver_cache', 'menu': '[I]', 'kind': 'v', 'abbr': '_resolver_cache = {} # Maps URLconf modules to RegexURLResolver instances.'}, {'word': '_reverse_with_prefix', 'menu': 'RegexURLResolver', 'kind': 'm', 'abbr': 'def _reverse_with_prefix(self, lookup_view, _prefix, *args, **kwargs):'}, {'word': '_urlconfs', 'menu': '[I]', 'kind': 'v', 'abbr': '_urlconfs = local()'}, {'word': 'add_prefix', 'menu': 'RegexURLPattern', 'kind': 'm', 'abbr': 'def add_prefix(self, prefix):'}, {'word': 'app_dict', 'menu': 'RegexURLResolver', 'kind': 'm', 'abbr': 'def app_dict(self):'}, {'word': 'callback', 'menu': 'RegexURLPattern', 'kind': 'm', 'abbr': 'def callback(self):'}, {'word': 'clear_script_prefix', 'menu': '[I]', 'kind': 'f', 'abbr': 'def clear_script_prefix():'}, {'word': 'clear_url_caches', 'menu': '[I]', 'kind': 'f', 'abbr': 'def clear_url_caches():'}, {'word': 'get_callable', 'menu': '[I]', 'kind': 'f', 'abbr': 'def get_callable(lookup_view, can_fail=False):'}, {'word': 'get_mod_func', 'menu': '[I]', 'kind': 'f', 'abbr': 'def get_mod_func(callback):'}, {'word': 'get_ns_resolver', 'menu': '[I]', 'kind': 'f', 'abbr': 'def get_ns_resolver(ns_pattern, resolver):'}, {'word': 'get_resolver', 'menu': '[I]', 'kind': 'f', 'abbr': 'def get_resolver(urlconf):'}, {'word': 'get_script_prefix', 'menu': '[I]', 'kind': 'f', 'abbr': 'def get_script_prefix():'}, {'word': 'get_urlconf', 'menu': '[I]', 'kind': 'f', 'abbr': 'def get_urlconf(default=None):'}, {'word': 'is_valid_path', 'menu': '[I]', 'kind': 'f', 'abbr': 'def is_valid_path(path, urlconf=None):'}, {'word': 'namespace', 'menu': 'ResolverMatch', 'kind': 'm', 'abbr': 'def namespace(self):'}, {'word': 'namespace_dict', 'menu': 'RegexURLResolver', 'kind': 'm', 'abbr': 'def namespace_dict(self):'}, {'word': 'regex', 'menu': 'LocaleRegexProvider', 'kind': 'm', 'abbr': 'def regex(self):'}, {'word': 'resolve', 'menu': 'RegexURLPattern', 'kind': 'm', 'abbr': 'def resolve(self, path):'}, {'word': 'resolve400', 'menu': 'RegexURLResolver', 'kind': 'm', 'abbr': 'resolve400'}, {'word': 'resolve403', 'menu': 'RegexURLResolver', 'kind': 'm', 'abbr': 'resolve403'}, {'word': 'resolve404', 'menu': 'RegexURLResolver', 'kind': 'm', 'abbr': 'resolve404'}, {'word': 'resolve500', 'menu': 'RegexURLResolver', 'kind': 'm', 'abbr': 'resolve500'}, {'word': 'reverse', 'menu': 'RegexURLResolver', 'kind': 'm', 'abbr': 'def reverse(self, lookup_view, *args, **kwargs):'}, {'word': 'reverse_dict', 'menu': 'RegexURLResolver', 'kind': 'm', 'abbr': 'def reverse_dict(self):'}, {'word': 'reverse_lazy', 'menu': '[I]', 'kind': 'v', 'abbr': 'reverse_lazy = lazy(reverse, str)'}, {'word': 'set_script_prefix', 'menu': '[I]', 'kind': 'f', 'abbr': 'def set_script_prefix(prefix):'}, {'word': 'set_urlconf', 'menu': '[I]', 'kind': 'f', 'abbr': 'def set_urlconf(urlconf_name):'}, {'word': 'url_patterns', 'menu': 'RegexURLResolver', 'kind': 'm', 'abbr': 'def url_patterns(self):'}, {'word': 'urlconf_module', 'menu': 'RegexURLResolver', 'kind': 'm', 'abbr': 'def urlconf_module(self):'}, {'word': 'view_name', 'menu': 'ResolverMatch', 'kind': 'm', 'abbr': 'def view_name(self):'}]
[ "pacifi.bnr@gmail.com" ]
pacifi.bnr@gmail.com
460d5f0bfeac95517098e3c24993693ef5f06d93
2b52acc6141bb0d4716b7b1ad617e5302ece42b3
/comentarios/api/viewsets.py
47d41f1b3d4ab4337725d95e3c8a25d85f541c66
[]
no_license
nayannanara/django-rest-framework
4eb621c55ffd22f2d5e4ea55815552f03d099c5f
6b2c8a6de091c4647b228bb19dd2ee536e4772bd
refs/heads/master
2023-03-04T14:42:29.942526
2021-02-14T13:02:37
2021-02-14T13:02:37
321,846,045
0
0
null
null
null
null
UTF-8
Python
false
false
261
py
from rest_framework.viewsets import ModelViewSet from comentarios.models import Comentario from .serializers import ComentarioSerializer class ComentarioViewSet(ModelViewSet): queryset = Comentario.objects.all() serializer_class = ComentarioSerializer
[ "nayanna501@gmail.com" ]
nayanna501@gmail.com
c1f385635984be5f23fc87275477174408f7985e
0f7718c7d4df241d6d4aa2638e265bd735f3761f
/python-client/test/test_recognize_request.py
d5ff6ac52b87fe00f2e73f50be0c31745e5fee92
[]
no_license
jplaceres/Guardian
9d0eca833b235b1c6cdd1e9f8524357aef0da375
74ecad9232b77e575350da4792986f1f5ec64aac
refs/heads/master
2020-04-26T11:00:42.848546
2019-03-02T22:09:59
2019-03-02T22:09:59
173,502,415
0
0
null
null
null
null
UTF-8
Python
false
false
881
py
# coding: utf-8 """ Betaface API 2.0 Betaface face recognition API. # noqa: E501 OpenAPI spec version: 2.0 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest import swagger_client from swagger_client.models.recognize_request import RecognizeRequest # noqa: E501 from swagger_client.rest import ApiException class TestRecognizeRequest(unittest.TestCase): """RecognizeRequest unit test stubs""" def setUp(self): pass def tearDown(self): pass def testRecognizeRequest(self): """Test RecognizeRequest""" # FIXME: construct object with mandatory attributes with example values # model = swagger_client.models.recognize_request.RecognizeRequest() # noqa: E501 pass if __name__ == '__main__': unittest.main()
[ "33101350+jplaceres@users.noreply.github.com" ]
33101350+jplaceres@users.noreply.github.com
c2f8e0154349643a895fea833e2a1eeb7e25c897
fdcbf5b203f07cceefbb38a746f4a43b322e263e
/Python/string_similarity/create_sample_data.py
208b55446b99e6914b361cbdf673d639438ffb52
[]
no_license
Masoumeh/0390.IbnAhmadMuqaddasi.AhsanTaqasim
e7a3eddc895edb79f8d93c1bd0f09f130a761858
592720e5a154fcfe9cdab84b16eaf5574f30b806
refs/heads/master
2021-01-18T00:36:09.962622
2017-11-07T13:13:46
2017-11-07T13:13:46
45,922,253
0
0
null
2015-11-10T15:49:02
2015-11-10T15:49:02
null
UTF-8
Python
false
false
592
py
import get_sttl_reg as gsr import numpy as np def write_sample_file(data_file, write_file): muq_sttls = list(gsr.get_sttl(data_file)) sample_index = np.random.choice(1200, 100) with open(write_file, 'w', encoding="utf8") as samples_file: for i in sample_index: sttl = muq_sttls[i] print(sttl) samples_file.write(sttl + "\n") write_sample_file("/home/rostam/Arabic_Persian/LocalAlmoghaddasi/Data/Muqaddasi/muq_hier_all", "/home/rostam/Arabic_Persian/LocalAlmoghaddasi/Data/Muqaddasi/string_similarity/sample_data")
[ "m.seydi@uni-leipzig.de" ]
m.seydi@uni-leipzig.de
fb4b0789e6190cd6c3f1eb1a911363043e65006e
587e2fc104a484c60aa2fab01c3cdc1d2a330778
/Prozor/Prozor.py
dda495e85ca4e4ff7cb4a46a1f952e95dea47cf9
[]
no_license
tlittle2/Kattis-Solutions-Python
7b3c379f9b394b8b944377c1329332e483ccfcf3
92ed9987b81e3276d2a03252177f1f45b98388e4
refs/heads/main
2022-10-10T07:51:33.431519
2022-09-30T22:29:12
2022-09-30T22:29:12
216,254,189
0
2
null
2022-09-30T18:27:47
2019-10-19T18:42:47
Python
UTF-8
Python
false
false
543
py
#/usr/bin/env python3 import sys def main(): rows,cols,rack= [int(x) for x in sys.stdin.readline().split()] window=[] for i in range(rows): print(window.append(list(sys.stdin.readline().rstrip()))) count= 0 for i in range(rows-rack+1): for j in range(cols-rack+1): for k in range(i+1, i+rack-1): count+=window[k][j+1: j+rack-1].count('*') print(count) for i in range(rows): print(''.join(window[i])) if __name__ == "__main__": main()
[ "noreply@github.com" ]
tlittle2.noreply@github.com
dbfefbd395ad03c04935a750e349e51e17f0f114
67758d0837e59828a6f522596268b90045ea309c
/02 skeleton_version/qt_import.py
d85715cac9c9add932f640d76bd770274f635462
[]
no_license
mskoenz/workingTitle
e2009fa470493db1b2e601d7075c32a30d3dcc4e
a27e2a7dfa60bedc9f92c92d4b20b2cc3acaa8cf
refs/heads/master
2020-05-18T03:41:39.205698
2012-01-22T21:45:47
2012-01-22T21:45:47
3,062,773
0
1
null
null
null
null
UTF-8
Python
false
false
450
py
#!/usr/bin/python3.2 # -*- coding: cp1252 -*- # # Author: Mario S. Könz <mskoenz@gmx.net> # Date: 16.01.2012 17:36:09 CET # File: qt_import.py try: from PySide.QtCore import * from PySide.QtGui import * print("PySide loaded") except ImportError: try: from PyQt4.QtCore import * from PyQt4.QtGui import * print("PyQt4 loaded") except ImportError: print("Error: no PySide or PyQt4 Module")
[ "mskoenz@gmx.net" ]
mskoenz@gmx.net
2abcdea583720c1791f057a4c62c1b85df091afe
a3c662a5eda4e269a8c81c99e229879b946a76f6
/.venv/lib/python3.7/site-packages/pylint/test/functional/cellvar_escaping_loop.py
23c6b4b2e146d28a183c0aa82118e1869bef02e4
[ "MIT" ]
permissive
ahmadreza-smdi/ms-shop
0c29da82c58b243507575672bbc94fb6e8068aeb
65ba3f3061e2ac5c63115b08dadfe7d67f645fb6
refs/heads/master
2023-04-27T19:51:34.858182
2019-11-24T20:57:59
2019-11-24T20:57:59
223,616,552
6
2
MIT
2023-04-21T20:51:21
2019-11-23T16:09:03
Python
UTF-8
Python
false
false
2,472
py
# pylint: disable=print-statement """Tests for loopvar-in-closure.""" from __future__ import print_function def good_case(): """No problems here.""" lst = [] for i in range(10): lst.append(i) def good_case2(): """No problems here.""" return [i for i in range(10)] def good_case3(): """No problems here.""" lst = [] for i in range(10): lst.append(lambda i=i: i) def good_case4(): """No problems here.""" lst = [] for i in range(10): print(i) lst.append(lambda i: i) def good_case5(): """No problems here.""" return (i for i in range(10)) def good_case6(): """Accept use of the variable inside return.""" for i in range(10): if i == 8: return lambda: i return lambda: -1 def good_case7(): """Lambda defined and called in loop.""" for i in range(10): print((lambda x: i + x)(1)) def good_case8(): """Another eager binding of the cell variable.""" funs = [] for i in range(10): def func(bound_i=i): """Ignore.""" return bound_i funs.append(func) return funs def bad_case(): """Closing over a loop variable.""" lst = [] for i in range(10): print(i) lst.append(lambda: i) # [cell-var-from-loop] def bad_case2(): """Closing over a loop variable.""" return [lambda: i for i in range(10)] # [cell-var-from-loop] def bad_case3(): """Closing over variable defined in loop.""" lst = [] for i in range(10): j = i * i lst.append(lambda: j) # [cell-var-from-loop] return lst def bad_case4(): """Closing over variable defined in loop.""" lst = [] for i in range(10): def nested(): """Nested function.""" return i**2 # [cell-var-from-loop] lst.append(nested) return lst def bad_case5(): """Problematic case. If this function is used as >>> [x() for x in bad_case5()] it behaves 'as expected', i.e. the result is range(10). If it's used with >>> lst = list(bad_case5()) >>> [x() for x in lst] the result is [9] * 10 again. """ return (lambda: i for i in range(10)) # [cell-var-from-loop] def bad_case6(): """Closing over variable defined in loop.""" lst = [] for i, j in zip(range(10), range(10, 20)): print(j) lst.append(lambda: i) # [cell-var-from-loop] return lst
[ "ahmadreza.smdi@gmail.com" ]
ahmadreza.smdi@gmail.com
6a318fbcc08879357f4b53da88f761a9ae7b1322
f7c39a27d7b932523097e8379fe18b77d99efafd
/apps/reserva/apps.py
2cd090ca175f5ab0e7ff3ccc919c7a518c51b7c5
[]
no_license
francobostian/TpMetodologia
8533ae01aa7ac07c75eca7cc45853f09a27a5772
755fc622f2186f17f976ea83e8c23265f284966e
refs/heads/master
2020-04-05T18:38:14.770350
2018-11-16T04:57:14
2018-11-16T04:57:14
157,106,826
1
0
null
null
null
null
UTF-8
Python
false
false
154
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.apps import AppConfig class ReservaConfig(AppConfig): name = 'reserva'
[ "francobostian@gmail.com" ]
francobostian@gmail.com
8927b66c17aba3be47ad44adf5e8be615f925b3b
23dbbf39374e30ecf518e5646182e36cd7537f6c
/backend/src/entities/entity.py
c043f8fa10aeecdc10ff6cf226c0cf0bd1e21fde
[]
no_license
ashokpkumar/templat_application
9c28824bf01ceb3d57bba01022139e70fdc79fba
2b364d38cfea06b5845a75e6e639d2296763b75b
refs/heads/staging-master
2023-03-27T08:20:39.455635
2021-03-25T15:24:45
2021-03-25T15:24:45
351,477,156
0
1
null
2021-03-30T13:21:22
2021-03-25T15:02:25
Python
UTF-8
Python
false
false
770
py
from datetime import datetime from sqlalchemy import create_engine, Column, String, Integer, DateTime from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker db_url = 'localhost:5432' db_name = 'online-exam' db_user = 'postgres' db_password = '0NLIN3-ex4m' engine = create_engine(f'postgresql://{db_user}:{db_password}@{db_url}/{db_name}') Session = sessionmaker(bind=engine) Base = declarative_base() class Entity(): id = Column(Integer, primary_key=True) created_at = Column(DateTime) updated_at = Column(DateTime) last_updated_by = Column(String) def __init__(self, created_by): self.created_at = datetime.now() self.updated_at = datetime.now() self.last_updated_by = created_by
[ "mani120488@gmail.com" ]
mani120488@gmail.com
ccbf0df253c59c0acbdb7fd3a32f366274aff649
39e876928091892e371c2390d3787ed7e8846069
/label_gui.py
04f624ab110397861b165971a64061416720f573
[]
no_license
IPavlak/Grayscale-CNN
540ab5c28b3b48341070359ba6aa7519e1ed2578
bc5e0e8f38e3bcc1669219600a330fe197265046
refs/heads/master
2020-07-28T05:08:57.633764
2019-10-03T11:47:12
2019-10-03T11:47:12
209,318,383
0
0
null
null
null
null
UTF-8
Python
false
false
6,175
py
import tkinter as tk import numpy as np from math import floor, ceil red = 'NOT' orange = 'NOT' white = 'NOT' txt_gui = None exit_flag = False def classify(ids): global red, orange, white args = ids.split(':') if args[0] == 'red': red = 'red -> ' + args[1] elif args[0] == 'orange': orange = 'orange -> ' + args[1] elif args[0] == 'white': white = 'white -> ' + args[1] txt_gui.delete(1.0, tk.END) txt_gui.insert(tk.CURRENT, red + " ||| " + orange + " ||| " + white) def next_img(root): global red, orange, white, exit_flag red = 'NOT' orange = 'NOT' white = 'NOT' exit_flag = True root.destroy() return def save_img(root, base_path, file, rd, row_max, col_max, rect_rows, rect_cols): global red, orange, white, exit_flag if red == 'NOT' or orange == 'NOT' or white == 'NOT': return rd = np.pad(rd, ((rect_rows, rect_rows), (rect_cols, rect_cols)), mode='constant', constant_values=((0,0), (0,0))) col_left = floor((rect_cols - 1) / 2) col_right = ceil((rect_cols - 1) / 2) row_down = ceil((rect_rows - 1) / 2) row_up = floor((rect_rows - 1) / 2) rect_red = rd[row_max[0]-row_down : row_max[0]+row_up+1, col_max[0]-col_left : col_max[0]+col_right+1] # array[start:stop+1] rect_orange = rd[row_max[1]-row_down : row_max[1]+row_up+1, col_max[1]-col_left : col_max[1]+col_right+1] # array[start:stop+1] rect_white = rd[row_max[2]-row_down : row_max[2]+row_up+1, col_max[2]-col_left : col_max[2]+col_right+1] # array[start:stop+1] rect_red = np.reshape(rect_red, (rect_rows, rect_cols)) rect_orange = np.reshape(rect_orange, (rect_rows, rect_cols)) rect_white = np.reshape(rect_white, (rect_rows, rect_cols)) f = open(base_path + red[7:len(red)] + '/' + file[0:len(file)-4] + '_red.txt', 'w') rect_red_array = np.asarray(rect_red) np.savetxt(f, np.asarray([row_max[0], col_max[0]]), delimiter=',') np.savetxt(f, rect_red_array, delimiter=',') f.close() f = open(base_path + orange[10:len(orange)] + '/' + file[0:len(file)-4] + '_orange.txt', 'w') rect_orange_array = np.asarray(rect_orange) np.savetxt(f, np.asarray([row_max[1], col_max[1]]), delimiter=',') np.savetxt(f, rect_orange_array, delimiter=',') f.close() f = open(base_path + white[9:len(white)] + '/' + file[0:len(file)-4] + '_white.txt', 'w') rect_white_array = np.asarray(rect_white) np.savetxt(f, np.asarray([row_max[2], col_max[2]]), delimiter=',') np.savetxt(f, rect_white_array, delimiter=',') f.close() red = 'NOT' orange = 'NOT' white = 'NOT' exit_flag = True root.destroy() return def run_gui(base_path, file, rd, row_max, col_max, rect_rows, rect_cols): root = tk.Tk() root.geometry("600x400+700+200") # size and placement of the gui window respectively global exit_flag exit_flag = False man = tk.Button(master=root, text='man', command=lambda: classify('red:man'), bg='red').place(x=1, y=5, width=100, height=30) car = tk.Button(master=root, text='car', command=lambda: classify('red:car'), bg='red').place(x=1, y=40, width=100, height=30) nothing = tk.Button(master=root, text='nothing', command=lambda: classify('red:nothing'), bg='red').place(x=1, y=75, width=100, height=30) wrong_man = tk.Button(master=root, text='wrong_man', command=lambda: classify('red:wrong_man'), bg='red').place(x=120, y=5, width=100, height=30) wrong_car = tk.Button(master=root, text='wrong_car', command=lambda: classify('red:wrong_car'), bg='red').place(x=120, y=40, width=100, height=30) garbage = tk.Button(master=root, text='garbage', command=lambda: classify('red:garbage'), bg='red').place(x=120, y=75, width=100, height=30) man = tk.Button(master=root, text='man', command=lambda: classify('orange:man'), bg='orange').place(x=1, y=120, width=100, height=30) car = tk.Button(master=root, text='car', command=lambda: classify('orange:car'), bg='orange').place(x=1, y=155, width=100, height=30) nothing = tk.Button(master=root, text='nothing', command=lambda: classify('orange:nothing'), bg='orange').place(x=1, y=190, width=100, height=30) wrong_man = tk.Button(master=root, text='wrong_man', command=lambda: classify('orange:wrong_man'), bg='orange').place(x=120, y=120, width=100, height=30) wrong_car = tk.Button(master=root, text='wrong_car', command=lambda: classify('orange:wrong_car'), bg='orange').place(x=120, y=155, width=100, height=30) garbage = tk.Button(master=root, text='garbage', command=lambda: classify('orange:garbage'), bg='orange').place(x=120, y=190, width=100, height=30) man = tk.Button(master=root, text='man', command=lambda: classify('white:man'), bg='white').place(x=1, y=235, width=100, height=30) car = tk.Button(master=root, text='car', command=lambda: classify('white:car'), bg='white').place(x=1, y=270, width=100, height=30) nothing = tk.Button(master=root, text='nothing', command=lambda: classify('white:nothing'), bg='white').place(x=1, y=305, width=100, height=30) wrong_man = tk.Button(master=root, text='wrong_man', command=lambda: classify('white:wrong_man'), bg='white').place(x=120, y=235, width=100, height=30) wrong_car = tk.Button(master=root, text='wrong_car', command=lambda: classify('white:wrong_car'), bg='white').place(x=120, y=270, width=100, height=30) garbage = tk.Button(master=root, text='garbage', command=lambda: classify('white:garbage'), bg='white').place(x=120, y=305, width=100, height=30) global txt_gui txt_gui = tk.Text(master=root, height=1, width=200, bg='#B4B4B4') txt_gui.pack(side=tk.BOTTOM) txt_gui.insert(tk.CURRENT, red + " ||| " + orange + " ||| " + white) next = tk.Button(master=root, text = 'NEXT', command=lambda: save_img(root, base_path, file, rd, row_max, col_max, rect_rows, rect_cols), bg='green').place(x=450, y=135, width=90, height=60) skip = tk.Button(master=root, text = 'SKIP', command=lambda: next_img(root), bg='grey').place(x=450, y=245, width=90, height=60) while not exit_flag: root.update_idletasks() root.update()
[ "ivan.pavlak@fer.hr" ]
ivan.pavlak@fer.hr
8b2e0a2780393df8d6d12b84da7e1d9a11670ab6
52ea21f0b6a2a994539bc900fa7b7d9c2278a3c4
/RoboticFramework/Position/Position.py
8fb2f2498970811e352cb1b4bb85d1dda72a9f29
[]
no_license
dheerendra1/RobotNaturalLearning
1b485a47a0deddaef55a6d8aa7bf0a4962478dcd
036070f713008950f07c9e42a52fc55868b0c544
refs/heads/master
2020-12-24T18:13:04.871143
2011-10-23T14:59:21
2011-10-23T14:59:21
null
0
0
null
null
null
null
UTF-8
Python
false
false
218
py
#Abstract position class # Author: Witold Wasilewski 2011 class Position: _value = 0 type = "Abstract" def __init__(self, value): self._value = list(value) def getValue(self): return self._value
[ "vitotao@gmail.com" ]
vitotao@gmail.com
415065eaf61d37a2964051f86901692df17d1bba
a96fffd451827146cbeeede4712e1ba23ea4147e
/lang/python/2016-05-19/exp6.py
2d93f956b27bfb80455979e2e9c5058e94b73fd2
[]
no_license
synchronized/gtd
360f3a030fa5d3939c610e521886c65e960f01c9
7363de59d198fdb2b1f09a68c7d61f314c6d8d4e
refs/heads/master
2023-06-24T09:09:36.702386
2023-06-12T02:16:36
2023-06-12T02:16:36
49,370,734
0
0
null
2023-02-25T04:24:05
2016-01-10T14:41:42
C++
UTF-8
Python
false
false
1,487
py
#!/usr/bin/env python # -*- coding:utf-8 -*- import os import pickle class FileDescr(object): saved = [] def __init__(self, name=None): self.name = name def __get__(self, obj, typ=None): if self.name not in FileDescr.saved: raise AttributeError, \ '%r used before assignment' % self.name try: f = open(self.name, 'r') val = pickle.load(f) f.close() return val except (pickle.InpicklingError, IOError, EOFError, AttributeError, ImportError, IndexError), e: raise AttributeError, \ "could not read %r: %s" % self.name def __set__(self, obj, val): f = open(self.name, 'w') try: try: pickle.dump(val, f) FileDescr.saved.append(self.name) except (TypeError, pickle.PicklingError), e: raise AttributeError, \ "could not pickle %r" % self.name finally: f.close() def __delete__(self, obj): try: os.unlink(self.name) FileDescr.saved.remove(self.name) except (OSError, ValueError), e: pass class MyFileVarClass(object): foo = FileDescr('foo') bar = FileDescr('bar') def main(): fvc = MyFileVarClass() fvc.foo = 42 fvc.bar = 'leanna' print fvc.foo, fvc.bar if __name__ == '__main__': main()
[ "synchronized@yeah.net" ]
synchronized@yeah.net
ec6d7359acfe5f63e5d0a2082973529f08f8a5d4
52d41c97581dbbe2c559472722b73f6731837a2f
/pydron/translation/test_decomp.py
e638f20360e5569c2224fdf18b3bf0e805614099
[ "MIT" ]
permissive
pydron/pydron
89268bf215f436d701b7dee31d7538157ab53e00
a7b484dec8bcc2730ba9bd76bc63bf3362c05e4d
refs/heads/master
2020-04-06T06:53:23.800903
2016-04-14T11:41:33
2016-04-14T11:41:33
56,232,534
5
2
null
null
null
null
UTF-8
Python
false
false
1,535
py
# Copyright (C) 2014 Stefan C. Mueller import unittest from pydron.translation import utils, decomp class TestDeComp(unittest.TestCase): def test_list(self): src = """ def test(): return [x for x in lst] """ expected = """ def test(): return [x for x in lst] """ utils.compare(src, expected, decomp.DeComp) def test_set(self): src = """ def test(): return {x for x in lst} """ expected = """ def test(): return set([x for x in lst]) """ utils.compare(src, expected, decomp.DeComp) def test_dict(self): src = """ def test(): return {k:v for k,v in lst} """ expected = """ def test(): return dict([(k,v) for k,v in lst]) """ utils.compare(src, expected, decomp.DeComp) def test_set_nested_list(self): src = """ def test(): return {x for x in {y for y in lst}} """ expected = """ def test(): return set([x for x in set([y for y in lst])]) """ utils.compare(src, expected, decomp.DeComp) def test_set_nested_elt(self): src = """ def test(): return {{y for y in x} for x in lst} """ expected = """ def test(): return set([set([y for y in x]) for x in lst]) """ utils.compare(src, expected, decomp.DeComp)
[ "scm@smurn.org" ]
scm@smurn.org
56a18ea38a3756bc399bf2e1e0c3ead7ee5d5c06
3c158b18fd706a8732c8b2f70ad57bc4328ec23b
/pyAlertGen.py
649532e666ba821d67cbaae98113261befeb8e5f
[ "MIT" ]
permissive
LavheyM/tkinter_base_template
19059e1d52780dca34e9dbfc84583d777b9f8d93
db7ead4c1f0448a7eefb2117eed083f85933702f
refs/heads/master
2020-07-01T18:16:59.615846
2019-08-08T13:03:26
2019-08-08T13:03:26
201,252,807
0
0
null
null
null
null
UTF-8
Python
false
false
765
py
import tkinter as tk class Application(tk.Frame): def __init__(self, master=None): super().__init__(master) self.master = master master.title("Python Link Generator v.01") master.geometry("425x175") self.grid() self.create_widgets() def create_widgets(self): self.button1 = tk.Button(self) self.button1["text"] = "Button1" self.button1["command"] = self.button1_output #self.button1.pack(side="top") self.quit = tk.Button(self, text="Quit", fg="red", command=self.master.destroy) #self.quit.pack(side="bottom") def button1_output(self): pass root = tk.Tk() app = Application(master=root) app.mainloop()
[ "40267291+LavheyM@users.noreply.github.com" ]
40267291+LavheyM@users.noreply.github.com
e7db50b5124ba11c9c8bdc76de58e831dc27f3d3
9c7cb29490635e373fbc50d0784a67804eb52b94
/operationstesting.py
d0deb91b0a9850e6b6ea79d9d7a98312c50e3613
[]
no_license
siddharthsubramaniam1996/sensiblepythoncode
42d98c635492a912295e202bdc9acd3a440f1e78
3501300935d615b02f3272748572eb2fc869e33f
refs/heads/master
2021-06-29T20:38:41.762966
2021-01-06T13:43:56
2021-01-06T13:43:56
197,215,857
1
1
null
null
null
null
UTF-8
Python
false
false
1,690
py
# -*- coding: utf-8 -*- """ Created on Mon Jul 29 19:47:18 2019 @author: SIDDHARTH """ import numpy as np L=np.array([3,4,5]) N=np.array([3,4,5],np.int32) print(L) print(N) print(L*N) print(N*3) print(L+L) print(N+N) O=np.array([2,4,6,8]) print(O) P=np.array([[2],[4],[6]]) print(P) Q=np.array([[1,2,3,4],[5,1,7,8]]) print(Q) R=np.zeros([1,6],dtype=int,order='C') print("\nMatrix R: \n", R) R[0][3]=15 R[0][5]=25 print("Result",R) S=np.arange(13,25).reshape(3,4) print (S) A=np.arange(10,100,10) print("\n\tA IS: \n") print(A) B=np.arange(0,16).reshape(4,4) print("\n\tB IS: \n") print(B) print("\n\tCut1 0:2,1:3 \n") C1=B[0:2,1:3] print(C1) print("\n\tCut2 2:6:3 \n") C2=A[2:6:3] #start stop jump print(C2) print("\n\tCut3 -1:-3 \n") C3=A[-1:-3] print(C3) print("\n\tCut4 :-1 \n") C4=B[:-1] print(C4) print("\n\tCut5 :-1 \n") C5=B[:3, 2:] print(C5) print("\n\tCut6 :-1 \n") C6=B[-3,6:2:-1] print(C6) print("\n\tConcat 1 \n") c7=np.array([1,2,3]) c8=np.array([3,2,1]) z=np.concatenate([c7,c8]) print(z) print("\n\tConcat 2 (axis =0) \n") grid=np.array([[1,2,3],[4,5,6]]) G2=np.concatenate([grid,grid], axis=None) print(G2) print("\n\tConcat 3 (axis =1) \n") grid=np.array([[1,2,3],[4,5,6]]) G3=np.concatenate([grid,grid], axis=1) print(G3) print("\n\tvstack \n") x=np.array([1,2,3]) g=np.array([[9,8,7],[6,5,4]]) R=np.vstack([x,g]) print(R) print("\n\t hstack \n") g1=np.array([[9,8,7],[6,5,4]]) y=np.array([[99],[99]]) R1=np.hstack([g,y]) print(R1) print("\n\t split \n") x=[1,2,3,99,99,3,2,1] x1, x2, x3=np.split(x, [3,5]) print("\nx1:",x1, "\nx2:",x2,"\nx3:",x3)
[ "noreply@github.com" ]
siddharthsubramaniam1996.noreply@github.com
e252c6bc189d98d40c6b3adf034ba673d18893f3
86091c60ceb6582768ba9fd24d6e7dd00dfcffec
/giggleliu/tba/hgen/utils.py
0fd01de5fe07f940fd21483053463e4e95178f2b
[ "MIT" ]
permissive
Lynn-015/NJU_DMRG
8d6167ab26c571b81ca1bdbfe7c7ffb9dccac7ea
88be712b2d17603f7a3c38836dabe8dbdee2aba3
refs/heads/master
2020-04-05T19:00:54.364285
2016-12-10T09:33:20
2016-12-10T09:33:20
44,971,751
2
0
null
null
null
null
UTF-8
Python
false
false
2,762
py
''' Author: Giggle Leo Date : 8 September 2014 Description : physics library ''' from numpy import * from numpy.linalg import * from matplotlib.pyplot import * import scipy.sparse as sps import pdb,time __all__=['sx','sy','sz','s','H2G','s2vec','vec2s','ind2c','c2ind'] ############################ DEFINITIONS ############################## # pauli spin sx = array([[0, 1],[ 1, 0]]) sy = array([[0, -1j],[1j, 0]]) sz = array([[1, 0],[0, -1]]) s=[identity(2),sx,sy,sz] ############################ FUNCTIONS ############################## def H2G(h,w,tp='r',geta=1e-2,sigma=None): ''' Get Green's function g from Hamiltonian h. h: an array of hamiltonian. w: the energy(frequency). tp: the type of Green's function. 'r': retarded Green's function.(default) 'a': advanced Green's function. 'matsu': finite temperature Green's function. geta: smearing factor. default is 1e-2. sigma: additional self energy. *return*: a Green's function. ''' if tp=='r': z=w+1j*geta elif tp=='a': z=w-1j*geta elif tp=='matsu': z=1j*w if sigma!=None: h=h+sigma hdim=ndim(h) if hdim>0: return inv(z*identity(h.shape[-1])-h) else: return 1./(z-h) def s2vec(s): ''' Transform a spin to a 4 dimensional vector, corresponding to s0,sx,sy,sz component. s: the spin. ''' res=array([trace(s),trace(dot(sx,s)),trace(dot(sy,s)),trace(dot(sz,s))])/2 return res def vec2s(n): ''' Transform a vector of length 3 or 4 to a pauli matrix. n: a 1-D array of length 3 or 4 to specify the `direction` of spin. *return*: 2 x 2 matrix. ''' if len(n)<=3: res=zeros([2,2],dtype='complex128') for i in xrange(len(n)): res+=s[i+1]*n[i] return res elif len(n)==4: return identity(2)*n[0]+sx*n[1]+sy*n[2]+sz*n[3] else: raise Exception('length of vector %s too large.'%len(n)) def c2ind(c,N): ''' Get the index of the total space N from the index of the subspace exression (n1 x n2 x n3...) c: a list of indexes like [i,j,k,...] N: the space config [n1,n2,n3...]. ''' n=c.shape[-1] cc=c[...,0] for i in xrange(n-1): cc=cc*N[i+1]+c[...,i+1] return cc def ind2c(ind,N): ''' Get the index of the index of the subspace from the total space N. ind: the index of total space. N: the space config [n1,n2,n3...]. ''' dim=len(N) indl=ndarray(list(shape(ind))+[dim],dtype='int32') for i in xrange(dim): indl[...,-1-i]=ind%N[-1-i] ind=ind/N[-1-i] return indl
[ "lynn_015@outlook.com" ]
lynn_015@outlook.com
6e480ff6a021a328c9c46edcbb4326f0509dfa29
984b125ae0b6094c1f05e0d6045bc9e3e1ca8b49
/html/v0.2/image/survey_example.py
0d019fdac15de4d6abf97c3d56e39e4c764698ae
[]
no_license
cdeil/gammapy-docs-rtd-archive
6a171322239ae918d4814a792cb64922226435a6
f28c7a480a66f6189d73e909967acfc8722d63f0
refs/heads/master
2021-05-11T02:22:18.826834
2018-01-21T17:38:04
2018-01-21T17:38:04
118,354,235
0
0
null
null
null
null
UTF-8
Python
false
false
651
py
"""Plot a Galactic plane survey image in two panels.""" from aplpy import FITSFigure from gammapy.datasets import FermiGalacticCenter from gammapy.image import GalacticPlaneSurveyPanelPlot class GPSFermiPlot(GalacticPlaneSurveyPanelPlot): def main(self, figure, subplot): filename = FermiGalacticCenter.filenames()['counts'] self.fits_figure = FITSFigure(filename, figure=figure, subplot=subplot) self.fits_figure.show_colorscale(vmin=1, vmax=10) self.fits_figure.ticks.set_xspacing(2) plot = GPSFermiPlot(npanels=3, center=(0, 0), fov=(30, 3)) plot.draw_panels('all') plot.figure.savefig('survey_example.png')
[ "Deil.Christoph@gmail.com" ]
Deil.Christoph@gmail.com
95b7635b1536790811d098d8565b00f3acc36710
879bebb89d30aac73e0cb3afb1412efdf51bcc11
/unum_config.py
7b64079f2218c39205f4b64d1a2aae600d25bac6
[]
no_license
jrmuizel/pyunum
d8247caf55757742dc8731d5353651e9c35b481d
c99c3eea3ffb5d235dd24426dcedf107af8091cf
refs/heads/master
2023-09-04T03:14:36.570175
2016-04-27T17:25:16
2016-04-27T17:25:16
34,972,849
57
14
null
2016-03-21T17:07:06
2015-05-03T03:48:16
Python
UTF-8
Python
false
false
12
py
e = 3 f = 4
[ "jmuizelaar@mozilla.com" ]
jmuizelaar@mozilla.com
a96d4d582ea9213d45d349e10c8139dd57e26a65
ae5f69089c0e792c913fa86f36d923cd60b47e51
/tests/test_insert.py
b206926a111e92e3a1620dbcb2831cb5cb91e949
[ "MIT" ]
permissive
kenchensb/sqllineage
ca930a222f3fd8d57195270bd6d5037359d06381
43da1348d2589ade519291630d1abb48042c6b99
refs/heads/master
2023-05-26T23:17:19.391680
2021-06-14T11:42:50
2021-06-14T11:42:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,177
py
from .helpers import helper def test_insert_into(): helper("INSERT INTO tab1 VALUES (1, 2)", set(), {"tab1"}) def test_insert_into_with_keyword_table(): helper("INSERT INTO TABLE tab1 VALUES (1, 2)", set(), {"tab1"}) def test_insert_into_with_columns(): helper("INSERT INTO tab1 (col1, col2) SELECT * FROM tab2;", {"tab2"}, {"tab1"}) def test_insert_into_with_columns_and_select(): helper("INSERT INTO tab1 (col1, col2) SELECT * FROM tab2", {"tab2"}, {"tab1"}) def test_insert_into_with_columns_and_select_union(): helper( "INSERT INTO tab1 (col1, col2) SELECT * FROM tab2 UNION SELECT * FROM tab3", {"tab2", "tab3"}, {"tab1"}, ) def test_insert_into_partitions(): helper( "INSERT INTO TABLE tab1 PARTITION (par1=1) SELECT * FROM tab2", {"tab2"}, {"tab1"}, ) def test_insert_overwrite(): helper("INSERT OVERWRITE tab1 SELECT * FROM tab2", {"tab2"}, {"tab1"}) def test_insert_overwrite_with_keyword_table(): helper("INSERT OVERWRITE TABLE tab1 SELECT col1 FROM tab2", {"tab2"}, {"tab1"}) def test_insert_overwrite_values(): helper( "INSERT OVERWRITE tab1 VALUES ('val1', 'val2'), ('val3', 'val4')", {}, {"tab1"} ) def test_insert_overwrite_from_self(): helper( """INSERT OVERWRITE TABLE tab_1 SELECT tab2.col_a from tab_2 JOIN tab_1 ON tab_1.col_a = tab_2.cola""", {"tab_1", "tab_2"}, {"tab_1"}, ) def test_with_insert(): helper( "WITH tab1 AS (SELECT * FROM tab2) INSERT INTO tab3 SELECT * FROM tab1", {"tab2"}, {"tab3"}, ) def test_with_insert_overwrite(): helper( "WITH tab1 AS (SELECT * FROM tab2) INSERT OVERWRITE tab3 SELECT * FROM tab1", {"tab2"}, {"tab3"}, ) def test_with_insert_plus_keyword_table(): helper( "WITH tab1 AS (SELECT * FROM tab2) INSERT INTO TABLE tab3 SELECT * FROM tab1", {"tab2"}, {"tab3"}, ) def test_with_insert_overwrite_plus_keyword_table(): helper( "WITH tab1 AS (SELECT * FROM tab2) INSERT OVERWRITE TABLE tab3 SELECT * FROM tab1", {"tab2"}, {"tab3"}, )
[ "noreply@github.com" ]
kenchensb.noreply@github.com
cdbbf6f97cfad02fde41b96e3addd353a035e946
c4a0ee5346d464fa4f9c7b6c93a627c5be60bbff
/scripts/WalkExp.py
85cec9fc1b3dd241183c42d2198342e769970f66
[]
no_license
s91402001/quadruped_control
f12dbb559cc3c91f64fa4aab83b0ee2966237879
680abd7cae854cea83028d82945ac6a20fedfba1
refs/heads/master
2021-01-19T03:19:40.119697
2016-07-09T10:41:36
2016-07-09T10:41:36
48,423,532
0
0
null
null
null
null
UTF-8
Python
false
false
5,182
py
#!/usr/bin/env python import rospy from math import cos from math import fabs import time import RobotFuncs from std_msgs.msg import Float32 from geometry_msgs.msg import Point from quadruped_control.msg import MotorAngles iniTime =0 leg1th1,leg1th2,leg2th1,leg2th2 ,leg3th1,leg3th2,leg4th1,leg4th2 = 90,0,-90,0,90,0,-90,0 LeftH = 0.04 RightH = 0.04 LeftL = 0.06 RightL = 0.06 deltaLmax = 0.05 Orientation = 0.0 desiredOrientation =0.0 Ta = 0.4 Td = 0.8 ptd = [-0.02,-0.15] ptd1 = [0.02,-0.15] isStop = False isTurn = False State = 1 def RightHCallback(data): global RightH RightH = RightH + round(data.data,3) print data.data def LeftHCallback(data): global LeftH LeftH = LeftH + round(data.data,3) print data.data def LeftLCallback(data): global LeftL LeftL = LeftL + round(data.data,3) print data.data def RightLCallback(data): global RightL RightL = RightL + round(data.data,3) print data.data def TaCallback(data): global Ta Ta = Ta + round(data.data,1) print data.data def TdCallback(data): global Td Td = Td + round(data.data,1) print data.data def ptdxCallback(data): global ptd ptd[0] = ptd[0] + round(data.data,3) print data.data def ptdyCallback(data): global ptd ptd[1] = ptd[1] + round(data.data,3) print data.data def ptd1xCallback(data): global ptd1 ptd1[0] = ptd1[0] + round(data.data,3) print data.data def ptd1yCallback(data): global ptd1 ptd1[1] = ptd1[1] + round(data.data,3) print data.data def isStopCallback(data): global isStop isStop = not isStop print data.data def isTurnCallback(data): global isTurn print data.data def OrientationCallback(data): global Orientation Orientation = data.x print data.x print Orientation def desiredOrientationCallback(data): global desiredOrientation desiredOrientaion = data.data print data.data def MainProssece(): global leg1th1,leg1th2,leg2th1,leg2th2 ,leg3th1,leg3th2,leg4th1,leg4th2 global iniTime,LeftH,RightH,LeftL,RightL,Ta,Td global ptd,ptd1 global deltaLmax,Orientation,desiredOrientation pub1 = rospy.Publisher('MotorSetpoint', MotorAngles, queue_size=1024) rospy.init_node('reference') rospy.Subscriber("LeftH", Float32, LeftHCallback) rospy.Subscriber("RightH", Float32, RightHCallback) rospy.Subscriber("LeftL", Float32, LeftLCallback) rospy.Subscriber("RightL", Float32, RightLCallback) rospy.Subscriber("Ta", Float32, TaCallback) rospy.Subscriber("Td", Float32, TdCallback) rospy.Subscriber("ptdx", Float32, ptdxCallback) rospy.Subscriber("ptdy", Float32, ptdyCallback) rospy.Subscriber("ptd1x", Float32, ptd1xCallback) rospy.Subscriber("ptd1y", Float32, ptd1yCallback) rospy.Subscriber("isStop", Float32, isStopCallback) rospy.Subscriber("BodyOrientation", Point, OrientationCallback) angles = MotorAngles() rate = rospy.Rate(50) # 10hz while not rospy.is_shutdown(): if iniTime ==0: iniTime = time.time() t = time.time() -iniTime if t <=5: global Orientation leg1th1,leg1th2,leg2th1,leg2th2 ,leg3th1,leg3th2,leg4th1,leg4th2 = 90,0,-90,0,90,0,-90,0 #rospy.loginfo("t = %s"%t) print ("t = %s"%t) print("Orientation = %s"%Orientation) elif t >5 and t <15: print ("t = %s"%t) x1 = 0 x2 = 0 x3 = 0 x4 = 0 y1 = -0.16 y2 = -0.16 y3 = -0.16 y4 = -0.16 leg1th1_des,leg1th2_des,leg2th1_des,leg2th2_des ,leg3th1_des,leg3th2_des,leg4th1_des,leg4th2_des = RobotFuncs.actualReference(x1,y1,x2,y2,x3,y3,x4,y4) tt =t-5 leg1th1 = 90 + (leg1th1_des-90)*tt/10 leg2th1 = -90 + (leg2th1_des+90)*tt/10 leg3th1 = 90 + (leg3th1_des-90)*tt/10 leg4th1 = -90 + (leg4th1_des+90)*tt/10 leg1th2 = leg1th2_des*tt*0/10 leg2th2 = leg2th2_des*tt*0/10 leg3th2 = leg3th2_des*tt*0/10 leg4th2 = leg4th2_des*tt*0/10 else : if (fabs(desiredOrientation-Orientation)) > 5: deltaL = (deltaLmax/fabs(desiredOrientation-Orientation))*(desiredOrientation-Orientation) print("deltaL 1=%s"%deltaL) else: deltaL = deltaLmax*(desiredOrientation-Orientation)/5.0 #print("deltaL =%s"%deltaL) print("delta =%s"%(desiredOrientation-Orientation)) leg1th1,leg1th2,leg2th1,leg2th2 ,leg3th1,leg3th2,leg4th1,leg4th2 = RobotFuncs.generateRemoteCommand(ptd,ptd1,LeftH,RightH,LeftL+deltaL,RightL-deltaL,Ta,Td,t) #rospy.loginfo("Reference : %s,\r\n%s,\t%s,\t%s,\t%s,\r\n%s,\t%s,\t%s,\t%s\r\n"%(t,leg1th1,leg1th2,leg2th1,leg2th2 ,leg3th1,leg3th2,leg4th1,leg4th2)) print("t = %s\r\nReference : %s,\t%s,\t%s,\t%s,\r\n%s,\t%s,\t%s,\t%s\r\n" %(t,leg1th1,leg1th2,leg2th1,leg2th2 ,leg3th1,leg3th2,leg4th1,leg4th2)) print("Right H = %s Left H = %s Right L = %s Left L = %s Ta = %s Td = %s ptd = %s ptd1 = %s isStop = %s" %(RightH,LeftH,RightL-deltaL,LeftL+deltaL,Ta,Td,ptd,ptd1,isStop)) #outFile = open('ExpData.txt','a') #outFile.write(str(t)+'\t'+str(Orientation)+'\t'+str(desiredOrientation)+'\r\n') angles.ang1 = leg1th1 angles.ang2 = leg2th1 angles.ang3 = leg3th1 angles.ang4 = leg4th1 angles.ang5 = leg1th2 angles.ang6 = leg2th2 angles.ang7 = leg3th2 angles.ang8 = leg4th2 pub1.publish(angles) rate.sleep() if __name__ == '__main__': try: MainProssece() except rospy.ROSInterruptException: pass
[ "s91402001@gmail.com" ]
s91402001@gmail.com
59cea2eb429009357563209061045b12a57395ed
dfb6a80dda5882a1c2be87b0b6e1e7a87a7b4c20
/test/test_device_type_array.py
07275f3238e36a65bc16075787c2dbfcab27855e
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
artikcloud/artikcloud-python
a090201bea9fadbdf5dd57d94d9085b03b34f927
c5489b2fca27fd9a8bcea99f309e02cb690dd349
refs/heads/master
2020-12-26T03:33:00.657575
2017-12-28T20:40:05
2017-12-28T20:40:05
55,102,598
13
11
null
2017-03-18T03:22:58
2016-03-30T22:38:07
Python
UTF-8
Python
false
false
835
py
# coding: utf-8 """ ARTIK Cloud API No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: 2.0.0 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys import unittest import artikcloud from artikcloud.rest import ApiException from artikcloud.models.device_type_array import DeviceTypeArray class TestDeviceTypeArray(unittest.TestCase): """ DeviceTypeArray unit test stubs """ def setUp(self): pass def tearDown(self): pass def testDeviceTypeArray(self): """ Test DeviceTypeArray """ model = artikcloud.models.device_type_array.DeviceTypeArray() if __name__ == '__main__': unittest.main()
[ "jswattonjue@gmail.com" ]
jswattonjue@gmail.com
6213143d37b701cddc3bd02ad04ead4730648dd3
fb0ddefaa2fec8b80b5f0d5f27eb201703e8599c
/Days/day15/binary.py
3ccec95ecf0594968af3e215ce3fa192319c9596
[]
no_license
hamidihekmat/Programming-Practice
faa10e8277bc6da3f413b35565b66a8e489f3064
2119357634482ca3c73de28818b9a6b4fa34a6cf
refs/heads/master
2020-07-13T12:00:10.223812
2019-10-04T18:37:08
2019-10-04T18:37:08
205,078,317
1
0
null
null
null
null
UTF-8
Python
false
false
153
py
def binary(int): binary = '' while int!=0: int = int / 2 binary += str(int % 2) return binary[::-1] print(binary(255))
[ "theonehamidi@gmail.com" ]
theonehamidi@gmail.com
7c47f7283c0da28dbf4eba399cb9ca36e5cde1f3
045a9da06ded1a2dd0311fcf34e4859e3934e2cd
/venv/Scripts/easy_install-script.py
5af263c5515d492ee2298fa0f2c59b34513af1b5
[]
no_license
testestzxcv/analysis_pd_test
48479a874d3234abf23babd251338b11ce4e1a57
92721655a843ed236262b9cdb3d5fa0e74f646fe
refs/heads/master
2020-03-20T09:10:26.664473
2018-06-14T08:36:49
2018-06-14T08:36:49
137,330,159
0
0
null
null
null
null
UTF-8
Python
false
false
447
py
#!D:\PycharmProjects\analysis_pd_test\venv\Scripts\python.exe # EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==39.1.0','console_scripts','easy_install' __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')() )
[ "illuillu55@hotmail.com" ]
illuillu55@hotmail.com
3cff6193ecc1eec7bc14e4e3012916d09dd0ce96
ac9ee909a8a9c546781450e2145210e86c0dfe2f
/LoginAuthentication-Django-main/Login/models.py
0e3dc7c12a0fe6693c02a69459685d9afdb77a81
[]
no_license
Florencekyarikunda/LoginAuthenticationForm-Django
79d054245d1a894362f968faf640eb040781c2e3
81584a8aa6c70c7099cf2b69489cb3dda48d8959
refs/heads/master
2023-07-04T02:27:38.698137
2021-08-09T09:09:09
2021-08-09T09:09:09
394,226,273
0
0
null
null
null
null
UTF-8
Python
false
false
473
py
from django.db import models from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): # Making one to one relationship with User model of Django user = models.OneToOneField(User, on_delete=models.CASCADE) auth_token = models.CharField(max_length=100) verified = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.username
[ "florencekyarikund@gmail.com" ]
florencekyarikund@gmail.com
dfcfba24d132a9c9a4b8646a52c480b1b175bf15
fa11c4d0fd4ddac2afd4387d4c58704fde19723c
/sample.py
2bd2f48c52fa4ee031de62de9cf1bb9adbf01c44
[]
no_license
rrakesh100/sample-django
4aad071f7e27458a5aa637233204ccddf5a45196
735d8a8c0221c2d471f2cddd6eb15475c6c8bc75
refs/heads/master
2020-07-18T20:19:20.832880
2019-09-04T11:46:54
2019-09-04T11:46:54
206,306,346
0
0
null
null
null
null
UTF-8
Python
false
false
192
py
import os; import sys; print(os.path.dirname(__file__)) print(os.path.basename(__file__)) print(os.path.abspath(__file__)) print(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
[ "rakesh.rampalli@bigbasket.com" ]
rakesh.rampalli@bigbasket.com
1bae556d02178233cda63a9813e54edbab64a307
560022b5f21c4b7c086547e6cf2d72351c5d87fd
/crm/crm/urls.py
e0b1d521f504acd8ff9e1ae07732ecf307cac586
[]
no_license
novice-gamer/crmself
5999667389a7ff5ba6002bcb8aa1fb6f2d03cdc4
e9d894c4a3be52983da8dc8359126fdccd42a88c
refs/heads/master
2023-01-23T06:06:53.855973
2021-04-09T07:58:08
2021-04-09T07:58:08
216,338,411
0
0
null
2023-01-11T19:54:53
2019-10-20T09:40:03
HTML
UTF-8
Python
false
false
835
py
"""crm URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.pulgin, name='pulgin') 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='pulgin') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url,include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^user/',include('user.urls',namespace='user') ), ]
[ "17611236100@163.com" ]
17611236100@163.com
d6cb57d8f74d7f6693fe814df163f7f5c7925053
fcbe8723526462b85a13310b9d1d1c466d10710f
/bot.py
3cab40dc00322cfae1f29352f16d8843b75f485f
[ "MIT" ]
permissive
hectorRod101/Instagram_Bot
e7fa88a48649ae652030ef69677efcbbf129888c
cd6b10fa7bf9bdd7b87fbf03a33892e020b6e8e5
refs/heads/main
2023-01-11T00:40:57.297461
2020-11-05T20:08:11
2020-11-05T20:08:11
310,380,221
0
0
null
null
null
null
UTF-8
Python
false
false
2,379
py
# Created By: Hector Rodriguez from selenium.webdriver.common.by import By from selenium import webdriver import os, time, sys import bot_functions as bf class InstagramBot: def __init__(self, username = None, password = None): """Initialize parameters for Instagram login.""" self.username = username self.password = password self.driver = webdriver.Chrome(executable_path='/Users/hectorrodriguez/Desktop/instaBot/chromedriver') def sign_up(self): """Bot for signing up for Instagram.""" self.driver.get('https://www.instagram.com/accounts/emailsignup/') def log_in(self): """Bot to log onto instagram with valid credits.""" print("Logging in.........") self.driver.get('https://www.instagram.com/accounts/login/') time.sleep(1) # pause self.driver.find_element_by_xpath("//input[@name='username']").send_keys(self.username) self.driver.find_element_by_xpath("//input[@name='password']").send_keys(self.password) time.sleep(1) # pause self.driver.find_element_by_xpath("//button[contains(.,'Log In')]").click() time.sleep(5) # pause print("Successfully logged in.\n") def save_info(self): """When save info appears onto screen.""" print("Save info screen.") if self.driver.find_element_by_xpath("//button[contains(.,'Not Now')]"): self.driver.find_element_by_xpath("//button[contains(.,'Not Now')]").click() if __name__ == '__main__': home = True # Set loop for menu. while home: # Check main menu bot options. val = bf.menu() # Check if it's a valid option. val, home = bf.check_option(val, home) # If valid option, run option. if not home: bot = bf.menu_selection(val, bf) home_log_in = True # Set loop for log in menu. while home_log_in: # Check login in menu bot options. val2 = bf.menu_log_in() # Check if it's a valid option. val2, home_log_in = bf.check_option_log_in(val2, home_log_in) # If valid option, run option. if not home_log_in and val2 != 5: home_log_in = True bf.menu_selection_log_in(val2, bf, bot.driver) elif val2 == 5: # Option log out. bf.log_out(bf, bot.driver)
[ "hectorrodriguez@Hectors-MacBook-Pro.local" ]
hectorrodriguez@Hectors-MacBook-Pro.local
71873742c0d28828c53b56ee54deb2d0f76bef90
c384c1f8062f01a6a343e4aad7fcd231a906dbf5
/python/Count the point V1.py
8755e096c7dd20fc5a9cbc5022e7ff3fd70538b0
[]
no_license
RawitSHIE/Algorithms-Training-Python
b9bf95ccc7b3974de78f290492d646679d05ae4b
02ba71f88d18e48b35046564fe6f61911db31ac4
refs/heads/master
2021-03-24T12:34:02.101117
2017-12-10T14:15:40
2017-12-10T14:15:40
109,127,600
0
0
null
null
null
null
UTF-8
Python
false
false
288
py
"""Count the point V.1""" def main(): """Count the point V.1""" time = int(input()) for _ in range(time): point = list(input()) if "." in point: num = point.index(".") print(len(point[num+1:])) else: print(0) main()
[ "Rawitgun@gmail.com" ]
Rawitgun@gmail.com
d4e66bfa17d1e1f19eb7b0ce1c189b1d70480b0d
245c492894a82b986d6cfcc4a2a519f08989a251
/present_k.py
d6d274d307a476b97c7fd8e12ae62fd383d53a11
[]
no_license
muthuramasamy/Player
bb20db14d787a6a8c514437a4a3e11a6a84f5273
11bdae8d84c980ef3d204d45f7a3a3fd480561c0
refs/heads/master
2020-04-18T18:09:59.563987
2019-02-18T13:38:26
2019-02-18T13:38:26
167,676,089
0
1
null
null
null
null
UTF-8
Python
false
false
178
py
# your code goes here n,k=map(int,input().split()) li=list(map(int,input().split())) f=0 for i in li: if i==k: f=1 else: continue if f==1: print("Yes") else: print("No")
[ "noreply@github.com" ]
muthuramasamy.noreply@github.com
b46aa02ab19cc27d82be37ad53921de0c0e5dbe6
f912049e661c163ac3db8ab8358df8da4c8f9fce
/common/auth.py
936f3f54a315b58a45134cc8df6a543285c2bc3f
[]
no_license
vibhash1083/load-test-locustio
4ab38e1c2fd4ce469fe0e88ce7b35d321fb8d974
3c6fd28b5b22f2ac9e281137aae0581e49923f75
refs/heads/master
2023-04-30T21:07:59.311492
2021-05-20T20:04:51
2021-05-20T20:04:51
116,121,893
0
0
null
null
null
null
UTF-8
Python
false
false
395
py
def login(self): # GET login page to get csrftoken from it print("logging innnnnnnnnn") response = self.client.get('quiz/login/') csrftoken = response.cookies['csrftoken'] # POST to login page with csrftoken self.client.post('quiz/login/', {'username': 'prajaip', 'password': 'locust'}, headers={'X-CSRFToken': csrftoken})
[ "prajaip@amazon.com" ]
prajaip@amazon.com
ceea920616f07da8b48de670bd3a87ceba768a61
099d29ec51df145a04c4ca0b22d069ef45ee3575
/Assegnment/inventory/migrations/0003_remove_inventory_author.py
3ed635828a3fe089ab54f6e91515c53245e210da
[]
no_license
prahaladc20/invent
51e7d6194e9c33a7b1131f46d6cdac21308f6809
8256e3f6e24231ba2561d760e5a1c5d481e3e33a
refs/heads/master
2023-01-24T12:29:08.281628
2019-12-10T15:07:33
2019-12-10T15:07:33
225,514,320
0
0
null
2023-01-07T12:25:22
2019-12-03T02:37:35
Python
UTF-8
Python
false
false
331
py
# Generated by Django 2.2.7 on 2019-11-27 15:22 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('inventory', '0002_inventory_author'), ] operations = [ migrations.RemoveField( model_name='inventory', name='author', ), ]
[ "prahaladc20@gmail.com" ]
prahaladc20@gmail.com
ef8b3323333c1819d0f0617597141303720ffa5a
fb0c0b784ae7e9f000d0194563a7784bbf46daf0
/data/components/message_window.py
e183a5473f9cd5a7d24eaf994c18145cc61670b7
[]
no_license
iminurnamez/lessor
25a0d2a84bad195b884f521d4ee6dc814602a5d0
b591a379d7f5019dbae57a5a5ee88672d2342729
refs/heads/master
2021-01-21T05:16:58.779434
2017-02-25T23:56:34
2017-02-25T23:56:34
83,165,839
0
0
null
null
null
null
UTF-8
Python
false
false
1,385
py
import pygame as pg from .. import prepare from ..components.labels import Label, Button, ButtonGroup, MultiLineLabel from ..components.window import Window class MessageWindow(Window): def __init__(self, building, player, message): super(MessageWindow, self).__init__(building, player) self.msg = MultiLineLabel(prepare.FONTS["PortmanteauRegular"], 24, message, prepare.TEXT_COLOR, {"center": self.rect.center}, bg=None, char_limit=21, align="center", vert_space=16) self.buttons = ButtonGroup() idle, hover = self.make_button_images("OK", "small") w, h = idle.get_size() Button((self.rect.centerx - (w//2), self.rect.bottom - 56), self.buttons, button_size=(w, h), idle_image=idle, hover_image=hover, call=self.cancel) def cancel(self, *args): self.done = True self.next = "GAMEPLAY" def get_event(self, event): self.buttons.get_event(event) def update(self, dt, mouse_pos): self.buttons.update(mouse_pos) def draw(self, surface): self.building.draw(surface) self.draw_window(surface) self.msg.draw(surface) self.buttons.draw(surface)
[ "easinerf@gmail.com" ]
easinerf@gmail.com
d706094388182f230bb3ca8c6b7f24b46b339ab1
9f66941e73cad0c215601339512b8dd6729792da
/Show_Program_exe/predictModelUI/tensorflow/core/protobuf/saved_object_graph_pb2.py
49dc225a4205282e1120033dc9b5f2026c16e5e6
[]
no_license
NgaAdrain/TEAM_Enter_Text_Here
eb0e02c13959b90eecc0c69d2b24adb23a50150a
a7217438284360e06c93d37092dca1afcecb735a
refs/heads/master
2023-07-20T11:42:50.353497
2021-05-28T08:30:53
2021-05-28T08:30:53
267,983,495
2
0
null
2023-07-06T22:00:36
2020-05-30T00:50:59
Python
UTF-8
Python
false
true
37,038
py
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: tensorflow/core/protobuf/saved_object_graph.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from tensorflow.core.framework import tensor_shape_pb2 as tensorflow_dot_core_dot_framework_dot_tensor__shape__pb2 from tensorflow.core.framework import types_pb2 as tensorflow_dot_core_dot_framework_dot_types__pb2 from tensorflow.core.framework import variable_pb2 as tensorflow_dot_core_dot_framework_dot_variable__pb2 from tensorflow.core.framework import versions_pb2 as tensorflow_dot_core_dot_framework_dot_versions__pb2 from tensorflow.core.protobuf import struct_pb2 as tensorflow_dot_core_dot_protobuf_dot_struct__pb2 from tensorflow.core.protobuf import trackable_object_graph_pb2 as tensorflow_dot_core_dot_protobuf_dot_trackable__object__graph__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='tensorflow/core/protobuf/saved_object_graph.proto', package='tensorflow', syntax='proto3', serialized_options=_b('ZHgithub.com/tensorflow/tensorflow/tensorflow/go/core/core_protos_go_proto\370\001\001'), serialized_pb=_b('\n1tensorflow/core/protobuf/saved_object_graph.proto\x12\ntensorflow\x1a,tensorflow/core/framework/tensor_shape.proto\x1a%tensorflow/core/framework/types.proto\x1a(tensorflow/core/framework/variable.proto\x1a(tensorflow/core/framework/versions.proto\x1a%tensorflow/core/protobuf/struct.proto\x1a\x35tensorflow/core/protobuf/trackable_object_graph.proto\"\xe8\x01\n\x10SavedObjectGraph\x12&\n\x05nodes\x18\x01 \x03(\x0b\x32\x17.tensorflow.SavedObject\x12O\n\x12\x63oncrete_functions\x18\x02 \x03(\x0b\x32\x33.tensorflow.SavedObjectGraph.ConcreteFunctionsEntry\x1a[\n\x16\x43oncreteFunctionsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x30\n\x05value\x18\x02 \x01(\x0b\x32!.tensorflow.SavedConcreteFunction:\x02\x38\x01\"\xd9\x05\n\x0bSavedObject\x12R\n\x08\x63hildren\x18\x01 \x03(\x0b\x32@.tensorflow.TrackableObjectGraph.TrackableObject.ObjectReference\x12^\n\x0eslot_variables\x18\x03 \x03(\x0b\x32\x46.tensorflow.TrackableObjectGraph.TrackableObject.SlotVariableReference\x12\x32\n\x0buser_object\x18\x04 \x01(\x0b\x32\x1b.tensorflow.SavedUserObjectH\x00\x12\'\n\x05\x61sset\x18\x05 \x01(\x0b\x32\x16.tensorflow.SavedAssetH\x00\x12-\n\x08\x66unction\x18\x06 \x01(\x0b\x32\x19.tensorflow.SavedFunctionH\x00\x12-\n\x08variable\x18\x07 \x01(\x0b\x32\x19.tensorflow.SavedVariableH\x00\x12G\n\x16\x62\x61re_concrete_function\x18\x08 \x01(\x0b\x32%.tensorflow.SavedBareConcreteFunctionH\x00\x12-\n\x08\x63onstant\x18\t \x01(\x0b\x32\x19.tensorflow.SavedConstantH\x00\x12-\n\x08resource\x18\n \x01(\x0b\x32\x19.tensorflow.SavedResourceH\x00\x12\x46\n\x10saveable_objects\x18\x0b \x03(\x0b\x32,.tensorflow.SavedObject.SaveableObjectsEntry\x1aR\n\x14SaveableObjectsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12)\n\x05value\x18\x02 \x01(\x0b\x32\x1a.tensorflow.SaveableObject:\x02\x38\x01\x42\x06\n\x04kindJ\x04\x08\x02\x10\x03R\nattributes\"`\n\x0fSavedUserObject\x12\x12\n\nidentifier\x18\x01 \x01(\t\x12\'\n\x07version\x18\x02 \x01(\x0b\x32\x16.tensorflow.VersionDef\x12\x10\n\x08metadata\x18\x03 \x01(\t\"*\n\nSavedAsset\x12\x1c\n\x14\x61sset_file_def_index\x18\x01 \x01(\x05\"\\\n\rSavedFunction\x12\x1a\n\x12\x63oncrete_functions\x18\x01 \x03(\t\x12/\n\rfunction_spec\x18\x02 \x01(\x0b\x32\x18.tensorflow.FunctionSpec\"\xa8\x01\n\x15SavedConcreteFunction\x12\x14\n\x0c\x62ound_inputs\x18\x02 \x03(\x05\x12\x42\n\x1d\x63\x61nonicalized_input_signature\x18\x03 \x01(\x0b\x32\x1b.tensorflow.StructuredValue\x12\x35\n\x10output_signature\x18\x04 \x01(\x0b\x32\x1b.tensorflow.StructuredValue\"|\n\x19SavedBareConcreteFunction\x12\x1e\n\x16\x63oncrete_function_name\x18\x01 \x01(\t\x12\x19\n\x11\x61rgument_keywords\x18\x02 \x03(\t\x12$\n\x1c\x61llowed_positional_arguments\x18\x03 \x01(\x03\"\"\n\rSavedConstant\x12\x11\n\toperation\x18\x01 \x01(\t\"\xf6\x01\n\rSavedVariable\x12#\n\x05\x64type\x18\x01 \x01(\x0e\x32\x14.tensorflow.DataType\x12+\n\x05shape\x18\x02 \x01(\x0b\x32\x1c.tensorflow.TensorShapeProto\x12\x11\n\ttrainable\x18\x03 \x01(\x08\x12<\n\x0fsynchronization\x18\x04 \x01(\x0e\x32#.tensorflow.VariableSynchronization\x12\x34\n\x0b\x61ggregation\x18\x05 \x01(\x0e\x32\x1f.tensorflow.VariableAggregation\x12\x0c\n\x04name\x18\x06 \x01(\t\"\x95\x01\n\x0c\x46unctionSpec\x12\x30\n\x0b\x66ullargspec\x18\x01 \x01(\x0b\x32\x1b.tensorflow.StructuredValue\x12\x11\n\tis_method\x18\x02 \x01(\x08\x12\x34\n\x0finput_signature\x18\x05 \x01(\x0b\x32\x1b.tensorflow.StructuredValueJ\x04\x08\x03\x10\x04J\x04\x08\x04\x10\x05\"\x1f\n\rSavedResource\x12\x0e\n\x06\x64\x65vice\x18\x01 \x01(\t\"A\n\x0eSaveableObject\x12\x15\n\rsave_function\x18\x02 \x01(\x05\x12\x18\n\x10restore_function\x18\x03 \x01(\x05\x42MZHgithub.com/tensorflow/tensorflow/tensorflow/go/core/core_protos_go_proto\xf8\x01\x01\x62\x06proto3') , dependencies=[tensorflow_dot_core_dot_framework_dot_tensor__shape__pb2.DESCRIPTOR,tensorflow_dot_core_dot_framework_dot_types__pb2.DESCRIPTOR,tensorflow_dot_core_dot_framework_dot_variable__pb2.DESCRIPTOR,tensorflow_dot_core_dot_framework_dot_versions__pb2.DESCRIPTOR,tensorflow_dot_core_dot_protobuf_dot_struct__pb2.DESCRIPTOR,tensorflow_dot_core_dot_protobuf_dot_trackable__object__graph__pb2.DESCRIPTOR,]) _SAVEDOBJECTGRAPH_CONCRETEFUNCTIONSENTRY = _descriptor.Descriptor( name='ConcreteFunctionsEntry', full_name='tensorflow.SavedObjectGraph.ConcreteFunctionsEntry', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='key', full_name='tensorflow.SavedObjectGraph.ConcreteFunctionsEntry.key', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='value', full_name='tensorflow.SavedObjectGraph.ConcreteFunctionsEntry.value', index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=_b('8\001'), is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=470, serialized_end=561, ) _SAVEDOBJECTGRAPH = _descriptor.Descriptor( name='SavedObjectGraph', full_name='tensorflow.SavedObjectGraph', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='nodes', full_name='tensorflow.SavedObjectGraph.nodes', index=0, number=1, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='concrete_functions', full_name='tensorflow.SavedObjectGraph.concrete_functions', index=1, number=2, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[_SAVEDOBJECTGRAPH_CONCRETEFUNCTIONSENTRY, ], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=329, serialized_end=561, ) _SAVEDOBJECT_SAVEABLEOBJECTSENTRY = _descriptor.Descriptor( name='SaveableObjectsEntry', full_name='tensorflow.SavedObject.SaveableObjectsEntry', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='key', full_name='tensorflow.SavedObject.SaveableObjectsEntry.key', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='value', full_name='tensorflow.SavedObject.SaveableObjectsEntry.value', index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=_b('8\001'), is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=1185, serialized_end=1267, ) _SAVEDOBJECT = _descriptor.Descriptor( name='SavedObject', full_name='tensorflow.SavedObject', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='children', full_name='tensorflow.SavedObject.children', index=0, number=1, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='slot_variables', full_name='tensorflow.SavedObject.slot_variables', index=1, number=3, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='user_object', full_name='tensorflow.SavedObject.user_object', index=2, number=4, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='asset', full_name='tensorflow.SavedObject.asset', index=3, number=5, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='function', full_name='tensorflow.SavedObject.function', index=4, number=6, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='variable', full_name='tensorflow.SavedObject.variable', index=5, number=7, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='bare_concrete_function', full_name='tensorflow.SavedObject.bare_concrete_function', index=6, number=8, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='constant', full_name='tensorflow.SavedObject.constant', index=7, number=9, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='resource', full_name='tensorflow.SavedObject.resource', index=8, number=10, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='saveable_objects', full_name='tensorflow.SavedObject.saveable_objects', index=9, number=11, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[_SAVEDOBJECT_SAVEABLEOBJECTSENTRY, ], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ _descriptor.OneofDescriptor( name='kind', full_name='tensorflow.SavedObject.kind', index=0, containing_type=None, fields=[]), ], serialized_start=564, serialized_end=1293, ) _SAVEDUSEROBJECT = _descriptor.Descriptor( name='SavedUserObject', full_name='tensorflow.SavedUserObject', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='identifier', full_name='tensorflow.SavedUserObject.identifier', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='version', full_name='tensorflow.SavedUserObject.version', index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='metadata', full_name='tensorflow.SavedUserObject.metadata', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=1295, serialized_end=1391, ) _SAVEDASSET = _descriptor.Descriptor( name='SavedAsset', full_name='tensorflow.SavedAsset', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='asset_file_def_index', full_name='tensorflow.SavedAsset.asset_file_def_index', index=0, number=1, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=1393, serialized_end=1435, ) _SAVEDFUNCTION = _descriptor.Descriptor( name='SavedFunction', full_name='tensorflow.SavedFunction', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='concrete_functions', full_name='tensorflow.SavedFunction.concrete_functions', index=0, number=1, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='function_spec', full_name='tensorflow.SavedFunction.function_spec', index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=1437, serialized_end=1529, ) _SAVEDCONCRETEFUNCTION = _descriptor.Descriptor( name='SavedConcreteFunction', full_name='tensorflow.SavedConcreteFunction', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='bound_inputs', full_name='tensorflow.SavedConcreteFunction.bound_inputs', index=0, number=2, type=5, cpp_type=1, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='canonicalized_input_signature', full_name='tensorflow.SavedConcreteFunction.canonicalized_input_signature', index=1, number=3, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='output_signature', full_name='tensorflow.SavedConcreteFunction.output_signature', index=2, number=4, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=1532, serialized_end=1700, ) _SAVEDBARECONCRETEFUNCTION = _descriptor.Descriptor( name='SavedBareConcreteFunction', full_name='tensorflow.SavedBareConcreteFunction', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='concrete_function_name', full_name='tensorflow.SavedBareConcreteFunction.concrete_function_name', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='argument_keywords', full_name='tensorflow.SavedBareConcreteFunction.argument_keywords', index=1, number=2, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='allowed_positional_arguments', full_name='tensorflow.SavedBareConcreteFunction.allowed_positional_arguments', index=2, number=3, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=1702, serialized_end=1826, ) _SAVEDCONSTANT = _descriptor.Descriptor( name='SavedConstant', full_name='tensorflow.SavedConstant', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='operation', full_name='tensorflow.SavedConstant.operation', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=1828, serialized_end=1862, ) _SAVEDVARIABLE = _descriptor.Descriptor( name='SavedVariable', full_name='tensorflow.SavedVariable', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='dtype', full_name='tensorflow.SavedVariable.dtype', index=0, number=1, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='shape', full_name='tensorflow.SavedVariable.shape', index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='trainable', full_name='tensorflow.SavedVariable.trainable', index=2, number=3, type=8, cpp_type=7, label=1, has_default_value=False, default_value=False, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='synchronization', full_name='tensorflow.SavedVariable.synchronization', index=3, number=4, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='aggregation', full_name='tensorflow.SavedVariable.aggregation', index=4, number=5, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='name', full_name='tensorflow.SavedVariable.name', index=5, number=6, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=1865, serialized_end=2111, ) _FUNCTIONSPEC = _descriptor.Descriptor( name='FunctionSpec', full_name='tensorflow.FunctionSpec', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='fullargspec', full_name='tensorflow.FunctionSpec.fullargspec', index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='is_method', full_name='tensorflow.FunctionSpec.is_method', index=1, number=2, type=8, cpp_type=7, label=1, has_default_value=False, default_value=False, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='input_signature', full_name='tensorflow.FunctionSpec.input_signature', index=2, number=5, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=2114, serialized_end=2263, ) _SAVEDRESOURCE = _descriptor.Descriptor( name='SavedResource', full_name='tensorflow.SavedResource', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='device', full_name='tensorflow.SavedResource.device', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=2265, serialized_end=2296, ) _SAVEABLEOBJECT = _descriptor.Descriptor( name='SaveableObject', full_name='tensorflow.SaveableObject', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='save_function', full_name='tensorflow.SaveableObject.save_function', index=0, number=2, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='restore_function', full_name='tensorflow.SaveableObject.restore_function', index=1, number=3, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=2298, serialized_end=2363, ) _SAVEDOBJECTGRAPH_CONCRETEFUNCTIONSENTRY.fields_by_name['value'].message_type = _SAVEDCONCRETEFUNCTION _SAVEDOBJECTGRAPH_CONCRETEFUNCTIONSENTRY.containing_type = _SAVEDOBJECTGRAPH _SAVEDOBJECTGRAPH.fields_by_name['nodes'].message_type = _SAVEDOBJECT _SAVEDOBJECTGRAPH.fields_by_name['concrete_functions'].message_type = _SAVEDOBJECTGRAPH_CONCRETEFUNCTIONSENTRY _SAVEDOBJECT_SAVEABLEOBJECTSENTRY.fields_by_name['value'].message_type = _SAVEABLEOBJECT _SAVEDOBJECT_SAVEABLEOBJECTSENTRY.containing_type = _SAVEDOBJECT _SAVEDOBJECT.fields_by_name['children'].message_type = tensorflow_dot_core_dot_protobuf_dot_trackable__object__graph__pb2._TRACKABLEOBJECTGRAPH_TRACKABLEOBJECT_OBJECTREFERENCE _SAVEDOBJECT.fields_by_name['slot_variables'].message_type = tensorflow_dot_core_dot_protobuf_dot_trackable__object__graph__pb2._TRACKABLEOBJECTGRAPH_TRACKABLEOBJECT_SLOTVARIABLEREFERENCE _SAVEDOBJECT.fields_by_name['user_object'].message_type = _SAVEDUSEROBJECT _SAVEDOBJECT.fields_by_name['asset'].message_type = _SAVEDASSET _SAVEDOBJECT.fields_by_name['function'].message_type = _SAVEDFUNCTION _SAVEDOBJECT.fields_by_name['variable'].message_type = _SAVEDVARIABLE _SAVEDOBJECT.fields_by_name['bare_concrete_function'].message_type = _SAVEDBARECONCRETEFUNCTION _SAVEDOBJECT.fields_by_name['constant'].message_type = _SAVEDCONSTANT _SAVEDOBJECT.fields_by_name['resource'].message_type = _SAVEDRESOURCE _SAVEDOBJECT.fields_by_name['saveable_objects'].message_type = _SAVEDOBJECT_SAVEABLEOBJECTSENTRY _SAVEDOBJECT.oneofs_by_name['kind'].fields.append( _SAVEDOBJECT.fields_by_name['user_object']) _SAVEDOBJECT.fields_by_name['user_object'].containing_oneof = _SAVEDOBJECT.oneofs_by_name['kind'] _SAVEDOBJECT.oneofs_by_name['kind'].fields.append( _SAVEDOBJECT.fields_by_name['asset']) _SAVEDOBJECT.fields_by_name['asset'].containing_oneof = _SAVEDOBJECT.oneofs_by_name['kind'] _SAVEDOBJECT.oneofs_by_name['kind'].fields.append( _SAVEDOBJECT.fields_by_name['function']) _SAVEDOBJECT.fields_by_name['function'].containing_oneof = _SAVEDOBJECT.oneofs_by_name['kind'] _SAVEDOBJECT.oneofs_by_name['kind'].fields.append( _SAVEDOBJECT.fields_by_name['variable']) _SAVEDOBJECT.fields_by_name['variable'].containing_oneof = _SAVEDOBJECT.oneofs_by_name['kind'] _SAVEDOBJECT.oneofs_by_name['kind'].fields.append( _SAVEDOBJECT.fields_by_name['bare_concrete_function']) _SAVEDOBJECT.fields_by_name['bare_concrete_function'].containing_oneof = _SAVEDOBJECT.oneofs_by_name['kind'] _SAVEDOBJECT.oneofs_by_name['kind'].fields.append( _SAVEDOBJECT.fields_by_name['constant']) _SAVEDOBJECT.fields_by_name['constant'].containing_oneof = _SAVEDOBJECT.oneofs_by_name['kind'] _SAVEDOBJECT.oneofs_by_name['kind'].fields.append( _SAVEDOBJECT.fields_by_name['resource']) _SAVEDOBJECT.fields_by_name['resource'].containing_oneof = _SAVEDOBJECT.oneofs_by_name['kind'] _SAVEDUSEROBJECT.fields_by_name['version'].message_type = tensorflow_dot_core_dot_framework_dot_versions__pb2._VERSIONDEF _SAVEDFUNCTION.fields_by_name['function_spec'].message_type = _FUNCTIONSPEC _SAVEDCONCRETEFUNCTION.fields_by_name['canonicalized_input_signature'].message_type = tensorflow_dot_core_dot_protobuf_dot_struct__pb2._STRUCTUREDVALUE _SAVEDCONCRETEFUNCTION.fields_by_name['output_signature'].message_type = tensorflow_dot_core_dot_protobuf_dot_struct__pb2._STRUCTUREDVALUE _SAVEDVARIABLE.fields_by_name['dtype'].enum_type = tensorflow_dot_core_dot_framework_dot_types__pb2._DATATYPE _SAVEDVARIABLE.fields_by_name['shape'].message_type = tensorflow_dot_core_dot_framework_dot_tensor__shape__pb2._TENSORSHAPEPROTO _SAVEDVARIABLE.fields_by_name['synchronization'].enum_type = tensorflow_dot_core_dot_framework_dot_variable__pb2._VARIABLESYNCHRONIZATION _SAVEDVARIABLE.fields_by_name['aggregation'].enum_type = tensorflow_dot_core_dot_framework_dot_variable__pb2._VARIABLEAGGREGATION _FUNCTIONSPEC.fields_by_name['fullargspec'].message_type = tensorflow_dot_core_dot_protobuf_dot_struct__pb2._STRUCTUREDVALUE _FUNCTIONSPEC.fields_by_name['input_signature'].message_type = tensorflow_dot_core_dot_protobuf_dot_struct__pb2._STRUCTUREDVALUE DESCRIPTOR.message_types_by_name['SavedObjectGraph'] = _SAVEDOBJECTGRAPH DESCRIPTOR.message_types_by_name['SavedObject'] = _SAVEDOBJECT DESCRIPTOR.message_types_by_name['SavedUserObject'] = _SAVEDUSEROBJECT DESCRIPTOR.message_types_by_name['SavedAsset'] = _SAVEDASSET DESCRIPTOR.message_types_by_name['SavedFunction'] = _SAVEDFUNCTION DESCRIPTOR.message_types_by_name['SavedConcreteFunction'] = _SAVEDCONCRETEFUNCTION DESCRIPTOR.message_types_by_name['SavedBareConcreteFunction'] = _SAVEDBARECONCRETEFUNCTION DESCRIPTOR.message_types_by_name['SavedConstant'] = _SAVEDCONSTANT DESCRIPTOR.message_types_by_name['SavedVariable'] = _SAVEDVARIABLE DESCRIPTOR.message_types_by_name['FunctionSpec'] = _FUNCTIONSPEC DESCRIPTOR.message_types_by_name['SavedResource'] = _SAVEDRESOURCE DESCRIPTOR.message_types_by_name['SaveableObject'] = _SAVEABLEOBJECT _sym_db.RegisterFileDescriptor(DESCRIPTOR) SavedObjectGraph = _reflection.GeneratedProtocolMessageType('SavedObjectGraph', (_message.Message,), { 'ConcreteFunctionsEntry' : _reflection.GeneratedProtocolMessageType('ConcreteFunctionsEntry', (_message.Message,), { 'DESCRIPTOR' : _SAVEDOBJECTGRAPH_CONCRETEFUNCTIONSENTRY, '__module__' : 'tensorflow.core.protobuf.saved_object_graph_pb2' # @@protoc_insertion_point(class_scope:tensorflow.SavedObjectGraph.ConcreteFunctionsEntry) }) , 'DESCRIPTOR' : _SAVEDOBJECTGRAPH, '__module__' : 'tensorflow.core.protobuf.saved_object_graph_pb2' # @@protoc_insertion_point(class_scope:tensorflow.SavedObjectGraph) }) _sym_db.RegisterMessage(SavedObjectGraph) _sym_db.RegisterMessage(SavedObjectGraph.ConcreteFunctionsEntry) SavedObject = _reflection.GeneratedProtocolMessageType('SavedObject', (_message.Message,), { 'SaveableObjectsEntry' : _reflection.GeneratedProtocolMessageType('SaveableObjectsEntry', (_message.Message,), { 'DESCRIPTOR' : _SAVEDOBJECT_SAVEABLEOBJECTSENTRY, '__module__' : 'tensorflow.core.protobuf.saved_object_graph_pb2' # @@protoc_insertion_point(class_scope:tensorflow.SavedObject.SaveableObjectsEntry) }) , 'DESCRIPTOR' : _SAVEDOBJECT, '__module__' : 'tensorflow.core.protobuf.saved_object_graph_pb2' # @@protoc_insertion_point(class_scope:tensorflow.SavedObject) }) _sym_db.RegisterMessage(SavedObject) _sym_db.RegisterMessage(SavedObject.SaveableObjectsEntry) SavedUserObject = _reflection.GeneratedProtocolMessageType('SavedUserObject', (_message.Message,), { 'DESCRIPTOR' : _SAVEDUSEROBJECT, '__module__' : 'tensorflow.core.protobuf.saved_object_graph_pb2' # @@protoc_insertion_point(class_scope:tensorflow.SavedUserObject) }) _sym_db.RegisterMessage(SavedUserObject) SavedAsset = _reflection.GeneratedProtocolMessageType('SavedAsset', (_message.Message,), { 'DESCRIPTOR' : _SAVEDASSET, '__module__' : 'tensorflow.core.protobuf.saved_object_graph_pb2' # @@protoc_insertion_point(class_scope:tensorflow.SavedAsset) }) _sym_db.RegisterMessage(SavedAsset) SavedFunction = _reflection.GeneratedProtocolMessageType('SavedFunction', (_message.Message,), { 'DESCRIPTOR' : _SAVEDFUNCTION, '__module__' : 'tensorflow.core.protobuf.saved_object_graph_pb2' # @@protoc_insertion_point(class_scope:tensorflow.SavedFunction) }) _sym_db.RegisterMessage(SavedFunction) SavedConcreteFunction = _reflection.GeneratedProtocolMessageType('SavedConcreteFunction', (_message.Message,), { 'DESCRIPTOR' : _SAVEDCONCRETEFUNCTION, '__module__' : 'tensorflow.core.protobuf.saved_object_graph_pb2' # @@protoc_insertion_point(class_scope:tensorflow.SavedConcreteFunction) }) _sym_db.RegisterMessage(SavedConcreteFunction) SavedBareConcreteFunction = _reflection.GeneratedProtocolMessageType('SavedBareConcreteFunction', (_message.Message,), { 'DESCRIPTOR' : _SAVEDBARECONCRETEFUNCTION, '__module__' : 'tensorflow.core.protobuf.saved_object_graph_pb2' # @@protoc_insertion_point(class_scope:tensorflow.SavedBareConcreteFunction) }) _sym_db.RegisterMessage(SavedBareConcreteFunction) SavedConstant = _reflection.GeneratedProtocolMessageType('SavedConstant', (_message.Message,), { 'DESCRIPTOR' : _SAVEDCONSTANT, '__module__' : 'tensorflow.core.protobuf.saved_object_graph_pb2' # @@protoc_insertion_point(class_scope:tensorflow.SavedConstant) }) _sym_db.RegisterMessage(SavedConstant) SavedVariable = _reflection.GeneratedProtocolMessageType('SavedVariable', (_message.Message,), { 'DESCRIPTOR' : _SAVEDVARIABLE, '__module__' : 'tensorflow.core.protobuf.saved_object_graph_pb2' # @@protoc_insertion_point(class_scope:tensorflow.SavedVariable) }) _sym_db.RegisterMessage(SavedVariable) FunctionSpec = _reflection.GeneratedProtocolMessageType('FunctionSpec', (_message.Message,), { 'DESCRIPTOR' : _FUNCTIONSPEC, '__module__' : 'tensorflow.core.protobuf.saved_object_graph_pb2' # @@protoc_insertion_point(class_scope:tensorflow.FunctionSpec) }) _sym_db.RegisterMessage(FunctionSpec) SavedResource = _reflection.GeneratedProtocolMessageType('SavedResource', (_message.Message,), { 'DESCRIPTOR' : _SAVEDRESOURCE, '__module__' : 'tensorflow.core.protobuf.saved_object_graph_pb2' # @@protoc_insertion_point(class_scope:tensorflow.SavedResource) }) _sym_db.RegisterMessage(SavedResource) SaveableObject = _reflection.GeneratedProtocolMessageType('SaveableObject', (_message.Message,), { 'DESCRIPTOR' : _SAVEABLEOBJECT, '__module__' : 'tensorflow.core.protobuf.saved_object_graph_pb2' # @@protoc_insertion_point(class_scope:tensorflow.SaveableObject) }) _sym_db.RegisterMessage(SaveableObject) DESCRIPTOR._options = None _SAVEDOBJECTGRAPH_CONCRETEFUNCTIONSENTRY._options = None _SAVEDOBJECT_SAVEABLEOBJECTSENTRY._options = None # @@protoc_insertion_point(module_scope)
[ "adrainnga@gmail.com" ]
adrainnga@gmail.com
8df1865493f7d6d659d54f4de4e6c2e98f00eeab
feaef9e12345f9a9b0a839d159d101357a22b3fe
/maxconnect4.py
1e63c90e2b1f2c327622bef3deb9b9e635a08c9e
[]
no_license
akash682/Maxconnect4Game
03975b07743d148255724b3f4325aab322770daa
1047504c6182504a61f3dec93e66e7f44966dd8e
refs/heads/master
2020-04-27T02:55:15.103086
2019-03-09T04:14:37
2019-03-09T04:14:37
174,009,249
0
0
null
null
null
null
UTF-8
Python
false
false
7,751
py
#!/usr/bin/env python # Written by Chris Conly based on C++ # code provided by Dr. Vassilis Athitsos # Written to be Python 2.4 compatible for omega import sys from MaxConnect4Game import * from Minimax import * import sys def oneMoveGame(currentGame, fname, depth): # Is the board full already? if currentGame.pieceCount == 42: print 'BOARD FULL\n\nGame Over!\n' sys.exit(0) # Make a move (Minimax algorithm implemented) aiPlay(currentGame, 'computer-next', depth) fname = fname; try: # open human.txt with write mode currentGame.gameFile = open(fname, 'w') except: sys.exit('Error opening output file, computer.txt') #SavetoFile currentGame.printGameBoardToFile() currentGame.gameFile.close() def interactiveGame(currentGame, init_next, depth): print('Interactive mode selected.') while currentGame.pieceCount !=42: if init_next == 'computer-next' and currentGame.currentTurn == 1 and currentGame.init_turn == 1: # --COMPUTER PROCESS-- aiPlay(currentGame, init_next, depth) if init_next == 'computer-next' and currentGame.currentTurn == 1 and currentGame.init_turn == 2: # --HUMAN INTERFACE- humaninterface(currentGame) elif init_next == 'computer-next' and currentGame.currentTurn == 2 and currentGame.init_turn ==1: # --HUMAN INTERFACE- humaninterface(currentGame) elif init_next == 'computer-next' and currentGame.currentTurn == 2 and currentGame.init_turn == 2: # --COMPUTER PROCESS-- aiPlay(currentGame, init_next, depth) elif init_next == 'human-next' and currentGame.currentTurn == 1 and currentGame.init_turn == 1: # --HUMAN INTERFACE- humaninterface(currentGame) elif init_next == 'human-next' and currentGame.currentTurn == 1 and currentGame.init_turn == 2: # --COMPUTER PROCESS-- aiPlay(currentGame, init_next, depth) elif init_next == 'human-next' and currentGame.currentTurn == 2 and currentGame.init_turn == 1: # --COMPUTER PROCESS-- aiPlay(currentGame, init_next, depth) elif init_next == 'human-next' and currentGame.currentTurn == 2 and currentGame.init_turn == 2: # --HUMAN INTERFACE- humaninterface(currentGame) # -----------------------------------RESULT------------------------------------------------------------ if currentGame.player1Score > currentGame.player2Score: if currentGame.init_turn == 1 and sys.argv[3] == 'computer-next': print('Computer won') else: print('You won') if currentGame.init_turn == 1 and sys.argv[3] == 'human-next': print('You won') else: print('Computer won.') elif currentGame.player1Score < currentGame.player2Score: if currentGame.init_turn == 1 and sys.argv[3] == 'computer-next': print('You won.') else: print('Computer won') if currentGame.init_turn == 1 and sys.argv[3] == 'human-next': print('Computer won') else: print('You won.') else: print('Draw game.') print('Thank you for playing MaxConnect4Game') #----HUMAN INTERFACE----- def humaninterface(currentGame): print('---------------HUMAN TURN------------------') while True: # column input user_move = input('Choose the column number between [1-7].') # column input check if not 1 <= user_move <= 7: print('Invalid number.') continue elif currentGame.gameBoard[0][user_move - 1] != 0: print('This column is already filled up.') continue else: break # Play with requested column currentGame.playPiece(user_move - 1) print 'Game state after move:' # Print GameBoard currentGame.printGameBoard() # Print Score currentGame.countScore() print('Score: Player 1 = %d, Player 2 = %d' % (currentGame.player1Score, currentGame.player2Score)) try: # open human.txt with write mode currentGame.gameFile = open("human.txt", 'w') except: sys.exit('Error opening output file, human.txt') # write currentGameBoard to human.txt currentGame.printGameBoardToFile() #----COMPUTER PROCESS----- #AI section. Creates Minimax object and starts method. def aiPlay(currentGame, init_next, depth): print ('---------------COMPUTER TURN---------------') #Minimax object miniobj = Minimax(currentGame, init_next, depth) #Result of next move(column) using minimax algorithm dec_col = miniobj.final_decision() #Play with result column currentGame.playPiece(dec_col) print('move %d: Player %d, column %d' % (currentGame.pieceCount, currentGame.currentTurn, dec_col + 1)) # Print GameBoard print 'Game state after move:' currentGame.printGameBoard() # Print Score currentGame.countScore() print('Score: Player 1 = %d, Player 2 = %d' % (currentGame.player1Score, currentGame.player2Score)) try: # open computer.txt with write mode currentGame.gameFile = open("computer.txt", 'w') except: sys.exit('Error opening output file, computer.txt') # write currentGameBoard to computer.txt currentGame.printGameBoardToFile() # human.txt computer.txt close currentGame.gameFile.close() def main(argv): # Make sure we have enough command-line arguments if len(argv) != 5: print 'Four command-line arguments are needed:' print('Usage: %s interactive [input_file] [computer-next/human-next] [depth]' % argv[0]) print('or: %s one-move [input_file] [output_file] [depth]' % argv[0]) sys.exit(2) game_mode, inFile = argv[1:3] if not game_mode == 'interactive' and not game_mode == 'one-move': print('%s is an unrecognized game mode' % game_mode) sys.exit(2) currentGame = maxConnect4Game() # Create a game # Try to open the input file try: currentGame.gameFile = open(inFile, 'r') except IOError: sys.exit("\nError opening input file.\nCheck file name.\n") # Read the initial game state from the file and save in a 2D list file_lines = currentGame.gameFile.readlines() currentGame.gameBoard = [[int(char) for char in line[0:7]] for line in file_lines[0:-1]] currentGame.currentTurn = int(file_lines[-1][0]) currentGame.init_turn = currentGame.currentTurn currentGame.gameFile.close() print '\nMaxConnect-4 game\n' print 'Game state before move:' currentGame.printGameBoard() # Update a few game variables based on initial state and print the score currentGame.checkPieceCount() currentGame.countScore() print('Score: Player 1 = %d, Player 2 = %d' % (currentGame.player1Score, currentGame.player2Score)) if game_mode == 'interactive': interactiveGame(currentGame, argv[3], argv[4]) # Be sure to pass whatever else you need from the command line else: # game_mode == 'one-move' # Set up the output file outFile = argv[3] try: currentGame.gameFile = open(outFile, 'w') except: sys.exit('Error opening output file.') oneMoveGame(currentGame,argv[3], argv[4]) # Be sure to pass any other arguments from the command line you might need. if __name__ == '__main__': main(sys.argv)
[ "noreply@github.com" ]
akash682.noreply@github.com
acf702401d77c59421e65ac7578a059df5d45539
4c3397f6e48800ac544e332ce3d408db8ab538e4
/colabsnippets/face_detection/fpn/FPN3StageMD.py
f024014011b3ec6ed3a3b02d18e5f90ff6386bb7
[]
no_license
rebser/colabsnippets
7fcd18ab09de527b374d8e358abc1075912389d9
005145d69179e4265f19ec021d38f4bceda40ed9
refs/heads/master
2023-03-18T09:39:05.966629
2020-03-08T10:53:12
2020-03-08T10:53:12
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,180
py
import tensorflow as tf from .FPN3StageBase import FPN3StageBase from ...ops import conv2d, reduction_block, main_block class FPN3StageMD(FPN3StageBase): def __init__(self, name='fpn3stagemd', with_detection_module=True, use_minimal_anchors=True): super().__init__(name=name, stage_filters=[128, 256, 512], with_detection_module=with_detection_module, use_minimal_anchors=use_minimal_anchors) def init_bottom_up_weights(self, weight_processor): weight_processor.process_conv_weights(3, 32, 'conv_in', filter_size=3) weight_processor.process_reduction_block_weights(32, 64, 'reduction_block_0') weight_processor.process_main_block_weights(64, 'main_block_0_0') weight_processor.process_reduction_block_weights(64, 128, 'reduction_block_1') weight_processor.process_main_block_weights(128, 'main_block_1_0') weight_processor.process_main_block_weights(128, 'main_block_1_1') weight_processor.process_reduction_block_weights(128, 256, 'reduction_block_2') weight_processor.process_main_block_weights(256, 'main_block_2_0') weight_processor.process_main_block_weights(256, 'main_block_2_1') weight_processor.process_reduction_block_weights(256, 512, 'reduction_block_3') weight_processor.process_main_block_weights(512, 'main_block_3_0') weight_processor.process_main_block_weights(512, 'main_block_3_1') weight_processor.process_main_block_weights(512, 'main_block_3_2') def bottom_up(self, x): out = tf.nn.relu(conv2d(x, 'conv_in', [1, 2, 2, 1])) out = reduction_block(out, 'reduction_block_0', is_activate_input=False) out = main_block(out, 'main_block_0_0') out = reduction_block(out, 'reduction_block_1') out = main_block(out, 'main_block_1_0') out1 = out = main_block(out, 'main_block_1_1') out = reduction_block(out, 'reduction_block_2') out = main_block(out, 'main_block_2_0') out2 = out = main_block(out, 'main_block_2_1') out = reduction_block(out, 'reduction_block_3') out = main_block(out, 'main_block_3_0') out = main_block(out, 'main_block_3_1') out3 = out = main_block(out, 'main_block_3_2') return out1, out2, out3
[ "muehler.v@gmail.com" ]
muehler.v@gmail.com
97ff9d00847b0ba529fc65f6788083fc1f43bc49
2a176ede9250c523425aa8a3e068bf7a64254068
/robot.py
5ff1fe79540a43cab9225391a0b30acac2f84474
[]
no_license
prikevs/nupt-zccx
31c99026efbc9645a81de1e50431acb939bf14ea
3c27b5f5093917a13bf654253ff5b8d0c477fdf4
refs/heads/master
2021-01-10T04:38:07.932983
2015-05-07T10:55:31
2015-05-07T10:55:31
34,276,326
2
1
null
null
null
null
UTF-8
Python
false
false
1,009
py
#!/usr/bin/env python2.7 #coding:utf-8 import werobot import re from zccx.handle import Handle robot = werobot.WeRoBot(token="kevince") msg1 = u"欢迎使用南邮晨跑查询微信公众号\n" msg2 = u"Developed by Kevince & Powered by https://github.com/prikevs/nupt-zccx\n" msg3 = u"首先请进行绑定操作:\n输入 绑定+姓名+学号 例如\n绑定 田二狗 B13040216" HELLO_MSG = msg1 + msg2 + msg3 @robot.subscribe def wesubscribe(message): return HELLO_MSG @robot.filter(u"查询") def word_consult(message): h = Handle(message.source) return h.consult() @robot.filter(re.compile(u"绑定(.*)")) def webind(message): h = Handle(message.source) return h.bind(message.content) @robot.voice def voice_consult(message): if message.recognition == u"查询": h = Handle(message.source) return h.consult() return "What are you talking about?" @robot.text def echo(message): return "请直接回复 查询 或者语音回复查询" robot.run()
[ "wildfire_ks@foxmail.com" ]
wildfire_ks@foxmail.com
3ae7787d9641335df5ad2bb0d983fb3866b51cd1
617e6557eb86754dd5a041d4aa4325c31f7a0d1a
/bench/genesys2.py
c853cee0ecd7e6cb4709b9d40ba529f847c44f62
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
chengzhangxinli/litedram
ae9a5faa82a21b5915cadfd80bc0f1530fb9ed5f
af979bbd3149c1bfe617320c22b4e4759de1182d
refs/heads/master
2023-01-20T17:26:38.469499
2020-11-24T18:48:56
2020-11-24T18:48:56
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,551
py
#!/usr/bin/env python3 # # This file is part of LiteDRAM. # # Copyright (c) 2020 Florent Kermarrec <florent@enjoy-digital.fr> # SPDX-License-Identifier: BSD-2-Clause import os import argparse from migen import * from litex.boards.platforms import genesys2 from litex.soc.cores.clock import * from litex.soc.interconnect.csr import * from litex.soc.integration.soc_core import * from litex.soc.integration.soc_sdram import * from litex.soc.integration.builder import * from litedram.phy import s7ddrphy from litedram.modules import MT41J256M16 from liteeth.phy.s7rgmii import LiteEthPHYRGMII # CRG ---------------------------------------------------------------------------------------------- class _CRG(Module, AutoCSR): def __init__(self, platform, sys_clk_freq): self.clock_domains.cd_sys_pll = ClockDomain() self.clock_domains.cd_sys = ClockDomain() self.clock_domains.cd_sys4x = ClockDomain(reset_less=True) self.clock_domains.cd_clk200 = ClockDomain() self.clock_domains.cd_uart = ClockDomain() # # # self.submodules.main_pll = main_pll = S7PLL(speedgrade=-2) self.comb += main_pll.reset.eq(~platform.request("cpu_reset_n")) main_pll.register_clkin(platform.request("clk200"), 200e6) main_pll.create_clkout(self.cd_sys_pll, sys_clk_freq) main_pll.create_clkout(self.cd_clk200, 200e6) main_pll.create_clkout(self.cd_uart, 100e6) main_pll.expose_drp() self.submodules.idelayctrl = S7IDELAYCTRL(self.cd_clk200) self.submodules.pll = pll = S7PLL(speedgrade=-2) self.comb += pll.reset.eq(~main_pll.locked) pll.register_clkin(self.cd_sys_pll.clk, sys_clk_freq) pll.create_clkout(self.cd_sys, sys_clk_freq) pll.create_clkout(self.cd_sys4x, 4*sys_clk_freq) sys_clk_counter = Signal(32) self.sync += sys_clk_counter.eq(sys_clk_counter + 1) self.sys_clk_counter = CSRStatus(32) self.comb += self.sys_clk_counter.status.eq(sys_clk_counter) # Bench SoC ---------------------------------------------------------------------------------------- class BenchSoC(SoCCore): def __init__(self, uart="crossover", sys_clk_freq=int(125e6), with_bist=False): platform = genesys2.Platform() # SoCCore ---------------------------------------------------------------------------------- SoCCore.__init__(self, platform, clk_freq=sys_clk_freq, integrated_rom_size = 0x10000, integrated_rom_mode = "rw", csr_data_width = 32, uart_name = uart) # CRG -------------------------------------------------------------------------------------- self.submodules.crg = _CRG(platform, sys_clk_freq) self.add_csr("crg") # DDR3 SDRAM ------------------------------------------------------------------------------- self.submodules.ddrphy = s7ddrphy.K7DDRPHY(platform.request("ddram"), memtype = "DDR3", nphases = 4, sys_clk_freq = sys_clk_freq) self.add_csr("ddrphy") self.add_sdram("sdram", phy = self.ddrphy, module = MT41J256M16(sys_clk_freq, "1:4"), origin = self.mem_map["main_ram"], with_bist = with_bist, ) # UARTBone --------------------------------------------------------------------------------- if uart != "serial": self.add_uartbone(name="serial", clk_freq=100e6, baudrate=115200, cd="uart") # Etherbone -------------------------------------------------------------------------------- self.submodules.ethphy = LiteEthPHYRGMII( clock_pads = self.platform.request("eth_clocks"), pads = self.platform.request("eth"), with_hw_init_reset = False) self.add_csr("ethphy") self.add_etherbone(phy=self.ethphy) # Analyzer --------------------------------------------------------------------------------- from litescope import LiteScopeAnalyzer analyzer_signals = [self.ddrphy.dfi] self.submodules.analyzer = LiteScopeAnalyzer(analyzer_signals, depth = 512, clock_domain = "sys", csr_csv = "analyzer.csv") self.add_csr("analyzer") # Leds ------------------------------------------------------------------------------------- from litex.soc.cores.led import LedChaser self.submodules.leds = LedChaser( pads = platform.request_all("user_led"), sys_clk_freq = sys_clk_freq) self.add_csr("leds") # Main --------------------------------------------------------------------------------------------- def main(): parser = argparse.ArgumentParser(description="LiteDRAM Bench on Genesys2") parser.add_argument("--uart", default="crossover", help="Selected UART: crossover (default) or serial") parser.add_argument("--build", action="store_true", help="Build bitstream") parser.add_argument("--with-bist", action="store_true", help="Add BIST Generator/Checker") parser.add_argument("--load", action="store_true", help="Load bitstream") parser.add_argument("--load-bios", action="store_true", help="Load BIOS") parser.add_argument("--set-sys-clk", default=None, help="Set sys_clk") parser.add_argument("--test", action="store_true", help="Run Full Bench") args = parser.parse_args() soc = BenchSoC(uart=args.uart, with_bist=args.with_bist) builder = Builder(soc, csr_csv="csr.csv") builder.build(run=args.build) if args.load: prog = soc.platform.create_programmer() prog.load_bitstream(os.path.join(builder.gateware_dir, soc.build_name + ".bit")) if args.load_bios: from common import s7_load_bios s7_load_bios("build/genesys2/software/bios/bios.bin") if args.set_sys_clk is not None: from common import s7_set_sys_clk s7_set_sys_clk(clk_freq=float(args.config), vco_freq=soc.crg.main_pll.compute_config()["vco"]) if args.test: from common import s7_bench_test s7_bench_test( freq_min = 60e6, freq_max = 180e6, freq_step = 1e6, vco_freq = soc.crg.main_pll.compute_config()["vco"], bios_filename = "build/genesys2/software/bios/bios.bin") if __name__ == "__main__": main()
[ "florent@enjoy-digital.fr" ]
florent@enjoy-digital.fr
332a2c3e1c62d34e4e9f75987b816e7d0c89b786
91d1a6968b90d9d461e9a2ece12b465486e3ccc2
/iam_write_f/server-certificate_update.py
f50d6dee040a81fc171979af61dd2f5573540c89
[]
no_license
lxtxl/aws_cli
c31fc994c9a4296d6bac851e680d5adbf7e93481
aaf35df1b7509abf5601d3f09ff1fece482facda
refs/heads/master
2023-02-06T09:00:33.088379
2020-12-27T13:38:45
2020-12-27T13:38:45
318,686,394
0
0
null
null
null
null
UTF-8
Python
false
false
911
py
#!/usr/bin/python # -*- codding: utf-8 -*- import os import sys sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))) from common.execute_command import write_parameter # url : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-instances.html if __name__ == '__main__': """ delete-server-certificate : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-server-certificate.html get-server-certificate : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-server-certificate.html list-server-certificates : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-server-certificates.html upload-server-certificate : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/upload-server-certificate.html """ write_parameter("iam", "update-server-certificate")
[ "hcseo77@gmail.com" ]
hcseo77@gmail.com
57f0b4f3983a5a317feac10e3d5f3eee570a4930
15f321878face2af9317363c5f6de1e5ddd9b749
/solutions_python/Problem_75/122.py
91ba1fe748d8690b47b3ad3c3d70a7a782710c20
[]
no_license
dr-dos-ok/Code_Jam_Webscraper
c06fd59870842664cd79c41eb460a09553e1c80a
26a35bf114a3aa30fc4c677ef069d95f41665cc0
refs/heads/master
2020-04-06T08:17:40.938460
2018-10-14T10:12:47
2018-10-14T10:12:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,423
py
#!/usr/bin/python # coding: utf-8 class OpposedElementsFound(Exception) : pass def main() : T = int(raw_input()) for t in xrange(T) : args = raw_input().split() args.reverse() C = int(args.pop()) allComb = {} for i in xrange(C) : s = args.pop() allComb[(s[0], s[1])] = s[2] allComb[(s[1], s[0])] = s[2] allOpposed = set() D = int(args.pop()) for i in xrange(D) : s = args.pop() allOpposed.add( (s[0], s[1]) ) allOpposed.add( (s[1], s[0]) ) N = int(args.pop()) S = args.pop() stack = [] for i in S : stack.append(i) while len(stack) >= 2 : p = (stack[-1], stack[-2]) if p in allComb : stack.pop() stack.pop() stack.append(allComb[p]) else : break try : for j in xrange(len(stack)) : for k in xrange(j, len(stack)) : p = (stack[j], stack[k]) if p in allOpposed : raise OpposedElementsFound() except OpposedElementsFound : stack[:] = [] print 'Case #%d: [%s]' % ((t + 1), ', '.join(stack)) if __name__ == '__main__' : main()
[ "miliar1732@gmail.com" ]
miliar1732@gmail.com
74e89a7099e0add391dcc3d2df835de9ff0604c4
82820a53954d9e8f7270ed8c25a6754fa3d407dc
/scripts/ciciol
31c9ae320be4ac8c002b85f4cdf17d2f4b62924b
[]
no_license
volpino/Ciciol
6c3010d9153be078aca08a669162db9b0152feda
2693d8a6ec3d59fbeabb25c2bc947db0fa00f4c0
refs/heads/develop
2020-04-17T10:32:02.567007
2012-03-26T08:32:44
2012-03-26T08:32:44
3,662,082
0
0
null
2023-08-29T21:29:21
2012-03-08T16:57:14
Python
UTF-8
Python
false
false
1,431
#!/usr/bin/env python import sys import logging from ciciol import Ciciol from ciciol.utils import setup if __name__ == '__main__': import optparse p = optparse.OptionParser( usage="usage: %prog [options]") p.add_option('-v', '--verbose', action="store_true", dest="verbose", default=False, help="Verbose logging") p.add_option('-c', "--config", action="store", dest="config", help="Config filename") p.add_option('-s', "--setup", action="store", dest="setup", help="Lauch setup for given feature") opts, _ = p.parse_args() if opts.setup: try: setup_func = getattr(setup, opts.setup) except AttributeError: p.error("Invalid setup feature") setup_func() sys.exit(0) if opts.verbose: logging.basicConfig(stream=sys.stderr, level=logging.DEBUG, format='%(name)s %(threadName)s %(asctime)s ' '%(levelname)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S') else: logging.basicConfig(stream=sys.stderr, level=logging.WARNING) if opts.verbose: logging.basicConfig(level=logging.DEBUG) c = Ciciol(config_fn=opts.config) try: c.run() except (KeyboardInterrupt, SystemExit): sys.exit()
[ "fox91@anche.no" ]
fox91@anche.no
55bddf73973779c6fa266e24ff8debbf72df4e49
4edb790e2cb11bf9ec63dd470773244bcf2f8213
/example_build_better_cli/setup.py
a7ad40a09d944844f46aafeea96bf331d494e31b
[]
no_license
xNok/pystatemachine
7002d169c46b4fd1780cc66e35fbecb164b9f4dd
e702fd1509d31a9946ec3b6ac1579f988c0bcb36
refs/heads/master
2021-09-06T22:09:30.239282
2021-08-19T14:33:33
2021-08-19T14:33:33
234,469,523
1
0
null
null
null
null
UTF-8
Python
false
false
404
py
#!/usr/bin/env python from setuptools import setup, find_packages setup(name='python_better_cli', version='1.0.0', description='5 tricks to improve command lines', author='xNok', author_email='xNok@gmail.com', packages=find_packages(exclude=['docs', 'tests*']), entry_points = { 'console_scripts': [ 'foobar=5_setup:main' ], } )
[ "nokwebspace@gmail.com" ]
nokwebspace@gmail.com
0e2c5c7abff42f5e18fe5c1a358e959befda0801
76ad9ddeed036602bbb4acc8c2bf06e05635cdaa
/hyspider/spiders/movie/db.py
9cf291aae2b011d912a494240dbec37ce89717c9
[]
no_license
improvejin/hyspider
0db8105900103d7fbc1faf80f80c12fd3bfa58c2
df394e2a48399bda25940f1e027a51d2ac85a516
refs/heads/master
2022-12-08T11:00:27.244654
2019-01-07T07:43:39
2019-01-07T07:43:39
164,394,618
1
2
null
2022-12-08T02:28:41
2019-01-07T07:30:48
Python
UTF-8
Python
false
false
2,111
py
import json import requests import scrapy from hyspider.items.movie import MovieDB from hyspider.utils.log import logger class MovieDBSpider(scrapy.Spider): name = 'movie_db' allowed_domains = ['douban.com'] in_theaters = 'https://api.douban.com/v2/movie/in_theaters?count=100' coming_soon = 'https://api.douban.com/v2/movie/coming_soon?count=200' city = '上海' channel = 'db' # db会对scray agent返回403 custom_settings = { 'DOWNLOADER_MIDDLEWARES': { 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware': None, 'hyspider.middlewares.useragent.chrome.ChromeMiddleware': 543, } } def start_requests(self): yield scrapy.Request(self.in_theaters, meta={'ongoing': 1}, callback=self.parse) yield scrapy.Request(self.coming_soon, meta={'ongoing': 0}, callback=self.parse) def parse(self, response): ongoing = response.meta['ongoing'] body = json.loads(response.body_as_unicode()) for movie in body['subjects']: m = MovieDB() m['id'] = movie['id'] m['name'] = movie['title'] m['type'] = '|'.join(movie['genres']) m['score'] = movie['rating']['average'] m['poster'] = movie['images']['large'] m['actors'] = ','.join([cast['name'] for cast in movie['casts']]) m['release_date'] = movie['year'] m['ongoing'] = ongoing duration = self.parse_duration(movie['id']) if duration is not None: m['duration'] = duration yield m def parse_duration(self, movie_id): try: r = requests.get('https://movie.douban.com/subject/{}/'.format(movie_id)) from bs4 import BeautifulSoup bs = BeautifulSoup(r.text) node = bs.find(property="v:runtime") if node is not None: return node.get_text() except Exception as e: logger.exception('Error') return None # if __name__ == '__main__': # parse_duration(26752088)
[ "jiating.jin@vipshop.com" ]
jiating.jin@vipshop.com
eb98d2bf4ffc16181844c9d20d36bff925b598af
7bededcada9271d92f34da6dae7088f3faf61c02
/pypureclient/flashblade/FB_2_7/models/snmp_manager.py
1c867f4105b7eced0f86aadd70c826f00a847ed4
[ "BSD-2-Clause" ]
permissive
PureStorage-OpenConnect/py-pure-client
a5348c6a153f8c809d6e3cf734d95d6946c5f659
7e3c3ec1d639fb004627e94d3d63a6fdc141ae1e
refs/heads/master
2023-09-04T10:59:03.009972
2023-08-25T07:40:41
2023-08-25T07:40:41
160,391,444
18
29
BSD-2-Clause
2023-09-08T09:08:30
2018-12-04T17:02:51
Python
UTF-8
Python
false
false
4,572
py
# coding: utf-8 """ FlashBlade REST API A lightweight client for FlashBlade REST API 2.7, developed by Pure Storage, Inc. (http://www.purestorage.com/). OpenAPI spec version: 2.7 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re import six import typing from ....properties import Property if typing.TYPE_CHECKING: from pypureclient.flashblade.FB_2_7 import models class SnmpManager(object): """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'name': 'str', 'id': 'str', 'host': 'str', 'notification': 'str', 'version': 'str', 'v2c': 'SnmpV2c', 'v3': 'SnmpV3' } attribute_map = { 'name': 'name', 'id': 'id', 'host': 'host', 'notification': 'notification', 'version': 'version', 'v2c': 'v2c', 'v3': 'v3' } required_args = { } def __init__( self, name=None, # type: str id=None, # type: str host=None, # type: str notification=None, # type: str version=None, # type: str v2c=None, # type: models.SnmpV2c v3=None, # type: models.SnmpV3 ): """ Keyword args: name (str): A name chosen by the user. Can be changed. Must be locally unique. id (str): A non-modifiable, globally unique ID chosen by the system. host (str): DNS hostname or IP address of a computer that hosts an SNMP manager to which Purity is to send trap messages when it generates alerts. notification (str): The type of notification the agent will send. Valid values are `inform` and `trap`. version (str): Version of the SNMP protocol to be used by Purity in communications with the specified manager. Valid values are `v2c` and `v3`. v2c (SnmpV2c) v3 (SnmpV3) """ if name is not None: self.name = name if id is not None: self.id = id if host is not None: self.host = host if notification is not None: self.notification = notification if version is not None: self.version = version if v2c is not None: self.v2c = v2c if v3 is not None: self.v3 = v3 def __setattr__(self, key, value): if key not in self.attribute_map: raise KeyError("Invalid key `{}` for `SnmpManager`".format(key)) self.__dict__[key] = value def __getattribute__(self, item): value = object.__getattribute__(self, item) if isinstance(value, Property): return None else: return value def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): if hasattr(self, attr): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(SnmpManager, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, SnmpManager): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
[ "tlewis@purestorage.com" ]
tlewis@purestorage.com
af8ae257b3d500b84f630ff8f93ffed08e118e8a
76d665df937da46d3fab9a6e363a2f6931feff4a
/TravelGear/urls.py
bf3f34924206dfafc9cb05843e778a752685a62b
[]
no_license
17201078/Project-CSE-310-17201078
23e325ddb8c62ce728ef35b84163a5badd0e76f4
2e444c7070a903ac4424aee0df4bc3abb9b2c7f8
refs/heads/master
2023-05-04T04:54:04.234060
2021-05-25T07:46:31
2021-05-25T07:46:31
370,586,058
0
0
null
null
null
null
UTF-8
Python
false
false
232
py
from django.urls import path, include from django.contrib import admin from django.conf.urls.static import static from .import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include('store.urls')), ]
[ "76899576+17201078@users.noreply.github.com" ]
76899576+17201078@users.noreply.github.com
12cf351f21aa609e58f988aa0bf3d97763273cad
c50becdbb9bf2e2793a55d775d6554a01969c4f0
/bucle_while2_python.py
9e38cdab390718fc9acf854423c122d4412bfcca
[]
no_license
Victormaximus/ejercicios_programacion
df7a536921f75be9cd6e73ee9c087b68e3061f5f
e2ea7e15e26309a4dec93e326833592c85b5ec41
refs/heads/master
2020-04-29T13:20:52.926339
2019-03-18T00:16:16
2019-03-18T00:16:16
176,166,997
0
0
null
null
null
null
UTF-8
Python
false
false
262
py
VariableContador = 0 while VariableContador <= 10: VariableNumerica = int(input("inserte la variable: ")) if VariableNumerica >= 50: VariableContador = VariableContador + 1 if VariableNumerica % 2 != 0: print(VariableNumerica)
[ "victormanuelchami@hotmail.com" ]
victormanuelchami@hotmail.com
505bdbc5051899409c5705d3b571bf3e7d806e50
81fab92212f48d0719a44770ec6b57336c5e0b59
/novela/_utils/metaclass.py
8a200c262cba61b8d2755524171f9d2d17f6e4ab
[]
no_license
Zessay/novel_analysis
954bd4b624a994ed0d48959c307cbe4a1f710f1f
a07087a77d6e0c7eeb0a7b4da23baac9bbbfb3d6
refs/heads/master
2023-03-13T06:56:31.062182
2021-03-05T04:36:33
2021-03-05T04:36:33
332,147,656
2
0
null
null
null
null
UTF-8
Python
false
false
2,732
py
# coding=utf-8 # @Author: 莫冉 # @Date: 2021-01-22 import inspect import enum from typing import Iterable, Any class LabelEnumMeta(enum.EnumMeta): """用于单层枚举类的元类""" def __new__(mcs, name, bases, attrs): obj = super().__new__(mcs, name, bases, attrs) obj._value2member_map_ = {} # value表示这个值对应的索引 # display_name表示这个枚举类对应的中文名 # description对应该枚举类的描述 # children对应存在二级类别的枚举类 for m in obj: if isinstance(m.value, (tuple, list)): if len(m.value) == 2: value, display_name = m.value m._value_ = value m.display_name = display_name m.children = None elif len(m.value) == 3: value, display_name, description = m.value m._value_ = value m.display_name = display_name m.description = description m.children = None elif len(m.value) == 4: value, display_name, description, children = m.value m._value_ = value m.display_name = display_name m.description = description m.children = children else: value = m.value else: value = m.value obj._value2member_map_[value] = m return obj class LoadEnumInterface(enum.Enum): """用于动态加载枚举类""" @classmethod def get_all_subclasses(cls) -> Iterable[Any]: """ Return a generator of all subclasses """ for subclass in cls.__subclasses__(): yield from subclass.get_all_subclasses() yield subclass @classmethod def load_class(cls, class_name) -> Any: """ Return a subclass of ``class_name``, case insensitively :param cls_name (str): target class name :return: """ result = None for subclass in cls.get_all_subclasses(): # print(subclass.__name__.lower()) if subclass.__name__.lower() == class_name.lower(): if result is None: result = subclass else: raise RuntimeError('There are two classes with the name "{}" located at "{}" and "{}". ' 'You have to remove one of them to make "load_class" work normally.'.format( class_name, inspect.getfile(result), inspect.getfile(subclass))) return result
[ "zhushuai0403@163.com" ]
zhushuai0403@163.com
6e66e6b7f8c7581380e43ea9c3a4c406187486fc
afdfcad1fddbe347c508a4ee1370bc1798fde00e
/day5.py
f657389c7714ebe61cdca578c151652ea27dedc5
[]
no_license
muszkin/advent-of-code-2020
67213884bde2740cfed2b0e9595cf9e57a3761aa
9e0988d2a6909ba740a24530d4d1cd2bb8786be3
refs/heads/main
2023-01-30T18:46:18.222106
2020-12-13T11:36:03
2020-12-13T11:36:03
316,169,343
0
0
null
null
null
null
UTF-8
Python
false
false
693
py
def get(seat_row: str, ran: list): for index, sr in enumerate(seat_row): if index == len(seat_row) - 1: if sr == "F" or sr == "L": return ran[0] else: return ran[1] if sr == "F" or sr == "L": ran = ran[0:int(len(ran)/2)] else: ran = ran[int(len(ran)/2):] file = open("day5-input.txt", "r") seats = map(str, file.read().split("\n")) ids = [] for seat in seats: row = get(seat[0:7], list(range(0, 128))) column = get(seat[7:], list(range(0, 8))) ids.append(row * 8 + column) print(max(ids)) for i in ids: if i + 2 in ids and i + 1 not in ids: print(i + 1)
[ "muszkin@gmail.com" ]
muszkin@gmail.com
ec24dedcdd0573e9451d4dea70c5855bbdc88e40
9ea87c10180665db0db6fa36997704acc001692d
/guides/rpi/mqpy.py
03d24816e17afe46ede57671d9fc9ac55ed158e1
[ "MIT" ]
permissive
ToraNova/library
8af942f4657ebc07043848616e5b75cdace67212
20b321302868e8c2ce8723c808aa9e7a313e2cb8
refs/heads/master
2021-07-13T07:57:40.631816
2020-07-02T18:41:08
2020-07-02T18:41:08
159,255,786
0
0
MIT
2019-05-17T05:43:34
2018-11-27T01:16:08
Python
UTF-8
Python
false
false
3,535
py
#!/usr/bin/python3 # Simple python-gpio for raspberry pi GPIO detection # uses callback events import time, datetime, sys import RPi.GPIO as gpio import paho.mqtt.client as mqtt from gpiomq import GPIOMQTT from utilog import srvlog as log import configparser #for config parsing #defining callback behavior def on_connect(client, userdata, flags, rc): client.connected_flag=True verbose_log("Connected to broker with rc:{}".format(rc),'i','sys') def on_disconnect(client,userdata,rc): client.connected_flag=False verbose_log("Disconnected from broker with rc:"+str(rc),'e','sys') def pkgprint(str): print("{}[MAIN] ".format(datetime.datetime.now()),str) def verbose_log(str,logtype,logname): if(logtype == 'i'): log[logname].info(str) elif(logtype == 'e'): log[logname].error(str) elif(logtype == 'w'): log[logname].warning(str) else: verboseprint("Logtype error") verboseprint(str) if __name__ == "__main__": # CONFIG PARSING #################################################### config = configparser.RawConfigParser() config.read("host.conf") hostaddr = config.get('conn','hostaddr') hostport = int(config.get('conn','port')) selfid = config.get('conn','clientid') b1pin = int(config.get('detc','b1_pin')) b2pin = int(config.get('detc','b2_pin')) en1 = True if config.get('detc','en_1') == "1" else False en2 = True if config.get('detc','en_2') == "1" else False verbose = True if config.get('detc','verbose') == "1" else False alcd_timer = int(config.get('detc','alcd')) #radar cooldown timer ##################################################################### verboseprint = pkgprint if verbose else lambda *a, **k: None pinlist = [b1pin,b2pin] #creates the mqtt client and attaches the callbacks client = mqtt.Client() client.on_connect = on_connect client.on_disconnect = on_disconnect client.zid = selfid client.en1 = en1 client.en2 = en2 client.connected_flag = False # MQTT SETUP ######################################################## verbose_log("System init, waiting for primary server...",'i','sys') verbose_log("Attempting to connect to host {} on port {}".format(hostaddr,hostport),'i','sys') while True: # keep trying until end of time try: client.connect(hostaddr,hostport,30) #CONNECT TO MQTT BROKER break except Exception as e: verbose_log("MQTT broker conn err: "+str(e),'e','sys') time.sleep(3) client.publish('zfence/wire',"{},{}".format(selfid,0)) verbose_log("Starting loop...",'i','sys') ctime = datetime.datetime.now() rtime = datetime.datetime.now() try: m = GPIOMQTT(gpio, pinlist, client, verbose) while True: try: client.loop() cdelt = datetime.datetime.now() - ctime rdelt = datetime.datetime.now() - rtime cdiff = divmod(cdelt.days * 86400 + cdelt.seconds, 60) rdiff = divmod(rdelt.days * 86400 + rdelt.seconds, 60) if(cdiff[1] > 30): #timer expired ctime = datetime.datetime.now() #reset timer client.publish('zfence/wire','{},{}'.format(selfid,0)) if(rdiff[1] > 3 and not client.connected_flag): rtime = datetime.datetime.now() try: client.reconnect() except Exception as e: verbose_log("MQTT broker reconn err: "+str(e),'e','sys') except KeyboardInterrupt: verbose_log("Quitting loop...",'w','sys') raise KeyboardInterrupt #elevate it to the outer try catch block except KeyboardInterrupt: print("Loop terminated") except Exception as e: #catch all print("Error has occurred :",str(e)) finally: gpio.cleanup()
[ "chia_jason96@live.com" ]
chia_jason96@live.com
40e70b4a488818d46d8b3bda7dd401256a057ef0
c0f285754eb9e2be6db11ae9a00a18a5630cad66
/picture_manage/picture/urls.py
01f476f17139f508ebf5c5b8157927f64235921d
[]
no_license
qjx666/document-manage
27ae56ece5303531e85297525792101b88c7c81d
2d3cb37304d65020d9c147afbff95892dbb1e5c7
refs/heads/master
2022-01-30T19:30:56.314775
2019-05-29T13:21:30
2019-05-29T13:21:30
null
0
0
null
null
null
null
UTF-8
Python
false
false
663
py
# -*- coding:utf-8 -*- # 为应用程序users定义URL模式 from django.urls import path,include,re_path from . import views urlpatterns = [ # 主页面 re_path(r'submit$', views.submit, name='submit'), re_path(r'modify$', views.modify, name='modify'), re_path(r'add$',views.add,name="add"), re_path(r'multiply-(\d+)-(\d+)$',views.multiply,name="multiply"), re_path(r'search.html$',views.search,name="search"), re_path(r'picture', views.picture, name='picture'), re_path(r'delete_(\d+)$', views.delete, name='delete'), path('download/<int:a>', views.download, name='download'), re_path(r'test$', views.test_image, name='test'), ]
[ "2380383965@qq.com" ]
2380383965@qq.com
7a8e34489199616f0421ed4a450e58123ba9d7ad
29981fa8b38f785dfe917fafbf1a07956eb021e9
/python/lsst/sims/operations/SeqHistory.py
e98be1e794e8160471fa47c16930bfbe35a6d10e
[]
no_license
humnaawan/sims_operations
f9f33b6a5113c05fbafc91ac6865389cb83af446
ab2bf2e872ce788772cb5e980542ef342110ac52
refs/heads/master
2020-07-27T22:42:31.032318
2017-01-20T05:17:32
2017-01-20T05:17:32
73,422,733
0
1
null
2017-01-20T05:12:51
2016-11-10T21:35:15
Python
UTF-8
Python
false
false
4,196
py
#!/usr/bin/env python """ SeqHistory Inherits from: LSSTObject : object Class Description The SeqHistory class is an interface to the SeqHistory database. It provides methods to ingest data into the database and to retrieve data from it. Method Types Constructor/Initializers - __init__ DB Access - addObservation - getObservation - cleanupProposal """ from utilities import * from LSSTObject import * from Observation import * class SeqHistory (LSSTObject): def __init__ (self, lsstDB, dbTableDict=None, log=False, logfile='./SeqHistory.log', verbose=0): """ Standard initializer. lsstDB LSST DB access object dbTableDict: log: False if not set; else log = logging.getLogger("....") logfile: name (and path) of the desired log file (defaults to ./SeqHistory.log) verbose: integer specifying the verbosity level (defaults to 0). -1=none, 0=min, 1=wordy, >1=very verbose """ self.lsstDB = lsstDB self.dbTableDict = dbTableDict # Setup logging if (verbose < 0): logfile = "/dev/null" elif ( not log ): print "Setting up SeqHistory logger" log = logging.getLogger("Simulator") hdlr = logging.FileHandler(logfile) formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s") hdlr.setFormatter(formatter) log.addHandler(hdlr) log.setLevel(logging.INFO) self.log = log self.logfile = logfile self.verbose = verbose if ( self.log and self.verbose > 1): self.log.info('SeqHistory: init()') #for key in self.dbTableDict: # print "SeqHistory: Database tables: " + key,self.dbTableDict[key] return # DB Access methods def addSequence (self, seq, fieldID, sessionID,obsdate,status): """ Ingest the given Observation instance into the database. Input seq Sequence instance. sessionID: An integer identifying this particular run. obsdate: date of final event status: reason for sequence completion Return None Raise Exception in case of error in the ingestion procedure. """ if ( self.log and self.verbose > 1): self.log.info('SeqHistory: addObservation(): dbTableKey:%s' % (self.dbTableDict['seqHistory'])) numRequestedEvents = seq.GetNumTargetEvents() numActualEvents = seq.GetNumActualEvents() tmpSeqHistoryDB = self.dbTableDict['seqHistory'] sql = "INSERT INTO %s VALUES (NULL, %d, %d, %d, %d, %d, %d, %f, %d, %d, '%d')" \ % ( self.dbTableDict['seqHistory'],\ sessionID,\ seq.date,\ obsdate,\ seq.propID,\ fieldID,\ seq.seqNum, seq.GetProgress(), numRequestedEvents, numActualEvents, status) # (n, dummy) = self.lsstDB.executeSQL (sql) return def cleanupProposal (self, propID, sessionID): """ Cleans up the SeqHistory database by removing all the entries relative to a given proposal ID. Input propID: An integer identifying a particular proposal. sessionID: An integer identifying this particular run. Return None Raise Exception in case of error in the ingestion procedure. """ if ( self.log and self.verbose > 1): self.log.info('SeqHistory: cleanupProposal()') # sql = 'DELETE FROM %s WHERE ' % (self.dbTableDict['seqHistory']) # sql += 'propID=%d AND ' % (propID) # sql += ' sessionID=%d' % (sessionID) # # (n, res) = self.lsstDB.executeSQL (sql) return # TESTS if (__name__ == '__main__'): pass
[ "" ]
5e2fff9451f4a7d4a40d060837845604ee8577a8
489b53afe55712946d15bd4371acad4f9f7d674e
/sandbox.py
f45d3f9d77a6913f779a255f1b17ce0eb056edad
[]
no_license
jardmclan/rfstation
c3ed69d2874f86485f1371d26e8d650f34f01a76
d146660e2b242280eaf6d60f8825495acfaaeea2
refs/heads/master
2023-03-21T08:30:56.218209
2021-03-12T03:29:16
2021-03-12T03:29:16
297,444,277
0
0
null
null
null
null
UTF-8
Python
false
false
279
py
import re out = b"Successfully submitted metadata object 9183465129133019626-242ac1111-0001-012".decode("utf-8") match = re.fullmatch(r"Successfully submitted metadata object (.+)", out) if match is not None: uuid = match.group(1) print(uuid) else: print("failed")
[ "mcleanj@hawaii.edu" ]
mcleanj@hawaii.edu
1eab197bbfb9a7676ad53bc230af3523d720b2f0
8c1ad79b554cace2bc45e4484fda6914f83ed326
/NewCompanyFrame.py
083b96d8cd84ce6c241ba458e85ed835236091f4
[]
no_license
CoryGeeAndDaBoiz/PythonProject
59b0e97be486ec7066abc4ab241edbc8fd22e956
83ed7cd18bad5f6f239a284ea9177cd77ca3b7e1
refs/heads/master
2016-09-06T18:09:44.681710
2014-03-27T17:47:52
2014-03-27T17:47:52
null
0
0
null
null
null
null
UTF-8
Python
false
false
479
py
import wx # Search for a new company by the stock symbol class newCompanyFrame(wx.Frame): def __init__(self,parent,id): wx.Frame.__init__(self,parent,id,'Company Search',size=(1000,550)) new_comp_panel = wx.Panel(self) wx.StaticText(new_comp_panel, -1, "Sym:", (8,13), (200,-1)) compName = wx.TextCtrl(new_comp_panel, pos=(45,10), size=(180,-1)) btn_Search = wx.Button(new_comp_panel, label="Search", pos=(227,9), size=(90,25))
[ "corygeeanddaboiz@gmail.com" ]
corygeeanddaboiz@gmail.com
6e510f560fa25f97fd56be7e45333f0a2683b37e
0c7b5f78f40ac95bb5adeafb1c199e99415c8705
/venv/Scripts/pip3-script.py
0bd503c2eb93bfd9f3793c5abb46e702f6142842
[]
no_license
BenoitGoethals/XmlSite
5b00c98f460c8eca4550482255578af2036844b5
8328b265c264d91646ad9e710311c868c08c72db
refs/heads/master
2022-04-08T05:57:35.887059
2020-02-10T06:56:16
2020-02-10T06:56:16
236,384,964
0
0
null
null
null
null
UTF-8
Python
false
false
414
py
#!C:\Users\benoit\PycharmProjects\XmlSite\venv\Scripts\python.exe # EASY-INSTALL-ENTRY-SCRIPT: 'pip==19.0.3','console_scripts','pip3' __requires__ = 'pip==19.0.3' 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('pip==19.0.3', 'console_scripts', 'pip3')() )
[ "benoitgoethals@outlook.com" ]
benoitgoethals@outlook.com
79d80c06892bcc0d65c9be037af02ee0c877cfec
b938a6e3dcf74e03c1f96e96e91a2bab0a0c2de5
/backend/excercise.py
25136c13deb0d10c3c92af1fe3816a8a7ea045b7
[]
no_license
Bellinazzi31/mvp
f77f3bd2011ad42aa00a3992150da270980c5d75
814513bdc8311087380e4867336b1bd84a3ee1a6
refs/heads/master
2023-04-01T14:15:18.047210
2021-03-30T21:51:48
2021-03-30T21:51:48
353,132,263
0
0
null
null
null
null
UTF-8
Python
false
false
6,098
py
import mariadb from flask import request, Response import dbcreds import json import secrets def get(): program_id = request.args.get("programId") conn = None cursor = None excercises = None try: conn = mariadb.connect(user = dbcreds.username , port = dbcreds.port , host = dbcreds.host , password = dbcreds.password,database = dbcreds.database) cursor = conn.cursor() cursor.execute("SELECT * FROM excercise where program_id = ?",[program_id]) excercises = cursor.fetchall() except Exception as ex: print(ex) finally: if(conn != None): conn.close() if (cursor != None): cursor.close if(excercises !=None): excercisesList = [] for excercise in excercises: excer = { "excerciseId" : excercise[0], "programId":excercise[4], "title":excercise[1], "description":excercise[2], "period": excercise[3] } excercisesList.append(excer) return Response(json.dumps(excercisesList,default=str),mimetype="application/json",status=200) else: return Response("Bad request",mimetype="html/text",status=400) def post(): program_id = request.json.get("programId") description = request.json.get("description") period = request.json.get("period") title = request.json.get("title") login_token = request.json.get("loginToken") conn = None cursor = None excercise_id =None try: conn = mariadb.connect(user=dbcreds.username , port = dbcreds.port , host = dbcreds.host , password = dbcreds.password,database = dbcreds.database) cursor = conn.cursor() cursor.execute("SELECT * FROM user INNER JOIN user_session on user.id = user_session.user_id WHERE user.user_role = ? AND user_session.login_token=?",["Coach",login_token]) coach = cursor.fetchall() if len(coach) == 1 : cursor.execute("INSERT INTO excercise (title,description,program_id,period) VALUES (?,?,?,?)",[title,description,program_id,period]) conn.commit() excercise_id = cursor.lastrowid except Exception as ex: print(ex) finally: if(conn != None): conn.close() if (cursor != None): cursor.close if excercise_id !=None : excercise = { "excerciseId" : excercise_id, "programId" : program_id, "title" : title, "description":description, "period": period } return Response(json.dumps(excercise,default=str),mimetype="application/json",status=201) else: return Response("Bad request",mimetype="html/text",status=400) def patch(): excercise_id = request.json.get("excerciseId") description = request.json.get("description") period = request.json.get("period") title = request.json.get("title") login_token = request.json.get("loginToken") conn = None cursor = None excercise = None affected_rows = None try: conn = mariadb.connect(user=dbcreds.username , port = dbcreds.port , host = dbcreds.host , password = dbcreds.password,database = dbcreds.database) cursor = conn.cursor() cursor.execute("SELECT * FROM user INNER JOIN user_session on user.id = user_session.user_id WHERE user.user_role = ? AND user_session.login_token=?",["Coach",login_token]) coach = cursor.fetchall() if len(coach) == 1 : if description !=None and description !="" : cursor.execute("UPDATE excercise SET description = ? where id =?",[description,excercise_id]) if period !=None and period !="" : cursor.execute("UPDATE excercise SET period = ? where id =?",[period,excercise_id]) if title !=None and title !="" : cursor.execute("UPDATE excercise SET title = ? where id =?",[title,excercise_id]) conn.commit() affected_rows = cursor.rowcount cursor.execute("SELECT * FROM excercise where id = ? ",[excercise_id]) excercise = cursor.fetchall()[0] except Exception as ex: print(ex) finally: if(conn != None): conn.close() if (cursor != None): cursor.close if affected_rows ==1 : excercise_details = { "excerciseId" : excercise[0], "programId":excercise[4], "title":excercise[1], "description":excercise[2], "period": excercise[3] } return Response(json.dumps(excercise_details,default=str),mimetype="application/json",status=201) else: return Response("Bad request",mimetype="html/text",status=400) def delete(): excercise_id = request.json.get("excerciseId") login_token = request.json.get("loginToken") conn = None cursor = None affected_rows = None try: conn = mariadb.connect(user=dbcreds.username , port = dbcreds.port , host = dbcreds.host , password = dbcreds.password,database = dbcreds.database) cursor = conn.cursor() cursor.execute("SELECT * FROM user INNER JOIN user_session on user.id = user_session.user_id WHERE user.user_role = ? AND user_session.login_token=?",["Coach",login_token]) coach = cursor.fetchall() if len(coach) == 1 : cursor.execute("DELETE FROM excercise where id = ?",[excercise_id]) conn.commit() affected_rows = cursor.rowcount except Exception as ex: print(ex) finally: if(conn != None): conn.close() if (cursor != None): cursor.close if affected_rows ==1 : return Response("Delete success",mimetype="html/text",status=204) else: return Response("Bad request",mimetype="html/text",status=400)
[ "bellinazzifelipe@gmail.com" ]
bellinazzifelipe@gmail.com
61800e0e35fd39838b134dc03a188b2128beb559
387721add1f00b836f8b62b348ebcd02e4cb40c0
/Location/views.py
3a7bd8ff63bbe5ea543b04bb09e3c9f976d9be00
[]
no_license
assissh/Landing-Page
9d3f35b141ab4980782d90288c16cca9ca50569a
a96119324b2fcf9d5e4eda5dd9b2681368b9c113
refs/heads/master
2020-03-08T10:16:15.518352
2018-04-04T13:51:36
2018-04-04T13:51:36
128,068,636
0
0
null
2018-04-04T13:48:11
2018-04-04T13:48:10
null
UTF-8
Python
false
false
2,848
py
# from django.shortcuts import render from django.contrib.auth.mixins import LoginRequiredMixin # for autherising users from django.views.generic import ListView, DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView from . import models from django.urls import reverse_lazy # Create your views here. # Create Location Here class LocationCreateView(LoginRequiredMixin, CreateView): model = models.Location template_name = 'Location/Location_new.html' login_url = 'login' # Decide fields for taking input Here fields = ['Location_Area','Location_Authorities_Involved','Location_Budget','Location_Comment','Location_City','Location_Category','Location_Description','Location_District','Location_Images','Location_Locality','Location_Name','Location_Postal_Address','Location_Creator','Location_Financial','Location_Id','Location_Latitude','Location_Longitude','Location_Subcategory','Location_Modifications_Allowed','Location_Ownership_Status','Location_Pincode','Location_Profile_Project','Location_Restrictions','Location_State','Location_Rating','Location_Street_Address','Location_Shooting_Aminities','Location_Video','Location_Surrounding'] # Set fields from current data or automated data def form_valid(self, form): form.instance.Location_Author = self.request.user return super().form_valid(form) # Location Details Here class LocationDetailView(LoginRequiredMixin, DetailView): model = models.Location template_name = 'Location/Location_detail.html' login_url = 'login' # Location ListView Here class LocationListView(ListView): model = models.Location template_name = 'Location/Location_list.html' login_url = 'login' # Location Update Here class LocationUpdateView(LoginRequiredMixin, UpdateView): model = models.Location # Decide fields for editing Here fields = ['Location_Area','Location_Authorities_Involved','Location_Budget','Location_Comment','Location_City','Location_Category','Location_Description','Location_District','Location_Images','Location_Locality','Location_Name','Location_Postal_Address','Location_Creator','Location_Financial','Location_Id','Location_Latitude','Location_Longitude','Location_Subcategory','Location_Modifications_Allowed','Location_Ownership_Status','Location_Pincode','Location_Profile_Project','Location_Restrictions','Location_State','Location_Rating','Location_Street_Address','Location_Shooting_Aminities','Location_Video','Location_Surrounding'] template_name = 'Location/Location_update.html' login_url = 'login' # Location Delete here class LocationDeleteView(LoginRequiredMixin,DeleteView): model = models.Location template_name = 'Location/Location_delete.html' success_url = reverse_lazy('Location_list') login_url = 'login'
[ "rashish66@gmail.com" ]
rashish66@gmail.com
90991c9b16713b45c5b717e36eebb064ee357850
921b3a67a24df947f085e93ba58833ec20f6b89e
/producer-tutorial/Lib/site-packages/faker/providers/address/hi_IN/__init__.py
264e08f7220d2c3d393bc8cad459d9ff9b4e7339
[]
no_license
jaslanm/python
e3bacd7ad0020b7e11adcb1b17dd6da3e4b2f65c
5cfa3913b89acb0b8cf79247de1b2820a8b92f3a
refs/heads/main
2023-08-30T01:53:13.752918
2021-10-23T13:24:48
2021-10-23T13:24:48
null
0
0
null
null
null
null
UTF-8
Python
false
false
7,640
py
from .. import Provider as AddressProvider class Provider(AddressProvider): city_formats = ('{{city_name}}', ) street_name_formats = ( '{{first_name}} {{last_name}}', '{{last_name}}', ) street_address_formats = ('{{building_number}} {{street_name}}', ) address_formats = ('{{street_address}}\n{{city}} {{postcode}}', '{{street_address}}\n{{city}}-{{postcode}}') building_number_formats = ( '####', '###', '##', '#', '#/#', '##/##', '##/###', '##/####') postcode_formats = ('######', ) cities = ( 'आदिलाबाद', 'अगरतला', 'अहमदाबाद', 'अहमदनगर', 'अजमेर', 'अम्बाजी', 'अमरपुर', 'इलाहाबाद', 'अकोला', 'अखनूर', 'अन्तर्गत', 'अलांग', 'अलीगढ', 'दादरा और नगर हवेली', 'अमरावती', 'अमरोहा', 'अनन्तपुर', 'करना', 'जिससेबेलारी', 'अनंतनाग', 'भागलपुर', 'भद्रक', 'बचेली', 'बहादुरगंज', 'बहादुरगढ', 'चिरमिरी', 'चिराला', 'चित्रदुर्ग', 'चित्तूर', 'चित्रकूट', 'देवगढ़', 'दालखोला', 'देवास', 'चंडीगढ', 'चिपलुन', 'चक्रधरपुर', 'चंबा', 'फतहपुर', 'फतेहपुर', 'फतेहगढ', 'सभापतिने', 'देवगढ़', 'धर्मापुरी', 'पाकाला', 'धारवाड', 'असम', 'देहरा', 'रानीताल', 'खडगपुर', 'मोकामा', 'मोकोकचुंग', 'जिलोंपर', 'विस्तारण', 'मोतिहारी', 'लखनऊ', 'मुंबई', 'हैदराबाद', ) states = ( 'अरूणाचल प्रदेश', 'बिहार', 'असम', 'आंध्र प्रदेश', 'छत्तीसगढ', 'हरियाणा', 'गुजरात', 'हिमाचल प्रदेश', 'गोवा', 'मध्य प्रदेश', 'महाराष्ट्र', 'जम्मू और कश्मीर', 'केरल', 'कर्नाटक', 'मणिपुर', 'मिजोरम', 'मेघालय', 'सिक्किम', 'राजस्थान', 'पंजाब', 'उडीसा', 'उत्तरांचल', 'उत्तर प्रदेश', 'तमिलनाडु', 'त्रिपुरा', 'पश्चिमी बंगाल', 'अंडमान और निकोबार', 'दमन और दीव', 'दादरा और नगर हवेली', 'दिल्ली', 'पांडिचेरी', 'लक्षद्वीप', ) countries = ( 'आर्मीनिया', 'यू.के.', 'फ्रांस', 'फलस्तीन', 'मिस्र', 'ब्राज़ील', 'ईरान', 'यूनान', 'स्पेन', 'जॉर्जिया', 'लेबनान', 'सायप्रस', 'सीरिया', 'कनाडा', 'रूस', 'संयुक्त राज्य अमरीका', 'नेदर्लान्ड', 'ऑस्ट्रेलिया', 'एंटीगुआ', 'बार्बुडा', 'ऑस्ट्रिया', 'अज़रबाइजान', 'बारबाडोस', 'बेलारूस', 'बेल्जियम', 'बेलीज़', 'बेनिन', 'बहामास', 'बहरीन', 'बांग्लादेश', 'भूटान', 'बोलिविया', 'बोस्निया', 'हर्जेगोविना', 'बोत्सवाना', 'ब्रुनेई', 'बुल्गारिया', 'बुर्किना फ़ासो', 'बर्मा', 'बुरूंडी', 'डोमिनिकन रिपब्लिक', 'गिनिया', 'टीमोर', 'फ़िनलैंड', 'गेबोन', 'गाम्बिया', 'जर्मनी', 'ग्रेनेडा', 'घाना', 'ग्रेट ब्रिटेन', 'हंगरी', 'भारत', 'हिन्दुस्तान', 'इराक', 'आयरलैंड', 'इंडोनेशिया', 'इटली', 'जमैका', 'जॉर्डन', 'जापान', 'क़जाख़स्तान', 'केन्या', 'किरिबाती', 'दक्षिण कोरिया', 'लातविया', 'लाओस', 'उत्तर कोरिया', 'कोसोवो', 'कुवैत', 'लेबनान', 'लिचटीनस्टीन', 'लिथुआनिया', 'लक्समबर्ग', 'लीबिया', 'लाइबेरिया', 'लेसोथो', 'नेपाल', 'न्यूज़ीलैण्ड', 'निकारागुआ', 'नाइजर', 'नाउरू', 'सेंट लुसिया', 'रोमानिया', 'अरब अमीरात', 'यूएई', 'युगांडा', 'यूक्रेन', 'उरूग्वे', 'उज़बेकिस्तान', 'यूनाइटेड किंगडम', 'वानुआतू', 'वेटिकन सिटी', 'वेनेजुएला', 'पश्चिमी सहारा', 'वियतनाम', 'यमन', 'ज़ायर', 'ज़ाम्बिया', 'ज़िम्बाब्वे', 'पाकिस्तान', 'सउदी अरब', 'ओमान', 'क़तर', 'ट्यूनीशिया', 'मोरक्को', 'तुर्की', 'श्रीलंका', 'अफ़ग़ानिस्तान', ) def city_name(self) -> str: return self.random_element(self.cities) def administrative_unit(self) -> str: return self.random_element(self.states) state = administrative_unit
[ "jaslanm@gmail.com" ]
jaslanm@gmail.com
873f76582d06ee71c7abd38a0f534e3e159b182a
e07f6732fa210844f1d6ef27aedd986a95e0aafa
/src/locations/views.py
935b848c158120e8b3724e8f1f4b3b7ec9dd3956
[]
no_license
jbierfeldt/WAMC
325058ca17fa6a9be09a4dacf816c8d086ff0ef9
cec9caa944730e931c74ed742c293dd4ee4e4d68
refs/heads/master
2021-04-12T05:06:25.412149
2015-05-11T14:58:29
2015-05-11T14:58:29
24,379,256
0
0
null
null
null
null
UTF-8
Python
false
false
1,361
py
from django.core import serializers from django import http from django.utils.text import slugify import json import re from django.views.generic.detail import BaseDetailView from locations.models import Location class JSONResponseMixin(object): def render_to_response(self, context): "Returns a JSON response containing 'context' as payload" return self.get_json_response(self.convert_context_to_json(context)) def get_json_response(self, content, **httpresponse_kwargs): "Construct an `HttpResponse` object." return http.HttpResponse(content, content_type='application/json', **httpresponse_kwargs) def convert_context_to_json(self, context): "Convert the context dictionary into a JSON object" data_struct = { 'name': context['object'].name, 'lat': context['object'].lat, 'lng': context['object'].lng } return json.dumps(data_struct) class LocationDetailView(BaseDetailView, JSONResponseMixin): model = Location def get_object(self, queryset=None): clean_split = re.split('-(?=[0-9])|\s(?=[0-9])', self.request.GET['tag']) print clean_split slug = slugify(clean_split[0]) print slug obj = Location.objects.get(tags__slug=slug) return obj # Create your views here.
[ "jbierfeldt@gmail.com" ]
jbierfeldt@gmail.com
56e3aa24312bd0459505ed4fef97735acd309444
5672737d1ff34bebfeb408426e52ed49df8be3bb
/graphgallery/attack/targeted/common/dice.py
199c77c82ff5a357cfc3632765515866b0b07504
[ "MIT" ]
permissive
sailfish009/GraphGallery
5063ee43340a6ca8da9f2d7fb3c44349e80321b2
4eec9c5136bda14809bd22584b26cc346cdb633b
refs/heads/master
2023-08-24T19:19:59.714411
2021-10-16T10:10:40
2021-10-16T10:10:40
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,398
py
import random import numpy as np from graphgallery.attack.targeted import Common from .rand import RAND @Common.register() class DICE(RAND): def add_edge(self, influence_nodes): u = random.choice(influence_nodes) neighbors = self.graph.adj_matrix[u].indices.tolist() potential_nodes = list(self.nodes_set - set(neighbors) - set([self.target, u])) if len(potential_nodes) == 0: return None v = random.choice(potential_nodes) label = self.graph.node_label if not self.is_modified(u, v) and (label[u] != label[v]): return (u, v) else: return None def del_edge(self, influence_nodes): u = random.choice(influence_nodes) neighbors = self.graph.adj_matrix[u].indices.tolist() potential_nodes = list(set(neighbors) - set([self.target, u])) if len(potential_nodes) == 0: return None v = random.choice(potential_nodes) if not self.allow_singleton and (self.modified_degree[u] <= 1 or self.modified_degree[v] <= 1): return None label = self.graph.node_label if not self.is_modified(u, v) and (label[u] == label[v]): return (u, v) else: return None
[ "cnljt@outlook.com" ]
cnljt@outlook.com
ce68ca6a985d5ee7aaf94ae58cdf1018d16e5b87
fab14fae2b494068aa793901d76464afb965df7e
/benchmarks/f3_wrong_hints/scaling_nonlinear_software/4-19_24.py
64ccf5f9ec01d994ed630115ca20592c032bc646
[ "MIT" ]
permissive
teodorov/F3
673f6f9ccc25acdfdecbfc180f439253474ba250
c863215c318d7d5f258eb9be38c6962cf6863b52
refs/heads/master
2023-08-04T17:37:38.771863
2021-09-16T07:38:28
2021-09-16T07:38:28
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,964
py
from typing import FrozenSet, Tuple import pysmt.typing as types from pysmt.environment import Environment as PysmtEnv from pysmt.fnode import FNode from utils import symb_to_next from hint import Hint, Location def transition_system(env: PysmtEnv) -> Tuple[FrozenSet[FNode], FNode, FNode, FNode]: assert isinstance(env, PysmtEnv) mgr = env.formula_manager pc = mgr.Symbol("pc", types.INT) x = mgr.Symbol("x", types.INT) y = mgr.Symbol("y", types.INT) z = mgr.Symbol("z", types.INT) x_pc = symb_to_next(mgr, pc) x_x = symb_to_next(mgr, x) x_y = symb_to_next(mgr, y) x_z = symb_to_next(mgr, z) symbols = frozenset([pc, x, y, z]) n_locs = 5 int_bound = n_locs pcs = [] x_pcs = [] ints = [mgr.Int(i) for i in range(int_bound)] for l in range(n_locs): n = ints[l] pcs.append(mgr.Equals(pc, n)) x_pcs.append(mgr.Equals(x_pc, n)) m_1 = mgr.Int(-1) pcend = mgr.Equals(pc, m_1) x_pcend = mgr.Equals(x_pc, m_1) # initial location. init = pcs[0] # control flow graph. cfg = mgr.And( # pc = -1 : -1, mgr.Implies(pcend, x_pcend), # pc = 0 & !(y >= 1) : -1, mgr.Implies(mgr.And(pcs[0], mgr.Not(mgr.GE(y, ints[1]))), x_pcend), # pc = 0 & y >= 1 : 1, mgr.Implies(mgr.And(pcs[0], mgr.GE(y, ints[1])), x_pcs[1]), # pc = 1 & !(z >= 1) : -1, mgr.Implies(mgr.And(pcs[1], mgr.Not(mgr.GE(z, ints[1]))), x_pcend), # pc = 1 & z >= 1 : 2, mgr.Implies(mgr.And(pcs[1], mgr.GE(z, ints[1])), x_pcs[2]), # pc = 2 & !(x >= 0) : -1, mgr.Implies(mgr.And(pcs[2], mgr.Not(mgr.GE(x, ints[0]))), x_pcend), # pc = 2 & x >= 0 : 3, mgr.Implies(mgr.And(pcs[2], mgr.GE(x, ints[0])), x_pcs[3]), # pc = 3 : 4, mgr.Implies(pcs[3], x_pcs[4]), # pc = 4 : 2, mgr.Implies(pcs[4], x_pcs[2])) # transition labels. labels = mgr.And( # (pc = -1 & pc' = -1) -> (x' = x & y' = y & z' = z), mgr.Implies( mgr.And(pcend, x_pcend), mgr.And(mgr.Equals(x_x, x), mgr.Equals(x_y, y), mgr.Equals(x_z, z))), # (pc = 0 & pc' = -1) -> (x' = x & y' = y & z' = z), mgr.Implies( mgr.And(pcs[0], x_pcend), mgr.And(mgr.Equals(x_x, x), mgr.Equals(x_y, y), mgr.Equals(x_z, z))), # (pc = 0 & pc' = 1) -> (x' = x & y' = y & z' = z), mgr.Implies( mgr.And(pcs[0], x_pcs[1]), mgr.And(mgr.Equals(x_x, x), mgr.Equals(x_y, y), mgr.Equals(x_z, z))), # (pc = 1 & pc' = -1) -> (x' = x & y' = y & z' = z), mgr.Implies( mgr.And(pcs[1], x_pcend), mgr.And(mgr.Equals(x_x, x), mgr.Equals(x_y, y), mgr.Equals(x_z, z))), # (pc = 1 & pc' = 2) -> (x' = x & y' = y & z' = z), mgr.Implies( mgr.And(pcs[1], x_pcs[2]), mgr.And(mgr.Equals(x_x, x), mgr.Equals(x_y, y), mgr.Equals(x_z, z))), # (pc = 2 & pc' = -1) -> (x' = x & y' = y & z' = z), mgr.Implies( mgr.And(pcs[2], x_pcend), mgr.And(mgr.Equals(x_x, x), mgr.Equals(x_y, y), mgr.Equals(x_z, z))), # (pc = 2 & pc' = 3) -> (x' = x & y' = y & z' = z), mgr.Implies( mgr.And(pcs[2], x_pcs[3]), mgr.And(mgr.Equals(x_x, x), mgr.Equals(x_y, y), mgr.Equals(x_z, z))), # (pc = 3 & pc' = 4) -> (x' = y*z - 1 & y' = y & z' = z), mgr.Implies( mgr.And(pcs[3], x_pcs[4]), mgr.And(mgr.Equals(x_x, mgr.Minus(mgr.Times(y, z), ints[1])), mgr.Equals(x_y, y), mgr.Equals(x_z, z))), # (pc = 4 & pc' = 2) -> (x' = x & y' = y+1 & z' = z), mgr.Implies( mgr.And(pcs[4], x_pcs[2]), mgr.And(mgr.Equals(x_x, x), mgr.Equals(x_y, mgr.Plus(y, ints[1])), mgr.Equals(x_z, z)))) # transition relation. trans = mgr.And(cfg, labels) # fairness. fairness = mgr.Not(pcend) return symbols, init, trans, fairness def hints(env: PysmtEnv) -> FrozenSet[Hint]: assert isinstance(env, PysmtEnv) mgr = env.formula_manager pc = mgr.Symbol("pc", types.INT) x = mgr.Symbol("x", types.INT) y = mgr.Symbol("y", types.INT) z = mgr.Symbol("z", types.INT) symbs = frozenset([pc, x, y, z]) x_pc = symb_to_next(mgr, pc) x_x = symb_to_next(mgr, x) x_y = symb_to_next(mgr, y) x_z = symb_to_next(mgr, z) res = [] i_0 = mgr.Int(0) i_1 = mgr.Int(1) i_2 = mgr.Int(2) i_3 = mgr.Int(3) loc0 = Location(env, mgr.GE(z, i_3)) loc0.set_progress(0, mgr.GT(x_z, z)) h_z = Hint("h_z1", env, frozenset([z]), symbs) h_z.set_locs([loc0]) res.append(h_z) loc0 = Location(env, mgr.GE(z, i_3), mgr.GE(y, i_0)) loc0.set_progress(1, mgr.GE(x_z, mgr.Plus(z, y))) loc1 = Location(env, mgr.GE(z, i_3), mgr.GE(x, i_0)) loc1.set_progress(0, mgr.GE(x_z, mgr.Plus(z, i_0))) h_z = Hint("h_z2", env, frozenset([z]), symbs) h_z.set_locs([loc0, loc1]) res.append(h_z) loc0 = Location(env, mgr.GE(y, i_3)) loc0.set_progress(1, mgr.Equals(x_y, mgr.Plus(y, i_1))) loc1 = Location(env, mgr.GE(y, i_3)) loc1.set_progress(2, mgr.Equals(x_y, y)) loc2 = Location(env, mgr.GE(y, i_3)) loc2.set_progress(2, mgr.Equals(x_y, mgr.Plus(y, i_1))) h_y = Hint("h_y4", env, frozenset([y]), symbs) h_y.set_locs([loc0, loc1, loc2]) res.append(h_y) loc0 = Location(env, mgr.GE(z, i_0)) loc0.set_progress(1, mgr.Equals(x_z, z)) loc1 = Location(env, mgr.GE(z, i_0)) loc1.set_progress(0, mgr.Equals(x_z, mgr.Plus(z, i_3))) h_z = Hint("h_z4", env, frozenset([z]), symbs) h_z.set_locs([loc0, loc1]) res.append(h_z) return frozenset(res)
[ "en.magnago@gmail.com" ]
en.magnago@gmail.com
193c0f5daa4e016227ac734facb2ea5dfa3bb46f
f0d713996eb095bcdc701f3fab0a8110b8541cbb
/amYH2SMto4yZw9E6n_19.py
6ad4dab5e20ba6ba2aa12a7d60bbef1fcaf658e6
[]
no_license
daniel-reich/turbo-robot
feda6c0523bb83ab8954b6d06302bfec5b16ebdf
a7a25c63097674c0a81675eed7e6b763785f1c41
refs/heads/main
2023-03-26T01:55:14.210264
2021-03-23T16:08:01
2021-03-23T16:08:01
350,773,815
0
0
null
null
null
null
UTF-8
Python
false
false
1,180
py
""" Write a function that returns `True` if the phone number is in a valid format. Valid formats are as follows: **With Country Code**| **Without Country Code** ---|--- +1-892-445-7663| 892-445-7663 1-892-445-7663| (892) 445-7663 1 (892) 445-7663| 892.567.8901 1.892.567.8901| 1/892/567/8901 1 892 567 8901| 892/567/8901 18925678901| 892 567 8901 ### Examples validate("578-332-1114") ➞ True validate("57-332-1114") ➞ False validate("577 332 1114") ➞ False # More than one space in between digits clusters. validate("57 332 1114") ➞ False # Unacceptable digit cluster length. validate("157%332-1114") ➞ False # Unacceptable delimiter. ### Notes * The country code will always be `+1` or `1`. * Each phone number will contain either 10 or 11 digits (depending on whether the country code exists). * There must either be exactly one space, a delimiter, or no space at all between the digit clusters. * You do not have to worry about extensions. """ import re ​ def validate(s): return bool(re.match(r'(?:\+?\d)?[- ./]?(?:\d{3}|\(\d{3}\))[- ./]?\d{3}[- ./]?\d{4}', s))
[ "daniel.reich@danielreichs-MacBook-Pro.local" ]
daniel.reich@danielreichs-MacBook-Pro.local
c6ddaf30fbca2509de73210a8c1e50c08424d871
1f8fa8755e19d521caa5c4063a2d3518bd925f83
/mysql-from-python.py
5fb47cbf157a9f1b0d8ce19a54c60fab3f697e5e
[]
no_license
Artrage/pymysql
d26fc737795d83310a85bfe51c9f6ddd784c74bd
f70a6e78fea65f39cdb80b722241ff8132a9b736
refs/heads/master
2022-12-22T15:05:27.426315
2020-09-15T12:02:14
2020-09-15T12:02:14
294,419,908
0
0
null
null
null
null
UTF-8
Python
false
false
631
py
import os import pymysql # Get username from Cloud9 workspace # (modify this variable if running on another environment) username = os.getenv('C9_USER') # Connect to the database connection = pymysql.connect(host='localhost', user=username, password='', db='Chinook') try: # Run a query with connection.cursor() as cursor: sql = "SELECT * FROM Artist;" cursor.execute(sql) result = cursor.fetchall() print(result) finally: # Close connection whether or not the above worked connection.close()
[ "art.balenok@gmail.com" ]
art.balenok@gmail.com
9b0a028dc463c20bab0b5cd04f3a053169274e09
dccd1058e723b6617148824dc0243dbec4c9bd48
/codeforces/837A.py
1e2ca2f8f3888d7535474d2dcd8b5df8a1b593e2
[]
no_license
imulan/procon
488e49de3bcbab36c624290cf9e370abfc8735bf
2a86f47614fe0c34e403ffb35108705522785092
refs/heads/master
2021-05-22T09:24:19.691191
2021-01-02T14:27:13
2021-01-02T14:27:13
46,834,567
7
1
null
null
null
null
UTF-8
Python
false
false
176
py
n = int(input()) s = input() ans = 0 for w in s.split(' '): t = 0 for c in w: if ord('A')<=ord(c)<=ord('Z'): t += 1 ans = max(ans,t) print(ans)
[ "k0223.teru@gmail.com" ]
k0223.teru@gmail.com
fc6ff244f04d5c3ed78ef4d3f3f06fab0771b412
e3046f25d96311a3f642d7bd55d76a536a98d228
/src/mailme/migrations/0001_initial.py
e88809b19a66936b2fa7cae1bb7150d06da51047
[ "BSD-3-Clause" ]
permissive
mailme/mailme
6afa6585588fd423a4d8f395683cde7df359b910
5e24a1b7078c6325d8302a4547c46027d76c4acf
refs/heads/master
2023-09-01T14:06:45.225768
2018-02-21T08:40:11
2018-02-21T08:40:11
54,772,613
2
1
BSD-3-Clause
2023-09-14T09:31:44
2016-03-26T09:43:12
Python
UTF-8
Python
false
false
5,169
py
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-03-29 12:26 from __future__ import unicode_literals from django.conf import settings import django.contrib.auth.models import django.contrib.postgres.fields.jsonb from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import uuid class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='User', fields=[ ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), ('id', models.UUIDField(default=uuid.uuid4, primary_key=True, serialize=False)), ('username', models.CharField(max_length=256, unique=True, verbose_name='Username')), ('name', models.TextField(blank=True, max_length=100, null=True, verbose_name='Name')), ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), ], options={ 'verbose_name': 'User', 'verbose_name_plural': 'Users', }, managers=[ ('objects', django.contrib.auth.models.UserManager()), ], ), migrations.CreateModel( name='Mailbox', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=256, verbose_name='Name')), ('uri', models.CharField(blank=True, default=None, help_text='Example: imap+ssl://myusername:mypassword@someserver', max_length=256, null=True, verbose_name='URI')), ('from_email', models.CharField(blank=True, default=None, max_length=255, null=True, verbose_name='From email')), ('active', models.BooleanField(default=True, verbose_name='Active')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Message', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('from_address', django.contrib.postgres.fields.jsonb.JSONField(blank=True, default=[], verbose_name='Sent from')), ('to_address', django.contrib.postgres.fields.jsonb.JSONField(blank=True, default=[], verbose_name='Sent to')), ('cc_address', django.contrib.postgres.fields.jsonb.JSONField(blank=True, default=[], verbose_name='CC')), ('bcc_address', django.contrib.postgres.fields.jsonb.JSONField(blank=True, default=[], verbose_name='BCC')), ('reply_to', django.contrib.postgres.fields.jsonb.JSONField(blank=True, null=True, verbose_name='Reply-To')), ('in_reply_to', django.contrib.postgres.fields.jsonb.JSONField(blank=True, null=True, verbose_name='In reply to')), ('headers', django.contrib.postgres.fields.jsonb.JSONField(blank=True, default={}, verbose_name='Headers')), ('subject', models.CharField(max_length=255, verbose_name='Subject')), ('original', models.TextField(verbose_name='Original (raw) text')), ('plain_body', models.TextField(blank=True, verbose_name='Text')), ('html_body', models.TextField(blank=True, verbose_name='HTML')), ('date', models.DateTimeField(blank=True, verbose_name='Date')), ('message_id', models.CharField(max_length=998)), ('references', django.contrib.postgres.fields.jsonb.JSONField(blank=True, null=True, verbose_name='References')), ], ), migrations.CreateModel( name='Thread', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('subject', models.CharField(max_length=256)), ('mailbox', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='threads', to='mailme.Mailbox')), ], ), migrations.AddField( model_name='message', name='thread', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='messages', to='mailme.Thread'), ), ]
[ "cg@webshox.org" ]
cg@webshox.org
f0a66338703bff98e6f8ac84537690a653604c9d
a2e638cd0c124254e67963bda62c21351881ee75
/Extensions/PairOptionsPricerDealPackage/FPythonCode/StrategyDealPackageBase.py
722d1533ec65186ebd68e6d79549af90aaaa0ad1
[]
no_license
webclinic017/fa-absa-py3
1ffa98f2bd72d541166fdaac421d3c84147a4e01
5e7cc7de3495145501ca53deb9efee2233ab7e1c
refs/heads/main
2023-04-19T10:41:21.273030
2021-05-10T08:50:05
2021-05-10T08:50:05
null
0
0
null
null
null
null
UTF-8
Python
false
false
14,178
py
import acm from PairOptionsDealPackageBase import PairOptionsDealPackageBase from PairOptionsUtil import QuotationLabel, CurrencyNameFromCurrency, GetSingleValue, RoundPremium from DealPackageDevKit import Object, CalcVal, Float, ParseFloat, Action from DealPackageUtil import DealPackageException from PairOptionsB2B import B2BCompositeAttribute class ValueNotSet(): pass class StrategyDealPackageBase(PairOptionsDealPackageBase): amountCallForeign = Object( label='@ForeignAmountLabel', objMapping='PricingOptions.AmountCallForeign', transform='@AmountTransform', onChanged='@UpdateDealPackageTrade', formatter='@ForeignAmountFormatterCB', enabled='@ForeignAmountEnabled', visible='@CallPutAmountsVisible', recreateCalcSpaceOnChange=True) amountCallDomestic = Object( label='@DomesticAmountLabel', objMapping='PricingOptions.AmountCallDomestic', transform='@AmountTransform', onChanged='@UpdateDealPackageTrade', formatter='@DomesticAmountFormatterCB', enabled='@DomesticAmountEnabled', visible='@CallPutAmountsVisible', recreateCalcSpaceOnChange=True) amountPutForeign = Object( label='@ForeignAmountLabel', objMapping='PricingOptions.AmountPutForeign', transform='@AmountTransform', onChanged='@UpdateDealPackageTrade', formatter='@ForeignAmountFormatterCB', enabled='@ForeignAmountEnabled', visible='@CallPutAmountsVisible', recreateCalcSpaceOnChange=True) amountPutDomestic = Object( label='@DomesticAmountLabel', objMapping='PricingOptions.AmountPutDomestic', transform='@AmountTransform', onChanged='@UpdateDealPackageTrade', formatter='@DomesticAmountFormatterCB', enabled='@DomesticAmountEnabled', visible='@CallPutAmountsVisible', recreateCalcSpaceOnChange=True) theorValCallSaveTrade = CalcVal(calcMapping='CallTrade:FDealSheet:Portfolio Theoretical Value FXOStrat', label='@TheorValSaveTradeLabel', formatter='@SingleValueFormatterCB', solverTopValue=True) theorValNoPremCallSaveTrade=CalcVal(calcMapping='CallTrade:FDealSheet:Portfolio Theoretical Value No Trade Payments FXOStrat', label='@TheorValNoPremiumSaveTradeLabel', formatter='@SingleValueFormatterCB', solverTopValue=True) theorValPutSaveTrade = CalcVal(calcMapping='PutTrade:FDealSheet:Portfolio Theoretical Value FXOStrat', label='@TheorValSaveTradeLabel', formatter='@SingleValueFormatterCB', solverTopValue=True) theorValNoPremPutSaveTrade =CalcVal(calcMapping='PutTrade:FDealSheet:Portfolio Theoretical Value No Trade Payments FXOStrat', label='@TheorValNoPremiumSaveTradeLabel', formatter='@SingleValueFormatterCB', solverTopValue=True) tradePrice = Float( label='@TradePriceLabel', objMapping='StrategyPrice') tradePremium = Float( label='@TradePremiumLabel', objMapping='StrategyPremium') callTradePrice = Object( label='@TradePriceLabel', objMapping='CallTrade.Price') callTradePremium = Object( label='@TradePremiumLabel', objMapping='CallTrade.Premium') putTradePrice = Object( label='@TradePriceLabel', objMapping='PutTrade.Price') putTradePremium = Object( label='@TradePremiumLabel', objMapping='PutTrade.Premium') amountCallHeader = Action( label='@AmountCallHeader', action='@UpdateBuySell') amountPutHeader = Action( label='@AmountPutHeader', action='@UpdateBuySell') # ------------------------------------------------------------------------------- # Composite attributes # ------------------------------------------------------------------------------- b2b = B2BCompositeAttribute(b2bName='B2B') b2bCall = B2BCompositeAttribute(b2bName='B2BCall') b2bPut = B2BCompositeAttribute(b2bName='B2BPut') '''******************************************************* * Trade/Instrument Get methods *******************************************************''' def Trade(self): return self.TradeAt('callTrade') def CallTrade(self): return self.TradeAt('callTrade') def PutTrade(self): return self.TradeAt('putTrade') def Instrument(self): return self.InstrumentAt('callTrade') def B2B(self): return [self.B2BTradeParamsAt('callTrade'), self.B2BTradeParamsAt('putTrade')] def B2BCall(self): return self.B2BTradeParamsAt('callTrade') def B2BPut(self): return self.B2BTradeParamsAt('putTrade') def QuoteCombinationTrade(self): return self.PricingOptions().QuoteCombinationTrade() def CallStrike(self): return self.strikeDomesticPerForeign def PutStrike(self): return self.strikeDomesticPerForeign '''******************************************************* * Label methods *******************************************************''' def TradePriceLabel(self, *args): return 'Price ' + QuotationLabel(self.LeadTrade()) def TradePremiumLabel(self, *args): return 'Premium ' + CurrencyNameFromCurrency(self.premiumCurrency) def CallVolatilityLabel(self, *args): return 'Call' def PutVolatilityLabel(self, *args): return 'Put' def AmountCallHeader(self, *args): return 'Buy Call' if self.AmountCallForeignSign() > 0 else 'Sell Call' def AmountPutHeader(self, *args): return 'Buy Put' if self.AmountPutForeignSign() > 0 else 'Sell Put' '''******************************************************* * OnChanged methods *******************************************************''' def SimulateVolatility(self, attributeName, old, new, userInputAttributeName): if new == 'ValueWillNotBeSet': self.SimulateCalculation(attributeName, None) else: self.volatility = self.GetSimulatedCalculationValue(attributeName) '''******************************************************* * Action methods *******************************************************''' def UpdateBuySell(self, *args): if self.PricingOptions().CurrentSaveIsFlipped(): self.amountCallDomestic = -self.amountCallDomestic else: self.amountCallForeign = -self.amountCallForeign '''******************************************************* * Visible methods *******************************************************''' def CallPutAmountsVisible(self, *args): visibile = False if self.saveIsFlippedSide: visible = abs(self.amountCallDomestic) != abs(self.amountPutDomestic) or self.IsShowModeDetail() else: visible = abs(self.amountCallForeign) != abs(self.amountPutForeign) or self.IsShowModeDetail() return visible '''******************************************************* * Choices methods *******************************************************''' def ExerciseTypeChoiceList(self, *args): return ['European'] '''******************************************************* * Object mapping methods *******************************************************''' def StrategyPrice(self, price = ValueNotSet()): if isinstance(price, ValueNotSet): if self.PricingOptions().CurrentSaveIsFlipped(): return (self.amountCallDomestic * self.callTradePrice + self.amountPutDomestic * self.putTradePrice) / self.amountDomestic if self.amountDomestic else 0.0 else: return (self.amountCallForeign * self.callTradePrice + self.amountPutForeign * self.putTradePrice) / self.amountForeign if self.amountForeign else 0.0 else: thVal = GetSingleValue(self.saveTradeCalcVal_theorValNoPremium.Value(), "Buy") if not (thVal and thVal.Number()): raise DealPackageException('No theoretical value for the strategy, you have to set the price on the components individually') thValCall = GetSingleValue(self.theorValNoPremCallSaveTrade.Value(), "Buy") thValPut = GetSingleValue(self.theorValNoPremPutSaveTrade.Value(), "Buy") callStrike = self.CallStrike() putStrike = self.PutStrike() thValCall = thValCall.Number() thValPut = thValPut.Number() thVal = thValCall + thValPut if self.PricingOptions().CurrentSaveIsFlipped(): self.callTradePrice = price * thValCall / thVal * self.amountDomestic / self.amountCallDomestic self.putTradePrice = price * thValPut / thVal * self.amountDomestic / self.amountPutDomestic else: self.callTradePrice = price * thValCall / thVal * self.amountForeign / self.amountCallForeign self.putTradePrice = price * thValPut / thVal * self.amountForeign / self.amountPutForeign def StrategyPremium(self, premium = ValueNotSet()): if isinstance(premium, ValueNotSet): return self.callTradePremium + self.putTradePremium else: thVal = GetSingleValue(self.saveTradeCalcVal_theorValNoPremium.Value(), "Buy") if not (thVal and thVal.Number()): raise DealPackageException('No theoretical value for the strategy, you have to set the premium on the components individually') thValCall = GetSingleValue(self.theorValNoPremCallSaveTrade.Value(), "Buy") callPremium = RoundPremium(self.premiumCurrency, premium * thValCall.Number() / thVal.Number()) self.callTradePremium = callPremium self.putTradePremium = RoundPremium(self.premiumCurrency, premium) - callPremium def UnsimulateOneVolatility(self, attrName, oldVal, newVal, *args): if self.IsCalculationSimulated('oneVolatility'): self.UnsimulateAttributeValue('oneVolatility') self.SetAttribute(attrName, newVal * 100) '''******************************************************* * Deal Package Interface methods *******************************************************''' def PriceGreekExcludeVolatilityMovement(self, *attr): return self.quoteTradeCalcVal.PriceGreekExcludeVolatilityMovement(*attr) def GetIntrinsicAttribute(self, name, isFwd): attr = 'intrinsic' attr += '2' if name.startswith('strike2') else '' attr += 'Fwd' if isFwd else 'Spot' return attr def AmountCallForeignSign(self): return 1 if self.amountCallForeign > 0 else -1 def AmountPutForeignSign(self): return 1 if self.amountPutForeign > 0 else -1 def AmountCallDomesticSign(self): return 1 if (self.amountCallDomestic > 0) else -1 def AmountPutDomesticSign(self): return 1 if (self.amountPutDomestic > 0) else -1 '''******************************************************* * Object mapping methods *******************************************************''' @classmethod def SetUp(cls, definitionSetUp): from DealPackageSetUp import AddInfoSetUp definitionSetUp.AddSetupItems( AddInfoSetUp( recordType='DealPackage', fieldName='MemoString', dataType='String', description='Options description', dataTypeGroup='Standard', subTypes=[], defaultValue='', mandatory=False))
[ "81222178+nenchoabsa@users.noreply.github.com" ]
81222178+nenchoabsa@users.noreply.github.com
401636124c6bb27058ccc63c5dddf06041a4a95c
fab5f4bc66f9aad0f28387d2b4bbd20b252575ac
/append.py
a603ea159b795a4931d00f35d8e99f40abb5cddc
[]
no_license
zacwbond/submod-string-appender
64c42a658ffd7a18fa937355a1e56e743d51e20e
443ba910cd6eebe968fce34e076d4fe3d824ee4c
refs/heads/master
2021-01-10T01:43:37.797278
2016-02-17T19:20:38
2016-02-17T19:20:38
51,854,017
0
0
null
2016-02-17T20:19:27
2016-02-16T17:18:56
Python
UTF-8
Python
false
false
742
py
def append_abc(s): return 'abc_' + s def append_bcd(s): return 'bcd_' + s def append_efg(s): return 'efg_' + s def append_stinker(s): return 'stinker_' + s if __name__ == '__main__': def unit_test(f, s, expected): if f(s) != expected: return False return True tests = { 'hello abc': (append_abc, 'hello world', 'abc_hello world'), 'hello bcd': (append_bcd, 'hello world', 'bcd_hello world') } print("\n\nPerforming the world's most incompetent unit test...") results = [(t, unit_test(f, s, e)) for (t, (f, s, e)) in tests.items()] if all(results): print('\n\nALL TESTS PASSED!') else: print('\n'.join([t + ' test FAILED' for (t, p) in results if not p]))
[ "zachary.bond@bigasssolutions.com" ]
zachary.bond@bigasssolutions.com
4c29029e33d273eaa754609f6e8b2b13dc4c418e
0fd50d8efb1f47c7a29054dbeb2e6079a59022cd
/utils/pvacapi/__init__.py
641c92d9bef136dfc157b4d89d77923c2ec88f0e
[ "BSD-3-Clause-Clear", "Apache-2.0" ]
permissive
malachig/pVACtools
8f6ead96660d5de3ffcc57f2224ad1fba8dd01e7
1e86411055b3da9f81f966e83578dfadc3883498
refs/heads/master
2023-03-18T05:31:39.196527
2022-01-06T19:11:58
2022-01-06T19:11:58
590,623,643
0
0
BSD-3-Clause-Clear
2023-01-18T20:41:32
2023-01-18T20:41:32
null
UTF-8
Python
false
false
60
py
__all__ = [ 'app', 'clear_cache' ] from . import *
[ "atawollam@gmail.com" ]
atawollam@gmail.com
1a9b0404f1fecb0e67e39598df067a2447ee813a
e94222c81c4692000b15670820652a545db41ae6
/supplementary_material/Learning_to_Cartoonize_supp/inference_code/inference.py
5c685f08771a5053c7440bc617b5f8fec1407a20
[]
no_license
SystemErrorWang/supplementary
7037ac7f5aff45853281f95b4702f9ca26cb94cc
ab8d143aadc87cec482879b4cbad2125156e4069
refs/heads/master
2022-03-27T21:31:37.239446
2019-11-23T02:28:42
2019-11-23T02:28:42
222,672,327
0
0
null
null
null
null
UTF-8
Python
false
false
3,300
py
''' CVPR 2020 submission, Paper ID 6791 Source code for 'Learning to Cartoonize Using White-Box Cartoon Representations' ''' import os import cv2 import numpy as np import tensorflow as tf import network import guided_filter from tqdm import tqdm def center_crop(image): h, w, c = np.shape(image) if h > w: dh = (h-w)//2 image = image[dh:dh+w, :, :] elif w > h: dw = (w-h)//2 image = image[:, dw:dw+h, :] return image def limit_720p(image): h, w, c = np.shape(image) if min(h, w) > 720: if h > w: h, w = int(720*h/w), 720 else: h, w = 720, int(720*w/h) image = cv2.resize(image, (w, h), interpolation=cv2.INTER_AREA) h, w = (h//8)*8, (w//8)*8 image = image[:h, :w, :] return image def cartoonize(name_list, output_folder, model_dir): input_photo = tf.placeholder(tf.float32, [1, None, None, 3]) outputs1 = network.unet_generator(input_photo) outputs2 = guided_filter.guided_filter(input_photo, outputs1, r=1, eps=5e-3) all_vars = tf.trainable_variables() gene_vars = [var for var in all_vars if 'generator' in var.name] saver = tf.train.Saver(var_list=gene_vars) config = tf.ConfigProto() config.gpu_options.allow_growth = True sess = tf.Session(config=config) sess.run(tf.global_variables_initializer()) saver.restore(sess, tf.train.latest_checkpoint(model_dir)) for content_path in tqdm(name_list): image = cv2.imread(content_path) try: image = limit_720p(image) h, w, c = np.shape(image) batch_image = image.astype(np.float32)/127.5 - 1 batch_image = np.expand_dims(batch_image, axis=0) out1, out2 = sess.run([outputs1, outputs2], feed_dict={input_photo: batch_image}) guided_weight = 1 output_image = (1-guided_weight)*out1+guided_weight*out2 output_image = (np.squeeze(output_image)+1)/2 #output_image = (output_image+0.01)**1.1+0.01 output_image = np.clip(output_image*255, 0, 255).astype(np.uint8) combined = np.empty((h, w*2, 3), dtype=np.uint8) combined[:, :w, :] = image combined[:, w:, :] = output_image name = content_path.split('/')[-1].split('.')[0] save1_path = os.path.join(output_folder, '{}.jpg'.format(name)) cv2.imwrite(save1_path, combined) #save2_path = os.path.join(output_folder, '{}_ours.jpg'.format(name)) #cv2.imwrite(save2_path, output_image) except: pass if __name__ == '__main__': ''' model_dir = 'models' name_list = list() for name in os.listdir('testset'): name_list.append(os.path.join('testset', name)) output_folder = 'output' if not os.path.exists(output_folder): os.mkdir(output_folder) cartoonize(name_list, output_folder, model_dir) ''' from selective_search import selective_search image = cv2.imread('testset/party7.jpg') output = selective_search(image, mode='single', random=False) print(output)
[ "secret_wang@outlook.com" ]
secret_wang@outlook.com
07039fd160d1f48fe2efec31078b006df2fbf471
732bece5927d83405b448963ffd2ed08f2ee8ef9
/tests/unit/api/validation/record_validator_tests.py
05331c44805de6b9becdb17f493fd81a6ed7cdb9
[]
no_license
thiagortz/phone-book
8b530017924a08fb225219c1eba83a7dbd97758c
02835f23c9ea22eabcab8f9db05187694ed2c6c8
refs/heads/master
2020-03-30T21:47:56.949507
2018-10-04T22:16:56
2018-10-04T22:16:56
151,642,415
0
0
null
null
null
null
UTF-8
Python
false
false
1,094
py
from unittest import TestCase from unittest.mock import patch from unittest.mock import Mock from app.api.record.validation.validator import Validator from app.utils.formats import PHONE_NUMBER_REX class RecordValidadorTests(TestCase): def setUp(self): self.validador = Validator() @patch("app.api.record.validation.validator.re") def test_is_valid_phone_number(self, re): pattern = Mock() pattern.match.return_value = object() re.compile.return_value = pattern phone_number = '21945568909' self.validador._is_valid_phone_number(phone_number) re.compile.assert_called_once_with(PHONE_NUMBER_REX) @patch("app.api.record.validation.validator.Validator._schema") @patch("app.api.record.validation.validator.FormatChecker") @patch("app.api.record.validation.validator.Draft4Validator") def test_draft4_validate(self, draft4, format, schema): draft4.validate.return_value = None self.validador.draft4_validate(data={}) draft4.assert_called_once_with(schema(), format_checker=format())
[ "thiago-dias@outlook.com" ]
thiago-dias@outlook.com
c1e2b450471c90733728dcdbe3046d7c624eac93
be9405b109fd1786249f028276a19f2c53f80273
/ex18.py
53333959e593bb95588c9b75f3706c01e2cd973d
[]
no_license
dongzeyuan/LPTHW
76209d917954bc88b6fb30094cc922e6f99e8e44
66fa6e5b5caad423cf984bf420cb083aa4940e1b
refs/heads/master
2021-01-21T10:19:24.944628
2017-03-04T13:24:04
2017-03-04T13:24:04
83,405,359
0
0
null
null
null
null
UTF-8
Python
false
false
360
py
def print_two(*args): arg1, arg2 = args print("arg1: %r, arg2: %r" % (arg1, arg2)) def print_two_again(arg1, arg2): print('arg1: %r, arg2: %r' % (arg1, arg2)) def print_one(arg1): print("arg1: %r" % arg1) def print_none(): print("I got nothing.") print_two("slash", "dong") print_one("slash") print_two_again("1", "2") print_none()
[ "dongfujing88@gmail.com" ]
dongfujing88@gmail.com
5e09919524ddd06ec18898f2f208eb83de797bc1
14aebe7f5f7b83637924f88df41cb5b8b813bc30
/msgvis/apps/experiment/management/commands/add_controlled_experiment.py
fdc128e05e6b390c32499bd14f0084f655060b0d
[ "MIT" ]
permissive
hds-lab/coding-ml
1ab5a4caceabb9864f4abf4ad90a771e5640ebd4
0c4d1aab92e7192ac11f61f6b58ebf2455cc8c9e
refs/heads/master
2020-12-10T05:44:58.740299
2017-02-10T01:36:37
2017-02-10T01:36:37
47,863,198
1
1
null
2016-12-11T23:43:25
2015-12-12T03:52:36
JavaScript
UTF-8
Python
false
false
2,805
py
from django.core.management.base import BaseCommand, make_option, CommandError import msgvis.apps.experiment.models as experiment_models from msgvis.apps.base.utils import check_or_create_dir from django.db import transaction import logging logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) class Command(BaseCommand): help = "Create a new controlled experiment." args = '<dictionary_id> <output_folder>' option_list = BaseCommand.option_list + ( make_option('-p', '--num_pairs', default=20, dest='num_pairs', help='Num of pairs in each conditions' ), # make_option('-c', '--num_conditions', # default=2, # dest='num_conditions', # help='Num of conditions in this experiment' # ), # make_option('-s', '--num_stages', # default=4, # dest='num_stages', # help='Num of stages in each condition' # ), make_option('-n', '--name', default='Experiment', dest='experiment_name', help='Name of this experiment' ), ) def handle(self, dictionary_id, output_folder, **options): if not dictionary_id: raise CommandError("Dictionary id is required.") try: dictionary_id = int(dictionary_id) except ValueError: raise CommandError("Dictionary id must be a number.") if not output_folder: raise CommandError("Output folder path is required.") num_pairs = options.get('num_pairs') #num_conditions = options.get('num_conditions') #num_stages = options.get('num_stages') experiment_name = options.get('experiment_name') # make sure the folder exists check_or_create_dir(output_folder) output_filename = "%s/user_accounts.log" % output_folder with open(output_filename, "w") as output: with transaction.atomic(savepoint=False): # create an experiment experiment = experiment_models.Experiment(name=experiment_name, saved_path_root=output_folder, dictionary_id=dictionary_id) experiment.save() experiment.initialize_controlled_experiment(#num_conditions=num_conditions, #num_stages=num_stages, num_pairs=num_pairs, output=output)
[ "nanchen.chen@gmail.com" ]
nanchen.chen@gmail.com
0a970ae7098ed4db96e7a3dfb9f6da2a4c8da81d
44064ed79f173ddca96174913910c1610992b7cb
/Second_Processing_app/temboo/Library/Foursquare/Users/CheckinsByUser.py
afc8767ec80d8e6b065d8be4e153e455acb86af8
[]
no_license
dattasaurabh82/Final_thesis
440fb5e29ebc28dd64fe59ecd87f01494ed6d4e5
8edaea62f5987db026adfffb6b52b59b119f6375
refs/heads/master
2021-01-20T22:25:48.999100
2014-10-14T18:58:00
2014-10-14T18:58:00
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,046
py
# -*- coding: utf-8 -*- ############################################################################### # # CheckinsByUser # Retrieve a list of check-ins for an authenticated user. # # Python version 2.6 # ############################################################################### from temboo.core.choreography import Choreography from temboo.core.choreography import InputSet from temboo.core.choreography import ResultSet from temboo.core.choreography import ChoreographyExecution import json class CheckinsByUser(Choreography): def __init__(self, temboo_session): """ Create a new instance of the CheckinsByUser Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. """ Choreography.__init__(self, temboo_session, '/Library/Foursquare/Users/CheckinsByUser') def new_input_set(self): return CheckinsByUserInputSet() def _make_result_set(self, result, path): return CheckinsByUserResultSet(result, path) def _make_execution(self, session, exec_id, path): return CheckinsByUserChoreographyExecution(session, exec_id, path) class CheckinsByUserInputSet(InputSet): """ An InputSet with methods appropriate for specifying the inputs to the CheckinsByUser Choreo. The InputSet object is used to specify input parameters when executing this Choreo. """ def set_AfterTimeStamp(self, value): """ Set the value of the AfterTimeStamp input for this Choreo. ((optional, date) Retrieve the first results after the seconds entered since epoch time.) """ InputSet._set_input(self, 'AfterTimeStamp', value) def set_BeforeTimeStamp(self, value): """ Set the value of the BeforeTimeStamp input for this Choreo. ((optional, date) Retrieve the first results prior to the seconds specified. Useful for paging backward in time.) """ InputSet._set_input(self, 'BeforeTimeStamp', value) def set_Limit(self, value): """ Set the value of the Limit input for this Choreo. ((optional, integer) The total number of results to be returned, up to 250.) """ InputSet._set_input(self, 'Limit', value) def set_OauthToken(self, value): """ Set the value of the OauthToken input for this Choreo. ((required, string) The Foursquare API OAuth token string.) """ InputSet._set_input(self, 'OauthToken', value) def set_Offset(self, value): """ Set the value of the Offset input for this Choreo. ((optional, integer) The number of results to skip. Used to page through results.) """ InputSet._set_input(self, 'Offset', value) def set_ResponseFormat(self, value): """ Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format that response should be in. Can be set to xml or json. Defaults to json.) """ InputSet._set_input(self, 'ResponseFormat', value) def set_UserID(self, value): """ Set the value of the UserID input for this Choreo. ((optional, string) Only 'self' is supported at this moment by the Foursquare API. Defaults to: self.) """ InputSet._set_input(self, 'UserID', value) class CheckinsByUserResultSet(ResultSet): """ A ResultSet with methods tailored to the values returned by the CheckinsByUser Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. """ def getJSONFromString(self, str): return json.loads(str) def get_Response(self): """ Retrieve the value for the "Response" output from this Choreo execution. (The response from Foursquare. Corresponds to the ResponseFormat input. Defaults to JSON.) """ return self._output.get('Response', None) class CheckinsByUserChoreographyExecution(ChoreographyExecution): def _make_result_set(self, response, path): return CheckinsByUserResultSet(response, path)
[ "dattasaurabh82@gmail.com" ]
dattasaurabh82@gmail.com
56a182b4418a7cec1d9e071eadaa0bc1e801a723
e0e6ef2f917a84eca1683db5d590e670a99219ff
/parser/generated/python/arrow.py
ebd03e80bcebc67d66d171b84f8a9c1e8b61729f
[]
no_license
mabudrais/LCLBinding
57bf4ee255493e7d492f04f21e67544edebe70a9
10adee21f65ee0cf5ff533adfc3a402b389442cf
refs/heads/master
2020-04-10T13:20:38.788353
2018-12-22T14:36:07
2018-12-22T14:36:07
161,047,806
0
0
null
null
null
null
UTF-8
Python
false
false
130
py
from Graphics import * from Controls import * from Classes import * from MainPasObject import * import LCLBindingUtil #import end
[ "m.abudrais@yahoo.com" ]
m.abudrais@yahoo.com
6f0f458414950830519af00253a3f12963a9376e
f3e18e8e7e47ec38cc637d96bed55610f7cfd5f0
/smart_card.py
e78861e7da8948a238d6778fa381f08f080a3cdd
[ "MIT" ]
permissive
KVR-ADITYA/IOT-3-level_auth
195a7d575f3c076fa3a920f9fa910c3b2c38527d
0bce66a96fc9834137b4be67ab218828c6478103
refs/heads/main
2023-03-14T09:39:41.759190
2021-02-19T11:02:29
2021-02-19T11:02:29
340,341,687
0
0
null
null
null
null
UTF-8
Python
false
false
14
py
import secrets
[ "noreply@github.com" ]
KVR-ADITYA.noreply@github.com
4a11547d58aecc997ef191b31a60bc45d35cfd4a
456a5bfc9a19fc6a66621f6646fe4d415669de40
/seal_test.py
8b9c9409c268037dbf992181c75515f54d9dcec2
[]
no_license
11uc/WholeCellPatch
d7bf31df4c97608b70c257297e2d163a30eb585d
96e184aa95a42b2a5ad80c2323379177112204c2
refs/heads/master
2020-04-21T22:44:35.756526
2019-02-09T22:58:54
2019-02-09T22:58:54
169,923,090
0
1
null
null
null
null
UTF-8
Python
false
false
14,289
py
#!/usr/local/bin/python3 import math import re import os import numpy as np import pandas as pd from scipy.optimize import curve_fit import matplotlib.pyplot as plt import pyqtgraph as pg import joblib from igor import binarywave from process import DataPrep, SignalProc import plot import util class SealTest(DataPrep, SignalProc): """ Analyze seal tests (short current or voltage steps) to calculate access resistance, input resistance and membrane capacitance of of neurons. """ def __init__(self, paramFile): DataPrep.__init__(self, paramFile) def checkParam(self): required = set(['baseline_start', 'baseline_end', 'steady_state_start', \ 'steady_state_end', 'seal_test_start', 'dV', 'dI', \ "scaleV", "scaleI", "minTau"]) if set(self.params.keys()) != required: raise ValueError def seal_test_v(self, verbose = False): ''' Analysze the seal test part of the trace and calculate the basic properties Parameters: plot (string) - name of the figure of the analysis process, default is empty string and no figure will be saved Properties: Rs (float) - access resistance Ri (float) - input resistance C (float) - membrane compacitance ''' t_baseline1 = self.params['baseline_start'] t_baseline2 = self.params['baseline_end'] t_steady1 = self.params['steady_state_start'] t_steady2 = self.params['steady_state_end'] t_0 = self.params['seal_test_start'] dV = self.params['dV'] scale = self.params["scaleV"] # scale up for better fitting minTau = self.params["minTau"] # minimum tau accepted trace = self.x * scale sr = self.sr I_b = np.mean(trace[int(t_baseline1 * sr):int(t_baseline2 * sr)]) # baseline current before seal test I_s = np.mean(trace[int(t_steady1 * sr):int(t_steady2 * sr)]) # steady state current after the voltage step std_Is = np.std(trace[int(t_steady1 * sr):int(t_steady2 * sr)]) # standard deviation of current at the steady state # used to define boundary for steady state current in fitting fit_fun = lambda t, _I0, _tau, _Is, _t0: _Is + (_I0 - _Is) * \ np.exp(-(t - _t0) / _tau) # exponential function to fit # I0 - current spike right after the voltage step # tau - decay time constant # Is - steady state current of the decay # t0 - start of the decay mf = None # medium fitting threshold trapped = True while trapped: if mf is not None: trace = self.thmedfilt(trace, 5, mf) # fit the exponential decay after the voltage step ft1 = np.argmax(trace[int(t_0 * sr):int(t_steady1 * sr)] * np.sign(dV)) \ + int(t_0 * sr) # index of peak value after the voltage step start of curve fitting ft2 = int(t_steady1 * sr) # index of the start of steady state, end of curve fitting fit_time = np.arange(ft1, ft2) / sr # time array of exponential fit fit_trace = np.array(trace[ft1:ft2]) # trace within the fit time period g_I0 = trace[ft1] # initial guess of I0 g_tau_ind = np.argwhere(np.sign(dV) * (trace[ft1:ft2] - I_s) < \ np.sign(dV) * (g_I0 - I_s) / np.e) g_tau = g_tau_ind[0] / sr # initial guess of tau p_0 = [g_I0, g_tau, I_s, t_0] # initial guess bnd = ([-np.inf, 0, I_s - 3 * std_Is, t_0], \ [I_s, t_steady1 - t_0, I_s + 3 * std_Is, t_steady1]) # bounds try: popt, pcov = curve_fit(fit_fun, fit_time, fit_trace, p0 = p_0) fit_I0, tau, fit_Is, fit_t0 = popt I_0 = fit_fun(ft1 / sr, fit_I0, tau, fit_Is, fit_t0) # Use the current of the fitted curve at the peak time as I0 if verbose or tau < minTau: verbose = True print('I0 = ', I_0) print('tau = ', tau) print('Ib = ', I_b) print('fit_Is = ', fit_Is) print('t0 = ', fit_t0) # pt1 = int(t_0 * sr) # pt2 = int(t_steady1 * sr) pt1 = ft1 pt2 = ft2 plot_time = np.arange(pt1, pt2) / sr if mf is None: plot_trace = np.array(trace[pt1:pt2]) else: plot_trace = self.thmedfilt(np.array(trace[pt1:pt2]), 5, mf) w = pg.GraphicsWindow() ax = w.addPlot() ax.plot(plot_time, plot_trace) ax.plot(plot_time, \ [fit_fun(i, fit_I0, tau, fit_Is, fit_t0) \ for i in plot_time], pen = pg.mkPen('r')) print("Median filter threshold?") ins = input() mf = float(ins) del(w) if mf <= 0: self.R_s, self.R_i, self.C = 0, 0, 0 break else: trapped = False self.R_s = dV / (I_0 - I_b) * scale self.R_i = dV / (I_s - I_b) * scale - self.R_s self.C = tau * (self.R_i + self.R_s) / self.R_i / self.R_s except TypeError: self.R_s, self.R_i, self.C = 0, 0, 0 break except ValueError: # when input is not a number self.R_s = dV / (I_0 - I_b) * scale self.R_i = dV / (I_s - I_b) * scale - self.R_s self.C = tau * (self.R_i + self.R_s) / self.R_i / self.R_s break if verbose: print('Rs = {0:.3e}, Ri = {1:.3e}, C = {2:.3e}'.format(self.R_s, \ self.R_i, self.C)) def seal_test_i(self, verbose = False): ''' Seal test in current clamp, calculate access resistance, input resistance, capacitance. Parameters: trace (array_like) - signal trace sr (float) - sampling rate params (dictionary) - parameters used for seal test analysis comp (boolean) - whether or not the Rs has been compensated Properties: Rs (float) - Access resistance Rin (float) - Input resistance C (float) - Membrane capacitance ''' t_baseline1 = self.params['baseline_start'] t_baseline2 = self.params['baseline_end'] t_steady1 = self.params['steady_state_start'] t_steady2 = self.params['steady_state_end'] t_0 = self.params['seal_test_start'] dI = self.params['dI'] scale = self.params["scaleI"] trace = self.x * scale sr = self.sr minTau = self.params["minTau"] V_b = np.mean(trace[int(t_baseline1 * sr):int(t_baseline2 * sr)]) # baseline current before seal test V_s = np.mean(trace[int(t_steady1 * sr):int(t_steady2 * sr)]) # steady state current after the voltage step std_Vs = np.std(trace[int(t_steady1 * sr):int(t_steady2 * sr)]) # standard deviation of current at the steady state # used to define boundary for steady state current in fitting trapped = True mf = None while trapped: if mf is not None: trace = self.thmedfilt(trace, 5, mf) # fit the exponential decay after the voltage step ind1 = int(t_0 * sr) # index of start of curve fit, assume charging of pipette # capacitance takes no time ind2 = int(t_steady1 * sr) # index of the start of steady state, end of curve fitting fit_time = np.arange(ind1, ind2) / sr # time array of exponential fit fit_trace = np.array(trace[ind1:ind2]) # trace within the fit time period fit_fun = lambda t, _V0, _tau, _Vs, _t0: _Vs + (_V0 - _Vs) * \ np.exp(-(t - _t0) / _tau) # exponential function to fit # V0 - volrage after the voltage jump due to the access resistance # tau - decay time constant # Vs - steady state potential of the decay # t0 - start of the decay g_V0 = trace[ind1] # initial guess of V0 g_tau_ind = np.argwhere(np.sign(dI) * (trace[ind1:ind2] - V_s) > \ np.sign(dI) * (g_V0 - V_s) / np.e) g_tau = g_tau_ind[0][0] / sr # initial guess of tau p_0 = [g_V0, g_tau, V_s, t_0] # initial guess bnd = ([-np.inf, 0, V_s - 3 * std_Vs, t_0], \ [V_s, t_steady1 - t_0, V_s + 3 * std_Vs, t_steady1]) # bounds try: popt, pcov = curve_fit(fit_fun, fit_time, fit_trace, p0 = p_0) fit_V0, tau, fit_Vs, fit_t0 = popt V_0 = fit_fun(ind1 / sr, fit_V0, tau, fit_Vs, fit_t0) if verbose or tau < minTau: verbose = True print('Vs = ', V_s) print('V0 = ', V_0) print('tau = ', tau) print('Vb = ', V_b) print('fit_Vs = ', fit_Vs) print('t0 = ', fit_t0) # ind1 = int(t_0 * sr) # ind2 = int(t_steady1 * sr) plot_time = np.arange(ind1, ind2) / sr if mf is None: plot_trace = np.array(trace[ind1:ind2]) else: plot_trace = self.thmedfilt(np.array(trace[ind1:ind2]), 5, mf) w = pg.GraphicsWindow() ax = w.addPlot() ax.plot(plot_time, plot_trace) ax.plot(plot_time, \ [fit_fun(i, fit_V0, tau, fit_Vs, fit_t0) \ for i in plot_time], pen = pg.mkPen('r')) ins = input() mf = float(ins) del(w) if mf <= 0: # input 0 or negative values to drop the results self.R_s, self.R_i, self.C = 0, 0, 0 break else: trapped = False self.R_s = (V_0 - V_b) / dI / scale self.R_i = (V_s - V_b) / dI / scale - self.R_s self.C = tau / self.R_i except TypeError: self.R_s, self.R_i, self.C = 0, 0, 0 break except ValueError: # when input is not a number, accept the result self.R_s = (V_0 - V_b) / dI / scale self.R_i = (V_s - V_b) / dI / scale - self.R_s self.C = tau / self.R_i break if verbose: print('Rs = {0:.3e}, Ri = {1:.3e}, C = {2:.3e}'.format(self.R_s, \ self.R_i, self.C)) def getProperties(self, pName): """ Retrieve seal tests properties. """ if pName == "Rin": return self.R_i elif pName == "Rs": return self.R_s elif pName == "C": return self.C elif pName == "tau": return self.R_i * self.C def batchAnalyze(self, dataFolder, output, reportF = "", \ dumpF = "", vclamp = True, verbose = 1): """ Batch mini analysis. Arguments: dataFolder (string) - raw trace data folder. output (string) - csv file with the indices of neurons to analyze. reportF (string) - output text file with seal tests results for all trials. dumpF (string) - data file to store analyzed data to for future use. vclamp (bool) - whether the data is from voltage clamp or currrent clamp. verbose (int) - verbose levels 0: no cli output 1: print cell numbers 2: print cell, trial number, plot fitting result """ if dataFolder[-1] != os.sep: dataFolder += os.sep name_params = util.get_name_params() data_files = os.listdir(dataFolder) df = pd.read_csv(output, index_col = 0) if len(dumpF): try: dp = joblib.load(dumpF) except (EOFError, IOError): dp = {} if len(reportF): rp = open(reportF, "w") for c in df.index: if verbose: print("Cell: {:d}".format(c)) rss = [] ris = [] cs = [] rp.write('\n' + name_params['prefix'] + ('_{0:0'+ name_params['pad'] + \ 'd}:').format(c) + '\n') for data_file in data_files: matched = re.match(name_params['prefix'] + name_params['link'] + \ '{:04d}'.format(c) + name_params['link'] + \ '0*([1-9][0-9]*)' + name_params['suffix'] , data_file) if matched: t = int(matched.group(1)) if verbose > 1: print("Trial: {:d}".format(t)) if "dp" in locals() and self.stored(dp, c, t): self.retrieve(dp, c, t) else: self.loadData(dataFolder, c, t) if vclamp: self.seal_test_v(verbose > 1) else: self.seal_test_i(verbose > 1) if "dp" in locals() and not self.stored(dp, c, t): self.store(dp, c, t) if self.getProperties("Rin") > 0: rss.append(self.getProperties("Rs")) ris.append(self.getProperties("Rin")) cs.append(self.getProperties("C")) rp.write('\t{0:d} Rs:{1:3.2f}; Ri:{2:3.2f}; C:{3:4.3f}\n'. format(t, rss[-1] / 1e6, ris[-1] / 1e6, cs[-1] * 1e9)) if len(rss): mrs = np.mean(rss) mri = np.mean(ris) mc = np.mean(cs) mtau = np.mean(np.array(ris) * np.array(cs)) else: mrs, mri, mc, mtau = np.nan, np.nan, np.nan, np.nan df.loc[c, "Rin"] = mri / 1e6 # Update Rs and tau only in voltage clamp because I usually have # Rs compensation on in current clamp and the seal test results # are not accurate. if vclamp: df.loc[c, "Rs"] = mrs / 1e6 df.loc[c, "mTau"] = mtau rp.write('\tMean:\n') rp.write('\tRs:{0:3.2f}; Ri:{1:3.2f}; C:{2:4.3f}\n'.format(\ mrs / 1e6, mri / 1e6, mc * 1e9)) if len(dumpF): joblib.dump(dp, dumpF) if len(reportF): rp.close() df.to_csv(output) def store(self, dp, c, t): if c not in dp: dp[c] = {} dp[c][t] = [self.R_s, self.R_i, self.C] def stored(self, dp, c, t): return len(dp) and c in dp and len(dp[c]) and t in dp[c] def retrieve(self, dp, c, t): [self.R_s, self.R_i, self.C] = dp[c][t] def filterRs(self, dumpF, maxRs, output, trialOut, filterBy = "trial"): ''' For voltage clamp seal tests, remove trials with access resistance above maxRs, write the remaining trial numbers to file output, and return mean Rs and Rin for each cell of the remaining trials. arguments: dumpF (string) - stored batch seal test results. maxRs (float) - upper threshold of Rs. output (String) - directory to summary output file, mean values trialOut (string) - output file for selected trials filterBy (string) - filter criterion "trial": remove trials with to high Rs "cells": remove cells with one trial that is above threshold ''' selected = {} dp = joblib.load(dumpF) df = pd.read_csv(output, index_col = 0) for c, vc in dp.items(): srs, sri, stau = 0, 0, 0 selected[c] = [] for t, vt in vc.items(): if vt[0] < maxRs and 0 < vt[0]: selected[c].append(t) srs += vt[0] sri += vt[1] stau += vt[2] * vt[1] elif filterBy == "cell": srs = np.nan sri = np.nan stau = np.nan if len(selected[c]): df.loc[c, "Rs"] = srs / len(selected[c]) / 1e6 df.loc[c, "Rin"] = sri / len(selected[c]) / 1e6 df.loc[c, "mTau"] = stau / len(selected[c]) else: df.loc[c, "Rs"] = np.nan df.loc[c, "Rin"] = np.nan df.loc[c, "mTau"] = np.nan df.to_csv(output) # write file with open(trialOut, 'w') as f: for k in sorted(selected): s = "{:d}: ".format(k) for t in selected[k]: s += str(t) s += "," s = s[:-1] + "\n" f.write(s) def ICnoise(trace, sr, begin, end): ''' noise r ICnoise(trace, sr, begin, end) Calculate std of sample points in trace within a certein time range to represent noise. Parameters: trace (array_like) - signal data sr (float) - sampling rate begin (float) - start point of the time range end (float) - end point of the time range Return: noise (float) - std as noise level ''' return np.std(trace[int(begin * sr):int(end * sr)])
[ "liuchenghao44@gmail.com" ]
liuchenghao44@gmail.com
b203df8ac8d4069daeb7d969a706e5ce937e6732
7c82a7a1537a03e9773cf5dee200999f045b323a
/4.1.3 Abstract Data Types/queue.py
735a51fd8f34362d50b31c3b021487813614bd03
[]
no_license
danielgunn/A-Level-CS
fd21038153131a41037fdc83a4ec474bf3c0e927
c9e214f3d8494c19ecf21b4a657e3b710dc214ea
refs/heads/master
2023-03-19T11:03:06.884200
2021-03-12T03:05:57
2021-03-12T03:05:57
103,843,064
3
1
null
null
null
null
UTF-8
Python
false
false
385
py
from list import List class Queue: l = List() def enqueue(self, value): self.l.add(value) def dequeue(self): if self.l.is_empty(): print("Error: dequeue attempt on empty queue") return None else: v = self.l.head.data self.l.remove(0) return v if __name__ == "__main__": help(Queue)
[ "4oESUv0U" ]
4oESUv0U
c2c535523afc8cbd95e7a52e74520c02f2fbc22c
122299087e4b1e83f8b18fa8d2aa914b19091315
/tree_bfs/boundary_binary_tree.py
d9e17312b322555fefd99fa22dbd47416b653ae2
[]
no_license
federicociner/leetcode
522254c59d15a3145a81905d9bb8889736d68ad2
5595ef27cf88a93fa639155180d4b3305438fa2c
refs/heads/master
2020-11-26T02:37:58.431440
2020-07-08T23:45:23
2020-07-08T23:45:23
228,939,486
0
0
null
null
null
null
UTF-8
Python
false
false
4,486
py
"""Given a binary tree, return the values of its boundary in anti-clockwise direction starting from root. Boundary includes left boundary, leaves, and right boundary in order without duplicate nodes. (The values of the nodes may still be duplicates.) Left boundary is defined as the path from root to the left-most node. Right boundary is defined as the path from root to the right-most node. If the root doesn't have left subtree or right subtree, then the root itself is left boundary or right boundary. Note this definition only applies to the input binary tree, and not applies to any subtrees. The left-most node is defined as a leaf node you could reach when you always firstly travel to the left subtree if exists. If not, travel to the right subtree. Repeat until you reach a leaf node. The right-most node is also defined by the same way with left and right exchanged. Example 1 Input: 1 \ 2 / \ 3 4 Ouput: [1, 3, 4, 2] Explanation: The root doesn't have left subtree, so the root itself is left boundary. The leaves are node 3 and 4. The right boundary are node 1,2,4. Note the anti-clockwise direction means you should output reversed right boundary. So order them in anti-clockwise without duplicates and we have [1,3,4,2]. Example 2 Input: ____1_____ / \ 2 3 / \ / 4 5 6 / \ / \ 7 8 9 10 Ouput: [1,2,4,7,8,9,10,6,3] Explanation: The left boundary are node 1,2,4. (4 is the left-most node according to definition) The leaves are node 4,7,8,9,10. The right boundary are node 1,3,6,10. (10 is the right-most node). So order them in anti-clockwise without duplicate nodes we have [1,2,4,7,8,9, 10,6,3]. """ from typing import List class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def __str__(self, level=0): ret = "\t" * level + f"TreeNode: {repr(self.val)}" + "\n" if self.left: ret += self.left.__str__(level + 1) if self.right: ret += self.right.__str__(level + 1) return ret def __repr__(self): return "<tree node representation>" class Solution: # Time complexity: O(n) # Space complexity: O(n) def boundaryOfBinaryTree(self, root: TreeNode) -> List[int]: if not root: return [] # Initialise boundary array boundary = [] if not self.is_leaf(root): boundary.append(root.val) # Get left boundary nextNode = root.left while nextNode: if not self.is_leaf(nextNode): boundary.append(nextNode.val) if nextNode.left: nextNode = nextNode.left else: nextNode = nextNode.right # Get leaves self.find_leaves(root, boundary) # Get right boundary stack = [] nextNode = root.right while nextNode: if not self.is_leaf(nextNode): stack.append(nextNode.val) if nextNode.right: nextNode = nextNode.right else: nextNode = nextNode.left while stack: boundary.append(stack.pop()) return boundary def find_leaves(self, node: TreeNode, boundary: List[int]) -> None: if self.is_leaf(node): boundary.append(node.val) else: if node.left: self.find_leaves(node.left, boundary) if node.right: self.find_leaves(node.right, boundary) def is_leaf(self, node: TreeNode) -> bool: return node.left is None and node.right is None if __name__ == "__main__": S = Solution() # Example 1 root = TreeNode(1) n1 = TreeNode(2) n2 = TreeNode(3) n3 = TreeNode(4) root.right = n1 n1.left = n2 n1.right = n3 assert S.boundaryOfBinaryTree(root) == [1, 3, 4, 2] # Example 2 root = TreeNode(1) n2 = TreeNode(2) n3 = TreeNode(3) n4 = TreeNode(4) n5 = TreeNode(5) n6 = TreeNode(6) n7 = TreeNode(7) n8 = TreeNode(8) n9 = TreeNode(9) n10 = TreeNode(10) root.left = n2 root.right = n3 n2.left = n4 n2.right = n5 n5.left = n7 n5.right = n8 n3.left = n6 n6.left = n9 n6.right = n10 assert S.boundaryOfBinaryTree(root) == [1, 2, 4, 7, 8, 9, 10, 6, 3] print("All tests passed.")
[ "federico.ciner1@cba.com.au" ]
federico.ciner1@cba.com.au
3963154da5f61758bf4e8a20d537670d2f773f88
32712c478ff9dff44de085cb50a1302bfc2eba67
/badges/admin.py
2de5a06f7d80c1a5d79728e5e31948ebe2e57d9b
[ "MIT" ]
permissive
vas3k/vas3k.club
158af17c329fe693178ca1bce36466922604df3b
b3ff2fd95ef1d6c593c57d3bcd501240f2705fbb
refs/heads/master
2023-09-03T07:10:10.859004
2023-09-01T09:08:32
2023-09-01T09:08:32
254,190,180
697
326
MIT
2023-09-04T09:02:12
2020-04-08T20:11:44
Python
UTF-8
Python
false
false
635
py
from django.contrib import admin from badges.models import Badge, UserBadge class BadgesAdmin(admin.ModelAdmin): list_display = ( "code", "title", "description", "price_days", "created_at", "is_visible", ) ordering = ("-created_at",) search_fields = ["title"] admin.site.register(Badge, BadgesAdmin) class UserBadgesAdmin(admin.ModelAdmin): list_display = ( "badge", "from_user", "to_user", "post", "comment", "created_at", ) ordering = ("-created_at",) admin.site.register(UserBadge, UserBadgesAdmin)
[ "me@vas3k.ru" ]
me@vas3k.ru
cfa36cbaa10d6086ca5294bb9709785974e89d6f
05786ed35013dbc5c19f89c76b4bc4f820922536
/quizzler-app-start/quiz_brain.py
cdbaf36ea97413294322b2663584daf40e1e3883
[]
no_license
nope2jope/quiz_this
dc6888f8527d759a5efd7943d198011c3955b18b
756ed9de4a2ba83c07ecc72764bbfe1c039bfe4c
refs/heads/main
2023-03-01T03:31:50.278117
2021-02-03T23:37:11
2021-02-03T23:37:11
335,784,543
0
0
null
null
null
null
UTF-8
Python
false
false
877
py
import html class QuizBrain: def __init__(self, q_list): self.question_number = 0 self.score = 0 self.question_list = q_list self.current_question = None def still_has_questions(self): return self.question_number < len(self.question_list) def next_question(self): try: self.current_question = self.question_list[self.question_number] except IndexError: return f"HERE WE GO" else: self.question_number += 1 q_text = html.unescape(self.current_question.text) return f"Q.{self.question_number}: {q_text}" def check_answer(self, user_answer): correct_answer = self.current_question.answer if user_answer == correct_answer: self.score += 1 return 'True' else: return 'False'
[ "noreply@github.com" ]
nope2jope.noreply@github.com
ae426f722f6003fbb33283a0eff3cd2e112d90a5
38d1ef01184bbdb3898b8cf495eeee48eaa1a30a
/koopman_modes_rollout_helper.py
74e2f5017ccef64bcd860f6f4a057a8b58b141c7
[]
no_license
LenCewa/MasterThesis
39c86c8ab3c752fedc445fea14368bbd74ca8f3a
b2d4d67b7ae2f363dd627ecb4355de1ae6ef04a3
refs/heads/master
2020-06-16T15:47:29.971151
2020-04-15T09:29:43
2020-04-15T09:29:43
195,626,164
0
1
null
null
null
null
UTF-8
Python
false
false
4,627
py
from Fourier import dFourier, ddFourier from evaluate_parameter_koopman import * import matplotlib.pyplot as plt # Newtons Optimization Method dN=N ddN=N d_fourier = dFourier(1, 1, 0.001, N, 450, [], []) dd_fourier = ddFourier(1, 1, 0.001, N, 450, [], []) def set_dfourier_coefficients(c, N): for i in range(N + 1): # N = 15 impliziert [a0, [a1, b1], ..., [a15, b15]] also 16 Listenelemente d_fourier.coefficients[i] = jnp.array(c[i]) def set_ddfourier_coefficients(c, N): for i in range(N + 1): # N = 15 impliziert [a0, [a1, b1], ..., [a15, b15]] also 16 Listenelemente dd_fourier.coefficients[i] = jnp.array(c[i]) def Loss(x, y): gx = [] for c in loc: set_fourier_coefficients(c, N) gx += [fourier.predict(fourier.coefficients, x)] gx = np.array(gx) return np.linalg.norm(gx - y)**2 def dLoss(x, y): gx = [] dgx = [] dL = 0 for c in loc: set_fourier_coefficients(c, N) set_dfourier_coefficients(c, dN) gx += [fourier.predict(fourier.coefficients, x)] dgx += [d_fourier.predict(d_fourier.coefficients, x)] gx = np.array(gx) dgx = np.array(dgx) for i in range(dim): dL += 2 * (y[i] - gx[i]) * (-dgx[i]) return dL def ddLoss(x, y): gx = [] dgx = [] ddgx = [] ddL = 0 for c in loc: set_fourier_coefficients(c, N) set_dfourier_coefficients(c, dN) set_ddfourier_coefficients(c, ddN) gx += [fourier.predict(fourier.coefficients, x)] dgx += [d_fourier.predict(d_fourier.coefficients, x)] ddgx += [dd_fourier.predict(dd_fourier.coefficients, x)] gx = np.array(gx) dgx = np.array(dgx) ddgx = np.array(ddgx) for i in range(dim): ddL += 2 * (dgx[i] ** 2 - (y[i] - gx[i]) * ddgx[i]) return ddL def Loss_alphad(x, y, alpha, d): gx_alphad = [] for c in loc: set_fourier_coefficients(c, N) gx_alphad += [fourier.predict(fourier.coefficients, x + alpha * d)] gx_alphad = np.array(gx_alphad) return np.linalg.norm(gx_alphad - y)**2 def newton_optimization_method(y, x0, iterations, alpha0, damping0): res = [x0] err = [] alpha = alpha0 damping = damping0 roh = [1.2, 0.5, 1, 0.5, 0.01] for k in range(iterations): x = res[k] L = Loss(x, y) err += [L] print("Iteration: k = ", k, "--> Error ||y - g(x_k)||^2 = ", L, " for x = ", x) if L < 1e-10: break dL = dLoss(x, y)[0] ddL = ddLoss(x, y)[0] d = -dL / (ddL + damping) L_alphad = Loss_alphad(x, y, alpha, d) i = 0 while L_alphad > (L + roh[4]*dL * alpha * d): print("Iteration: ", k, " while-loop: ", i) # print("f(x + alpha * d) = ", gx_alphad, " > f(x) + r*f'(x) = ", g_x + roh[4] * dL) i += 1 alpha = roh[1] * alpha # Optionally: damping = roh[2] * damping d = -dL / (ddL + damping) L_alphad = Loss_alphad(x, y, alpha, d) x = x + alpha * d res += [x] alpha = np.min([roh[0], alpha, 1]) # Optinally: damping = roh[3] * damping return res, err reconstruct = [] reconstruct_error = [] alpha0 = 1 damping0 = 0.999 rollout_list = [50, 1] for r in rollout_list: print("H1") Y = koopman_mpc_rollout_prediction(K, r, steps, dim, 0).reshape(1, -1) print(Y.shape) for i in range(dim - 1): print("Compute Y, iteration = ",i) Y = np.append(Y, koopman_mpc_rollout_prediction(K, r, steps, dim, i + 1).reshape(1, -1), axis=0) Y = np.array(Y) print("Shape of Y:", Y.shape) reconstruct = [] reconstruct_error = [] newton_steps = 20 for t in range(len(trajectory)): #Y.shape[1] Y.shape[1]-1 print("Iteration: ", t, " / 500 and rollout = ", r) res, err = newton_optimization_method(Y[:, t*r].reshape(-1, 1), trajectory[t], newton_steps, alpha0, damping0) reconstruct += [res[-1]] reconstruct_error += [err[-1]] for m in range(r-1): res, err = newton_optimization_method(Y[:, t*r+m+1].reshape(-1, 1), reconstruct[t*r+m], newton_steps, alpha0, damping0) reconstruct += [res[-1]] reconstruct_error += [err[-1]] # save reconstrcted trajectory after every 50 iteration np.save("Reconstructions_RollOut/" + "mpc_rollout_length=" + str(r) + "_basis=" + str(basis_vector), reconstruct) np.save("Reconstruction_Errors_RollOut/" + "mpc_rollout_length=" + str(r) + "_basis=" + str(basis_vector), reconstruct_error)
[ "len13@hotmail.de" ]
len13@hotmail.de
ed6444d14e4a48cf3c0e7007bcd0b884296aabd8
809b2d40a02e85e3d5a75ae16f2a776e2918d125
/lecture2.py
6276d8c93198846c05998305ce41cd08c2927ca5
[]
no_license
ethanmatthews/Matthews-Assignment2
25e7441f15bd6eb4a558ab7a65cc1c0648dbe4b1
8e089c9a41ac5a65bc8170fedc0fa15971bf062e
refs/heads/master
2022-12-17T07:42:20.515983
2020-09-21T04:19:34
2020-09-21T04:19:34
295,560,966
0
0
null
null
null
null
UTF-8
Python
false
false
3,729
py
# # This is a human readable message # ''' # This is also a # human readable message # ''' # # print("This statement will not print") # ''' # print("These statements") # print("will not print") # ''' # # Display two strings on separate lines # print("Marc") # print("Hauschildt") # # Display two print statements on a single line, separated by a space # print("Hauschildt") # # Display two strings on a single line, separated by a space # print("Marc", "Hauschildt") # print("Marc " + "Hauschildt") # You have to manually add the space here # # Display two strings on a single line, separated by a period # # Display a string with a quotation mark # print("My fantasy football team name is the \"Bootleggers\"") # # Display a string with a back slash # print("C:\\Users\\k0519415") # # Display a string with a new line escape # print("The quick brown fox\njumped over the lazy dog") # # Display a string with a tab character # name = "Jennifer" # age = 19 # print("Name\t\tAge") # print(name + "\t" + str(age)) # # Display decimals rounded to two decimal places # print("Product\t\tPrice") # print("Bananas\t\t" + "$" + format(0.789, ".2f")) # print("Apples\t\t" + "$" + format(1.211, ".2f")) # # Display commas separating large numbers with decimals aligned # print("Product\t\tPrice") # print("Bugatti\t\t" + "$" + format(1000000, "12,.2f")) # print("F-150\t\t" + "$" + format(55000, "12,.2f")) # # Display commas separating large numbers with decimals aligned # print("How a baby spends its day:") # print("Eating\t\t" + format(0.25, ".0%")) # print("Sleeping\t" + format(0.75, ".0%")) # print("I am " + str(19) + " years old") # score = 0 # score = score + 20 # print(score) # 20 # score += 20 # print(score) # 40 # score = score - 15 # print(score) # 25 # score -= 15 # print(score) # 10 # import math # print(math.pow(2, 3)) # 8.0 - similar to 2 ** 3, but the result is a float # print(math.sqrt(25)) # 5.0 - square root # print(math.pi) # 3.141592653589793 # print(math.ceil(2.5)) # 3 - round up to nearest integer # print(math.floor(2.5)) # 2 - round down to nearest integer # print(round(2.555, 2)) # 2.56 - round up or down # print(round(2.554, 2)) # 2.55 - round up or down # print(math.fabs(-10)) # 10.0 - absolute value, distance from 0 # side1Length = 3 # side2Length = 4 # hypotenuse = math.sqrt(side1Length ** 2 + side2Length ** 2) # Pythagorean theorem # print(hypotenuse) # 5.0 # radius = 3 # areaOfCircle = math.pi * math.pow(radius, 2) # print(areaOfCircle) ''' Problem 1. Superfluous Buns Format: - variable_name, data_type, data_source, example Input(s): - number_of_guests, int, from the user, 125 - hotdogs_per_guest, float, from the user, 1.25 - HOTDOGS_PER_PACK, int, constant, 8 - BUNS_PER_PACK, int, constant, 12 Process(es): - min_hotdogs_needed, int, math.ceil(number_of_guests * hotdogs_per_guest), 157 - hotdog_packages, int, math.ceil(min_hotdogs_needed / HOTDOGS_PER_PACK), 20 - hotdog_count, int hotdog_packages * HOTDOGS_PER_PACK, 160 - bun_packages, int, math.ceil(hotdog_count / BUNS_PER_PACK), 14 - bun_count, int, bun_packages * BUNS_PER_PACK, 168 - extra_hotdogs, int, hotdog_count - min_hotdogs_needed, 3 - extra_buns, int, bun_count - min_hotdogs_needed, 11 Output(s): - hotdog_packages - bun_packages - extra_hotdogs - extra_buns ''' # # Type your code here # import math # number_of_guests = int(input("How many guests?")) #125 # dogs_per_guest = float(input("How many hotdogs per guest?")) #1.25 # DOGS_PER_PACK = 8 # BUNS_PER_PACK = 12 # min_dogs_needed = math.ceil(number_of_guests * dogs_per_guest) #157.0 # print(min_dogs_needed) # hotdog_packages = math.ceil(min_dogs_needed / DOGS_PER_PACK) #20.0 # print(hotdog_packages)
[ "ethan-matthews@student.kirkwood.edu" ]
ethan-matthews@student.kirkwood.edu
9d693845b36a0a9f1657a290629bbc8933bb867f
751a8a16290fb709deaca4d52226b48f587f3cdd
/check.spec
0060f829e2d5a9207e836540185e985340964b3a
[]
no_license
aibotez/ip
0b8069d413d45752491b3e7452b37fde080c6c5f
3ee48c030e16f0c9f5425e82c91ad7e528d25e43
refs/heads/master
2020-04-24T22:24:30.591960
2019-02-24T07:57:39
2019-02-24T07:57:39
172,311,038
0
0
null
null
null
null
WINDOWS-1252
Python
false
false
845
spec
# -*- mode: python -*- block_cipher = None a = Analysis(['check.py'], pathex=['G:\\python\\ÏîÄ¿\\´úÀí'], binaries=[], datas=[], hiddenimports=[], hookspath=[], runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher, noarchive=False) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE(pyz, a.scripts, a.binaries, a.zipfiles, a.datas, [], name='check', debug=False, bootloader_ignore_signals=False, strip=False, upx=True, runtime_tmpdir=None, console=True )
[ "2290227486@qq.com" ]
2290227486@qq.com
c8cd0530837fc1343888c978be7360120bd9cb36
b20ded7b01710508b09496a657a21e626818769c
/batch_crawl_of_key_words.py
c3c1d67428e554343096cdc13330bed14b77a113
[]
no_license
cash2one/cwq-crawler
b991876a08c08030e5e71caa60fe5291c39747c4
301ef9aa8f6551a9fb31a3957a1d4e5353a7bc0b
refs/heads/master
2021-01-22T16:04:56.680827
2016-05-30T03:30:33
2016-05-30T03:30:33
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,924
py
#-*- coding: utf-8 -*- """ 读取excel, 逐次抓取每个关键词的一定数目的top商品 每个关键词的top商品对应一个文件, 文件名以关键词进行区分 """ import xlrd import xlwt import os import re import httplib2 from pyquery import PyQuery from utils import extractNum default_prefix = "C:/users/chenweiqiang/Desktop/" keys = [] def get_keys(filename, prefix=default_prefix): file = os.path.join(prefix, filename) wb = xlrd.open_workbook(file) ws = wb.sheets()[0] for index in range(1, ws.nrows): keys.append(ws.cell(index, 0).value) def iterator(merchants): amazon_base1="http://www.amazon.com/s/ref=nb_sb_noss?keywords=" amazon_base2="&sort=review-rank" aliexpress_base1="http://www.aliexpress.com/wholesale?SearchText=" aliexpress_base2="&shipCountry=us&SortType=total_tranpro_desc&g=n" dhgate_base1="http://www.dhgate.com/wholesale/search.do?searchkey=" dhgate_base2="&searchSource=sort&stype=down&sinfo=reviewavgscore" for item in keys: if 'amazon' in merchants: amazon_url = amazon_base1 + item.replace(" ", "+") + amazon_base2 process_amazon(amazon_url, item) if 'aliexpress' in merchants: aliexpress_url = aliexpress_base1 + item.replace(" ", "+") + aliexpress_base2 process_aliexpress(aliexpress_url, item) if 'dhgate' in merchants: dhgate_url = dhgate_base1 + item.replace(" ", "+") + dhgate_base2 process_dhgate(dhgate_url, item) def process_amazon(entance_url, item): current_url = entance_url count = 0 wb = xlwt.Workbook(encoding="utf-8") ws = wb.add_sheet("sheet1") ws.write(0,0,"name") ws.write(0,1,"price") ws.write(0,2,"product_url") ws.write(0,3,"img_url") ws.write(0,4,"reviews") while True: content = fetch_page_content(current_url) doc = PyQuery(content) nodeList = doc("div#atfResults > ul#s-results-list-atf > li") #前六个 nodeList_other = doc('div#btfResults > ul > li') nodeList.extend(nodeList_other) for node in nodeList: nodeQ = PyQuery(node) name = nodeQ('h2').parent('a').attr('title') product_url = nodeQ('h2').parent('a').attr('href') img_url = nodeQ('img.s-access-image').attr('src') price = nodeQ('span.s-price').text() reviews = nodeQ('div[class="a-row a-spacing-mini"] > a[class="a-size-small a-link-normal a-text-normal"]').remove('span').text() if not reviews: reviews = nodeQ('div[class="a-row a-spacing-top-mini a-spacing-none"] > a[class="a-size-small a-link-normal a-text-normal"]').remove('span').text() reviews = re.sub("See.*",'', reviews).strip() count += 1 ws.write(count,0,name) ws.write(count,1,price) ws.write(count,2,product_url) ws.write(count,3,img_url) ws.write(count,4,reviews) current_url = parseNextPage(doc, current_url) if count >= 100: break wb.save("./output/amazon-" + item + ".xls") def process_aliexpress(entance_url, item): current_url = entance_url count = 0 wb = xlwt.Workbook(encoding="utf-8") ws = wb.add_sheet("sheet1") ws.write(0,0,"name") ws.write(0,1,"price") ws.write(0,2,"product_url") ws.write(0,3,"img_url") ws.write(0,4,"reviews") ws.write(0,5,"sold") while True: content = fetch_page_content(current_url) doc = PyQuery(content) #失败: http://www.aliexpress.com/wholesale?SearchText=wall+clock&shipCountry=us&SortType=total_tranpro_desc nodeList = doc("li.list-item") #只能获取3个 doc_part = PyQuery(doc('script#lazy-render').text()) otherNodeList = doc_part("li.list-item") nodeList.extend(otherNodeList) for node in nodeList: nodeQ = PyQuery(node) name = nodeQ('div.detail > h3 > a').eq(0).attr('title') product_url = nodeQ('div.detail> h3 > a').eq(0).attr('href') img_url = nodeQ('div.img > a > img.picCore').attr('src') price = nodeQ('span.price').text() reviews = extractNum(nodeQ('div.rate-history > a[class="rate-num "]').text()) orders = extractNum(nodeQ('a[class="order-num-a "] > em').text()) count += 1 ws.write(count,0,name) ws.write(count,1,price) ws.write(count,2,product_url) ws.write(count,3,img_url) ws.write(count,4,reviews) ws.write(count,5,orders) current_url = parseAliexpressNextPageUrl(doc, current_url) if count >= 100: break wb.save("./output/aliexpress-" + item + ".xls") def process_dhgate(entance_url, item): current_url = entance_url count = 0 wb = xlwt.Workbook(encoding="utf-8") ws = wb.add_sheet("sheet1") ws.write(0,0,"name") ws.write(0,1,"price") ws.write(0,2,"product_url") ws.write(0,3,"img_url") ws.write(0,4,"reviews") ws.write(0,5,"sold") while True: if not current_url: break content = fetch_page_content(current_url) doc = PyQuery(content) nodeList = doc("div.listitem") for node in nodeList: nodeQ = PyQuery(node) name = nodeQ('h3.pro-title > a').text() product_url = nodeQ('h3.pro-title > a').attr('href') img_url = nodeQ('div.photo > a.pic > img').attr('src') price = nodeQ('ul.pricewrap > li.price').text() reviews = extractNum(nodeQ('span.reviewnum').text()) spanList = nodeQ('span') orders = None for span in spanList: spanQ = PyQuery(span) if spanQ.text().startswith("Sold"): orders = extractNum(spanQ.text()) count += 1 ws.write(count,0,name) ws.write(count,1,price) ws.write(count,2,product_url) ws.write(count,3,img_url) ws.write(count,4,reviews) ws.write(count,5,orders) current_url = parseDhgateNextPageUrl(doc, current_url) if count >= 100: break wb.save("./output/dhgate-" + item + ".xls") def parseNextPage(doc, url): return "http://www.amazon.com" + doc('a#pagnNextLink').attr('href') def parseAliexpressNextPageUrl(doc, url): return doc('a.page-next').attr('href') def parseDhgateNextPageUrl(doc, url): return doc('a.next').attr('href') def fetch_page_content(url): h = httplib2.Http() response, content = h.request(url) if response.status == 200: return content if __name__ == '__main__': #merchants = ['amazon', 'aliexpress', 'dhgate'] merchants = ['dhgate'] get_keys(u'Homer Dector CT关键词.xlsx') #必须加u iterator(merchants)
[ "chenweiqiang@lightinthebox.com" ]
chenweiqiang@lightinthebox.com
c3d983f043466d2017b451a515eb6e63f8395cdf
0e1fbfa23989dd5679d272b12c1e3d2080f2feb2
/mmcv/utils/ext_loader.py
2a3c223838126e146160612724bf73f0b60f0d20
[ "Apache-2.0" ]
permissive
LuGuo1920/mmcv
dae1003f63ce23d5cfc58b27c0c620a61cc5323e
76d9bf1efb052785fea95cb157288a102976a49e
refs/heads/master
2023-05-30T08:11:36.148373
2021-06-28T09:31:36
2021-06-28T09:31:36
381,047,895
1
0
Apache-2.0
2021-06-28T13:49:28
2021-06-28T13:49:27
null
UTF-8
Python
false
false
1,924
py
import importlib import os import pkgutil import warnings from collections import namedtuple import torch if torch.__version__ != 'parrots': def load_ext(name, funcs): ext = importlib.import_module('mmcv.' + name) for fun in funcs: assert hasattr(ext, fun), f'{fun} miss in module {name}' return ext else: from parrots import extension from parrots.base import ParrotsException has_return_value_ops = [ 'nms', 'softnms', 'nms_match', 'nms_rotated', 'top_pool_forward', 'top_pool_backward', 'bottom_pool_forward', 'bottom_pool_backward', 'left_pool_forward', 'left_pool_backward', 'right_pool_forward', 'right_pool_backward', 'fused_bias_leakyrelu', 'upfirdn2d', 'ms_deform_attn_forward', ] def get_fake_func(name, e): def fake_func(*args, **kwargs): warnings.warn(f'{name} is not supported in parrots now') raise e return fake_func def load_ext(name, funcs): ExtModule = namedtuple('ExtModule', funcs) ext_list = [] lib_root = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) for fun in funcs: try: ext_fun = extension.load(fun, name, lib_dir=lib_root) except ParrotsException as e: if 'No element registered' not in e.message: warnings.warn(e.message) ext_fun = get_fake_func(fun, e) ext_list.append(ext_fun) else: if fun in has_return_value_ops: ext_list.append(ext_fun.op) else: ext_list.append(ext_fun.op_) return ExtModule(*ext_list) def check_ops_exist(): ext_loader = pkgutil.find_loader('mmcv._ext') return ext_loader is not None
[ "noreply@github.com" ]
LuGuo1920.noreply@github.com
1c54275b907380b5fa2c52e4721bd84443bb77a7
1b5c808e51cd6cd945748a14d735f72841871575
/scripts/ksap_exploit.py
51970dcc196f50fa2f50a60edb51fb230c1a7426
[]
no_license
zlmone/SecSysEngCtfSS14
1ba0c4f9f121b5a694dfd718506378358ab9148e
e22721a8a75de18f7d112449f2151ee144f64893
refs/heads/master
2021-05-27T19:37:07.221611
2014-06-04T13:38:42
2014-06-04T13:38:42
null
0
0
null
null
null
null
UTF-8
Python
false
false
796
py
#!/usr/bin/env python import sys import math import base64 import codecs import socket import sys import Crypto import hashlib from Crypto.Cipher import DES3 from Crypto import Random from Crypto.Util import Counter from Crypto.Hash import * from os.path import expanduser from os import listdir import subprocess from os.path import isfile, join import os if __name__ == '__main__': onlyfiles = [ f for f in listdir("out") if isfile(join("out",f)) ] for fp in onlyfiles: path = "out/"+fp f = open(path, "r") contentEncoded = f.read() content = base64.b64decode(contentEncoded) lines = content.split('\n') for line in lines: if "active" in line: flag = line[5:38] os.system("/home/user/Data/TU/secsyseng1/CTF/scripts/submit_flag.py "+flag) f.close()
[ "zoltan.krekus@opengroupware.ch" ]
zoltan.krekus@opengroupware.ch
9b1c89433e328bf11272cbd13947ef07e5c11770
7075436a4f848f04c41fff05348318e2791086b6
/us-power-dash-app/pages/index.py
77bb1d2a8f43e00e10bb6e79746ba8320624fe16
[]
no_license
Tclack88/Renewable-Energy
9b197458134725396cc87c9af3f47109494a36e9
3d9913833a98a365b90b2219883e1ad96ec37527
refs/heads/master
2023-05-25T22:17:33.102988
2022-07-05T13:44:59
2022-07-05T13:44:59
215,392,260
2
1
null
2023-05-01T23:18:47
2019-10-15T20:38:28
Jupyter Notebook
UTF-8
Python
false
false
2,147
py
import dash import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output import plotly.express as px import pandas as pd import numpy as np from app import app """ https://dash-bootstrap-components.opensource.faculty.ai/l/components/layout Layout in Bootstrap is controlled using the grid system. The Bootstrap grid has twelve columns. There are three main layout components in dash-bootstrap-components: Container, Row, and Col. The layout of your app should be built as a series of rows of columns. We set md=4 indicating that on a 'medium' sized or larger screen each column should take up a third of the width. Since we don't specify behaviour on smaller size screens Bootstrap will allow the rows to wrap so as not to squash the content. """ column1 = dbc.Col( [ dcc.Markdown( """ ## If a new power plant were to open in the US, could we predict its power output? With this app, you can see all current U.S. power plants as well as predict a new one based on a location and type of plant of choosing. """ ), dcc.Link(dbc.Button('Try It Out!', color='primary'), href='/predictions') ], md=4, ) energy_codes = pd.read_csv('assets/energy_codes.csv') data = pd.read_csv('assets/power_plants_human_readable.csv') # map fuel colors to intuitive colors color_map = dict(zip(energy_codes['Energy Source Description'],energy_codes.color)) # hover data hover_name = 'plant_type' hover_data = ['prime_mover','total_power'] title='The current U.S. power layout. Zoom around, find your local power plants!' fig = px.scatter_mapbox(data_frame = data, lat = 'lat', lon = 'lon', size = 'total_power', color = 'energy_source',color_discrete_map = color_map,zoom=3.2,hover_data=hover_data,hover_name = hover_name,size_max = 25) fig.update_layout(mapbox_style = "stamen-watercolor",showlegend=False,title=title, width = 1000, height = 600) column2 = dbc.Col( [ dcc.Graph(figure=fig), ],md=8 ) layout = dbc.Row([column1, column2])
[ "tclack@aol.com" ]
tclack@aol.com
2c3636239c359b654bce6774dea039342f4615c1
0b2d21d87615e648068bc4eceee17575dd1bbf1c
/weigthed_k_nearest_neighbors.py
122d236ccd0b89a47a15e28b2364174356c736e4
[]
no_license
ronigatt/ML-HW1
bac021854176f881af31492111a2bc4cc8999152
54e5b3cc1a2ce52cdfbce5a91fbd90b25d63a47f
refs/heads/master
2023-01-19T14:56:17.984664
2020-11-21T16:37:06
2020-11-21T16:37:06
306,458,685
0
0
null
null
null
null
UTF-8
Python
false
false
1,747
py
from typing import Tuple import numpy as np class WeightedKNearestNeighbors: """ Simple implementation of a k-NN estimator. """ def __init__(self, n_neighbors: int = 1) -> None: self.k = n_neighbors self.X_train = None self.y_train = None def fit(self, X_train: np.ndarray, y_train: np.ndarray) -> None: """ Set the train dataset attributes to be used for prediction. """ self.X_train = X_train self.y_train = y_train def get_neighbor_classes(self, observation: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: """ Returns an array of the classes of the *k* nearest neighbors. """ distances = np.sqrt(np.sum((self.X_train - observation)**2, axis=1)) # Create an array of training set indices ordered by their # distance from the current observation indices = np.argsort(distances, axis=0) selected_indices = indices[:self.k] return self.y_train[selected_indices], distances[selected_indices] def estimate_class(self, observation: np.ndarray) -> int: """ Estimates to which class a given row (*observation*) belongs. """ neighbor_classes, distances = self.get_neighbor_classes(observation) weights = 1 / np.square(distances) classes = np.unique(neighbor_classes) class_weight = [sum(weights[neighbor_classes == neighbor_class]) for neighbor_class in classes] return classes[np.argmax(class_weight)] # Replace with `mode()` def predict(self, X: np.ndarray): """ Apply k-NN estimation for each row in a given dataset. """ return np.apply_along_axis(self.estimate_class, 1, X)
[ "ronigattegno@mail.tau.ac.il" ]
ronigattegno@mail.tau.ac.il
15a2af635847f045d978ea39e5bd6d3943831c81
9c3b41c6855909318b12b5c0c7e4b914771bd811
/backend/DIP/test.py
4adb2eed2c3bcb4dd0cf3934c6dd6ed567ab40b8
[]
no_license
LeeJAJA/DIP_Final_Project
85072972a488c5ec8a9df7ffc5a2e252ddb5b922
291d76bdf426394b95c6f3321f42064cc5dda062
refs/heads/main
2023-02-21T17:01:27.251721
2021-01-24T18:21:46
2021-01-24T18:21:46
325,323,851
4
0
null
null
null
null
UTF-8
Python
false
false
4,394
py
import sys import os import warnings from model import COVNet_CSR from utils import load_net import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from torchvision import datasets, transforms from sklearn.metrics import roc_auc_score from sklearn.metrics import classification_report import numpy as np import argparse import json import cv2 import dataset import time import configparser target_names=["Non-infected","Cap","Covid-19"] parser = argparse.ArgumentParser(description='PyTorch DIP2020') parser.add_argument('--model', '-m', metavar='MODEL', default=None, type=str, help='path to the model') parser.add_argument('--batch_size', '-bs', metavar='BATCHSIZE' ,type=int, help='batch size', default=16) parser.add_argument('--gpu',metavar='GPU', type=str, help='GPU id to use.', default="0") parser.add_argument('--count', '-c', metavar='IMG_COUNT', type=int, help='Count of imgs.', default=25) def create_dir_not_exist(path): for length in range(1, len(path.split(os.path.sep))): check_path = os.path.sep.join(path.split(os.path.sep)[:(length+1)]) if not os.path.exists(check_path): os.mkdir(check_path) print(f'Created Dir: {check_path}') def checkSuffix(file_list): img_suffixs=['png'] for file in file_list: if not (file.split('.')[-1] in img_suffixs): file_list.remove(file) return file_list def main(): global args conf= configparser.ConfigParser() args = parser.parse_args() TEST_DIR = './test_dir' test_list = [TEST_DIR] # test_list=checkSuffix(test_list) os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu if not args.model: print("Usage: --model -m\n\tpath to the model") sys.exit() model = COVNet_CSR(3) criterion = nn.CrossEntropyLoss().cuda() model = DataParallel_withLoss(model, criterion) trained_net = torch.load(args.model) model.load_state_dict(trained_net['state_dict']) model = model.cuda() vote_pred = np.zeros(len(test_list)) vote_score = np.zeros(len(test_list)) targetlist, scorelist, predlist = test(test_list,model,criterion) print(targetlist[0],'--',target_names[int(predlist[0])]) def test(test_list, model, criterion): print ('begin test') test_loader = torch.utils.data.DataLoader(dataset.listDataset(test_list,train=False,count=args.count), batch_size=args.batch_size, shuffle = False) model.eval() correct = 0 predlist=[] scorelist=[] targetlist=[] with torch.no_grad(): for i,(img, target) in enumerate(test_loader): target = target[0] img = img.cuda() img = img.type(torch.FloatTensor) output = model(target, img) score = F.softmax(output, dim=1) pred = output.argmax(dim=1, keepdim=True) # print(target, int(pred)) pred=pred.squeeze(1) predlist=np.append(predlist, pred.cpu().numpy()) scorelist=np.append(scorelist, score.cpu().numpy()[:,1]) targetlist=np.append(targetlist,target) # print("{} ---- {}".format(i,len(test_loader))) print ('test done') return targetlist, scorelist, predlist class FullModel(nn.Module): def __init__(self, model, loss): super(FullModel, self).__init__() self.model = model self.loss = loss def forward(self, targets, *inputs): outputs = self.model(*inputs) # loss = self.loss(outputs, torch.topk(targets.long(), 1)[1].squeeze(1)) return outputs def DataParallel_withLoss(model,loss,**kwargs): model=FullModel(model, loss) if 'device_ids' in kwargs.keys(): device_ids=kwargs['device_ids'] else: device_ids=None if 'output_device' in kwargs.keys(): output_device=kwargs['output_device'] else: output_device=None if 'cuda' in kwargs.keys(): cudaID=kwargs['cuda'] model=torch.nn.DataParallel(model, device_ids=device_ids, output_device=output_device).cuda(cudaID) else: model=torch.nn.DataParallel(model, device_ids=device_ids, output_device=output_device).cuda() return model if __name__ == '__main__': main()
[ "v-jiajieli@microsoft.com" ]
v-jiajieli@microsoft.com
558f806ef3cf4da4ecd19def816a9ecbee9c5b2d
a0f55e31c92c31832fbe074038f07b8f8726425b
/Python/Python编程实践gwpy2-code/code/modules/temperature.py
3b2efc93b6953585f76955309183412c19d238db
[ "MIT" ]
permissive
jjc521/E-book-Collection
7533717250395a8b81163564eef821e66bae5202
b18bf6630bf99b7bf19b4cc4450b67887f618d31
refs/heads/master
2023-03-15T23:48:49.018347
2019-08-30T07:26:01
2019-08-30T07:26:01
206,090,622
2
2
null
null
null
null
UTF-8
Python
false
false
507
py
def convert_to_celsius(fahrenheit): """ (number) -> float Return the number of Celsius degrees equivalent to fahrenheit degrees. >>> convert_to_celsius(75) 23.88888888888889 """ return (fahrenheit - 32.0) * 5.0 / 9.0 def above_freezing(celsius): """ (number) -> bool Return True iff temperature celsius degrees is above freezing. >>> above_freezing(5.2) True >>> above_freezing(-2) False """ return celsius > 0
[ "907097904@qq.com" ]
907097904@qq.com
c546794f818cd7dad078231721e1a58b6fd382fa
607278f02cfbd1104b06385f064d85670b6d8794
/t1.py
91bfd8f44b69bcca999428a6a4d3571cb207a619
[]
no_license
Dvk2002/Algo
445baaa03409ce7e16ddddbd8d0c0ada41f564bf
4444c8603424617565d9e9fe90eec238f01b93d8
refs/heads/master
2020-12-07T02:03:06.827289
2020-07-01T13:48:30
2020-07-01T13:48:30
232,608,626
0
0
null
null
null
null
UTF-8
Python
false
false
367
py
#1. Выполнить логические побитовые операции «И», «ИЛИ» и др. над числами 5 и 6. # Выполнить над числом 5 побитовый сдвиг вправо и влево на два знака. a = 5 b = 6 print(bin(a)) print(a & b) print(a | b) print(a ^ b) print(a << 2) print(a >> 2)
[ "noreply@github.com" ]
Dvk2002.noreply@github.com
b3f013300f5bacd1ee5510b6238b8cec1feacf9d
b810066cbbd9fa3d76839df58cb232f7c06a2adf
/graph/kcores.py
f9024cac72b11d9923d22cafbbb01540299cdcb7
[]
no_license
VaishnaviDhulipalla2902/Data-Structures-and-Algorithms
2cb8a00047fc3636c492799324595f982fbe12d1
52a6d65ffef3c3cbfc90a05d90a3c5493c1dc2c8
refs/heads/master
2020-04-08T16:53:11.003330
2018-11-28T17:36:17
2018-11-28T17:36:17
159,540,148
0
0
null
null
null
null
UTF-8
Python
false
false
3,346
py
# program to find K-Cores of a graph from collections import defaultdict # This class represents a undirected graph using adjacency # list representation class Graph: def __init__(self,vertices): self.V= vertices #No. of vertices # default dictionary to store graph self.graph= defaultdict(list) # function to add an edge to undirected graph def addEdge(self,u,v): self.graph[u].append(v) self.graph[v].append(u) # A recursive function to call DFS starting from v. # It returns true if vDegree of v after processing is less # than k else false # It also updates vDegree of adjacent if vDegree of v # is less than k. And if vDegree of a processed adjacent # becomes less than k, then it reduces of vDegree of v also, def DFSUtil(self,v,visited,vDegree,k): # Mark the current node as visited visited[v] = True # Recur for all the vertices adjacent to this vertex for i in self.graph[v]: # vDegree of v is less than k, then vDegree of # adjacent must be reduced if vDegree[v] < k: vDegree[i] = vDegree[i] - 1 # If adjacent is not processed, process it if visited[i]==False: # If vDegree of adjacent after processing becomes # less than k, then reduce vDegree of v also if (self.DFSUtil(i,visited,vDegree,k)): vDegree[v]-=1 # Return true if vDegree of v is less than k return vDegree[v] < k # Prints k cores of an undirected graph def printKCores(self,k): # INITIALIZATION # Mark all the vertices as not visited visited = [False]*self.V # Store vDegrees of all vertices vDegree = [0]*self.V for i in self.graph: vDegree[i]=len(self.graph[i]) # choose any vertex as starting vertex self.DFSUtil(0,visited,vDegree,k) # DFS traversal to update vDegrees of all # vertices,in case they are unconnected for i in range(self.V): if visited[i] ==False: self.DFSUtil(i,k,vDegree,visited) # PRINTING K CORES print "\n K-cores: " for v in range(self.V): # Only considering those vertices which have # vDegree >= K after DFS if vDegree[v] >= k: print str("\n [ ") + str(v) + str(" ]"), # Traverse adjacency list of v and print only # those adjacent which have vvDegree >= k # after DFS for i in self.graph[v]: if vDegree[i] >= k: print "-> " + str(i), k = 3; g1 = Graph (9); g1.addEdge(0, 1) g1.addEdge(0, 2) g1.addEdge(1, 2) g1.addEdge(1, 5) g1.addEdge(2, 3) g1.addEdge(2, 4) g1.addEdge(2, 5) g1.addEdge(2, 6) g1.addEdge(3, 4) g1.addEdge(3, 6) g1.addEdge(3, 7) g1.addEdge(4, 6) g1.addEdge(4, 7) g1.addEdge(5, 6) g1.addEdge(5, 8) g1.addEdge(6, 7) g1.addEdge(6, 8) g1.printKCores(k) g2 = Graph(13); g2.addEdge(0, 1) g2.addEdge(0, 2) g2.addEdge(0, 3) g2.addEdge(1, 4) g2.addEdge(1, 5) g2.addEdge(1, 6) g2.addEdge(2, 7) g2.addEdge(2, 8) g2.addEdge(2, 9) g2.addEdge(3, 10) g2.addEdge(3, 11) g2.addEdge(3, 12) g2.printKCores(k)
[ "noreply@github.com" ]
VaishnaviDhulipalla2902.noreply@github.com
740d5a837b4cf6ccf1dce748d6dbf6261231c33f
4cf340a94809ce51b8cd29896c27cb1b34d746e3
/venvv/Scripts/pip3-script.py
05100c20d341092af86a93edd6cfb76e66019b82
[]
no_license
cuongpianna/automation_test
ca9798ef2a3ef65f58dd5597240c5e094ca6213c
570ddaa1d8be65f69bd987a189622a674f37c37a
refs/heads/master
2020-04-08T19:22:55.486396
2018-11-30T10:28:24
2018-11-30T10:28:24
159,652,814
0
0
null
null
null
null
UTF-8
Python
false
false
422
py
#!C:\Users\admin\Desktop\lam\autotest\letskodeit\venvv\Scripts\python.exe # EASY-INSTALL-ENTRY-SCRIPT: 'pip==10.0.1','console_scripts','pip3' __requires__ = 'pip==10.0.1' 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('pip==10.0.1', 'console_scripts', 'pip3')() )
[ "cuongpianna1996@gmail.com" ]
cuongpianna1996@gmail.com
5625dc31686635f15a536d27320a06ce760647d8
2146cd1c3c00d9cb4f09c7b2a606cbf321cf1ede
/Temporizador_LCD/main.py
b42040b858d719954b6eff3c6105f1b4fb768a00
[]
no_license
marioferreyra/Proyectos_PyQt4
269aca2b12687424c6f046b6546aa8e5fb20a9bb
e79759462de1e170b785306118315284002c5ddc
refs/heads/master
2020-06-13T19:59:40.027452
2019-07-02T02:27:00
2019-07-02T02:27:00
194,772,943
0
0
null
null
null
null
UTF-8
Python
false
false
3,206
py
# -*- coding: utf-8 -*- from PyQt4.QtGui import * from PyQt4.QtCore import * from PyQt4 import uic ONE_SECOND = 1000 # 1000 ms = 1 s class Temporizador(QWidget): """ Ventana de un temporizador, con opciones para setear el tiempo, iniciar, pausar y resetear. """ def __init__(self): QWidget.__init__(self) uic.loadUi("temporizador.ui", self) self.timer = QTimer() self.tick = 0 # Segundos transcurridos # Tiempo que se setea self.hours = 0 self.minutes = 0 self.seconds = 0 # Estado inicial de los botones self.btnStart.setEnabled(False) self.btnReset.setEnabled(False) # Conexiones self.timer.timeout.connect(self.updateLCD) self.btnExit.clicked.connect(self.close) self.btnSet.clicked.connect(self.setTime) self.btnStart.clicked.connect(self.start) self.btnReset.clicked.connect(self.reset) self.lcd.display("00:00:00") def start(self): """ Inicia el Temporizador. """ if not self.isTimerActive(): self.btnSet.setEnabled(False) self.btnReset.setEnabled(False) self.timer.start(ONE_SECOND) self.btnStart.setText("Stop") else: self.btnSet.setEnabled(True) self.btnReset.setEnabled(True) self.timer.stop() self.btnStart.setText("Start") def reset(self): """ Resetea el Temporizador. """ self.btnStart.setEnabled(True) self.btnStart.setText("Start") self.timer.stop() self.tick = self.hours*3600 + self.minutes*60 + self.seconds self.lcd.display("%02d:%02d:%02d" % (self.hours, self.minutes, self.seconds)) def updateLCD(self): """ Actualiza el tiempo del LCD. Cuando llega a 00:00:00, se muestra un aviso. """ if self.tick != 0: self.tick -= 1 hour = self.tick / 3600 minute = (self.tick % 3600) / 60 second = (self.tick % 3600) % 60 self.lcd.display("%02d:%02d:%02d" % (hour, minute, second)) else: self.timer.stop() self.btnSet.setEnabled(True) self.btnStart.setEnabled(False) self.btnReset.setEnabled(True) self.btnStart.setText("Start") QMessageBox.warning(self,"Aviso","### ALARM ###") def setTime(self): """ Setea el Tiempo establecido en el LCD. """ self.btnStart.setEnabled(True) self.btnReset.setEnabled(True) t = self.time.time() self.hours = t.hour() self.minutes = t.minute() self.seconds = t.second() self.tick = self.hours*3600 + self.minutes*60 + self.seconds self.lcd.display(t.toString()) def isTimerActive(self): """ Retorna True si el temporizador (timer) esta activo. """ return self.timer.isActive() if __name__ == "__main__": import sys app = QApplication(sys.argv) myapp = Temporizador() myapp.show() sys.exit(app.exec_())
[ "ferreyramario7@gmail.com" ]
ferreyramario7@gmail.com
06c51227a9261b7a9b1f911e5ff2ebd76daea836
f7d0c32b8d29dcff788d439c2b7051734afbbfc6
/meiduo1/apps/user1/crons.py
c3a3f835bb36096554b8b4821ab26a9b54fa8c6b
[ "MIT" ]
permissive
woobrain/nginx-uwsgi-web
dcf5159ba3f3332108c2d351ef3dac0cc504ade7
5b3ca1fba8205c2c0a2b91d951f812f1c30e12ae
refs/heads/master
2022-12-22T21:08:00.758841
2019-11-13T12:31:20
2019-11-13T12:31:20
221,447,696
0
0
MIT
2022-12-11T19:51:54
2019-11-13T11:52:19
JavaScript
UTF-8
Python
false
false
1,091
py
import os import time from django.conf import settings from django.template import loader from apps.user1.models import ContentCategory from apps.user1.utils import get_categories def generate_static_index_html(): """ 生成静态的主页html文件 """ print('%s: generate_static_index_html' % time.ctime()) # 获取商品频道和分类 categories = get_categories() # 广告内容 contents = {} content_categories = ContentCategory.objects.all() for cat in content_categories: contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence') # 渲染模板 context = { 'categories': categories, 'contents': contents } # 获取首页模板文件 template = loader.get_template('index.html') # 渲染首页html字符串 html_text = template.render(context) # 将首页html字符串写入到指定目录,命名'index.html' file_path = os.path.join(settings.STATICFILES_DIRS[0], 'index.html') with open(file_path, 'w', encoding='utf-8') as f: f.write(html_text)
[ "xwp_fullstack@163.com" ]
xwp_fullstack@163.com
d962fc5032ad40cdc67297acaa22af482ab70d52
ba875d5f71e9d0339a00fc57a26ace159df41079
/server2/urls.py
5fa5390ef5988a449c220a7c349b3e28dd6b5961
[]
no_license
Ruiyang-061X/ruiyang-website
b3f6dc33f45e3e5c22697f64067525888027c91d
0037760438f1cc5ed836a25e1776c13d48a9396d
refs/heads/master
2020-09-24T21:01:06.413638
2019-12-04T10:58:36
2019-12-04T10:58:36
225,843,077
1
0
null
null
null
null
UTF-8
Python
false
false
825
py
"""server2 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import include, path urlpatterns = [ path('', include('ruiyang_website.urls')), path('admin/', admin.site.urls), ]
[ "ruiyang@Ubuntu18.04" ]
ruiyang@Ubuntu18.04