blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
288
content_id
stringlengths
40
40
detected_licenses
listlengths
0
112
license_type
stringclasses
2 values
repo_name
stringlengths
5
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
684 values
visit_date
timestamp[us]date
2015-08-06 10:31:46
2023-09-06 10:44:38
revision_date
timestamp[us]date
1970-01-01 02:38:32
2037-05-03 13:00:00
committer_date
timestamp[us]date
1970-01-01 02:38:32
2023-09-06 01:08:06
github_id
int64
4.92k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-04 01:52:49
2023-09-14 21:59:50
gha_created_at
timestamp[us]date
2008-05-22 07:58:19
2023-08-21 12:35:19
gha_language
stringclasses
147 values
src_encoding
stringclasses
25 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
128
12.7k
extension
stringclasses
142 values
content
stringlengths
128
8.19k
authors
listlengths
1
1
author_id
stringlengths
1
132
7f2040a18d8ae48cdf68130156100676b859f15b
1b3addbc9473b6ffb999665601470ccc4d1153b0
/libs/thumb/movieThumb.py
83e16f22327f4b3a9e7bde2ac613809fe449ca31
[]
no_license
weijia/approot
e1f712fa92c4c3200210eb95d251d890295769ba
15fac5b31a4d619d1bdede3d1131f5e6e57cd43b
refs/heads/master
2020-04-15T13:15:01.956721
2014-08-26T14:02:17
2014-08-26T14:02:17
11,049,975
1
0
null
null
null
null
UTF-8
Python
false
false
2,248
py
#! /bin/env python #from http://pymedia.org/tut/src/dump_video.py.html import sys, os import pymedia.muxer as muxer import pymedia.video.vcodec as vcodec import pygame def genVideoThumb(local_path, dest_dir): basename = os.path.basename(local_path) thumb_path_without_ext = os.path.join(dest_dir, basename.split(".")[0] + "_T") import random while os.path.exists(thumb_path_without_ext + ".jpg"): thumb_path_without_ext += str(random.randint(0, 10)) thumb_path = thumb_path_without_ext + '___%d.jpg' dumpVideo(local_path, thumb_path.encode('gbk'), 2) return thumb_path % 1 def dumpVideo(inFile, outFilePattern, fmt): dm = muxer.Demuxer(inFile.split('.')[-1]) i = 1 f = open(inFile, 'rb') s = f.read(400000) r = dm.parse(s) v = filter(lambda x: x['type'] == muxer.CODEC_TYPE_VIDEO, dm.streams) if len(v) == 0: raise 'There is no video stream in a file %s' % inFile v_id = v[0]['index'] print 'Assume video stream at %d index: ' % v_id c = vcodec.Decoder(dm.streams[v_id]) while len(s) > 0: if i > 1: break for fr in r: if fr[0] == v_id: d = c.decode(fr[1]) # Save file as RGB BMP if d: dd = d.convert(fmt) img = pygame.image.fromstring(dd.data, dd.size, "RGB") pygame.image.save(img, outFilePattern % i) i += 1 break s = f.read(400000) r = dm.parse(s) #print 'Saved %d frames' % i # ---------------------------------------------------------------------------------- # Dump the whole video file into the regular BMP images in the directory and file name specified # http://pymedia.org/ if __name__ == "__main__": if len(sys.argv) != 4: print 'Usage: dump_video <file_name> <image_pattern> <format_number>\n' + \ '\n<image_patter> should include %d in the name. ex. test_%d.bmp.' + \ '<format_number> can be: RGB= 2' + \ '\nThe resulting image will be in a bmp format' else: pygame.init() dumpVideo(sys.argv[1], sys.argv[2], int(sys.argv[3])) pygame.quit()
[ "richardwangwang@gmail.com" ]
richardwangwang@gmail.com
8cab1b2cbf3a564aaa63881deefcd2ff4b6268de
f9609ff4f2bbea570f3cb4cd3f9fe6b3595d4145
/commands/cmd_oload.py
2f1222a7ec0e09ed83c5c5b47341433566adc839
[]
no_license
VladThePaler/PythonWars-1996
2628bd2fb302faacc91688ad942799537c974f50
d8fbc27d90f1deb9755c0ad0e1cf2c110f406e28
refs/heads/master
2023-05-08T19:51:28.586440
2021-05-14T04:19:17
2021-05-14T04:19:17
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,639
py
# PythonWars copyright © 2020, 2021 by Paul Penner. All rights reserved. # In order to use this codebase you must comply with all licenses. # # Original Diku Mud copyright © 1990, 1991 by Sebastian Hammer, # Michael Seifert, Hans Henrik Stærfeldt, Tom Madsen, and Katja Nyboe. # # Merc Diku Mud improvements copyright © 1992, 1993 by Michael # Chastain, Michael Quan, and Mitchell Tse. # # GodWars improvements copyright © 1995, 1996 by Richard Woolcock. # # ROM 2.4 is copyright 1993-1998 Russ Taylor. ROM has been brought to # you by the ROM consortium: Russ Taylor (rtaylor@hypercube.org), # Gabrielle Taylor (gtaylor@hypercube.org), and Brian Moore (zump@rom.org). # # Ported to Python by Davion of MudBytes.net using Miniboa # (https://code.google.com/p/miniboa/). # # In order to use any part of this Merc Diku Mud, you must comply with # both the original Diku license in 'license.doc' as well the Merc # license in 'license.txt'. In particular, you may not remove either of # these copyright notices. # # Much time and thought has gone into this software, and you are # benefiting. We hope that you share your changes too. What goes # around, comes around. import game_utils import handler_game import instance import interp import merc import object_creator def cmd_oload(ch, argument): argument, arg1 = game_utils.read_word(argument) argument, arg2 = game_utils.read_word(argument) if not arg1 or not arg1.isdigit(): ch.send("Syntax: oload <vnum> <level>.\n") return if not arg2: level = ch.trust else: # New feature from Alander. if not arg2.isdigit(): ch.send("Syntax: oload <vnum> <level>.\n") return level = int(arg2) if level not in merc.irange(0, ch.trust): ch.send("Limited to your trust level.\n") return vnum = int(arg1) if vnum not in instance.item_templates: ch.send("No object has that vnum.\n") return item = object_creator.create_item(instance.item_templates[vnum], level) if item.flags.take: ch.put(item) handler_game.act("$p appears in $n's hands!", ch, item, None, merc.TO_ROOM) else: ch.in_room.put(item) handler_game.act("$n has created $p!", ch, item, None, merc.TO_ROOM) handler_game.act("You create $p.", ch, item, None, merc.TO_CHAR) item.questmaker = ch.name interp.register_command( interp.CmdType( name="oload", cmd_fun=cmd_oload, position=merc.POS_DEAD, level=7, log=merc.LOG_ALWAYS, show=True, default_arg="" ) )
[ "jindrak@gmail.com" ]
jindrak@gmail.com
80a8724e780c5057018d2ad75baf284d200906cc
880d9cc2704f7de649ad4455dd7ec2806b6a9e95
/PythonExam/北京理工大学Python语言程序设计-Book/Chapter5/5.1BigTianZiGe.py
89436192a9459828aca260e6b959b29642934e28
[]
no_license
shunz/Python-100-Days_Practice
14795757effcff50a4644f57c5c109fa1c9c38ac
82f508ff6911ce3aa5c5a69cd481a6cc87f02258
refs/heads/master
2020-12-26T18:52:32.755384
2020-04-07T15:49:36
2020-04-07T15:49:36
237,604,470
0
0
null
null
null
null
UTF-8
Python
false
false
320
py
"""绘制大田字格""" def draw(n): line = 3 * n + 1 # 一共要绘制的行数 for i in range(1, line+1): if i % 3 == 1: # 判断需要绘制哪种线 print(n * '+----', end='') print('+') else: print(n * '| ', end='') print('|') draw(5)
[ "rockucn@gmail.com" ]
rockucn@gmail.com
bff6d26590f067bd15ad04ee687e8f3bf1027a7a
6d6d82ce7835fd8fca1aa12f775a75f4d7901f0f
/makedoc.py
1e2c1ef75b934eb9702f4faf493c766702d71fb0
[ "Apache-2.0" ]
permissive
shmakovpn/whatprovides
b7a3867f0529d465a8405f6669b797a5c7de2e2c
69aab055397ae49844c93cfe17fdfaf18b02f79d
refs/heads/master
2023-02-12T00:39:28.936096
2021-01-14T08:26:25
2021-01-14T08:26:25
273,847,446
0
0
null
null
null
null
UTF-8
Python
false
false
555
py
""" whatprovides makedoc.py This script runs 'shpinx-build -b html docs/source docs/build/html' """ import os SCRIPT_DIR: str = os.path.dirname(os.path.abspath(__file__)) def run_sphinx(): docs_dir: str = os.path.join(SCRIPT_DIR, 'docs') docs_source_dir: str = os.path.join(docs_dir, 'source') build_dir: str = os.path.join(docs_dir, 'build') html_dir: str = os.path.join(build_dir, 'html') os.system('sphinx-build -b html "%s" "%s"' % (docs_source_dir, html_dir)) print('__END__') if __name__ == '__main__': run_sphinx()
[ "shmakovpn@yandex.ru" ]
shmakovpn@yandex.ru
18d7e89c4ff3ab5e1f4886895111d3e359f7a99a
0466559817d3a1be9409da2c83db99c4db3bacfe
/hubcheck/pageobjects/widgets/tools_status_approve_license_form.py
7c7e4da3883a72ce8d045d1ce61dc77718770acd
[ "MIT" ]
permissive
ken2190/hubcheck
955cf9b75a1ee77e28256dfd3a780cfbc17de961
2ff506eb56ba00f035300862f8848e4168452a17
refs/heads/master
2023-03-20T15:17:12.949715
2015-09-29T16:11:18
2015-09-29T16:11:18
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,813
py
from hubcheck.pageobjects.widgets.form_base import FormBase from hubcheck.pageobjects.basepageelement import Button from hubcheck.pageobjects.basepageelement import Checkbox from hubcheck.pageobjects.basepageelement import Select from hubcheck.pageobjects.basepageelement import TextArea class ToolsStatusApproveLicenseForm(FormBase): def __init__(self, owner, locatordict={}): super(ToolsStatusApproveLicenseForm,self).__init__(owner,locatordict) # load hub's classes ToolsStatusApproveLicenseForm_Locators = \ self.load_class('ToolsStatusApproveLicenseForm_Locators') # update this object's locator self.locators.update(ToolsStatusApproveLicenseForm_Locators.locators) # update the locators with those from the owner self.update_locators_from_owner() # setup page object's components self.sourceaccess = Select(self,{'base':'access'}) self.templates = Select(self,{'base':'templates'}) self.licensetext = TextArea(self,{'base':'license'}) self.reason = TextArea(self,{'base':'reason'}) self.authorize = Checkbox(self,{'base':'authorize'}) self.fields = ['sourceaccess','templates','licensetext','reason','authorize'] # update the component's locators with this objects overrides self._updateLocators() class ToolsStatusApproveLicenseForm_Locators_Base(object): """locators for ToolsStatusApproveLicenseForm object""" locators = { 'base' : "css=#licenseForm", 'access' : "css=#t_code", 'templates' : "css=#templates", 'license' : "css=#license", 'reason' : "css=#reason", 'authorize' : "css=#field-authorize", 'submit' : "css=#licenseForm [type='submit']", }
[ "telldsk@gmail.com" ]
telldsk@gmail.com
5bd122562edd702b509be8347cb903fabd7a348c
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p02622/s965763591.py
6eb619ddc1792d0336e698e3556c81de57f06d66
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
153
py
s = input() t = input() ans = abs(len(s) - len(t)) count = min(len(s), len(t)) for i in range(count): if s[i] != t [i]: ans += 1 print(ans)
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
450964e2ca1c9a822fb9063c290bf73249f962dc
b72dbc51279d3e59cb6410367b671f8a956314c1
/leet_code/leet_289_미완.py
af573016d838cdf5fed6d1582fe7f3571eef673e
[]
no_license
ddobokki/coding-test-practice
7b16d20403bb1714d97adfd1f47aa7d3ccd7ea4b
c88d981a1d43b986169f7884ff3ef1498e768fc8
refs/heads/main
2023-07-08T15:09:32.269059
2021-08-08T12:19:44
2021-08-08T12:19:44
344,116,013
0
0
null
null
null
null
UTF-8
Python
false
false
934
py
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: p_to_s = {} s_to_p = {} s_list = s.split() if len(pattern) != len(s_list): return False for i in range(len(pattern)): if not pattern[i] in p_to_s: p_to_s[pattern[i]] = s_list[i] else: if p_to_s[pattern[i]] != s_list[i]: return False if not s_list[i] in s_to_p: s_to_p[s_list[i]] = pattern[i] else: if s_to_p[s_list[i]] != pattern[i]: return False return True print(Solution().wordPattern(pattern = "abba", s = "dog cat cat dog")) print(Solution().wordPattern(pattern = "aaaa", s = "dog cat cat dog")) print(Solution().wordPattern(pattern = "abba", s = "dog cat cat fish")) print(Solution().wordPattern(pattern = "abba", s = "dog dog dog dog"))
[ "44228269+ddobokki@users.noreply.github.com" ]
44228269+ddobokki@users.noreply.github.com
43dc21afee9084e1dac7059070a15dba3c140d9b
8c5c4102b1c0f54ceeaa67188532f72c7e269bab
/ucr_adiac.py
9d23e9782528db8910955949b3d7e0c9ed82de5a
[ "MIT" ]
permissive
stjordanis/dtw-numba
a6d3e745e005b0bc8026d973f33668931bbde9f2
d8bc9e1f0cde108e429ff72e654ed8aa10a6b4ae
refs/heads/master
2022-01-04T16:59:26.423994
2019-01-14T01:45:11
2019-01-14T01:45:11
null
0
0
null
null
null
null
UTF-8
Python
false
false
457
py
from utils.data_loader import load_dataset from odtw import KnnDTW X_train, y_train, X_test, y_test = load_dataset('adiac', normalize_timeseries=True) print() # parameters num_neighbours = 1 model = KnnDTW(num_neighbours) # fit to the dataset model.fit(X_train, y_train) # Predict / Evaluate the score accuracy = model.evaluate(X_test, y_test) error = 1. - accuracy print("*" * 20, "\n") print("Test Accuracy :", accuracy) print("Test Error :", error)
[ "titu1994@gmail.com" ]
titu1994@gmail.com
a3fad2f7d00ea5094ccd316d80677c52d5b80656
61efd764ae4586b6b2ee5e6e2c255079e2b01cfc
/azure-mgmt-network/azure/mgmt/network/v2017_10_01/models/application_gateway_frontend_ip_configuration.py
955d0ad0ccdd29a9286612911582c511c7937114
[ "MIT" ]
permissive
AutorestCI/azure-sdk-for-python
a3642f53b5bf79d1dbb77851ec56f4cc0c5b3b61
60b0726619ce9d7baca41f6cd38f741d74c4e54a
refs/heads/master
2021-01-21T02:23:59.207091
2018-01-31T21:31:27
2018-01-31T21:31:27
55,251,306
4
3
null
2017-11-13T17:57:46
2016-04-01T17:48:48
Python
UTF-8
Python
false
false
3,079
py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from .sub_resource import SubResource class ApplicationGatewayFrontendIPConfiguration(SubResource): """Frontend IP configuration of an application gateway. :param id: Resource ID. :type id: str :param private_ip_address: PrivateIPAddress of the network interface IP Configuration. :type private_ip_address: str :param private_ip_allocation_method: PrivateIP allocation method. Possible values include: 'Static', 'Dynamic' :type private_ip_allocation_method: str or ~azure.mgmt.network.v2017_10_01.models.IPAllocationMethod :param subnet: Reference of the subnet resource. :type subnet: ~azure.mgmt.network.v2017_10_01.models.SubResource :param public_ip_address: Reference of the PublicIP resource. :type public_ip_address: ~azure.mgmt.network.v2017_10_01.models.SubResource :param provisioning_state: Provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param name: Name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str :param type: Type of the resource. :type type: str """ _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'private_ip_address': {'key': 'properties.privateIPAddress', 'type': 'str'}, 'private_ip_allocation_method': {'key': 'properties.privateIPAllocationMethod', 'type': 'str'}, 'subnet': {'key': 'properties.subnet', 'type': 'SubResource'}, 'public_ip_address': {'key': 'properties.publicIPAddress', 'type': 'SubResource'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__(self, id=None, private_ip_address=None, private_ip_allocation_method=None, subnet=None, public_ip_address=None, provisioning_state=None, name=None, etag=None, type=None): super(ApplicationGatewayFrontendIPConfiguration, self).__init__(id=id) self.private_ip_address = private_ip_address self.private_ip_allocation_method = private_ip_allocation_method self.subnet = subnet self.public_ip_address = public_ip_address self.provisioning_state = provisioning_state self.name = name self.etag = etag self.type = type
[ "laurent.mazuel@gmail.com" ]
laurent.mazuel@gmail.com
3cf9d17ecba3aa57d48ecb8dfdd99b8f2850da18
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03407/s848933325.py
ff4cec19ca5069927aff3e41f680aa80c10562e8
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
158
py
def solve(string): a, b, c = map(int, string.split()) return "Yes" if a + b - c >= 0 else "No" if __name__ == '__main__': print(solve(input()))
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
02b153c3d0fc5f6666834084cdbd1206b6fec8e0
5ff73a257eed74de87c0279c69552c19420fcc7d
/venv/bin/restauth-service.py
1c22855c0d3bbf3289c293172bb8dd3aa5f859d9
[]
no_license
GanapathiAmbore/api_auth_pro
9109f4fbd50ae0225875daa3f82418b7c9aa5381
d98e3cf1cade4c9b461fe298f94bdc38625c06aa
refs/heads/master
2022-06-13T08:31:49.728775
2019-07-16T05:16:37
2019-07-16T05:16:37
196,578,277
0
0
null
2022-04-22T21:55:26
2019-07-12T12:47:44
Python
UTF-8
Python
false
false
3,830
py
#!/home/ganapathi/PycharmProjects/authpro/venv/bin/python # -*- coding: utf-8 -*- # # This file is part of RestAuth (https://restauth.net). # # RestAuth is free software: you can redistribute it and/or modify it under the terms of the GNU # General Public License as published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # RestAuth is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License along with RestAuth. If not, # see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals import os import sys from pkg_resources import DistributionNotFound from pkg_resources import Requirement from pkg_resources import resource_filename # Setup environment os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'RestAuth.settings') sys.path.append(os.getcwd()) try: req = Requirement.parse("RestAuth") path = resource_filename(req, 'RestAuth') if os.path.exists(path): # pragma: no cover sys.path.insert(0, path) except DistributionNotFound: pass # we're run in a not-installed environment try: from django.core.exceptions import ValidationError from django.db import transaction from django.db.utils import IntegrityError from Services.models import Service from Services.cli.parsers import parser except ImportError as e: # pragma: no cover sys.stderr.write( 'Error: Cannot import RestAuth. Please make sure RestAuth is in your PYTHONPATH.\n') sys.exit(1) def main(args=None): args = parser.parse_args(args=args) if args.action == 'add': password = args.get_password(args) if args.password_generated: print(args.pwd) args.service.set_password(password) args.service.save() elif args.action == 'rename': args.service.username = args.name with transaction.atomic(): try: args.service.save() except IntegrityError: parser.error("%s: Service already exists." % args.name) elif args.action == 'rm': args.service.delete() elif args.action == 'ls': for service in Service.objects.all().order_by('username'): print('%s: %s' % (service.name, ', '.join(service.addresses))) elif args.action == 'view': print('Last used: %s' % (args.service.last_login)) print('Hosts: %s' % (', '.join(args.service.addresses))) print('Permissions: %s' % (', '.join(args.service.permissions))) elif args.action == 'set-hosts': try: args.service.set_hosts(*args.hosts) except ValidationError as e: parser.error(e.messages[0]) elif args.action == 'add-hosts': try: args.service.add_hosts(*args.hosts) except ValidationError as e: parser.error(e.messages[0]) elif args.action == 'rm-hosts': args.service.del_hosts(*args.hosts) elif args.action == 'set-password': password = args.get_password(args) if args.password_generated: print(args.pwd) args.service.set_password(password) args.service.save() elif args.action == 'set-permissions': args.service.user_permissions.clear() args.service.user_permissions.add(*args.permissions) elif args.action == 'add-permissions': args.service.user_permissions.add(*args.permissions) elif args.action == 'rm-permissions': # pragma: no branch args.service.user_permissions.remove(*args.permissions) if __name__ == '__main__': # pragma: no cover main()
[ "ganapathiambore@gmail.com" ]
ganapathiambore@gmail.com
01afe9e24bd9eb31dadd305dec3fa3f60ba98f28
1d23c51bd24fc168df14fa10b30180bd928d1ea4
/Lib/site-packages/twisted/logger/_legacy.py
c03f93b687532317a997175c0116dd9231be8e8f
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
BeaverInc/covid19CityMontreal
62dac14840dadcdf20985663bc2527c90bab926c
1b283589f6885977a179effce20212a9311a2ac0
refs/heads/master
2021-05-22T20:01:22.443897
2020-06-21T08:00:57
2020-06-21T08:00:57
253,067,914
0
0
null
null
null
null
UTF-8
Python
false
false
5,237
py
# -*- test-case-name: twisted.logger.test.test_legacy -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Integration with L{twisted.python.log}. """ from zope.interface import implementer from ._levels import LogLevel from ._format import formatEvent from ._observer import ILogObserver from ._stdlib import fromStdlibLogLevelMapping, StringifiableFromEvent @implementer(ILogObserver) class LegacyLogObserverWrapper(object): """ L{ILogObserver} that wraps an L{twisted.python.log.ILogObserver}. Received (new-style) events are modified prior to forwarding to the legacy observer to ensure compatibility with observers that expect legacy events. """ def __init__(self, legacyObserver): """ @param legacyObserver: a legacy observer to which this observer will forward events. @type legacyObserver: L{twisted.python.log.ILogObserver} """ self.legacyObserver = legacyObserver def __repr__(self): return ( "{self.__class__.__name__}({self.legacyObserver})" .format(self=self) ) def __call__(self, event): """ Forward events to the legacy observer after editing them to ensure compatibility. @param event: an event @type event: L{dict} """ # The "message" key is required by textFromEventDict() if "message" not in event: event["message"] = () if "time" not in event: event["time"] = event["log_time"] if "system" not in event: event["system"] = event.get("log_system", "-") # Format new style -> old style if "format" not in event and event.get("log_format", None) is not None: # Create an object that implements __str__() in order to defer the # work of formatting until it's needed by a legacy log observer. event["format"] = "%(log_legacy)s" event["log_legacy"] = StringifiableFromEvent(event.copy()) # In the old-style system, the 'message' key always holds a tuple # of messages. If we find the 'message' key here to not be a # tuple, it has been passed as new-style parameter. We drop it # here because we render it using the old-style 'format' key, # which otherwise doesn't get precedence, and the original event # has been copied above. if not isinstance(event["message"], tuple): event["message"] = () # From log.failure() -> isError blah blah if "log_failure" in event: if "failure" not in event: event["failure"] = event["log_failure"] if "isError" not in event: event["isError"] = 1 if "why" not in event: event["why"] = formatEvent(event) elif "isError" not in event: if event["log_level"] in (LogLevel.error, LogLevel.critical): event["isError"] = 1 else: event["isError"] = 0 self.legacyObserver(event) def publishToNewObserver(observer, eventDict, textFromEventDict): """ Publish an old-style (L{twisted.python.log}) event to a new-style (L{twisted.logger}) observer. @note: It's possible that a new-style event was sent to a L{LegacyLogObserverWrapper}, and may now be getting sent back to a new-style observer. In this case, it's already a new-style event, adapted to also look like an old-style event, and we don't need to tweak it again to be a new-style event, hence the checks for already-defined new-style keys. @param observer: A new-style observer to handle this event. @type observer: L{ILogObserver} @param eventDict: An L{old-style <twisted.python.log>}, log event. @type eventDict: L{dict} @param textFromEventDict: callable that can format an old-style event as a string. Passed here rather than imported to avoid circular dependency. @type textFromEventDict: 1-arg L{callable} taking L{dict} returning L{str} @return: L{None} """ if "log_time" not in eventDict: eventDict["log_time"] = eventDict["time"] if "log_format" not in eventDict: text = textFromEventDict(eventDict) if text is not None: eventDict["log_text"] = text eventDict["log_format"] = u"{log_text}" if "log_level" not in eventDict: if "logLevel" in eventDict: try: level = fromStdlibLogLevelMapping[eventDict["logLevel"]] except KeyError: level = None elif "isError" in eventDict: if eventDict["isError"]: level = LogLevel.critical else: level = LogLevel.info else: level = LogLevel.info if level is not None: eventDict["log_level"] = level if "log_namespace" not in eventDict: eventDict["log_namespace"] = u"log_legacy" if "log_system" not in eventDict and "system" in eventDict: eventDict["log_system"] = eventDict["system"] observer(eventDict)
[ "36340780+lanyutian88@users.noreply.github.com" ]
36340780+lanyutian88@users.noreply.github.com
e3bc0a518cc3efc7e7c027f9b002fdbccbd0ed8f
67a0618de2844f175e74684214d45d1ba4b78554
/core/views.py
1e20ab3fe39e835fec71321975a7adf4527011eb
[ "MIT" ]
permissive
fantasiforbundet/grenselandet
c748fa0701d5c96351da916678f771e3717dea10
d0a8878fa2aa1ee65737702d86ef25482bf46bff
refs/heads/master
2020-11-26T20:56:00.828700
2015-02-06T16:45:16
2015-02-06T16:45:16
null
0
0
null
null
null
null
UTF-8
Python
false
false
793
py
# -*- coding: utf-8 -*- """ Generic views for webpage """ from django.views.generic.base import TemplateView from django.conf import settings class TextTemplateView(TemplateView): """ Render plain text file. """ def render_to_response(self, context, **response_kwargs): response_kwargs['content_type'] = 'text/plain' return super(TemplateView, self).render_to_response(context, **response_kwargs) class HumansTxtView(TextTemplateView): """ humans.txt contains information about who made the site. """ template_name = 'humans.txt' class RobotsTxtView(TextTemplateView): """ robots.txt contains instructions for webcrawler bots. """ if settings.DEBUG: template_name = 'robots-debug.txt' else: template_name = 'robots.txt'
[ "haakenlid@gmail.com" ]
haakenlid@gmail.com
05d8f7afde2beb0ee1fa60b24698bbaec6bff6ee
53fab060fa262e5d5026e0807d93c75fb81e67b9
/backup/user_072/ch37_2019_10_01_17_50_41_334636.py
d8c0718ce3db7304a4911b49043117ba88bc9165
[]
no_license
gabriellaec/desoft-analise-exercicios
b77c6999424c5ce7e44086a12589a0ad43d6adca
01940ab0897aa6005764fc220b900e4d6161d36b
refs/heads/main
2023-01-31T17:19:42.050628
2020-12-16T05:21:31
2020-12-16T05:21:31
306,735,108
0
0
null
null
null
null
UTF-8
Python
false
false
481
py
def eh_primo(numero): i=3 if numero==0 or numero==1: return False if numero==2: return True if numero%2==0: return False while numero>i: if numero%i==0: return False i+=2 return True def lista_primos(z): i=1 lista=[] while len(lista)<z: if eh_primo(i)==True: lista.append(i) i+=1 return lista
[ "you@example.com" ]
you@example.com
dc9bfe97a28ba15b3cac30f50bd63591f69f984a
70b0d4b4440a97b648a08de0d89cc536e8f4c569
/programmersaddsum.py
c1984961c684f7f8ddcf59b1e5cede34e7782682
[]
no_license
seoseokbeom/leetcode
01c9ca8a23e38a3d3c91d2de26f0b2a3a1710487
9d68de2271c2d5666750c8060407b56abbf6f45d
refs/heads/master
2023-03-27T20:20:24.790750
2021-03-25T04:43:50
2021-03-25T04:43:50
273,779,517
1
0
null
null
null
null
UTF-8
Python
false
false
214
py
import itertools def solution(numbers): arriter = itertools.combinations(numbers, 2) res = set() for v in arriter: res.add(sum(v)) return sorted(list(res)) print(solution([5, 0, 2, 7]))
[ "pronunciatio@naver.com" ]
pronunciatio@naver.com
40cfca4342379984f26a53b5676ab401bdc45adf
67bafcfbd2caa774eb3765e6b2e28b7accbf1307
/API/run.py
59ff19dc4a977469c88d18edb48c65459cb43d58
[]
no_license
andy6804tw/digit-recognizer-project
9b8f1a226001665019bb15845db24138615ac81d
523920662cb853de0a08639ddfd449f0984a4d8e
refs/heads/master
2021-07-06T21:20:26.633250
2020-03-03T10:38:06
2020-03-03T10:38:06
230,412,581
3
0
null
2021-05-06T19:49:15
2019-12-27T09:19:50
HTML
UTF-8
Python
false
false
215
py
from app import app import config @app.route('/') def index(): return 'server started on '+str(config.PORT)+' PORT '+str(config.ENV) if __name__ == '__main__': print(app.url_map) app.run(port=config.PORT)
[ "andy6804tw@yahoo.com.tw" ]
andy6804tw@yahoo.com.tw
39e70a4daa73f14bc0fd321efc59599fa0359c32
7f9d4bce21b6d03ff7976c1462556db593abc2b2
/python3/0392.py
1756a1bf9cf8384ec1d78b45e95931f24318efe2
[]
no_license
crazykuma/leetcode
116343080f3869a5395fb60a46ac0556d170fa15
cc186fddf09592607bd18d333a99980703ac1ab3
refs/heads/master
2020-09-11T12:27:21.863546
2020-05-20T05:43:07
2020-05-20T05:43:07
222,064,196
0
0
null
null
null
null
UTF-8
Python
false
false
888
py
class Solution: def isSubsequence(self, s: str, t: str) -> bool: if not s: # s为空时是任何字符串的子集 return True if len(set(s)-set(t)) > 0: # s与t的差异不为空时,s不是任何t的子集 return False i, j = 0, 0 m, n = len(s), len(t) cur = '' while i < m and j < n: # 判断字符串t的值是否是下一个字符串s的值 if t[j] != s[i]: j += 1 else: cur += t[j] if s == cur: return True i += 1 j += 1 return False if __name__ == "__main__": s = Solution() assert s.isSubsequence("", "ahbgdc") == True assert s.isSubsequence("abc", "ahbgdc") == True assert s.isSubsequence("axc", "ahbgdc") == False
[ "crazykuma@qq.com" ]
crazykuma@qq.com
9a65e431490dc31d401ad844749544f12fa401fd
407aa951fe64227c685eccd698b59959f2093dfc
/featureTests/1_DATA_ANALYSIS/0_delete_samples.py
9b69d80728a4e044a45de5998d59a1fdae37bd30
[]
no_license
sycophant-stone/tf_base
32ad6798b2fcd728d959070a8eaf81649c9e247f
f6b4cb26fbc294e2a24dfa5d2ce05b9b33d77d41
refs/heads/master
2023-04-03T21:09:57.893549
2019-09-30T07:09:56
2019-09-30T07:09:56
138,027,678
4
0
null
2023-03-24T21:55:38
2018-06-20T12:06:55
Jupyter Notebook
UTF-8
Python
false
false
516
py
import os def select_intrest_pics(pic_path): n_img = len(os.listdir(pic_path)) print(n_img) #assert n_img == 9963, 'VOC2007 should be 9963 samples' for i in xrange(n_img): if i< 10: continue del_path = os.path.join(pic_path, '{:06d}.jpg'.format(i)) print('i:%d, num_img:%d, del_path:%s'%(i, n_img, del_path)) if os.path.exists(del_path): os.system('rm %s'%(del_path)) if __name__ == '__main__' : select_intrest_pics('VOC2007/JPEGImages/')
[ "kawayi_rendroid@163.com" ]
kawayi_rendroid@163.com
a2fb9b7cc2174067b3dd28bb67f67ab7ad054100
0627aa3a4b1349eccc56eb7315bd9e99bbf6d84b
/otus_stackoverflow/questions/urls.py
81d04bee9a183168f45298518d81bc7e558c1b85
[]
no_license
vsokoltsov/OTUS_PYTHON
93bc0efd8011bf47bb838d241e56703e6d9278f7
feac92294756385fe5021bfa838d27b9334d6b7b
refs/heads/master
2022-12-11T04:28:12.450518
2019-03-23T15:39:39
2019-03-23T15:39:39
177,306,191
0
0
null
2022-12-08T02:30:43
2019-03-23T15:31:22
Python
UTF-8
Python
false
false
1,537
py
from django.conf.urls import url from django.contrib.auth.decorators import login_required from rest_framework.routers import DefaultRouter from django.conf.urls import include from .views import ( QuestionsView, QuestionCreateView, QuestionDetailView, TagsListView, AnswerCreateView, VoteAnswerView, VoteQuestionView, SearchView ) from .api.v1 import QuestionViewSet router = DefaultRouter() router.register( 'v1/questions', QuestionViewSet, base_name='api_v1_questions' ) urlpatterns = [ url(r'^$', QuestionsView.as_view(), name='root_path'), url( r'^questions$', QuestionsView.as_view(), name='questions_list' ), url( r'^questions/new$', QuestionCreateView.as_view(), name='new_question' ), url( r'^questions/search$', SearchView.as_view(), name="questions_search" ), url( r'^questions/(?P<question_id>[A-Za-z0-9]*)$', QuestionDetailView.as_view(), name='question_detail' ), url( r'^questions/(?P<question_id>[A-Za-z0-9]*)/answers$', AnswerCreateView.as_view(), name="new_answer" ), url( r'^questions/(?P<question_id>[A-Za-z0-9]*)/vote$', VoteQuestionView.as_view(), name="vote_question" ), url( r'^questions/(?P<question_id>[A-Za-z0-9]*)/answers/' + r'(?P<answer_id>[A-Za-z0-9]*)/vote$', VoteAnswerView.as_view(), name="vote_answer" ), url( r'^tags$', TagsListView.as_view(), name='tags_list' ), url(r'api', include(router.urls)), ]
[ "vforvad@gmail.com" ]
vforvad@gmail.com
5adf8dc1a5f8953fc511c63cb60f5482a01c4c9f
9d40cb0b457b2c8c787af7185af664b20df6845e
/tabletloom/driver-fabric.py
9b064e9906999345e650bb7fd8b848d830ca79f5
[]
no_license
fo-am/patternmatrix2
f13365618179867a3e27efecf946ec8f5dea190d
3ec85b334f7da256b96265e29482641f38002f95
refs/heads/master
2023-04-12T06:46:15.469411
2022-02-22T13:53:16
2022-02-22T13:53:16
92,929,344
1
0
null
null
null
null
UTF-8
Python
false
false
3,146
py
import smbus import time import mcp23017 import tangible import osc bus = smbus.SMBus(1) mcp = [0x20,0x21,0x22,0x23] # sensor orientation dn = 0 up = 1 lr = 2 rl = 3 layout = [[0x20,0,dn], [0x20,1,dn], [0x20,2,dn], [0x20,3,dn], [0x21,0,dn], [0x21,1,dn], [0x21,2,dn], [0x21,3,dn], [0x22,0,dn], [0x22,1,dn], [0x22,2,dn], [0x22,3,dn], [0x23,0,dn], [0x23,1,dn], [0x23,2,dn], [0x23,3,dn]] tokens = {"circle": [[0,0,0,0],[1,1,1,1]], "rectangle": [[0,1, 1,0], [1,0, 0,1]], "triangle": [[1,1, 0,0], [0,1, 0,1], [0,0, 1,1], [1,0, 1,0]], "square": [[0,0,0,1],[0,0,1,0],[0,1,0,0],[1,0,0,0], [1,1,1,0],[1,1,0,1],[1,0,1,1],[0,1,1,1]]} for address in mcp: mcp23017.init_mcp(bus,address) grid = tangible.sensor_grid(25,layout,tokens) frequency=0.1 ####################################################### def convert_symbols(s): return {tangible.convert_4bit_twist(v):k for k, v in s} symbols = [["ccw",[1,1,1,1]],["cw",[0,0,0,0]], ["cw",[1,0,1,0]],["cw",[0,1,0,1]], ["flip-all",[1,1,0,0]],["flip-odd",[0,1,1,0]],["flip-even",[0,0,1,1]],["flip-fhalf",[1,0,0,1]], ["cw",[1,0,0,0]],["cw",[0,1,0,0]],["cw",[0,0,1,0]],["cw",[0,0,0,1]], ["cw",[0,1,1,1]],["cw",[1,0,1,1]],["cw",[1,1,0,1]],["cw",[1,1,1,0]]] symbols = convert_symbols(symbols) def build_pattern(data,symbols): pat=[] for i in range(0,4): s="" for v in data[i][:4]: s+=symbols[v]+" " pat.append(s) return pat def send_pattern(pat): osc.Message("/eval",["(weave-instructions '(\n"+pat+"))"]).sendlocal(8000) def send_col(col): print("colour shift: "+col) osc.Message("/eval",["(play-now (mul (adsr 0 0.1 1 0.1)"+ "(sine (mul (sine 30) 800))) 0)"+ "(set-warp-yarn! loom warp-yarn-"+col+")"+ "(set-weft-yarn! loom weft-yarn-"+col+")"]).sendlocal(8000) ####################################################### last="" last_col=0 while True: for address in mcp: grid.update(frequency,address, mcp23017.read_inputs_a(bus,address), mcp23017.read_inputs_b(bus,address)) pat = build_pattern(grid.data(4),symbols) cc = pat[0]+pat[1]+pat[2]+pat[3] if cc!=last: last=cc print(" "+pat[0]+pat[1]+pat[2]+pat[3]+"\n") send_pattern(cc) col=grid.state[15].value_current if False: #col!=last_col: last_col=col if col==1: send_col("a") if col==2: send_col("b") if col==4: send_col("c") if col==8: send_col("d") if col==7: send_col("e") if col==11: send_col("f") if col==13: send_col("g") if col==14: send_col("h") #grid.pprint(5) time.sleep(frequency)
[ "dave@fo.am" ]
dave@fo.am
e9054bddbbdc4a4c693bbaaf2cbc2fed48ce3e8f
380372bbec9b77df14bb96fc32aca7061cca0635
/astro/moon/iss1.py
cbe0e79c2cab4b1eabf19ca8b6856b125462b177
[]
no_license
IchiroYoshida/python_public
d3c42dc31b3206db3a520a007ea4fb4ce6c1a6fd
37ccadb1d3d42a38561c7708391f4c11836f5360
refs/heads/master
2023-08-16T17:19:07.278554
2023-08-13T21:29:51
2023-08-13T21:29:51
77,261,682
2
0
null
null
null
null
UTF-8
Python
false
false
779
py
import math import time from datetime import datetime import ephem degrees_per_radian = 180.0 / math.pi home = ephem.Observer() home.lon = '-122.63' # +E home.lat = '45.56' # +N home.elevation = 80 # meters # Always get the latest ISS TLE data from: # http://spaceflight.nasa.gov/realdata/sightings/SSapplications/Post/JavaSSOP/orbit/ISS/SVPOST.html iss = ephem.readtle('ISS', '1 25544U 98067A 16165.54018716 .00016717 00000-0 10270-3 0 9008', '2 25544 51.6441 76.2279 0000507 322.3584 37.7533 15.54548251 4412' ) while True: home.date = datetime.utcnow() iss.compute(home) print('iss: altitude %4.1f deg, azimuth %5.1f deg' % (iss.alt * degrees_per_radian, iss.az * degrees_per_radian)) time.sleep(1.0)
[ "yoshida.ichi@gmail.com" ]
yoshida.ichi@gmail.com
2ccc9be68390f86c4dc72a2aed2aba3c9e87f173
53fab060fa262e5d5026e0807d93c75fb81e67b9
/backup/user_169/ch146_2020_04_12_17_11_21_542240.py
756543924c51ab18f1a1af082e34978cca04a01f
[]
no_license
gabriellaec/desoft-analise-exercicios
b77c6999424c5ce7e44086a12589a0ad43d6adca
01940ab0897aa6005764fc220b900e4d6161d36b
refs/heads/main
2023-01-31T17:19:42.050628
2020-12-16T05:21:31
2020-12-16T05:21:31
306,735,108
0
0
null
null
null
null
UTF-8
Python
false
false
542
py
def conta_ocorrencias(lista): lista2=[] lista3=[] for i in range(len(lista)): lista.count(lista[i]) lista3.append( lista.count(lista[i]) ) for i in lista3: if lista3.count(i)>1: lista3.remove(i) for i in lista: if lista.count(i)>1: lista.remove(i) for i in range(len(lista)): lista2.append(lista[i]) list(zip(lista2,lista3)) dict(zip(lista2,lista3)) return dict(zip(lista2,lista3))
[ "you@example.com" ]
you@example.com
e66245d10fdc516e42f9e199e11f20956954434a
490f5e517942f529ddc8c1e0d421a208ff1ca29b
/02_code/exctools.py
828134802f8e1fac0826f0e6ff3cd498809b3b4f
[]
no_license
emnglang/py-lab
facdc464a8c84b90f06b5cb639315981c0b4ba8d
bc3566da81e0b2cfa9ce563ffc198d35294971a1
refs/heads/master
2020-03-25T15:10:42.856062
2018-08-24T14:54:33
2018-08-24T14:54:33
143,869,343
0
0
null
null
null
null
UTF-8
Python
false
false
334
py
import sys, traceback def safe(callee, *pargs, **kargs): try: callee(*pargs, **kargs) # Catch everything else except: # Or "except Exception as E:" traceback.print_exc() print('Got %s %s' % (sys.exc_info()[0], sys.exc_info()[1])) if __name__ == '__main__': import oops2 safe(oops2.oops)
[ "linja1688@gmail.com" ]
linja1688@gmail.com
5cb5b24b3295a6a98df8c170a567fba75aec2d0a
2387b5ecf12d9a17976e049e4adbf739edafc830
/core/migrations/0002_auto_20150511_1223.py
79c7b2c9754a0743a3a1d31bc73b26c92766009c
[]
no_license
nathananderson03/britdoc
3ce0b1141a648fce30056ca32fd8665ed6cf4971
ddb921ed82088abbacdbb625baf3c9cae7987ccb
refs/heads/master
2021-01-17T06:29:23.812112
2016-07-20T16:39:25
2016-07-20T16:39:25
63,797,054
0
0
null
null
null
null
UTF-8
Python
false
false
806
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('core', '0001_initial'), ] operations = [ migrations.AlterField( model_name='film', name='production_year', field=models.IntegerField(default=2015, verbose_name='Year of Completion', choices=[(1990, 1990), (1991, 1991), (1992, 1992), (1993, 1993), (1994, 1994), (1995, 1995), (1996, 1996), (1997, 1997), (1998, 1998), (1999, 1999), (2000, 2000), (2001, 2001), (2002, 2002), (2003, 2003), (2004, 2004), (2005, 2005), (2006, 2006), (2007, 2007), (2008, 2008), (2009, 2009), (2010, 2010), (2011, 2011), (2012, 2012), (2013, 2013), (2014, 2014), (2015, 2015)]), ), ]
[ "nathan.andersson03@gmail.com" ]
nathan.andersson03@gmail.com
b91811713854a626b904698f64ca3f4bd8e8740d
2cc483723d7cb9c7a2b145b03e41a564e0c5449a
/app/save_weights.py
0491cd1aebebbc6630ecd45aef737b48c80335c3
[]
no_license
MattSegal/QueensSpeech
cb7331860393e30847dd0b4bb7dd9edd77ca3cb0
cf868bacbaf5b0871dbccc7024ec06857b07aa5c
refs/heads/master
2021-03-12T20:24:30.281294
2017-05-16T12:54:22
2017-05-16T12:54:22
91,458,300
0
0
null
null
null
null
UTF-8
Python
false
false
845
py
import cPickle import numpy as np import os.path def get_name(file): base_path = os.path.dirname(os.path.realpath(__file__)) return base_path + os.path.normpath('/weights/'+file) f = open('net.pkl','rb') net = cPickle.loads(f.read()) parallel_layer = net.layers[0] hidden_layer_1 = net.layers[1] hidden_layer_2 = net.layers[2] softmax_layer = net.layers[3] np.savetxt(get_name('0_weights.arr'),parallel_layer.layer.weights) np.savetxt(get_name('1_weights.arr'),hidden_layer_1.weights) np.savetxt(get_name('2_weights.arr'),hidden_layer_2.weights) np.savetxt(get_name('3_weights.arr'),softmax_layer.weights) np.savetxt(get_name('0_bias.arr'),parallel_layer.layer.bias) np.savetxt(get_name('1_bias.arr'),hidden_layer_1.bias) np.savetxt(get_name('2_bias.arr'),hidden_layer_2.bias) np.savetxt(get_name('3_bias.arr'),softmax_layer.bias)
[ "mattdsegal@gmail.com" ]
mattdsegal@gmail.com
7329a13090fbf583b35134b78c4ef08362f28dc2
2dd3dd778f4f3ef3ca143636a42ce777e948dfc1
/select_ptk2.py
4d3d32d4f27ba2275054b5fd74b8458fa5c1c635
[]
no_license
vaaaaanquish-xx/select-command-using-ptk
64aea38b9b686c024a624baf2064cfe9f1cea255
07b6c7baddff15e8838a6b9b9a4b314450a9f1f9
refs/heads/master
2020-04-07T16:08:55.648027
2018-11-22T15:03:23
2018-11-22T15:03:23
158,517,117
1
1
null
null
null
null
UTF-8
Python
false
false
4,009
py
# -*- coding: utf-8 -*- # ptk 2.x ver from prompt_toolkit.application import Application from prompt_toolkit.layout.margins import ScrollbarMargin from prompt_toolkit.filters import IsDone from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.layout.containers import Window from prompt_toolkit.layout.containers import ConditionalContainer from prompt_toolkit.layout.containers import ScrollOffsets from prompt_toolkit.layout.containers import HSplit from prompt_toolkit.layout.controls import FormattedTextControl from prompt_toolkit.layout.dimension import LayoutDimension as D from prompt_toolkit.layout.layout import Layout from prompt_toolkit.mouse_events import MouseEventType from prompt_toolkit.styles import Style from prompt_toolkit.styles import pygments_token_to_classname from prompt_toolkit.styles.pygments import style_from_pygments_dict from pygments.token import Token import subprocess choices = ['ls', 'ifconfig', 'pwd', 'who'] string_query = ' Command Select ' inst = ' (Use arrow keys)' def selected_item(text): res = subprocess.call(text) print(res) class InquirerControl(FormattedTextControl): selected_option_index = 0 answered = False def __init__(self, choices, **kwargs): self.choices = choices super(InquirerControl, self).__init__(self._get_choice_tokens, **kwargs) @property def choice_count(self): return len(self.choices) def _get_choice_tokens(self): tokens = [] T = Token def append(index, label): selected = (index == self.selected_option_index) def select_item(app, mouse_event): self.selected_option_index = index self.answered = True token = T.Selected if selected else T tokens.append((T.Selected if selected else T, ' > ' if selected else ' ')) if selected: tokens.append((Token.SetCursorPosition, '')) tokens.append((T.Selected if selected else T, '%-24s' % label, select_item)) tokens.append((T, '\n')) for i, choice in enumerate(self.choices): append(i, choice) tokens.pop() return [('class:'+pygments_token_to_classname(x[0]), str(x[1])) for x in tokens] def get_selection(self): return self.choices[self.selected_option_index] ic = InquirerControl(choices) def get_prompt_tokens(): tokens = [] T = Token tokens.append((Token.QuestionMark, '?')) tokens.append((Token.Question, string_query)) if ic.answered: tokens.append((Token.Answer, ' ' + ic.get_selection())) selected_item(ic.get_selection()) else: tokens.append((Token.Instruction, inst)) return [('class:'+pygments_token_to_classname(x[0]), str(x[1])) for x in tokens] HSContainer = HSplit([ Window(height=D.exact(1), content=FormattedTextControl(get_prompt_tokens)), ConditionalContainer( Window( ic, width=D.exact(43), height=D(min=3), scroll_offsets=ScrollOffsets(top=1, bottom=1) ), filter=~IsDone())]) layout = Layout(HSContainer) kb = KeyBindings() @kb.add('c-q', eager=True) @kb.add('c-c', eager=True) def _(event): event.app.exit(None) @kb.add('down', eager=True) def move_cursor_down(event): ic.selected_option_index = ( (ic.selected_option_index + 1) % ic.choice_count) @kb.add('up', eager=True) def move_cursor_up(event): ic.selected_option_index = ( (ic.selected_option_index - 1) % ic.choice_count) @kb.add('enter', eager=True) def set_answer(event): ic.answered = True event.app.exit(None) inquirer_style = style_from_pygments_dict({ Token.QuestionMark: '#5F819D', Token.Selected: '#FF9D00', Token.Instruction: '', Token.Answer: '#FF9D00 bold', Token.Question: 'bold' }) app = Application( layout=layout, key_bindings=kb, mouse_support=False, style=inquirer_style ) app.run()
[ "6syun9@gmail.com" ]
6syun9@gmail.com
677e75005b39feb32f9b2e382f9ccb08f2840189
c9b5ed2eb5d596f141004f7b82e79bc2fb36072d
/equipes/api/serializers.py
ac8cb9a5c81ec70d5e9358ed8f90924bad2664d4
[]
no_license
jocsakesley/encontrocomcristo
3fd670544a42abfc43f2c2d6a34c8e3fdd9d2550
8e9bbf41f6d80f2ac15fc4240ff4b108957d5cd6
refs/heads/master
2023-02-24T15:20:01.129002
2021-02-04T17:33:06
2021-02-04T17:33:06
330,020,768
0
0
null
null
null
null
UTF-8
Python
false
false
1,535
py
from rest_framework import serializers from equipes.models import Equipe from funcao.models import Funcao from participantes.api.serializers import ParticipantesSerializer from participantes.models import Participante class EquipesSerializer(serializers.ModelSerializer): lider = ParticipantesSerializer() membros = ParticipantesSerializer(many=True) class Meta: model = Equipe fields = "__all__" def cria_membros(self, membros, equipes): for membro in membros: funcao = membro['funcao'] del membro['funcao'] func = Funcao.objects.get_or_create(**funcao)[0] membro['funcao'] = func mb = Participante.objects.get_or_create(**membro)[0] print(mb) equipes.membros.add(mb) def create(self, validated_data): print(dict(validated_data['lider'])) lider = validated_data['lider'] del validated_data['lider'] membros = validated_data['membros'] del validated_data['membros'] equipes = Equipe.objects.create(**validated_data) self.cria_membros(membros, equipes) funcao = dict(lider) funcao = dict(funcao['funcao']) print(funcao) func = Funcao.objects.get_or_create(**funcao)[0] lider = dict(lider) lider['funcao'] = func lid = Participante.objects.get_or_create(**lider)[0] equipes.lider = lid equipes.save() return equipes #def update(self, instance, validated_data):
[ "jocsadm@gmail.com" ]
jocsadm@gmail.com
700c728094234c49a378ee39c18548edcf4cdc70
6d960d2ac7cb38f3e2db21cf59c10b2a734fcf42
/code/scripts/searchlight_movie_perms.py
78220d4547a9214baf26589ec742393540bbda49
[ "MIT" ]
permissive
physthoth/sherlock-topic-model-paper
2d86a1581ffc8a5fca553656bb1ca67f73bf634c
4f77750c436264585879efb9f91957dc555f36a9
refs/heads/master
2020-09-25T11:13:32.457422
2018-10-08T18:40:17
2018-10-08T18:40:17
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,578
py
import sys import numpy as np from nilearn.image import load_img from brainiak.searchlight.searchlight import Searchlight import pandas as pd subid = int(sys.argv[1]) perm = int(sys.argv[2]) np.random.seed(perm) # load fmri data data = load_img('/idata/cdl/data/fMRI/andy/sherlock/data/sherlock_movie_s%s_10000.nii.gz' % str(subid)).get_data() # load dtw warp path and extract the movie path #path = np.load('/idata/cdl/data/fMRI/andy/sherlock/data/s%s_dtw_path.npy' % str(subid)) #movie_path = np.array(list(map(lambda x: x[0], path))) # reindex the fmri data with the movie path #data = data[:,:,:, movie_path] # create the mask mask = data[:,:,:,0]!=10000 # load video model model = np.load('/idata/cdl/data/fMRI/andy/sherlock/data/movie_corrmat.npy') # shift the video model shift = np.random.randint(1, model.shape[0]-1) shifted = np.roll(model, shift=shift, axis=0) # recompute shifted correlation matrix model = pd.DataFrame(shifted).T.corr().values # Create searchlight object params = dict(sl_rad=5) sl = Searchlight(**params) # Distribute data to processes sl.distribute([data], mask) sl.broadcast(model) # Define voxel function def sfn(l, msk, myrad, bcast_var): from scipy.spatial.distance import cdist from scipy.stats import pearsonr b = l[0][msk,:].T c = 1 - cdist(b, b, 'correlation').ravel() return pearsonr(c, bcast_var.ravel())[0] # Run searchlight result = sl.run_searchlight(sfn) np.save('/idata/cdl/data/fMRI/andy/sherlock/analyses/searchlight_movie/perms/s%s_perm%s_shift%s' % (str(subid), str(perm), str(shift)), result)
[ "andrew.heusser@gmail.com" ]
andrew.heusser@gmail.com
c2d7cb06a8b114a948211b5dd7d2cfe7c0012b7d
1925c535d439d2d47e27ace779f08be0b2a75750
/bloomberg/same_tree.py
e61ffeb81f1564b400d34c9b10a77d2466f534f5
[]
no_license
arthurDz/algorithm-studies
ee77d716041671c4b8bb757d8d96f3d10b6589f7
1e4d23dd0c40df34f58d71c7ca3e6491be732075
refs/heads/master
2023-04-27T12:17:06.209278
2021-04-30T20:16:18
2021-04-30T20:16:18
null
0
0
null
null
null
null
UTF-8
Python
false
false
841
py
# Given two binary trees, write a function to check if they are the same or not. # Two binary trees are considered the same if they are structurally identical and the nodes have the same value. # Example 1: # Input: 1 1 # / \ / \ # 2 3 2 3 # [1,2,3], [1,2,3] # Output: true # Example 2: # Input: 1 1 # / \ # 2 2 # [1,2], [1,null,2] # Output: false # Example 3: # Input: 1 1 # / \ / \ # 2 1 1 2 # [1,2,1], [1,1,2] # Output: false def isSameTree(self, p, q): if not p and not q: return True if (not p and q) or (not q and p) or (p.val != q.val): return False return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
[ "yunfan.yang@minerva.kgi.edu" ]
yunfan.yang@minerva.kgi.edu
dd52c60b639b8ff8d22bc8853e5f0b95231434bd
3d07a6eb8cba4f6821c4a36c508e2f2cf1e407ee
/ps6/ps6_3.py
33b87f81d5ed9f3b5be283898e4429c8d8dd00e6
[]
no_license
claraqqqq/i_c_s_p_a_t_m_i_t
d4aaa9a176b698e8c402674de0a1bfe2d0e1e6ae
3a0cae66fab7320a55ed3403b11c042bd347dcda
refs/heads/master
2021-01-19T09:44:50.012962
2015-04-07T15:13:45
2015-04-07T15:13:45
29,719,682
0
0
null
null
null
null
UTF-8
Python
false
false
759
py
# ENCRYPTION """ strings. encode to them use to able be should you applyCoder, and buildCoder written have you Once Cases Test 8) test.', a is applyShift('This >>> bmab.' i qa 'Bpqa 18) bmab.', i qa applyShift('Bpqa >>> test.' a is 'This """ def applyShift(text, shift): """ shift given the by shifted Caesar text new a returns text, a Given case upper case, lower remain should letters case Lower offset. should punctuation other all and case, upper remain should letters is. it as stay to shift the apply to string text: 26) < int <= (0 text the shift to amount shift: amount. specified by shifted being after text returns: """ ### TODO. ### HINT: This is a wrapper function. coder = buildCoder(shift) return applyCoder(text, coder)
[ "claraqqqq@gmail.com" ]
claraqqqq@gmail.com
a510e0648dd38fe7c0ec63582bf5a346f19838c2
eeb469954b768095f2b8ad2376f1a114a3adb3fa
/961.py
9ceaffbdf9802217725e20fd681051191aa438b9
[ "MIT" ]
permissive
RafaelHuang87/Leet-Code-Practice
ef18dda633932e3cce479f7d5411552d43da0259
7754dcee38ffda18a5759113ef06d7becf4fe728
refs/heads/master
2020-07-18T20:09:10.311141
2020-02-11T09:56:39
2020-02-11T09:56:39
206,305,113
0
0
null
null
null
null
UTF-8
Python
false
false
274
py
""" Solution for Leet Code 961. """ class Solution: def repeatedNTimes(A): temp = {} for data in A: if data not in temp: temp[data] = 1 else: return data print(Solution.repeatedNTimes([1,3,2,1]))
[ "rafaelhuang@163.com" ]
rafaelhuang@163.com
5388a6574e30e9d7340f6908a1a97e1f2eedf4c7
da1721d2783ea4d67ff4e73cee6eee71292f2ef7
/toontown/ai/DistributedSillyMeterMgr.py
a45f47422f60ca9ce436eee33a9023ca2d40d653
[ "BSD-3-Clause" ]
permissive
open-toontown/open-toontown
bbdeb1b7bf0fb2861eba2df5483738c0112090ca
464c2d45f60551c31397bd03561582804e760b4a
refs/heads/develop
2023-07-07T01:34:31.959657
2023-05-30T23:49:10
2023-05-30T23:49:10
219,221,570
143
104
BSD-3-Clause
2023-09-11T09:52:34
2019-11-02T22:24:38
Python
UTF-8
Python
false
false
2,339
py
from direct.directnotify import DirectNotifyGlobal from direct.distributed import DistributedObject from toontown.ai import DistributedPhaseEventMgr import time class DistributedSillyMeterMgr(DistributedPhaseEventMgr.DistributedPhaseEventMgr): neverDisable = 1 notify = DirectNotifyGlobal.directNotify.newCategory('DistributedSillyMeterMgr') def __init__(self, cr): DistributedPhaseEventMgr.DistributedPhaseEventMgr.__init__(self, cr) cr.SillyMeterMgr = self def announceGenerate(self): DistributedPhaseEventMgr.DistributedPhaseEventMgr.announceGenerate(self) messenger.send('SillyMeterIsRunning', [self.isRunning]) def delete(self): self.notify.debug('deleting SillyMetermgr') messenger.send('SillyMeterIsRunning', [False]) DistributedPhaseEventMgr.DistributedPhaseEventMgr.delete(self) if hasattr(self.cr, 'SillyMeterMgr'): del self.cr.SillyMeterMgr def setCurPhase(self, newPhase): DistributedPhaseEventMgr.DistributedPhaseEventMgr.setCurPhase(self, newPhase) messenger.send('SillyMeterPhase', [newPhase]) def setIsRunning(self, isRunning): DistributedPhaseEventMgr.DistributedPhaseEventMgr.setIsRunning(self, isRunning) messenger.send('SillyMeterIsRunning', [isRunning]) def getCurPhaseDuration(self): if len(self.holidayDates) > 0: startHolidayDate = self.holidayDates[self.curPhase] if self.curPhase + 1 >= len(self.holidayDates): self.notify.error('No end date for phase %' % self.curPhase) return -1 else: endHolidayDate = self.holidayDates[self.curPhase + 1] startHolidayTime = time.mktime(startHolidayDate.timetuple()) endHolidayTime = time.mktime(endHolidayDate.timetuple()) holidayDuration = endHolidayTime - startHolidayTime if holidayDuration < 0: self.notify.error('Duration not set for phase %' % self.curPhase) return -1 else: return holidayDuration else: self.notify.warning('Phase dates not yet known') return -1 def getCurPhaseStartDate(self): if len(self.holidayDates) > 0: return self.holidayDates[self.curPhase]
[ "jwcotejr@gmail.com" ]
jwcotejr@gmail.com
ede1040ed424de83ddae76fb583b84076606c140
5002d20adbd983963f71ceb0bfaea148b1cbc079
/CSE/CSE Major Projects - 2017_21/Politeness Transfer_ A Tag and Generate Approach/code/be-af.py
e316ef98b46f41f7fb3320e27fd4b00cebb5e039
[]
no_license
19WH1A0578/BVRITHYDERABAD
d15863ab255837bc11e49ff0742f6d6ab32c2c28
2492f5bd0eebf9103566a0cc7f96d732407c4317
refs/heads/main
2023-07-03T01:46:12.654932
2021-07-31T07:09:54
2021-07-31T07:09:54
384,429,090
1
0
null
2021-07-09T12:23:28
2021-07-09T12:23:28
null
UTF-8
Python
false
false
1,082
py
# -*- coding: utf-8 -*- import pandas as pd import os from convokit import Corpus, Utterance, Speaker from convokit import PolitenessStrategies train_corpus = Corpus(filename=("data/train/training-corpus/")) ps = PolitenessStrategies(strategy_attribute_name = "strategies", \ marker_attribute_name = "markers", \ strategy_collection="politeness_local") # it is important to set markers to True train_corpus = ps.transform(train_corpus, markers=True) for utt in train_corpus.iter_utterances(): strategy_split = utt.meta['strategy'] assert utt.meta['strategies'][strategy_split] == 1 # helper functions further detailed in Marker_Edits.ipynb from strategy_manipulation import remove_strategies_from_utt for utt in train_corpus.iter_utterances(): remove_strategies_from_utt(utt, [utt.meta['strategy']]) utt = train_corpus.get_utterance('100087711.41.31') # 100087711.41.31 # 10387534.0.0 # 105319599.26773.0 print("BEFORE:", utt.text) print("AFTER:", utt.meta)
[ "saisudhavadisina@gmail.com" ]
saisudhavadisina@gmail.com
660d20122ec3c754f92aa8e51fb1153f3787c410
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p02901/s827366183.py
e8d52e3e5d9a72d4e8c404ef73945cacb67be0a1
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
794
py
INF = 2*10**7 def main(): N, M = (int(i) for i in input().split()) A = [] B = [] C = [] for _ in range(M): a, b = (int(i) for i in input().split()) A.append(a) B.append(b) bit = 0 for i in input().split(): bit |= (1 << (int(i)-1)) C.append(bit) dp = [[INF]*(1 << N) for _ in range(M+1)] dp[0][0] = 0 for i in range(M): for j in range(1 << N): dp[i+1][j] = min(dp[i+1][j], dp[i][j]) if dp[i][j] != INF: next_bit = j | C[i] dp[i+1][next_bit] = min(dp[i+1][next_bit], dp[i][j] + A[i]) ans = dp[-1][-1] if ans == INF: print(-1) else: print(ans) # print(*dp, sep="\n") if __name__ == '__main__': main()
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
d63665e90489f68f80177c8430c39c23d6a03832
f80ef3a3cf859b13e8af8433af549b6b1043bf6e
/pyobjc-framework-SystemConfiguration/Lib/SystemConfiguration/__init__.py
cf487eb2587ebcfb8bbfd19031f0c22d49f7614c
[ "MIT" ]
permissive
ronaldoussoren/pyobjc
29dc9ca0af838a56105a9ddd62fb38ec415f0b86
77b98382e52818690449111cd2e23cd469b53cf5
refs/heads/master
2023-09-01T05:15:21.814504
2023-06-13T20:00:17
2023-06-13T20:00:17
243,933,900
439
49
null
2023-06-25T02:49:07
2020-02-29T08:43:12
Python
UTF-8
Python
false
false
993
py
""" Python mapping for the SystemConfiguration framework. This module does not contain docstrings for the wrapped code, check Apple's documentation for details on how to use these functions and classes. """ import sys import Foundation import objc from SystemConfiguration import _metadata sys.modules["SystemConfiguration"] = mod = objc.ObjCLazyModule( "SystemConfiguration", "com.apple.SystemConfiguration", objc.pathForFramework("/System/Library/Frameworks/SystemConfiguration.framework"), _metadata.__dict__, None, { "__doc__": __doc__, "__path__": __path__, "__loader__": globals().get("__loader__", None), "objc": objc, }, (Foundation,), ) del sys.modules["SystemConfiguration._metadata"] import SystemConfiguration._manual as m # isort:skip # noqa: E402 for nm in dir(m): setattr(mod, nm, getattr(m, nm)) mod.SCBondInterfaceRef = mod.SCNetworkInterfaceRef mod.SCVLANInterfaceRef = mod.SCNetworkInterfaceRef
[ "ronaldoussoren@mac.com" ]
ronaldoussoren@mac.com
bd25c0f81a90e0e4885aa39d8448b944fd5868c5
5c309a45507e26ac7320a474d82c5887c7af9f30
/MySite/MySite/urls.py
4ce2d92aeef3abf905ee0d81702179359a2608c5
[]
no_license
MMohan1/MySite
09c003dcad8158ee3e16a5d14405cb6aaeb396fe
c14c2fb13cff10e79b8cb444ec1cf4996c7742cc
refs/heads/master
2021-01-22T13:08:37.734894
2014-12-25T09:37:39
2014-12-25T09:37:39
null
0
0
null
null
null
null
UTF-8
Python
false
false
420
py
from django.conf.urls import patterns, include, url from django.contrib import admin urlpatterns = patterns('', # Examples: # url(r'^$', 'MySite.views.home', name='home'), url(r'^polls/', include('polls.urls', namespace="polls")), url(r'^admin/', include(admin.site.urls)), )
[ "manmohansharma987@gmail.com" ]
manmohansharma987@gmail.com
93055757e6e1ffa121edea16b0567e884338203f
b05fee086482565ef48785f2a9c57cfe2c169f68
/part_one/3-observer_pattern/after/observer/subject_abc.py
f2fb23403b3aafcbd9450c06eee0527def13727a
[]
no_license
diegogcc/py-design_patterns
76db926878d5baf9aea1f3d2f6a09f4866c3ce1e
2b49b981f2d3514bbd02796fe9a8ec083df6bb38
refs/heads/master
2023-04-01T08:28:53.211024
2021-04-05T11:48:19
2021-04-05T11:48:19
304,145,791
0
0
null
null
null
null
UTF-8
Python
false
false
575
py
from abc import ABCMeta from observer import ABCObserver class ABCSubject(metaclass=ABCMeta): _observers = set() def attach(self, observer): if not isinstance(observer, ABCObserver): raise TypeError('Observer not derived from ABCObserver') self._observers |= {observer} def detach(self, observer): self._observers -= {observer} def notify(self, value=None): for observer in self._observers: if value is None: observer.update() else: observer.update(value)
[ "diegoc906@gmail.com" ]
diegoc906@gmail.com
12a7c034769b181f60b365d9088a81e33ef47347
15f321878face2af9317363c5f6de1e5ddd9b749
/solutions_python/Problem_200/260.py
d0237b341a7b08a08d30d63213739e6e1ee988f4
[]
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
773
py
def good(numberStr): numberList = map(int, list(numberStr)) length = len(numberList) notYetFix = 0 for i in range(length - 1): if numberList[i] < numberList[i+1]: notYetFix = i+1 elif numberList[i] > numberList[i+1]: break elif i == length - 2 and numberList[i] == numberList[i+1]: notYetFix = length - 1 if notYetFix != length - 1: numberList[notYetFix] -= 1 for j in range(notYetFix+1, length): numberList[j] = 9 resultList = map(str, numberList) if resultList[0] == '0': resultList[0] = '' return ''.join(resultList) n = int(raw_input()) for i in range(n): input = raw_input().strip() print "Case #{0}: {1}".format(i+1, good(input))
[ "miliar1732@gmail.com" ]
miliar1732@gmail.com
5fa492dd4548a8e0b896cfcc59dd262eb4d1a0b2
315b5795445848af093839214d7ce852b3080b66
/Scrapy/tutorial/tutorial/spiders/quotes_spider.py
89a646ff776c9e851e87e2a6ae5bb192d7aa9e63
[]
no_license
yangyang0126/PythonSpider
030657a04d91850c1bfe19a685f83e5dff670aeb
eb2b12557735eddf43603155a23bd582531c387d
refs/heads/master
2021-06-25T16:21:39.561541
2021-03-31T11:03:17
2021-03-31T11:03:17
213,564,028
4
2
null
null
null
null
UTF-8
Python
false
false
1,008
py
# -*- coding: utf-8 -*- """ Created on Tue May 5 17:55:42 2020 @author: zhaoy """ import scrapy class QuotesSpider(scrapy.Spider): name = "quotes" start_urls = [ 'http://quotes.toscrape.com/page/1/', 'http://quotes.toscrape.com/page/2/', ] def parse(self, response): page = response.url.split("/")[-2] filename = 'quotes-%s.html' % page with open(filename, 'wb') as f: f.write(response.body) self.log('Saved file %s' % filename) for quote in response.css('div.quote'): yield { 'text': quote.css('span.text::text').get(), 'author': quote.css('small.author::text').get(), 'tags': quote.css('div.tags a.tag::text').getall(), } next_page = response.css('li.next a').attrib['href'] if next_page is not None: yield scrapy.follow(next_page, callback=self.parse)
[ "zhaojingyi0126@163.com" ]
zhaojingyi0126@163.com
178fea7a115e8617e01db117b27aadc0ff3258ef
2545252679e65a1912a56a8e6cfd3f3f8e26af87
/virtualenv/Scripts/pilprint.py
fd424994966180548bd4c1b7369a7139513279fc
[]
no_license
tubbatun/customize-django-oscar-templates-
796a1288cd18f12258c3c20958ce84e8fdb9af78
41404e4aa59aa36a4159034af7fab32a8b3b3263
refs/heads/master
2021-01-11T11:37:46.098571
2016-12-19T10:55:02
2016-12-19T10:55:02
76,853,932
1
0
null
null
null
null
UTF-8
Python
false
false
2,642
py
#!c:\users\sathi\desktop\tryoscar\virtualenv\scripts\python.exe # # The Python Imaging Library. # $Id$ # # print image files to postscript printer # # History: # 0.1 1996-04-20 fl Created # 0.2 1996-10-04 fl Use draft mode when converting. # 0.3 2003-05-06 fl Fixed a typo or two. # from __future__ import print_function import getopt import os import sys import subprocess VERSION = "pilprint 0.3/2003-05-05" from PIL import Image from PIL import PSDraw letter = (1.0*72, 1.0*72, 7.5*72, 10.0*72) def description(filepath, image): title = os.path.splitext(os.path.split(filepath)[1])[0] format = " (%dx%d " if image.format: format = " (" + image.format + " %dx%d " return title + format % image.size + image.mode + ")" if len(sys.argv) == 1: print("PIL Print 0.3/2003-05-05 -- print image files") print("Usage: pilprint files...") print("Options:") print(" -c colour printer (default is monochrome)") print(" -d debug (show available drivers)") print(" -p print via lpr (default is stdout)") print(" -P <printer> same as -p but use given printer") sys.exit(1) try: opt, argv = getopt.getopt(sys.argv[1:], "cdpP:") except getopt.error as v: print(v) sys.exit(1) printerArgs = [] # print to stdout monochrome = 1 # reduce file size for most common case for o, a in opt: if o == "-d": # debug: show available drivers Image.init() print(Image.ID) sys.exit(1) elif o == "-c": # colour printer monochrome = 0 elif o == "-p": # default printer channel printerArgs = ["lpr"] elif o == "-P": # printer channel printerArgs = ["lpr", "-P%s" % a] for filepath in argv: try: im = Image.open(filepath) title = description(filepath, im) if monochrome and im.mode not in ["1", "L"]: im.draft("L", im.size) im = im.convert("L") if printerArgs: p = subprocess.Popen(printerArgs, stdin=subprocess.PIPE) fp = p.stdin else: fp = sys.stdout ps = PSDraw.PSDraw(fp) ps.begin_document() ps.setfont("Helvetica-Narrow-Bold", 18) ps.text((letter[0], letter[3]+24), title) ps.setfont("Helvetica-Narrow-Bold", 8) ps.text((letter[0], letter[1]-30), VERSION) ps.image(letter, im) ps.end_document() if printerArgs: fp.close() except: print("cannot print image", end=' ') print("(%s:%s)" % (sys.exc_info()[0], sys.exc_info()[1]))
[ "sathi@mahdil.com" ]
sathi@mahdil.com
8b1d765af3d85bf9ff7d1ae97ba2b77b9ad6777e
24d9f077593b33c707b12d3a00cf91750f740729
/src/utils.py
8efc2f56c796915263859578fe1363f3dbb0998e
[ "Apache-2.0" ]
permissive
xiaonanln/myleetcode-python
274c8b8d7c29fd74dd11beb845180fb4e415dcd1
95d282f21a257f937cd22ef20c3590a69919e307
refs/heads/master
2021-01-22T21:45:59.786543
2019-04-21T15:24:23
2019-04-21T15:24:23
85,474,052
0
0
null
null
null
null
UTF-8
Python
false
false
2,012
py
import sys def mdarray(initVal, *dims): return [initVal] * dims[0] if len(dims) == 1 else [ mdarray(initVal, *dims[1:]) for _ in xrange(dims[0])] class ListNode: def __init__(self, x): self.val = x self.next = None def printlist(head): n = head vals = [] while n is not None: vals.append(n.val) n = n.next print '->'.join(map(str, vals)) + '->[end]' def makelist(*values): if len(values) == 1 and isinstance(values[0], list): values = values[0] if not values: return None head = None prev = None for val in values: node = ListNode(val) if head is None: head = node prev = node else: prev.next = node prev = node return head class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def maketree(values): if len(values) == 1 and isinstance(values[0], list): values = values[0] if not values: return None root = TreeNode(values[0]) next = 1 deepest = [root] while next < len(values): assert deepest, (deepest, values) new_deepest = [] for node in deepest: node.left = TreeNode(values[next]) if next < len(values) and values[next] is not None else None node.right = TreeNode(values[next+1]) if next+1 < len(values) and values[next+1] is not None else None if node.left: new_deepest.append(node.left) if node.right: new_deepest.append(node.right) next += 2 deepest = new_deepest return root def printtree(root): if root is None: print 'EMPTY TREE' _printtree(root, 0) def _printtree(root, level): if root is None: return print ('\t' * level) + str(root.val) _printtree(root.left, level+1) _printtree(root.right, level+1)
[ "xiaonanln@gmail.com" ]
xiaonanln@gmail.com
e7624008f621053eb84fcdeaba639ad1a2f74dcf
4c68af90463865564ad710b4d50ad79c7e6ba5ac
/maintain_api/config.py
c37ba2c885f2bb7c0509d2b6d274b457830d751a
[ "MIT" ]
permissive
LandRegistry/maintain-api
d231f34105f594ea960327076a81bcd67a639a6c
fa1ecf71332b47606293c59eeaed8ae43d5231cd
refs/heads/master
2020-04-03T21:16:28.830573
2018-10-26T14:45:00
2018-10-31T14:39:22
155,569,033
0
1
null
null
null
null
UTF-8
Python
false
false
3,375
py
import os from urllib.parse import quote_plus # RULES OF CONFIG: # 1. No region specific code. Regions are defined by setting the OS environment variables appropriately to build up the # desired behaviour. # 2. No use of defaults when getting OS environment variables. They must all be set to the required values prior to the # app starting. # 3. This is the only file in the app where os.environ should be used. # For logging FLASK_LOG_LEVEL = os.environ['LOG_LEVEL'] # For health route COMMIT = os.environ['COMMIT'] # This APP_NAME variable is to allow changing the app name when the app is running in a cluster. So that # each app in the cluster will have a unique name. APP_NAME = os.environ['APP_NAME'] # Mint API MINT_API_URL = os.environ['MINT_API_URL'] MINT_API_URL_ROOT = os.environ['MINT_API_URL_ROOT'] # Search API URL SEARCH_API_URL = os.environ['SEARCH_API_URL'] # Authentication AUTHENTICATION_API_URL = os.environ['AUTHENTICATION_API_URL'] AUTHENTICATION_API_BASE_URL = os.environ['AUTHENTICATION_API_BASE_URL'] # --- Database variables start # These must all be set in the OS environment. # The password must be the correct one for either the app user or alembic user, # depending on which will be used (which is controlled by the SQL_USE_ALEMBIC_USER variable) SQL_HOST = os.environ['SQL_HOST'] SQL_DATABASE = os.environ['SQL_DATABASE'] SQL_PASSWORD = os.environ['SQL_PASSWORD'] APP_SQL_USERNAME = os.environ['APP_SQL_USERNAME'] ALEMBIC_SQL_USERNAME = os.environ['ALEMBIC_SQL_USERNAME'] if os.environ['SQL_USE_ALEMBIC_USER'] == 'yes': FINAL_SQL_USERNAME = ALEMBIC_SQL_USERNAME else: FINAL_SQL_USERNAME = APP_SQL_USERNAME SQLALCHEMY_DATABASE_URI = 'postgres://{0}:{1}@{2}/{3}'.format( FINAL_SQL_USERNAME, quote_plus(SQL_PASSWORD), SQL_HOST, SQL_DATABASE) SQLALCHEMY_TRACK_MODIFICATIONS = False # Explicitly set this in order to remove warning on run SQLALCHEMY_POOL_RECYCLE = int(os.environ['SQLALCHEMY_POOL_RECYCLE']) # --- Database variables end STATUTORY_PROVISION_CACHE_TIMEOUT_MINUTES = os.environ['STATUTORY_PROVISION_CACHE_TIMEOUT_MINUTES'] MAX_HEALTH_CASCADE = os.environ['MAX_HEALTH_CASCADE'] DEPENDENCIES = { "postgres": SQLALCHEMY_DATABASE_URI, "mint-api": MINT_API_URL_ROOT, "search-api": SEARCH_API_URL, "authentication-api": AUTHENTICATION_API_BASE_URL } LOGCONFIG = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'simple': { '()': 'maintain_api.extensions.JsonFormatter' }, 'audit': { '()': 'maintain_api.extensions.JsonAuditFormatter' } }, 'filters': { 'contextual': { '()': 'maintain_api.extensions.ContextualFilter' } }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'simple', 'filters': ['contextual'], 'stream': 'ext://sys.stdout' }, 'audit_console': { 'class': 'logging.StreamHandler', 'formatter': 'audit', 'filters': ['contextual'], 'stream': 'ext://sys.stdout' } }, 'loggers': { 'maintain_api': { 'handlers': ['console'], 'level': FLASK_LOG_LEVEL }, 'audit': { 'handlers': ['audit_console'], 'level': 'INFO' } } }
[ "james.lademann@landregistry.gov.uk" ]
james.lademann@landregistry.gov.uk
d200d0184ab94946218cf6520cfcdc3467b09255
54f352a242a8ad6ff5516703e91da61e08d9a9e6
/Source Codes/AtCoder/arc087/A/3622945.py
a059d27d881c55058b7b747bc2cf9607e6321128
[]
no_license
Kawser-nerd/CLCDSA
5cbd8a4c3f65173e4e8e0d7ed845574c4770c3eb
aee32551795763b54acb26856ab239370cac4e75
refs/heads/master
2022-02-09T11:08:56.588303
2022-01-26T18:53:40
2022-01-26T18:53:40
211,783,197
23
9
null
null
null
null
UTF-8
Python
false
false
651
py
import sys stdin = sys.stdin sys.setrecursionlimit(10**5) def li(): return map(int, stdin.readline().split()) def li_(): return map(lambda x: int(x)-1, stdin.readline().split()) def lf(): return map(float, stdin.readline().split()) def ls(): return stdin.readline().split() def ns(): return stdin.readline().rstrip() def lc(): return list(ns()) def ni(): return int(stdin.readline()) def nf(): return float(stdin.readline()) from collections import Counter n = ni() a = list(li()) cnt = Counter(a) ans = 0 for k,v in cnt.items(): if v < k: ans += v elif v > k: ans += (v-k) print(ans)
[ "kwnafi@yahoo.com" ]
kwnafi@yahoo.com
e85cfedc1dfff139224d07cd93ee4c56cca29c0d
25279384025751b3b400aea006f164d66c167104
/Sytem_demo/绕过360创建用户.py
0905c44166dfef60318e16f76264d8548adfe5cc
[]
no_license
linruohan/my_study
6fda0b49f4c671919ec7a7fc6ba596b49ec66e59
7666f93259495b6928751d50eb1bab114e118038
refs/heads/master
2020-03-28T18:26:47.776943
2018-09-17T05:52:17
2018-09-17T05:52:17
148,882,060
0
0
null
null
null
null
UTF-8
Python
false
false
2,060
py
import win32api import win32net import win32netcon verbose_level = 0 server = None # Run on local machine. def CreateUser(): "Creates a new test user, then deletes the user" a = """#Author: Lz1y #Blog:http://www.Lz1y.cn\n\n\n\n""" print(a) testName = "Lz1y$" try: win32net.NetUserDel(server, testName) print("Warning - deleted user before creating it!") except win32net.error: pass d = {} d['name'] = testName d['password'] = 'P@ssW0rd!!!' d['priv'] = win32netcon.USER_PRIV_USER d['comment'] = None d['flags'] = win32netcon.UF_NORMAL_ACCOUNT | win32netcon.UF_SCRIPT try: win32net.NetUserAdd(server, 1, d) print("CreateUser Successed!") print("Username is "+testName) LocalGroup(testName) except: print("Sorry,CreateUser Failed!") print("Try to Change Guest!") ChangeGuest() def LocalGroup(uname=None): "Creates a local group, adds some members, deletes them, then removes the group" level = 3 if uname is None: uname="Lz1y$" if uname.find("\\")<0: uname = win32api.GetDomainName() + "\\" + uname group = 'Administrators' try: u={'domainandname': uname} win32net.NetLocalGroupAddMembers(server, group, level, [u]) mem, tot, res = win32net.NetLocalGroupGetMembers(server, group, level) print("Add to Administrators Successd!"+'\n'+"Username:Lz1y$\npassword:P@ssW0rd!!!") except: print("Sorry,Add to Administrators Failed!") def ChangeGuest(): level=3 uname="Guest" group = 'Administrators' try: win32net.NetUserChangePassword(None,uname,"P@ssW0rd!!!","P@ssW0rd!!!") u={'domainandname': uname} win32net.NetLocalGroupAddMembers(server, group, level, [u]) mem, tot, res = win32net.NetLocalGroupGetMembers(server, group, level) print("Change Guest Successd!"+'\n'+"Username:Guest\npassword:P@ssW0rd!!!") except: print("Change Guest Failed!Your priv must be System") CreateUser()
[ "mjt1220@126.com" ]
mjt1220@126.com
710ef00ecca7a2d4948cd6f3da2950555dda2974
c2849586a8f376cf96fcbdc1c7e5bce6522398ca
/ch08/ex8-5.py
2db05423dda3d46e39af01c7f937fdf5eb56bf12
[]
no_license
freebz/Learning-Python
0559d7691517b4acb0228d1cc76de3e93915fb27
7f577edb6249f4bbcac4f590908b385192dbf308
refs/heads/master
2020-09-23T01:48:24.009383
2019-12-02T12:26:40
2019-12-02T12:26:40
225,371,155
0
0
null
null
null
null
UTF-8
Python
false
false
298
py
# 리스트 메서드 호출 L = ['eat', 'more', 'SPAM!'] L.append('please') # 추가 메서드 호출: 끝에 아이템을 추가함 L # ['eat', 'more', 'SPAM!', 'please'] L.sort() # 리스트 아이템 정렬('S' < 'e') L # ['SPAM!', 'eat', 'more', 'please']
[ "freebz@hananet.net" ]
freebz@hananet.net
3f660de7246377aed56171a5b3a247539393fa1e
ce8c59b637d024424d331c1b2b9df3bd9d91c5a5
/tasks_8/homework/task_8_3.py
51e6f1accb79e6ba49cc85ca9a9e18a851fb8e18
[]
no_license
htmlprogrammist/kege-2021
7ca9155724e8041b807405d23391fb6503a7589b
4fa3cd9a0cc4213bbdf4576894953452b256b56e
refs/heads/master
2023-06-03T19:56:09.160795
2021-06-25T09:07:31
2021-06-25T09:07:31
308,915,777
1
1
null
null
null
null
UTF-8
Python
false
false
801
py
""" Вася составляет 4-буквенные коды из букв У, Л, Е, Й. Каждую букву нужно использовать ровно 1 раз, при этом код не может начинаться с буквы Й и не может содержать сочетания ЕУ. Сколько различных кодов может составить Вася? """ s = 'УЛЕЙ' counter = 0 for a in s[:3]: for b in s: for c in s: for d in s: st = a + b + c + d flag = True for x in st: if st.count(x) != 1: flag = False if flag: if st.count('ЕУ') == 0: counter += 1 print(counter)
[ "badmaeve2511@gmail.com" ]
badmaeve2511@gmail.com
368e6ea2ec3beae8484e00f5d2b77552687787da
d04d3eec289376e7682403af2f32044b3991d27b
/6 - Objects and Classes/Lab-1.py
bc2ec3fd61e84ac0da482be820de7019f23c313e
[]
no_license
m-evtimov96/softUni-python-fundamentals
190002dbc6196211340126814e8ed4fce3b8a07f
817a44a3d78130d37e58facfc7bcfdc8af5f4051
refs/heads/master
2020-12-10T12:45:27.847764
2020-06-23T13:09:43
2020-06-23T13:09:43
233,598,519
0
0
null
null
null
null
UTF-8
Python
false
false
277
py
class Comment: def __init__(self, username, content, likes = 0): self.username = username self.content = content self.likes = likes comment = Comment('user1', 'I like this book') print(comment.username) print(comment.content) print(comment.likes)
[ "m.evtimov196@gmail.com" ]
m.evtimov196@gmail.com
7042a0bd3044411ecbe1410052639e87c767e370
1f227fa290b9b0669722ba5144f99b9b7f969d32
/trash7djangoProject/settings.py
edaeea2e1d292b6038c57905937018d0679f72ef
[]
no_license
sglee487/trash7djangoProject
c8188259283cd89711cea9ff456c7224db841216
4bc9cc022199cfe83a876031901c98e202df2193
refs/heads/master
2023-08-16T22:03:25.294216
2021-10-02T03:25:53
2021-10-02T03:25:53
380,723,080
0
0
null
null
null
null
UTF-8
Python
false
false
3,395
py
""" Django settings for trash7djangoProject project. Generated by 'django-admin startproject' using Django 3.2.4. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-r5bxqn2252sqg+=myto!b47otc(jy+rf25@nspec-5pt@-d7$y' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['13.209.34.118'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'sslserver' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'trash7djangoProject.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'trash7djangoProject.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'ko-ke' TIME_ZONE = 'Asia/Seoul' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / 'static', ] # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
[ "sglee487@gmail.com" ]
sglee487@gmail.com
a2eb2f15d648514d2fb306b3dfc4f32265613857
19236d9e966cf5bafbe5479d613a175211e1dd37
/cohesity_management_sdk/models/tenant_view_update_details.py
4bfe6d01532e5630f8534fce69d0d7d939816cd2
[ "MIT" ]
permissive
hemanshu-cohesity/management-sdk-python
236c44fbd9604809027f8ddd0ae6c36e4e727615
07c5adee58810979780679065250d82b4b2cdaab
refs/heads/master
2020-04-29T23:22:08.909550
2019-04-10T02:42:16
2019-04-10T02:42:16
176,474,523
0
0
NOASSERTION
2019-03-19T09:27:14
2019-03-19T09:27:12
null
UTF-8
Python
false
false
1,613
py
# -*- coding: utf-8 -*- # Copyright 2019 Cohesity Inc. class TenantViewUpdateDetails(object): """Implementation of the 'Tenant View Update Details.' model. Specifies view update details about a tenant. Attributes: tenant_id (string): Specifies the unique id of the tenant. view_names (list of string): Specifies the PolicyIds for respective tenant. """ # Create a mapping from Model property names to API property names _names = { "tenant_id":'tenantId', "view_names":'viewNames' } def __init__(self, tenant_id=None, view_names=None): """Constructor for the TenantViewUpdateDetails class""" # Initialize members of the class self.tenant_id = tenant_id self.view_names = view_names @classmethod def from_dictionary(cls, dictionary): """Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the object as obtained from the deserialization of the server's response. The keys MUST match property names in the API description. Returns: object: An instance of this structure class. """ if dictionary is None: return None # Extract variables from the dictionary tenant_id = dictionary.get('tenantId') view_names = dictionary.get('viewNames') # Return an object of this model return cls(tenant_id, view_names)
[ "ashish@cohesity.com" ]
ashish@cohesity.com
8a4d3531c5aca0cc15b6816c3e76e0f611e2404c
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p02408/s132954082.py
adf3cae7f1f026a2ec83181f0895f2eaa43eaf7f
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
337
py
suit = {"S": 0, "H": 1, "C": 2, "D": 3} suit_keys = list(suit.keys()) deck = [[suit_keys[i] + " " + str(j + 1) for j in range(13)] for i in range(4)] for _ in range(int(input())): card = input().split() deck[suit[card[0]]][int(card[1]) - 1] = "" for i in range(4): for j in deck[i]: if j != "": print(j)
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
75735120139c7430867a75bdaa0c5d627ceee1c6
2a6f6cc148cbccb55c826bf01e0159ef58a733ec
/train_script_TFR.py
b530c0917e7daaab9900ae33b730b0b625a92c6e
[]
no_license
QuantumPlumber/CookieBoxMachineLearning
5e9a4ebf385aa40373d4d5dbc1020b40dc06500f
dfc60bb9b29d519618d59b10f9acae058f368e17
refs/heads/master
2022-11-21T20:13:52.507033
2019-09-19T02:09:00
2019-09-19T02:09:00
168,767,419
0
0
null
null
null
null
UTF-8
Python
false
false
1,020
py
import numpy as np import time #base_filename = 'reformed_TF_train_mp_1_quarter' #base_filename = 'TF_train_update_TFR' #base_filename = 'TF_train_waveform_TFR' #base_filename = 'TF_train_wave_unwrapped_TFR' base_filename = 'TF_train_wave_unwrapped_eggs_TFR' dataset_size = 60000 TFR_filesize = 10000 def file_chunker(start, stop, step, base_filename): for ii in np.arange(start, stop, step): yield '{}_{}-{}'.format(base_filename, ii, ii + step) file_chunks = file_chunker(start=0, stop=dataset_size, step=TFR_filesize, base_filename=base_filename) file_list = [] for file in file_chunks: file_list.append(file) print(file_list) repeat = 2 batch_size = 64 train_step = dataset_size*repeat checkpoint = time.perf_counter() classifier.train( input_fn=lambda: fn.input_TFR_functor(TFRecords_file_list=file_list, long=TFR_filesize, repeat=repeat, batch_size=batch_size), steps=train_step) delta_t = checkpoint - time.perf_counter() print('Trained {} epochs in {}'.format(repeat, delta_t))
[ "44450703+QuantumPlumber@users.noreply.github.com" ]
44450703+QuantumPlumber@users.noreply.github.com
286662ec2018c9f32e6fb986fc832bc0ab1dc3cf
5e8931a6bb8b883b9e2f4979ad4b469eabece11f
/appfat/blog/migrations/0011_auto_20180801_1543.py
50fa24c12e04c6bad3e71a7fc5e11be56c9df76a
[]
no_license
dennyerikson/django-AppFat
accbfe232ab3895d39ee2ba2af69baff55d2986c
476a821aba1aff7c4a3bea0dbafa03e145eb6325
refs/heads/master
2020-03-22T20:17:01.080648
2019-01-06T23:40:12
2019-01-06T23:40:12
140,586,930
0
0
null
null
null
null
UTF-8
Python
false
false
451
py
# -*- coding: utf-8 -*- # Generated by Django 1.9.13 on 2018-08-01 18:43 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blog', '0010_auto_20180727_1711'), ] operations = [ migrations.AlterField( model_name='aluno', name='alu_curso', field=models.CharField(max_length=200), ), ]
[ "dennyeriks00on@gmail.com" ]
dennyeriks00on@gmail.com
dd0d4b267638c32c16c41ea77a4ed9f1a38c0773
6db1b8b05c6a4fb68f8514f07bc5725e881691ee
/test/test_updating_a_mailing_list_request.py
80ee367c3265a652b4858a6e670f1b0dc9e0f7e6
[]
no_license
mooTheo/Python-Moosend-Wrapper
7cc776dc90a78484b605d33b6e0403fee27f99ac
eaf3b5f82960aef5dfd4201026e57e88ad663005
refs/heads/master
2021-07-07T20:55:32.994324
2017-10-03T14:17:42
2017-10-03T14:17:42
104,724,718
0
0
null
null
null
null
UTF-8
Python
false
false
933
py
# coding: utf-8 """ Moosend API TODO: Add a description OpenAPI spec version: 1.0 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys import unittest import moosend from moosend.rest import ApiException from moosend.models.updating_a_mailing_list_request import UpdatingAMailingListRequest class TestUpdatingAMailingListRequest(unittest.TestCase): """ UpdatingAMailingListRequest unit test stubs """ def setUp(self): pass def tearDown(self): pass def testUpdatingAMailingListRequest(self): """ Test UpdatingAMailingListRequest """ # FIXME: construct object with mandatory attributes with example values #model = moosend.models.updating_a_mailing_list_request.UpdatingAMailingListRequest() pass if __name__ == '__main__': unittest.main()
[ "theo@moosend.com" ]
theo@moosend.com
30f4e4a5a110d3d3199fca57cbf4ebf05170115b
6b8c52048648c82543ce899d5fb2f8b0dcabb6e5
/heaps/misha&candies.py
fb7d4cc3ccfeafc3f4ba12ef01e7c2e4167e6994
[]
no_license
arnabs542/DS-AlgoPrac
c9f7f0d383bcb3b793b09b219135f1bc9d607081
fcc2d6d014e9ffdce3ff4b64d12ce054222e434d
refs/heads/master
2022-12-13T05:56:33.098629
2020-09-15T13:48:54
2020-09-15T13:48:54
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,864
py
"""Misha and Candies Misha loves eating candies. She has given N boxes of Candies. She decides, every time she will choose a box having the minimum number of candies, eat half of the candies and put the remaining candies in the other box that has the minimum number of candies. Misha does not like a box if it has the number of candies greater than K so she won't eat from that box. Can you find how many candies she will eat? Note: If a box has an odd number of candies then Misha will eat floor(odd/2) Input Format The first argument is A an Array of Integers, where A[i] is the number of candies in the ith box. The second argument is K, the maximum number of candies Misha like in a box. Output Format Return an Integer X i.e number of candies Misha will eat. Constraints 1 <= N <= 1e5 1 <= A[i] <= 1e5 1 <= K <= 1e6 For Example Example Input: A = [3, 2, 3] k = 4 Example Output: 2 Explanation: 1st time Misha will eat from 2nd box, i.e 1 candy she'll eat and will put the remaining 1 candy in the 1st box. 2nd time she will eat from the 3rd box, i.e 1 candy she'll eat and will put the remaining 2 candies in the 1st box. She will not eat from the 3rd box as now it has candies greater than K. So the number of candies Misha eat is 2.""" class Solution: # @param A : list of integers # @param B : integer # @return an integer def solve(self, A, B): if not A: return 0 import heapq as hq hq.heapify(A) ans = 0 while True: # print(A) temp = hq.heappop(A) if temp > B: return ans eat = temp//2 ans += eat if A: next = hq.heappop(A) hq.heappush(A, next+temp-eat) else: return ans return ans
[ "vvrmahendra@gmail.com" ]
vvrmahendra@gmail.com
ab8e5e33a928ac00940e2bd2a5eafe5e661de615
c130a094e04eb448201ca2ab8ed4fe56cd1d80bc
/samples/openapi3/client/petstore/python-experimental/petstore_api/model/object_with_difficultly_named_props.py
2429a2205a21853b42e39fce88ac749973f708a0
[ "Apache-2.0" ]
permissive
janweinschenker/openapi-generator
83fb57f9a5a94e548e9353cbf289f4b4172a724e
2d927a738b1758c2213464e10985ee5124a091c6
refs/heads/master
2022-02-01T17:22:05.604745
2022-01-19T10:43:39
2022-01-19T10:43:39
221,860,152
1
0
Apache-2.0
2019-11-15T06:36:25
2019-11-15T06:36:24
null
UTF-8
Python
false
false
2,307
py
# coding: utf-8 """ OpenAPI Petstore This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech """ import re # noqa: F401 import sys # noqa: F401 import typing # noqa: F401 from frozendict import frozendict # noqa: F401 import decimal # noqa: F401 from datetime import date, datetime # noqa: F401 from frozendict import frozendict # noqa: F401 from petstore_api.schemas import ( # noqa: F401 AnyTypeSchema, ComposedSchema, DictSchema, ListSchema, StrSchema, IntSchema, Int32Schema, Int64Schema, Float32Schema, Float64Schema, NumberSchema, DateSchema, DateTimeSchema, DecimalSchema, BoolSchema, BinarySchema, NoneSchema, none_type, InstantiationMetadata, Unset, unset, ComposedBase, ListBase, DictBase, NoneBase, StrBase, IntBase, NumberBase, DateBase, DateTimeBase, BoolBase, BinaryBase, Schema, _SchemaValidator, _SchemaTypeChecker, _SchemaEnumMaker ) class ObjectWithDifficultlyNamedProps( DictSchema ): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. model with properties that have invalid names for python """ _required_property_names = set(( '123-list', )) special_property_name = Int64Schema locals()['$special[property.name]'] = special_property_name del locals()['special_property_name'] _123_list = StrSchema locals()['123-list'] = _123_list del locals()['_123_list'] _123_number = IntSchema locals()['123Number'] = _123_number del locals()['_123_number'] def __new__( cls, *args: typing.Union[dict, frozendict, ], _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, **kwargs: typing.Type[Schema], ) -> 'ObjectWithDifficultlyNamedProps': return super().__new__( cls, *args, _instantiation_metadata=_instantiation_metadata, **kwargs, )
[ "noreply@github.com" ]
janweinschenker.noreply@github.com
e56902c26f13b52578ca430af1c005065ee503e9
28b9adc46eb9bb7616c4f74fe29f9a3417f2f963
/SIM_PKL/catatan/models.py
2cb3c0434d4c040bf64928b425a3d0f9c25523bb
[]
no_license
mohamad1213/SIMPKL
ca0a6dafb97b494e5edf9276e358f800eee808e1
e6ef5d6b8a5c18c85067314a3664bf43959a0370
refs/heads/master
2023-01-04T18:27:06.306534
2020-11-03T06:53:50
2020-11-03T06:53:50
297,674,434
0
0
null
null
null
null
UTF-8
Python
false
false
443
py
from django.db import models from datetime import datetime from django.contrib.auth.models import User class Catatan(models.Model): owner = models.ForeignKey(User, on_delete = models.DO_NOTHING,related_name='catatan') tgl_kegiatan = models.DateField(default=datetime.now) judul = models.CharField(max_length=100) ket = models.TextField(max_length=200) upload_img = models.ImageField(default='', upload_to='images/')
[ "hatami391998@gmail.com" ]
hatami391998@gmail.com
24da05951cd9db1b073a0188ea67b0faf41a421c
1c321bd2ca285625fe89e62519b04d26aaf83060
/networking/dns/dnstest.py
364fc028e848290c48f3c33d41c1ad212ea69638
[]
no_license
w31ha0/hackTools
e554706a755102113a644b62b6816585c02570b5
f133a96ed1922dce0c0758110ba93aedef0e61fd
refs/heads/master
2021-01-21T12:36:02.581405
2018-04-23T06:54:05
2018-04-23T06:54:05
91,798,452
2
1
null
null
null
null
UTF-8
Python
false
false
1,028
py
#!/usr/bin/env python # This code is strictly for demonstration purposes. # If used in any other way or for any other purposes. In no way am I responsible # for your actions or any damage which may occur as a result of its usage # dnsSpoof.py # Author: Nik Alleyne - nikalleyne at gmail dot com # http://securitynik.blogspot.com from os import uname from subprocess import call from sys import argv, exit from time import ctime, sleep from scapy.all import * spoofedIPPkt = IP(src='1.2.3.4',dst='1.2.3.4') spoofedUDP_TCPPacket = UDP(sport=53,dport=123) spoofedDNSPakcet = DNS(id=1,qr=1,opcode=1,aa=1,rd=0,ra=0,z=0,rcode=0,qdcount=1,ancount=1,nscount=1,arcount=1,qd=DNSQR(qname="google.com",qtype=1,qclass=1),an=DNSRR(rrname="google.com",rdata='1.1.1.1',ttl=86400),ns=DNSRR(rrname="google.com",type=2,ttl=86400,rdata=argv[2]),ar=DNSRR(rrname="google.com",rdata='1.1.1.1')) pckToSend = Ether()/spoofedIPPkt/spoofedUDP_TCPPacket/spoofedDNSPakcet sendp(pckToSend,iface=argv[1].strip(), count=1)
[ "root@localhost.localdomain" ]
root@localhost.localdomain
bde8f107575dc263a831f0089ca35d8a3d5bb93f
d001abba19711d678f2ba09dfbd5c84357be6bb0
/src/contest/yukicoder/280/B.py
025b75bdeffc6dfe7b3305220a7944a2bbfcf387
[]
no_license
cormoran/CompetitiveProgramming
89f8b3ceda97985d32b8cd91056b49abeb243e6f
fa0e479ab299f53984fa7541d088c10c447fb6e4
refs/heads/master
2020-04-17T19:59:49.724498
2020-03-28T15:46:26
2020-03-28T15:46:26
65,995,023
0
0
null
null
null
null
UTF-8
Python
false
false
241
py
#!/usr/bin/env python3 import fractions N = int(input()) Z = list(map(int, input().split())) G = fractions.Fraction(1, 1); for i in range(N - 1): G *= fractions.Fraction(Z[i + 1], Z[i]) print(str(G.numerator) + '/' + str(G.denominator))
[ "cormoran707@gmail.com" ]
cormoran707@gmail.com
c5061c88d417dc3ff636d5051915df0c3f4e6865
80d50ea48e10674b1b7d3f583a1c4b7d0b01200f
/src/datadog_api_client/v1/model/table_widget_definition_type.py
41754b3fe02824bdb701f7c9092457b96605e51b
[ "Apache-2.0", "BSD-3-Clause", "MIT", "MPL-2.0" ]
permissive
DataDog/datadog-api-client-python
3e01fa630278ad0b5c7005f08b7f61d07aa87345
392de360e7de659ee25e4a6753706820ca7c6a92
refs/heads/master
2023-09-01T20:32:37.718187
2023-09-01T14:42:04
2023-09-01T14:42:04
193,793,657
82
36
Apache-2.0
2023-09-14T18:22:39
2019-06-25T22:52:04
Python
UTF-8
Python
false
false
882
py
# Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License. # This product includes software developed at Datadog (https://www.datadoghq.com/). # Copyright 2019-Present Datadog, Inc. from __future__ import annotations from datadog_api_client.model_utils import ( ModelSimple, cached_property, ) from typing import ClassVar class TableWidgetDefinitionType(ModelSimple): """ Type of the table widget. :param value: If omitted defaults to "query_table". Must be one of ["query_table"]. :type value: str """ allowed_values = { "query_table", } QUERY_TABLE: ClassVar["TableWidgetDefinitionType"] @cached_property def openapi_types(_): return { "value": (str,), } TableWidgetDefinitionType.QUERY_TABLE = TableWidgetDefinitionType("query_table")
[ "noreply@github.com" ]
DataDog.noreply@github.com
b41ef3fee8820ab56138281c31348d0908d77313
92699c30f0ef36e6c76024c0966ad453bcd4e893
/visualize.py
73277a64915b433240deaf1f2365582459b10188
[ "MIT" ]
permissive
AungMyatSan/unsup-3d-keypoints
c333b71216087d01e219288969a2dcaae9257ead
93af69ba92bb00d1d2785967055df30ac745f95c
refs/heads/main
2023-08-25T20:09:11.010042
2021-11-03T15:57:52
2021-11-03T15:57:52
null
0
0
null
null
null
null
UTF-8
Python
false
false
174
py
from experiments import algo_registry, get_args if __name__ == '__main__': args = get_args() experiment = algo_registry[args.algo](args) experiment.visualize()
[ "boyuanchen@berkeley.edu" ]
boyuanchen@berkeley.edu
2d2113c43a965b1556bcdf535ced30eea8d3734f
46b5c1bc98678f02cbd39b6c814e6b32908a6c22
/venv/bin/csvlook
c02dbd9fedc446b3516fcaab1177f4e2063e9e8e
[]
no_license
Peter-32/portofvirginiaapp
ea0aceedce6efe928f4c128fb4935f000048678f
e0cfdd379d9654d41b301a52bcd6d77aa08d4591
refs/heads/master
2022-11-07T15:13:51.111003
2019-07-24T05:15:57
2019-07-24T05:15:57
198,562,849
0
1
null
2022-10-08T03:46:30
2019-07-24T05:13:23
Python
UTF-8
Python
false
false
304
#!/Users/petermyers/Desktop/Code/test_pyinstaller2/venv/bin/python # -*- coding: utf-8 -*- import re import sys from csvkit.utilities.csvlook import launch_new_instance if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit(launch_new_instance())
[ "peter@impactradius.com" ]
peter@impactradius.com
1bd639ff67bbc8cd8cc937c885b0d31a4cacaf7d
c5cdb85c122c32165a0a00428ab85c03bc5d8fa6
/Week3/day2/tv_shows/application/migrations/0001_initial.py
723c8528775c0927ca23fb7c84e04b09bf37b34a
[]
no_license
sadieBoBadie/Dec2020Python
70f841aff0b816a0cbf5519418d0c6ce14b90729
595aeea4092c8962c8a7e08fa757a0b8ddc8c897
refs/heads/main
2023-02-01T15:28:25.885585
2020-12-19T02:46:48
2020-12-19T02:46:48
317,356,502
0
9
null
null
null
null
UTF-8
Python
false
false
795
py
# Generated by Django 2.2 on 2020-12-15 22:19 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Show', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=255)), ('description', models.TextField()), ('network', models.CharField(max_length=255)), ('release_date', models.DateField()), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ], ), ]
[ "sflick@codingdojo.com" ]
sflick@codingdojo.com
a0ff0eb4f6ab02c8d96e79c6f9123bfb69ca2e08
fa0e61d9cf6ace4c3198724afa9ddbc15ac8cd1f
/qurry/constructs/define.py
24b6ee3b84556563203e76a8f48fcec008ed292f
[ "MIT" ]
permissive
nguyenducnhaty/Qurry
aa338877b8f72394a0165bdc2ab8838ff6386e34
9766cc8ea19d438d3408080bf584faab12537789
refs/heads/master
2020-05-28T08:05:39.762862
2019-04-03T18:45:41
2019-04-03T18:45:41
null
0
0
null
null
null
null
UTF-8
Python
false
false
712
py
from ..definitions import update_definitions from ..datatype import Datatype from pprint import pprint def process_type(body, kernel): if len(body) == 1: body = body[0] head, *rest = body if head in kernel.definitions and isinstance(kernel.definitions[head], Datatype): return kernel.definitions[head].__init__(*rest) else: raise ValueError('Cannot process type {}'.format(head)) def define(*expression, kernel=None): name, *rest = expression if name not in kernel.definitions: kernel.definitions[name] = process_type(rest, kernel) print(kernel.definitions) else: raise ValueError('{} is already defined'.format(name)) return ''
[ "lucassaldyt@gmail.com" ]
lucassaldyt@gmail.com
71e45223c641fee198b9a3403e9340051a5e26a4
d15eb98c00537b6303b3b9f396eac6df5af10f20
/transformer_RC/eval.py
26b907dcdd6ec297c83a09f7a4a46671b8ae6b75
[]
no_license
fooSynaptic/transfromer_NN_Block
ab17d2ac5ecc04d3fd54407d72b8dc44c5671168
62c7769e6dc66de8185f29ecb5a7de4f3ceb3374
refs/heads/master
2023-04-04T01:28:13.066026
2019-11-22T02:11:25
2019-11-22T02:11:25
150,613,743
9
0
null
2023-03-24T22:46:39
2018-09-27T16:05:59
Python
UTF-8
Python
false
false
5,632
py
# -*- coding: utf-8 -*- #/usr/bin/python3 import codecs import os import tensorflow as tf import numpy as np from hyperparams import rc_Hyperparams as hp from data_load import load_vocabs, load_train_data, load_test_data, create_data from train import Graph #from nltk.translate.bleu_score import corpus_bleu import argparse #from sklearn.metrics import classification_report #from utils import compute_bleu_rouge import pandas as pd from modules import bleu def find_best_answer_for_passage(start_probs, end_probs, passage_len=None): """ Finds the best answer with the maximum start_prob * end_prob from a single passage """ if passage_len is None: passage_len = len(start_probs) else: passage_len = min(len(start_probs), passage_len) best_start, best_end, max_prob = -1, -1, 0 for start_idx in range(passage_len): #within the span of answer limit for ans_len in range(hp.ans_maxlen): end_idx = start_idx + ans_len if end_idx >= passage_len: continue prob = start_probs[start_idx] * end_probs[end_idx] if prob > max_prob: best_start = start_idx best_end = end_idx max_prob = prob return (best_start, best_end), max_prob def eval(task_name): # Load graph g = Graph(is_training=False) print("Graph loaded") # Load data test_data = pd.read_csv(hp.testfile) questions, contents, q_lens, p_lens, start_pos, end_pos = load_test_data() raw_passages = list(test_data['content']) reference_answers = list(test_data['answer']) word2idx, idx2word = load_vocabs() # Start session with g.graph.as_default(): sv = tf.train.Supervisor() with sv.managed_session(config=tf.ConfigProto(allow_soft_placement=True)) as sess: ## Restore parameters sv.saver.restore(sess, tf.train.latest_checkpoint(hp.logdir)) print("Restored!") ## Get model name print('Model dir:', hp.logdir) mname = open(hp.logdir + '/checkpoint', 'r').read().split('"')[1] # model name print("Model name:", mname) ## Inference if not os.path.exists('results'): os.mkdir('results') with codecs.open("results/" + mname, "w", "utf-8") as fout: pred_answers, ref_answers = [], [] pred_dict, ref_dict = {}, {} ques_id = 0 eval_dict = {'bleu_1':[], 'bleu_2':[], 'bleu_3':[], 'bleu_4':[]} for i in range(len(questions) // hp.batch_size): print("Iterator: {} / {}".format(i, len(questions)//hp.batch_size)) ### Get mini-batches q = questions[i*hp.batch_size: (i+1)*hp.batch_size] p = contents[i*hp.batch_size: (i+1)*hp.batch_size] q_length = q_lens[i*hp.batch_size: (i+1)*hp.batch_size] p_length = p_lens[i*hp.batch_size: (i+1)*hp.batch_size] s_pos = start_pos[i*hp.batch_size: (i+1)*hp.batch_size] e_pos = end_pos[i*hp.batch_size: (i+1)*hp.batch_size] passages = raw_passages[i*hp.batch_size: (i+1)*hp.batch_size] ref_answers = reference_answers[i*hp.batch_size: (i+1)*hp.batch_size] feed_dict = {g.q: q, g.p: p, g.q_length: q_length, g.p_length: p_length, g.start_label: s_pos, g.end_label: e_pos} start_probs, end_probs = sess.run([g.start_probs, g.end_probs], feed_dict) ### Write to file for start_prob, end_prob, passage, ref in zip(start_probs, end_probs, passages, ref_answers): pred_span, prob = find_best_answer_for_passage(start_prob, end_prob) pred_answer = passage[pred_span[0]: pred_span[1]+1] if not len(pred_answer) > 0: continue pred_dict[str(ques_id)] = [pred_answer] ref_dict[str(ques_id)] = [ref] ques_id += 1 fout.write('-ref: '+ ref) fout.write("-pred: "+ pred_answer) b1, b2, b3, b4 = bleu(list(pred_answer), list(ref), 1), \ bleu(list(pred_answer), list(ref), 2), \ bleu(list(pred_answer), list(ref), 3), \ bleu(list(pred_answer), list(ref), 4) eval_dict['bleu_1'].append(b1) eval_dict['bleu_2'].append(b2) eval_dict['bleu_3'].append(b3) eval_dict['bleu_2'].append(b2) for metric in eval_dict: fout.write(metric + '\t' + str(np.mean(eval_dict[metric])) + '\n') print(metric + '\t' + str(np.mean(eval_dict[metric]))) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Choice the task you want to eval.') parser.add_argument('--task', help='task name(default: RC)') args = parser.parse_args() task_name = args.task eval(task_name) print("Done")
[ "hujiaxin@ajmide.com" ]
hujiaxin@ajmide.com
33bf6b98e2e6b8bbde66d8196ef5407b2978efbb
2073b98ec0f42c0cca08480cad534aa11fee6101
/solution/src/SecondGo.py
2402d26443d1b3a2382ed8295292545cf564cb1e
[]
no_license
chrisjdavie/ReverseShuffleMerge
47c81fcdab26177676b0a82402bb61a2440c8027
184f09f7f83a11d4904874d91853dc4467f4f219
refs/heads/master
2021-01-10T13:43:48.666040
2016-01-02T15:13:22
2016-01-02T15:13:22
48,913,511
0
0
null
null
null
null
UTF-8
Python
false
false
4,286
py
''' First go ran over the time limit, which isn't surprising as I brute forced with permutations. Looking at this, there is a more elegant solution, but it's not clear immediately how. But it's there. Okay, this approach worked, but it's not the clearest what's going on. Esentially, there are the merged counts and the reverse counts, and I first deplete the merged counts and then the reverse counts, always looking for the next best (and removing that from the reverse counts when found.) A better solution (in terms of code simplicity, probably takes much longer in alg terms), that I can't be bothered to implement right now, is finding the best characters, and then filling those up, adding in any that go over the limit. There's also a trick, keeping track of the previous minimum value, and if you hit a crappy one, substitute that in, then reversing to that point (repopulating the arrays appropriately) and starting again. I'm not 100% I've got the reversing right in my alg, I think there might be some cases it doesn't work, but I'm not sure, I might be okay. Created on 1 Jan 2016 @author: chris ''' import copy from collections import Counter def smallercharBest(testString, highChar, charCountsRemain): # finds the smallest character in a test string (with some # constraints) minChar = 'zz' for testChar in testString: if testChar < minChar and charCountsRemain[testChar] > 0 \ and testChar < highChar: minChar = testChar if minChar == 'zz': return minChar, -1 else: return minChar, testString.index(minChar) def updateBestChar(charBest, reversedCharsCounter, bestUnique): # Checks if all of the best character have been found, # and then sets the next best as the character to look for if reversedCharsCounter[charBest] == 0: if len(bestUnique) == 0: charBest = 'zz' else: charBest = bestUnique.pop(0) return charBest mixedString = raw_input().strip() # find characters in original string elements = Counter(mixedString) reversedCharsCounter = Counter() for char in elements: reversedCharsCounter[char] = elements[char]/2 uniqueChars = set(reversedCharsCounter.elements()) # try with the most lexicographically ordered test bestUnique = sorted(list(uniqueChars)) op = [] mergedCharsCounter = copy.deepcopy(reversedCharsCounter) remainString = list(mixedString[::-1]) charBest = bestUnique.pop(0) indsPop = [] prevCharInd = 0 for i, charRemain in enumerate(remainString): if charRemain == charBest: # found the best character, add to output op.append(charRemain) reversedCharsCounter[charRemain] -= 1 prevCharInd = i elif mergedCharsCounter[charRemain] > 0: # skips this character, assigns it to the merged characters mergedCharsCounter[charRemain] -= 1 elif reversedCharsCounter[charRemain] > 0: # if there are characters of charRemain to be found in the # reversed character, seek lexiographically smaller characters # between this and the previous character. # # then append this character to the output. resetInd = i if ord(charRemain) - ord(charBest) > 1: smallerInd = 0 while smallerInd > -1: smallChar, smallerInd = smallercharBest(remainString[prevCharInd+1:i], charRemain, reversedCharsCounter) if smallerInd > -1: op.append(smallChar) reversedCharsCounter[smallChar] -= 1 prevCharInd += 1 + smallerInd mergedCharsCounter[smallChar] += 1 try: resetInd = prevCharInd + 1 + remainString[prevCharInd+1:i].index(charRemain) except(ValueError): pass op.append(charRemain) reversedCharsCounter[charRemain] -= 1 prevCharInd = resetInd charBest = updateBestChar(charBest, reversedCharsCounter, bestUnique) if charBest == 'zz': break print "".join(op)
[ "chris.d@theasi.co" ]
chris.d@theasi.co
16db50922eb05c4853e1a5a7bf928ed0a8659684
3a4fbde06794da1ec4c778055dcc5586eec4b7d2
/@lib/12-13-2011-01/vyperlogix/sitemap/reader.py
db72d9f10eac4984c687669739d3f543c9c1f55b
[]
no_license
raychorn/svn_python-django-projects
27b3f367303d6254af55c645ea003276a5807798
df0d90c72d482b8a1e1b87e484d7ad991248ecc8
refs/heads/main
2022-12-30T20:36:25.884400
2020-10-15T21:52:32
2020-10-15T21:52:32
304,455,211
0
0
null
null
null
null
UTF-8
Python
false
false
2,192
py
import re import string import sys import httplib import urllib2 from xml.dom import minidom from vyperlogix.misc import _utils __copyright__ = """\ (c). Copyright 2008-2014, Vyper Logix Corp., All Rights Reserved. Published under Creative Commons License (http://creativecommons.org/licenses/by-nc/3.0/) restricted to non-commercial educational use only., http://www.VyperLogix.com for details THE AUTHOR VYPER LOGIX CORP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE ! USE AT YOUR OWN RISK. """ class ModelSitemap: def __init__(self): self.data = [] def links (self, address): file_request = urllib2.Request(address) file_opener = urllib2.build_opener() file_feed = file_opener.open(file_request).read() items = [] file_feed = _utils.ascii_only(file_feed) try: file_xml = minidom.parseString(file_feed) item_nodes = file_xml.getElementsByTagName("url") for item in item_nodes: nodes = [] for node in [n for n in item.childNodes if (n.nodeName == 'loc')]: try: nodes.append(node.firstChild.data) except: pass for n in nodes: items.append(n) except Exception, e: info_string = _utils.formattedException(details=e) items.append(info_string) items.append(str(file_feed)) return items def read_sitemap_links(url): sitemap = ModelSitemap() links = sitemap.links(url) return links if __name__ == "__main__": import sys print >>sys.stdout, __copyright__ print >>sys.stderr, __copyright__
[ "raychorn@gmail.com" ]
raychorn@gmail.com
21406bbc518e376d68ec6a67b0ff2d8424741171
686d2e525b7cd7a792501309f251dbf6dcea7ef4
/leetcode/dynamic programming/26.62 不同的路径.py
f04f16a4ae7089ade35d23be260e8a2168acc76d
[]
no_license
freemanwang/Algorithm
fa23c9c33c43f942e72d9d1828a95417e7c99575
bb691c1afb460a382d7aaaa308e8b4e17f5bf4c5
refs/heads/master
2020-06-29T19:37:32.584724
2020-02-07T06:36:29
2020-02-07T06:36:29
200,605,658
0
0
null
null
null
null
UTF-8
Python
false
false
772
py
''' 一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。 问总共有多少条不同的路径? 说明:m 和 n 的值均不超过 100。 示例 1: 输入: m = 3, n = 2 输出: 3 解释: 从左上角开始,总共有 3 条路径可以到达右下角。 1. 向右 -> 向右 -> 向下 2. 向右 -> 向下 -> 向右 3. 向下 -> 向右 -> 向右 示例 2: 输入: m = 7, n = 3 输出: 28 ''' # 应用动态规划解决问题 #状态转移:走到(m,n) 只能由 (m-1,n) 向右走一格 或者 (m,n-1) 向下走一格 # 最优子结构:F(m, n) = F(m-1, n) + F(m, n-1) # 边界:
[ "121689123@qq.com" ]
121689123@qq.com
b2b21d3ee8516a7cfb2bf97d2d121a455ef2fad3
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03479/s210485900.py
104cb0c9d70362d67521ce65fec1cbf0a4e8d9bf
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
301
py
import sys readline = sys.stdin.readline MOD = 10 ** 9 + 7 INF = float('INF') sys.setrecursionlimit(10 ** 5) def main(): x, y = list(map(int, readline().split())) ans = 0 c = x while c <= y: ans += 1 c <<= 1 print(ans) if __name__ == '__main__': main()
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
d8d63477b2da98c431cad1a9d38bd02193e100f4
9bb958a3b5ae3a083a265b37bc1f83fc2c41bdfd
/tests/test_api.py
cfdaa9bc9819e93aa32461dc45c32babf4eee411
[]
no_license
chfw/Minion
434ccd6042f8730151b6fdf711b6f9e0cd7f077d
88093463de0ad4b30f63f7bc933c8dbcd13888da
refs/heads/master
2020-12-03T04:07:55.727275
2017-06-29T20:57:26
2017-06-29T20:57:26
95,818,616
0
0
null
null
null
null
UTF-8
Python
false
false
1,366
py
import sys import json from nose.tools import eq_ from minion.app import create_app PY2 = sys.version_info[0] == 2 class TestViews: def setUp(self): self.app = create_app() self.client = self.app.test_client() def test_api_run_view(self): data = { 'command': 'ls -l' } response = self._request_api_run_view(data) if PY2: response_json = json.loads(response.data) else: response_json = json.loads( response.data.decode('utf-8')) eq_(response.status_code, 200) assert('setup.py' in response_json['result']) def test_api_run_view_with_wrong_payload(self): data = { 'commando': 'ls -l' } response = self._request_api_run_view(data) if PY2: response_json = json.loads(response.data) else: response_json = json.loads( response.data.decode('utf-8')) eq_(response.status_code, 400) assert('In correct instructions, Master' in response_json['message']) def _request_api_run_view(self, data): headers = { 'Content-Type': 'application/json' } response = self.client.post( '/api/run/', data=json.dumps(data), headers=headers) return response
[ "wangc_2011@hotmail.com" ]
wangc_2011@hotmail.com
0c5be048707b2514b3ed824531d847aee604bf4b
09e57dd1374713f06b70d7b37a580130d9bbab0d
/benchmark/startCirq1993.py
6838def910331cff05b9e13bcc3360a738377755
[ "BSD-3-Clause" ]
permissive
UCLA-SEAL/QDiff
ad53650034897abb5941e74539e3aee8edb600ab
d968cbc47fe926b7f88b4adf10490f1edd6f8819
refs/heads/main
2023-08-05T04:52:24.961998
2021-09-19T02:56:16
2021-09-19T02:56:16
405,159,939
2
0
null
null
null
null
UTF-8
Python
false
false
2,775
py
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 5/15/20 4:49 PM # @File : grover.py # qubit number=4 # total number=32 import cirq import cirq.google as cg from typing import Optional import sys from math import log2 import numpy as np #thatsNoCode from cirq.contrib.svg import SVGCircuit # Symbols for the rotation angles in the QAOA circuit. def make_circuit(n: int, input_qubit): c = cirq.Circuit() # circuit begin c.append(cirq.H.on(input_qubit[0])) # number=9 c.append(cirq.H.on(input_qubit[1])) # number=2 c.append(cirq.H.on(input_qubit[2])) # number=3 c.append(cirq.H.on(input_qubit[3])) # number=4 c.append(cirq.Y.on(input_qubit[3])) # number=12 c.append(cirq.H.on(input_qubit[3])) # number=29 c.append(cirq.CZ.on(input_qubit[2],input_qubit[3])) # number=30 c.append(cirq.H.on(input_qubit[3])) # number=31 c.append(cirq.H.on(input_qubit[0])) # number=5 c.append(cirq.H.on(input_qubit[1])) # number=6 c.append(cirq.H.on(input_qubit[2])) # number=24 c.append(cirq.CZ.on(input_qubit[3],input_qubit[2])) # number=25 c.append(cirq.H.on(input_qubit[2])) # number=26 c.append(cirq.H.on(input_qubit[2])) # number=7 c.append(cirq.H.on(input_qubit[3])) # number=8 c.append(cirq.X.on(input_qubit[2])) # number=23 c.append(cirq.H.on(input_qubit[3])) # number=16 c.append(cirq.CZ.on(input_qubit[0],input_qubit[3])) # number=17 c.append(cirq.H.on(input_qubit[3])) # number=18 c.append(cirq.X.on(input_qubit[3])) # number=14 c.append(cirq.CNOT.on(input_qubit[0],input_qubit[3])) # number=15 c.append(cirq.Y.on(input_qubit[2])) # number=10 c.append(cirq.Y.on(input_qubit[2])) # number=11 c.append(cirq.X.on(input_qubit[1])) # number=20 c.append(cirq.X.on(input_qubit[1])) # number=21 c.append(cirq.X.on(input_qubit[3])) # number=27 c.append(cirq.X.on(input_qubit[3])) # number=28 # circuit end c.append(cirq.measure(*input_qubit, key='result')) return c def bitstring(bits): return ''.join(str(int(b)) for b in bits) if __name__ == '__main__': qubit_count = 4 input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)] circuit = make_circuit(qubit_count,input_qubits) circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap') circuit_sample_count =2000 simulator = cirq.Simulator() result = simulator.run(circuit, repetitions=circuit_sample_count) frequencies = result.histogram(key='result', fold_func=bitstring) writefile = open("../data/startCirq1993.csv","w+") print(format(frequencies),file=writefile) print("results end", file=writefile) print(circuit.__len__(), file=writefile) print(circuit,file=writefile) writefile.close()
[ "wangjiyuan123@yeah.net" ]
wangjiyuan123@yeah.net
5ab5578bf208327a1eff085990fe8f1e60f3c230
05abb78c60a69422ae3e00a542bbd4573faf8174
/exercicios-pythonBrasil/estrutura-de-decisao/ex4.py
af8c4d8e04260c01583f8f17167d8136b44e919b
[]
no_license
xuting1108/Programas-de-estudo
72b812d52f5b130a95103c38dbe9e471dc5aa6f9
01fe21097055d69c2115cff3da2199429e87dead
refs/heads/master
2022-10-20T17:06:14.517643
2019-04-08T11:16:12
2019-04-08T11:16:12
179,678,721
0
1
null
2022-10-09T13:13:57
2019-04-05T12:38:23
Python
UTF-8
Python
false
false
228
py
#Faça um Programa que verifique se uma letra digitada é vogal ou consoante. letra = input('digite uma letra: ') vogal = ['a','e','i','o','u'] if letra in vogal: print('a letra é vogal') else: print('a letra é consoante')
[ "xuting1108@hotmail.com" ]
xuting1108@hotmail.com
6f0e82c805b291ff0a194472a3145feebdb5cd8f
d0c0c46bade87640425b5587cc984f24f74cad24
/entrofy/utils.py
86f6959c8707d44b06c324229b95896f41e2c0f6
[]
no_license
dhuppenkothen/entrofy
4b3b28d66321ee29e2bfa9516cc2bf681b81ee7b
d0789a9f84147f623746efabb28721dd2dc4c141
refs/heads/master
2023-05-26T03:59:03.695720
2023-05-03T17:04:12
2023-05-03T17:04:12
43,324,813
83
26
null
2023-05-03T16:52:11
2015-09-28T20:21:10
Jupyter Notebook
UTF-8
Python
false
false
861
py
#!/usr/bin/env python # -*- encoding: utf-8 -*- '''Utilities for entrofy''' import numbers import numpy as np # The following is borrowed from scikit-learn v0.17 def check_random_state(seed): """Turn seed into a np.random.RandomState instance If seed is None, return the RandomState singleton used by np.random. If seed is an int, return a new RandomState instance seeded with seed. If seed is already a RandomState instance, return it. Otherwise raise ValueError. """ if seed is None or seed is np.random: return np.random.mtrand._rand if isinstance(seed, (numbers.Integral, np.integer)): return np.random.RandomState(seed) if isinstance(seed, np.random.RandomState): return seed raise ValueError('%r cannot be used to seed a numpy.random.RandomState' ' instance' % seed)
[ "brian.mcfee@nyu.edu" ]
brian.mcfee@nyu.edu
3208c332acc55b368ab94bdf44b3b9837d19ccc6
7298d1692c6948f0880e550d6100c63a64ce3ea1
/catalog-configs/Vocab/oly_residue_feature_residue_range_granularity_term.py
2a6871af85b0c4d5dfc6549841f414bf74e6de31
[]
no_license
informatics-isi-edu/protein-database
b7684b3d08dbf22c1e7c4a4b8460248c6f0d2c6d
ce4be1bf13e6b1c22f3fccbb513824782609991f
refs/heads/master
2023-08-16T10:24:10.206574
2023-07-25T23:10:42
2023-07-25T23:10:42
174,095,941
2
0
null
2023-06-16T19:44:43
2019-03-06T07:39:14
Python
UTF-8
Python
false
false
6,309
py
import argparse from attrdict import AttrDict from deriva.core import ErmrestCatalog, get_credential, DerivaPathError from deriva.utils.catalog.components.deriva_model import DerivaCatalog import deriva.core.ermrest_model as em from deriva.core.ermrest_config import tag as chaise_tags from deriva.utils.catalog.manage.update_catalog import CatalogUpdater, parse_args groups = { 'pdb-admin': 'https://auth.globus.org/0b98092c-3c41-11e9-a8c8-0ee7d80087ee', 'pdb-reader': 'https://auth.globus.org/8875a770-3c40-11e9-a8c8-0ee7d80087ee', 'pdb-writer': 'https://auth.globus.org/c94a1e5c-3c40-11e9-a5d1-0aacc65bfe9a', 'pdb-curator': 'https://auth.globus.org/eef3e02a-3c40-11e9-9276-0edc9bdd56a6', 'isrd-staff': 'https://auth.globus.org/176baec4-ed26-11e5-8e88-22000ab4b42b' } table_name = 'oly_residue_feature_residue_range_granularity_term' schema_name = 'Vocab' column_annotations = { 'RCT': { chaise_tags.display: { 'name': 'Creation Time' }, chaise_tags.generated: None, chaise_tags.immutable: None }, 'RMT': { chaise_tags.display: { 'name': 'Last Modified Time' }, chaise_tags.generated: None, chaise_tags.immutable: None }, 'RCB': { chaise_tags.display: { 'name': 'Created By' }, chaise_tags.generated: None, chaise_tags.immutable: None }, 'RMB': { chaise_tags.display: { 'name': 'Modified By' }, chaise_tags.generated: None, chaise_tags.immutable: None }, 'ID': {}, 'URI': {}, 'Name': {}, 'Description': {}, 'Synonyms': {}, 'Owner': {} } column_comment = { 'ID': 'The preferred Compact URI (CURIE) for this term.', 'URI': 'The preferred URI for this term.', 'Name': 'The preferred human-readable name for this term.', 'Description': 'A longer human-readable description of this term.', 'Synonyms': 'Alternate human-readable names for this term.', 'Owner': 'Group that can update the record.' } column_acls = {} column_acl_bindings = {} column_defs = [ em.Column.define( 'ID', em.builtin_types['ermrest_curie'], nullok=False, default='PDB:{RID}', comment=column_comment['ID'], ), em.Column.define( 'URI', em.builtin_types['ermrest_uri'], nullok=False, default='/id/{RID}', comment=column_comment['URI'], ), em.Column.define( 'Name', em.builtin_types['text'], nullok=False, comment=column_comment['Name'], ), em.Column.define( 'Description', em.builtin_types['markdown'], nullok=False, comment=column_comment['Description'], ), em.Column.define('Synonyms', em.builtin_types['text[]'], comment=column_comment['Synonyms'], ), em.Column.define('Owner', em.builtin_types['text'], comment=column_comment['Owner'], ), ] visible_columns = { '*': [ 'RID', 'Name', 'Description', 'ID', 'URI', ['Vocab', 'oly_residue_feature_residue_range_granularity_term_RCB_fkey'], ['Vocab', 'oly_residue_feature_residue_range_granularity_term_RMB_fkey'], 'RCT', 'RMT', ['Vocab', 'oly_residue_feature_residue_range_granularity_term_Owner_fkey'] ] } table_display = {'row_name': {'row_markdown_pattern': '{{{Name}}}'}} table_annotations = { chaise_tags.table_display: table_display, chaise_tags.visible_columns: visible_columns, } table_comment = 'A set of controlled vocabular terms.' table_acls = {} table_acl_bindings = { 'self_service_group': { 'types': ['update', 'delete'], 'scope_acl': ['*'], 'projection': ['Owner'], 'projection_type': 'acl' }, 'self_service_creator': { 'types': ['update', 'delete'], 'scope_acl': ['*'], 'projection': ['RCB'], 'projection_type': 'acl' } } key_defs = [ em.Key.define( ['RID'], constraint_names=[('Vocab', 'oly_residue_feature_residue_range_granularity_term_RIDkey1')], ), em.Key.define( ['ID'], constraint_names=[('Vocab', 'oly_residue_feature_residue_range_granularity_term_IDkey1')], ), em.Key.define( ['URI'], constraint_names=[('Vocab', 'oly_residue_feature_residue_range_granularity_term_URIkey1')], ), ] fkey_defs = [ em.ForeignKey.define( ['Owner'], 'public', 'Catalog_Group', ['ID'], constraint_names=[ ('Vocab', 'oly_residue_feature_residue_range_granularity_term_Owner_fkey') ], acls={ 'insert': [groups['pdb-curator']], 'update': [groups['pdb-curator']] }, acl_bindings={ 'set_owner': { 'types': ['update', 'insert'], 'scope_acl': ['*'], 'projection': ['ID'], 'projection_type': 'acl' } }, ), em.ForeignKey.define( ['RCB'], 'public', 'ERMrest_Client', ['ID'], constraint_names=[('Vocab', 'oly_residue_feature_residue_range_granularity_term_RCB_fkey')], acls={ 'insert': ['*'], 'update': ['*'] }, ), em.ForeignKey.define( ['RMB'], 'public', 'ERMrest_Client', ['ID'], constraint_names=[('Vocab', 'oly_residue_feature_residue_range_granularity_term_RMB_fkey')], acls={ 'insert': ['*'], 'update': ['*'] }, ), ] table_def = em.Table.define( table_name, column_defs=column_defs, key_defs=key_defs, fkey_defs=fkey_defs, annotations=table_annotations, acls=table_acls, acl_bindings=table_acl_bindings, comment=table_comment, provide_system=True ) def main(catalog, mode, replace=False, really=False): updater = CatalogUpdater(catalog) updater.update_table(mode, schema_name, table_def, replace=replace, really=really) if __name__ == "__main__": host = 'pdb.isrd.isi.edu' catalog_id = 5 mode, replace, host, catalog_id = parse_args(host, catalog_id, is_table=True) catalog = DerivaCatalog(host, catalog_id=catalog_id, validate=False) main(catalog, mode, replace)
[ "carl@isi.edu" ]
carl@isi.edu
2459f55cbfc596a0348544e1082025d1c74df70f
5d22d9b2cb5cad7970c1055aeef55d2e2a5acb8e
/leetcode/medium/Single_Number_II.py
add9ece16433795ee1263f81466aec110f3a062b
[ "MIT" ]
permissive
shhuan/algorithms
36d70f1ab23dab881bf1a15573fbca7b2a3f4235
2830c7e2ada8dfd3dcdda7c06846116d4f944a27
refs/heads/master
2021-05-07T14:21:15.362588
2017-11-07T08:20:16
2017-11-07T08:20:16
109,799,698
0
1
null
null
null
null
UTF-8
Python
false
false
2,869
py
# -*- coding: utf-8 -*- """ created by huash06 at 2015-04-14 09:08 Given an array of integers, every element appears three times except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 本题目抄袭网上解答 http://blog.csdn.net/u011960402/article/details/17750993 """ __author__ = 'huash06' import sys import os class Solution: # @param A, a list of integer # @return an integer def singleNumber(self, A): if not A: return -1 # 题目中,如果数组中的元素都是三个三个出现的,那么从二进制表示的角度,每个位上的1加起来,应该可以整除3。 # 如果某个特定位上的1加起来,可以被3整除,说明对应x的那位是0,因为如果是1,不可能被3整除 # 如果某个特定位上的1加起来,不可以被3整除,说明对应x的那位是1 # 我们可以开辟一个大小为32的数组,第0个元素表示,A中所有元素的二进制表示的最低位的和,依次类推。 # 最后,再转换为十进制数即可。这里要说明的是,用一个大小为32的整数数组表示,同样空间是O(1)的 count = [0]*32 for v in A: for i in range(32): if ((v >> i) & 1) > 0: count[i] += 1 print(count) result = 0 for i in range(31, -1, -1): result <<= 1 if count[i] % 3 != 0: result += 1 # python3 没有int, 是自动类型 if result & (1 << 31): result -= (1 << 32) return result def singleNumber2(self, A): """ 看了上面的分析之后,我们突然会想是否有一些更简洁的方法来实现这个问题。 同样从位运算的角度来看,我希望一个数用来表示出现一次的位,也就是说这个数的为1的位就表示这个位上面的数出现过了一次, 比如0x10001,就表示bit[0]和bit[4]就是出现过了一次的位。然后再用一个数表示出现过了两次的位,再用一个数表示出现过了3次的位。 只要这个位出现过了3次,我就把这个位拿清除掉,这样剩余的最后出现过一次的位的这个数就是我们要找的数了。 :param A: :return: """ ones = 0 twos = 0 threes = 0 for v in A: twos |= ones & v ones ^= v threes = ones & twos ones &= ~threes twos &= ~threes return ones s = Solution() # print(s.singleNumber([1, 2, 3, 1, 1, 3, 3])) # print(s.singleNumber([6, 3, 3, 3])) print(s.singleNumber([-2,-2,1,1,-3,1,-3,-3,-4,-2])) print(s.singleNumber2([-2,-2,1,1,-3,1,-3,-3,-4,-2]))
[ "shuangquanhuang@gmail.com" ]
shuangquanhuang@gmail.com
5639785d939846e909c75cbee27aa23627cd0be5
ff60aaabe366ebd8f60b8e0e66a86896553f32a3
/3)printrepeatedterm.py
6f2a348d23c6f7fac53e93f03f6698939d5cb112
[]
no_license
ramyasutraye/Python-6
cb2f55339f6b74dffe6f73551f3554703e17b673
1cc1c8a9f0045b72e1d55ef1bb3cf48d8df8612c
refs/heads/master
2020-04-12T02:05:21.861754
2018-09-21T19:02:29
2018-09-21T19:02:29
null
0
0
null
null
null
null
UTF-8
Python
false
false
329
py
b=[] c=[] n=int(input("n")) if(1<=n<=100000): d = 0 for i in range(0,n): a=int(input("a")) b.append(a) if(i==b[i]): if(i>1): c.append(i) d=d+1 if(d>0): for i in range(0,d): print(c[i],end='') else: print(-1)
[ "noreply@github.com" ]
ramyasutraye.noreply@github.com
1803103160982a7a1919f6e7222975837423e07b
15f321878face2af9317363c5f6de1e5ddd9b749
/solutions_python/Problem_74/906.py
6098eb329012ba22538c600f690fc3242f5cc393
[]
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,750
py
f=open("A-large.in.txt","r") seq=f.readlines() f.close() N=eval(seq[0]) resultats=[] for i in range(1,N+1): print("Case #"+str(i)) l=seq[i].split() n=eval(l[0]) j=1 tabO=[] tabB=[] ordre=[] while j!=len(l): letter=l[j] j=j+1 number=eval(l[j]) j=j+1 ordre.append(letter) if letter=='O': tabO.append(number) elif letter=='B': tabB.append(number) CO=1 CB=1 result=0 iO=0 iB=0 move=0 while move!=n: letter=ordre[move] if letter=='O': target=tabO[iO] if iB<len(tabB): target2=tabB[iB] if CB<target2: CB=CB+1 elif CB>target2: CB=CB-1 if CO<target: CO=CO+1 elif CO>target: CO=CO-1 else: iO=iO+1 move=move+1 if letter=='B': target=tabB[iB] if iO<len(tabO): target2=tabO[iO] if CO<target2: CO=CO+1 elif CO>target2: CO=CO-1 if CB<target: CB=CB+1 elif CB>target: CB=CB-1 else: iB=iB+1 move=move+1 result=result+1 resultats.append("Case #"+str(i)+": "+str(result)+"\n") f=open("o.in","w") f.writelines(resultats) f.close()
[ "miliar1732@gmail.com" ]
miliar1732@gmail.com
a0b9911f771263a3ccb57196cec783570a84af37
a83bafc38b514a0339a5991be15870551ac49681
/test/test_size.py
fa8c40e84c918eb4dedd5c56839a82898118cc61
[]
no_license
bimdata/python-api-client
4ec2f81e404ef88d3a7e4d08e18965b598c567a2
c9b6ea0fbb4729b2a1c10522bdddfe08d944739d
refs/heads/master
2023-08-17T13:38:43.198097
2023-08-09T12:48:12
2023-08-09T12:48:12
131,603,315
0
4
null
2022-10-10T15:21:26
2018-04-30T14:06:15
Python
UTF-8
Python
false
false
850
py
""" BIMData API BIMData API is a tool to interact with your models stored on BIMData’s servers. Through the API, you can manage your projects, the clouds, upload your IFC files and manage them through endpoints. # noqa: E501 The version of the OpenAPI document: v1 (v1) Contact: support@bimdata.io Generated by: https://openapi-generator.tech """ import sys import unittest import bimdata_api_client from bimdata_api_client.model.size import Size class TestSize(unittest.TestCase): """Size unit test stubs""" def setUp(self): pass def tearDown(self): pass def testSize(self): """Test Size""" # FIXME: construct object with mandatory attributes with example values # model = Size() # noqa: E501 pass if __name__ == '__main__': unittest.main()
[ "infra@bimdata.io" ]
infra@bimdata.io
7cd2ab7936c6d68d7f3f14fd20b81bad6a522aee
4dd6a8d8024a72a3e2d8e71e86fd34888a149902
/keras/keras31_GRU.py
6f2d253b30f0ee9f5173859af80147f7d052dc83
[]
no_license
KOOKDONGHUN/study
d483b125d349956b325bc5f4d99a4a95dd80ccbc
517effbb19ddc820d53f0a6194463e7687467af6
refs/heads/master
2023-01-14T09:13:48.346502
2020-11-20T09:03:25
2020-11-20T09:03:25
259,818,381
0
0
null
null
null
null
UTF-8
Python
false
false
887
py
from numpy import array from keras.models import Sequential from keras.layers import Dense, LSTM, GRU # 1. 데이터 x = array([[1,2,3],[2,3,4],[3,4,5],[4,5,6]]) # x = x.reshape(x.shape[0], x.shape[1], 1) # y = array([4,5,6,7]) # print(x.shape) # print(y.shape) # # 2. 모델구성 model = Sequential() model.add(GRU(17,activation='relu',input_shape=(3,1))) # model.add(Dense(42)) model.add(Dense(39)) model.add(Dense(41)) model.add(Dense(1)) # 아웃풋 레이어 model.summary() # 3. 실행 from keras.callbacks import EarlyStopping els = EarlyStopping(monitor='loss', patience=8, mode='auto') model.compile(optimizer='adam',loss = 'mse') model.fit(x,y,epochs=200,batch_size=1,callbacks=[els]) # # 4. 테스트 x_predict = array([5,6,7]) x_predict = x_predict.reshape(1,3,1) print(x_predict,"\n",x_predict.shape) y_predict = model.predict(x_predict) print(y_predict)
[ "dh3978@naver.com" ]
dh3978@naver.com
26efc3cce877f299cf32012575f07145b63c0430
dda618067f13657f1afd04c94200711c1920ea5f
/scoop/user/views/sitemap.py
56f977aedeaf09d8b4316a0d943c922d7c04de75
[]
no_license
artscoop/scoop
831c59fbde94d7d4587f4e004f3581d685083c48
8cef6f6e89c1990e2b25f83e54e0c3481d83b6d7
refs/heads/master
2020-06-17T20:09:13.722360
2017-07-12T01:25:20
2017-07-12T01:25:20
74,974,701
0
0
null
null
null
null
UTF-8
Python
false
false
539
py
# coding: utf-8 from django.conf import settings from django.contrib.sitemaps import Sitemap from scoop.user.models.user import User class ProfileSitemap(Sitemap): """ Sitemap des profils utilisateurs """ limit = getattr(settings, 'SITEMAPS_ITEMS_PER_PAGE', 10000) # Getter def items(self): """ Renvoyer les objets du sitemap """ return User.objects.only('id', 'username').active() def location(self, obj): """ Renvoyer l'URL d'un profil du sitemap """ return obj.get_absolute_url()
[ "steve.kossouho@gmail.com" ]
steve.kossouho@gmail.com
393ec2cbe1fca2ff890772f6098dac1b3cc965e2
c397b704f6a18e5db90ef29325ee6d0564243c23
/dashboard/templatetags/tag.py
0ac21c9b270bdc07cb70bdcd725b394ffa58e0f5
[]
no_license
Raza046/Learning-management-System
47f112b3a05c3581675ff6d11f2bf95598b97b50
2bf29f2caff6247ca7a23cf041ca52f4f311b9b4
refs/heads/master
2023-02-23T14:42:27.815725
2021-01-29T10:25:55
2021-01-29T10:25:55
334,098,818
1
0
null
null
null
null
UTF-8
Python
false
false
332
py
from django import template register = template.Library() @register.filter def to_str1(value1): v = value1.split(":")[0] print("Str1 --> " + str(v)) return int(v) @register.filter def last_str(value): v2 = value.split(":")[1].split("-")[1] print("Str2 --> " + str(v2)) return int(v2)
[ "rulmustafa22@gmail.com" ]
rulmustafa22@gmail.com
6b91fcb254bfed2355e297e9b6d8373cda8ba3cd
1faf6ad07b7ed8c58577517803d7e26e97e71a7b
/setup.py
31a093f80d58d10e4f455b5cf4c785619af955cc
[]
no_license
pizzapanther/Django-Permissions-Keeper
d6b668b1926d2c0df39617c1adacec2350a63114
3f77332f74d58c67464a38d960050dba31d50e17
refs/heads/master
2021-01-22T03:39:03.654842
2012-05-04T21:43:40
2012-05-04T21:43:40
4,229,019
0
1
null
null
null
null
UTF-8
Python
false
false
510
py
import sys from setuptools import setup, find_packages setup( name = "permkeep", version = '12.05.1', description = "Easy way to keep group permissions in sync between Development and Production environments.", url = "https://github.com/pizzapanther/Django-Permissions-Keeper", author = "Paul Bailey", author_email = "paul.m.bailey@gmail.com", license = "BSD", packages = ['permkeep', 'permkeep.management', 'permkeep.management.commands'], include_package_data = True, )
[ "paul.m.bailey@gmail.com" ]
paul.m.bailey@gmail.com
220633df6985c7f48707704ceff0d82d9b9de024
9508879fcf1cff718f3fe80502baff8b82c04427
/python_domain/strings/the_minion_game.py
90bbaa4f8b053286f8a6493f0de4ace47d978aa8
[]
no_license
davidozhang/hackerrank
e37b4aace7d63c8be10b0d4d2bffb4d34d401d55
bdc40d6ff3e603949eb294bbc02a1e24a4ba5b80
refs/heads/master
2021-05-04T11:31:59.110118
2017-11-15T09:17:27
2017-11-15T09:17:27
47,906,672
1
0
null
null
null
null
UTF-8
Python
false
false
647
py
#!/usr/bin/python VOWELS = set(['A', 'E', 'I', 'O', 'U']) def main(): cons_indices, vowel_indices, cons_count, vowel_count = [], [], 0, 0 word = raw_input() length = len(word) for i in xrange(length): cons_indices.append(i) if word[i] not in VOWELS else vowel_indices.append(i) for j in cons_indices: cons_count += length - j for k in vowel_indices: vowel_count += length - k if cons_count > vowel_count: print 'Stuart ' + str(cons_count) elif cons_count < vowel_count: print 'Kevin ' + str(vowel_count) else: print 'Draw' if __name__ == '__main__': main()
[ "davzee@hotmail.com" ]
davzee@hotmail.com
2c28c51ebc9ab2af80770363f29a38e35845b4eb
987a68b9c196f39ba1810a2261cd4a08c35416a3
/BitManipulation/477-total-hamming-distance.py
d72e1cdc9fb4e1437904f0b57379eaa8d1614906
[]
no_license
xizhang77/LeetCode
c26e4699fbe1f2d2c4706b2e5ee82131be066ee5
ce68f5af57f772185211f4e81952d0345a6d23cb
refs/heads/master
2021-06-05T15:33:22.318833
2019-11-19T06:53:24
2019-11-19T06:53:24
135,076,199
0
0
null
null
null
null
UTF-8
Python
false
false
1,043
py
# -*- coding: utf-8 -*- ''' The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Now your job is to find the total Hamming distance between all pairs of the given numbers. Example: Input: 4, 14, 2 Output: 6 Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just showing the four bits relevant in this case). So the answer will be: HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6. Note: Elements of the given array are in the range of 0 to 10^9 Length of the array will not exceed 10^4. ''' # Time: O(32*n) ~ O(n) class Solution(object): def totalHammingDistance(self, nums): """ :type nums: List[int] :rtype: int """ ans = 0 n = len(nums) for pos in range(32): mask = 1 << pos ones = 0 for a in nums: ones += 1 if a&mask else 0 ans += (n-ones)*ones return ans
[ "xizhang1@cs.stonybrook.edu" ]
xizhang1@cs.stonybrook.edu
e514d3ebe05555c553230d7c7194e58ed12483ee
735a315ea82893f2acd5ac141f1a9b8be89f5cb9
/pylib/mdsplus/widgets/mdsplusonoff.py
e81302052652ef5f273b89179e660d88e9edca3e
[]
no_license
drsmith48/pppl-mdsplus-python
5ce6f7ccef4a23ea4b8296aa06f51f3a646dd36f
0fb5100e6718c8c10f04c3aac120558f521f9a59
refs/heads/master
2021-07-08T02:29:59.069616
2017-10-04T20:17:32
2017-10-04T20:17:32
105,808,853
0
0
null
null
null
null
UTF-8
Python
false
false
846
py
import gtk import gobject from mdspluswidget import MDSplusWidget class MDSplusOnOff(MDSplusWidget,gtk.CheckButton): __gtype_name__ = 'MDSplusOnOff' __gproperties__ = MDSplusWidget.__gproperties__ def reset(self): try: self.set_active(not self.getNode().state) except Exception,e: print "onoff reset had problem: %s" % (str(e),) raise def apply(self): if self.putOnApply: try: self.getNode().state=not self.get_active() except Exception,e: print "onooff apply had problem; %s" % (str(e),) def __init__(self): gtk.CheckButton.__init__(self) MDSplusWidget.__init__(self) self.putOnApply = True self.nidOffset = 0 gobject.type_register(MDSplusOnOff)
[ "drsmith8@wisc.edu" ]
drsmith8@wisc.edu
b0ad84988b762ee1b062b2341ef5f74ca5aa6e21
beea74a2a1f2445b107af411197e8b6300e715e6
/supervised_learning/0x01-classification/18-deep_neural_network.py
c0b59e9055452ecf800ba4ef9300a59b1bbc3e1d
[]
no_license
95ktsmith/holbertonschool-machine_learning
0240d8fa8523b06d3353c2bffa74205b84253be8
2757c8526290197d45a4de33cda71e686ddcbf1c
refs/heads/master
2023-07-26T16:02:26.399758
2021-09-09T15:57:57
2021-09-09T15:57:57
310,087,776
0
0
null
null
null
null
UTF-8
Python
false
false
2,595
py
#!/usr/bin/env python3 """ Deep Neural Network """ import numpy as np class DeepNeuralNetwork: """ Class representing a deep neural network """ def __init__(self, nx, layers): """ Init nx is the number of input features nx must be a positive integer layers is a list representing the number of nodes in each layer layers must be a list of positive integers L: number of layers in the network cache: dictionary to hold all intermediary values of the network weights: dictionary to hold all weights and biases of the network """ if type(nx) is not int: raise TypeError("nx must be an integer") if nx < 1: raise ValueError("nx must be a positive integer") if type(layers) is not list or len(layers) == 0: raise TypeError("layers must be a list of positive integers") self.__L = len(layers) self.__cache = {} self.__weights = {} for i in range(0, self.L): if type(layers[i]) is not int or layers[i] < 1: raise TypeError("layers must be a list of positive integers") if i == 0: w = np.random.randn(layers[i], nx) * np.sqrt(2 / nx) self.__weights['W1'] = w self.__weights['b1'] = np.zeros((layers[i], 1)) else: w = np.random.randn(layers[i], layers[i - 1]) w *= np.sqrt(2 / layers[i - 1]) self.__weights['W{}'.format(i + 1)] = w self.__weights['b{}'.format(i + 1)] = np.zeros((layers[i], 1)) @property def L(self): """ L getter """ return self.__L @property def cache(self): """ cache getter """ return self.__cache @property def weights(self): """ weights getter """ return self.__weights def forward_prop(self, X): """ Calculates the forward propagation of the neural network X with shape (nx, m) contains input data nx is the number of input features m is the number of examples Updates __cache """ self.__cache["A0"] = X for i in range(1, self.L + 1): w = "W" + str(i) a = "A" + str(i - 1) b = "b" + str(i) Y = self.weights[w] @ self.cache[a] + self.weights[b] A = 1 / (1 + np.exp(Y * -1)) self.__cache["A" + str(i)] = A return self.__cache["A" + str(self.L)], self.__cache
[ "95ktsmith@gmail.com" ]
95ktsmith@gmail.com
6f030a71946122b5dda42fcbca479ce4f90632ec
2614f223ad9aecddaca4358d51910e036bf0c2ff
/archived/asap/count_asap.py
7981d5311e807c7e01362783a836046a0c2a45e3
[]
no_license
cff874460349/tct
d615efb7485e5de3de66e2d02fff5ce9b33350a3
5bb4b16c4fad03a470243dd7db807a6a733d02e5
refs/heads/master
2021-03-14T00:55:51.556468
2019-06-28T03:56:54
2019-06-28T03:56:54
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,174
py
# count the number of annotations in each category import os import csv import collections from xml.dom.minidom import parse import xml.dom.minidom import xlsxwriter def scan_files(directory, prefix=None, postfix=None): files_list = [] for root, sub_dirs, files in os.walk(directory): for special_file in files: if postfix: if special_file.endswith(postfix): files_list.append(os.path.join(root, special_file)) elif prefix: if special_file.startswith(prefix): files_list.append(os.path.join(root, special_file)) else: files_list.append(os.path.join(root, special_file)) return files_list colorCounts = {"#000000": 0, "#aa0000": 0, "#aa007f": 0, "#aa00ff": 0, "#ff0000": 0, "#005500": 0, "#00557f": 0, "#0055ff": 0, "#aa5500": 0, "#aa557f": 0, "#aa55ff": 0, "#ff5500": 0, "#ff557f": 0, "#ff55ff": 0, "#00aa00": 0, "#00aa7f": 0, "#00aaff": 0, "#55aa00": 0, "#55aa7f": 0} largeCounts = {"#000000": 0, "#aa0000": 0, "#aa007f": 0, "#aa00ff": 0, "#ff0000": 0, "#005500": 0, "#00557f": 0, "#0055ff": 0, "#aa5500": 0, "#aa557f": 0, "#aa55ff": 0, "#ff5500": 0, "#ff557f": 0, "#ff55ff": 0, "#00aa00": 0, "#00aa7f": 0, "#00aaff": 0, "#55aa00": 0, "#55aa7f": 0} classes = {"#aa0000": "HSIL", "#aa007f": "ASCH", "#005500": "LSIL", "#00557f": "ASCUS", "#0055ff": "SCC", "#aa557f": "ADC", "#aa55ff": "EC", "#ff5500": "AGC1", "#ff557f": "AGC2", "#ff55ff": "AGC3", "#00aa00": "FUNGI", "#00aa7f": "TRI", "#00aaff": "CC", "#55aa00": "ACTINO", "#55aa7f": "VIRUS", "#ffffff": "NORMAL", "#000000": "MC", "#aa00ff": "SC", "#ff0000": "RC", "#aa5500": "GEC"} total = 0 large = 0 def count(files_list): global total # number of files global large for file in files_list: DOMTree = xml.dom.minidom.parse(file) collection = DOMTree.documentElement total += 1 annotations = collection.getElementsByTagName("Annotation") wrong = 0 for annotation in annotations: if annotation.getAttribute("Color") in colorCounts: colorCounts[annotation.getAttribute("Color")] += 1 coordinates = annotation.getElementsByTagName("Coordinate") x_coords = [] y_coords = [] for coordinate in coordinates: x_coords.append(float(coordinate.getAttribute("X"))) y_coords.append(float(coordinate.getAttribute("Y"))) x_min = int(min(x_coords)) x_max = int(max(x_coords)) y_min = int(min(y_coords)) y_max = int(max(y_coords)) if (x_max-x_min) > 608 or (y_max-y_min) > 608: largeCounts[annotation.getAttribute("Color")] += 1 large += 1 else: wrong += 1 print("position: " + annotation.getAttribute("Name")) if wrong > 0: print("# wrong color = " + str(wrong) + " --> " + file) print() def write_csv(counts, csv_path): with open(csv_path, 'w') as csv_file: csv_writer = csv.writer(csv_file) for key,value in counts.items(): csv_writer.writerow([key,classes[key], value]) # count annotations from single root directory file_path = "/home/sakulaki/yolo-yuli/xxx/data_20180922/checked" files_list = scan_files(file_path, postfix=".xml") count(files_list) write_csv(collections.OrderedDict(sorted(colorCounts.items())), "/home/sakulaki/yolo-yuli/xxx/data_20180922/summary.csv") # # count annotations from multiple separated directories # classes = ("01_ASCUS", "02_LSIL", "03_ASCH", "04_HSIL", "05_SCC", "06_AGC1", "07_AGC2", "08_ADC", "09_EC", "10_FUNGI", "11_TRI", "12_CC", "13_ACTINO", "14_VIRUS") # file_path = "/media/tsimage/Elements/data" # for class_i in classes: # file_path_i = os.path.join(file_path, class_i) # files_list = scan_files(file_path_i, postfix=".xml") # count(files_list) # output results print("# files: " + str(total)) print(colorCounts) print("# labels large than 608: " + str(large)) print(largeCounts) # write to excel # workbook = xlsxwriter.Workbook("C:/liyu/gui/tct/res/个人统计.xlsx") # worksheet = workbook.add_worksheet() # worksheet.write(0, 0, file_path) # row = 1 # for key in colorCounts.keys(): # worksheet.write(row, 0, key) # worksheet.write(row, 1, colorCounts[key]) # row += 1 # workbook.close()
[ "yuli00986081@gmail.com" ]
yuli00986081@gmail.com
d674af227aff1f94b7c80bd78974fba9c40fc93f
32cf94c304c2c832595a28b49c7d9e0361d50950
/test/re2/unicode_test.py
a88a3ad5a4bd5c1ae59908c3aef9b84135ee98f9
[ "MIT" ]
permissive
oudream/ccxx
11d3cd9c044c5f413ebc0735548f102a6f583114
26cecfb02e861ce6b821b33350493bac4793e997
refs/heads/master
2023-01-29T11:20:12.210439
2023-01-12T06:49:23
2023-01-12T06:49:23
47,005,127
46
11
MIT
2020-10-17T02:24:06
2015-11-28T01:05:30
C
UTF-8
Python
false
false
6,720
py
#!/usr/bin/python2.4 # # Copyright 2008 The RE2 Authors. All Rights Reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. """Unittest for the util/regexp/re2/unicode.py module.""" import os import StringIO from google3.pyglib import flags from google3.testing.pybase import googletest from google3.util.regexp.re2 import unicode _UNICODE_DIR = os.path.join(flags.FLAGS.test_srcdir, "google3", "third_party", "unicode", "ucd-5.1.0") class ConvertTest(googletest.TestCase): """Test the conversion functions.""" def testUInt(self): self.assertEquals(0x0000, unicode._UInt("0000")) self.assertEquals(0x263A, unicode._UInt("263A")) self.assertEquals(0x10FFFF, unicode._UInt("10FFFF")) self.assertRaises(unicode.InputError, unicode._UInt, "263") self.assertRaises(unicode.InputError, unicode._UInt, "263AAAA") self.assertRaises(unicode.InputError, unicode._UInt, "110000") def testURange(self): self.assertEquals([1, 2, 3], unicode._URange("0001..0003")) self.assertEquals([1], unicode._URange("0001")) self.assertRaises(unicode.InputError, unicode._URange, "0001..0003..0005") self.assertRaises(unicode.InputError, unicode._URange, "0003..0001") self.assertRaises(unicode.InputError, unicode._URange, "0001..0001") def testUStr(self): self.assertEquals("0x263A", unicode._UStr(0x263a)) self.assertEquals("0x10FFFF", unicode._UStr(0x10FFFF)) self.assertRaises(unicode.InputError, unicode._UStr, 0x110000) self.assertRaises(unicode.InputError, unicode._UStr, -1) _UNICODE_TABLE = """# Commented line, should be ignored. # The next line is blank and should be ignored. 0041;Capital A;Line 1 0061..007A;Lowercase;Line 2 1F00;<Greek, First>;Ignored 1FFE;<Greek, Last>;Line 3 10FFFF;Runemax;Line 4 0000;Zero;Line 5 """ _BAD_TABLE1 = """ 111111;Not a code point; """ _BAD_TABLE2 = """ 0000;<Zero, First>;Missing <Zero, Last> """ _BAD_TABLE3 = """ 0010..0001;Bad range; """ class AbortError(Exception): """Function should not have been called.""" def Abort(): raise AbortError("Abort") def StringTable(s, n, f): unicode.ReadUnicodeTable(StringIO.StringIO(s), n, f) class ReadUnicodeTableTest(googletest.TestCase): """Test the ReadUnicodeTable function.""" def testSimpleTable(self): ncall = [0] # can't assign to ordinary int in DoLine def DoLine(codes, fields): self.assertEquals(3, len(fields)) ncall[0] += 1 self.assertEquals("Line %d" % (ncall[0],), fields[2]) if ncall[0] == 1: self.assertEquals([0x0041], codes) self.assertEquals("0041", fields[0]) self.assertEquals("Capital A", fields[1]) elif ncall[0] == 2: self.assertEquals(range(0x0061, 0x007A + 1), codes) self.assertEquals("0061..007A", fields[0]) self.assertEquals("Lowercase", fields[1]) elif ncall[0] == 3: self.assertEquals(range(0x1F00, 0x1FFE + 1), codes) self.assertEquals("1F00..1FFE", fields[0]) self.assertEquals("Greek", fields[1]) elif ncall[0] == 4: self.assertEquals([0x10FFFF], codes) self.assertEquals("10FFFF", fields[0]) self.assertEquals("Runemax", fields[1]) elif ncall[0] == 5: self.assertEquals([0x0000], codes) self.assertEquals("0000", fields[0]) self.assertEquals("Zero", fields[1]) StringTable(_UNICODE_TABLE, 3, DoLine) self.assertEquals(5, ncall[0]) def testErrorTables(self): self.assertRaises(unicode.InputError, StringTable, _UNICODE_TABLE, 4, Abort) self.assertRaises(unicode.InputError, StringTable, _UNICODE_TABLE, 2, Abort) self.assertRaises(unicode.InputError, StringTable, _BAD_TABLE1, 3, Abort) self.assertRaises(unicode.InputError, StringTable, _BAD_TABLE2, 3, Abort) self.assertRaises(unicode.InputError, StringTable, _BAD_TABLE3, 3, Abort) class ParseContinueTest(googletest.TestCase): """Test the ParseContinue function.""" def testParseContinue(self): self.assertEquals(("Private Use", "First"), unicode._ParseContinue("<Private Use, First>")) self.assertEquals(("Private Use", "Last"), unicode._ParseContinue("<Private Use, Last>")) self.assertEquals(("<Private Use, Blah>", None), unicode._ParseContinue("<Private Use, Blah>")) class CaseGroupsTest(googletest.TestCase): """Test the CaseGroups function (and the CaseFoldingReader).""" def FindGroup(self, c): if type(c) == str: c = ord(c) for g in self.groups: if c in g: return g return None def testCaseGroups(self): self.groups = unicode.CaseGroups(unicode_dir=_UNICODE_DIR) self.assertEquals([ord("A"), ord("a")], self.FindGroup("a")) self.assertEquals(None, self.FindGroup("0")) class ScriptsTest(googletest.TestCase): """Test the Scripts function (and the ScriptsReader).""" def FindScript(self, c): if type(c) == str: c = ord(c) for script, codes in self.scripts.items(): for code in codes: if c == code: return script return None def testScripts(self): self.scripts = unicode.Scripts(unicode_dir=_UNICODE_DIR) self.assertEquals("Latin", self.FindScript("a")) self.assertEquals("Common", self.FindScript("0")) self.assertEquals(None, self.FindScript(0xFFFE)) class CategoriesTest(googletest.TestCase): """Test the Categories function (and the UnicodeDataReader).""" def FindCategory(self, c): if type(c) == str: c = ord(c) short = None for category, codes in self.categories.items(): for code in codes: if code == c: # prefer category Nd over N if len(category) > 1: return category if short == None: short = category return short def testCategories(self): self.categories = unicode.Categories(unicode_dir=_UNICODE_DIR) self.assertEquals("Ll", self.FindCategory("a")) self.assertEquals("Nd", self.FindCategory("0")) self.assertEquals("Lo", self.FindCategory(0xAD00)) # in First, Last range self.assertEquals(None, self.FindCategory(0xFFFE)) self.assertEquals("Lo", self.FindCategory(0x8B5A)) self.assertEquals("Lo", self.FindCategory(0x6C38)) self.assertEquals("Lo", self.FindCategory(0x92D2)) self.assertTrue(ord("a") in self.categories["L"]) self.assertTrue(ord("0") in self.categories["N"]) self.assertTrue(0x8B5A in self.categories["L"]) self.assertTrue(0x6C38 in self.categories["L"]) self.assertTrue(0x92D2 in self.categories["L"]) def main(): googletest.main() if __name__ == "__main__": main()
[ "oudream@126.com" ]
oudream@126.com
a6321682c22d998495daa7c30cf51f69ad8cfdcd
fbe0d8ceb2d753596d61f948939999499767abcd
/selectivechat_project/asgi.py
07e8be94cc5c78874d1fc5c2106161cf867f541d
[ "MIT" ]
permissive
calixo888/selectivechat
ac0929ecbdb99e7e76fdbf8e5e037de20d418e64
2acbabe2355590986ea838348013d6ae7ddc6210
refs/heads/master
2022-05-03T02:40:23.329969
2020-10-25T23:18:26
2020-10-25T23:18:26
238,330,840
0
0
MIT
2022-04-22T23:00:33
2020-02-04T23:49:05
JavaScript
UTF-8
Python
false
false
215
py
import os import django from channels.routing import get_default_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "selectivechat_project.settings") django.setup() application = get_default_application()
[ "calix.huang1@gmail.com" ]
calix.huang1@gmail.com
1a68aeae4a81ff86a15a5dc3c037aa863c913cbc
a4cab19f70365d1d5fba31f7d93ecd315ccc6268
/0x01-python-if_else_loops_functions/8-uppercase.py
6b69d971831179f43a3140e150e24617959a7914
[]
no_license
cmmolanos1/holbertonschool-higher_level_programming
c2154022cb868caccb7759812c292106c3654b41
a58c4fb3659d520b4d78631c6a00c6301f79522d
refs/heads/master
2020-07-22T23:54:31.275115
2020-04-11T00:46:00
2020-04-11T00:46:00
207,374,519
0
2
null
null
null
null
UTF-8
Python
false
false
210
py
#!/usr/bin/python3 def uppercase(str): for i in range(len(str)): char = ord(str[i]) if 97 <= char <= 122: char = char - 32 print("{:c}".format(char), end='') print()
[ "926@holbertonschool.com" ]
926@holbertonschool.com
e89f9593303b5bb1ecd95e569dd8df7c44645932
c2d2b22edac0b3c0b021ad28ad638dece18c2549
/Python/Problems/Knapsack_Problem/solution.py
208187de85cbc3228edbb5207e7f8c0bec3a934a
[]
no_license
dileepmenon/GeeksForGeeks
248c69065d947f760f054dd4681063f21ca9be23
9b5f8955a02cae27e4677b2c3fa1578e6ad1c545
refs/heads/master
2021-05-23T05:24:58.876414
2017-12-04T05:58:47
2017-12-04T05:58:47
95,201,250
1
0
null
null
null
null
UTF-8
Python
false
false
618
py
#!bin/python3 def KP(w_l, p_l, W): if not w_l: return 0 if W == 0: return 0 try: return d[(p_l[0], len(p_l), W)] except: if W-w_l[0] >= 0: s = max(p_l[0] + KP(w_l[1:], p_l[1:], W-w_l[0]), KP(w_l[1:], p_l[1:], W)) else: s = KP(w_l[1:], p_l[1:], W) d[(p_l[0], len(p_l), W)] = s return s num_t = int(input()) for i in range(num_t): n = int(input()) W = int(input()) p_l = list(map(int, input().strip().split())) w_l = list(map(int, input().strip().split())) d = {} print(KP(w_l, p_l, W))
[ "dileepmenon92@yahoo.com" ]
dileepmenon92@yahoo.com
91242f64a3dda3056dd978c5cd6248e143e8a1d6
3f642957664a470897b10b15ab29734bf53ffd9c
/config/settings/prod.py
9bdb2635999a4209e918ea4ff182fcec05d179f1
[]
no_license
birkoss/walleteur-api
da276de50f2d976bae9d749da98f80f3f6c45518
bc16f2e5801ccddf90bff1cf1eb867c697fb9d71
refs/heads/master
2023-03-28T16:59:23.678986
2021-04-11T00:13:06
2021-04-11T00:13:06
354,413,671
0
0
null
null
null
null
UTF-8
Python
false
false
585
py
from .base import * ALLOWED_HOSTS = ['api.walleteur.app'] DEBUG = True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': get_secret('DATABASE_NAME'), 'USER': get_secret('DATABASE_USER'), 'PASSWORD': get_secret('DATABASE_PASSWORD'), 'HOST': 'localhost', 'PORT': '3306', 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'" } } } STATIC_URL = 'https://walleteur.app/assets/api/' STATIC_ROOT = '/home/walleteur/domains/walleteur.app/public_html/assets/api/'
[ "admin@birkoss.com" ]
admin@birkoss.com
f6f3db537ccc13b21749242df396539920dc9396
3f2847f499878ea2a42cffea6f312ebe5fc14098
/aiosmb/dcerpc/v5/common/even6/resultset.py
46f925c1d14ad1eb0f7059f73a16c8520df23bf1
[]
no_license
rvrsh3ll/aiosmb
a924b2d2be3e60b44a1522db52a1d2316fc3ba6f
a00a7d32f43e91746e74f5d72cd8f2ff4a4e8ea6
refs/heads/master
2023-06-07T15:33:14.701529
2023-05-30T16:02:35
2023-05-30T16:02:35
203,462,354
0
0
null
2023-05-31T07:45:14
2019-08-20T22:15:30
Python
UTF-8
Python
false
false
1,258
py
import io # https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-even6/762528ba-f36a-4d17-ba2b-0f0244a45f2f class RESULT_SET: def __init__(self): self.totalSize = None self.headerSize = None self.eventOffset = None self.bookmarkOffset = None self.binXmlSize = None self.eventData = None self.numberOfSubqueryIDs = None self.subqueryIDs = None self.bookMarkData = None @staticmethod def from_bytes(data): return RESULT_SET.from_buffer(io.BytesIO(data)) @staticmethod def from_buffer(buff): r = RESULT_SET() pos = buff.tell() r.totalSize = int.from_bytes(buff.read(4), byteorder = 'little', signed = False) pos += r.totalSize r.headerSize = int.from_bytes(buff.read(4), byteorder = 'little', signed = False) r.eventOffset = int.from_bytes(buff.read(4), byteorder = 'little', signed = False) r.bookmarkOffset = int.from_bytes(buff.read(4), byteorder = 'little', signed = False) r.binXmlSize = int.from_bytes(buff.read(4), byteorder = 'little', signed = False) r.eventData = buff.read(r.binXmlSize) r.numberOfSubqueryIDs = int.from_bytes(buff.read(4), byteorder = 'little', signed = False) r.subqueryIDs = buff.read(r.numberOfSubqueryIDs) r.bookMarkData = buff.read(pos - buff.tell()) return r
[ "info@skelsec.com" ]
info@skelsec.com
e0e63584b29b38b3bbf8b8c4aae8e8e2e55f8837
13d222bc3332378d433835914da26ed16b583c8b
/tests/challenge90/test_challenge90.py
888f1e85cb508d5239b468228512fd72a0fa717a
[]
no_license
mattjhussey/pemjh
c27a09bab09cd2ade31dc23fffac07374bea9366
2ebb0a525d2d1c0ee28e83fdc2638c2bec97ac99
refs/heads/master
2023-04-16T03:08:59.390698
2023-04-08T10:54:00
2023-04-08T10:54:00
204,912,926
0
0
null
null
null
null
UTF-8
Python
false
false
199
py
""" Tests for challenge90 """ from robber import expect from pemjh.challenge90 import main def test_challenge90(): """ Regression testing challenge90 """ expect(main()).to.eq(1217)
[ "matthew.hussey@googlemail.com" ]
matthew.hussey@googlemail.com
36362d5255285a4d5af86585e2249648aeeb2fe9
eadde35af2b82fe3de7bc2f1cbc579af0a1a8816
/bookstore/migrations/0005_auto_20180910_1302.py
aca3b8ea2a485fa9413c77f0abf75b52ecb84281
[]
no_license
hdforoozan/Shop
425a2371d2f96baca29db0948294edb31a4504b8
776d36149733a38bda26715bc3b16c03f0d53a9c
refs/heads/master
2020-04-24T06:22:14.033290
2019-02-20T22:51:49
2019-02-20T22:51:49
171,762,724
0
0
null
null
null
null
UTF-8
Python
false
false
416
py
# Generated by Django 2.1 on 2018-09-10 08:32 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('bookstore', '0004_auto_20180909_1735'), ] operations = [ migrations.AlterField( model_name='book', name='price', field=models.DecimalField(blank=True, decimal_places=2, max_digits=10), ), ]
[ "hdforoozan@gmail.com" ]
hdforoozan@gmail.com
d08de54d6bc59e78633d8e6b4a520fc80e51009c
909bb1b51213e47424ac9ccf3c3ca83764a5c04b
/semestre01/exercises_university_uri/1282.1.py
27d805f65a4be6aee16bc016ef4043a431a27604
[ "MIT" ]
permissive
alaanlimaa/impactaADS
07e5d74c88ca0ec85c96960fadc2e22cbb67269b
307d0b2c7831a5038184592afae7a825b2774498
refs/heads/main
2023-07-23T20:36:06.045907
2021-08-30T15:45:02
2021-08-30T15:45:02
387,860,398
0
0
null
null
null
null
UTF-8
Python
false
false
1,280
py
def txt(msg): print('-' * len(msg)) print(msg) print('-' * len(msg)) qtdCanais = int(input()) lista = [] for c in range(1, qtdCanais + 1): num = input() if ' ' in num: numE = num.replace(' ', '-') numE = numE.replace(';', ' ').split() lista.append(numE) else: num = num.replace(';', ' ').split() lista.append(num) premium = float(input()) notPremium = float(input()) txt('BÔNUS') for s in lista: insc = int(s[1]) mont = float(s[2]) div = insc % 1000 if 'não' in s: if insc > 1000 and div > 0: totInsc = insc - div monetizar = ((totInsc / 1000) * notPremium) + mont elif insc < 1000 and div > 0: monetizar = float(s[2]) elif div == 0: monetizar = ((insc / 1000) * notPremium) + mont else: if insc > 1000 and div > 0: totInsc = insc - div monetizar = ((totInsc / 1000) * premium) + mont elif insc < 1000 and div > 0: monetizar = float(s[2]) elif div == 0: monetizar = ((insc / 1000) * premium) + mont if '-' in str(s[0]): print(f'{str(s[0]).replace("-", " ")}: R$ {monetizar:.2f}') else: print(f'{s[0]}: R$ {monetizar:.2f}')
[ "alanlimabusiness@outlook.com" ]
alanlimabusiness@outlook.com
60c39f0052992c31c1a7d737ffd1a39b574e54e5
a742bd051641865d2e5b5d299c6bc14ddad47f22
/algorithm/leetcode/greedy/02-无重叠区间.py
74158138c6e570b1e20ea082b1bcb41d0e108c23
[]
no_license
lxconfig/UbuntuCode_bak
fb8f9fae7c42cf6d984bf8231604ccec309fb604
3508e1ce089131b19603c3206aab4cf43023bb19
refs/heads/master
2023-02-03T19:10:32.001740
2020-12-19T07:27:57
2020-12-19T07:27:57
321,351,481
0
0
null
null
null
null
UTF-8
Python
false
false
653
py
""" 给定一个区间的集合,找到需要移除区间的最小数量,使剩余区间互不重叠。 """ from typing import List class Solution: def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: def OverlapIntervals(intervals: List[List[int]]) -> int: if not intervals: return 0 items = sorted(intervals, key=lambda x: x[1]) x, count = items[0], 1 for item in items[1: ]: if item[0] >= x[1]: count, x = count + 1, item return count return len(intervals) - OverlapIntervals(intervals)
[ "525868229@qq.com" ]
525868229@qq.com
57938b46b9880b0ecc3b834e564bc5fe379aef20
bd1281d7da02ace6b50aeb267b9a0cd8876eea11
/badwolf/log/views.py
c31fb6ed5e556649a9a6c522df649952389c2021
[ "MIT" ]
permissive
bosondata/badwolf
6ebde680df6d3e7e7e0a7d295ce7cf6944a93d3d
c693785af101f68505769cd712bbf13e37423587
refs/heads/master
2023-03-08T04:51:36.911524
2019-07-11T02:44:22
2019-07-11T02:44:22
67,678,705
95
15
MIT
2018-12-19T09:05:49
2016-09-08T07:18:49
Python
UTF-8
Python
false
false
3,039
py
# -*- coding: utf-8 -*- import os import logging import deansi from flask import Blueprint, current_app, send_from_directory, request, abort, Response from docker import DockerClient logger = logging.getLogger(__name__) blueprint = Blueprint('log', __name__) FOLLOW_LOG_JS = '''<script type="text/javascript"> var observeDOM = (function(){ var MutationObserver = window.MutationObserver || window.WebKitMutationObserver, eventListenerSupported = window.addEventListener; return function(obj, callback){ if( MutationObserver ){ // define a new observer var obs = new MutationObserver(function(mutations, observer){ if( mutations[0].addedNodes.length || mutations[0].removedNodes.length ) callback(); }); // have the observer observe foo for changes in children obs.observe( obj, { childList:true, subtree:true }); } else if( eventListenerSupported ){ obj.addEventListener('DOMNodeInserted', callback, false); obj.addEventListener('DOMNodeRemoved', callback, false); } }; })(); window.autoFollow = true; window.onscroll = function() { if (window.innerHeight + window.pageYOffset >= document.body.offsetHeight - 10) { window.autoFollow = true; } else { window.autoFollow = false; } }; observeDOM(document, function() { if (window.autoFollow) { window.scrollTo(window.pageXOffset, document.body.scrollHeight); } }); </script>''' @blueprint.route('/build/<sha>', methods=['GET']) def build_log(sha): task_id = request.args.get('task_id') log_dir = os.path.join(current_app.config['BADWOLF_LOG_DIR'], sha) # old log path if os.path.exists(os.path.join(log_dir, 'build.html')): return send_from_directory(log_dir, 'build.html') if not task_id: abort(404) # new log path log_dir = os.path.join(log_dir, task_id) if os.path.exists(os.path.join(log_dir, 'build.html')): return send_from_directory(log_dir, 'build.html') # Try realtime logs docker = DockerClient( base_url=current_app.config['DOCKER_HOST'], timeout=current_app.config['DOCKER_API_TIMEOUT'], version='auto', ) containers = docker.containers.list(filters=dict( status='running', label='task_id={}'.format(task_id), )) if not containers: abort(404) # TODO: ensure only 1 container matched task_id container = containers[0] def _streaming_gen(): yield '<style>{}</style>'.format(deansi.styleSheet()) yield FOLLOW_LOG_JS yield '<div class="ansi_terminal">' buffer = [] for log in container.logs(stdout=True, stderr=True, stream=True, follow=True): char = str(log) buffer.append(char) if char == '\n': yield deansi.deansi(''.join(buffer)) buffer = [] if buffer: yield deansi.deansi(''.join(buffer)) yield '</div>' return Response(_streaming_gen(), mimetype='text/html;charset=utf-8')
[ "messense@icloud.com" ]
messense@icloud.com
a4e5dd0c35c7a3cb860b83cb9f710b863ad829b1
15f321878face2af9317363c5f6de1e5ddd9b749
/solutions_python/Problem_206/1034.py
37a51eca5168bb24b1adf080e12fe5ea12ac91a4
[]
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
856
py
import os input_file = open("input_large.in", "r") output_file = open("output_large.out", "w") cases = int(input_file.readline()) for i in range(cases): params = input_file.readline().split(" ") full_dist = float(params[0]) num_horses = int(params[1]) h_distances = [] h_speeds = [] for h in range(num_horses): h_params = input_file.readline().split(" ") h_start_pos = int(h_params[0]) h_speed = int(h_params[1]) h_distances.append(float(full_dist) - float(h_start_pos)) h_speeds.append(float(h_speed)) time_remaining = [h_distances[j] / h_speeds[j] for j in range(len(h_distances))] annie_time = max(time_remaining) annie_speed = full_dist / annie_time output_file.write("Case #" + str(i + 1) + ": " + str(annie_speed) + "\n")
[ "miliar1732@gmail.com" ]
miliar1732@gmail.com
84cde06244cc011a3a7ae182d30b956383dc9e3b
4cd4e5c39523f5889efb676414c5f4e58bc38991
/point_clouds/aux.py
1875110bb05ac37092d93f63297800da5c1efd46
[ "MIT" ]
permissive
optas/geo_tool
84a63c8dd9e9881234737a816a2a5b119e4368eb
7eda787b4b9361ee6cb1601a62495d9d5c3605e6
refs/heads/master
2022-02-26T18:03:09.930737
2022-01-23T03:19:46
2022-01-23T03:19:46
67,737,034
7
3
null
null
null
null
UTF-8
Python
false
false
3,712
py
''' Created on Aug 21, 2017 @author: optas ''' import warnings import numpy as np from sklearn.neighbors import NearestNeighbors from scipy.sparse.linalg import eigs from numpy.linalg import norm from .. fundamentals import Graph from .. utils.linalg_utils import l2_norm def greedy_match_pc_to_pc(from_pc, to_pc): '''map from_pc points to to_pc by minimizing the from-to-to euclidean distance.''' nn = NearestNeighbors(n_neighbors=1).fit(to_pc) distances, indices = nn.kneighbors(from_pc) return indices, distances def chamfer_pseudo_distance(pc1, pc2): _, d1 = greedy_match_pc_to_pc(pc1, pc2) _, d2 = greedy_match_pc_to_pc(pc2, pc1) return np.sum(d1) + np.sum(d2) def laplacian_spectrum(pc, n_evecs, k=6): ''' k: (int) number of nearest neighbors each point is connected with in the constructed Adjacency matrix that will be used to derive the Laplacian. ''' neighbors_ids, distances = pc.k_nearest_neighbors(k) A = Graph.knn_to_adjacency(neighbors_ids, distances) if Graph.connected_components(A)[0] != 1: raise ValueError('Graph has more than one connected component, increase k.') A = (A + A.T) / 2.0 L = Graph.adjacency_to_laplacian(A, 'norm').astype('f4') evals, evecs = eigs(L, n_evecs + 1, sigma=-10e-1, which='LM') if np.any(l2_norm(evecs.imag, axis=0) / l2_norm(evecs.real, axis=0) > 1.0 / 100): warnings.warn('Produced eigen-vectors are complex and contain significant mass on the imaginary part.') evecs = evecs.real # eigs returns complex values by default. evals = evals.real index = np.argsort(evals) # Sort evals from smallest to largest evals = evals[index] evecs = evecs[:, index] return evals, evecs def unit_cube_grid_point_cloud(resolution, clip_sphere=False): '''Returns the center coordinates of each cell of a 3D grid with resolution^3 cells, that is placed in the unit-cube. If clip_sphere it True it drops the "corner" cells that lie outside the unit-sphere. ''' grid = np.ndarray((resolution, resolution, resolution, 3), np.float32) spacing = 1.0 / float(resolution - 1) for i in xrange(resolution): for j in xrange(resolution): for k in xrange(resolution): grid[i, j, k, 0] = i * spacing - 0.5 grid[i, j, k, 1] = j * spacing - 0.5 grid[i, j, k, 2] = k * spacing - 0.5 if clip_sphere: grid = grid.reshape(-1, 3) grid = grid[norm(grid, axis=1) <= 0.5] return grid, spacing def point_cloud_to_volume(points, vsize, radius=1.0): """ input is Nx3 points. output is vsize*vsize*vsize assumes points are in range [-radius, radius] Original from https://github.com/daerduoCarey/partnet_seg_exps/blob/master/exps/utils/pc_util.py """ vol = np.zeros((vsize,vsize,vsize)) voxel = 2*radius/float(vsize) locations = (points + radius)/voxel locations = locations.astype(int) vol[locations[:, 0], locations[:, 1], locations[:, 2]] = 1.0 return vol def volume_to_point_cloud(vol): """ vol is occupancy grid (value = 0 or 1) of size vsize*vsize*vsize return Nx3 numpy array. Original from Original from https://github.com/daerduoCarey/partnet_seg_exps/blob/master/exps/utils/pc_util.py """ vsize = vol.shape[0] assert(vol.shape[1] == vsize and vol.shape[1] == vsize) points = [] for a in range(vsize): for b in range(vsize): for c in range(vsize): if vol[a,b,c] == 1: points.append(np.array([a, b, c])) if len(points) == 0: return np.zeros((0, 3)) points = np.vstack(points) return points
[ "optas@stanford.edu" ]
optas@stanford.edu
2286d2a45d3515907c5f7eb59c5add02b7a6e530
76f59c245744e468577a293a0b9b078f064acf07
/79.word-search.py
632b1ff08a943956d5e83bffd8706832f9f80968
[]
no_license
satoshun-algorithm-example/leetcode
c3774f07e653cf58640a6e7239705e58c5abde82
16b39e903755dea86f9a4f16df187bb8bbf835c5
refs/heads/master
2020-07-01T10:24:05.343283
2020-01-13T03:27:27
2020-01-13T03:27:27
201,144,558
0
0
null
null
null
null
UTF-8
Python
false
false
1,863
py
# # @lc app=leetcode id=79 lang=python3 # # [79] Word Search # from typing import List # @lc code=start class Solution: def exist(self, board: List[List[str]], word: str) -> bool: if not word: return True leading = word[0] for y in range(len(board)): for x in range(len(board[0])): if board[y][x] == leading: access = [[True for _ in range(len(board[0]))] for _ in range(len(board))] access[y][x] = False if self.search(x, y, board, word[1:], access): return True return False def search(self, x, y, board, word, access): if not word: return True if x - 1 >= 0 and access[y][x - 1]: if board[y][x - 1] == word[0]: access[y][x - 1] = False if self.search(x - 1, y, board, word[1:], access): return True access[y][x - 1] = True if x + 1 < len(board[0]) and access[y][x + 1]: if board[y][x + 1] == word[0]: access[y][x + 1] = False if self.search(x + 1, y, board, word[1:], access): return True access[y][x + 1] = True if y - 1 >= 0 and access[y - 1][x]: if board[y - 1][x] == word[0]: access[y - 1][x] = False if self.search(x, y - 1, board, word[1:], access): return True access[y - 1][x] = True if y + 1 < len(board) and access[y + 1][x]: if board[y + 1][x] == word[0]: access[y + 1][x] = False if self.search(x, y + 1, board, word[1:], access): return True access[y + 1][x] = True return False # @lc code=end
[ "shun.sato1@gmail.com" ]
shun.sato1@gmail.com