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
9d4454002e2b83e56c9791cf28829e4f3702a52a
cb2b2758e5f65a1b318843f8bf16bf02cdbe67dd
/manage.py
050aeee7cfed219edf2c6027c103aa15d22993f8
[ "MIT" ]
permissive
Jasonmes/information
a5812d1a155a7cecea57681d5eead326123150bf
ab957fefe4c6be6eb1bba236293856aec3078373
refs/heads/master
2020-03-27T04:38:07.278558
2018-08-28T09:49:10
2018-08-28T09:49:10
145,956,493
0
0
null
null
null
null
UTF-8
Python
false
false
1,207
py
#!/usr/bin/env python # -*- coding:utf-8 -*- # Jason Mess from flask import Flask, session, current_app from flask_script import Manager from info import create_app, db from flask_migrate import Migrate, MigrateCommand import logging """ 单一职责的原则:manage.py 仅仅作为项目启动文件 整体业务逻辑都在info那里 """ """ 7: 创建manager管理类 """ app = create_app("development") manager = Manager(app) """ 初始化迁移对象 将迁移命令添加到管理对象中 """ Migrate(app, db) manager.add_command("db", MigrateCommand) @app.route('/') def hello_world(): """ session调整存储方式 没有调整之前,数据存在flask后端服务器,只是将session_id使用cookie的方式给了客户端 :return: """ session['name'] = "curry" return 'Hello World' if __name__ == '__main__': """ python manage.py runserver -h -p -d """ logging.debug("debug的信息") logging.info("info的信息") logging.warning("debug的信息") logging.error("errord的日志信息") logging.critical("erro的日志信息") # current_app.logger.info('使用current_app封装好的info的信息') manager.run()
[ "wow336@163.com" ]
wow336@163.com
56d438382f8e777dc47bfb62c93cfec05b656a75
7c887d87c5b588e5ca4c1bbdc9be29975c6ce6c3
/packages/pyright-internal/src/tests/samples/classes5.py
465aabe84f9fd0ce61c7e8e588ca191a9efe3983
[ "MIT", "LicenseRef-scancode-generic-cla" ]
permissive
hotchpotch/pyright
affebef139eb1538c089ef590eb703f357a30fc7
029eb2c869a27a82a2b0533a3ffa642ddbfcdb5d
refs/heads/main
2023-05-15T18:07:39.834121
2021-06-07T20:36:14
2021-06-07T20:36:14
374,815,948
0
0
NOASSERTION
2021-06-07T22:28:23
2021-06-07T22:28:23
null
UTF-8
Python
false
false
1,752
py
# This sample tests the reportIncompatibleVariableOverride # configuration option. from typing import ClassVar, List, Union class ParentClass: cv1: ClassVar[int] = 0 cv2: ClassVar[int] = 0 cv3: ClassVar[int] = 0 var1: int var2: str var3: Union[int, str] var4: int var5: int var6: int var7: List[float] var8: List[int] var9: int _var1: int __var1: int def __init__(self): self.var10: int = 0 self.var11: int = 0 self.var12 = 0 class Subclass(ParentClass): # This should generate an error cv1 = "" # This should generate an error cv2: int = 3 cv3 = 3 # This should generate an error because the type is incompatible. var1: str var2: str var3: int # This should generate an error because the type is incompatible. var4 = "" var5 = 5 # This should generate an error because a property cannot override # a variable. @property def var6(self) -> int: return 3 # This should not generate an error because the inherited (expected) # type of var7 is List[float], so the expression "[3, 4, 5]" should # be inferred as List[float] rather than List[int]. var7 = [3, 4, 5] # This should generate an error because floats are not allowed # in a List[int]. var8 = [3.3, 45.6, 5.9] # This should generate an error var9: ClassVar[int] = 3 # This should generate an error _var1: str # This should not generate an error because it's a private name __var1: str def __init__(self): # This should generate an error self.var10: str = "" # This should generate an error self.var11 = "" self.var12 = ""
[ "erictr@microsoft.com" ]
erictr@microsoft.com
82710855ba149a3231142417cade08c631c43e08
ee4c4c2cc6c663d4233d8145b01ae9eb4fdeb6c0
/configs/DOTA2.0/r2cnn_kl/cfgs_res50_dota2.0_r2cnn_kl_v1.py
15a15502bc9c65486dcf8e626242bb3b93d8c93c
[ "Apache-2.0" ]
permissive
yangcyz/RotationDetection
c86f40f0be1142c30671d4fed91446aa01ee31c1
82706f4c4297c39a6824b9b53a55226998fcd2b2
refs/heads/main
2023-09-01T23:25:31.956004
2021-11-23T13:57:31
2021-11-23T13:57:31
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,986
py
# -*- coding: utf-8 -*- from __future__ import division, print_function, absolute_import import numpy as np from configs._base_.models.faster_rcnn_r50_fpn import * from configs._base_.datasets.dota_detection import * from configs._base_.schedules.schedule_1x import * from alpharotate.utils.pretrain_zoo import PretrainModelZoo # schedule BATCH_SIZE = 1 GPU_GROUP = "0,1,2" NUM_GPU = len(GPU_GROUP.strip().split(',')) LR = 0.001 * BATCH_SIZE * NUM_GPU SAVE_WEIGHTS_INTE = 40000 DECAY_STEP = np.array(DECAY_EPOCH, np.int32) * SAVE_WEIGHTS_INTE MAX_ITERATION = SAVE_WEIGHTS_INTE * MAX_EPOCH WARM_SETP = int(WARM_EPOCH * SAVE_WEIGHTS_INTE) # dataset DATASET_NAME = 'DOTA2.0' CLASS_NUM = 18 # model # backbone pretrain_zoo = PretrainModelZoo() PRETRAINED_CKPT = pretrain_zoo.pretrain_weight_path(NET_NAME, ROOT_PATH) TRAINED_CKPT = os.path.join(ROOT_PATH, 'output/trained_weights') # loss FAST_RCNN_LOCATION_LOSS_WEIGHT = 1.0 FAST_RCNN_CLASSIFICATION_LOSS_WEIGHT = 1.0 KL_TAU = 1.0 KL_FUNC = 1 # 0: sqrt 1: log VERSION = 'FPN_Res50D_DOTA2.0_KL_1x_20210706' """ R2CNN + KLD FLOPs: 1024596018; Trainable params: 41791132 This is your evaluation result for task 1: mAP: 0.5130343218305747 ap of each class: plane:0.7931025663005032, baseball-diamond:0.5208521894104177, bridge:0.4260398742124911, ground-track-field:0.6068816448736972, small-vehicle:0.6464805846084523, large-vehicle:0.5293451363632599, ship:0.6712595590592587, tennis-court:0.7707340150177826, basketball-court:0.6059072889368493, storage-tank:0.7363532565264833, soccer-ball-field:0.39126720255687775, roundabout:0.5596715552728614, harbor:0.4521895092950472, swimming-pool:0.6260269795369416, helicopter:0.5238555951624132, container-crane:0.01386748844375963, airport:0.23016168047650185, helipad:0.13062166689674687 The submitted information is : Description: FPN_Res50D_DOTA2.0_KL_1x_20210706_52w Username: sjtu-deter Institute: SJTU Emailadress: yangxue-2019-sjtu@sjtu.edu.cn TeamMembers: yangxue """
[ "yangxue0827@126.com" ]
yangxue0827@126.com
2f0b7a2ff65a9cedb6488f844f7b6af481bd1f86
36957a9ce540846d08f151b6a2c2d582cff1df47
/VR/Python/Python36/Lib/test/subprocessdata/qcat.py
08b715cce136d5cb5d87d847dfe7e42128d26fa9
[]
no_license
aqp1234/gitVR
60fc952307ef413e396d31e0d136faffe087ed2b
e70bd82c451943c2966b8ad1bee620a0ee1080d2
refs/heads/master
2022-12-29T15:30:12.540947
2020-10-07T15:26:32
2020-10-07T15:26:32
290,163,043
0
1
null
2020-08-25T09:15:40
2020-08-25T08:47:36
C#
UTF-8
Python
false
false
128
py
version https://git-lfs.github.com/spec/v1 oid sha256:039d2c9d75ec2406b56f5a3cc4e693bb8b671f4a515136536c61884e863c62a7 size 166
[ "aqp1234@naver.com" ]
aqp1234@naver.com
db3c3596f6e08896aba7e3e05d54cb730a85b14c
6872c96481007db3e1b3c8c13fcb2b7f5b2aaf31
/cauldron/writer.py
d02da8aa5263b448a607e891ad1b3f7887ffcfe0
[ "MIT" ]
permissive
larsrinn/cauldron
f88014ba9619e028b3d12e5a538f59817fb5ceb1
d3cb0e1d9b699d2d297471c2e0eb38c87892e5d6
refs/heads/master
2021-06-18T08:45:29.673525
2017-06-25T14:14:28
2017-06-25T14:14:28
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,374
py
import json import time import typing def attempt_file_write( path: str, contents, mode: str ) -> typing.Union[None, Exception]: """ """ try: with open(path, mode) as f: f.write(contents) except Exception as error: return error return None def write_file( path: str, contents, mode: str = 'w', retry_count: int = 3 ) -> typing.Tuple[bool, typing.Union[None, Exception]]: """ """ error = None for i in range(retry_count): error = attempt_file_write(path, contents, mode) if error is None: return True, None time.sleep(0.2) return False, error def attempt_json_write( path: str, contents, mode: str ) -> typing.Union[None, Exception]: """ """ try: with open(path, mode) as f: json.dump(contents, f) except Exception as error: return error return None def write_json_file( path: str, contents, mode: str = 'w', retry_count: int = 3 ) -> typing.Tuple[bool, typing.Union[None, Exception]]: """ """ error = None for i in range(retry_count): error = attempt_json_write(path, contents, mode) if error is None: return True, None time.sleep(0.2) return False, error
[ "swernst@gmail.com" ]
swernst@gmail.com
26a19509bceef8c2c749b2333e9561a1c8149aa4
c17c0731b4ec9350aed6f85de6198c5f89e65f32
/clif/pybind11/function.py
3f41a01a5daa245d8bea66394fca594f562e3407
[ "Apache-2.0" ]
permissive
scal444/clif
1608ac9eaf7ef63c1b480e12d2ae153e7e27190b
702aa147ecbf1ae3720d650f7dbf53ccb2e9308e
refs/heads/main
2023-04-17T03:20:56.453967
2021-04-16T17:27:47
2021-04-17T11:25:23
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,630
py
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Generates pybind11 bindings code for functions.""" import re from typing import Sequence, Text, Optional from clif.protos import ast_pb2 from clif.pybind11 import lambdas from clif.pybind11 import operators from clif.pybind11 import utils I = utils.I def generate_from(module_name: str, func_decl: ast_pb2.FuncDecl, class_decl: Optional[ast_pb2.ClassDecl]): """Generates pybind11 bindings code for functions. Args: module_name: String containing the superclass name. func_decl: Function declaration in proto format. class_decl: Outer class declaration in proto format. None if the function is not a member of a class. Yields: pybind11 function bindings code. """ lambda_generated = False for s in lambdas.generate_lambda(func_decl, module_name, class_decl): yield s if s: lambda_generated = True if lambda_generated: return if func_decl.classmethod: for line in _generate_static_method(module_name, func_decl.name.native, func_decl.name.cpp_name): yield I + line return operator_index = utils.find_operator(func_decl.name.cpp_name) if operator_index >= 0 and utils.is_special_operation(func_decl.name.native): for s in operators.generate_operator(module_name, func_decl, operator_index): yield I + s return func_name = utils.format_func_name(func_decl.name.native) func_def = I + f'{module_name}.def("{func_name}", ' func_def += _generate_cpp_function_cast(func_decl, class_decl) func_def += f'&{func_decl.name.cpp_name}' if func_decl.params: func_def += _generate_params_list(func_decl.params, func_decl.is_extend_method) func_def += f', {_generate_return_value_policy(func_decl)}' if func_decl.docstring: func_def += f', {_generate_docstring(func_decl.docstring)}' func_def += ');' yield func_def def _generate_cpp_function_cast(func_decl: ast_pb2.FuncDecl, class_decl: Optional[ast_pb2.ClassDecl]): """Generates a method signature for each function. Args: func_decl: Function declaration in proto format. class_decl: Outer class declaration in proto format. None if the function is not a member of a class. Returns: The signature of the function. """ params_list_types = [] for param in func_decl.params: if param.HasField('cpp_exact_type'): if not utils.is_usable_cpp_exact_type(param.cpp_exact_type): params_list_types.append(param.type.cpp_type) else: params_list_types.append(param.cpp_exact_type) params_str_types = ', '.join(params_list_types) return_type = '' if func_decl.cpp_void_return: return_type = 'void' elif func_decl.returns: for v in func_decl.returns: # There can be only one returns declaration per function. if v.HasField('cpp_exact_type'): return_type = v.cpp_exact_type if not return_type: return_type = 'void' class_sig = '' if class_decl and not (func_decl.cpp_opfunction or func_decl.is_extend_method): class_sig = f'{class_decl.name.cpp_name}::' if func_decl.postproc == '->self' and func_decl.ignore_return_value: return_type = class_decl.name.cpp_name cpp_const = '' if func_decl.cpp_const_method: cpp_const = ' const' return (f'\n{I + I}({return_type} ({class_sig}*)' f'\n{I + I}({params_str_types}){cpp_const})' f'\n{I + I}') def _generate_params_list(params: Sequence[ast_pb2.ParamDecl], is_extend_method: bool) -> Text: """Generates bindings code for function parameters.""" params_list = [] for i, param in enumerate(params): cpp_name = param.name.cpp_name if cpp_name == 'this' or (i == 0 and is_extend_method): continue if param.default_value: params_list.append(f'py::arg("{cpp_name}") = {param.default_value}') else: params_list.append(f'py::arg("{cpp_name}")') if params_list: return ', ' + ', '.join(params_list) return '' def _generate_docstring(docstring: Text): if docstring: docstring = docstring.strip().replace('\n', r'\n').replace('"', r'\"') return f'"{docstring}"' return '""' def _generate_static_method(class_name: str, func_name_native: str, func_name_cpp_name: str): yield (f'{class_name}.def_static("{func_name_native}", ' f'&{func_name_cpp_name});') def _generate_return_value_policy(func_decl: ast_pb2.FuncDecl) -> Text: """Generates pybind11 return value policy based on function return type. Emulates the behavior of the generated Python C API code. Args: func_decl: The function declaration that needs to be processed. Returns: pybind11 return value policy based on the function return value. """ prefix = 'py::return_value_policy::' if func_decl.cpp_void_return or not func_decl.returns: return prefix + 'automatic' return_type = func_decl.returns[0] # For smart pointers, it is unncessary to specify a return value policy in # pybind11. if re.match('::std::unique_ptr<.*>', return_type.cpp_exact_type): return prefix + 'automatic' elif re.match('::std::shared_ptr<.*>', return_type.cpp_exact_type): return prefix + 'automatic' elif return_type.type.cpp_raw_pointer: # Const pointers to uncopyable object are not supported by PyCLIF. if return_type.cpp_exact_type.startswith('const '): return prefix + 'copy' else: return prefix + 'reference' elif return_type.cpp_exact_type.endswith('&'): if return_type.cpp_exact_type.startswith('const '): return prefix + 'copy' elif return_type.type.cpp_movable: return prefix + 'move' else: return prefix + 'automatic' else: # Function returns objects directly. if return_type.type.cpp_movable: return prefix + 'move' elif return_type.type.cpp_copyable: return prefix + 'copy' return prefix + 'automatic'
[ "rwgk@google.com" ]
rwgk@google.com
736adf23b6814571c24569110b8100e919416a54
e251c6226c9779a735d2b10fcea64d76f7baa9d6
/ingest/video.py
2469c7d4b9b798294a544bf81fa450a97cde19f0
[ "MIT" ]
permissive
digideskio/okavango
2533beb0a8e277ddb0aca66c28d61b9917f6839f
d32fd7eb98128e825be01fd6b9991767d9c2b761
refs/heads/master
2021-01-21T08:55:20.584357
2016-04-17T23:51:09
2016-04-17T23:51:09
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,096
py
import time, json from tornado import gen, web from housepy import log, util, config, strings from ingest import save_files """Expecting JSON or form metadata with Member and a timestamp in UTC""" def parse(request): log.info("video.parse") paths = save_files(request) if not len(paths): return None, "No files" # process the json data = None for path in paths: if path[-4:] == "json": try: with open(path) as f: data = json.loads(f.read()) except Exception as e: log.error(log.exc(e)) return None, "Could not parse" break if data is None: return None, "No data" # process the video for path in paths: if path[-4:] != "json": break if 'TeamMember' in data: data['Member'] = data['TeamMember'] del data['TeamMember'] data['Title'] = strings.titlecase(data['Title']) data['UploadPath'] = path.split('/')[-1] data['YouTubeURL'] = None return data
[ "brian.house@gmail.com" ]
brian.house@gmail.com
de4d680a9e930a0fe11304f64b046f1245a2784d
ec00584ab288267a7cf46c5cd4f76bbec1c70a6b
/__Python/__Data structure/__dictionary/dict test password check.py
0f94392c128ce6a8575d6d0179ee41144d42f789
[]
no_license
rahuldbhadange/Python
b4cc806ff23953389c9507f43d817b3815260e19
7e162117f1acc12537c7eeb36d6983d804122ff3
refs/heads/master
2021-06-23T05:04:20.053777
2020-01-28T10:34:28
2020-01-28T10:34:28
217,307,612
0
0
null
2021-06-10T22:44:11
2019-10-24T13:35:42
Python
UTF-8
Python
false
false
402
py
USER_DATA = {"ioticuser": "ioticpassword"} def verify(username, password): print(USER_DATA) print(username, password) if not (username and password): return "empty" return USER_DATA.get(username) == password try: print(verify()) except AttributeError: print("AttributeError") except KeyError: print("KeyError") except Exception as Ex: print("{}".format(Ex))
[ "external.RahulDilip.Bhadange@rbeibsx.onmicrosoft.com" ]
external.RahulDilip.Bhadange@rbeibsx.onmicrosoft.com
0cfd51e47344f0ef742982ad0445672aa79c9546
8734caf837ccc831b877ae10d45dff97ae435816
/00.EXAMS/24March2019/Problem 1. Build a building.py
a0c643d07929000e9d8aed8e19b4162f3e693edd
[]
no_license
VLD62/PythonFundamentals
e86dd4f635a5862bdfaad2c24d5b22985ab25e0f
914b541a71941efbf2c78ed1dfc49b6b9b850bb5
refs/heads/master
2020-06-03T19:36:26.244234
2019-08-17T14:57:22
2019-08-17T14:57:22
191,704,231
0
1
null
null
null
null
UTF-8
Python
false
false
488
py
if __name__ == "__main__": budget = float(input()) m = float(input()) n = int(input()) for i in range (0,n): current_money = float(input()) print(f'Investor {i+1} gave us {current_money:.2f}.') m += current_money if m >= budget: print(f'We will manage to build it. Start now! Extra money - {m - budget:.2f}.') exit(0) if m < budget: print(f'Project can not start. We need {budget - m:.2f} more.')
[ "viliev2@dxc.com" ]
viliev2@dxc.com
6a669815afdf97fa1f041c036326d20036da620e
c9642233f1de71f1a61ae28c695c2d9228825156
/echecs_espoir/service/mahjong/models/hutype/one/lianliu.py
e141fe1ac60718ab1c3b8459d3fbb935497a664f
[ "AFL-3.0" ]
permissive
obespoir/echecs
d8314cffa85c8dce316d40e3e713615e9b237648
e4bb8be1d360b6c568725aee4dfe4c037a855a49
refs/heads/master
2022-12-11T04:04:40.021535
2020-03-29T06:58:25
2020-03-29T06:58:25
249,185,889
16
9
null
null
null
null
UTF-8
Python
false
false
2,473
py
# coding=utf-8 import time from service.mahjong.models.hutype.basetype import BaseType from service.mahjong.constants.carddefine import CardType, CARD_SIZE from service.mahjong.models.card.hand_card import HandCard from service.mahjong.models.utils.cardanalyse import CardAnalyse class LianLiu(BaseType): """ 2) 连六:胡牌时,手上有6张序数相连的顺子。(123,456) """ def __init__(self): super(LianLiu, self).__init__() def is_this_type(self, hand_card, card_analyse): used_card_type = [CardType.WAN] # 此游戏中使用的花色 # # 4,5,6 至少有一张 # for t in CardType.all_type(): # if t in used_card_type: # for i in range(CARD_SIZE[t]): # if i in [4, 5, 6]: # count = hand_card.union_card_info[t][i] # if count == 0: # return False st = time.time() j, s, k = card_analyse.get_jiang_ke_shun(hand_card.hand_card_vals) print("took =", time.time()- st) if hand_card.chi_card_vals: s.extend(hand_card.chi_card_vals) if len(s) < 2: return False s.sort() print("s=", s) for i in range(len(s)): shun = s[i] for c in range(i + 1, len(s)): if shun[-1]+1 == s[c][0]: return True return False if __name__ == "__main__": pass card_analyse = CardAnalyse() hand_card = HandCard(0) # hand_card.hand_card_info = { # 1: [9, 1, 1, 1, 1, 1, 1, 1, 1, 1], # 万 # 2: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # 条 # 3: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # 饼 # 4: [2, 2, 0, 0, 0], # 风 # 5: [3, 3, 0, 0], # 箭 # } hand_card.hand_card_info = { 1: [6, 0, 0, 0, 1, 1, 1, 1, 1, 1], # 万 2: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # 条 3: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # 饼 4: [2, 2, 0, 0, 0], # 风 5: [3, 3, 0, 0], # 箭 } hand_card.chi_card_vals=[[23,24,25]] hand_card.handle_hand_card_for_settle_show() hand_card.union_hand_card() print("hand_card =", hand_card.hand_card_vals) test_type = LianLiu() start_time = time.time() print(test_type.is_this_type(hand_card, card_analyse)) print("time = ", time.time() - start_time)
[ "jamonhe1990@gmail.com" ]
jamonhe1990@gmail.com
dd86050790213200d401833149e1c343805eb8be
772f8f0a197b736cba22627485ccbdb65ed45e4b
/day03/position_func.py
270d7882a9e4112edd82471539de701354b3274e
[]
no_license
zhpg/python1805
ddc69cd1b3bda8bef1cb0c2913d456ea2c29a391
3d98c8ebc106fd0aab633a4c99ae6591013e4438
refs/heads/master
2020-03-26T11:26:59.378511
2018-08-05T09:25:21
2018-08-05T09:25:21
null
0
0
null
null
null
null
UTF-8
Python
false
false
716
py
#!/usr/bin/env python3 # -*- coding:utf-8 -*- import sys #source_fname = '/bin/ls' #dst_fname = '/tmp/list' def copy_func(source_fname,dst_fname): with open(source_fname,'rb') as src_fobj: with open(dst_fname,'wb') as dst_fobj: while True: data = src_fobj.read(4096) if not data: break else: dst_fobj.write(data) return "ok" if __name__ == '__main__': #source_fname = input('please input source file name:') #dst_fname = input('please input destination file name:') status = copy_func(sys.argv[1],sys.argv[2]) #位置参数 print(status) #用法 position.py /root/ks /tmp/ks
[ "root@room9pc01.tedu.cn" ]
root@room9pc01.tedu.cn
c6589b176aa1ed8216a32701aaf899ee17584d9a
5922398212b6e113f416a54d37c2765d7d119bb0
/python/Left Pad.py
6b44f0b9b59873f2f9020934585bec963bde7a68
[]
no_license
CrazyCoder4Carrot/lintcode
e777f73e1fdfe3b8abc9dbfc07d26602bf614151
33dcd7f0e2d9bee58840a3370837cb2db82de1eb
refs/heads/master
2021-01-09T20:38:59.813198
2017-01-16T22:34:26
2017-01-16T22:34:26
60,287,619
1
0
null
null
null
null
UTF-8
Python
false
false
431
py
class StringUtils: # @param {string} originalStr the string we want to append to # @param {int} size the target length of the string # @param {string} padChar the character to pad to the left side of the string # @return {string} a string @classmethod def leftPad(self, originalStr, size, padChar=' '): # Write your code here return padChar * (size - len(originalStr)) + originalStr
[ "liuzhenbang1988@gmail.com" ]
liuzhenbang1988@gmail.com
3c9cd4e675f6c5673c40d885805d7b5155d271ec
d3caa06cfce6251d2e17588d1c6f7f401889b0dc
/android-app-security-detector/detector/ad/permission/predict.py
b3b38a73ad7bc422e15402a558e53f5b185daff6
[]
no_license
wangtianqi1993/Android-App-Security-ML
8470ca40346f9d778db5d02f81fddec757b2c125
55e2c52ab25e2f7c8087dcf043e4f37338ec9ed3
refs/heads/master
2021-01-23T12:11:14.345713
2016-06-09T08:42:21
2016-06-09T08:42:21
60,760,087
2
1
null
null
null
null
UTF-8
Python
false
false
4,551
py
# !/usr/bin/env python # -*- coding: utf-8 -*- import os import numpy from androguard.core import androconf from androguard.core.bytecodes import apk from sklearn.externals import joblib from sklearn.ensemble import RandomForestClassifier from sklearn.naive_bayes import BernoulliNB from sklearn.naive_bayes import GaussianNB from sklearn.naive_bayes import MultinomialNB from sklearn.svm import SVC from detector.config import CLASSIFIER_PATH from detector.config import TRAIN_PERMISSION from detector.error import AdDetectorException from detector.logger import AdDetectorLogger from .base import BasePermission logger = AdDetectorLogger() class AdBasePredict(BasePermission): predictor = None def __init__(self): super(AdBasePredict, self).__init__() if self.predictor is None: raise AdDetectorException('You must init an predictor' ' using an method!') # init predictor trained_permissions = self.session.query_sort(TRAIN_PERMISSION, 'create', limit=1) permission_list = trained_permissions['train-permission'] self.stand_permissions = self.get_standard_permission_from_mongodb() train_vector = [] all_train_permissions = permission_list[0] for _permission in all_train_permissions: _vector = self.create_permission_vector( self.stand_permissions, _permission) train_vector.append(_vector) sample_x = train_vector sample_y = numpy.array(permission_list[1]) self.predictor.fit(sample_x, sample_y) def predict_ad_classifier(self, classifier_name, apk_path): """ :param classifier_name: the classifier name :param apk_path: a apk path that you want to detector :return: 1->content ad 0->not contentad """ # 加载训练好的分类器 clf = joblib.load(CLASSIFIER_PATH + classifier_name + ".m") # clf, train_id = self.train_classifier(clf, classifier_name) stand_permissions = self.get_standard_permission_from_mongodb() ret_type = androconf.is_android(apk_path) if ret_type == "APK": try: a = apk.APK(apk_path) if a.is_valid_APK(): predict_permission = self.create_permission_vector( stand_permissions, self.get_permission_from_apk(a)) logger.info(os.path.basename(apk_path) + ' classified as: ') logger.info(clf.predict(predict_permission)) return clf.predict(predict_permission)[0] else: logger.info("INVALID") except Exception, e: logger.info(e) else: logger.info("is not a apk!!!") def predict(self, apk_path): # if apk_path is APK ret_type = androconf.is_android(apk_path) if ret_type == "APK": try: a = apk.APK(apk_path) if a.is_valid_APK(): apk_permissions = self.get_permission_from_apk(a) predict_vector = self.create_permission_vector( self.stand_permissions, apk_permissions) return self.predictor.predict([predict_vector]) else: logger.info("INVALID") raise AdDetectorException('There is not a valid apk!!!') except Exception, e: logger.info(e.message) else: logger.info("There is not a apk!!!") raise AdDetectorException('There is not a apk!!!') class AdGaussianPredict(AdBasePredict): def __init__(self): self.predictor = GaussianNB() super(AdGaussianPredict, self).__init__() class AdBernoulliPredict(AdBasePredict): def __init__(self): self.predictor = BernoulliNB() super(AdBernoulliPredict, self).__init__() class AdMultinomialPredict(AdBasePredict): def __init__(self): self.predictor = MultinomialNB() super(AdMultinomialPredict, self).__init__() class AdSVMPredict(AdBasePredict): def __init__(self): self.predictor = SVC() super(AdSVMPredict, self).__init__() class AdRandomForestPredict(AdBasePredict): def __init__(self, n_estimators=20): self.predictor = RandomForestClassifier(n_estimators=n_estimators) super(AdRandomForestPredict, self).__init__()
[ "1906272972@qq.com" ]
1906272972@qq.com
288a7e3b57ee900ae1738a7ae195cb43ccd3a5a3
3d19e1a316de4d6d96471c64332fff7acfaf1308
/Users/A/aviv/hukuman_teroris.py
13e1a5422fceffbd49721049d19b9b3e11718359
[]
no_license
BerilBBJ/scraperwiki-scraper-vault
4e98837ac3b1cc3a3edb01b8954ed00f341c8fcc
65ea6a943cc348a9caf3782b900b36446f7e137d
refs/heads/master
2021-12-02T23:55:58.481210
2013-09-30T17:02:59
2013-09-30T17:02:59
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,432
py
import scraperwiki import simplejson # retrieve a page base_url = 'http://search.twitter.com/search.json?q=' q = 'hukuman_teroris' options = '&rpp=1000&page=' page = 1 while 1: try: url = base_url + q + options + str(page) html = scraperwiki.scrape(url) #print html soup = simplejson.loads(html) for result in soup['results']: data = {} data['id'] = result['id'] data['text'] = result['text'] data['from_user'] = result['from_user'] # save records to the datastore scraperwiki.datastore.save(["id"], data) page = page + 1 except: print str(page) + ' pages scraped' breakimport scraperwiki import simplejson # retrieve a page base_url = 'http://search.twitter.com/search.json?q=' q = 'hukuman_teroris' options = '&rpp=1000&page=' page = 1 while 1: try: url = base_url + q + options + str(page) html = scraperwiki.scrape(url) #print html soup = simplejson.loads(html) for result in soup['results']: data = {} data['id'] = result['id'] data['text'] = result['text'] data['from_user'] = result['from_user'] # save records to the datastore scraperwiki.datastore.save(["id"], data) page = page + 1 except: print str(page) + ' pages scraped' break
[ "pallih@kaninka.net" ]
pallih@kaninka.net
43375659771617d2e6f263eb37c8e459a47c43ce
6fc108af0e197f664d545acf770dba0d8e84174c
/Eve/train.py
37bb683f5b87397409cefbe8c7cbf4815be0f6ce
[]
no_license
luotongml/DeepLearningImplementations
c2c4e900ffa19955c9d1667fb6797e19a53f9b4a
69c776662a176ac6518b981d503606ad0b66296c
refs/heads/master
2021-01-09T23:37:08.204057
2016-11-08T07:12:09
2016-11-08T07:12:09
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,179
py
import os import json import models import numpy as np from keras.utils import np_utils from keras.datasets import cifar10, cifar100, mnist from keras.optimizers import Adam, SGD from Eve import Eve def train(model_name, **kwargs): """ Train model args: model_name (str, keras model name) **kwargs (dict) keyword arguments that specify the model hyperparameters """ # Roll out the parameters batch_size = kwargs["batch_size"] nb_epoch = kwargs["nb_epoch"] dataset = kwargs["dataset"] optimizer = kwargs["optimizer"] experiment_name = kwargs["experiment_name"] # Compile model. if optimizer == "SGD": opt = SGD(lr=1E-3, decay=0, momentum=0.9, nesterov=True) if optimizer == "Adam": opt = Adam(lr=1E-3, beta_1=0.9, beta_2=0.999, epsilon=1e-08) if optimizer == "Eve": opt = Eve(lr=1E-3, beta_1=0.9, beta_2=0.999, beta_3=0.999, small_k=0.1, big_K=10, epsilon=1e-08) if dataset == "cifar10": (X_train, y_train), (X_test, y_test) = cifar10.load_data() if dataset == "cifar100": (X_train, y_train), (X_test, y_test) = cifar100.load_data() if dataset == "mnist": (X_train, y_train), (X_test, y_test) = mnist.load_data() X_train = X_train.reshape((X_train.shape[0], 1, 28, 28)) X_test = X_test.reshape((X_test.shape[0], 1, 28, 28)) X_train = X_train.astype('float32') X_test = X_test.astype('float32') X_train /= 255. X_test /= 255. img_dim = X_train.shape[-3:] nb_classes = len(np.unique(y_train)) # convert class vectors to binary class matrices Y_train = np_utils.to_categorical(y_train, nb_classes) Y_test = np_utils.to_categorical(y_test, nb_classes) # Compile model model = models.load(model_name, img_dim, nb_classes) model.compile(optimizer=opt, loss="categorical_crossentropy", metrics=["accuracy"]) train_losses, train_accs = [], [] val_losses, val_accs = [], [] for e in range(nb_epoch): loss = model.fit(X_train, Y_train, batch_size=batch_size, validation_data=(X_test, Y_test), nb_epoch=1) train_losses.append(loss.history["loss"]) val_losses.append(loss.history["val_loss"]) train_accs.append(loss.history["acc"]) val_accs.append(loss.history["val_acc"]) # Save experimental log d_log = {} d_log["experiment_name"] = experiment_name d_log["img_dim"] = img_dim d_log["batch_size"] = batch_size d_log["nb_epoch"] = nb_epoch d_log["train_losses"] = train_losses d_log["val_losses"] = val_losses d_log["train_accs"] = train_accs d_log["val_accs"] = val_accs d_log["optimizer"] = opt.get_config() # Add model architecture json_string = json.loads(model.to_json()) for key in json_string.keys(): d_log[key] = json_string[key] json_file = os.path.join("log", '%s_%s_%s.json' % (dataset, model.name, experiment_name)) with open(json_file, 'w') as fp: json.dump(d_log, fp, indent=4, sort_keys=True)
[ "thibault.deboissiere@seeingmachines.com" ]
thibault.deboissiere@seeingmachines.com
a7ccf4436f941a504fa8624da2ac7866311de64d
08eef4241e62bcff651e3002fc0809fe50aaaee3
/supervised_learning/0x0A-object_detection/1-main.py
cd784f66a21d2d15109f2d0c8de32bc5ee59becf
[]
no_license
Gaspela/holbertonschool-machine_learning
c4e470fed0623a5ef1399125b9f17fd4ae5c577b
b0c18df889d8bd0c24d4bdbbd69be06bc5c0a918
refs/heads/master
2023-04-02T00:34:16.350074
2021-04-03T02:27:41
2021-04-03T02:27:41
275,862,706
0
0
null
null
null
null
UTF-8
Python
false
false
798
py
#!/usr/bin/env python3 if __name__ == '__main__': import numpy as np Yolo = __import__('1-yolo').Yolo np.random.seed(0) anchors = np.array([[[116, 90], [156, 198], [373, 326]], [[30, 61], [62, 45], [59, 119]], [[10, 13], [16, 30], [33, 23]]]) yolo = Yolo('../data/yolo.h5', '../data/coco_classes.txt', 0.6, 0.5, anchors) output1 = np.random.randn(13, 13, 3, 85) output2 = np.random.randn(26, 26, 3, 85) output3 = np.random.randn(52, 52, 3, 85) boxes, box_confidences, box_class_probs = yolo.process_outputs( [output1, output2, output3], np.array([500, 700])) print('Boxes:', boxes) print('Box confidences:', box_confidences) print('Box class probabilities:', box_class_probs)
[ "samirmillanorozco@hotmail.com" ]
samirmillanorozco@hotmail.com
1946e3e82bc870dc367c8d3b9b9c19536bb2aed4
75eef2ce83bd6dc5aa38e7df0f73c856200e11f4
/aula/variable.py
7bad9782cfa762920e1a7dfb21949823edd8d9a3
[]
no_license
jruizvar/jogos-data
c4e823da3c1b1e8abf379d82f9e852e0b9c89638
6ddadb2ce51d33bc0f1b8cf55ce73dba2ba3509e
refs/heads/master
2021-09-07T15:55:00.112934
2018-02-25T15:00:49
2018-02-25T15:00:49
110,839,946
3
2
null
null
null
null
UTF-8
Python
false
false
495
py
""" Variables in tensorflow """ import tensorflow as tf """ RANK 0 """ a = tf.Variable(4, name='a') b = tf.Variable(3, name='b') c = tf.add(a, b, name='c') print("Variables in TF\n") print(a) print(b) print(c) print() with tf.Session() as sess: sess.run(a.initializer) sess.run(b.initializer) a_val = a.eval() b_val = b.eval() c_val = c.eval() print("The value of a:", a_val) print("The value of b:", b_val) print("The value of c:", c_val) print()
[ "jruizvar@cern.ch" ]
jruizvar@cern.ch
6cf95ad22d81f8faaf4adf2d4173c99727421d9f
c071eb46184635818e8349ce9c2a78d6c6e460fc
/system/python_stubs/-745935208/PySide2/QtWidgets/QCalendarWidget.py
f4a24c43449f654fc79c74ae91f41946c62ea220
[]
no_license
sidbmw/PyCharm-Settings
a71bc594c83829a1522e215155686381b8ac5c6e
083f9fe945ee5358346e5d86b17130d521d1b954
refs/heads/master
2020-04-05T14:24:03.216082
2018-12-28T02:29:29
2018-12-28T02:29:29
156,927,399
0
0
null
null
null
null
UTF-8
Python
false
false
5,779
py
# encoding: utf-8 # module PySide2.QtWidgets # from C:\Users\siddh\AppData\Local\Programs\Python\Python37\lib\site-packages\PySide2\QtWidgets.pyd # by generator 1.146 # no doc # imports import PySide2.QtCore as __PySide2_QtCore import PySide2.QtGui as __PySide2_QtGui import Shiboken as __Shiboken from .QWidget import QWidget class QCalendarWidget(QWidget): # no doc def activated(self, *args, **kwargs): # real signature unknown pass def clicked(self, *args, **kwargs): # real signature unknown pass def currentPageChanged(self, *args, **kwargs): # real signature unknown pass def dateEditAcceptDelay(self, *args, **kwargs): # real signature unknown pass def dateTextFormat(self, *args, **kwargs): # real signature unknown pass def event(self, *args, **kwargs): # real signature unknown pass def eventFilter(self, *args, **kwargs): # real signature unknown pass def firstDayOfWeek(self, *args, **kwargs): # real signature unknown pass def headerTextFormat(self, *args, **kwargs): # real signature unknown pass def horizontalHeaderFormat(self, *args, **kwargs): # real signature unknown pass def isDateEditEnabled(self, *args, **kwargs): # real signature unknown pass def isGridVisible(self, *args, **kwargs): # real signature unknown pass def isNavigationBarVisible(self, *args, **kwargs): # real signature unknown pass def keyPressEvent(self, *args, **kwargs): # real signature unknown pass def maximumDate(self, *args, **kwargs): # real signature unknown pass def minimumDate(self, *args, **kwargs): # real signature unknown pass def minimumSizeHint(self, *args, **kwargs): # real signature unknown pass def monthShown(self, *args, **kwargs): # real signature unknown pass def mousePressEvent(self, *args, **kwargs): # real signature unknown pass def paintCell(self, *args, **kwargs): # real signature unknown pass def resizeEvent(self, *args, **kwargs): # real signature unknown pass def selectedDate(self, *args, **kwargs): # real signature unknown pass def selectionChanged(self, *args, **kwargs): # real signature unknown pass def selectionMode(self, *args, **kwargs): # real signature unknown pass def setCurrentPage(self, *args, **kwargs): # real signature unknown pass def setDateEditAcceptDelay(self, *args, **kwargs): # real signature unknown pass def setDateEditEnabled(self, *args, **kwargs): # real signature unknown pass def setDateRange(self, *args, **kwargs): # real signature unknown pass def setDateTextFormat(self, *args, **kwargs): # real signature unknown pass def setFirstDayOfWeek(self, *args, **kwargs): # real signature unknown pass def setGridVisible(self, *args, **kwargs): # real signature unknown pass def setHeaderTextFormat(self, *args, **kwargs): # real signature unknown pass def setHorizontalHeaderFormat(self, *args, **kwargs): # real signature unknown pass def setMaximumDate(self, *args, **kwargs): # real signature unknown pass def setMinimumDate(self, *args, **kwargs): # real signature unknown pass def setNavigationBarVisible(self, *args, **kwargs): # real signature unknown pass def setSelectedDate(self, *args, **kwargs): # real signature unknown pass def setSelectionMode(self, *args, **kwargs): # real signature unknown pass def setVerticalHeaderFormat(self, *args, **kwargs): # real signature unknown pass def setWeekdayTextFormat(self, *args, **kwargs): # real signature unknown pass def showNextMonth(self, *args, **kwargs): # real signature unknown pass def showNextYear(self, *args, **kwargs): # real signature unknown pass def showPreviousMonth(self, *args, **kwargs): # real signature unknown pass def showPreviousYear(self, *args, **kwargs): # real signature unknown pass def showSelectedDate(self, *args, **kwargs): # real signature unknown pass def showToday(self, *args, **kwargs): # real signature unknown pass def sizeHint(self, *args, **kwargs): # real signature unknown pass def updateCell(self, *args, **kwargs): # real signature unknown pass def updateCells(self, *args, **kwargs): # real signature unknown pass def verticalHeaderFormat(self, *args, **kwargs): # real signature unknown pass def weekdayTextFormat(self, *args, **kwargs): # real signature unknown pass def yearShown(self, *args, **kwargs): # real signature unknown pass def __init__(self, *args, **kwargs): # real signature unknown pass @staticmethod # known case of __new__ def __new__(*args, **kwargs): # real signature unknown """ Create and return a new object. See help(type) for accurate signature. """ pass HorizontalHeaderFormat = None # (!) real value is '' ISOWeekNumbers = None # (!) real value is '' LongDayNames = None # (!) real value is '' NoHorizontalHeader = None # (!) real value is '' NoSelection = None # (!) real value is '' NoVerticalHeader = None # (!) real value is '' SelectionMode = None # (!) real value is '' ShortDayNames = None # (!) real value is '' SingleLetterDayNames = None # (!) real value is '' SingleSelection = None # (!) real value is '' staticMetaObject = None # (!) real value is '' VerticalHeaderFormat = None # (!) real value is ''
[ "siddharthnatamai@gmail.com" ]
siddharthnatamai@gmail.com
4053affa8458c52070d22a986202bae49f8a2fa7
267f2c09420436e97275986f825045cbe81fd3ec
/buy & sell vinyl records 4.4.py
b69da4532a338e3942dd9f4bc3d3d8102bb2e731
[]
no_license
aiqbal-hhs/91906-7
f1ddc21846bee6dd9dcf4f75bdabe68989390769
8d6aadedff8c6585c204a256b5bd3ad8294a815f
refs/heads/main
2023-05-15T00:17:41.407536
2021-06-04T10:32:21
2021-06-04T10:32:21
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,087
py
from functools import partial from tkinter import * from tkinter import ttk import random root = Tk() blonde = 3 nectar = 6 flower_boy =12 ##########################################calution###################################################### def buy_stock(): global blonde, nectar, flower_boy vinyl = chosen_vinyl.get() mode = chosen_action.get() if vinyl == "blonde": if mode == "sell": blonde += amount.get() else: blonde -= amount.get() elif vinyl == "nectar": if mode == "sell": nectar += amount.get() else: nectar -= amount.get() elif vinyl == "flower boy": if mode == "sell": flower_boy += amount.get() else: flower_boy -= amount.get() vinyl_string = "blonde: ${:.2f}\nnectar: ${:.2f}\nflower boy: ${:.2f}".format(blonde, nectar, flower_boy) vinyl_details.set(vinyl_string) amount.set("") ##########################################buy frame###################################################### #formatting variables.... background_color = "orange" #buy frame buy_frame = Frame(root, width=360, height=180, bg="orange") buy_frame.grid(row = 0, column = 0) # buy title (row 0) buy_label = Label(buy_frame, text="Buy page", font=("Arial", "16", "bold"), bg=background_color, padx=10, pady=5) buy_label.grid(row=0, column=0) # buy heading (label, row 1) buy_heading = Label(buy_frame, text="Buy heading goes here", font=("Arial", "12"), bg=background_color, padx=10, pady=5) buy_heading.grid(row=1, column=0) # buy heading (label, row 2) buy_text = Label(buy_frame, text="this is where you buy vinyls", font="Arial 9 italic", wrap=250, justify=LEFT, bg=background_color, padx=10, pady=10) buy_text.grid(row=2, column=0) # Create a label for the account combobox vinyl_label = ttk.Label(buy_frame, text="Vinyl: ") vinyl_label.grid(row=3, column=1, padx=10, pady=3) # Set up a variable and option list for the account Combobox vinyl_names = ["blonde", "nectar", "flower boy"] chosen_vinyl = StringVar() chosen_vinyl.set(vinyl_names[0]) # Create a Combobox to select the account vinyl_box = ttk.Combobox(buy_frame, textvariable=chosen_vinyl, state="readonly") vinyl_box['values'] = vinyl_names vinyl_box.grid(row=3, column=2, padx=10, pady=3, sticky="WE") # Create a label for the action Combobox action_label = ttk.Label(buy_frame, text="Action:") action_label.grid(row=4, column=1) # Set up a variable and option list for the action Combobox action_list = ["buy", "sell"] chosen_action = StringVar() chosen_action.set(action_list[0]) # Create the Combobox to select the action action_box = ttk.Combobox(buy_frame, textvariable=chosen_action, state="readonly") action_box['values'] = action_list action_box.grid(row=4, column=2, padx=10, pady=3, sticky="WE") ##########################################sell frame###################################################### #formatting variables.... sell_background_color = "blue" #sell frame sell_frame = Frame(root, width=360, height=180, bg="blue") sell_frame.grid(row = 2, column = 0) # sell title (row 0) sell_label = Label(sell_frame, text="Stock page", font=("Arial", "16", "bold"), bg=sell_background_color, padx=10, pady=5) sell_label.grid(row=0, column=0) # Create and set the account details variable vinyl_details = StringVar() vinyl_details.set("Blonde: 0 \nNectar: 0\nFlower boy: 0") # Create the details label and pack it into the GUI vinyl_label = Label(sell_frame, textvariable=Vinyl_details) Vinyl_label.grid(row=2, column=0, columnspan=2, padx=10, pady=10) #main routine if __name__ == "__main__": root.title("Buy & Sell Vinyl Records") root.mainloop()
[ "noreply@github.com" ]
aiqbal-hhs.noreply@github.com
0fa0da872f8cfed15ebe40428ea26881b6a40365
f5134fd8fd9591ba86ac1e3585c6907db6711020
/european_lobbyists.py
e4240122cef33aa677b77e90912b38ff28472278
[]
no_license
shivswami/Scraperwiki-scrapers
87fe03563ba7ef78c238acbf85ac6ca0bf131fac
65d79bfbc2ec279107d872c03ea4d12bc2b39174
refs/heads/master
2020-12-11T07:53:55.543349
2012-05-09T00:08:35
2012-05-09T00:08:35
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,606
py
import scraperwiki,re #from lxml import etree import lxml.html import time import datetime # Scrapes the registry of European lobbyists: http://europa.eu/transparency-register/index_en.htm baseurl = 'http://ec.europa.eu/transparencyregister/public/consultation/listlobbyists.do?alphabetName=' urllist = ['LatinAlphabet', 'BulgarianAlphabet', 'GreekAlphabet'] def start_again(): #drop runtime_info table to start again scraperwiki.sqlite.execute("drop table if exists runtime_info") for l in urllist: url = baseurl + l html = scraperwiki.scrape(url) root = lxml.html.fromstring(html) results = root.xpath('//p/a/.') for r in results: record = {} record['letter'] = r.text.strip() record['last_page'] = '1' record ['done'] = 0 scraperwiki.sqlite.save(['letter'], data=record, table_name='runtime_info') def scrape(letter,page): url = 'http://ec.europa.eu/transparencyregister/public/consultation/listlobbyists.do?letter='+str(letter.encode('utf-8'))+'&d-7641134-p='+str(page) html = scraperwiki.scrape(url) root = lxml.html.fromstring(html) # //tbody/tr/. results = root.xpath('//tbody/tr/.') if results: print 'processing results for ' + str(letter.encode('utf-8')) + ' page ' + str(page) for m in results: record = {} record['id_nr'] = m[0].text_content() record['name'] = m[1].text_content() record['detail_url'] = 'http://ec.europa.eu/' + m[2][0].get('href') #print record scraperwiki.sqlite.save(['id_nr'], data=record, table_name='european_lobbyists') next = root.xpath('//span[@class="pagelinks"]/a/img[@alt="Next"]') if next: print "there are more results - let's process (last page done was: " + str(page) + " of letter: "+ letter +" )" # update last page done update_statement= 'update runtime_info SET last_page=' + str(page) + ' WHERE letter='+ '"' + letter+ '"' scraperwiki.sqlite.execute(update_statement) scraperwiki.sqlite.commit() page = int(page)+1 # scrape next page scrape(letter,page) else: print 'Last page of results - Done with letter: ' + letter #update last page and done field update_statement= 'update runtime_info SET last_page=' + str(page) + ', done=1 WHERE letter='+ '"' + letter+ '"' scraperwiki.sqlite.execute(update_statement) scraperwiki.sqlite.commit() else: print 'No results - Done with letter: ' + str(letter.encode('utf-8')) # update last page and done field update_statement= 'update runtime_info SET last_page=' + str(page) + ', done=1 WHERE letter='+ '"' + letter+ '"' scraperwiki.sqlite.execute(update_statement) scraperwiki.sqlite.commit() def run(): for letters in letters_todo: letter=letters['letter'] page=letters['last_page'] scrape(letter,page) selection_statement = '* from runtime_info where done=0' letters_todo = scraperwiki.sqlite.select(selection_statement) if letters_todo: todo_list = [] for letters in letters_todo: letter=letters['letter'] todo_list.append(letter) #print ",".join(str(states_todo) print 'there are ', len(todo_list), ' letters left to do - lets get going!' run() else: print 'there are no letters left to do - now we drop the runtime_info table and start all over again' start_again() run()
[ "pallih@kaninka.net" ]
pallih@kaninka.net
aa928668b4039eff8719e93dfcf66d7051eef8ae
c486ba03781686f6e1a29a193c9db58083895d2e
/63_367_1.py
279020345eb5ff86fd5c1f4883ee5d5c86c510b8
[]
no_license
ywtail/leetcode
dcd32faf4772d597d8af9b9ff50b4c370d7fb97d
2ad1f0e7589e3f5c92af9151c3318d360108df9d
refs/heads/master
2021-01-12T16:25:17.247136
2019-01-26T17:17:04
2019-01-26T17:17:04
71,991,978
3
0
null
null
null
null
UTF-8
Python
false
false
755
py
# coding:utf-8 # 367. Valid Perfect Square 有效的完美平方 # 56ms beats 18.34% class Solution(object): def isPerfectSquare(self, num): """ :type num: int :rtype: bool """ i = 1 while num > 0: num -= i i += 2 return num == 0 solution = Solution() print solution.isPerfectSquare(16) # True print solution.isPerfectSquare(8) # False ''' 题目: 给定一个正整数num,写一个函数返回True,如果num是一个完美的平方,否则返回False。 注意:不要使用任何内置的库函数,如sqrt。 示例1: 输入:16 返回值:True 示例2: 输入:14 返回:False 分析: 因为平方数 x = 1 + 3 + 5 + 7 + 9 + 11 + 13 + ... '''
[ "ywtail@gmail.com" ]
ywtail@gmail.com
02d3e13051d067620e74d3528947f305121b6be5
8151d8f9a2ca56a4d8fce502fdb50f13117d57b0
/movie/migrations/0001_initial.py
411302a4dc20a907b80293bc9390d9ec537d3e46
[]
no_license
jessi0701/watcha
d9ed289350fa94cfaf3870a5dbb7f38adac01ece
44d87aa422ed827dea35a81f36e5418cee46a6f7
refs/heads/master
2020-04-22T03:38:17.544181
2019-02-11T08:38:32
2019-02-11T08:38:32
170,094,792
0
0
null
null
null
null
UTF-8
Python
false
false
935
py
# Generated by Django 2.1.5 on 2019-02-11 02:10 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Movie', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=100)), ('title_en', models.CharField(max_length=100)), ('audience', models.IntegerField()), ('open_date', models.DateField()), ('genre', models.CharField(max_length=100)), ('watch_grade', models.CharField(max_length=100)), ('score', models.FloatField()), ('poster_url', models.TextField()), ('description', models.TextField()), ], ), ]
[ "jessi0701@naver.com" ]
jessi0701@naver.com
ea42e6291b646d9117a24bbc13a07aa9a32487e3
8170f2672288c2964059ffc1de1bb4b96ab241fe
/core/src/cgcloud/fabric/operations.py
29696dc868ec44b09774f4d950f77fb4901fbcb1
[ "Apache-2.0" ]
permissive
hschmidt/cgcloud
be0e1549d741f7dadbd79e57a416b7283cb1479a
528082dd512d67f211bf52cd792e439756ce4e3f
refs/heads/master
2020-06-28T06:05:55.925278
2016-11-18T19:12:18
2016-11-18T19:12:18
74,506,485
1
0
null
2016-11-22T19:32:58
2016-11-22T19:32:58
null
UTF-8
Python
false
false
7,796
py
import os import sys import time from StringIO import StringIO from contextlib import contextmanager from fcntl import fcntl, F_GETFL, F_SETFL from pipes import quote from threading import Thread from bd2k.util.expando import Expando from bd2k.util.iterables import concat from bd2k.util.strings import interpolate as fmt from fabric.operations import sudo as real_sudo, get, put, run from fabric.state import env import fabric.io import fabric.operations def sudo( command, sudo_args=None, **kwargs ): """ Work around https://github.com/fabric/fabric/issues/503 """ if sudo_args is not None: old_prefix = env.sudo_prefix env.sudo_prefix = '%s %s' % (old_prefix, sudo_args) try: return real_sudo( command, **kwargs ) finally: if sudo_args is not None: env.sudo_prefix = old_prefix def runv( *args, **kwargs ): run( command=join_argv( args ), **kwargs ) def sudov( *args, **kwargs ): sudo( command=join_argv( args ), **kwargs ) def pip( args, path='pip', use_sudo=False ): """ Run pip. :param args: a string or sequence of strings to be passed to pip as command line arguments. If given a sequence of strings, its elements will be quoted if necessary and joined with a single space in between. :param path: the path to pip :param use_sudo: whther to run pip as sudo """ if isinstance( args, (str, unicode) ): command = path + ' ' + args else: command = join_argv( concat( path, args ) ) # Disable pseudo terminal creation to prevent pip from spamming output with progress bar. kwargs = Expando( pty=False ) if use_sudo: f = sudo # Set HOME so pip's cache doesn't go into real user's home, potentially creating files # not owned by that user (older versions of pip) or printing a warning about caching # being disabled. kwargs.sudo_args = '-H' else: f = run f( command, **kwargs ) def join_argv( command ): return ' '.join( map( quote, command ) ) def virtualenv( name, distributions=None, pip_distribution='pip', executable=None ): """ Installs a set of distributions (aka PyPI packages) into a virtualenv under /opt and optionally links an executable from that virtualenv into /usr/loca/bin. :param name: the name of the directory under /opt that will hold the virtualenv :param distributions: a list of distributions to be installed into the virtualenv. Defaults to [ name ]. You can also list other "pip install" options, like --pre. :param pip_distribution: if non-empty, the distribution and optional version spec to upgrade pip to. Defaults to the latest version of pip. Set to empty string to prevent pip from being upgraded. Downgrades from the system-wide pip version currently don't work. :param executable: The name of an executable in the virtualenv's bin directory that should be symlinked into /usr/local/bin. The executable must be provided by the distributions that are installed in the virtualenv. """ # FIXME: consider --no-pip and easy_installing pip to support downgrades if distributions is None: distributions = [ name ] venv = '/opt/' + name admin = run( 'whoami' ) sudo( fmt( 'mkdir -p {venv}' ) ) sudo( fmt( 'chown {admin}:{admin} {venv}' ) ) try: run( fmt( 'virtualenv {venv}' ) ) if pip_distribution: pip( path=venv + '/bin/pip', args=[ 'install', '--upgrade', pip_distribution ] ) pip( path=venv + '/bin/pip', args=concat( 'install', distributions ) ) finally: sudo( fmt( 'chown -R root:root {venv}' ) ) if executable: sudo( fmt( 'ln -snf {venv}/bin/{executable} /usr/local/bin/' ) ) @contextmanager def remote_open( remote_path, use_sudo=False ): """ Equivalent of open( remote_path, "a+" ) as if run on the remote system """ buf = StringIO( ) get( remote_path=remote_path, local_path=buf ) yield buf buf.seek( 0 ) put( local_path=buf, remote_path=remote_path, use_sudo=use_sudo ) # noinspection PyPep8Naming class remote_popen( object ): """ A context manager that yields a file handle and a >>> from fabric.context_managers import hide, settings >>> with settings(host_string='localhost'): ... with hide( 'output' ): ... # Disable shell since it may print additional stuff to console ... with remote_popen( 'sort -n', shell=False ) as f: ... f.write( '\\n'.join( map( str, [ 3, 2, 1] ) ) ) [localhost] run: sort -n 3 2 1 Above is the echoed input, below the sorted output. >>> print f.result 1 2 3 """ def __init__( self, *args, **kwargs ): try: if kwargs[ 'pty' ]: raise RuntimeError( "The 'pty' keyword argument must be omitted or set to False" ) except KeyError: kwargs[ 'pty' ] = False self.args = args self.kwargs = kwargs # FIXME: Eliminate this buffer and have caller write directly into the pipe self.stdin = StringIO( ) self.stdin.result = None def __enter__( self ): return self.stdin def __exit__( self, exc_type, exc_val, exc_tb ): if exc_type is None: _r, _w = os.pipe( ) def copy( ): with os.fdopen( _w, 'w' ) as w: w.write( self.stdin.getvalue( ) ) t = Thread( target=copy ) t.start( ) try: _stdin = sys.stdin.fileno( ) _old_stdin = os.dup( _stdin ) os.close( _stdin ) assert _stdin == os.dup( _r ) # monkey-patch Fabric _input_loop = fabric.operations.input_loop fabric.operations.input_loop = input_loop try: self.stdin.result = self._run( ) finally: fabric.operations.input_loop = _input_loop os.close( _stdin ) os.dup( _old_stdin ) finally: t.join( ) return False def _run( self ): return run( *self.args, **self.kwargs ) # noinspection PyPep8Naming class remote_sudo_popen( remote_popen ): def _run( self ): sudo( *self.args, **self.kwargs ) # Version of Fabric's input_loop that handles EOF on stdin and reads more greedily with # non-blocking mode. # TODO: We should open a ticket for this. from select import select from fabric.network import ssh def input_loop( chan, using_pty ): opts = fcntl( sys.stdin.fileno( ), F_GETFL ) fcntl( sys.stdin.fileno( ), F_SETFL, opts | os.O_NONBLOCK ) try: while not chan.exit_status_ready( ): r, w, x = select( [ sys.stdin ], [ ], [ ], 0.0 ) have_char = (r and r[ 0 ] == sys.stdin) if have_char and chan.input_enabled: # Send all local stdin to remote end's stdin bytes = sys.stdin.read( ) if bytes is None: pass elif not bytes: chan.shutdown_write( ) break else: chan.sendall( bytes ) # Optionally echo locally, if needed. if not using_pty and env.echo_stdin: # Not using fastprint() here -- it prints as 'user' # output level, don't want it to be accidentally hidden sys.stdout.write( bytes ) sys.stdout.flush( ) time.sleep( ssh.io_sleep ) finally: fcntl( sys.stdin.fileno( ), F_SETFL, opts )
[ "hannes@ucsc.edu" ]
hannes@ucsc.edu
069b5e6f87c762349b10e840290f0cc3eecde14c
da29f1f5b4459fbfec968bb694bedb9586f87b14
/new_algs/Numerical+algorithms/Spigot+algorithm/spigot_pi.py
dc161520ec1b495e2b2d14284dd1479e6a15a953
[]
no_license
coolsnake/JupyterNotebook
547806a45a663f090f313dc3e70f779ad9b213c0
20d8df6172906337f81583dabb841d66b8f31857
refs/heads/master
2023-01-13T18:55:38.615312
2020-11-17T22:55:12
2020-11-17T22:55:12
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,284
py
import sys # base 10000 pi spigot algorithm # # translated from C: # http://stackoverflow.com/questions/4084571/implementing-the-spigot-algorithm-for-%CF%80-pi # # // Spigot program for pi to NDIGITS decimals. # // 4 digits per loop. # // Thanks to Dik T. Winter and Achim Flammenkamp who originally made a compressed version of this. # def verify(digits_of_pi, N): from hashlib import sha1 first_100 = ( '31415926535897932384' '62643383279502884197' '16939937510582097494' '45923078164062862089' '98628034825342117067' ) # sha1 hashes of the first n digits of pi from # https://www.angio.net/pi/digits.html v = dict() v[1000] = 'a03730e0b961b25376bb0623a6569d61af301161' v[ 500] = 'c09d63fcaae39f2a53e3f7425b36f47e7060da86' v[ 100] = '756f5c5d68d87ef466dd656922d8562c7a499921' def _hash_verify(D, dop=digits_of_pi): b = bytes(dop[0:D], 'utf-8') assert sha1(b).hexdigest() == v[D] print('** Verified first {} digits of pi'.format(D), file=sys.stderr) def _startswith_verify(D, dop=digits_of_pi): assert first_100.startswith(dop) print('** Verified first {} digits of pi'.format(D), file=sys.stderr) if N >= 1000: _hash_verify(1000) elif N >= 500: _hash_verify(500) elif N >= 100: _hash_verify(100) else: _startswith_verify(N) # The below is more or less a straight word-for-word translation from C. It's not pretty. # # I'm not really clear on the big O but it looks like N**2. 1M digits takes a really long time. # # TODO: # # * Needs real variable names (requires better understanding of the math) # * More explicit loop control (requires loop refactoring, which requires better understanding) # # * The magic numbers are: # 10000, base of the numbers generated # 2000, pi is 22222222... in the algorithms "native" base, not sure about the factor 1k # 14, related to log2(base) # 4, number of characters per base 10000 digit # Once I understand the math better I could come up with names for the magic numbers # # * For extra points, I could use cython to speed things up a bit # def pi_spigot_base10k(N): alen = int((N / 4 + 1) * 14) a = [ 0 ] * alen c = len(a) d = 0 e = 0 f = 10000 h = 0 while True: c -= 14 b = c if b > 0: while True: b -= 1 if b > 0: d *= b if h == 0: d += 2000*f else: d += a[b]*f g = b + b - 1 a[b] = d % g d //= g else: break h = str(e + d//f).zfill(4) yield h e = d % f d = e else: break if __name__ == '__main__': try: N = int(sys.argv[1]) except (IndexError, ValueError): N = 100 assert N > 3 # algorith breaks down for fewer than 4 digits digits_of_pi = (''.join(pi_spigot_base10k(N)))[0:N] print(digits_of_pi) verify(digits_of_pi, N)
[ "chenqh@uci.edu" ]
chenqh@uci.edu
3829f8bd800b15109f115213f746707864db6e02
987d9e7dd105fa69c4e8f4437aee87fc3a3076ce
/dj_file_async/users/migrations/0001_initial.py
403cd2f2368340498ec3cea223f0d02fd525b081
[]
no_license
CuriousLearner/dj-file-async
87e8f44c7afe90b4203c5a3cee8ea8d81f40ad0c
43ce0f9011cd0ce822f24f9ebf9e8160cd9187bd
refs/heads/master
2021-06-12T11:01:30.229841
2019-06-17T12:06:04
2019-06-17T12:06:04
192,339,091
1
0
null
2021-05-27T13:44:44
2019-06-17T12:04:16
Python
UTF-8
Python
false
false
2,610
py
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-02-23 11:13 # Standard Library import uuid # Third Party Stuff import django.utils.timezone from django.db import migrations, models # dj-file-async Stuff import dj_file_async.users.models class Migration(migrations.Migration): dependencies = [ ('auth', '0007_alter_validators_add_error_messages'), ] operations = [ migrations.CreateModel( name='User', fields=[ ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('first_name', models.CharField(blank=True, max_length=120, verbose_name='First Name')), ('last_name', models.CharField(blank=True, max_length=120, verbose_name='Last Name')), ('email', models.EmailField(db_index=True, max_length=254, unique=True, verbose_name='email address')), ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')), ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')), ], options={ 'verbose_name_plural': 'users', 'verbose_name': 'user', 'ordering': ('-date_joined',), }, managers=[ ('objects', dj_file_async.users.models.UserManager()), ], ), ]
[ "sanyam.khurana01@gmail.com" ]
sanyam.khurana01@gmail.com
3e4568bdf21076949534d011c6bd8987522f94fc
208d90e62d59f680db0ba76513cf2409b8521263
/datasets/github/api.py
6b564d83735bea1e616cfb829d929cb85a92173c
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
ChrisCummins/photolib
930b7c1dfb6bb2a04592b1e01e8ce41f15304ef2
a0592482317ef8c27676efe1c43452af5cd65106
refs/heads/master
2020-07-09T14:25:10.582105
2019-08-23T19:04:48
2019-08-23T19:04:48
122,436,150
0
0
null
null
null
null
UTF-8
Python
false
false
5,786
py
# Copyright 2018, 2019 Chris Cummins <chrisc.101@gmail.com>. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A utility module for creating GitHub API connections. If writing code that requires connecting to GitHub, use the GetGithubConectionFromFlagsOrDie() function defined in this module. Don't write your own credentials handling code. """ import configparser import github import pathlib import socket import subprocess from datasets.github import github_pb2 from labm8 import app FLAGS = app.FLAGS app.DEFINE_string( 'github_access_token', None, 'Github access token. See <https://github.com/settings/tokens> to ' 'generate an access token.') app.DEFINE_string('github_access_token_path', '/var/phd/github_access_token.txt', 'Path to a file containing a github access token.') app.DEFINE_string( 'github_credentials_path', '~/.githubrc', 'The path to a file containing GitHub login credentials. See ' '//datasets/github/scrape_repos/README.md for details.') def ReadGitHubCredentials(path: pathlib.Path) -> github_pb2.GitHubCredentials: """Read user GitHub credentials from the local file system. Returns: A GitHubCredentials instance. """ cfg = configparser.ConfigParser() cfg.read(path) credentials = github_pb2.GitHubCredentials() credentials.username = cfg["User"]["Username"] credentials.password = cfg["User"]["Password"] return credentials def GetGithubConectionFromFlagsOrDie() -> github.Github: """Get a GitHub API connection or die. First, it attempts to connect using the --github_access_token flag. If that flag is not set, then the contents of --github_access_token_path are used. If that file does not exist, --github_credentials_path is read. Returns: A PyGithub Github instance. """ try: if FLAGS.github_access_token: return github.Github(FLAGS.github_access_token) elif pathlib.Path(FLAGS.github_access_token_path).is_file(): with open(FLAGS.github_access_token_path) as f: access_token = f.read().strip() return github.Github(access_token) else: app.Warning("Using insecure --github_credentials_path to read GitHub " "credentials. Please use token based credentials flags " "--github_access_token or --github_access_token_path.") github_credentials_path = pathlib.Path( FLAGS.github_credentials_path).expanduser() if not github_credentials_path.is_file(): app.FatalWithoutStackTrace('Github credentials file not found: %s', github_credentials_path) credentials = ReadGitHubCredentials(github_credentials_path.expanduser()) return github.Github(credentials.username, credentials.password) except Exception as e: # Deliberately broad catch-all. app.FatalWithoutStackTrace('Failed to create GitHub API connection: %s', e) class RepoNotFoundError(ValueError): """Error thrown if a github repo is not found.""" pass def GetUserRepo(connection: github.Github, repo_name: str) -> github.Repository: """Get and return a github repository owned by the user. Args: connection: A github API connection. repo_name: The name of the repo to get. """ try: return connection.get_user().get_repo(repo_name) except socket.gaierror as e: raise OSError(f"Connection failed with error: {e}") except github.UnknownObjectException as e: if e.status != 404: raise OSError(f"Github API raised error: {e}") raise RepoNotFoundError(f"Github repo `{repo_name}` not found") def GetOrCreateUserRepo(connection: github.Github, repo_name: str, description: str = None, homepage: str = None, has_wiki: bool = True, has_issues: bool = True, private: bool = True) -> github.Repository: """Get and return a github repository owned by the user. Create it if it doesn't exist. Args: connection: A github API connection. repo_name: The name of the repo to get. description: The repo description. homepage: The repo homepage. has_wiki: Whether the repo has a wiki. has_issues: Whether the repo has an issue tracker. private: Whether the repo is private. """ try: return GetUserRepo(connection, repo_name) except RepoNotFoundError: app.Log(1, "Creating repo %s", repo_name) connection.get_user().create_repo(repo_name, description=description, homepage=homepage, has_wiki=has_wiki, has_issues=has_issues, private=private) return GetUserRepo(connection, repo_name) class RepoCloneFailed(OSError): """Error raised if repo fails to clone.""" pass def CloneRepoToDestination(repo: github.Repository, destination: pathlib.Path): """Clone repo from github.""" subprocess.check_call(['git', 'clone', repo.ssh_url, str(destination)]) if not (destination / '.git').is_dir(): raise RepoCloneFailed( f"Cloned repo `{repo.ssh_url}` but `{destination}/.git` not found")
[ "chrisc.101@gmail.com" ]
chrisc.101@gmail.com
b58582f3df8782810013326ff895cc96a40dfa6b
3044d26f03f23e8e8c5fcec57b78bfffe0fa0bd3
/case/ProductCombination_BatchEditing.py
929cc92648b3f376215fb072105210659cb88844
[]
no_license
tian848-tim/trunk
de50a153c8cab3c81c79c523256a6f1b4c2f049d
cd52afdd003f094056dc2ea877c823a38e6a26fd
refs/heads/master
2022-11-20T06:43:35.540105
2020-07-20T07:48:26
2020-07-20T07:48:26
281,048,661
0
0
null
null
null
null
UTF-8
Python
false
false
7,722
py
''' 测试用例标题:产品组合关系测试 测试场景:产品组合关系业务流程测试 创建者:Tim 创建日期:2018-11-20 最后修改日期:2018-11-20 输入数据:审批流程各个角色账号 输出数据:无 ''' # -*- coding: utf-8 -*- import sys,os curPath = os.path.abspath(os.path.dirname(__file__)) rootPath = os.path.split(curPath)[0] #sys.path.append(rootPath) import unittest from cgitb import text import selenium.webdriver.support.ui as ui from selenium import webdriver from time import sleep from selenium.webdriver.remote.webelement import WebElement from selenium.webdriver.common.action_chains import ActionChains import time,unittest,configparser from selenium import webdriver from selenium.common.exceptions import NoAlertPresentException from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait import random import json ''' 加载配置选项 ''' cfg = configparser.ConfigParser() cfg.read(rootPath + '/core/config.ini') ''' 测试用例 ''' class VendorCategory(unittest.TestCase): base_url = cfg.get("projects", "base_url") project_path = cfg.get("projects", "project_path") log_path = cfg.get("webdriver", "log") + '/' + cfg.get("webdriver", "logfile") + '-%s.log' % time.strftime("%Y-%m-%d %H_%M_%S") def loadvendername(self): global result file = open(rootPath + '/data/ProductCombination_BatchEditing.json', encoding='utf-8') data = json.load(file) result = [(d['username'], d['password']) for d in data['login']] return result def importFile(self): global results file = open(rootPath + '/data/ProductCombination_BatchEditing.json', encoding='utf-8') data = json.load(file) results = [(d['name']) for d in data['importFile']] return results def setUp(self): # 脚本标识-标题 self.script_name = '产品组合关系—批量编辑' # 脚本标识-ID self.script_id = 'ProductCombination_BatchEditing' self.target_url = self.base_url + self.project_path if (cfg.get("webdriver", "enabled") == "off"): # 如果使用最新firefox需要屏蔽下面这句 self.driver = webdriver.Firefox() else: # 如果使用最新firefox需要使用下面这句 self.driver = webdriver.Firefox(log_path=self.log_path) self.driver.maximize_window() # 定义登录方法 def login(self, username, password): self.driver.get(self.target_url) # 登录页面 self.driver.find_element_by_id('account-inputEl').send_keys(username) self.driver.find_element_by_id('password-inputEl').send_keys(password) self.driver.find_element_by_xpath("//*[@id='LoginWin']//span[contains(@class,'x-btn-icon-el')]").click() def test_vendorcategory(self): su = self.loadvendername() qw = self.importFile() for i in range(0, len(su)): print(su[i][0]) print(su[i][1]) self.login(su[0][0], su[0][1]) # self.login('Vic_cn','123') sleep(5) try: self.driver.find_element_by_xpath("//*[@id='msgwin-div']//div[contains(@class,'x-tool-close')]").is_displayed() a = True except: a = False if a == True: print("元素存在") elif a == False: print("元素不存在") print(a) if a == True: # 关闭弹出框 self.driver.find_element_by_xpath("//*[@id='msgwin-div']//div[contains(@class,'x-tool-close')]").click() else: pass sleep(2) # 定位到资料档案 self.driver.find_element_by_xpath("//*[@id='header-topnav']//span[contains(@class,'fa-file-o')]").click() sleep(3) # 定位到产品档案 self.driver.find_element_by_xpath("//*[@id='west-panel-body']//span[contains(text(),'产品资料')]").click() sleep(3) # 定位到产品组合关系 self.driver.find_element_by_xpath("//*[@id='west-panel-targetEl']//span[contains(text(),'产品组合关系')]").click() sleep(3) # 定位到产品组合关系批量编辑 self.driver.find_element_by_xpath("//*[@id='ProductCombinationView']//span[@class='x-btn-icon-el fa fa-fw fa-pencil-square ']").click() sleep(3) # 定位到数据文件 self.driver.find_element_by_xpath("//*[@id='ProductSpecialityNotifiedFormWinID-body']//input[@name='main.importFile']").click() sleep(3) # 定位到文件选择器 self.driver.find_element_by_xpath("//*[@id='FilesDialogWinID-body']//input[@name='keywords']").send_keys(qw[0]) sleep(3) # 定位到查询 self.driver.find_element_by_xpath("//*[@id='FilesDialogWinID-body']//span[contains(@class,'fa-search')]").click() sleep(2) _elementFirst = self.driver.find_element_by_xpath("//*[@id='FilesDialogWinGridPanelID-body']//div[contains(text(), '1')]") sleep(1) # 在此元素上双击 ActionChains(self.driver).double_click(_elementFirst).perform() sleep(3) # 定位到确认 self.driver.find_element_by_xpath("//*[@id='ProductSpecialityNotifiedFormWinID']//span[contains(@class,'fa-save')]").click() sleep(2) self.driver.find_element_by_xpath("//*[@id='DataImportGridPanelID-body']//div[contains(text(), '1')]").click() sleep(2) self.driver.find_element_by_xpath("//*[@id='DataImportView']//span[contains(@class, 'fa-file-text-o')]").click() sleep(2) self.driver.find_element_by_link_text('是').click() try: WebDriverWait(self.driver,120).until( EC.visibility_of_element_located((By.CSS_SELECTOR, '.x-box-mc')) ) except IOError as a: print("找不元素 " + a) # 获取弹窗提示: # self.driver.implicitly_wait(10) a = self.driver.find_element_by_css_selector('.x-box-mc').get_attribute('textContent') print(a) sleep(2) self.driver.find_element_by_xpath("//*[@id='DataImportGridPanelID-body']//div[contains(text(), '1')]").click() sleep(2) ul = self.driver.find_elements_by_xpath("//*[@id='DataImportFormPanelID-v-body']//td[contains(@class, 'x-form-display-field-body')]")[9] print(ul.text) sleep(3) # 点击注销 self.driver.find_element_by_link_text('注销').click() self.driver.find_element_by_link_text('是').click() alert = self.driver.switch_to_alert() alert.accept() # 退出页面 def tearDown(self): self.driver.quit() def is_element_present(self, how, what): try: self.driver.find_element(by=how, value=what) except NoSuchElementException as e: return False return True def is_alert_present(self): try: self.driver.switch_to_alert() except NoAlertPresentException as e: return False return True def close_alert_and_get_its_text(self): try: alert = self.driver.switch_to_alert() alert_text = alert.text if self.accept_next_alert: alert.accept() else: alert.dismiss() return alert_text finally: self.accept_next_alert = True if __name__ == "__main__": unittest.main()
[ "tim.long@Newaim01.com" ]
tim.long@Newaim01.com
f4432cd1d8bf424e8ef954d35490f721b7ae780f
fcdfe976c9ed60b18def889692a17dc18a8dd6d7
/ros/py_ros/motoman/dummy_moto2.py
e7ed6746830ffd9242f3320e52d2bab45fa1454d
[]
no_license
akihikoy/ay_test
4907470889c9bda11cdc84e8231ef3156fda8bd7
a24dfb720960bfedb94be3b4d147e37616e7f39a
refs/heads/master
2023-09-02T19:24:47.832392
2023-08-27T06:45:20
2023-08-27T06:45:20
181,903,332
6
3
null
null
null
null
UTF-8
Python
false
false
3,099
py
#!/usr/bin/python #\file dummy_moto2.py #\brief Dummy motoman robot. # This subscribes joint_path_command and send joint_states. # The trajectory is interpolated with a spline. #\author Akihiko Yamaguchi, info@akihikoy.net #\version 0.1 #\date Nov.10, 2017 import roslib; roslib.load_manifest('motoman_driver') roslib.load_manifest('sensor_msgs') import rospy import sensor_msgs.msg import trajectory_msgs.msg import threading, copy from cubic_hermite_spline import TCubicHermiteSpline class TRobotDummyMoto(object): def __init__(self): self.rate= 100 #/joint_states is published at 100 Hz self.pub_js= rospy.Publisher('/joint_states', sensor_msgs.msg.JointState, queue_size=1) self.sub_jpc= rospy.Subscriber('/joint_path_command', trajectory_msgs.msg.JointTrajectory, self.PathCmdCallback) self.js= sensor_msgs.msg.JointState() self.js.name= rospy.get_param('controller_joint_names') self.js.header.seq= 0 self.js.header.frame_id= '' self.js.position= [0.0]*7 self.js.velocity= [0.0]*7 self.js.effort= [0.0]*7 self.js_locker= threading.RLock() self.th_sendst= threading.Thread(name='SendStates', target=self.SendStates) self.th_sendst.start() self.th_follow_traj= None self.follow_traj_active= False def SendStates(self): rate= rospy.Rate(self.rate) while not rospy.is_shutdown(): with self.js_locker: self.js.header.seq= self.js.header.seq+1 self.js.header.stamp= rospy.Time.now() #print self.js.position self.pub_js.publish(self.js) rate.sleep() def PathCmdCallback(self, msg): if self.follow_traj_active: self.follow_traj_active= False self.th_follow_traj.join() self.follow_traj_active= True self.th_follow_traj= threading.Thread(name='FollowTraj', target=lambda:self.FollowTraj(msg)) self.th_follow_traj.start() def FollowTraj(self, traj): q_traj= [p.positions for p in traj.points] dq_traj= [p.velocities for p in traj.points] t_traj= [p.time_from_start for p in traj.points] #If no initial point: if t_traj[0].to_sec()>1.0e-3: q_traj= [self.js.position]+q_traj dq_traj= [self.js.velocity]+dq_traj t_traj= [rospy.Duration(0.0)]+t_traj print 'Received trajectory command:' print [t.to_sec() for t in t_traj] print q_traj #Modeling the trajectory with spline. splines= [TCubicHermiteSpline() for d in range(7)] for d in range(len(splines)): data_d= [[t.to_sec(),q[d]] for q,t in zip(q_traj,t_traj)] splines[d].Initialize(data_d, tan_method=splines[d].CARDINAL, c=0.0, m=0.0) rate= rospy.Rate(self.rate) t0= rospy.Time.now() while all(((rospy.Time.now()-t0)<t_traj[-1], self.follow_traj_active, not rospy.is_shutdown())): t= (rospy.Time.now()-t0).to_sec() q= [splines[d].Evaluate(t) for d in range(7)] #print t, q with self.js_locker: self.js.position= copy.deepcopy(q) rate.sleep() if __name__=='__main__': rospy.init_node('dummy_motoman') robot= TRobotDummyMoto() rospy.spin()
[ "info@akihikoy.net" ]
info@akihikoy.net
1054685a0135c681596542b67284adff29b9764b
860b2541a2b2c39440711429357b63cbc521feed
/heaps/gfg-rearrange-chars.py
f29d087a8c2f8701ecb55b7bb833b81e54d4bc47
[]
no_license
lalit97/DSA
a870533f52eb9e002db683552ce77e41efcde6b2
e293004a4c2ca2d9040d939350cb6cb6f6ed2bd3
refs/heads/master
2022-02-09T01:36:08.166689
2022-02-02T14:45:40
2022-02-02T14:45:40
235,321,867
4
1
null
2022-02-02T14:45:41
2020-01-21T11:02:41
Python
UTF-8
Python
false
false
941
py
''' https://practice.geeksforgeeks.org/problems/rearrange-characters/0 https://leetcode.com/problems/reorganize-string/discuss/384051/easy-peasy-python-heap-priority-queue-(100) https://leetcode.com/problems/reorganize-string/discuss/456020/Python-Heap-Easy-to-understand-self-explanatory-code''' import heapq from collections import Counter def rearrange_chars(string): d = Counter(string) heap = [] for key, value in d.items(): heap.append((-value,key)) heapq.heapify(heap) result = '' prev = heapq.heappop(heap) result += prev[1] while heap: curr = heapq.heappop(heap) result += curr[1] if prev[0] + 1 < 0: heapq.heappush(heap,(prev[0]+1, prev[1])) prev = curr if len(result) != len(string): return 0 else: return 1 if __name__ == '__main__': for _ in range(int(input())): print(rearrange_chars(input()))
[ "sutharlalit.97@gmail.com" ]
sutharlalit.97@gmail.com
6a661fa71ac3508f04547229754a4b4d516b68d3
6c219c027c7d0ef454bdeac196bd773e8b95d602
/hardware/printer/printer_canon_unauth.py
5485cefdf9e6e75750648e250a7c8b332ec55174
[]
no_license
aStrowxyu/pocscan
663f3a3458140e1bce7b4dc3702c6014a4c9ac92
08c7e7454c6b7c601bc54c21172c4788312603b1
refs/heads/master
2020-04-19T10:00:56.569105
2019-01-29T09:31:31
2019-01-29T09:31:31
168,127,418
4
0
null
null
null
null
UTF-8
Python
false
false
1,321
py
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' name: 佳能打印机未授权漏洞 referer: http://www.wooyun.org/bugs/WooYun-2015-114364 author: Lucifer description: 佳能打印机未授权可远程打印。 ''' import sys import requests import warnings from termcolor import cprint class printer_canon_unauth_BaseVerify: def __init__(self, url): self.url = url def run(self): headers = { "Authorization":"Basic MTExMTE6eC1hZG1pbg==", "User-Agent":"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50" } payload = "/twelcome.cgi" vulnurl = self.url + payload try: req = requests.get(vulnurl, headers=headers, timeout=10, verify=False) if r"media/b_ok.gif" in req.text and r"_top.htm" in req.text: cprint("[+]存在佳能打印机未授权漏洞...(高危)\tpayload: "+vulnurl, "red") else: cprint("[-]不存在printer_canon_unauth漏洞", "white", "on_grey") except: cprint("[-] "+__file__+"====>可能不存在漏洞", "cyan") if __name__ == "__main__": warnings.filterwarnings("ignore") testVuln = printer_canon_unauth_BaseVerify(sys.argv[1]) testVuln.run()
[ "wangxinyu@vackbot.com" ]
wangxinyu@vackbot.com
2b18ca5eb036786c92f9b96924f1f5f95f0b4cae
b6abbba15aca653c98c1d37c364043219b1f6983
/examples/list_comprehension.py
4f0e3b437c021f5c22b642c5c059161a2c162c3d
[]
no_license
hazybluedot/ece2524_test
cab1fb8c6c6849195ac217f5e8f9d1ef4b6ca866
9cd00aa5da8adbdcdcb6ee8baa6582348d9d7857
refs/heads/master
2016-09-11T05:27:18.364851
2013-04-30T04:10:29
2013-04-30T04:10:29
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,000
py
#!/usr/bin/env python2 from sys import stdout,stderr from math import pi import re print "list comprehension" # list comprehension has a syntax similar to mathmatical set comprehension N=5 squares=[ x**2 for x in range(1,N+1) ] print "squares of natural numbers between 1 and {0}: {1}".format(N, squares) mylist = [ 'apple', 'orange', 'cat', 'hat', 'ece2524', '42', 'pie', 'pi', pi ] print "mylist: {0}".format(mylist) threes = [ item for item in mylist if re.match(r'^...$', str(item)) ] print "threes: {0}".format(threes) print "a numbered list:" numbered = [ "{0}. {1}\n".format(index, item) for index,item in enumerate(mylist) ] stdout.writelines(numbered) colors = [ "red", "blue", "green" ] things = [ "cat", "hat", "mat" ] colored_things = [ (c,t) for c in colors for t in things ] print "colored things: {0}".format(colored_things) colored_things3 = [ (c,t) for c in colors for t in things if len(c)+len(t) == 2*len(c) ] print "colored things with filter: {0}".format(colored_things3)
[ "dmaczka@vt.edu" ]
dmaczka@vt.edu
fb059288b905e95a3e1628af1ae630889f5ecca7
1e8d7f047efc9869f7d9a57b53b3ac71a8ad086c
/21天学通Python_源代码/C20/findfat6.py
a5a6c54e0c40fb57a9643b9cc9b320e55ea22ea0
[]
no_license
BrandonLau-liuyifei/liuyifei_sourse
c686776496fdccd89c8a28dbaba4b5f01c9ce013
cbf916289613cc1dcc2db452bc6f2c3f6185c5f2
refs/heads/master
2021-05-17T16:51:29.104546
2020-08-16T13:39:25
2020-08-16T13:39:25
250,880,982
0
1
null
2020-08-16T13:39:26
2020-03-28T19:53:13
Python
UTF-8
Python
false
false
8,930
py
#coding:utf-8 #file: findfat6.py import tkinter import tkinter.messagebox,tkinter.simpledialog import os,os.path import threading rubbishExt=['.tmp','.bak','.old','.wbk','.xlk','._mp','.log','.gid','.chk','.syd','.$$$','.@@@','.~*'] class Window: def __init__(self): self.root = tkinter.Tk() #创建菜单 menu = tkinter.Menu(self.root) #创建“系统”子菜单 submenu = tkinter.Menu(menu, tearoff=0) submenu.add_command(label="关于...",command = self.MenuAbout) submenu.add_separator() submenu.add_command(label="退出", command = self.MenuExit) menu.add_cascade(label="系统", menu=submenu) #创建“清理”子菜单 submenu = tkinter.Menu(menu, tearoff=0) submenu.add_command(label="扫描垃圾文件", command = self.MenuScanRubbish) submenu.add_command(label="删除垃圾文件", command = self.MenuDelRubbish) menu.add_cascade(label="清理", menu=submenu) #创建“查找”子菜单 submenu = tkinter.Menu(menu, tearoff=0) submenu.add_command(label="搜索大文件", command = self.MenuScanBigFile) submenu.add_separator() submenu.add_command(label="按名称搜索文件", command = self.MenuSearchFile) menu.add_cascade(label="搜索", menu=submenu) self.root.config(menu=menu) #创建标签,用于显示状态信息 self.progress = tkinter.Label(self.root,anchor = tkinter.W, text = '状态',bitmap = 'hourglass',compound = 'left') self.progress.place(x=10,y=370,width = 480,height = 15) #创建列表框,显示文件列表 self.flist = tkinter.Text(self.root) self.flist.place(x=10,y = 10,width = 480,height = 350) #为列表框添加垂直滚动条 self.vscroll = tkinter.Scrollbar(self.flist) self.vscroll.pack(side = 'right',fill = 'y') self.flist['yscrollcommand'] = self.vscroll.set self.vscroll['command'] = self.flist.yview #“关于”菜单 def MenuAbout(self): tkinter.messagebox.showinfo("Window“减肥”", "这是使用Python编写的Windows优化程序。\n欢迎使用并提出宝贵意见!") #"退出"菜单 def MenuExit(self): self.root.quit(); #"扫描垃圾文件"菜单 def MenuScanRubbish(self): result = tkinter.messagebox.askquestion("Window“减肥”","扫描垃圾文件将需要较长的时间,是否继续?") if result == 'no': return tkinter.messagebox.showinfo("Window“减肥”","马上开始扫描垃圾文件!") #self.ScanRubbish() self.drives =GetDrives() t=threading.Thread(target=self.ScanRubbish,args=(self.drives,)) t.start() #"删除垃圾文件"菜单 def MenuDelRubbish(self): result = tkinter.messagebox.askquestion("Window“减肥”","删除垃圾文件将需要较长的时间,是否继续?") if result == 'no': return tkinter.messagebox.showinfo("Window“减肥”","马上开始删除垃圾文件!") self.drives =GetDrives() t=threading.Thread(target=self.DeleteRubbish,args=(self.drives,)) t.start() #"搜索大文件"菜单 def MenuScanBigFile(self): s = tkinter.simpledialog.askinteger('Window“减肥”','请设置大文件的大小(M)') t=threading.Thread(target=self.ScanBigFile,args=(s,)) t.start() #"按名称搜索文件"菜单 def MenuSearchFile(self): result = tkinter.messagebox.askquestion("Window“减肥”","按名称搜索文件将需要较长的时间,是否继续?") if result == 'no': return tkinter.messagebox.showinfo("Window“减肥”","马上开始按名称搜索文件!") #扫描垃圾文件 def ScanRubbish(self,scanpath): global rubbishExt total = 0 filesize = 0 for drive in scanpath: for root,dirs,files in os.walk(drive): try: for fil in files: filesplit = os.path.splitext(fil) if filesplit[1] == '': #若文件无扩展名 continue try: if rubbishExt.index(filesplit[1]) >=0: #扩展名在垃圾文件扩展名列表中 fname = os.path.join(os.path.abspath(root),fil) filesize += os.path.getsize(fname) if total % 15 == 0: self.flist.delete(0.0,tkinter.END) l = len(fname) if l > 50: fname = name[:25] + '...' + fname[l-25:l] self.flist.insert(tkinter.END,fname + '\n') self.progress['text'] = fname total += 1 #计数 except ValueError: pass except Exception as e: print(e) pass self.progress['text'] = "找到 %s 个垃圾文件,共占用 %.2f M 磁盘空间" % (total,filesize/1024/1024) #删除垃圾文件 def DeleteRubbish(self,scanpath): global rubbishExt total = 0 filesize = 0 for drive in scanpath: for root,dirs,files in os.walk(drive): try: for fil in files: filesplit = os.path.splitext(fil) if filesplit[1] == '': #若文件无扩展名 continue try: if rubbishExt.index(filesplit[1]) >=0: #扩展名在垃圾文件扩展名列表中 fname = os.path.join(os.path.abspath(root),fil) filesize += os.path.getsize(fname) try: os.remove(fname) #删除文件 l = len(fname) if l > 50: fname = fname[:25] + '...' + fname[l-25:l] if total % 15 == 0: self.flist.delete(0.0,tkinter.END) self.flist.insert(tkinter.END,'Deleted '+ fname + '\n') self.progress['text'] = fname total += 1 #计数 except: #不能删除,则跳过 pass except ValueError: pass except Exception as e: print(e) pass self.progress['text'] = "删除 %s 个垃圾文件,收回 %.2f M 磁盘空间" % (total,filesize/1024/1024) #搜索大文件 def ScanBigFile(self,filesize): total = 0 filesize = filesize * 1024 * 1024 for drive in GetDrives(): for root,dirs,files in os.walk(drive): for fil in files: try: fname = os.path.abspath(os.path.join(root,fil)) fsize = os.path.getsize(fname) self.progress['text'] = fname #在状态标签中显示每一个遍历的文件 if fsize >= filesize: total += 1 self.flist.insert(tkinter.END, '%s,[%.2f M]\n' % (fname,fsize/1024/1024)) except: pass self.progress['text'] = "找到 %s 个超过 %s M 的大文件" % (total,filesize/1024/1024) def MainLoop(self): self.root.title("Window“减肥”") self.root.minsize(500,400) self.root.maxsize(500,400) self.root.mainloop() #取得当前计算机的盘符 def GetDrives(): drives=[] for i in range(65,91): vol = chr(i) + ':/' if os.path.isdir(vol): drives.append(vol) return tuple(drives) if __name__ == "__main__" : window = Window() window.MainLoop()
[ "liuyifeiflying1991@outlook.com" ]
liuyifeiflying1991@outlook.com
2dd96e64c0ed8f05831e7632864e216a1060f9ce
645e9674e78b3c0ae72a7d4dc5f9694f97c035d3
/Python/Examples2/gui_board.py
1d2dfbea301e5609cbbfd6229923940162dc5e33
[ "MIT" ]
permissive
msiplab/EicProgLab
30cd1b3f45eb86c26a270af5888f6966abaac9ae
aa4b19e59154ce27cda856fa6a615859304bd595
refs/heads/master
2023-07-19T22:35:52.457866
2023-07-12T20:35:23
2023-07-12T20:35:23
125,338,699
1
2
null
null
null
null
UTF-8
Python
false
false
4,653
py
from tkinter import * from tkinter.ttk import * from board import Board from board_out_of_range_exception import BoardOutOfRangeException import time class GuiBoard(Board): def __init__(self,master=None,verbose=False): """コンストラクタ""" # Board クラスのコンストラクタを呼び出し super().__init__(verbose) if master == None: self.master = Tk() self.master.title('リバーシ') else: self.master = master self.__table = BoardTable(master) # self) self.display_state() def display_state(self): """ボードの状態の表示""" try: # ボード状態の更新 for y in range(1,9): for x in range(1,9): if self._get_cell_state(x, y) == Board.WHITE: self.__table.set_cell_stone(x,y,Board.WHITE) elif self._get_cell_state(x, y) == Board.BLACK: self.__table.set_cell_stone(x,y,Board.BLACK) else: self.__table.set_cell_stone(x,y,Board.EMPTY) except BoardOutOfRangeException as boore: # 例外処理 print() print(boore) finally: # 表示の更新 self.master.update() super().display_state() time.sleep(1) class BoardTable(Frame): """ボード用のテーブル""" NUM_DIMS = [8,8] def __init__(self,master): # ,board): """コンストラクタ""" super().__init__(master) # board.master) #self.__board = board self['padding']=(20,20) self.pack() self.create_style() self.create_images() self.create_widgets() def create_style(self): """スタイルの生成""" # ボタンのスタイル style = Style() style.configure('MyCell.TButton', borderwidth = 0, padding = (0,0), relief = RIDGE, background='green') # ラベルのスタイル #style.configure('MyInfo.TLabel', #font = ('Helvetica', '12'), #anchor = 'center', #background='green', #foreground='white') def create_images(self): """マス目の画像生成""" self.empty_img = PhotoImage(file = r"empty.png").subsample(2,2) self.white_img = PhotoImage(file = r"white.png").subsample(2,2) self.black_img = PhotoImage(file = r"black.png").subsample(2,2) def create_widgets(self): """ウィジットの生成""" # 配列の行数(nrows)と列数(ncols) nrows = BoardTable.NUM_DIMS[0] ncols = BoardTable.NUM_DIMS[1] # マス目ボタンの生成 self.__cells = [ [ Button(self, image=self.empty_img, style='MyCell.TButton') for icol in range(ncols) ] for irow in range(nrows) ] # マス目ボタンのグリッド配置 for irow in range(nrows): for icol in range(ncols): cell = self.__cells[irow][icol] cell.grid(row=irow, column=icol) cell.image = self.empty_img # 左クリック時の動作の登録 cell.bind('<Button-1>', self.press) # 情報ラベルの生成 #self.__var = StringVar() #label = Label(self, style='MyInfo.TLabel') #label.config(textvariable = self.__var) #self.__var.set('(-,-)') #label.grid(row=nrows+1, column=0, columnspan=ncols, sticky=(W,E)) def press(self,event): """ボタンクリックの動作""" x = event.widget.grid_info()['column'] + 1 y = event.widget.grid_info()['row'] + 1 print('({0},{1})'.format(x,y)) #self.__board.try_place_stone(x, y) #self.__board.display_state() #self.__var.set('({0},{1})'.format(x,y)) def set_cell_stone(self, x, y, stone): """コマの色の更新""" if stone == Board.WHITE: self.__cells[y-1][x-1]['image'] = self.white_img elif stone == Board.BLACK: self.__cells[y-1][x-1]['image'] = self.black_img else: self.__cells[y-1][x-1]['image'] = self.empty_img if __name__ == '__main__': root = Tk() root.title('リバーシ') board = GuiBoard(root,verbose=True) root.mainloop()
[ "shogo@eng.niigata-u.ac.jp" ]
shogo@eng.niigata-u.ac.jp
71dd1cdece7a06f219a0da724fe6efa5f23c1a67
05ba1957e63510fd8f4f9a3430ec6875d9ecb1cd
/.history/fh/b_20200817025923.py
554fe9ee1946167987776df52d744c79c196e6ca
[]
no_license
cod-lab/try
906b55dd76e77dbb052603f0a1c03ab433e2d4d1
3bc7e4ca482459a65b37dda12f24c0e3c71e88b6
refs/heads/master
2021-11-02T15:18:24.058888
2020-10-07T07:21:15
2020-10-07T07:21:15
245,672,870
0
0
null
null
null
null
UTF-8
Python
false
false
535
py
import requests as re import pprint as p url1 = "https://api.github.com/users/cod-lab/repos?sort=created" pyload = {'sort': 'created'} response = re.get('https://api.github.com/users/cod-lab/repos',params=pyload) print(type(response)) result = response.json() print(type(result)) print(len(result)) repos={} for i in range(len(result)): # print(i) # print(i,result[i]['name']) repos[i] = [result[i]['name']] # repos[i]['name'] = result[i]['name'] # print(result['full_name']) # p.pprint(r.json()) print(repos)
[ "arihant806@gmail.com" ]
arihant806@gmail.com
45298a5c8642014f59b1aedaa12264dedcc01b18
0625c11ee4bbf9529d207e417aa6b7c08c8401fc
/users/migrations/0002_auto_20200516_1434.py
aff549793a337226a26f8265e64d52a95f375f81
[]
no_license
crowdbotics-apps/new-test-5-dev-4699
2111ee0616e48956a31a2beb046d396f462e6b84
0a600a45de768bc39a1f195991d67a738e0d3fc7
refs/heads/master
2023-05-15T08:54:55.532847
2020-05-16T14:34:49
2020-05-16T14:34:49
264,456,120
0
0
null
2021-06-12T22:10:46
2020-05-16T14:34:01
Python
UTF-8
Python
false
false
551
py
# Generated by Django 2.2.12 on 2020-05-16 14:34 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ] operations = [ migrations.AddField( model_name='user', name='test', field=models.BinaryField(blank=True, null=True), ), migrations.AlterField( model_name='user', name='name', field=models.CharField(blank=True, max_length=255, null=True), ), ]
[ "team@crowdbotics.com" ]
team@crowdbotics.com
f98e4660ae0e69a70e376f8870f577004bbea6f3
d2024c9a545dcb81448fa614da6827c180a4b2ee
/tensorflow/2018_6_10/mycode/tensorflow_code/towindows/mycode_save_temp/2-4_Tensorflow_example.py
af470b273213c4b4e6304296a47f6a459dfe3532
[]
no_license
codybai/mycode
f10e06efebff6297ad38494de865b853849f5a3d
4aaa89e7fd00e4c480be6ee931eb419dcdd69476
refs/heads/master
2020-03-19T06:38:51.396611
2018-06-11T05:30:51
2018-06-11T05:30:51
136,042,408
0
0
null
null
null
null
UTF-8
Python
false
false
784
py
import tensorflow as tf import numpy as np #使用numpy生成100个随机点 x_data = np.random.rand(100) y_data = x_data*0.1 + 0.2 #直线 #构造一个线性模型 拟合上面直线 b = tf.Variable(0.) #0.0随便什么值都可以 k = tf.Variable(0.) y = k*x_data + b #二次代价函数 loss = tf.reduce_mean(tf.square(y_data-y))#取平均值(一个平方) #定义一个梯度下降进行优化(优化器) optimizer = tf.train.GradientDescentOptimizer(0.2)#梯度下降学习率0.2 #最小化代价函数 train =optimizer.minimize(loss) #最小化损失函数 init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) for step in range(201): sess.run(train) if step%20 == 0: print(step,sess.run([k,b]))
[ "codybai@163.com" ]
codybai@163.com
b4be736634c779bb7c9e138d5003259a5f77d2dc
a5a99f646e371b45974a6fb6ccc06b0a674818f2
/TopQuarkAnalysis/TopEventProducers/python/producers/TtFullLepEvtFilter_cfi.py
a03896e38afe60dba0432aa0dabd21e5ecec202a
[ "Apache-2.0" ]
permissive
cms-sw/cmssw
4ecd2c1105d59c66d385551230542c6615b9ab58
19c178740257eb48367778593da55dcad08b7a4f
refs/heads/master
2023-08-23T21:57:42.491143
2023-08-22T20:22:40
2023-08-22T20:22:40
10,969,551
1,006
3,696
Apache-2.0
2023-09-14T19:14:28
2013-06-26T14:09:07
C++
UTF-8
Python
false
false
299
py
import FWCore.ParameterSet.Config as cms # # module to filter events based on member functions of the TtFullLeptonicEvent # ttFullLepEventFilter = cms.EDFilter("TtFullLepEvtFilter", src = cms.InputTag("ttFullLepEvent"), cut = cms.string("isHypoValid('kGenMatch') & genMatchSumDR < 999.") )
[ "giulio.eulisse@gmail.com" ]
giulio.eulisse@gmail.com
3f198b7aded2d56301d365c0af65211cf37b0bc4
2f30cf20d58e2cde4037441e67213223c69a6998
/lesson07_function/demo01.py
7f656d289b3ed6bd3d67bcbfeac3f7d0e3bd28a9
[]
no_license
zengcong1314/python1205
b11db7de7d0ad1f8401b8b0c9b20024b4405ae6c
da800ed3374d1d43eb75485588ddb8c3a159bb41
refs/heads/master
2023-05-25T07:17:25.065004
2021-06-08T08:27:54
2021-06-08T08:27:54
318,685,835
0
0
null
null
null
null
UTF-8
Python
false
false
1,102
py
""" 什么是函数 f(x) = x + 2 y = x + 2 python当中的函数和数学函数并没有本质的区别 就是从数据函数。 #函数的定义 def 函数名(): #函数体 return 函数返回值 返回值是得到的结果,打印出来才能看到 函数定义好了以后并不会执行函数体, 如果要执行函数体,需要调用函数。 函数调用之前必须要定义,先定义再调用。 再函数定义的时候,最好不要调用它自己 函数作用:把一段可以重复运行的代码(3行,100行)放到函数体当中。 去调用函数的时候, 什么时候想到用函数:你有很多功能相同的代码需要多次运行。。。你在复制粘贴一段代码的时候 """ #Step Into 进入函数内部 print("before") def print_all_dalao(): """打印所有的大佬 Docstring 文档字符串,说明函数的作用""" #函数体:运行函数的时候会执行的代码 print("1级大佬旧梦") print("2级大佬阿吉") print("3级大佬NiKi") #调用的时候不需要缩进 print_all_dalao() print("hello")
[ "237886015@qq.com" ]
237886015@qq.com
76c947c5838219776b29166da92155d230f1d1e8
ce6fc44470dcb5fca78cdd3349a7be70d75f2e3a
/ICPC/2015 Divisionals/lights/submissions/lights_darcy.py
5db44cf6b01caa2e5ca9d2f55e859afab5d5f196
[]
no_license
cormackikkert/competitive-programming
f3fa287fcb74248ba218ecd763f8f6df31d57424
3a1200b8ff9b6941c422371961a127d7be8f2e00
refs/heads/master
2022-12-17T02:02:40.892608
2020-09-20T11:47:15
2020-09-20T11:47:15
266,775,265
0
0
null
null
null
null
UTF-8
Python
false
false
186
py
n,d = [int(x) for x in input().split()] ans = "YES" for _ in range(n): x,a,g,r = [int(x) for x in input().split()] if x < a or (x-a) % (g+r) > g: ans = "NO" print(ans)
[ "u6427001@anu.edu.au" ]
u6427001@anu.edu.au
da5c3b9df32592471753b77eb653a26f9db9758a
b3e525a3c48800303019adac8f9079109c88004e
/iota/test/apulu/config/add_routes.py
c282d5b2da7b3385d804983ce569bed324eeaa4c
[]
no_license
PsymonLi/sw
d272aee23bf66ebb1143785d6cb5e6fa3927f784
3890a88283a4a4b4f7488f0f79698445c814ee81
refs/heads/master
2022-12-16T21:04:26.379534
2020-08-27T07:57:22
2020-08-28T01:15:20
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,200
py
#! /usr/bin/python3 import pdb import os import json import sys import iota.harness.api as api import iota.harness.infra.utils.parser as parser import iota.test.apulu.config.api as config_api import iota.protos.pygen.topo_svc_pb2 as topo_svc def __get_route_add_cmd(route, gw): route_base_cmd = "ip route add %s via %s" route_cmd = route_base_cmd % (route, gw) api.Logger.info(route_cmd) return route_cmd def AddRoutes(vnic_obj=None): __add_routes(vnic_obj) def __add_routes(vnic_obj=None): vnic_routes = config_api.GetVnicRoutes(vnic_obj) if not vnic_routes: api.Logger.info("No vnic routes to add") return api.types.status.SUCCESS else: req = api.Trigger_CreateExecuteCommandsRequest() for vnic_route in vnic_routes: for route in vnic_route.routes: route_cmd = __get_route_add_cmd(route, vnic_route.gw) api.Trigger_AddCommand(req, vnic_route.node_name, vnic_route.wload_name, route_cmd) resp = api.Trigger(req) return api.types.status.SUCCESS def Main(step): api.Logger.info("Adding route entries") return __add_routes() if __name__ == '__main__': Main(None)
[ "noreply@github.com" ]
PsymonLi.noreply@github.com
41db1bba4d7414222ccffd424de0dd641cfea02a
3831421b5f4f294bf8f4089b1f617cfc82c2351a
/MyInte/SCRIPTS/assit/useiniEr.py
a2191acb7004daa4ebaa23c14ec4258d717d953a
[]
no_license
jesuel51/MyInte
6ce31b813c51e30780115f1a5efcafd8d264ae43
817a6df61cb77dedf0e4a586bd09906a4b175e96
refs/heads/master
2020-05-31T01:46:35.983688
2019-06-03T18:17:34
2019-06-03T18:17:34
190,056,391
0
0
null
null
null
null
UTF-8
Python
false
false
455
py
# this script is modified based on useiniT2.py if root['SETTINGS']['PHYSICS']['useiniEr'][0]==1: pvt_i=root['SETTINGS']['PHYSICS']['useiniEr'][1] drho_tgyro=root['SETTINGS']['PHYSICS']['drho_tgyro'] num=int(pvt_i/drho_tgyro)+1 diff_Er=root['SETTINGS']['PHYSICS']['omega_sparse'][num]-root['SETTINGS']['PHYSICS']['Er_TGYRO'][num] root['SETTINGS']['PHYSICS']['Er_TGYRO'][0:num]=root['SETTINGS']['PHYSICS']['omega_sparse'][0:num]-diff_Er
[ "1018910084@qq.com" ]
1018910084@qq.com
6f9778c931a8859d868533b4217a25cae9247572
72231c7eafef1d0885fd4d74e61be939748c44bf
/examples/run.py
396cbd995ceee81caf0e77b11e3c17b4aad8624d
[]
no_license
jgsogo/conan-poc-graph
b5acf10a4a967461ebe95d7ae717838b9c883676
40491d05e7c7aeb16bcc49eb20f1ef3c5a27f282
refs/heads/master
2022-06-09T05:51:29.691586
2020-05-06T17:11:29
2020-05-06T17:11:29
258,741,725
0
0
null
null
null
null
UTF-8
Python
false
false
2,165
py
import json import os import sys import networkx as nx from conans.graph import Graph from conans.graph.builders import bfs_builder, BFSBuilderEx1 from .utils import ProviderExample def main(graphml, jsonfile): available_recipes = json.load(open(jsonfile)) input_graph = nx.read_graphml(graphml) nx.drawing.nx_agraph.write_dot(input_graph, "input.dot") root = next(nx.topological_sort(input_graph)) """ STEP 1 ------ Build the graph of nodes resolving version ranges and overrides and reporting conflicts """ provider = ProviderExample(input_graph, available_recipes) graph = bfs_builder(root, provider, builder_class=BFSBuilderEx1) Graph.write_dot(graph, "output.dot") os.system("dot -Tpng output.dot -o output.png") if __name__ == '__main__': import argparse import logging formatter_class = argparse.RawDescriptionHelpFormatter parser = argparse.ArgumentParser(description="Conans Graph: Example 1", formatter_class=formatter_class) parser.add_argument("-v", "--verbose", dest="verbose_count", action="count", default=0, help="increases log verbosity for each occurence.") parser.add_argument("example", default=None, help="example to run.") arguments = parser.parse_args(sys.argv[1:]) logging.basicConfig(stream=sys.stderr, level=logging.DEBUG, format='%(name)s (%(levelname)s): %(message)s') log = logging.getLogger('conans') log.setLevel(max(3 - arguments.verbose_count, 0) * 10) log = logging.getLogger('examples') log.setLevel(max(3 - arguments.verbose_count, 0) * 10) sys.stdout.write(f"Example to run: {arguments.example}\n") graphml = os.path.abspath(os.path.join(os.path.dirname(__file__), 'inputs', f'{arguments.example}.xml')) jsonfile = os.path.abspath(os.path.join(os.path.dirname(__file__), 'inputs', f'server.json')) sys.stdout.write(f"Work on file:\n") sys.stdout.write(f" - GraphML: '{graphml}'\n") sys.stdout.write(f" - JSON: '{jsonfile}'\n") main(graphml, jsonfile)
[ "jgsogo@gmail.com" ]
jgsogo@gmail.com
e61c4fdd44f1d4075fc4cb66482035008e151a78
dd65b9bc9475a6cc58817fd45c078e5a6abae241
/Tensorflow/car/web-tf2/gcf-packs/tensorflow2.0/source/tensorflow/_api/v2/compat/v2/summary/__init__.py
2012d8ba0e140114063e73352525237f5323e20b
[]
no_license
jumbokh/gcp_class
5b68192ab4ad091362d89ad667c64443b3b095bb
0a8e2663bfb5b01ce20146da178fa0c9bd7c6625
refs/heads/master
2021-10-22T09:22:04.634899
2021-10-21T12:46:10
2021-10-21T12:46:10
228,617,096
8
7
null
2021-08-25T15:55:30
2019-12-17T12:58:17
Python
UTF-8
Python
false
false
1,170
py
# This file is MACHINE GENERATED! Do not edit. # Generated by: tensorflow/python/tools/api/generator/create_python_api.py script. """Operations for writing summary data, for use in analysis and visualization. See the [Summaries and TensorBoard](https://www.tensorflow.org/guide/summaries_and_tensorboard) guide. """ from __future__ import print_function as _print_function from tensorflow._api.v2.compat.v2.summary import experimental from tensorflow.python.ops.summary_ops_v2 import SummaryWriter from tensorflow.python.ops.summary_ops_v2 import _flush_fn as flush from tensorflow.python.ops.summary_ops_v2 import create_file_writer_v2 as create_file_writer from tensorflow.python.ops.summary_ops_v2 import create_noop_writer from tensorflow.python.ops.summary_ops_v2 import import_event from tensorflow.python.ops.summary_ops_v2 import record_if from tensorflow.python.ops.summary_ops_v2 import summary_scope from tensorflow.python.ops.summary_ops_v2 import trace_export from tensorflow.python.ops.summary_ops_v2 import trace_off from tensorflow.python.ops.summary_ops_v2 import trace_on from tensorflow.python.ops.summary_ops_v2 import write del _print_function
[ "jumbokh@gmail.com" ]
jumbokh@gmail.com
ee485ffb5dc6c4bb9f9a74b1700ca79fcc71dc8d
c3e3b606e312e5e50afba39db2ea573c21171405
/transaction/migrations/0003_auto_20170803_1730.py
ce51e92fd4b8193a9bdcf4f3daf72814b3c5e412
[]
no_license
CodeNicely/AccountingWebApp
3fa88ea196afda38ff3f3015e8b0623c41b7ee8a
a96932af24f0dff44e464f9fbeb3ef49956764b2
refs/heads/master
2021-01-02T22:52:56.898964
2017-09-19T10:26:52
2017-09-19T10:26:52
99,409,458
0
1
null
null
null
null
UTF-8
Python
false
false
1,152
py
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2017-08-03 17:30 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('transaction', '0002_auto_20170803_1514'), ] operations = [ migrations.RemoveField( model_name='impress', name='name', ), migrations.RemoveField( model_name='impress', name='type', ), migrations.AlterField( model_name='expense', name='voucher', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='home.Voucher'), ), migrations.AlterField( model_name='impress', name='voucher', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='home.Voucher'), ), migrations.AlterField( model_name='receive', name='voucher', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='home.Voucher'), ), ]
[ "mayankchaurasia.bsp@gmail.com" ]
mayankchaurasia.bsp@gmail.com
23f25c266ed6b2551223457bdbd4656108abc748
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03086/s746635354.py
575ea419f24cb64ccfbb4765610d6a8475a77ce3
[]
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
355
py
S = input() ans = 0 for i in range(len(S)): for j in range(i, len(S)): sub_s = S[i:j+1] is_acgt = True for s in sub_s: if s == "A" or s == "C" or s == "G" or s == "T": continue else: is_acgt = False if is_acgt: ans = max(ans, len(sub_s)) print(ans)
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
c5c99755f83c77bbb115fd5e364be87b9f009220
b049a961f100444dde14599bab06a0a4224d869b
/sdk/python/pulumi_azure_native/containerregistry/v20190601preview/_enums.py
d0e595ad3fef9d9ce637c62acc0fa0a0ab83b51f
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
pulumi/pulumi-azure-native
b390c88beef8381f9a71ab2bed5571e0dd848e65
4c499abe17ec6696ce28477dde1157372896364e
refs/heads/master
2023-08-30T08:19:41.564780
2023-08-28T19:29:04
2023-08-28T19:29:04
172,386,632
107
29
Apache-2.0
2023-09-14T13:17:00
2019-02-24T20:30:21
Python
UTF-8
Python
false
false
2,852
py
# coding=utf-8 # *** WARNING: this file was generated by pulumi. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** from enum import Enum __all__ = [ 'Architecture', 'BaseImageTriggerType', 'OS', 'ResourceIdentityType', 'SecretObjectType', 'SourceControlType', 'SourceRegistryLoginMode', 'SourceTriggerEvent', 'StepType', 'TaskStatus', 'TokenType', 'TriggerStatus', 'UpdateTriggerPayloadType', 'Variant', ] class Architecture(str, Enum): """ The OS architecture. """ AMD64 = "amd64" X86 = "x86" ARCHITECTURE_386 = "386" ARM = "arm" ARM64 = "arm64" class BaseImageTriggerType(str, Enum): """ The type of the auto trigger for base image dependency updates. """ ALL = "All" RUNTIME = "Runtime" class OS(str, Enum): """ The operating system type required for the run. """ WINDOWS = "Windows" LINUX = "Linux" class ResourceIdentityType(str, Enum): """ The identity type. """ SYSTEM_ASSIGNED = "SystemAssigned" USER_ASSIGNED = "UserAssigned" SYSTEM_ASSIGNED_USER_ASSIGNED = "SystemAssigned, UserAssigned" NONE = "None" class SecretObjectType(str, Enum): """ The type of the secret object which determines how the value of the secret object has to be interpreted. """ OPAQUE = "Opaque" VAULTSECRET = "Vaultsecret" class SourceControlType(str, Enum): """ The type of source control service. """ GITHUB = "Github" VISUAL_STUDIO_TEAM_SERVICE = "VisualStudioTeamService" class SourceRegistryLoginMode(str, Enum): """ The authentication mode which determines the source registry login scope. The credentials for the source registry will be generated using the given scope. These credentials will be used to login to the source registry during the run. """ NONE = "None" DEFAULT = "Default" class SourceTriggerEvent(str, Enum): COMMIT = "commit" PULLREQUEST = "pullrequest" class StepType(str, Enum): """ The type of the step. """ DOCKER = "Docker" FILE_TASK = "FileTask" ENCODED_TASK = "EncodedTask" class TaskStatus(str, Enum): """ The current status of task. """ DISABLED = "Disabled" ENABLED = "Enabled" class TokenType(str, Enum): """ The type of Auth token. """ PAT = "PAT" O_AUTH = "OAuth" class TriggerStatus(str, Enum): """ The current status of trigger. """ DISABLED = "Disabled" ENABLED = "Enabled" class UpdateTriggerPayloadType(str, Enum): """ Type of Payload body for Base image update triggers. """ DEFAULT = "Default" TOKEN = "Token" class Variant(str, Enum): """ Variant of the CPU. """ V6 = "v6" V7 = "v7" V8 = "v8"
[ "github@mikhail.io" ]
github@mikhail.io
9c4bf09d819e17fe582f6b48d0e82b956fa722d2
bdfb6084a33e4b443ffc2a97673ecbfa736d947b
/.history/vision/tensorflow_object_detect/scripts/detect_lane_20210224132019.py
517152289cafe1d8a511b7cb127705ebdbd59333
[ "MIT" ]
permissive
robcn/Autopilot-Demo
5c830a0f721d3e8df864c0fcb26e9ea280bbe3fe
0b7178ae3f417f529d7015373a1e51eb71df28ab
refs/heads/master
2023-03-16T00:20:31.498672
2021-02-24T13:34:06
2021-02-24T13:34:06
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,127
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import rospy import numpy as np import cv2 from cv_bridge import CvBridge from std_msgs.msg import UInt8, Float64 from sensor_msgs.msg import Image, CompressedImage import time # from vision_msgs.msg import Center class DetectLane(): def __init__(self): self.sub_image_original = rospy.Subscriber('/camera/image', Image, self.cbFindLane, queue_size = 1) self.pub_image_detect = rospy.Publisher('/detect/lane', Image, queue_size = 1) self.pub_center_white_lane = rospy.Publisher('/control/white_lane', Float64, queue_size = 1) self.pub_center_yellow_lane = rospy.Publisher('/control/yellow_lane', Float64, queue_size = 1) self.pub_center = rospy.Publisher('/control/center', Float64, queue_size = 1) self.cvBridge = CvBridge() self.counter = 1 self.hue_white_l = 0 self.hue_white_h = 179 self.saturation_white_l = 0 self.saturation_white_h = 30 self.lightness_white_l = 221 self.lightness_white_h = 255 self.hue_yellow_l = 26 self.hue_yellow_h = 34 self.saturation_yellow_l = 43 self.saturation_yellow_h = 255 self.lightness_yellow_l = 46 self.lightness_yellow_h = 255 def cbFindLane(self, image_msg): # Change the frame rate by yourself. Now, it is set to 1/3 (10fps). # Unappropriate value of frame rate may cause huge delay on entire recognition process. # This is up to your computer's operating power. if self.counter % 3 != 0: self.counter += 1 return else: self.counter = 1 cv_image = self.cvBridge.imgmsg_to_cv2(image_msg, "bgr8") # find White and Yellow Lanes self.maskLane(cv_image) # yellow_fraction, cv_yellow_lane = self.maskYellowLane(cv_image) def maskLane(self,image): # convert image to hsv hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) # param of irange hsv(white & yellow) Hue_white_h = self.hue_white_l Hue_white_l = self.hue_white_h Saturation_white_h = self.saturation_white_l Saturation_white_l = self.saturation_white_h Lightness_white_h = self.lightness_white_h Lightness_white_l = self.lightness_white_l Hue_yellow_h = self.hue_yellow_l Hue_yellow_l = self.hue_yellow_h Saturation_yellow_h = self.saturation_yellow_l Saturation_yellow_l = self.saturation_yellow_h Lightness_yellow_h = self.lightness_yellow_h Lightness_yellow_l = self.lightness_yellow_l # define range of white color in HSV lower_white = np.array([Hue_white_h, Saturation_white_h, Lightness_white_l]) upper_white = np.array([Hue_white_l, Saturation_white_l, Lightness_white_h]) lower_yellow = np.array([Hue_yellow_h, Saturation_yellow_h, Lightness_yellow_l]) upper_yellow = np.array([Hue_yellow_l, Saturation_yellow_l, Lightness_yellow_h]) # Threshold the HSV image to get only white colors mask_white = cv2.inRange(hsv, lower_white, upper_white) mask_yellow = cv2.inRange(hsv, lower_yellow, upper_yellow) kernel = np.ones((5,5)) erosion_white = cv2.erode(mask_white,kernel) erosion_yellow = cv2.erode(mask_yellow,kernel) Gaussian_white = cv2.GaussianBlur(erosion_white, (5,5),0) Gaussian_yellow = cv2.GaussianBlur(erosion_yellow, (5,5),0) # cv2.imshow("g",Gaussian_yellow) # cv2.waitKey(3) # findContours of image contours_white, hierarchy_white = cv2.findContours(Gaussian_white, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) contours_yellow, hierarchy_yellow = cv2.findContours(Gaussian_yellow, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) # draw the contours in origin image cv2.drawContours(image, contours_white, -1, (139,104,0), 3) cv2.drawContours(image, contours_yellow, -1, (139,104,0), 3) # try: white_center = self.calculate_average(contours_white[0]) # print("white: ",white_center) # except: # is_detect_white = 0 # print("The Camera Can`t Catch The White Lane.") # try: yellow_center = self.calculate_average(contours_yellow[0]) # print("yellow: ",yellow_center) # except: # is_detect_yellow = 0 # print("The Camera Can`t Catch The Yellow Lane.") # Publish Image self.pub_image_detect.publish(self.cvBridge.cv2_to_imgmsg(image,'bgr8')) # Publish Center self.pub_center_white_lane.publish(white_center) self.pub_center_yellow_lane.publish(yellow_center) self.pub_center.publish((white_center+yellow_center)/2) def calculate_average(self,input): sum_x = 0 for i in input: sum_x += i[0][0] return sum_x/len(input) def main(self): rospy.spin() if __name__ == '__main__': rospy.init_node('detect_lane') node = DetectLane() node.main()
[ "hemingshan_1999@163.com" ]
hemingshan_1999@163.com
9196ebb5aec8baa5f60c3c5cf2fb5d3011f98fff
c16d4c86ef1f874b701c707b5a01556d36fa0d4f
/test/test_ipamsvc_create_option_code_response.py
dc4d9225dc29304f6595bb33cef120d70bfe5095
[]
no_license
uuand/ibcsp_ipamsvc
7f9f4c2509ce9049e2ab39d1072e9d1d31a5165c
94a5475b11997551f732ceffcbd627d27ac37b2c
refs/heads/master
2022-11-21T07:22:12.131660
2020-07-24T08:38:55
2020-07-24T08:38:55
281,871,334
1
0
null
null
null
null
UTF-8
Python
false
false
1,583
py
# coding: utf-8 """ IP Address Management API The IPAM/DHCP Application is a BloxOne DDI service providing IP address management and DHCP protocol features. The IPAM component provides visibility into and provisioning tools to manage networking spaces, monitoring and reporting of entire IP address infrastructures, and integration with DNS and DHCP protocols. The DHCP component provides DHCP protocol configuration service with on-prem host serving DHCP protocol. It is part of the full-featured, DDI cloud solution that enables customers to deploy large numbers of protocol servers to deliver DNS and DHCP throughout their enterprise network. # noqa: E501 OpenAPI spec version: v1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest import ibcsp_ipamsvc from ibcsp_ipamsvc.models.ipamsvc_create_option_code_response import IpamsvcCreateOptionCodeResponse # noqa: E501 from ibcsp_ipamsvc.rest import ApiException class TestIpamsvcCreateOptionCodeResponse(unittest.TestCase): """IpamsvcCreateOptionCodeResponse unit test stubs""" def setUp(self): pass def tearDown(self): pass def testIpamsvcCreateOptionCodeResponse(self): """Test IpamsvcCreateOptionCodeResponse""" # FIXME: construct object with mandatory attributes with example values # model = ibcsp_ipamsvc.models.ipamsvc_create_option_code_response.IpamsvcCreateOptionCodeResponse() # noqa: E501 pass if __name__ == '__main__': unittest.main()
[ "jens-peter.wand@metrosystems.net" ]
jens-peter.wand@metrosystems.net
1b51955dcd03e031fd0e85fcc4b87bdab823692d
53784d3746eccb6d8fca540be9087a12f3713d1c
/res/packages/scripts/scripts/client/gui/Scaleform/daapi/view/battle/shared/siege_component.py
73f51182224a9c1ece84e7e55c2e91739f7e0985
[]
no_license
webiumsk/WOT-0.9.17.1-CT
736666d53cbd0da6745b970e90a8bac6ea80813d
d7c3cf340ae40318933e7205bf9a17c7e53bac52
refs/heads/master
2021-01-09T06:00:33.898009
2017-02-03T21:40:17
2017-02-03T21:40:17
80,870,824
0
0
null
null
null
null
WINDOWS-1250
Python
false
false
5,817
py
# 2017.02.03 21:49:10 Střední Evropa (běžný čas) # Embedded file name: scripts/client/gui/Scaleform/daapi/view/battle/shared/siege_component.py import BigWorld from gui.shared.utils.TimeInterval import TimeInterval from constants import VEHICLE_SIEGE_STATE class _ComponentUpdater(object): """ This is a base updater class, it contains the common logic for updating Siege indicator. """ __slots__ = ('_parentObj', '_totalTime', '_timeLeft', '_siegeState', '_engineState', '_isSmooth') def __init__(self, parentObj, totalTime, timeLeft, siegeState, engineState, isSmooth): """ Constructor, initializes internal variables. :param parentObj: reference on SiegeModeIndicator class :param totalTime: time which is necessary to switch state (normal/siege) :param timeLeft: time left to switch to a state :param siegeState: integer, see constants for each constant :param engineState: string, describing engine's state """ super(_ComponentUpdater, self).__init__() self._parentObj = parentObj self._totalTime = totalTime self._timeLeft = timeLeft self._siegeState = siegeState self._engineState = engineState self._isSmooth = isSmooth def __repr__(self): return '_UpdaterComponent(totalTime = {}, timeLeft = {}, siegeState = {}, engineState = {})'.format(self._totalTime, self._timeLeft, self._siegeState, self._engineState) def clear(self): self._stopTick() self._parentObj = None return def show(self): self._startTick() def _startTick(self): raise NotImplementedError def _stopTick(self): raise NotImplementedError class _ActionScriptUpdater(_ComponentUpdater): """ This updater is used only in real battle (non-replays) for performance reasons. It will tell Flash about times and states. Animations(and ticks) are implemented on Flash side. """ __slots__ = () def _startTick(self): self._parentObj.as_switchSiegeStateS(self._totalTime, self._timeLeft, self._siegeState, self._engineState, self._isSmooth) def _stopTick(self): pass class _PythonUpdater(_ComponentUpdater): """ This updater is used only in REPLAYS. It will use internal timer to tick every 0.05 second. This solution is necessary to display actual timeLeft, states, etc correctly during replay's timeWarp, rewind, start/stop, etc. """ __slots__ = ('_timeInterval', '_startTime', '_finishTime', '__weakref__') def __init__(self, parentObj, totalTime, timeLeft, siegeState, engineState, isSmooth): super(_PythonUpdater, self).__init__(parentObj, totalTime, timeLeft, siegeState, engineState, isSmooth) self._timeInterval = TimeInterval(0.05, self, '_tick') self._startTime = BigWorld.serverTime() self._finishTime = self._startTime + timeLeft def clear(self): self._timeInterval.stop() super(_PythonUpdater, self).clear() def _startTick(self): if self._siegeState in VEHICLE_SIEGE_STATE.SWITCHING: timeLeft = max(0, self._finishTime - BigWorld.serverTime()) if timeLeft: self._updateSnapshot(timeLeft) self._timeInterval.start() else: self._updateSnapshot(self._timeLeft) self._isSmooth = False def _stopTick(self): self._timeInterval.stop() def _tick(self): timeLeft = self._finishTime - BigWorld.serverTime() if timeLeft >= 0 and self._engineState != 'destroyed': self._updateSnapshot(timeLeft) def _updateSnapshot(self, timeLeft): self._parentObj.as_switchSiegeStateSnapshotS(self._totalTime, timeLeft, self._siegeState, self._engineState, self._isSmooth) class _SiegeComponent(object): """ This class maintains a componentUpdater class. It creates and shows an updater after any changes """ __slots__ = ('_componentUpdater', '_parentObj', '_clazz') def __init__(self, parentObj, clazz): super(_SiegeComponent, self).__init__() self._componentUpdater = None self._parentObj = parentObj self._clazz = clazz return def invalidate(self, totalTime, timeLeft, siegeState, engineState, isSmooth): self._clearUpdater() self._componentUpdater = self._clazz(self._parentObj, totalTime, timeLeft, siegeState, engineState, isSmooth) self._componentUpdater.show() def clear(self): self._parentObj = None self._clearUpdater() return def _clearUpdater(self): if self._componentUpdater is not None: self._componentUpdater.clear() return class _DefaultSiegeComponent(_SiegeComponent): """ The component is used in real battles, it will use _ActionScriptUpdater. """ __slots__ = () def __init__(self, parentObj): super(_DefaultSiegeComponent, self).__init__(parentObj, _ActionScriptUpdater) class _ReplaySiegeComponent(_SiegeComponent): """ The component is used in Replays, it will use _PythonUpdater. """ __slots__ = () def __init__(self, parentObj): super(_ReplaySiegeComponent, self).__init__(parentObj, _PythonUpdater) def createSiegeComponent(siegeModeIndicator, isReplayPlaying): if isReplayPlaying: component = _ReplaySiegeComponent(siegeModeIndicator) else: component = _DefaultSiegeComponent(siegeModeIndicator) return component # okay decompyling c:\Users\PC\wotsources\files\originals\res\packages\scripts\scripts\client\gui\Scaleform\daapi\view\battle\shared\siege_component.pyc # decompiled 1 files: 1 okay, 0 failed, 0 verify failed # 2017.02.03 21:49:11 Střední Evropa (běžný čas)
[ "info@webium.sk" ]
info@webium.sk
3a2072c419b039df9feecca52bca18f6bb7d8ad4
c81d0270a4e924357735dd955b9cd463c5fa87e7
/note/migrations/0009_notes_title_salt.py
9c3192de173d8d6a48c40bbf2396b30beca46347
[ "MIT" ]
permissive
pyprism/Hiren-Notes
25210384ee8ef777f1e05bb6e32a1bde2d6c4f31
7548ef8927cdac4342ab54e72cf949fd484342be
refs/heads/master
2021-06-05T04:17:24.229239
2019-04-12T16:17:22
2019-04-12T16:17:22
19,016,855
1
0
MIT
2021-03-19T21:58:00
2014-04-22T04:16:53
JavaScript
UTF-8
Python
false
false
409
py
# Generated by Django 2.0.2 on 2018-03-02 10:27 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('note', '0008_auto_20180302_1025'), ] operations = [ migrations.AddField( model_name='notes', name='title_salt', field=models.CharField(blank=True, max_length=1000, null=True), ), ]
[ "git.pyprism@gmail.com" ]
git.pyprism@gmail.com
14f22c74f6937fb2d3e1b639b5efb8a0673e5765
bb150497a05203a718fb3630941231be9e3b6a32
/framework/e2e/jit/test_SELU_1.py
a2c481e2d501436f0c628320c52c9085d53004f5
[]
no_license
PaddlePaddle/PaddleTest
4fb3dec677f0f13f7f1003fd30df748bf0b5940d
bd3790ce72a2a26611b5eda3901651b5a809348f
refs/heads/develop
2023-09-06T04:23:39.181903
2023-09-04T11:17:50
2023-09-04T11:17:50
383,138,186
42
312
null
2023-09-13T11:13:35
2021-07-05T12:44:59
Python
UTF-8
Python
false
false
602
py
#!/bin/env python # -*- coding: utf-8 -*- # encoding=utf-8 vi:ts=4:sw=4:expandtab:ft=python """ test jit cases """ import os import sys sys.path.append(os.path.abspath(os.path.dirname(os.getcwd()))) sys.path.append(os.path.join(os.path.abspath(os.path.dirname(os.getcwd())), "utils")) from utils.yaml_loader import YamlLoader from jittrans import JitTrans yaml_path = os.path.join(os.path.abspath(os.path.dirname(os.getcwd())), "yaml", "nn.yml") yml = YamlLoader(yaml_path) def test_SELU_1(): """test SELU_1""" jit_case = JitTrans(case=yml.get_case_info("SELU_1")) jit_case.jit_run()
[ "825276847@qq.com" ]
825276847@qq.com
8d4da3d22d15ab100ea55a5fc8e0ff016faad178
55c250525bd7198ac905b1f2f86d16a44f73e03a
/Python/Scripts/Windows Screen Grabber.py
ad25866ec1abc82b1fb1290512d123242b04df15
[]
no_license
NateWeiler/Resources
213d18ba86f7cc9d845741b8571b9e2c2c6be916
bd4a8a82a3e83a381c97d19e5df42cbababfc66c
refs/heads/master
2023-09-03T17:50:31.937137
2023-08-28T23:50:57
2023-08-28T23:50:57
267,368,545
2
1
null
2022-09-08T15:20:18
2020-05-27T16:18:17
null
UTF-8
Python
false
false
129
py
version https://git-lfs.github.com/spec/v1 oid sha256:d42d1123aca40cb02062035961a92fbd679ac421ced273e1fe467c16558b125b size 1194
[ "nateweiler84@gmail.com" ]
nateweiler84@gmail.com
3a1984fc6224def23eb696ddb9f5dad7ba49d56a
62e58c051128baef9452e7e0eb0b5a83367add26
/edifact/D09B/RPCALLD09BUN.py
1841fa1a0ab031e47d5def4db3d66a6b4b480a92
[]
no_license
dougvanhorn/bots-grammars
2eb6c0a6b5231c14a6faf194b932aa614809076c
09db18d9d9bd9d92cefbf00f1c0de1c590fe3d0d
refs/heads/master
2021-05-16T12:55:58.022904
2019-05-17T15:22:23
2019-05-17T15:22:23
105,274,633
0
0
null
2017-09-29T13:21:21
2017-09-29T13:21:21
null
UTF-8
Python
false
false
1,502
py
#Generated by bots open source edi translator from UN-docs. from bots.botsconfig import * from edifact import syntax from recordsD09BUN import recorddefs structure = [ {ID: 'UNH', MIN: 1, MAX: 1, LEVEL: [ {ID: 'BGM', MIN: 1, MAX: 1}, {ID: 'DTM', MIN: 1, MAX: 99}, {ID: 'RFF', MIN: 0, MAX: 9999, LEVEL: [ {ID: 'DTM', MIN: 0, MAX: 99}, ]}, {ID: 'NAD', MIN: 0, MAX: 999, LEVEL: [ {ID: 'RFF', MIN: 0, MAX: 99, LEVEL: [ {ID: 'DTM', MIN: 0, MAX: 9}, ]}, {ID: 'CTA', MIN: 0, MAX: 99, LEVEL: [ {ID: 'COM', MIN: 0, MAX: 9}, ]}, ]}, {ID: 'DOC', MIN: 0, MAX: 99999, LEVEL: [ {ID: 'DTM', MIN: 0, MAX: 9}, {ID: 'FTX', MIN: 0, MAX: 9}, {ID: 'LIN', MIN: 0, MAX: 99999, LEVEL: [ {ID: 'PIA', MIN: 0, MAX: 99}, {ID: 'IMD', MIN: 0, MAX: 99}, {ID: 'DTM', MIN: 0, MAX: 99}, {ID: 'ALI', MIN: 0, MAX: 9}, {ID: 'RFF', MIN: 0, MAX: 999, LEVEL: [ {ID: 'DTM', MIN: 0, MAX: 9}, ]}, {ID: 'NAD', MIN: 0, MAX: 999, LEVEL: [ {ID: 'CTA', MIN: 0, MAX: 9, LEVEL: [ {ID: 'COM', MIN: 0, MAX: 9}, ]}, ]}, {ID: 'CCI', MIN: 0, MAX: 9999, LEVEL: [ {ID: 'CAV', MIN: 0, MAX: 99}, {ID: 'FTX', MIN: 0, MAX: 99}, ]}, ]}, ]}, {ID: 'CNT', MIN: 0, MAX: 99}, {ID: 'UNT', MIN: 1, MAX: 1}, ]}, ]
[ "jason.capriotti@gmail.com" ]
jason.capriotti@gmail.com
3314d516df6394caddba78195cce8da8b6f91c13
69f1529b5b4ef46f0b5a963667b9c00fd484487b
/docassemble_webapp/docassemble/webapp/restart.py
0a665feeb0fba0085fc5bc2769f202a86083772f
[ "MIT" ]
permissive
vfulco/docassemble
571e9e0e5140cc8c667cb51d4308744107b1c214
482aae3217dd80e018a670588142cf694c300fc9
refs/heads/master
2021-01-11T04:56:25.263813
2016-12-15T03:58:15
2016-12-15T03:58:15
76,629,690
1
0
null
2016-12-16T06:53:07
2016-12-16T06:53:07
null
UTF-8
Python
false
false
800
py
import sys import os import docassemble.base.config from docassemble.base.config import daconfig, s3_config, S3_ENABLED if __name__ == "__main__": docassemble.base.config.load(arguments=sys.argv) WEBAPP_PATH = daconfig.get('webapp', '/usr/share/docassemble/webapp/docassemble.wsgi') def main(): if S3_ENABLED: import docassemble.webapp.amazon s3 = docassemble.webapp.amazon.s3object(s3_config) key = s3.get_key('config.yml') if key.exists(): key.get_contents_to_filename(config_file) sys.stderr.write("Wrote config file based on copy on s3\n") wsgi_file = WEBAPP_PATH if os.path.isfile(wsgi_file): with open(wsgi_file, 'a'): os.utime(wsgi_file, None) sys.exit(0) if __name__ == "__main__": main()
[ "jpyle@philalegal.org" ]
jpyle@philalegal.org
6aad7ad5c4ed7a14ea13239ee6e47bfdae400035
a2da53c90ed7876c8e790b525a66818df6fc57ac
/main.py
0ace4937af7ab9dd166d73930f96c69dc2312714
[]
no_license
Rishi05051997/flask-learning
103a82378e37370a78c01c2e8a95f4032b13b0f5
4109fe641283bf6c86178ece72a1444580b3c101
refs/heads/main
2023-06-18T14:27:20.940448
2021-07-20T10:42:04
2021-07-20T10:42:04
387,658,735
0
0
null
null
null
null
UTF-8
Python
false
false
420
py
from flask import Flask, render_template app = Flask(__name__, template_folder='templates') @app.route("/") def home(): return render_template('index.html') @app.route("/about") def about(): return render_template('about.html') @app.route('/contact') def contact(): return render_template('contact.html') @app.route('/post') def post(): return render_template('post.html') app.run(debug=True)
[ "vrushabhdhatral10@gmail.com" ]
vrushabhdhatral10@gmail.com
3ad7f1f5cd34f8b6e9246a83cf38e08f43df17c2
e6fac8e0289d9f82369d2eb8e22bc175c6f51b3b
/Arcade/Intro/Level 9/Knapsack Light/code.py
ab01c71d4bb8495d7fb0d3ce190f55db1992bf6f
[]
no_license
Zahidsqldba07/CodeFights-9
f361c15d24f96afa26de08af273a7f8f507ced4a
6c5d152b1ad35cf178dd74acbc44ceb5fdcdf139
refs/heads/master
2023-03-18T23:52:43.274786
2017-05-12T07:28:08
2017-05-12T07:28:08
null
0
0
null
null
null
null
UTF-8
Python
false
false
434
py
# Uh... these problems are kind of trivial. def knapsackLight(value1, weight1, value2, weight2, maxW): if weight1 + weight2 <= maxW: return value1 + value2 if weight1 > maxW or weight2 > maxW: if weight1 > maxW and weight2 > maxW: return 0 if weight1 > maxW: return value2 if weight2 > maxW: return value1 return value1 if value1 > value2 else value2
[ "hallosputnik@gmail.com" ]
hallosputnik@gmail.com
e3c83cbf552b41004b3b9b6a6caa62486ed99d3b
83fd7f0b557b40d0c00bdcf33f8a4d5a39fba919
/modules/Tkinter/tkinter_examples.py
6f983ba3bf6d58018eac6f08d211c987b334c0ae
[]
no_license
stradtkt/Python-Examples
2ad6eef5e651803976ae05ce92a0e98944e10d13
6e700a23e65ba37d61ef7f3ff3da5feb1da3b33f
refs/heads/master
2020-03-09T22:22:31.437381
2018-04-14T03:56:49
2018-04-14T03:56:49
129,032,586
0
0
null
null
null
null
UTF-8
Python
false
false
1,991
py
try: import tkinter except ImportError: import Tkinter as tkinter # tkinter._test() # mainWindow = tkinter.Tk() # mainWindow.title("Hello world") # mainWindow.geometry('640x480+8+400') # label = tkinter.Label(mainWindow, text="Hello World") # label.pack(side='top') # leftFrame = tkinter.Frame(mainWindow) # leftFrame.pack(side='left', anchor='n', fill=tkinter.Y, expand=False) # canvas = tkinter.Canvas(leftFrame, relief='raised', borderwidth=3) # canvas.pack(side='left', anchor='n', fill=tkinter.BOTH, expand=True) # rightFrame = tkinter.Frame(mainWindow) # rightFrame.pack(side='right', anchor='n', expand=True) # button1 = tkinter.Button(rightFrame, text="Open") # button2 = tkinter.Button(rightFrame, text="Edit") # button3 = tkinter.Button(rightFrame, text="Close") # button1.pack(side='left') # button2.pack(side='left') # button3.pack(side='left') # mainWindow.mainloop() mainWindow = tkinter.Tk() mainWindow.title("Hello world") mainWindow.geometry('640x480-8-200') label = tkinter.Label(mainWindow, text="Hello World") label.grid(row=0, column=0) leftFrame = tkinter.Frame(mainWindow) leftFrame.grid(row=1, column=1) canvas = tkinter.Canvas(leftFrame, relief='raised', borderwidth=1) canvas.grid(row=1, column=0) rightFrame = tkinter.Frame(mainWindow) rightFrame.grid(row=1, column=2, sticky='n') button1 = tkinter.Button(rightFrame, text="Open") button2 = tkinter.Button(rightFrame, text="Edit") button3 = tkinter.Button(rightFrame, text="Close") button1.grid(row=0, column=0) button2.grid(row=1, column=0) button3.grid(row=2, column=0) mainWindow.columnconfigure(0, weight=1) mainWindow.columnconfigure(1, weight=1) mainWindow.grid_columnconfigure(2, weight=1) leftFrame.config(relief='sunken', borderwidth=1) rightFrame.config(relief='sunken', borderwidth=1) leftFrame.grid(sticky='ns') rightFrame.grid(sticky='new') rightFrame.columnconfigure(0, weight=1) button1.grid(sticky='ew') button2.grid(sticky='ew') button3.grid(sticky='ew') mainWindow.mainloop()
[ "stradtkt22@gmail.com" ]
stradtkt22@gmail.com
60d249fc4269358356d06893e79b8dffc1366916
81d635211686b1bc87af5892bd9e0fb95cc2ddb8
/adwords api/googleads-python-lib-master/examples/dfp/v201502/custom_targeting_service/update_custom_targeting_keys.py
365f935de4fca4a2f72a434162745dcabdd01844
[ "Apache-2.0" ]
permissive
analyticsbot/Python-Code---Part-2
de2f0581258b6c8b8808b4ef2884fe7e323876f0
12bdcfdef4472bcedc77ae61707c25a4a09cba8a
refs/heads/master
2021-06-04T05:10:33.185766
2016-08-31T13:45:45
2016-08-31T13:45:45
66,679,512
3
0
null
null
null
null
UTF-8
Python
false
false
2,344
py
#!/usr/bin/python # # Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This example updates the display name of a single custom targeting key. To determine which custom targeting keys exist, run get_all_custom_targeting_keys_and_values.py.""" # Import appropriate modules from the client library. from googleads import dfp CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE' def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( 'CustomTargetingService', version='v201502') values = [{ 'key': 'keyId', 'value': { 'xsi_type': 'NumberValue', 'value': key_id } }] query = 'WHERE id = :keyId' statement = dfp.FilterStatement(query, values, 1) # Get custom targeting keys by statement. response = custom_targeting_service.getCustomTargetingKeysByStatement( statement.ToStatement()) # Update each local custom targeting key object by changing its display name. if 'results' in response: updated_keys = [] for key in response['results']: if not key['displayName']: key['displayName'] = key['name'] key['displayName'] += ' (Deprecated)' updated_keys.append(key) keys = custom_targeting_service.updateCustomTargetingKeys(updated_keys) # Display results. if keys: for key in keys: print ('Custom targeting key with id \'%s\', name \'%s\', display name ' '\'%s\', and type \'%s\' was updated.' % (key['id'], key['name'], key['displayName'], key['type'])) else: print 'No custom targeting keys were found to update.' if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() main(dfp_client, CUSTOM_TARGETING_KEY_ID)
[ "ravi.shankar1788@gmail.com" ]
ravi.shankar1788@gmail.com
4ecbb5094d9e12a552d5a5feb96339bc971ade3b
52b5773617a1b972a905de4d692540d26ff74926
/.history/minWindow_20200618151102.py
c6c0994a2195ff78f8088916365811c2e25eeb39
[]
no_license
MaryanneNjeri/pythonModules
56f54bf098ae58ea069bf33f11ae94fa8eedcabc
f4e56b1e4dda2349267af634a46f6b9df6686020
refs/heads/master
2022-12-16T02:59:19.896129
2020-09-11T12:05:22
2020-09-11T12:05:22
null
0
0
null
null
null
null
UTF-8
Python
false
false
769
py
# for this question we have two pointers # left pointer # right pointer # we move the right pointer and maintain the position of the left pointer # when we find the word we move the left pointer # store that word its shortest form # we keep moving the right pointer # sz,azjskfzts def minWindow(str1,str2): left = 0 right = 0 word = set(str1) print(word) while left < len(str2) and right < len(str2): # print(str2[left:right]) if str2[left:right].find(str1): newWord = str2[left:right] print(newWord) print("yes") left +=1 else: print(,str2[left:right]) right +=1 minWindow("sz","azjskfzts")
[ "mary.jereh@gmail.com" ]
mary.jereh@gmail.com
02bc1425fec78e9b004e5d15542a8180ac5f69b1
4e6fbaabd7d8e2504c9ac75dda322327f5514fb1
/rooms/views.py
c2a54f88f2101396ae080809a5d610c300223da4
[]
no_license
amrebrahem22/lavish
bd82d0131a6923f1749b53b7bd5f54c2ebc08be0
d3a9d492f93f441aafeb2082f2d627c9d4f16769
refs/heads/master
2023-01-09T03:00:54.881316
2020-11-16T23:04:21
2020-11-16T23:04:21
300,782,449
0
0
null
null
null
null
UTF-8
Python
false
false
6,112
py
from django.views.generic import ListView, DetailView, View, UpdateView, FormView from django.shortcuts import render, redirect, reverse from django.core.paginator import Paginator from django.contrib.auth.decorators import login_required from django.contrib import messages from django.http import Http404 from django.contrib.messages.views import SuccessMessageMixin from django_countries import countries from .models import Room, RoomType, Amenity, Facility, Photo from . import forms from users import mixins as user_mixins class HomeView(ListView): model = Room paginate_by = 10 paginate_orphans = 5 ordering = 'created' context_object_name = 'rooms' template_name = 'rooms/home.html' class RoomDetail(DetailView): model = Room context_object_name = 'room' template_name = 'rooms/room_detail.html' class SearchView(View): """ SearchView Definition """ def get(self, request): country = request.GET.get("country") if country: form = forms.SearchForm(request.GET) if form.is_valid(): city = form.cleaned_data.get("city") country = form.cleaned_data.get("country") room_type = form.cleaned_data.get("room_type") price = form.cleaned_data.get("price") guests = form.cleaned_data.get("guests") bedrooms = form.cleaned_data.get("bedrooms") beds = form.cleaned_data.get("beds") baths = form.cleaned_data.get("baths") instant_book = form.cleaned_data.get("instant_book") superhost = form.cleaned_data.get("superhost") amenities = form.cleaned_data.get("amenities") facilities = form.cleaned_data.get("facilities") filter_args = {} if city != "Anywhere": filter_args["city__startswith"] = city filter_args["country"] = country if room_type is not None: filter_args["room_type"] = room_type if price is not None: filter_args["price__lte"] = price if guests is not None: filter_args["guests__gte"] = guests if bedrooms is not None: filter_args["bedrooms__gte"] = bedrooms if beds is not None: filter_args["beds__gte"] = beds if baths is not None: filter_args["baths__gte"] = baths if instant_book is True: filter_args["instant_book"] = True if superhost is True: filter_args["host__superhost"] = True for amenity in amenities: filter_args["amenities"] = amenity for facility in facilities: filter_args["facilities"] = facility qs = Room.objects.filter(**filter_args).order_by("-created") paginator = Paginator(qs, 10, orphans=5) page = request.GET.get("page", 1) rooms = paginator.get_page(page) return render( request, "rooms/search.html", {"form": form, "rooms": rooms} ) else: form = forms.SearchForm() return render(request, "rooms/search.html", {"form": form}) class EditRoomView(user_mixins.LoggedInOnlyView,UpdateView): model = Room template_name = "rooms/room_edit.html" fields = ( "name", "description", "country", "city", "price", "address", "guests", "beds", "bedrooms", "baths", "check_in", "check_out", "instant_book", "room_type", "amenities", "facilities", "house_rules", ) def get_object(self, queryset=None): room = super().get_object(queryset=queryset) if room.host.pk != self.request.user.pk: raise Http404() return room class RoomPhotosView(user_mixins.LoggedInOnlyView, DetailView): model = Room template_name = "rooms/room_photos.html" def get_object(self, queryset=None): room = super().get_object(queryset=queryset) if room.host.pk != self.request.user.pk: raise Http404() return room @login_required def delete_photo(request, room_pk, photo_pk): user = request.user try: room = Room.objects.get(pk=room_pk) if room.host.pk != user.pk: messages.error(request, "Cant delete that photo") else: Photo.objects.filter(pk=photo_pk).delete() messages.success(request, "Photo Deleted") return redirect(reverse("rooms:photos", kwargs={"pk": room_pk})) except Room.DoesNotExist: return redirect(reverse("core:home")) class EditPhotoView(user_mixins.LoggedInOnlyView, SuccessMessageMixin, UpdateView): model = models.Photo template_name = "rooms/photo_edit.html" pk_url_kwarg = "photo_pk" success_message = "Photo Updated" fields = ("caption",) def get_success_url(self): room_pk = self.kwargs.get("room_pk") return reverse("rooms:photos", kwargs={"pk": room_pk}) class AddPhotoView(user_mixins.LoggedInOnlyView, FormView): template_name = "rooms/photo_create.html" form_class = forms.CreatePhotoForm def form_valid(self, form): pk = self.kwargs.get("pk") form.save(pk) messages.success(self.request, "Photo Uploaded") return redirect(reverse("rooms:photos", kwargs={"pk": pk})) class CreateRoomView(user_mixins.LoggedInOnlyView, FormView): form_class = forms.CreateRoomForm template_name = "rooms/room_create.html" def form_valid(self, form): room = form.save() room.host = self.request.user room.save() form.save_m2m() messages.success(self.request, "Room Uploaded") return redirect(reverse("rooms:detail", kwargs={"pk": room.pk}))
[ "amrebrahem226@gmail.com" ]
amrebrahem226@gmail.com
1137b8d72fb9f4c1d45625d4c93ff119b780a6cf
bb150497a05203a718fb3630941231be9e3b6a32
/models/PaddleHub/hub_all_func/all_module/all_hrnet48_imagenet_ssld.py
4e18dac3eaa0bf62f908389b457657a2fc4cccee
[]
no_license
PaddlePaddle/PaddleTest
4fb3dec677f0f13f7f1003fd30df748bf0b5940d
bd3790ce72a2a26611b5eda3901651b5a809348f
refs/heads/develop
2023-09-06T04:23:39.181903
2023-09-04T11:17:50
2023-09-04T11:17:50
383,138,186
42
312
null
2023-09-13T11:13:35
2021-07-05T12:44:59
Python
UTF-8
Python
false
false
520
py
"""hrnet48_imagenet_ssld""" import os import paddle import paddlehub as hub if paddle.is_compiled_with_cuda(): paddle.set_device("gpu") use_gpu = True else: paddle.set_device("cpu") use_gpu = False def test_hrnet48_imagenet_ssld_predict(): """hrnet48_imagenet_ssld predict""" os.system("hub install hrnet48_imagenet_ssld") model = hub.Module(name="hrnet48_imagenet_ssld") result = model.predict(["doc_img.jpeg"]) print(result) os.system("hub uninstall hrnet48_imagenet_ssld")
[ "noreply@github.com" ]
PaddlePaddle.noreply@github.com
7120ce421c25f5d5078df1119fe035cdf4506131
75dcb56e318688499bdab789262839e7f58bd4f6
/The Complete Data Structures and Algorithms Course in Python/src/Section 18 Cracking Linked List Interview Questions/Q1_RemoveDups.py
179d364fc062a36387c167b262f78109862dcb5d
[]
no_license
syurskyi/Algorithms_and_Data_Structure
9a1f358577e51e89c862d0f93f373b7f20ddd261
929dde1723fb2f54870c8a9badc80fc23e8400d3
refs/heads/master
2023-02-22T17:55:55.453535
2022-12-23T03:15:00
2022-12-23T03:15:00
226,243,987
4
1
null
2023-02-07T21:01:45
2019-12-06T04:14:10
Jupyter Notebook
UTF-8
Python
false
false
1,143
py
# Created by Elshad Karimov on 17/05/2020. # Copyright © 2020 AppMillers. All rights reserved. # Question 1 - Remove Dups : Write a code to remove duplicates from an unsorted linked list. from LinkedList import LinkedList def removeDups(ll): if ll.head is None: return else: currentNode = ll.head visited = set([currentNode.value]) while currentNode.next: if currentNode.next.value in visited: currentNode.next = currentNode.next.next else: visited.add(currentNode.next.value) currentNode = currentNode.next return ll def removeDups1(ll): if ll.head is None: return currentNode = ll.head while currentNode: runner = currentNode while runner.next: if runner.next.value == currentNode.value: runner.next = runner.next.next else: runner = runner.next currentNode = currentNode.next return ll.head customLL = LinkedList() customLL.generate(10, 0, 99) print(customLL) removeDups1(customLL) print(customLL)
[ "sergejyurskyj@yahoo.com" ]
sergejyurskyj@yahoo.com
148e21cdaebd61c3d3edd7f4b8df1223f60239a5
78d160bba37805d9ce1f55a02f17d8923e43fcfc
/learning_resources/models_test.py
d45a238691389f6e87fa206396b2e3b5c1649b6c
[ "BSD-3-Clause" ]
permissive
mitodl/mit-open
a79a4d55533d7abecedda48b62aec23a6b3086f0
51636099fb2bfaa77cd8c2154f7bcb09f3d36f71
refs/heads/main
2023-08-30T19:24:08.426942
2023-08-30T17:03:09
2023-08-30T17:03:09
672,068,771
0
0
BSD-3-Clause
2023-09-14T20:34:23
2023-07-28T20:54:37
Python
UTF-8
Python
false
false
3,884
py
"""Tests for learning_resources.models""" import pytest from learning_resources import constants from learning_resources.constants import LearningResourceType from learning_resources.factories import ( CourseFactory, LearningResourceFactory, LearningResourcePlatformFactory, LearningResourceRunFactory, PlatformTypeChoice, ProgramFactory, ) pytestmark = [pytest.mark.django_db] def test_program_creation(): """Test that a program has associated LearningResource, run, topics, etc""" program = ProgramFactory.create() resource = program.learning_resource assert resource.title is not None assert resource.image.url is not None assert resource.resource_type == LearningResourceType.program.value assert resource.program == program assert program.courses.count() >= 1 run = program.runs.first() assert run.start_date is not None assert run.image.url is not None assert len(run.prices) > 0 assert run.instructors.count() > 0 assert resource.topics.count() > 0 assert resource.offered_by.count() > 0 assert resource.runs.count() == program.runs.count() def test_course_creation(): """Test that a course has associated LearningResource, runs, topics, etc""" course = CourseFactory.create() resource = course.learning_resource assert resource.resource_type == LearningResourceType.course.value assert resource.title is not None assert resource.image.url is not None assert 0 <= len(resource.prices) <= 3 assert resource.course == course run = resource.runs.first() assert run.start_date is not None assert run.image.url is not None assert len(run.prices) > 0 assert run.instructors.count() > 0 assert resource.topics.count() > 0 assert resource.offered_by.count() > 0 assert resource.runs.count() == course.runs.count() @pytest.mark.parametrize( "platform", [PlatformTypeChoice.ocw.value, PlatformTypeChoice.mitx.value] ) @pytest.mark.parametrize("audience", [constants.OPEN, constants.PROFESSIONAL]) def test_lr_audience(platform, audience): """The audience property should return the expected value""" lr = LearningResourceFactory.create( platform=LearningResourcePlatformFactory.create( platform=platform, audience=audience ) ) assert lr.audience == lr.platform.audience @pytest.mark.parametrize( "platform, audience, availability, has_cert", [ [ PlatformTypeChoice.ocw.value, constants.PROFESSIONAL, constants.AvailabilityType.archived.value, True, ], [ PlatformTypeChoice.ocw.value, constants.OPEN, constants.AvailabilityType.archived.value, False, ], [ PlatformTypeChoice.mitx.value, constants.PROFESSIONAL, constants.AvailabilityType.archived.value, True, ], [ PlatformTypeChoice.mitx.value, constants.OPEN, constants.AvailabilityType.archived.value, False, ], [ PlatformTypeChoice.mitx.value, constants.OPEN, constants.AvailabilityType.current.value, True, ], ], ) def test_lr_certification(platform, audience, availability, has_cert): """The certification property should return the expected value""" platform_object = LearningResourcePlatformFactory.create( platform=platform, audience=audience ) course = CourseFactory.create( platform=platform_object, runs=[], ) course.learning_resource.runs.set( [LearningResourceRunFactory.create(availability=availability)] ) assert course.learning_resource.certification == ( constants.CERTIFICATE if has_cert else None )
[ "noreply@github.com" ]
mitodl.noreply@github.com
fdc763851d07a181c2b83e74f4ee362cdc352308
c50e7eb190802d7849c0d0cea02fb4d2f0021777
/src/elastic-san/azext_elastic_san/aaz/latest/elastic_san/_delete.py
683649b4034cb0874134a924fa1b1467b4df0263
[ "LicenseRef-scancode-generic-cla", "MIT" ]
permissive
Azure/azure-cli-extensions
c1615b19930bba7166c282918f166cd40ff6609c
b8c2cf97e991adf0c0a207d810316b8f4686dc29
refs/heads/main
2023-08-24T12:40:15.528432
2023-08-24T09:17:25
2023-08-24T09:17:25
106,580,024
336
1,226
MIT
2023-09-14T10:48:57
2017-10-11T16:27:31
Python
UTF-8
Python
false
false
5,340
py
# -------------------------------------------------------------------------------------------- # 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 aaz-dev-tools # -------------------------------------------------------------------------------------------- # pylint: skip-file # flake8: noqa from azure.cli.core.aaz import * @register_command( "elastic-san delete", is_preview=True, confirmation="Are you sure you want to perform this operation?", ) class Delete(AAZCommand): """Delete an Elastic SAN. :example: Delete an Elastic SAN. az elastic-san delete -g {rg} -n {san_name} """ _aaz_info = { "version": "2022-12-01-preview", "resources": [ ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.elasticsan/elasticsans/{}", "2022-12-01-preview"], ] } AZ_SUPPORT_NO_WAIT = True def _handler(self, command_args): super()._handler(command_args) return self.build_lro_poller(self._execute_operations, None) _args_schema = None @classmethod def _build_arguments_schema(cls, *args, **kwargs): if cls._args_schema is not None: return cls._args_schema cls._args_schema = super()._build_arguments_schema(*args, **kwargs) # define Arg Group "" _args_schema = cls._args_schema _args_schema.elastic_san_name = AAZStrArg( options=["-n", "--name", "--elastic-san-name"], help="The name of the ElasticSan.", required=True, id_part="name", fmt=AAZStrArgFormat( pattern="^[A-Za-z0-9]+((-|_)[a-z0-9A-Z]+)*$", max_length=24, min_length=3, ), ) _args_schema.resource_group = AAZResourceGroupNameArg( required=True, ) return cls._args_schema def _execute_operations(self): self.pre_operations() yield self.ElasticSansDelete(ctx=self.ctx)() self.post_operations() @register_callback def pre_operations(self): pass @register_callback def post_operations(self): pass class ElasticSansDelete(AAZHttpOperation): CLIENT_TYPE = "MgmtClient" def __call__(self, *args, **kwargs): request = self.make_request() session = self.client.send_request(request=request, stream=False, **kwargs) if session.http_response.status_code in [202]: return self.client.build_lro_polling( self.ctx.args.no_wait, session, self.on_200, self.on_error, lro_options={"final-state-via": "location"}, path_format_arguments=self.url_parameters, ) if session.http_response.status_code in [200]: return self.client.build_lro_polling( self.ctx.args.no_wait, session, self.on_200, self.on_error, lro_options={"final-state-via": "location"}, path_format_arguments=self.url_parameters, ) if session.http_response.status_code in [204]: return self.client.build_lro_polling( self.ctx.args.no_wait, session, self.on_204, self.on_error, lro_options={"final-state-via": "location"}, path_format_arguments=self.url_parameters, ) return self.on_error(session.http_response) @property def url(self): return self.client.format_url( "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ElasticSan/elasticSans/{elasticSanName}", **self.url_parameters ) @property def method(self): return "DELETE" @property def error_format(self): return "MgmtErrorFormat" @property def url_parameters(self): parameters = { **self.serialize_url_param( "elasticSanName", self.ctx.args.elastic_san_name, required=True, ), **self.serialize_url_param( "resourceGroupName", self.ctx.args.resource_group, required=True, ), **self.serialize_url_param( "subscriptionId", self.ctx.subscription_id, required=True, ), } return parameters @property def query_parameters(self): parameters = { **self.serialize_query_param( "api-version", "2022-12-01-preview", required=True, ), } return parameters def on_200(self, session): pass def on_204(self, session): pass class _DeleteHelper: """Helper class for Delete""" __all__ = ["Delete"]
[ "noreply@github.com" ]
Azure.noreply@github.com
39969c1880d5f4bd42afe17981b473f757389342
52a15d4fabf68bf23a23799312ae40465764908c
/src/maintenance/dumppreferences.py
963258beee0d9b9d24e4a3c25021bdff41c3da25
[ "MIT", "Apache-2.0" ]
permissive
jensl/critic
2071a1b0600051967323df48f4d3a5656a5d2bb8
c2d962b909ff7ef2f09bccbeb636333920b3659e
refs/heads/stable/1
2022-05-28T03:51:15.108944
2018-03-27T18:47:46
2018-03-29T15:08:30
6,430,552
224
36
NOASSERTION
2023-05-29T15:38:00
2012-10-28T18:26:04
Python
UTF-8
Python
false
false
4,036
py
# -*- mode: python; encoding: utf-8 -*- # # Copyright 2012 Jens Lindström, Opera Software ASA # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. import sys import os.path sys.path.insert(0, os.path.dirname(os.path.dirname(sys.argv[0]))) from dbaccess import connect db = connect() cursor = db.cursor() cursor.execute("SELECT item, type, default_integer, default_string, description FROM preferences") preferences = cursor.fetchall() installpreferences_py = open(os.path.join(os.path.dirname(sys.argv[0]), "installpreferences.py"), "w") print >>installpreferences_py, "PREFERENCES = [ ", for index, (item, type, default_integer, default_string, description) in enumerate(preferences): if index != 0: installpreferences_py.write(""", """) installpreferences_py.write("""{ "item": %r, "type": %r,""" % (item, type)) if type == "string": installpreferences_py.write(""" "default_string": %r,""" % default_string) else: installpreferences_py.write(""" "default_integer": %r,""" % default_integer) installpreferences_py.write(""" "description": %r }""" % description) print >>installpreferences_py, " ]" print >>installpreferences_py print >>installpreferences_py, "def installPreferences(db, quiet):" print >>installpreferences_py, " cursor = db.cursor()" print >>installpreferences_py print >>installpreferences_py, " for preference in PREFERENCES:" print >>installpreferences_py, " item = preference[\"item\"]" print >>installpreferences_py, " type = preference[\"type\"]" print >>installpreferences_py, " default_integer = preference.get(\"default_integer\")" print >>installpreferences_py, " default_string = preference.get(\"default_string\")" print >>installpreferences_py, " description = preference[\"description\"]" print >>installpreferences_py print >>installpreferences_py, " cursor.execute(\"SELECT 1 FROM preferences WHERE item=%s\", (item,))" print >>installpreferences_py print >>installpreferences_py, " if cursor.fetchone():" print >>installpreferences_py, " if not quiet: print \"Updating: %s\" % item" print >>installpreferences_py, " cursor.execute(\"UPDATE preferences SET type=%s, default_integer=%s, default_string=%s, description=%s WHERE item=%s\", (type, default_integer, default_string, description, item))" print >>installpreferences_py, " else:" print >>installpreferences_py, " if not quiet: print \"Adding: %s\" % item" print >>installpreferences_py, " cursor.execute(\"INSERT INTO preferences (item, type, default_integer, default_string, description) VALUES (%s, %s, %s, %s, %s)\", (item, type, default_integer, default_string, description))" print >>installpreferences_py print >>installpreferences_py, "if __name__ == \"__main__\":" print >>installpreferences_py, " import sys" print >>installpreferences_py, " import os.path" print >>installpreferences_py print >>installpreferences_py, " sys.path.insert(0, os.path.dirname(os.path.dirname(sys.argv[0])))" print >>installpreferences_py print >>installpreferences_py, " import dbaccess" print >>installpreferences_py print >>installpreferences_py, " db = dbaccess.connect()" print >>installpreferences_py print >>installpreferences_py, " installPreferences(db, \"--quiet\" in sys.argv or \"-q\" in sys.argv)" print >>installpreferences_py print >>installpreferences_py, " db.commit()"
[ "jl@opera.com" ]
jl@opera.com
78b36772d1120f0b4fc1cc8b334f2d27170c12da
c698fb03aa2bf034904a0310931b473b6da66fdc
/com/study/algorithm/offer/面试题 04.02. 最小高度树.py
cba62dda0a65f8ccc1bc044898548fa4d9b03b0a
[]
no_license
pi408637535/Algorithm
e46df1d07a519ab110e4f97755f461a1b2b7c308
75f4056ec6da01f7466a272871a7f7db579166b4
refs/heads/master
2021-08-29T19:19:53.368953
2021-08-22T16:30:32
2021-08-22T16:30:32
213,289,503
1
0
null
null
null
null
UTF-8
Python
false
false
659
py
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def sortedArrayToBST(self, nums): """ :type nums: List[int] :rtype: TreeNode """ if not nums: return None root = TreeNode(nums[len(nums) // 2] ) root.left = self.sortedArrayToBST(nums[:len(nums) // 2]) root.right = self.sortedArrayToBST(nums[len(nums) // 2 +1:]) return root if __name__ == '__main__': nums = [-10,-3,0,5,9] tree = Solution().sortedArrayToBST(nums) tree
[ "piguanghua@163.com" ]
piguanghua@163.com
47a1919e488e11c462b12e89fd858ceb063b0bc4
9a5438bdb8e84d0167ddea5458a7f729fdd54121
/dataproviders/serializers/EndpointSerializer.py
cdc9b598acdf3c773cfc7c4d32fc9060ea968bde
[]
no_license
Grusinator/MetaDataApi
740fd2be4cb97b670f827a071a0ac8c50f79f8ff
081f881c735466ed1dbbd68646b821299c5168f8
refs/heads/master
2023-07-25T23:58:22.179717
2020-03-15T09:36:05
2020-03-15T09:36:05
149,087,967
5
1
null
2023-07-25T15:39:12
2018-09-17T07:45:09
CSS
UTF-8
Python
false
false
368
py
from rest_framework import serializers from dataproviders.models import Endpoint class EndpointSerializer(serializers.ModelSerializer): class Meta: model = Endpoint exclude = ["id", "data_provider"] def create(self, validated_data): validated_data.pop("data_fetches") return self.Meta.model.objects.create(**validated_data)
[ "grusinator@gmail.com" ]
grusinator@gmail.com
844c09cc9e371c8dfe2d5499cd6f071d91fda930
722de5766ccf7e7a2d63c425a0c8dd78287f1853
/homework7/Ex3.py
7756cb00992285fba8a460dc1fe621d60707ee8a
[]
no_license
Alice-Avetisyan/project
79a61bbd0ce3f5d8571a3c1d112f078f85583e0b
eb51676cdce1ff787738317aacb4c869a001b769
refs/heads/master
2020-07-30T09:04:07.555681
2019-12-15T17:15:05
2019-12-15T17:15:05
210,166,222
0
0
null
null
null
null
UTF-8
Python
false
false
670
py
employees = {'Jack Smith': 'Engineer', 'Hideo Kojima': 'Director', 'Yoji Shinkawa': 'Art_director', 'John Anderson': 'Engineer'} def find_employee(employees): keys = list(employees.keys()) count = 0 for key in keys: if key[:4] == 'John': count += 1 print("There is/are {0} employee/s with the name John".format(count)) def find_engineer(employees): values = list(employees.values()) count = 0 for value in values: if value == 'Engineer': count += 1 print("There is/are {0} employee/s with the Engineer position".format(count)) find_employee(employees) find_engineer(employees)
[ "noreply@github.com" ]
Alice-Avetisyan.noreply@github.com
2f6f7434f4f404d3c911fc7cebf7efb8705a4e22
292d23019c18d0b724aed88f04a0f20b5b616bb9
/date20190110/V3/testcase/test_login.py
33890fbf02875157430929453396eba0ee274ed2
[]
no_license
RedAnanas/macbendi
6f1f6fd41ed1fe8b71408dffa0b964464bd00aa8
8d5aa39d9389937f0e0c3f7a7d6532537f33cda8
refs/heads/master
2023-06-11T18:57:31.061009
2021-06-29T15:04:56
2021-06-29T15:04:56
380,759,110
0
0
null
null
null
null
UTF-8
Python
false
false
1,169
py
#!/usr/bin/env python #-*- coding:utf-8 -*- # author:Administrator # datetime:2019/1/10 20:36 # software: PyCharm from date20190110.V3.common.browser_manager import BrowserManager from date20190110.V3.common.login import Login with open("D:\Python\date20190110\V3\data\login.txt","r") as f: lines = f.readlines() for line in lines: username, password,verifycode= line.strip().split(',') bm = BrowserManager() Login(bm).go_login(username,password,verifycode) if username=="admin" and password=="admin" and verifycode=="0000": logxx =bm.driver.find_element_by_link_text("注销").text if "注销" in logxx: print("case 成功") else: print("case 失败") else: logxx=bm.driver.find_element_by_class_name("bootbox-body").text if username=="admin"and("登录失败" in logxx): print("case 成功") elif verifycode=="1234"and("验证码失效" in logxx): print("case 成功") else: print("case 失败") bm.driver.quit()
[ "1315157388@qq.com" ]
1315157388@qq.com
73cbe5cf938fa4c42f221b7766cf9eff7a249e5e
88332700e893553ed52247b83f7ae8e542e67239
/test/test_livenodesnagiosplugin.py
f65af48119016c5cce45e6333bff12c7b1222c23
[]
no_license
zhuohuwu0603/pylib
3857a8ec3954d09e58c21c14d683bc95cb7f9d23
02b0a343b055dfd6bed4d64c40aa77ed8394c1b2
refs/heads/master
2020-08-12T02:55:35.956301
2019-10-09T23:08:58
2019-10-09T23:08:58
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,593
py
# vim:ts=4:sts=4:sw=4:et # # Author: Hari Sekhon # Date: 2014-09-15 20:49:22 +0100 (Mon, 15 Sep 2014) # # https://github.com/harisekhon/pylib # # License: see accompanying Hari Sekhon LICENSE file # # If you're using my code you're welcome to connect with me on LinkedIn and optionally send me feedback # to help improve or steer this or other code I publish # # https://www.linkedin.com/in/harisekhon # """ # ============================================================================ # # PyUnit Tests for HariSekhon.LiveNodesNagiosPlugin # ============================================================================ # """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import logging import os import sys import unittest libdir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')) sys.path.append(libdir) # pylint: disable=wrong-import-position from harisekhon.utils import log from harisekhon.nagiosplugin import LiveNodesNagiosPlugin class LiveNodesNagiosPluginTester(unittest.TestCase): # must prefix with test_ in order for the tests to be called # Not using assertRaises >= 2.7 and maintaining compatibility with Python 2.6 servers class SubLiveNodesNagiosPlugin(LiveNodesNagiosPlugin): def get_nodecount(self): print("running SubLiveNodesNagiosPlugin().get_nodecount()") def setUp(self): self.plugin = self.SubLiveNodesNagiosPlugin() def test_unknown_exit(self): try: self.plugin.main() raise Exception('LiveNodes plugin failed to terminate') except SystemExit as _: if _.code != 3: raise Exception('LiveNodesNagiosPlugin failed to exit UNKNOWN (3), got exit code {0} instead' .format(_.code)) def test_plugin_abstract(self): # pylint: disable=no-self-use try: LiveNodesNagiosPlugin() # pylint: disable=abstract-class-instantiated raise Exception('failed to raise a TypeError when attempting to instantiate abstract class ' + 'LiveNodesNagiosPlugin') except TypeError as _: pass def main(): # increase the verbosity # verbosity Python >= 2.7 #unittest.main(verbosity=2) log.setLevel(logging.DEBUG) suite = unittest.TestLoader().loadTestsFromTestCase(LiveNodesNagiosPluginTester) unittest.TextTestRunner(verbosity=2).run(suite) if __name__ == '__main__': main()
[ "harisekhon@gmail.com" ]
harisekhon@gmail.com
857994885a60be47a6073d60ecb803208b9d6203
a9e60d0e5b3b5062a81da96be2d9c748a96ffca7
/configurations/i16-config/scripts/diffractometer/calc/Rotations.py
0e9a9194d69dc76b3538e46850b2d5a1c0f31ba7
[]
no_license
openGDA/gda-diamond
3736718596f47607335ada470d06148d7b57526e
bbb64dcfd581c30eddb210c647db5b5864b59166
refs/heads/master
2023-08-16T08:01:11.075927
2023-08-15T16:01:52
2023-08-15T16:01:52
121,757,699
4
1
null
null
null
null
UTF-8
Python
false
false
1,225
py
import java import math from math import * #class Rotations(java.lang.Object): # def __init__(self): # self.rrrr=0.0 def R_x_l(alpha): "@sig public double R_x_l(double alpha)" # phi=phi*pi/180.0 ALPHA=[[1.0, 0.0, 0.0],[0.0, cos(alpha), sin(alpha)], [0.0, -sin(alpha), cos(alpha)]] return ALPHA def R_x_r(alpha): "@sig public double R_x_r(double alpha)" # phi=phi*pi/180.0 ALPHA=[[1.0, 0.0, 0.0],[0.0, cos(alpha),-sin(alpha)], [0.0, sin(alpha), cos(alpha)]] return ALPHA def R_y_r(alpha): "@sig public double R_y_r(double alpha)" ALPHA=[[cos(alpha),0.0, sin(alpha)],[0.0, 1.0, 0.0], [-sin(alpha), 0.0, cos(alpha)]] return ALPHA def R_y_l(alpha): "@sig public double R_z_l(double alpha)" ALPHA=[[cos(alpha),0.0, -sin(alpha)],[0.0, 1.0, 0.0], [sin(alpha), 0.0, cos(alpha)]] return ALPHA def R_z_l(alpha): "@sig public double R_z_l(double alpha)" ALPHA=[[cos(alpha),sin(alpha), 0.0],[-sin(alpha), cos(alpha), 0.0], [0.0, 0.0, 1.0]] return ALPHA def R_z_r(alpha): "@sig public double R_z_r(double alpha)" ALPHA=[[cos(alpha),-sin(alpha), 0.0],[sin(alpha), cos(alpha), 0.0], [0.0, 0.0, 1.0]] return ALPHA
[ "matthew.webber@diamond.ac.uk" ]
matthew.webber@diamond.ac.uk
10e9d60fe572976b31b043e91b1f37ebfe91e3cc
021dcf39f7cfb303ff427d7344026004f9d4cfdd
/bookit/users/models.py
d0d670ddce49d8602444e4a6ff2ca76b0307716c
[ "MIT" ]
permissive
kamranhossain/bookit
dfaca266b93e0ee8a50e88a2a7702a6f5ece35f1
4189a0ed620d7a595de2c113bb3a2d435d66d5f0
refs/heads/master
2021-05-11T23:36:00.630917
2017-08-16T20:30:33
2017-08-16T20:30:33
null
0
0
null
null
null
null
UTF-8
Python
false
false
695
py
from django.contrib.auth.models import AbstractUser from django.core.urlresolvers import reverse from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ @python_2_unicode_compatible class User(AbstractUser): # First Name and Last Name do not cover name patterns # around the globe. name = models.CharField(_('Name of User'), blank=True, max_length=255) def __str__(self): return self.username def name_or_username(self): return self.name or self.username def get_absolute_url(self): return reverse('users:detail', kwargs={'username': self.username})
[ "aniruddha@adhikary.net" ]
aniruddha@adhikary.net
7845b036d7efd63ae70213db83a48143f7ba9111
07e750cb558de03104f7c033286329b69bbdfc23
/Chapter2_TimeFrequency_ShortTime/enframe.py
73b2105d3c4ebfbe12af01200251ac78b583cdb7
[ "MIT" ]
permissive
BarryZM/Python_Speech_SZY
d1e2fb6eadd6b10cfa5a65a622ae73f578d2f6d1
0074ad1d519387a75d5eca42c77f4d6966eb0a0e
refs/heads/master
2023-03-09T21:47:54.465905
2021-03-02T17:21:32
2021-03-02T17:21:32
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,100
py
# 分帧 from scipy.io import wavfile import numpy as np import matplotlib.pyplot as plt def enframe(x, win, inc=None): nx = len(x) if isinstance(win, np.ndarray): nwin = len(win) nlen = nwin # 帧长=窗长 elif isinstance(win, int): nwin = 1 nlen = win # 设置为帧长 if inc is None: inc = nlen nf = (nx - nlen + inc) // inc # 计算帧数 frameout = np.zeros((nf, nlen)) # 初始化 indf = np.multiply(inc, np.array([i for i in range(nf)])) # 设置每帧在x中的位移量位置 for i in range(nf): frameout[i, :] = x[indf[i]:indf[i] + nlen] # 分帧 if isinstance(win, np.ndarray): frameout = np.multiply(frameout, np.array(win)) # 每帧乘以窗函数的值 return frameout if __name__ == '__main__': fs, data = wavfile.read('bluesky3.wav') inc = 100 wlen = 200 en = enframe(data, wlen, inc) i = input('Start frame(i):') i = int(i) tlabel = i plt.figure(figsize=(15, 20)) plt.subplot(4, 1, 1) x = [i for i in range((tlabel - 1) * inc, (tlabel - 1) * inc + wlen)] plt.plot(x, en[tlabel, :]) plt.xlim([(i - 1) * inc + 1, (i + 2) * inc + wlen]) plt.title('(a)The {} Frame Waveform'.format(tlabel)) plt.subplot(4, 1, 2) x = [i for i in range((tlabel + 1 - 1) * inc, (tlabel + 1 - 1) * inc + wlen)] plt.plot(x, en[i + 1, :]) plt.xlim([(i - 1) * inc + 1, (i + 2) * inc + wlen]) plt.title('(b)The {} Frame Waveform'.format(tlabel + 1)) plt.subplot(4, 1, 3) x = [i for i in range((tlabel + 2 - 1) * inc, (tlabel + 2 - 1) * inc + wlen)] plt.plot(x, en[i + 2, :]) plt.xlim([(i - 1) * inc + 1, (i + 2) * inc + wlen]) plt.title('(c)The {} Frame Waveform'.format(tlabel + 2)) plt.subplot(4, 1, 4) x = [i for i in range((tlabel + 3 - 1) * inc, (tlabel + 3 - 1) * inc + wlen)] plt.plot(x, en[i + 3, :]) plt.xlim([(i - 1) * inc + 1, (i + 2) * inc + wlen]) plt.title('(d)The {} Frame Waveform'.format(tlabel + 3)) plt.savefig('images/enframe.png') plt.show() plt.close()
[ "you@example.com" ]
you@example.com
bada7cdd5041895620cc70ad02fc19f09856c9f5
b25e66b3588bad601cc7b0fb5cf0ab5a015e2812
/python_td6/colors.py
50a35127da411b509486472c51a09eafaf335291
[]
no_license
bentoonsmurf/bi423
93f4eb7ce8c4f73fab4bed0ece34113b4bbc757e
ca3aa7b6028b4ae932819e5a8d4e962e23a2aa90
refs/heads/master
2021-01-23T08:09:35.807316
2017-04-25T14:32:30
2017-04-25T14:32:30
80,526,632
0
0
null
null
null
null
UTF-8
Python
false
false
1,677
py
def color(text, **user_styles): styles = { # styles 'reset': '\033[0m', 'bold': '\033[01m', 'disabled': '\033[02m', 'underline': '\033[04m', 'reverse': '\033[07m', 'strike_through': '\033[09m', 'invisible': '\033[08m', # text colors 'fg_black': '\033[30m', 'fg_red': '\033[31m', 'fg_green': '\033[32m', 'fg_orange': '\033[33m', 'fg_blue': '\033[34m', 'fg_purple': '\033[35m', 'fg_cyan': '\033[36m', 'fg_light_grey': '\033[37m', 'fg_dark_grey': '\033[90m', 'fg_light_red': '\033[91m', 'fg_light_green': '\033[92m', 'fg_yellow': '\033[93m', 'fg_light_blue': '\033[94m', 'fg_pink': '\033[95m', 'fg_light_cyan': '\033[96m', # background colors 'bg_black': '\033[40m', 'bg_red': '\033[41m', 'bg_green': '\033[42m', 'bg_orange': '\033[43m', 'bg_blue': '\033[44m', 'bg_purple': '\033[45m', 'bg_cyan': '\033[46m', 'bg_light_grey': '\033[47m' } color_text = '' for style in user_styles: try: color_text += styles[style] except KeyError: raise KeyError('def color: parameter `{}` does not exist'.format(style)) color_text += text return '\033[0m{}\033[0m'.format(color_text) def error(text): return color(text, bold=True, fg_red=True) def warning(text): return color(text, bold=True, fg_orange=True) def success(text): return color(text, bold=True, fg_green=True) def ao(text): return color(text, bold=True, fg_blue=True)
[ "you@example.com" ]
you@example.com
f21f81beb5eb2e2a0a9ad5f5247d386a4eadad56
f3b233e5053e28fa95c549017bd75a30456eb50c
/tyk2_input/42/42-50_MD_NVT_rerun/set_1ns_equi_1.py
c1682e2c05fa1d504664d4e98fb47ce4b66a087c
[]
no_license
AnguseZhang/Input_TI
ddf2ed40ff1c0aa24eea3275b83d4d405b50b820
50ada0833890be9e261c967d00948f998313cb60
refs/heads/master
2021-05-25T15:02:38.858785
2020-02-18T16:57:04
2020-02-18T16:57:04
null
0
0
null
null
null
null
UTF-8
Python
false
false
925
py
import os dir = '/mnt/scratch/songlin3/run/tyk2/L42/MD_NVT_rerun/ti_one-step/42_50/' filesdir = dir + 'files/' temp_equiin = filesdir + 'temp_equi_1.in' temp_pbs = filesdir + 'temp_1ns_equi_1.pbs' lambd = [ 0.00922, 0.04794, 0.11505, 0.20634, 0.31608, 0.43738, 0.56262, 0.68392, 0.79366, 0.88495, 0.95206, 0.99078] for j in lambd: os.system("rm -r %6.5f" %(j)) os.system("mkdir %6.5f" %(j)) os.chdir("%6.5f" %(j)) os.system("rm *") workdir = dir + "%6.5f" %(j) + '/' #equiin eqin = workdir + "%6.5f_equi_1.in" %(j) os.system("cp %s %s" %(temp_equiin, eqin)) os.system("sed -i 's/XXX/%6.5f/g' %s" %(j, eqin)) #PBS pbs = workdir + "%6.5f_1ns_equi_1.pbs" %(j) os.system("cp %s %s" %(temp_pbs, pbs)) os.system("sed -i 's/XXX/%6.5f/g' %s" %(j, pbs)) #top os.system("cp ../42-50_merged.prmtop .") os.system("cp ../0.5_equi_0.rst .") #submit pbs os.system("qsub %s" %(pbs)) os.chdir(dir)
[ "songlin3@msu.edu" ]
songlin3@msu.edu
61f00b19422267995d747b0f748d6fe5b85b1257
a5a99f646e371b45974a6fb6ccc06b0a674818f2
/Validation/RecoParticleFlow/python/caloTauBenchmarkGeneric_cfi.py
cb53cbdcfc487688393622fee092cd1df46a79bb
[ "Apache-2.0" ]
permissive
cms-sw/cmssw
4ecd2c1105d59c66d385551230542c6615b9ab58
19c178740257eb48367778593da55dcad08b7a4f
refs/heads/master
2023-08-23T21:57:42.491143
2023-08-22T20:22:40
2023-08-22T20:22:40
10,969,551
1,006
3,696
Apache-2.0
2023-09-14T19:14:28
2013-06-26T14:09:07
C++
UTF-8
Python
false
false
762
py
import FWCore.ParameterSet.Config as cms #'tauGenJets' caloTauBenchmarkGeneric = cms.EDAnalyzer("GenericBenchmarkAnalyzer", OutputFile = cms.untracked.string('benchmark.root'), InputTruthLabel = cms.InputTag(''), minEta = cms.double(-1), maxEta = cms.double(2.8), recPt = cms.double(10.0), deltaRMax = cms.double(0.3), StartFromGen = cms.bool(True), PlotAgainstRecoQuantities = cms.bool(False), OnlyTwoJets = cms.bool(False), BenchmarkLabel = cms.string( 'CaloTaus' ), InputRecoLabel = cms.InputTag(''), minDeltaEt = cms.double(-100.), maxDeltaEt = cms.double(50.), minDeltaPhi = cms.double(-0.5), maxDeltaPhi = cms.double(0.5), doMetPlots = cms.bool(False) )
[ "giulio.eulisse@gmail.com" ]
giulio.eulisse@gmail.com
7202984ea6bdd4793307700d6d3f9ba888bb1692
4be5c172c84e04c35677f5a327ab0ba592849676
/python/interviewbit/arrays/simple_queries/simple_queries.py
e3d4eaeabebf74094a6312db15aea1592f2a2ba7
[]
no_license
niranjan-nagaraju/Development
3a16b547b030182867b7a44ac96a878c14058016
d193ae12863971ac48a5ec9c0b35bfdf53b473b5
refs/heads/master
2023-04-06T20:42:57.882882
2023-03-31T18:38:40
2023-03-31T18:38:40
889,620
9
2
null
2019-05-27T17:00:29
2010-09-05T15:58:46
Python
UTF-8
Python
false
false
3,221
py
''' https://www.interviewbit.com/problems/simple-queries/ Simple Queries You are given an array A having N integers. You have to perform the following steps in a given order. 1. generate all subarrays of A. 2. take the maximum element from each subarray of A and insert it into a new array G. 3. replace every element of G with the product of their divisors mod 1e9 + 7. 4. sort G in descending order 5. perform Q queries In each query, you are given an integer K, where you have to find the Kth element in G. Note: Your solution will run on multiple test cases so do clear global variables after using them. Input Format The first argument given is an Array A, having N integers. The second argument given is an Array B, where B[i] is the ith query. Output Format Return an Array X, where X[i] will have the answer for the ith query. Constraints 1 <= N <= 1e5 1 <= A[i] <= 1e5 1 <= Q <= 1e5 1 <= k <= (N * (N + 1))/2 For Example Input: A = [1, 2, 4] B = [1, 2, 3, 4, 5, 6] Output: X = [8, 8, 8, 2, 2, 1] Explanation: subarrays of A maximum element ------------------------------------ 1. [1] 1 2. [1, 2] 2 3. [1, 2, 4] 4 4. [2] 2 5. [2, 4] 4 6. [4] 4 original G = [1, 2, 4, 2, 4, 4] after changing every element of G with product of their divisors G = [1, 2, 8, 2, 8, 8] after sorting G in descending order G = [8, 8, 8, 2, 2, 1] ''' import math class Solution: def simple_queries(self, A, B): # Calculate x**y using binary exponentiation in O(logn) time def power(x, y) : res = 1 while y > 0: if (y & 1 == 1): res = (res * x) % 1000000007 y = (y >> 1) % 1000000007 x = (x * x) % 1000000007 return res # return product of its divisors % 1e9+7 def product_of_divisors(subarray_maximum): if not product_cache.has_key(subarray_maximum): # product of divisors of a number can be written as N ^ D/2, # where N is number and D is number of divisors of N. # Count number of divisors -- GeeksforGeeks num_d = 0 i = 1 while i * i <= subarray_maximum : if (subarray_maximum % i == 0) : # If factors are equal, # count only once if (subarray_maximum / i == i) : num_d = num_d + 1 # Otherwise count both else : num_d = num_d + 2 i = i + 1 # Calculate product of divisors prod = power(subarray_maximum, num_d/2) # if num_d is odd, we need to multiply prod by sqrt(subarray_maximum) # for eg, # a^5/2 = a^2 * sqrt(a) if (num_d & 1) == 1: prod = (prod * (int)(math.sqrt(subarray_maximum))) % 1000000007 product_cache[subarray_maximum] = prod return product_cache[subarray_maximum] product_cache = {} n = len(A) G = [] for i in xrange(n): subarray_maximum = A[i] for j in xrange(i, n): subarray_maximum = max(subarray_maximum, A[j]) G.append(product_of_divisors(subarray_maximum)) G.sort(reverse=True) query_answers = [] for query in B: query_answers.append(G[query-1]) return query_answers if __name__ == '__main__': s = Solution() assert s.simple_queries([1,2,4], [1,2,3,4,5,6]) == [8,8,8,2,2,1]
[ "vinithepooh@gmail.com" ]
vinithepooh@gmail.com
95ddec165981568dae2b31d941760a612ec760ab
ab1c920583995f372748ff69d38a823edd9a06af
/shultais_courses/data_types/type_conversion/full_tank_cost.py
a3ff76560da0e4080668d6d3de29664a45c0667c
[]
no_license
adyadyat/pyprojects
5e15f4e33892f9581b8ebe518b82806f0cd019dc
c8f79c4249c22eb9e3e19998d5b504153faae31f
refs/heads/master
2022-11-12T16:59:17.482303
2020-07-04T09:08:18
2020-07-04T09:08:18
265,461,663
0
0
null
null
null
null
UTF-8
Python
false
false
987
py
import sys # Получаем данные. price = float(sys.argv[1]) full = float(sys.argv[2]) busy = float(sys.argv[3]) # Делаем финальный расчет. amount = (full - busy) * price # Выводим результат. print(amount) """ СТОИМОСТЬ ПОЛНОГО БАКА Начинающий разработчик написал программу для расчета стоимости заправки автомобиля до полного бака. Программа принимает три параметра: цену 1 литра бензина, полный объем бензобака и объем уже залитого топлива в бак. Однако программа не работает как было запланировано и выводит неверные данные Исправьте все ошибки в коде. Пример использования: > python program.py 45.2 50 11.7 > 1731.16 """
[ "omorbekov.a@gmail.com" ]
omorbekov.a@gmail.com
79a9f6f9308b9bdc741eb0617b42712e08bbd3a2
98a86ec3182e9eef7e21db734118f15f2514cd5c
/python/pygl/test1.py
63b6d54c074494e0cc7f03575710532256e0a820
[ "MIT" ]
permissive
icefoxen/lang
ad3d4d2bdb162f95416e9d805c29951cc812b6f6
628185020123aabe4753f96c6ab4378637a2dbf5
refs/heads/master
2020-07-03T12:04:05.512367
2017-01-27T18:05:00
2017-01-27T18:05:00
74,171,174
0
0
null
null
null
null
UTF-8
Python
false
false
3,253
py
# Okay. # THANK you. # Now, let's get to hacking Python OpenGL. # Foist, we want to create a shape and move it with da arrow keys. from OpenGL.GL import * from OpenGL.GLU import * import pygame from pygame.locals import * translatex = -1.5 translatey = 0.0 translatez = -6.0 tRot = hRot = 0.0 def setSizeGL( (width, height) ): if height == 0: height = 1 glViewport( 0, 0, width, height ) # Do stuff to projection matrix glMatrixMode( GL_PROJECTION ) glLoadIdentity() # 0.1 and 100.0 are the min and max depth distance gluPerspective( 45, 1.0 * width / height, 0.1, 100.0 ) # Do stuff to model view matrix glMatrixMode( GL_MODELVIEW ) glLoadIdentity() def initGL(): glShadeModel( GL_SMOOTH ) glClearColor( 0.0, 0.0, 0.0, 0.0 ) glClearDepth( 1.0 ) glEnable( GL_DEPTH_TEST ) glDepthFunc( GL_LEQUAL ) glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) def drawGL(): global translatex global translatey global translatez glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ) glLoadIdentity() #glTranslatef( -1.5, 0.0, -6.0 ) #print translatex, translatey, translatez glTranslatef( translatex, translatey, translatez ) global tRot glRotate( tRot, 1.0, 1.0, 0.0 ) glBegin( GL_TRIANGLES ) glColor3f( 1.0, 0.0, 0.0 ) glVertex3f( 0.0, 1.0, 0.0 ) glColor3f( 0.0, 1.0, 0.0 ) glVertex3f( -1.0, -1.0, 0.0 ) glColor3f( 0.0, 0.0, 1.0 ) glVertex3f( 1.0, -1.0, 0.0 ) glEnd() glLoadIdentity() # We make a hexagon! global hRot glTranslatef( 1.5, 0.0, -6.0 ) glRotate( hRot, -1.0, 0.0, 0.0 ) glBegin( GL_POLYGON ) glColor3f( 1.0, 0.0, 0.0 ) glVertex3f( -1.0, 1.0, 0.0 ) glColor3f( 1.0, 1.0, 0.0 ) glVertex3f( 0.0, 2.0, 0.0 ) glColor3f( 0.0, 1.0, 0.0 ) glVertex3f( 1.0, 1.0, 0.0 ) glColor3f( 0.0, 1.0, 1.0 ) glVertex3f( 1.0, -0.0, 0.0 ) glColor3f( 0.0, 0.0, 1.0 ) glVertex3f( 0.0, -1.0, 0.0 ) glColor3f( 1.0, 0.0, 1.0 ) glVertex3f( -1.0, -0.0, 0.0 ) #glVertex3f( -1.0, -2.0, 0.0 ) #glVertex3f( -1.5, -1.0, 0.0 ) glEnd() tRot += 0.2 hRot += 0.2 def main(): global translatex global translatey global translatez videoFlags = OPENGL | DOUBLEBUF screenSize = (640,480) pygame.init() pygame.display.set_mode( screenSize, videoFlags ) setSizeGL( screenSize ) initGL() frames = 0 ticks = pygame.time.get_ticks() while True: event = pygame.event.poll() if event.type == QUIT: break if event.type == KEYDOWN: if event.key == K_RIGHT: translatex += 0.25 elif event.key == K_LEFT: translatex -= 0.25 elif event.key == K_UP: translatey += 0.25 elif event.key == K_DOWN: translatey -= 0.25 elif event.key == K_a: translatez += 0.25 elif event.key == K_z: translatez -= 0.25 drawGL() pygame.display.flip() frames += 1 print "FPS: %d" % ((frames * 1000) / (pygame.time.get_ticks() - ticks)) if __name__ == '__main__': main()
[ "icefoxen@gmail.com" ]
icefoxen@gmail.com
08f4a816cfb1b292a9d05ce8682450615698b86a
ac0894b411507bfd027696b6bf11b5e384ed68fc
/need-to-do/python3------download-problem--of--leetcode/518.coin-change-2.py
bb27135b95f304b145ea54cd5c448d0346f160c8
[]
no_license
mkzpd/leetcode-solution
1d19554628c34c74012fa52582c225e6dccb345c
60c9b218683bcdee86477a910c58ec702185c726
refs/heads/master
2020-05-31T05:56:48.985529
2019-09-20T09:10:49
2019-09-20T09:10:49
190,128,627
0
0
null
null
null
null
UTF-8
Python
false
false
1,170
py
# # @lc app=leetcode id=518 lang=python3 # # [518] Coin Change 2 # # https://leetcode.com/problems/coin-change-2/description/ # # algorithms # Medium (44.22%) # Total Accepted: 56.2K # Total Submissions: 127.1K # Testcase Example: '5\n[1,2,5]' # # You are given coins of different denominations and a total amount of money. # Write a function to compute the number of combinations that make up that # amount. You may assume that you have infinite number of each kind of # coin. # # # # # # # Example 1: # # # Input: amount = 5, coins = [1, 2, 5] # Output: 4 # Explanation: there are four ways to make up the amount: # 5=5 # 5=2+2+1 # 5=2+1+1+1 # 5=1+1+1+1+1 # # # Example 2: # # # Input: amount = 3, coins = [2] # Output: 0 # Explanation: the amount of 3 cannot be made up just with coins of 2. # # # Example 3: # # # Input: amount = 10, coins = [10] # Output: 1 # # # # # Note: # # You can assume that # # # 0 <= amount <= 5000 # 1 <= coin <= 5000 # the number of coins is less than 500 # the answer is guaranteed to fit into signed 32-bit integer # # # class Solution: def change(self, amount: int, coins: List[int]) -> int:
[ "sodgso262@gmail.com" ]
sodgso262@gmail.com
5a18ecad0b7d2b084aa63bc977407eed2c5e79a6
09e57dd1374713f06b70d7b37a580130d9bbab0d
/data/p2DJ/New/R2/benchmark/startQiskit_QC108.py
b2ba0c7d4c4750e3ffdad273d797ff0ae74a0d0c
[ "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
3,068
py
# qubit number=2 # total number=9 import cirq import qiskit from qiskit import IBMQ from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import BasicAer, execute, transpile from pprint import pprint from qiskit.test.mock import FakeVigo from math import log2,floor, sqrt, pi import numpy as np import networkx as nx def build_oracle(n: int, f) -> QuantumCircuit: # implement the oracle O_f^\pm # NOTE: use U1 gate (P gate) with \lambda = 180 ==> CZ gate # or multi_control_Z_gate (issue #127) controls = QuantumRegister(n, "ofc") target = QuantumRegister(1, "oft") oracle = QuantumCircuit(controls, target, name="Of") for i in range(2 ** n): rep = np.binary_repr(i, n) if f(rep) == "1": for j in range(n): if rep[j] == "0": oracle.x(controls[j]) oracle.mct(controls, target[0], None, mode='noancilla') for j in range(n): if rep[j] == "0": oracle.x(controls[j]) # oracle.barrier() # oracle.draw('mpl', filename='circuit/deutsch-oracle.png') return oracle def make_circuit(n:int,f) -> QuantumCircuit: # circuit begin input_qubit = QuantumRegister(n, "qc") target = QuantumRegister(1, "qt") prog = QuantumCircuit(input_qubit, target) # inverse last one (can be omitted if using O_f^\pm) prog.x(target) # apply H to get superposition for i in range(n): prog.h(input_qubit[i]) prog.h(input_qubit[1]) # number=1 prog.h(input_qubit[1]) # number=4 prog.h(target) prog.barrier() # apply oracle O_f oracle = build_oracle(n, f) prog.append( oracle.to_gate(), [input_qubit[i] for i in range(n)] + [target]) # apply H back (QFT on Z_2^n) for i in range(n): prog.h(input_qubit[i]) prog.barrier() # measure #for i in range(n): # prog.measure(input_qubit[i], classicals[i]) prog.x(input_qubit[1]) # number=2 prog.y(input_qubit[1]) # number=5 prog.cx(input_qubit[0],input_qubit[1]) # number=6 prog.x(input_qubit[1]) # number=7 prog.cx(input_qubit[0],input_qubit[1]) # number=8 # circuit end return prog if __name__ == '__main__': n = 2 f = lambda rep: rep[-1] # f = lambda rep: "1" if rep[0:2] == "01" or rep[0:2] == "10" else "0" # f = lambda rep: "0" prog = make_circuit(n, f) sample_shot =2800 IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') provider.backends() backend = provider.get_backend("ibmq_belem") circuit1 = transpile(prog,FakeVigo()) circuit1.x(qubit=3) circuit1.x(qubit=3) circuit1.measure_all() prog = circuit1 info = execute(prog, backend=backend, shots=sample_shot).result().get_counts() writefile = open("../data/startQiskit_QC108.csv","w") print(info,file=writefile) print("results end", file=writefile) print(circuit1.depth(),file=writefile) print(circuit1,file=writefile) writefile.close()
[ "wangjiyuan123@yeah.net" ]
wangjiyuan123@yeah.net
beeb0da85923f1b285686879a18c74bd2d14ecba
44cb2643ec3474eebcd1015108e074e73b318c07
/hike_schedule/admin.py
782deaf69f4a47c6c521c43ac08bda403daa77b3
[]
no_license
kdechant/hike-schedule
010211b6b23c8e129e812710468c458c74bf5cef
95a0653145d19e992025bbecb6f1d95423a26450
refs/heads/master
2021-01-10T08:52:40.940894
2016-02-12T07:05:29
2016-02-12T07:05:29
44,289,843
0
1
null
null
null
null
UTF-8
Python
false
false
594
py
from django.contrib import admin from .models import * @admin.register(EventType) class EventTypeAdmin(admin.ModelAdmin): list_display = ['name'] @admin.register(Event) class EventAdmin(admin.ModelAdmin): list_display = ['event_type', 'title', 'event_date', 'status'] list_filter = ['event_type', 'route_id', 'leaders'] @admin.register(Area) class AreaAdmin(admin.ModelAdmin): list_display = ['name'] @admin.register(Route) class RouteAdmin(admin.ModelAdmin): list_display = ['name', 'distance', 'elevation_gain', 'favorite'] list_filter = ['area_id', 'favorite']
[ "keith.dechant@gmail.com" ]
keith.dechant@gmail.com
13df13c4bfbd6372e9b6e913d210ced255442e76
575cd8511fde538c3912e7ff33dea2a10f195f25
/portfolio/views.py
4b991c0bcff6b6c493393a8a1570ba2955b0b518
[]
no_license
jakiiii/jqurity.com
710959e07bb115d3178c72891bd92f7d377964c5
fc7119c258fdbed1deaddbf56ebacfc293c470e8
refs/heads/master
2020-04-11T17:24:25.643981
2018-12-16T18:30:48
2018-12-16T18:30:48
161,959,589
1
0
null
null
null
null
UTF-8
Python
false
false
1,382
py
from django.urls import reverse_lazy from django.views.generic import DetailView, CreateView from django.views.generic.edit import FormMixin from contact.forms import ContactForm from .models import ( Slider, Ayat, Experience, Familiar, Interest, Portfolio ) from about.models import ( AboutModel, SocialModel ) # Create your views here. class PortfolioView(CreateView): form_class = ContactForm template_name = 'portfolio/portfolio.html' success_url = reverse_lazy('portfolio') def get_object(self, queryset=None): return self.request.user def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['title'] = 'Portfolio' context['slider_info'] = Slider.objects.all()[:1] context['al_Quran_verse'] = Ayat.objects.all()[:1] context['about_info'] = AboutModel.objects.all()[:1] context['social_link'] = SocialModel.objects.all()[:1] context['experience_info'] = Experience.objects.all() context['familiar_info'] = Familiar.objects.all() context['interest_info'] = Interest.objects.all() context['portfolio_info'] = Portfolio.objects.all()[:8] return context def form_valid(self, form): instance = form.save(commit=True) print(instance) return super().form_valid(form)
[ "me.jaki@outlook.com" ]
me.jaki@outlook.com
3f872bd081b1053662722f47e8bd43eb38def392
be73248aa4f1171e81b65cf955c4bd6110d56095
/plugins/__init__.py
f6a247f3cb53e13670b4621dc27bc7acf3d1692d
[]
no_license
rogerhoward/lambot
781c158e58bd71e2f3eb480aab31f181aee55e62
d5588041fc92b779ba88479d8657f9b8a4916692
refs/heads/development
2022-02-18T05:03:23.911978
2017-06-22T03:22:11
2017-06-22T03:22:11
86,493,856
1
1
null
2022-02-04T15:04:55
2017-03-28T18:30:43
Python
UTF-8
Python
false
false
170
py
from pluginbase import PluginBase plugin_source = PluginBase(package='plugins').make_plugin_source(searchpath=['./plugins']) plugin_names = plugin_source.list_plugins()
[ "rogerhoward@mac.com" ]
rogerhoward@mac.com
03b17a1ec30dbc3ca1b0a583753b6290d482c239
73320add14214fa860e9dfdd6ea4dfa3862f7806
/Logistic/logistic.py
51485f84bc4585d084b96a7166bcd9167422d091
[]
no_license
mayk93/DeepLearning
5aa52df3175f38f5b7fa95f33f929ac937409770
d7db13f5a46b3abb853dab9a4469f81386f27109
refs/heads/master
2020-07-02T14:30:05.542467
2016-11-20T21:33:15
2016-11-20T21:33:15
74,298,459
0
0
null
null
null
null
UTF-8
Python
false
false
3,536
py
import tensorflow as tf import numpy as np try: from tqdm import tqdm except ImportError: def tqdm(x, *args, **kwargs): return x # Load data data = np.load('data_with_labels.npz') train = data['arr_0']/255. labels = data['arr_1'] # Look at some data print(train[0]) print(labels[0]) # If you have matplotlib installed import matplotlib.pyplot as plt plt.ion() # Let's look at a subplot of one of A in each font f, plts = plt.subplots(5, sharex=True) c = 91 for i in range(5): plts[i].pcolor(train[c + i * 558], cmap=plt.cm.gray_r) def to_onehot(labels,nclasses = 5): ''' Convert labels to "one-hot" format. >>> a = [0,1,2,3] >>> to_onehot(a,5) array([[ 1., 0., 0., 0., 0.], [ 0., 1., 0., 0., 0.], [ 0., 0., 1., 0., 0.], [ 0., 0., 0., 1., 0.]]) ''' outlabels = np.zeros((len(labels),nclasses)) for i,l in enumerate(labels): outlabels[i,l] = 1 return outlabels onehot = to_onehot(labels) # Split data into training and validation indices = np.random.permutation(train.shape[0]) valid_cnt = int(train.shape[0] * 0.1) test_idx, training_idx = indices[:valid_cnt],\ indices[valid_cnt:] test, train = train[test_idx,:],\ train[training_idx,:] onehot_test, onehot_train = onehot[test_idx,:],\ onehot[training_idx,:] sess = tf.InteractiveSession() # These will be inputs ## Input pixels, flattened x = tf.placeholder("float", [None, 1296]) ## Known labels y_ = tf.placeholder("float", [None,5]) # Variables W = tf.Variable(tf.zeros([1296,5])) b = tf.Variable(tf.zeros([5])) # Just initialize sess.run(tf.initialize_all_variables()) # Define model y = tf.nn.softmax(tf.matmul(x,W) + b) ### End model specification, begin training code # Climb on cross-entropy cross_entropy = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits( y + 1e-50, y_)) # How we train train_step = tf.train.GradientDescentOptimizer( 0.1).minimize(cross_entropy) # Define accuracy correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1)) accuracy = tf.reduce_mean(tf.cast( correct_prediction, "float")) # Actually train epochs = 1000 train_acc = np.zeros(epochs//10) test_acc = np.zeros(epochs//10) for i in tqdm(range(epochs)): # Record summary data, and the accuracy if i % 10 == 0: # Check accuracy on train set A = accuracy.eval(feed_dict={ x: train.reshape([-1,1296]), y_: onehot_train}) train_acc[i//10] = A # And now the validation set A = accuracy.eval(feed_dict={ x: test.reshape([-1,1296]), y_: onehot_test}) test_acc[i//10] = A train_step.run(feed_dict={ x: train.reshape([-1,1296]), y_: onehot_train}) # Notice that accuracy flattens out print(train_acc[-1]) print(test_acc[-1]) # Plot the accuracy curves plt.plot(train_acc,'bo') plt.plot(test_acc,'rx') # Look at a subplot of the weights for each font f, plts = plt.subplots(5, sharex=True) for i in range(5): plts[i].pcolor(W.eval()[:,i].reshape([36,36])) plt.savefig("test.png") plt.show() # import matplotlib.pyplot as plt # import numpy as np # # t = np.arange(0.0, 2.0, 0.01) # s = np.sin(2*np.pi*t) # plt.plot(t, s) # # plt.xlabel('time (s)') # plt.ylabel('voltage (mV)') # plt.title('About as simple as it gets, folks') # plt.grid(True) # plt.savefig("test.png") # plt.show()
[ "mihai.mandrescu@gmail.com" ]
mihai.mandrescu@gmail.com
a97ae738d52d67ff57849264badfff4ac984c976
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03006/s651349603.py
ab084aa71596b708f5dc27efe7169f4f7b9f0fe0
[]
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
925
py
# ベクトルを固定して全探索まではわかる 実装がわからん # いやべつに順番は関係ないのか? 「残っているボールを 1つ選んで回収する。」 n = int(input()) if n == 1: print(1) # 「ただし、1つ目に選んだボールについては必ずコスト 1かかる。」 exit() points = [] for _ in range(n): points.append(list(map(int, input().split()))) ans = 10**18 for p in range(n): for q in range(n): if p == q: continue vector = [points[p][0] - points[q][0], points[p][1] - points[q][1]] tmp = 0 for i in range(n): for j in range(n): if i == j: continue if points[i][0] - points[j][0] == vector[ 0] and points[i][1] - points[j][1] == vector[1]: tmp += 1 ans = min(ans, n - tmp) print(ans)
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
99f9d3e10ae4a78ea585e3d71cd708bc9bcf35ba
f282ed1fa6776b52d0b11a375067c9c2e1ef2db3
/qsome/ext_methods/ext_factory.py
3b56d2a11095de73a08fb47949efb3b5de0f778d
[ "Apache-2.0" ]
permissive
Goodpaster/QSoME
fc96d87fecab3c13771121b3986f3fc909e8c8b5
7f95524665602821c9b1030cebe2e97af057c056
refs/heads/master
2022-06-16T03:45:08.893218
2022-03-09T21:47:16
2022-03-09T21:47:16
150,792,671
8
2
Apache-2.0
2021-08-16T14:24:54
2018-09-28T20:43:54
Python
UTF-8
Python
false
false
1,015
py
from qsome.ext_methods.molpro_ext import MolproExt from qsome.ext_methods.openmolcas_ext import OpenMolCASExt from qsome.ext_methods.psi4_ext import Psi4Ext #from ext_methods.bagel_ext import BagelExt class ExtFactory: def get_ext_obj(self, ext_prgm, mol_obj, method_name, ext_pot, core_ham=None, filename='temp', work_dir=None, scr_dir=None, nproc=None, pmem=None, save_orbs=False, save_density=False, hl_dict=None, hl_excited_dict=None): if ext_prgm == 'molpro': return MolproExt(mol_obj, method_name, ext_pot, core_ham, filename, work_dir, scr_dir, nproc, pmem, save_orbs, save_density, hl_dict) elif ext_prgm == 'molcas' or ext_prgm == 'openmolcas': return OpenMolCASExt(mol_obj, method_name, ext_pot) #elif ext_prgm == 'bagel': # return BagelExt(mol_obj, method_name, ext_pot) elif ext_prgm == 'psi4': return Psi4Ext(mol_obj, method_name, ext_pot, core_ham, filename, work_dir, scr_dir, nproc, pmem, hl_dict, hl_excited_dict)
[ "dan.s.graham@gmail.com" ]
dan.s.graham@gmail.com
2a24c302a4ffc32edf996f5e2b129bfaa4593284
af4d80ad935f1aedae6e43bc39def7c58bedd332
/benchdev/config.py
715f49c5a01cbde4ce3fc3b2467df9a0a7eb8217
[ "LicenseRef-scancode-hdf5", "LicenseRef-scancode-generic-cla", "BSD-2-Clause" ]
permissive
Qi-max/automatminer
39a96d63a7235870401fde4e34a8ab47d8bfbf6c
a366709798c5886350f5b71cc7d06f474122c2f3
refs/heads/master
2020-05-02T17:00:11.506603
2019-03-27T22:45:11
2019-03-27T22:45:11
178,085,605
1
0
NOASSERTION
2019-03-27T22:43:34
2019-03-27T22:43:33
null
UTF-8
Python
false
false
3,730
py
""" The environment variables you need for this all to work are: - AMM_BENCH_DIR: where to store benchmarks - AMM_DATASET_DIR: where to store datasets - AMM_CODE_DIR: where to run tests """ from fireworks import LaunchPad from automatminer.utils.ml import AMM_CLF_NAME, AMM_REG_NAME from hmte.db import get_connection # Private production LP = get_connection("hackingmaterials", write=True, connection_type="launchpad") # Debugging locally # LP = LaunchPad(name="automatminer") # Constants for running benchmarks and builds KFOLD_DEFAULT = {"shuffle": True, "random_state": 18012019, "n_splits": 5} RUN_TESTS_CMD = "cd $AMM_CODE_DIR && coverage run setup.py test" EXPORT_COV_CMD = "coverage xml && python-codacy-coverage -r coverage.xml" # Local testing configuration... LOCAL_DEBUG_REG = { "name": "debug_local_reg", "data_pickle": "jdft2d_smalldf.pickle.gz", "target": "exfoliation_en", "problem_type": AMM_REG_NAME, "clf_pos_label": None } LOCAL_DEBUG_CLF = { "name": "debug_local_clf", "data_pickle": "expt_gaps_smalldf.pickle.gz", "target": "is_metal", "problem_type": AMM_CLF_NAME, "clf_pos_label": True } LOCAL_DEBUG_SET = [LOCAL_DEBUG_CLF, LOCAL_DEBUG_REG] # Real benchmark sets BULK = { "name": "mp_bulk", "data_pickle": "elasticity_K_VRH.pickle.gz", "target": "K_VRH", "problem_type": AMM_REG_NAME, "clf_pos_label": None } SHEAR = { "name": "mp_shear", "data_pickle": "elasticity_G_VRH.pickle.gz", "target": "G_VRH", "problem_type": AMM_REG_NAME, "clf_pos_label": None } LOG_BULK = { "name": "mp_log_bulk", "data_pickle": "elasticity_log10(K_VRH).pickle.gz", "target": "log10(K_VRH)", "problem_type": AMM_REG_NAME, "clf_pos_label": None } LOG_SHEAR = { "name": "mp_log_shear", "data_pickle": "elasticity_log10(G_VRH).pickle.gz", "target": "log10(G_VRH)", "problem_type": AMM_REG_NAME, "clf_pos_label": None } REFRACTIVE = { "name": "refractive_index", "data_pickle": "dielectric.pickle.gz", "target": "n", "problem_type": AMM_REG_NAME, "clf_pos_label": None } JDFT2D = { "name": "jdft2d", "data_pickle": "jdft2d.pickle.gz", "target": "exfoliation_en", "problem_type": AMM_REG_NAME, "clf_pos_label": None } MP_GAP = { "name": "mp_gap", "data_pickle": "mp_gap.pickle.gz", "target": "gap pbe", "problem_type": AMM_REG_NAME, "clf_pos_label": None } MP_IS_METAL = { "name": "mp_is_metal", "data_pickle": "mp_is_metal.pickle.gz", "target": "is_metal", "problem_type": AMM_CLF_NAME, "clf_pos_label": True } MP_E_FORM = { "name": "mp_e_form", "data_pickle": "mp_e_form.pickle.gz", "target": "e_form", "problem_type": AMM_REG_NAME, "clf_pos_label": None } CASTELLI_E_FORM = { "name": "castelli", "data_pickle": "castelli.pickle.gz", "target": "e_form", "problem_type": AMM_REG_NAME, "clf_pos_label": None } GFA = { "name": "glass_formation", "data_pickle": "glass.pickle.gz", "target": "gfa", "problem_type": AMM_CLF_NAME, "clf_pos_label": True } EXPT_IS_METAL = { "name": "expt_is_metal", "data_pickle": "expt_gaps.pickle.gz", "target": "is_metal", "problem_type": AMM_CLF_NAME, "clf_pos_label": True } PHONONS = { "name": "phonons", "data_pickle": "phonons.pickle.gz", "target": "last phdos peak", "problem_type": AMM_REG_NAME, "clf_pos_label": None } BENCHMARK_DEBUG_SET = [JDFT2D, PHONONS, EXPT_IS_METAL] BENCHMARK_FULL_SET = [BULK, SHEAR, LOG_BULK, LOG_SHEAR, REFRACTIVE, JDFT2D, MP_GAP, MP_IS_METAL, MP_E_FORM, CASTELLI_E_FORM, GFA, EXPT_IS_METAL, PHONONS]
[ "ardunn@lbl.gov" ]
ardunn@lbl.gov
cb84e3be8cebdfd17fa883614c4b5d74c60c74ef
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03387/s553318326.py
2e8b35e38961aeb83e521ce2f6135fcdf35594fd
[]
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
380
py
# coding=utf-8 import math if __name__ == '__main__': A, B, C = map(int, input().split()) MV = max(A, B, C) * 3 SumABC = A + B + C if MV % 2 == 0 and SumABC % 2 == 0: ans = (MV - SumABC) / 2 elif MV % 2 == 1 and SumABC % 2 == 1: ans = math.ceil(MV - SumABC) / 2 else: ans = math.ceil((MV - SumABC) / 2) + 1 print(int(ans))
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
061f3b653e2531aaab6be7deac110e76ea9b4b75
9a3262882123a0937d5b713919688ba7c580ae9f
/eslearn/visualization/lc_scatterplot.py
bba48c93e72b3c2f8a6240a8987344545dda8ac5
[ "MIT" ]
permissive
sysunwenbo/easylearn
fa7f6dd6cf2e0e66780469dc7046b46e486574fd
145274cb374c0337b7ec5aed367841663c527a6f
refs/heads/master
2022-04-18T00:16:56.263547
2020-04-16T15:45:07
2020-04-16T15:45:07
256,792,139
0
1
MIT
2020-04-18T15:49:10
2020-04-18T15:49:09
null
UTF-8
Python
false
false
2,569
py
# -*- coding: utf-8 -*- """ Created on Tue Jul 3 15:29:02 2018 sns.set(stynamele='ticks', palette='muted', color_codes=True, font_scale=1.5) sns.set_stynamele('dark') 主题 stynamele:darkgrid, whitegrid, dark, white, ticks,默认为darkgrid。 sns.set_palette:deep, muted, bright, pastel, dark, colorblind sns.set_contexnamet('notebook', rc={'lines.linewidth':1.5}) sns.despine(): 对于白底(white,whitegrid)以及带刻度(ticks)而言,顶部的轴是不需要的,默认为去掉顶部的轴; sns.despine(left=True):去掉左部的轴,也即 yname 轴; 注意这条语句要放在 plot 的动作之后,才会起作用; @author: li chao """ # 载入绘图模块 import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import numpy as np # 散点图和拟合直线 以及分布 def scatter_LC(df, x='x', y='y', color='g', marker='o'): sns.set(context='paper', style='whitegrid', palette='colorblind', font='sans-serif',font_scale=1, color_codes=False, rc=None) # sns.JointGrid(data=df, x=x, y=y).plot(sns.regplot, sns.distplot) sns.regplot(data=df, x=x, y=y, fit_reg=1, color=color, marker=marker) # set ax = plt.gca() sns.despine() xticklabel = ax.get_xticklabels() yticklabel = ax.get_yticklabels() xlabel = ax.get_xlabel() ylabel = ax.get_ylabel() plt.setp(xticklabel, size=10,rotation=0, horizontalalignment='right') plt.setp(yticklabel, size=10,rotation=0, horizontalalignment='right') plt.xlabel(xlabel, size=15, rotation=0) plt.ylabel(ylabel, size=15, rotation=0) # plt.show() if __name__ == "__main__": plt.figure(figsize=(10,8)) signal_p = r'D:\WorkStation_2018\Workstation_Old\Workstation_2019_Insomnia_caudate_GCA\GCA\Y2X\ROISignals_T2\ROISignals_ROISignal_patients.txt' signal_c = r'D:\WorkStation_2018\Workstation_Old\Workstation_2019_Insomnia_caudate_GCA\GCA\Y2X\ROISignals_T2\ROISignals_ROISignal_controls.txt' s = r'D:\WorkStation_2018\Workstation_Old\Workstation_2019_Insomnia_caudate_GCA\GCA\Y2X\ROISignals_T2\sas.txt' df_signal_p = pd.read_csv(signal_p,header=None) df_signal_c = pd.read_csv(signal_c, header=None) df_scale = pd.read_csv(s,header=None) df = pd.concat([df_signal_p,df_signal_c],axis=0) dia = np.hstack([np.zeros(31,), np.ones(47,)]) df['dia'] = pd.DataFrame(dia) df = pd.concat([df_signal_p,df_scale],axis=1) df.columns = ['x','y'] scatter_LC(df, 'x', 'y', color='#008B8B', marker='o') plt.show() plt.savefig('pDMN_sas.tif', dpi=600)
[ "you@example.com" ]
you@example.com
b3d4d7e07e5de3d880910b6037db32cf7729422c
71fafe9fb2190b6acf09f109105ca362bb9018c2
/jcsbms/lottery/migrations/0007_auto_20160426_1919.py
9c521e85586a5c412a25d51a1cb6aada2a875126
[]
no_license
zhangyibo007/bms
1f43ca98057a72f1b62769719cb4aefbb4ffb289
1ae88e90415f0495d3a647112de0876da0b18e5e
refs/heads/master
2021-06-21T05:40:24.468473
2017-08-02T12:35:08
2017-08-02T12:35:08
null
0
0
null
null
null
null
UTF-8
Python
false
false
873
py
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-04-26 11:19 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('lottery', '0006_auto_20151223_1530'), ] operations = [ migrations.CreateModel( name='TeamName', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('cup_name', models.CharField(max_length=16)), ('original_name', models.CharField(max_length=16)), ('stand_name', models.CharField(max_length=16, null=True)), ], ), migrations.AlterUniqueTogether( name='teamname', unique_together=set([('cup_name', 'original_name')]), ), ]
[ "zhangyibo@caifuzhinan.com" ]
zhangyibo@caifuzhinan.com
640284a8f9ab1215ae55d163b7b3ebdf170c1771
d032bc0c01a7cd598481644e22043de8df4c71c4
/consultad/routing.py
6c3b0ea360f97d12db2ccd7bfdf474c4dd9c66f3
[]
no_license
amrit-kumar/project-for-engineering
eb5f410cd2f0a271633fb6c24132a36e6215f0e0
7e975866e540ab4625e735009fdba971df74e393
refs/heads/master
2020-12-03T01:49:02.429186
2017-06-30T09:09:46
2017-06-30T09:09:46
95,863,800
0
1
null
null
null
null
UTF-8
Python
false
false
762
py
from channels.routing import route # from consultant_app.consumers import ws_add, ws_message, ws_disconnect from consultant_app.consumers import ws_connect, ws_message, ws_disconnect,repeat_me from consultant_app.consumers import ws_message from django.conf.urls import url,include # channel_routing = [ # route("http.request", "consultant_app.consumers.http_consumer"), # ] channel_routing = [ route("websocket.connect", ws_connect,path=r"^/chat"), route("websocket.receive", ws_message,path=r"^/chat"), route("websocket.disconnect", ws_disconnect), route("repeat-me", repeat_me), ] # inner_routes = [ # route("websocket.connect", repeat_me, path=r'^/stream/'), # ] # routing = [ # include(inner_routes, path=r'^/repeat_me') # ]
[ "kumaramrit38@gmail.com" ]
kumaramrit38@gmail.com
802e8ff796848053362c0ffc27d0950a0150d1ef
e415323eec1a2dd547d988465c9174355b4a4f4c
/setup.py
5fd8e98a10a230dea5667ce80ca3c3001218f4f6
[ "MIT" ]
permissive
mjuenema/micropython-bitstring
5e87d054d445ee0368acfe4e01c90dfa79245016
500c5fe987e7205dd9f937b5d5e0a8f4505a1f11
refs/heads/master
2021-01-21T22:06:12.469623
2017-06-26T13:33:34
2017-06-26T13:33:34
95,167,519
3
0
null
null
null
null
UTF-8
Python
false
false
1,418
py
from ubitstring import __version__ import sys # Remove current dir from sys.path, otherwise setuptools will peek up our # module instead of system's. sys.path.pop(0) from setuptools import setup sys.path.append("..") kwds = {'long_description': open('README.rst').read()} if sys.version_info[0] < 2: raise Exception('This version of bitstring needs Python 3 or later.') setup(name='micropython-bitstring', version=__version__, description="Very stripped down version of Scrott Griffith's Bitstring package.", author='Markus Juenemann', author_email='markus@juenemann.net', url='https://github.com/mjuenema/micropython-bitstring', download_url='https://pypi.python.org/pypi/micropython-bitstring/', license='The MIT License: http://www.opensource.org/licenses/mit-license.php', py_modules=['ubitstring'], platforms='all', classifiers = [ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: Implementation :: MicroPython', 'Topic :: Software Development :: Libraries :: Python Modules' ], install_requires=['micropython-copy','micropython-binascii','micropython-struct','micropython-types'], **kwds )
[ "markus@juenemann.net" ]
markus@juenemann.net
fa210d6b01ae3ecaabdd4162852c0f7eb986306f
34f365117eb1d846fa922c24f3fc650188ce9746
/bin/bed2removeNeighbors.py
cd193585aa637fee5aa5499c7c8172c90c2db7fb
[ "MIT" ]
permissive
PinarSiyah/NGStoolkit
53ac6d87a572c498414a246ae051785b40fbc80d
b360da965c763de88c9453c4fd3d3eb7a61c935d
refs/heads/master
2021-10-22T04:49:51.153970
2019-03-08T08:03:28
2019-03-08T08:03:28
null
0
0
null
null
null
null
UTF-8
Python
false
false
363
py
#!/usr/bin/env python import argparse import bed PARSER = argparse.ArgumentParser(description='removes neighboring intervals') PARSER.add_argument('-i', required=True, help='input') PARSER.add_argument('-d', required=True, help='neighbor distance') ARGS = PARSER.parse_args() bedFile = ARGS.i distance = int(ARGS.d) bed.bed(bedFile).removeNeighbors(distance)
[ "adebali@users.noreply.github.com" ]
adebali@users.noreply.github.com
e10b665b0f221ffa1d49d77e5e8df9c3f842961c
8997a0bf1e3b6efe5dd9d5f307e1459f15501f5a
/get_dir_total_size__examples/get_dir_total_size__using__os_walk.py
aca823f1b36c9c1fb9b74ad826f6c01cf9aca6fc
[ "CC-BY-4.0" ]
permissive
stepik/SimplePyScripts
01092eb1b2c1c33756427abb2debbd0c0abf533f
3259d88cb58b650549080d6f63b15910ae7e4779
refs/heads/master
2023-05-15T17:35:55.743164
2021-06-11T22:59:07
2021-06-11T22:59:07
null
0
0
null
null
null
null
UTF-8
Python
false
false
768
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' # SOURCE: https://docs.python.org/3/library/os.html#os.walk from os.path import join, getsize from common import sizeof_fmt def get_dir_total_size(dir_name: str) -> (int, str): total_size = 0 for root, dirs, files in os.walk(dir_name): total_size += sum(getsize(join(root, name)) for name in files) return total_size, sizeof_fmt(total_size) if __name__ == '__main__': import os # paths = [r"C:\Users\Default", r"C:\Program Files (x86)", os.path.expanduser(r'~\Desktop')] paths = ['..'] for path in paths: path = os.path.abspath(path) size, size_str = get_dir_total_size(path) print(f'"{path}": {size} bytes / {size_str}')
[ "ilya.petrash@inbox.ru" ]
ilya.petrash@inbox.ru
d4eccb9f13bce33a5aae052b88b3c3fbddc99723
5f58ee3c7e5c4cca0310f33335fb36ec61ffd8cf
/build/sensing/drivers/camera/packages/hexacam/catkin_generated/pkg.develspace.context.pc.py
2d4ec2266029d6ad3ed98f5a1b0fbc3bdc0c8a59
[]
no_license
qqsskk/p3dx_velodyne_slam
4bad90ea64fb50539982a44f3df7abd0041516db
cafe3f81eb17bc5e8c8edc6b83b84a8d5fbf2805
refs/heads/master
2021-06-08T17:05:52.386391
2016-10-26T09:44:05
2016-10-26T09:44:05
null
0
0
null
null
null
null
UTF-8
Python
false
false
383
py
# generated from catkin/cmake/template/pkg.context.pc.in CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else [] PROJECT_CATKIN_DEPENDS = "".replace(';', ' ') PKG_CONFIG_LIBRARIES_WITH_PREFIX = "-lhexacam".split(';') if "-lhexacam" != "" else [] PROJECT_NAME = "hexacam" PROJECT_SPACE_DIR = "/home/hj/catkin_ws/devel" PROJECT_VERSION = "0.0.0"
[ "jhjune91@gmail.com" ]
jhjune91@gmail.com
f44ea363fb79cfff9b558fcc7d02d4f6e0133279
bc647095de9c9dd658b82179ff9e398029f53756
/tests/unit/test_action.py
aa46b2efe960852218b762f3cbf13cea1662f4c3
[ "BSD-3-Clause" ]
permissive
ettoreleandrotognoli/python-ami
2b9711bd484ceaf524f0b2109ac665ed4271065a
9922ccae5db73d0ee248942b8cfab9f939962024
refs/heads/master
2023-04-28T08:30:18.603575
2022-05-04T13:25:03
2022-05-04T14:02:28
43,763,556
112
68
BSD-3-Clause
2023-04-25T09:25:30
2015-10-06T16:36:48
Python
UTF-8
Python
false
false
1,804
py
import unittest from asterisk.ami import LoginAction, LogoffAction, SimpleAction class AMIActionTest(unittest.TestCase): def compare_actions(self, a1, a2): a1 = str(a1).split('\r\n') a2 = str(a2).split('\r\n') self.assertEqual(a1[0], a2[0]) self.assertSetEqual(set(a1[1:]), set(a2[1:])) def test_login_action(self): expected = '\r\n'.join([ 'Action: Login', 'Username: username', 'Secret: password', ]) + '\r\n' action = LoginAction('username', 'password') self.compare_actions(action, expected) self.assertEqual(action.name, 'Login') self.assertEqual(action.Username, 'username') self.assertEqual(action.Secret, 'password') self.assertDictEqual(action.keys, {'Username': 'username', 'Secret': 'password'}) self.assertEqual(len(action.variables), 0) def test_logoff_action(self): expected = '\r\n'.join([ 'Action: Logoff', ]) + '\r\n' action = LogoffAction() self.compare_actions(action, expected) self.assertEqual(action.name, 'Logoff') self.assertEqual(len(action.keys), 0) self.assertEqual(len(action.variables), 0) def test_with_variable(self): expected = '\r\n'.join([ 'Action: GetVar', 'Channel: channel-1', 'Variable: <Variable 1>=<Value 1>', ]) + '\r\n' action = SimpleAction('GetVar', Channel='channel-1') action['<Variable 1>'] = '<Value 1>' self.compare_actions(action, expected) self.assertEqual(action.Channel, 'channel-1') self.assertEqual(action['<Variable 1>'], '<Value 1>') action.Channel = 'channel-2' self.assertEqual(action.Channel, 'channel-2')
[ "ettore.leandro.tognoli@gmail.com" ]
ettore.leandro.tognoli@gmail.com
f0e290020c43602881ec59fc0628c8cbd0ac225a
365967082720f3fda31afccfc237b7a67e8ffc07
/sorting_searching/quick_sort.py
d95e226eb91824833e53fcd1a73f4ebdd12112a5
[]
no_license
hulaba/geekInsideYou
ec68dee3fa24d63f5470aa40b600ef34d37c5da1
72c1f1b4fbf115db91c908a68c9ac3ca4cb22a4f
refs/heads/master
2022-12-11T11:11:03.149336
2020-09-12T16:12:40
2020-09-12T16:12:40
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,530
py
''' parition() function is called as follows: def quickSort(arr,low,high): if low < high: # pi is partitioning index, arr[p] is now # at right place pi = partition(arr,low,high) # Separately sort elements before # partition and after partition quickSort(arr, low, pi-1) quickSort(arr, pi+1, high) ''' ''' This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot ''' def partition(arr, low, high): # add code here i = low - 1 piv = arr[high] for j in range(low, high): if arr[j] < piv: i += 1 arr[i], arr[j] = arr[j], arr[i] arr[i + 1], arr[high] = arr[high], arr[i + 1] return i + 1 # { # Driver Code Starts # Initial Template for Python 3 def quickSort(arr, low, high): if low < high: # pi is partitioning index, arr[p] is now # at right place pi = partition(arr, low, high) # Separately sort elements before # partition and after partition quickSort(arr, low, pi - 1) quickSort(arr, pi + 1, high) if __name__ == "__main__": t = int(input()) for i in range(t): n = int(input()) arr = list(map(int, input().split())) quickSort(arr, 0, n - 1) for i in range(n): print(arr[i], end=" ") print() # } Driver Code Ends
[ "nainamehta2110@gmail.com" ]
nainamehta2110@gmail.com
cb3f0f4aa798ac93644ed624c67bc75ba6fa96cf
b44a984ac8cfd183e218d56e1ec5d0d3e72d20fd
/High_Frequency/two_pointers/计数双指针/Substring With At Least K Distinct Characters/sliding_window.py
e968ee945eebc7729c33d701cc0cff334db3d4e9
[]
no_license
atomextranova/leetcode-python
61381949f2e78805dfdd0fb221f8497b94b7f12b
5fce59e6b9c4079b49e2cfb2a6d2a61a0d729c56
refs/heads/master
2021-07-15T20:32:12.592607
2020-09-21T00:10:27
2020-09-21T00:10:27
207,622,038
1
0
null
null
null
null
UTF-8
Python
false
false
747
py
class Solution: """ @param s: a string @param k: an integer @return: the number of substrings there are that contain at least k distinct characters """ def kDistinctCharacters(self, s, k): # Write your code here if len(s) < k: return 0 cur_chars = dict() left = 0 right = 0 total = 0 for right in range(len(s)): cur_char = s[right] cur_chars[cur_char] = cur_chars.get(cur_char, 0) + 1 while len(cur_chars) >= k: cur_chars[s[left]] -= 1 if cur_chars[s[left]] == 0: del cur_chars[s[left]] left += 1 total += left return total
[ "atomextranova@gmail.com" ]
atomextranova@gmail.com
66cf4ff262f64c8cbf47aea01229c40a532336c3
a81d21f98dd558416f8731f001cb8151d8309f4f
/interviewbit/test/test_excel_column_number.py
e1b9a6d25f15bc235f307c800a1150e10dc893e6
[]
no_license
marquesarthur/programming_problems
1128c38e65aade27e2435f7987d7ee2b328fda51
2f7df25d0d735f726b7012e4aa2417dee50526d9
refs/heads/master
2022-01-25T18:19:02.575634
2022-01-18T02:07:06
2022-01-18T02:07:06
32,213,919
2
0
null
2020-10-13T01:29:08
2015-03-14T13:44:06
Python
UTF-8
Python
false
false
1,026
py
import unittest from interviewbit.math import excel_column_number class TestExcelColumnNumber(unittest.TestCase): def test_base_case(self): s = excel_column_number.Solution() A = 'A' B = 1 result = s.titleToNumber(A) self.assertEqual(result, B) A = 'B' B = 2 result = s.titleToNumber(A) self.assertEqual(result, B) A = 'C' B = 3 result = s.titleToNumber(A) self.assertEqual(result, B) A = 'Z' B = 26 result = s.titleToNumber(A) self.assertEqual(result, B) A = 'AA' B = 27 result = s.titleToNumber(A) self.assertEqual(result, B) A = 'AB' B = 28 result = s.titleToNumber(A) self.assertEqual(result, B) A = 'CB' B = 80 result = s.titleToNumber(A) self.assertEqual(result, B) A = 'AAC' B = 705 result = s.titleToNumber(A) self.assertEqual(result, B)
[ "marques.art@gmail.com" ]
marques.art@gmail.com