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
861f15ba01e952a68448af0f114c2835c1095cb6
f56b6d816532174baf6054db443a467143b250df
/FiloBlu/process.py
6597c9175ba0d01116b8f86566a73574129c5c7b
[ "MIT" ]
permissive
Nico-Curti/FiloBluService
61eddb6f5b8a4c1c3fa66ba84fc4a7e9e4d8eeda
78fa802e37409b7826f2a5e96772fe79a5ba5e5a
refs/heads/master
2020-05-23T05:47:38.590459
2020-01-23T17:16:17
2020-01-23T17:16:17
186,654,530
2
0
NOASSERTION
2020-01-09T16:35:52
2019-05-14T15:52:58
Python
UTF-8
Python
false
false
4,610
py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import time __author__ = 'Nico Curti' __email__ = 'nico.curti2@unibo.it' # global variables that must be set and used in the following class # The paths are relative to the current python file DICTIONARY = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'data', 'updated_dictionary.dat')) MODEL = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'data', 'dual_w_0_2_class_ind_cw.h5')) CONFIGFILE = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'data', 'config.json')) LOGFILE = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'logs', 'filo_blu_process_service.log')) UPDATE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'updates')) def parse_args(): """ Just a simple parser of the command line. There are not required parameters because the scripts can run also with the set of default variables set at the beginning of this script. ----- Return args : object - Each member of the object identify a different command line argument (properly casted) """ import argparse description = 'Filo Blu Process Service' parser = argparse.ArgumentParser(description = description) parser.add_argument('--config', dest='config', type=str, required=False, action='store', help='Json configuration file for DB credentials', default=CONFIGFILE ) parser.add_argument('--logs', dest='logs', type=str, required=False, action='store', help='Log filename with absolute path', default=LOGFILE ) parser.add_argument('--network_model', dest='model', type=str, required=False, action='store', help='Network Model weights filename', default=MODEL ) parser.add_argument('--dictionary', dest='dictionary', type=str, required=False, action='store', help='Word dictionary sorted by frequency', default=DICTIONARY ) parser.add_argument('--update_dir', dest='update_dir', type=str, required=False, action='store', help='Directory in which update models are stored', default=UPDATE_DIR ) args = parser.parse_args() args.config = os.path.abspath(args.config) args.logs = os.path.abspath(args.logs) args.model = os.path.abspath(args.model) args.dictionary = os.path.abspath(args.dictionary) args.update_dir = os.path.abspath(args.update_dir) # Create the logs directory if it does not exist. log_directory = os.path.dirname(LOGFILE) os.makedirs(log_directory, exist_ok=True) os.makedirs(args.update_dir, exist_ok=True) return args if __name__ == '__main__': """ This main represent the tensorflow process service called by 'filoblu_service_tf.py' and it perform the right sequence of calls that can be found also in the 'filoblu_service_np.py' script in the main loop of the service object. """ args = parse_args() from database import FiloBluDB db = FiloBluDB(args.config, args.logs) db.get_logger.info('LOADING PROCESSING MODEL...') try: from network_model_tf import NetworkModel net = NetworkModel(args.model) db.get_logger.info('MODEL LOADED') except Exception as e: db.log_error(e) db.get_logger.info('LOADING WORD DICTIONARY...') try: from misc import read_dictionary dictionary = read_dictionary(args.dictionary) db.get_logger.info('DICTIONARY LOADED') except Exception as e: db.log_error(e) db.callback_read_last_messages() time.sleep(10) db.callback_process_messages(net, dictionary) time.sleep(10) db.callback_write_score_messages() db.callback_load_new_weights(args.model, args.update_dir) db.callback_clear_log() db.callback_score_history_log(args.update_dir) db.get_logger.info('FILO BLU Service: STARTING UP') while True: if db._wait: net = NetworkModel(args.model) db._wait = False db.log_error('FILO BLU Service: SHUTDOWN')
[ "nico.curti2@unibo.it" ]
nico.curti2@unibo.it
cdbb77434240451c649c927be9399be79278f4f5
cc7b0e228b4a0717eedd5410a66f72039c8f6960
/project/twitter/rest.py
0b3eb658ab53d91c894d8203ea6abff91349bb93
[]
no_license
lixiaochun/PyCrawler
870740b93835749a071a1e07a5cac4a5051a091c
7e7de51087c69d97649d78c31f9f70ab94d70383
refs/heads/master
2020-03-15T11:57:57.373199
2018-05-02T09:39:15
2018-05-02T09:39:15
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,645
py
# -*- coding:UTF-8 -*- """ Twitter REST API https://dev.twitter.com/rest/reference @author: hikaru email: hikaru870806@hotmail.com 如有问题或建议请联系 """ from common import * import base64 import json import os API_HOST = "https://api.twitter.com" API_VERSION = "1.1" ACCESS_TOKEN = None token_file_path = os.path.join(os.path.dirname(__file__), "token") def init(): # 设置代理 crawler.quickly_set_proxy() if ACCESS_TOKEN is not None: return True # 文件存在,检查格式是否正确 if os.path.exists(token_file_path): api_info = tool.json_decode(tool.decrypt_string(tool.read_file(token_file_path)), []) if crawler.check_sub_key(("api_key", "api_secret"), api_info): # 验证token是否有效 if get_access_token(api_info["api_key"], api_info["api_secret"]): output.print_msg("access token get succeed!") return True else: output.print_msg("api info has expired") else: output.print_msg("decrypt api info failure") # token已经无效了,删除掉 path.delete_dir_or_file(token_file_path) output.print_msg("Please input api info") while True: api_key = output.console_input("API KEY: ") api_secret = output.console_input("API SECRET; ") # 验证token是否有效 if get_access_token(api_key, api_secret): # 加密保存到文件中 if not os.path.exists(token_file_path): api_info = tool.encrypt_string(json.dumps({"api_key": api_key, "api_secret": api_secret})) tool.write_file(api_info, token_file_path, tool.WRITE_FILE_TYPE_REPLACE) output.print_msg("access token get succeed!") return True output.print_msg("incorrect api info, please type again!") return False def get_access_token(api_key, api_secret): auth_url = API_HOST + "/oauth2/token" header_list = { "Authorization": "Basic %s" % base64.b64encode("%s:%s" % (api_key, api_secret)), "Content-Type": 'application/x-www-form-urlencoded;charset=UTF-8.', } post_data = { "grant_type": "client_credentials" } response = net.http_request(auth_url, method="POST", header_list=header_list, fields=post_data, json_decode=True) if ( response.status == net.HTTP_RETURN_CODE_SUCCEED and crawler.check_sub_key(("token_type", "access_token"), response.json_data) and response.json_data["token_type"] == "bearer" ): global ACCESS_TOKEN ACCESS_TOKEN = response.json_data["access_token"] return True return False def _get_api_url(end_point): return "%s/%s/%s" % (API_HOST, API_VERSION, end_point) # 根据user_id获取用户信息 def get_user_info_by_user_id(user_id): api_url = _get_api_url("users/show.json") query_data = {"user_id": user_id} header_list = {"Authorization": "Bearer %s" % ACCESS_TOKEN} response = net.http_request(api_url, method="GET", fields=query_data, header_list=header_list, json_decode=True) if response.status == net.HTTP_RETURN_CODE_SUCCEED: return response.json_data return {} # 关注指定用户 def follow_account(user_id): api_url = _get_api_url("friendships/create.json") api_url += "?user_id=%s" % user_id header_list = { "Authorization": "Bearer %s" % ACCESS_TOKEN, } response = net.http_request(api_url, method="POST", header_list=header_list, json_decode=True) if response.status == net.HTTP_RETURN_CODE_SUCCEED: pass return False init()
[ "hikaru870806@hotmail.com" ]
hikaru870806@hotmail.com
82f9883b46dc46677116610f39d5554711370c56
be0f3dfbaa2fa3d8bbe59229aef3212d032e7dd1
/Gauss_v45r9/Gen/DecFiles/options/12215011.py
81feb939e9f19c70ffcc6bcbccd5824ec589796b
[]
no_license
Sally27/backup_cmtuser_full
34782102ed23c6335c48650a6eaa901137355d00
8924bebb935b96d438ce85b384cfc132d9af90f6
refs/heads/master
2020-05-21T09:27:04.370765
2018-12-12T14:41:07
2018-12-12T14:41:07
185,989,173
0
0
null
null
null
null
UTF-8
Python
false
false
1,789
py
# file /home/hep/ss4314/cmtuser/Gauss_v45r9/Gen/DecFiles/options/12215011.py generated: Fri, 27 Mar 2015 16:10:03 # # Event Type: 12215011 # # ASCII decay Descriptor: [ B+ -> mu+ mu- (K_1(1400)+ -> (X -> K+ pi- pi+)) ]cc # from Configurables import Generation Generation().EventType = 12215011 Generation().SampleGenerationTool = "SignalRepeatedHadronization" from Configurables import SignalRepeatedHadronization Generation().addTool( SignalRepeatedHadronization ) Generation().SignalRepeatedHadronization.ProductionTool = "PythiaProduction" from Configurables import ToolSvc from Configurables import EvtGenDecay ToolSvc().addTool( EvtGenDecay ) ToolSvc().EvtGenDecay.UserDecayFile = "$DECFILESROOT/dkfiles/Bu_Kprime1mumu=MS,DecProdCut.dec" Generation().SignalRepeatedHadronization.CutTool = "DaughtersInLHCb" Generation().SignalRepeatedHadronization.SignalPIDList = [ 521,-521 ] # Ad-hoc particle gun code from Configurables import ParticleGun pgun = ParticleGun("ParticleGun") pgun.SignalPdgCode = 521 pgun.DecayTool = "EvtGenDecay" pgun.GenCutTool = "DaughtersInLHCb" from Configurables import FlatNParticles pgun.NumberOfParticlesTool = "FlatNParticles" pgun.addTool( FlatNParticles , name = "FlatNParticles" ) from Configurables import MomentumSpectrum pgun.ParticleGunTool = "MomentumSpectrum" pgun.addTool( MomentumSpectrum , name = "MomentumSpectrum" ) pgun.MomentumSpectrum.PdgCodes = [ 521,-521 ] pgun.MomentumSpectrum.InputFile = "$PGUNSDATAROOT/data/Ebeam4000GeV/MomentumSpectrum_521.root" pgun.MomentumSpectrum.BinningVariables = "pteta" pgun.MomentumSpectrum.HistogramPath = "h_pteta" from Configurables import BeamSpotSmearVertex pgun.addTool(BeamSpotSmearVertex, name="BeamSpotSmearVertex") pgun.VertexSmearingTool = "BeamSpotSmearVertex" pgun.EventType = 12215011
[ "slavomirastefkova@b2pcx39016.desy.de" ]
slavomirastefkova@b2pcx39016.desy.de
3658f5f515232b6535cfc3f3f5df886394dcc75a
33518b9521d8e633010b0b9d1ea0f7a937437200
/Python/pascals_triangle_ii/pascals_triangle_ii.py
85eb1cf48a9472625f0d927e6f7711fe645c5be6
[]
no_license
lqs4188980/CodingPractice
977ddb69306c92a5e3df88f26572200622fad82a
c17653832269ab1bb3e411f7d74bef4c8e9985b3
refs/heads/master
2021-01-22T05:10:40.885490
2016-02-05T09:06:51
2016-02-05T09:06:51
25,272,652
0
1
null
2016-01-06T07:50:29
2014-10-15T20:40:34
Java
UTF-8
Python
false
false
354
py
# 1: 1 # 2: 1 1 # 3: 1 2 1 # 4: 1 3 3 1 class Solution(object): def getRow(self, rowIndex): row = [0] * (rowIndex + 1) row[0] = 1 for i in range(rowIndex + 1): prev = 0 for j in range(i+1): tmp = row[j] row[j] += prev prev = tmp return row
[ "xiaoqin.zhu.4@gmail.com" ]
xiaoqin.zhu.4@gmail.com
8d3efb954b41d4cdf01b57e400aab6217641e7ef
dd3b8bd6c9f6f1d9f207678b101eff93b032b0f0
/basis/AbletonLive10.1_MIDIRemoteScripts/OpenLabs/SpecialTransportComponent.py
9cd5ad4f3d6a0974af0291a4d3f3ded2741e6e44
[]
no_license
jhlax/les
62955f57c33299ebfc4fca8d0482b30ee97adfe7
d865478bf02778e509e61370174a450104d20a28
refs/heads/master
2023-08-17T17:24:44.297302
2019-12-15T08:13:29
2019-12-15T08:13:29
228,120,861
3
0
null
2023-08-03T16:40:44
2019-12-15T03:02:27
Python
UTF-8
Python
false
false
3,873
py
# uncompyle6 version 3.4.1 # Python bytecode 2.7 (62211) # Decompiled from: Python 2.7.16 (v2.7.16:413a49145e, Mar 2 2019, 14:32:10) # [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] # Embedded file name: /Users/versonator/Jenkins/live/output/mac_64_static/Release/python-bundle/MIDI Remote Scripts/OpenLabs/SpecialTransportComponent.py # Compiled at: 2019-04-09 19:23:44 from __future__ import absolute_import, print_function, unicode_literals import Live from _Framework.TransportComponent import TransportComponent from _Framework.InputControlElement import * from _Framework.ButtonElement import ButtonElement from _Framework.EncoderElement import EncoderElement class SpecialTransportComponent(TransportComponent): u""" Transport component that takes buttons for Undo and Redo """ def __init__(self): TransportComponent.__init__(self) self._undo_button = None self._redo_button = None self._bts_button = None return def disconnect(self): TransportComponent.disconnect(self) if self._undo_button != None: self._undo_button.remove_value_listener(self._undo_value) self._undo_button = None if self._redo_button != None: self._redo_button.remove_value_listener(self._redo_value) self._redo_button = None if self._bts_button != None: self._bts_button.remove_value_listener(self._bts_value) self._bts_button = None return def set_undo_button(self, undo_button): assert isinstance(undo_button, (ButtonElement, type(None))) if undo_button != self._undo_button: if self._undo_button != None: self._undo_button.remove_value_listener(self._undo_value) self._undo_button = undo_button if self._undo_button != None: self._undo_button.add_value_listener(self._undo_value) self.update() return def set_redo_button(self, redo_button): assert isinstance(redo_button, (ButtonElement, type(None))) if redo_button != self._redo_button: if self._redo_button != None: self._redo_button.remove_value_listener(self._redo_value) self._redo_button = redo_button if self._redo_button != None: self._redo_button.add_value_listener(self._redo_value) self.update() return def set_bts_button(self, bts_button): assert isinstance(bts_button, (ButtonElement, type(None))) if bts_button != self._bts_button: if self._bts_button != None: self._bts_button.remove_value_listener(self._bts_value) self._bts_button = bts_button if self._bts_button != None: self._bts_button.add_value_listener(self._bts_value) self.update() return def _undo_value(self, value): if not self._undo_button != None: raise AssertionError assert value in range(128) if self.is_enabled() and (value != 0 or not self._undo_button.is_momentary()): if self.song().can_undo: self.song().undo() return def _redo_value(self, value): if not self._redo_button != None: raise AssertionError assert value in range(128) if self.is_enabled() and (value != 0 or not self._redo_button.is_momentary()): if self.song().can_redo: self.song().redo() return def _bts_value(self, value): if not self._bts_button != None: raise AssertionError assert value in range(128) if self.is_enabled() and (value != 0 or not self._bts_button.is_momentary()): self.song().current_song_time = 0.0 return
[ "jharrington@transcendbg.com" ]
jharrington@transcendbg.com
949191d90fda07a28149027d4d0724a6f9933dad
9e549ee54faa8b037f90eac8ecb36f853e460e5e
/venv/lib/python3.6/site-packages/requests/api.py
de38136491407780126771413bdb604e269beb90
[ "MIT" ]
permissive
aitoehigie/britecore_flask
e8df68e71dd0eac980a7de8c0f20b5a5a16979fe
eef1873dbe6b2cc21f770bc6dec783007ae4493b
refs/heads/master
2022-12-09T22:07:45.930238
2019-05-15T04:10:37
2019-05-15T04:10:37
177,354,667
0
0
MIT
2022-12-08T04:54:09
2019-03-24T00:38:20
Python
UTF-8
Python
false
false
6,253
py
# -*- coding: utf-8 -*- """ requests.api ~~~~~~~~~~~~ This module implements the Requests API. :copyright: (c) 2012 by Kenneth Reitz. :license: Apache2, see LICENSE for more details. """ from . import sessions def request(method, url, **kwargs): """Constructs and sends a :class:`Request <Request>`. :param method: method for the new :class:`Request` object. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary, list of tuples or bytes to send in the body of the :class:`Request`. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`. :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`. :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload. ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')`` or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content-type'`` is a string defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers to add for the file. :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth. :param timeout: (optional) How many seconds to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple :param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``. :type allow_redirects: bool :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy. :param verify: (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to ``True``. :param stream: (optional) if ``False``, the response content will be immediately downloaded. :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. :return: :class:`Response <Response>` object :rtype: requests.Response Usage:: >>> import requests >>> req = requests.request('GET', 'https://httpbin.org/get') <Response [200]> """ # By using the 'with' statement we are sure the session is closed, thus we # avoid leaving sockets open which can trigger a ResourceWarning in some # cases, and look like a memory leak in others. with sessions.Session() as session: return session.request(method=method, url=url, **kwargs) def get(url, params=None, **kwargs): r"""Sends a GET request. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary, list of tuples or bytes to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response """ kwargs.setdefault("allow_redirects", True) return request("get", url, params=params, **kwargs) def options(url, **kwargs): r"""Sends an OPTIONS request. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response """ kwargs.setdefault("allow_redirects", True) return request("options", url, **kwargs) def head(url, **kwargs): r"""Sends a HEAD request. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response """ kwargs.setdefault("allow_redirects", False) return request("head", url, **kwargs) def post(url, data=None, json=None, **kwargs): r"""Sends a POST request. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json data to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response """ return request("post", url, data=data, json=json, **kwargs) def put(url, data=None, **kwargs): r"""Sends a PUT request. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json data to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response """ return request("put", url, data=data, **kwargs) def patch(url, data=None, **kwargs): r"""Sends a PATCH request. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json data to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response """ return request("patch", url, data=data, **kwargs) def delete(url, **kwargs): r"""Sends a DELETE request. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response """ return request("delete", url, **kwargs)
[ "aitoehigie@gmail.com" ]
aitoehigie@gmail.com
814cbdab73818496ae33f465eb65ca4f4532978a
17a2963202dd4a8261b0db0629f44eb4ec0a87cb
/scrapy_demo/settings.py
ca5d73c2f759db3b38ecbb011c997b69296f1b1e
[]
no_license
maketubu7/scrapy_demo
61089fe75444b3156dfc0dfd5f6fd363f7353901
1c0c36dadeae68032841453eba0ebf031665993b
refs/heads/master
2023-01-06T18:04:07.246431
2020-11-11T09:03:21
2020-11-11T09:03:21
311,916,208
0
0
null
null
null
null
UTF-8
Python
false
false
3,310
py
# -*- coding: utf-8 -*- # Scrapy settings for scrapy_demo project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # https://docs.scrapy.org/en/latest/topics/settings.html # https://docs.scrapy.org/en/latest/topics/downloader-middleware.html # https://docs.scrapy.org/en/latest/topics/spider-middleware.html BOT_NAME = 'scrapy_demo' DOWNLOAD_TIMEOUT = 500 RETRY_ENABLED = True #打开重试开关 RETRY_TIMES = 3 #重试次数 RETRY_HTTP_CODES = [429,404,403] #重试 SPIDER_MODULES = ['scrapy_demo.spiders'] NEWSPIDER_MODULE = 'scrapy_demo.spiders' # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'scrapy_demo (+http://www.yourdomain.com)' # Obey robots.txt rules ROBOTSTXT_OBEY = True # Configure maximum concurrent requests performed by Scrapy (default: 16) #CONCURRENT_REQUESTS = 32 # Configure a delay for requests for the same website (default: 0) # See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay # See also autothrottle settings and docs #DOWNLOAD_DELAY = 3 # The download delay setting will honor only one of: #CONCURRENT_REQUESTS_PER_DOMAIN = 16 #CONCURRENT_REQUESTS_PER_IP = 16 # Disable cookies (enabled by default) #COOKIES_ENABLED = False # Disable Telnet Console (enabled by default) #TELNETCONSOLE_ENABLED = False # Override the default request headers: #DEFAULT_REQUEST_HEADERS = { # 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', # 'Accept-Language': 'en', #} # Enable or disable spider middlewares # See https://docs.scrapy.org/en/latest/topics/spider-middleware.html #SPIDER_MIDDLEWARES = { # 'scrapy_demo.middlewares.ScrapyDemoSpiderMiddleware': 543, #} # Enable or disable downloader middlewares # See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html DOWNLOADER_MIDDLEWARES = { 'scrapy_demo.middlewares.RandomUserAgentMiddleware': 543, 'scrapy_demo.middlewares.ProxyMiddleware': 541, } # Enable or disable extensions # See https://docs.scrapy.org/en/latest/topics/extensions.html #EXTENSIONS = { # 'scrapy.extensions.telnet.TelnetConsole': None, #} # Configure item pipelines # See https://docs.scrapy.org/en/latest/topics/item-pipeline.html ITEM_PIPELINES = { 'scrapy_demo.pipelines.ScrapyDemoPipeline': 300, } # Enable and configure the AutoThrottle extension (disabled by default) # See https://docs.scrapy.org/en/latest/topics/autothrottle.html #AUTOTHROTTLE_ENABLED = True # The initial download delay #AUTOTHROTTLE_START_DELAY = 5 # The maximum download delay to be set in case of high latencies #AUTOTHROTTLE_MAX_DELAY = 60 # The average number of requests Scrapy should be sending in parallel to # each remote server #AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0 # Enable showing throttling stats for every response received: #AUTOTHROTTLE_DEBUG = False # Enable and configure HTTP caching (disabled by default) # See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings #HTTPCACHE_ENABLED = True #HTTPCACHE_EXPIRATION_SECS = 0 #HTTPCACHE_DIR = 'httpcache' #HTTPCACHE_IGNORE_HTTP_CODES = [] #HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
[ "601176930@qq.com" ]
601176930@qq.com
7b17232de8954cc217c0c9269ed8caaa1ba4fe8e
f8daf3972d5820945172005659cf0d7dfc1086d6
/trunk/python/feeding_modules/ingredients_by_dish_storage.py
eebe000ad27c25161a32a1e31dcb2633288d3cb4
[]
no_license
BGCX067/family-feeding-svn-to-git
ec2645a1f36da717783bf21b42e1227588c20de5
bece6a73d4b6be9b29480c2bc7690b7e5e6961a4
refs/heads/master
2016-09-01T08:58:00.414527
2015-12-28T14:36:42
2015-12-28T14:36:42
48,759,877
0
0
null
null
null
null
UTF-8
Python
false
false
3,087
py
class ingredients_by_dish_storage : def __init__ ( self ) : self . _ingredients_by_dish = None self . _consts = None self . _re = None def set_modules ( self , consts , re ) : self . _consts = consts self . _re = re def get ( self ) : return self . _ingredients_by_dish def dish_ingredient_unit_amount ( self , dish , ingredient ) : units_amounts = { } if dish in self . _ingredients_by_dish : if ingredient in self . _ingredients_by_dish [ dish ] : for unit , amount in self . _ingredients_by_dish [ dish ] [ ingredient ] . items ( ) : if unit not in units_amounts : units_amounts [ unit ] = float ( 0 ) units_amounts [ unit ] += float ( amount ) return units_amounts def dish_ingredients ( self , dish ) : ingredients = set ( ) if dish in self . _ingredients_by_dish : ingredients = set ( self . _ingredients_by_dish [ dish ] . keys ( ) ) return ingredients def all_ingredients ( self ) : ingredients = set ( ) for dish , dish_ingredients in self . _ingredients_by_dish . items ( ) : ingredients = ingredients . union ( set ( dish_ingredients . keys ( ) ) ) return ingredients def all_dishes ( self ) : return set ( self . _ingredients_by_dish . keys ( ) ) def load ( self ) : wiki_file_name = self . _consts . wiki_path + self . _consts . ingredients_by_dish_file_name + self . _consts . dot_wiki try : wiki_contents = open ( wiki_file_name , self . _consts . open_file_for_read ) . readlines ( ) except IOError : wiki_contents = [ ] self . _ingredients_by_dish = { } current_dish = unicode ( ) for wiki_line in wiki_contents : unicode_wiki_line = wiki_line . decode ( self . _consts . utf8 ) match = self . _re . match ( self . _consts . header_regexp , unicode_wiki_line , self . _re . UNICODE ) if match : current_dish = match . group ( 1 ) . lower ( ) if current_dish not in self . _ingredients_by_dish : self . _ingredients_by_dish [ current_dish ] = { } match = self . _re . match ( self . _consts . ingredient_amount_list_regexp , unicode_wiki_line , self . _re . UNICODE ) if match : ingredient = match . group ( 1 ) . lower ( ) amount = float ( match . group ( 2 ) ) unit = match . group ( 3 ) . lower ( ) if ingredient not in self . _ingredients_by_dish [ current_dish ] : self . _ingredients_by_dish [ current_dish ] [ ingredient ] = { } if unit not in self . _ingredients_by_dish [ current_dish ] [ ingredient ] : self . _ingredients_by_dish [ current_dish ] [ ingredient ] [ unit ] = float ( 0 ) self . _ingredients_by_dish [ current_dish ] [ ingredient ] [ unit ] += amount
[ "you@example.com" ]
you@example.com
7d5ccfce3809cde8fda8b2041c7df122dd0d1231
7fdf76ac241714a223ae049278287fd33cab2769
/40-practical.py
4a8fdd8c95b0f6c912f853a0a27fbb98af508515
[]
no_license
ajaybhatia/python-practical-2020
9c0aa15c8e3985f4af6716028af0332e58780554
6e8310a84a0f18427c248efaf179ff76f50414e3
refs/heads/master
2023-01-19T13:45:26.335828
2020-11-20T05:03:41
2020-11-20T05:03:41
292,453,610
0
1
null
null
null
null
UTF-8
Python
false
false
643
py
''' Practical 40 Construct a Python program to write and append text to a file and display the text. ''' from os import getcwd filename = "/tmp/names.txt" try: file = open(filename, "a") # Write names in a file "/tmp/names.txt" while True: name = input("Enter a name: ") if name == "0": break file.write(name + "\n") file.close() # Read file contents and print them on screen print(f"{filename} contains following contents:") print("----------------------------------------\n") file = open(filename, "r") print(file.read()) except FileNotFoundError: print(f"'{filename}' do not exists on {getcwd()}")
[ "prof.ajaybhatia@gmail.com" ]
prof.ajaybhatia@gmail.com
0efed9264a2bb7f084086f644c2111d8902ce4e2
8f64d50494507fd51c0a51010b84d34c667bd438
/BeautyForMe/myvenv/Lib/site-packages/win32comext/shell/demos/IShellLinkDataList.py
bf52f781c45e27794f26bffce8da383cc5c62bc1
[ "MIT" ]
permissive
YooInKeun/CAU_CSE_Capstone_3
5a4a61a916dc13c8635d25a04d59c21279678477
51405c4bed2b55661aa0708c8acea17fe72aa701
refs/heads/master
2022-12-11T15:39:09.721019
2021-07-27T08:26:04
2021-07-27T08:26:04
207,294,862
6
1
MIT
2022-11-22T04:52:11
2019-09-09T11:37:13
Python
UTF-8
Python
false
false
1,666
py
from win32com.shell import shell, shellcon import pythoncom, win32api, os, sys temp_dir=win32api.GetTempPath() linkname=win32api.GetTempFileName(temp_dir,'cmd')[0] os.remove(linkname) linkname+='.lnk' print('Link name:',linkname) ish=pythoncom.CoCreateInstance(shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink) ish.SetPath(os.environ['cOMSPEC']) ish.SetWorkingDirectory(os.path.split(sys.executable)[0]) ish.SetDescription('shortcut made by python') console_props={ 'Signature':shellcon.NT_CONSOLE_PROPS_SIG, 'InsertMode':True, 'FullScreen':False, ## True looks like "DOS Mode" from win98! 'FontFamily':54, 'CursorSize':75, ## pct of character size 'ScreenBufferSize':(152, 256), 'AutoPosition':False, 'FontSize':(4, 5), 'FaceName':'', 'HistoryBufferSize':32, 'InputBufferSize':0, 'QuickEdit':True, 'Font':0, ## 0 should always be present, use win32console.GetNumberOfConsoleFonts() to find how many available 'FillAttribute':7, 'PopupFillAttribute':245, 'WindowSize':(128, 32), 'WindowOrigin':(0, 0), 'FontWeight':400, 'HistoryNoDup':False, 'NumberOfHistoryBuffers':32, ## ColorTable copied from a 'normal' console shortcut, with some obvious changes ## These do not appear to be documented. From experimentation, [0] is background, [7] is foreground text 'ColorTable':(255, 8388608, 32768, 8421376, 128, 8388736, 32896, 12582912, 8421504, 16711680, 65280, 16776960, 255, 16711935, 65535, 16777215) } ishdl=ish.QueryInterface(shell.IID_IShellLinkDataList) ishdl.AddDataBlock(console_props) ipf=ish.QueryInterface(pythoncom.IID_IPersistFile) ipf.Save(linkname,1) os.startfile(linkname)
[ "keun0390@naver.com" ]
keun0390@naver.com
f6a46eb065ef80c1559c9bdc9ecc8000c50b019d
392d16a4efcfe85ca99c82f816bdb37de8821098
/builtin_packages/datetime_sp/datetime_operation.py
a007315f3182c58d312b0de8b5d0c60b465892fa
[]
no_license
binderclip/code-snippets-python
a62305157c179748a80e8d7afa08178133465e6b
5b5381afd19dbd3c511d79a1d207c4a1789c0367
refs/heads/master
2022-12-11T08:34:45.373978
2021-11-27T08:38:04
2021-11-27T08:38:04
109,646,422
26
8
null
2022-12-09T05:21:26
2017-11-06T04:10:19
Python
UTF-8
Python
false
false
376
py
import datetime def main(): dt1 = datetime.datetime(2018, 6, 27) dt2 = datetime.datetime(2018, 6, 28) print('max: {}'.format(max(dt1, dt2))) print('minus: {}'.format(dt1 - dt2)) # print('plus: {}'.format(dt1 + dt2)) # TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'datetime.datetime' if __name__ == '__main__': main()
[ "binderclip2014@gmail.com" ]
binderclip2014@gmail.com
fa2b6ac1485395e04c0cb2535f099dde7990656b
0b4e3df18811a0de6e2e91e7efe1afc1ac635489
/pyshanb/utils.py
2f076ffd657f5868bc01b7d1d7ec17bf95b9d534
[ "MIT" ]
permissive
mozillazg/PyShanb
0c50d4d9554385041ba4b9df93f485e16b6540cd
40aa7ef21a6413fd2c722b451395f29283bb7949
refs/heads/dev
2023-08-23T21:16:52.104501
2014-04-01T13:20:16
2014-04-01T13:20:16
6,542,229
17
5
MIT
2018-03-05T01:08:52
2012-11-05T09:58:31
Python
UTF-8
Python
false
false
3,588
py
#!/usr/bin/env python # -*- coding: utf-8 -*- """一些功能函数 """ import os from getpass import getpass from .cmdoption import CmdOption from .conf import Settings # Modified from https://github.com/webpy/webpy/blob/master/web/utils.py class Storage(dict): """A Storage object is like a dictionary except `obj.foo` can be used in addition to `obj['foo']`. >>> o = storage(a=1) >>> o.a 1 >>> o['a'] 1 >>> o.a = 2 >>> o['a'] 2 >>> del o.a >>> o.a Traceback (most recent call last): ... AttributeError: 'a' """ def __getattr__(self, key): try: return self[key] except KeyError as k: raise AttributeError(k) def __setattr__(self, key, value): self[key] = value def __delattr__(self, key): try: del self[key] except KeyError as k: raise AttributeError(k) def __repr__(self): return '<Storage ' + dict.__repr__(self) + '>' storage = Storage def parse_settings(): u"""解析各个设置项.""" # 获取各命令行参数的值 options = CmdOption().options configfile = options.settings username = options.username password = options.password ask_add_example = options.ask_add_example enable_iciba = options.enable_iciba auto_play = options.auto_play example = options.example english = options.english # 读取配置文件 if configfile: configfile = os.path.realpath(configfile) conf = Settings(configfile, username, '').settings if password is None: password = conf.password if not password: password = getpass('Please input password: ') username = username or conf.username password = password or conf.password if auto_play is None: auto_play = conf.auto_play # 自动播放单词读音 settings = {} # shanbay.com site = conf.site settings['site'] = site settings['username'] = username settings['password'] = password settings['auto_add'] = conf.auto_add # 自动保存单词到扇贝网 settings['ask_add'] = conf.ask_add # 询问是否保存单词 settings['auto_play'] = auto_play if english is None: english = conf.enable_en_definition settings['en_definition'] = english # 单词英文释义 settings['url_login'] = site + conf.url_login settings['api_get_word'] = site + conf.api_get_word # 获取单词信息的 api settings['api_get_example'] = site + conf.api_get_example # 获取例句的 api settings['api_add_word'] = site + conf.api_add_word # 保存单词的 api # 获取用户信息的 api settings['api_get_user_info'] = site + conf.api_get_user_info settings['api_add_example'] = site + conf.api_add_example # 添加例句的 api if ask_add_example is None: ask_add_example = conf.ask_add_example # 询问是否添加例句 settings['ask_example'] = ask_add_example if example is None: example = conf.enable_example settings['example'] = example # 用户自己添加的单词例句 # iciba.com if enable_iciba is None: enable_iciba = conf.enable_iciba settings['iciba'] = enable_iciba settings['iciba_audio'] = conf.enable_icb_audio settings['iciba_lang'] = conf.enable_icb_lang settings['iciba_syllable'] = conf.enable_icb_syllable settings['iciba_extra'] = conf.enable_icb_syllable settings['colour'] = options.colour settings['plugins'] = options.plugins return storage(settings)
[ "opensource.mozillazg@gmail.com" ]
opensource.mozillazg@gmail.com
4c47324bc0e1d6065d40f28039ef03d9630a3096
01f4d1a2972887bbd1482ade4e253e0bc4373cd5
/check.py
7eac3e308ec347e8a4d4efea0e46bda86e84a33b
[]
no_license
1024Person/ProxyPool
cdabe5d6e29fd98109e4ae1dbb86391bb511310f
cd314cf1fded46b15708d56e8cb85c2099384a6e
refs/heads/main
2023-03-21T19:16:30.370551
2021-03-06T07:27:40
2021-03-06T07:27:40
344,514,686
1
0
null
null
null
null
UTF-8
Python
false
false
4,872
py
# 检测模块 from poolclient import PoolClient from setting import test_url,test_headers,USER_AGENT_LIST,check_max_worker,csv_file_path,good_ips_file_path from random import choice from concurrent.futures import ThreadPoolExecutor import requests class CheckIp(): # 参数:check_max_worker: 线程池中的线程数,默认是从settings中引入的100个,可以修改setting文件中的全局配置,也可以在创建的时候自己再传入一个数字,推荐后一种方法 # 参数:check_fn : 检查ip可用性的方法,默认是CheckIp自带的__check方法,如果传入定制的check_fn这个函数的参数必须是一个pd.Series对象,这个对象的index是["ip","scores"] # 参数:test_url : 用来检测ip的网址,默认使用setting文件中的test_url # 参数:test_headers : 定制headers,默认使用setting文件中的test_headers # 参数:client_path : 连接器需要获取混沌代理池路径 # 参数:client_good_path: 连接器需要获取优质代理池路径 def __init__(self,max_workers=check_max_worker,check_fn=None,ts_url=test_url,ts_headers=test_headers,client_path = csv_file_path,client_good_path=good_ips_file_path): self.__total_ip_count = 0 # 代理池中代理的数量 self.__success_ip_count = 0 # 代理池中成功可用代理的数量 self.poolclient = None self.client_path = client_path self.good_client_path = good_ips_file_path self.test_url = ts_url self.test_header = ts_headers self.CheckPool = ThreadPoolExecutor(max_workers=check_max_worker,thread_name_prefix="CheckIp") if not check_fn : self.check_fn = self.__check else: self.check_fn = check_fn # 开启检查池 # 参数:check_fn 检测函数,默认为self.__check # 注意:check_fn 函数只能有一个参数:ip(Series对象) # 要检测代理ip的网站,需要从setting.py里设置test_url,想定制headers也需要从setting.py文件中设置test_headers def start_check(self): self.client_pool() print("{}开始运行".format(self.CheckPool._thread_name_prefix)) for ip in self.poolclient.get_all_ip(): future = self.CheckPool.submit(self.check_fn,(ip,)) future.add_done_callback(self.__update_pool) # 链接数据池 def client_pool(self): print("正在连接数据池.....") self.poolclient = PoolClient(csv_file_path=self.client_path,good_ips_file_path=self.good_client_path) # 关闭检查池 def shutdown(self): print("关闭检查池") self.CheckPool.shutdown(wait=True) print("检查池关闭成功") self.poolclient.shutdown() # 关闭数据池 # 获取代理池成功率 def get_success_rate(self): return self.__success_ip_count / self.__total_ip_count # 线程池的回调函数,用来更新代理池的分数 def __update_pool(self,future): self.__total_ip_count += 1 result = future.result() success_or_fail, ip= result if success_or_fail: self.__success_ip_count += 1 self.poolclient.success_ip(ip) else: self.poolclient.fail_ip(ip) print("===" * 20) # 将每次测试结果隔开, # 参数:ip:Series对象,当前要检测的ip代理 # return: # bool 返回当前ip是否可用 # ip 设置分数的时候需要 def __check(self,ip): ip = ip[0] # 先将ip的Series对象获取出来 proxy = { "http":"http://"+ip["ip"], "https":"https://"+ip["ip"] } try: response = requests.get(url=self.test_url,headers=self.test_header,proxies=proxy,timeout=30) if response.status_code == 200: return (True,ip) else: print("请求状态码不对") print("status_code:",response.status_code) return (False,ip) except requests.exceptions.ProxyError: print("代理出错") return (False,ip) except requests.exceptions.ConnectTimeout: print("请求太慢,直接pass掉了") return (False,ip) except requests.exceptions.TooManyRedirects: print("我也不知道怎么就出错了") return (False,ip) except requests.exceptions.ReadTimeout: print("ReadTimeout") return (False,ip) except: return (False,ip) if __name__ == "__main__": check = CheckIp() check.start_check() check.shutdown() message = """ 本次测试网址: {}, 本次测试成功率:{}%, """.format(check.test_url,check.get_success_rate()) print(message)
[ "239903524@qq.com" ]
239903524@qq.com
95a5dfd878c46a91038a0a3438cec95df558968e
bb33e6be8316f35decbb2b81badf2b6dcf7df515
/source/res/scripts/common/goodies/goodie_constants.py
8e816e66038e66d865b8418dd4dcf2b5fa3bc7c4
[]
no_license
StranikS-Scan/WorldOfTanks-Decompiled
999c9567de38c32c760ab72c21c00ea7bc20990c
d2fe9c195825ececc728e87a02983908b7ea9199
refs/heads/1.18
2023-08-25T17:39:27.718097
2022-09-22T06:49:44
2022-09-22T06:49:44
148,696,315
103
39
null
2022-09-14T17:50:03
2018-09-13T20:49:11
Python
UTF-8
Python
false
false
1,243
py
# Python bytecode 2.7 (decompiled from Python 2.7) # Embedded file name: scripts/common/goodies/goodie_constants.py MAX_ACTIVE_GOODIES = 3 class GOODIE_STATE: INACTIVE = 0 ACTIVE = 1 USED = 2 class GOODIE_VARIETY: DISCOUNT = 0 BOOSTER = 1 DEMOUNT_KIT = 2 RECERTIFICATION_FORM = 3 DISCOUNT_NAME = 'discount' BOOSTER_NAME = 'booster' DEMOUNT_KIT_NAME = 'demountKit' RECERTIFICATION_FORM_NAME = 'recertificationForm' NAME_TO_ID = {DISCOUNT_NAME: DISCOUNT, BOOSTER_NAME: BOOSTER, DEMOUNT_KIT_NAME: DEMOUNT_KIT, RECERTIFICATION_FORM_NAME: RECERTIFICATION_FORM} DISCOUNT_LIKE = (DISCOUNT, DEMOUNT_KIT, RECERTIFICATION_FORM) class GOODIE_TARGET_TYPE: ON_BUY_PREMIUM = 1 ON_BUY_SLOT = 2 ON_POST_BATTLE = 3 ON_BUY_GOLD_TANKMEN = 4 ON_FREE_XP_CONVERSION = 5 ON_BUY_VEHICLE = 6 ON_EPIC_META = 7 ON_DEMOUNT_OPTIONAL_DEVICE = 8 EPIC_POST_BATTLE = 9 ON_DROP_SKILL = 10 class GOODIE_CONDITION_TYPE: MAX_VEHICLE_LEVEL = 1 class GOODIE_RESOURCE_TYPE: GOLD = 10 CREDITS = 20 XP = 30 CREW_XP = 40 FREE_XP = 50 FL_XP = 60 class GOODIE_NOTIFICATION_TYPE: EMPTY = 1 REMOVED = 3 DISABLED = 4 ENABLED = 5
[ "StranikS_Scan@mail.ru" ]
StranikS_Scan@mail.ru
f40951ca21c7c8bd3b03ea03a2771195723484ff
556db265723b0cc30ad2917442ed6dad92fd9044
/tensorflow/python/kernel_tests/random/multinomial_op_big_test.py
8e2a734c8171d890fc2159029bc3b7940da1fdee
[ "MIT", "Apache-2.0", "BSD-2-Clause" ]
permissive
graphcore/tensorflow
c1669b489be0e045b3ec856b311b3139858de196
085b20a4b6287eff8c0b792425d52422ab8cbab3
refs/heads/r2.6/sdk-release-3.2
2023-07-06T06:23:53.857743
2023-03-14T13:04:04
2023-03-14T13:48:43
162,717,602
84
17
Apache-2.0
2023-03-25T01:13:37
2018-12-21T13:30:38
C++
UTF-8
Python
false
false
3,624
py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Long tests for Multinomial.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import random_seed from tensorflow.python.framework import test_util from tensorflow.python.ops import random_ops from tensorflow.python.platform import test class MultinomialTest(test.TestCase): # check that events with tiny probabilities are not over-sampled def testLargeDynamicRange(self): random_seed.set_random_seed(10) counts_by_indices = {} with self.test_session(): samples = random_ops.multinomial( constant_op.constant([[-30, 0]], dtype=dtypes.float32), num_samples=1000000, seed=15) for _ in range(100): x = self.evaluate(samples) indices, counts = np.unique(x, return_counts=True) # pylint: disable=unexpected-keyword-arg for index, count in zip(indices, counts): if index in counts_by_indices.keys(): counts_by_indices[index] += count else: counts_by_indices[index] = count self.assertEqual(counts_by_indices[1], 100000000) def testLargeDynamicRange2(self): random_seed.set_random_seed(10) counts_by_indices = {} with self.test_session(): samples = random_ops.multinomial( constant_op.constant([[0, -30]], dtype=dtypes.float32), num_samples=1000000, seed=15) for _ in range(100): x = self.evaluate(samples) indices, counts = np.unique(x, return_counts=True) # pylint: disable=unexpected-keyword-arg for index, count in zip(indices, counts): if index in counts_by_indices.keys(): counts_by_indices[index] += count else: counts_by_indices[index] = count self.assertEqual(counts_by_indices[0], 100000000) @test_util.run_deprecated_v1 def testLargeDynamicRange3(self): random_seed.set_random_seed(10) counts_by_indices = {} # here the cpu undersamples and won't pass this test either with self.test_session(): samples = random_ops.multinomial( constant_op.constant([[0, -17]], dtype=dtypes.float32), num_samples=1000000, seed=22) # we'll run out of memory if we try to draw 1e9 samples directly # really should fit in 12GB of memory... for _ in range(100): x = self.evaluate(samples) indices, counts = np.unique(x, return_counts=True) # pylint: disable=unexpected-keyword-arg for index, count in zip(indices, counts): if index in counts_by_indices.keys(): counts_by_indices[index] += count else: counts_by_indices[index] = count self.assertGreater(counts_by_indices[1], 0) if __name__ == "__main__": test.main()
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
7db94008661c38b8142fa16719f0287d2a459e82
9b64f0f04707a3a18968fd8f8a3ace718cd597bc
/huaweicloud-sdk-kms/huaweicloudsdkkms/v1/model/enable_key_request.py
5b879f74aab865beeda3267d42cd6356f98b8914
[ "Apache-2.0" ]
permissive
jaminGH/huaweicloud-sdk-python-v3
eeecb3fb0f3396a475995df36d17095038615fba
83ee0e4543c6b74eb0898079c3d8dd1c52c3e16b
refs/heads/master
2023-06-18T11:49:13.958677
2021-07-16T07:57:47
2021-07-16T07:57:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,306
py
# coding: utf-8 import re import six class EnableKeyRequest: """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ sensitive_list = [] openapi_types = { 'version_id': 'str', 'body': 'OperateKeyRequestBody' } attribute_map = { 'version_id': 'version_id', 'body': 'body' } def __init__(self, version_id=None, body=None): """EnableKeyRequest - a model defined in huaweicloud sdk""" self._version_id = None self._body = None self.discriminator = None self.version_id = version_id if body is not None: self.body = body @property def version_id(self): """Gets the version_id of this EnableKeyRequest. API版本号 :return: The version_id of this EnableKeyRequest. :rtype: str """ return self._version_id @version_id.setter def version_id(self, version_id): """Sets the version_id of this EnableKeyRequest. API版本号 :param version_id: The version_id of this EnableKeyRequest. :type: str """ self._version_id = version_id @property def body(self): """Gets the body of this EnableKeyRequest. :return: The body of this EnableKeyRequest. :rtype: OperateKeyRequestBody """ return self._body @body.setter def body(self, body): """Sets the body of this EnableKeyRequest. :param body: The body of this EnableKeyRequest. :type: OperateKeyRequestBody """ self._body = body def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: if attr in self.sensitive_list: result[attr] = "****" else: result[attr] = value return result def to_str(self): import simplejson as json return json.dumps(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, EnableKeyRequest): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
[ "hwcloudsdk@huawei.com" ]
hwcloudsdk@huawei.com
b1084a090a7ff81f0b9175324a0fccd57c80d89f
f1a6013a41ea5d49e034d1932991ef039e767e34
/utils/pycraft/networking/types/enum.py
61aa2384964941e48560e53764ea808ae78b02e9
[ "Apache-2.0" ]
permissive
Merrg1n/PCRC
a544c234ea1eea79bb6fb235cc610d14090d6a7f
0af9f6d3a1f9f2e0b78b71241176968b0e5983af
refs/heads/master
2023-01-24T01:16:57.956263
2020-06-18T09:10:11
2020-06-18T09:10:11
256,414,160
2
1
Apache-2.0
2020-04-30T04:01:53
2020-04-17T05:54:22
Python
UTF-8
Python
false
false
3,179
py
"""Types for enumerations of values occurring in packets, including operations for working with these values. The values in an enum are given as class attributes with UPPERCASE names. These classes are usually not supposed to be instantiated, but sometimes an instantiatable class may subclass Enum to provide class enum attributes in addition to other functionality. """ from .utility import Vector __all__ = ( 'Enum', 'BitFieldEnum', 'AbsoluteHand', 'RelativeHand', 'BlockFace', 'Difficulty', 'Dimension', 'GameMode', 'OriginPoint' ) class Enum(object): # Return a human-readable string representation of an enum value. @classmethod def name_from_value(cls, value): for name, name_value in cls.__dict__.items(): if name.isupper() and name_value == value: return name class BitFieldEnum(Enum): @classmethod def name_from_value(cls, value): if not isinstance(value, int): return ret_names = [] ret_value = 0 for cls_name, cls_value in sorted( [(n, v) for (n, v) in cls.__dict__.items() if isinstance(v, int) and n.isupper() and v | value == value], reverse=True, key=lambda p: p[1] ): if ret_value | cls_value != ret_value or cls_value == value: ret_names.append(cls_name) ret_value |= cls_value if ret_value == value: return '|'.join(reversed(ret_names)) if ret_names else '0' # Designation of one of a player's hands, in absolute terms. class AbsoluteHand(Enum): LEFT = 0 RIGHT = 1 # Designation of one a player's hands, relative to a choice of main/off hand. class RelativeHand(Enum): MAIN = 0 OFF = 1 # Designation of one of a block's 6 faces. class BlockFace(Enum): BOTTOM = 0 # -Y TOP = 1 # +Y NORTH = 2 # -Z SOUTH = 3 # +Z WEST = 4 # -X EAST = 5 # +X # A dict mapping Vector tuples to the corresponding BlockFace values. # When accessing this dict, plain tuples also match. For example: # >>> BlockFace.from_vector[0, 0, -1] == BlockFace.NORTH # True from_vector = { Vector(0, -1, 0): BOTTOM, Vector(0, +1, 0): TOP, Vector(0, 0, -1): NORTH, Vector(0, 0, +1): SOUTH, Vector(-1, 0, 0): WEST, Vector(+1, 0, 0): EAST, } # A dict mapping BlockFace values to unit Position tuples. # This is the inverse mapping of face_by_position. For example: # >>> BlockFace.to_vector[BlockFace.NORTH] # Position(x=0, y=0, z=-1) to_vector = {fce: pos for (pos, fce) in from_vector.items()} # Designation of a world's difficulty. class Difficulty(Enum): PEACEFUL = 0 EASY = 1 NORMAL = 2 HARD = 3 # Designation of a world's dimension. class Dimension(Enum): NETHER = -1 OVERWORLD = 0 END = 1 # Designation of a player's gamemode. class GameMode(Enum): SURVIVAL = 0 CREATIVE = 1 ADVENTURE = 2 SPECTATOR = 3 # Currently designates an entity's feet or eyes. # Used in the Face Player Packet class OriginPoint(Enum): FEET = 0 EYES = 1
[ "yqx791125833@gmail.com" ]
yqx791125833@gmail.com
a019180e0075ec7252a926b93dd4c554d208df3b
c7a6f8ed434c86b4cdae9c6144b9dd557e594f78
/ECE364/.PyCharm40/system/python_stubs/348993582/gio/_gio/DataStreamNewlineType.py
c4d1842167c838cc909223916099ae59e915cb29
[]
no_license
ArbalestV/Purdue-Coursework
75d979bbe72106975812b1d46b7d854e16e8e15e
ee7f86145edb41c17aefcd442fa42353a9e1b5d1
refs/heads/master
2020-08-29T05:27:52.342264
2018-04-03T17:59:01
2018-04-03T17:59:01
null
0
0
null
null
null
null
UTF-8
Python
false
false
736
py
# encoding: utf-8 # module gio._gio # from /usr/lib64/python2.6/site-packages/gtk-2.0/gio/_gio.so # by generator 1.136 # no doc # imports import gio as __gio import glib as __glib import gobject as __gobject import gobject._gobject as __gobject__gobject class DataStreamNewlineType(__gobject.GEnum): # no doc def __init__(self, *args, **kwargs): # real signature unknown pass __weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """list of weak references to the object (if defined)""" __dict__ = None # (!) real value is '' __enum_values__ = { 0: 0, 1: 1, 2: 2, 3: 3, } __gtype__ = None # (!) real value is ''
[ "pkalita@princeton.edu" ]
pkalita@princeton.edu
5b327ff182d5d14550e1064d5c2185b50eca57df
297497957c531d81ba286bc91253fbbb78b4d8be
/testing/web-platform/tests/webdriver/tests/bidi/__init__.py
5cf37be6f9713640cde99d8b18bff4479093afbd
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
marco-c/gecko-dev-comments-removed
7a9dd34045b07e6b22f0c636c0a836b9e639f9d3
61942784fb157763e65608e5a29b3729b0aa66fa
refs/heads/master
2023-08-09T18:55:25.895853
2023-08-01T00:40:39
2023-08-01T00:40:39
211,297,481
0
0
NOASSERTION
2019-09-29T01:27:49
2019-09-27T10:44:24
C++
UTF-8
Python
false
false
3,290
py
from typing import Any, Callable, Dict from webdriver.bidi.modules.script import ContextTarget def recursive_compare(expected: Any, actual: Any) -> None: if callable(expected): expected(actual) return assert type(expected) == type(actual) if type(expected) is list: assert len(expected) == len(actual) for index, _ in enumerate(expected): recursive_compare(expected[index], actual[index]) return if type(expected) is dict: assert expected.keys() <= actual.keys(), \ f"Key set should be present: {set(expected.keys()) - set(actual.keys())}" for key in expected.keys(): recursive_compare(expected[key], actual[key]) return assert expected == actual def any_bool(actual: Any) -> None: assert isinstance(actual, bool) def any_dict(actual: Any) -> None: assert isinstance(actual, dict) def any_int(actual: Any) -> None: assert isinstance(actual, int) def any_int_or_null(actual: Any) -> None: if actual is not None: any_int(actual) def any_list(actual: Any) -> None: assert isinstance(actual, list) def any_string(actual: Any) -> None: assert isinstance(actual, str) def any_string_or_null(actual: Any) -> None: if actual is not None: any_string(actual) def int_interval(start: int, end: int) -> Callable[[Any], None]: def _(actual: Any) -> None: any_int(actual) assert start <= actual <= end return _ async def create_console_api_message(bidi_session, context: str, text: str): await bidi_session.script.call_function( function_declaration="""(text) => console.log(text)""", arguments=[{"type": "string", "value": text}], await_promise=False, target=ContextTarget(context["context"]), ) return text async def get_device_pixel_ratio(bidi_session, context: str) -> float: result = await bidi_session.script.call_function( function_declaration="""() => { return window.devicePixelRatio; }""", target=ContextTarget(context["context"]), await_promise=False) return result["value"] async def get_element_dimensions(bidi_session, context, element): result = await bidi_session.script.call_function( arguments=[element], function_declaration="""(element) => { const rect = element.getBoundingClientRect(); return { height: rect.height, width: rect.width } }""", target=ContextTarget(context["context"]), await_promise=False, ) return remote_mapping_to_dict(result["value"]) async def get_viewport_dimensions(bidi_session, context: str): expression = """ ({ height: window.innerHeight || document.documentElement.clientHeight, width: window.innerWidth || document.documentElement.clientWidth, }); """ result = await bidi_session.script.evaluate( expression=expression, target=ContextTarget(context["context"]), await_promise=False, ) return remote_mapping_to_dict(result["value"]) def remote_mapping_to_dict(js_object) -> Dict: obj = {} for key, value in js_object: obj[key] = value["value"] return obj
[ "mcastelluccio@mozilla.com" ]
mcastelluccio@mozilla.com
8e1242fb0e5ba86f9c53c43d6463a61f6ac9212d
bbf1ae079309eca11270422d3f0d259d1515d430
/numerical-tours/python/nt_solutions/ml_4_sgd/exo4.py
a9a0d7a44a6ba0f8f26665a55f1a3befa8b1563f
[ "BSD-2-Clause" ]
permissive
ZichaoDi/Di_MATLABTool
5e6a67b613c4bcf4d904ddc47c2744b4bcea4885
c071291c63685c236f507b2cb893c0316ab6415c
refs/heads/master
2021-08-11T07:28:34.286526
2021-08-04T18:26:46
2021-08-04T18:26:46
149,222,333
9
5
null
null
null
null
UTF-8
Python
false
false
1,091
py
tau = .002/n ElistG = np.zeros( ( int(niter/err_rate), nsamples) ) for irun in np.arange(0,nsamples): w = np.zeros( (p,1) ) G = np.zeros( (p,n) ) # keep track of gradients g = np.zeros( (p,1) ) for it in np.arange(0,niter): if np.mod(it,err_rate)==1: ElistG[ int(it/err_rate),irun ] = E(w,X,y) i = int( np.floor(np.random.rand()*n) ) # draw uniformly g1 = nablaEi(w,i) # update grad g = g - MakeCol(G[:,i]) + g1 G[:,i] = g1.flatten() # w = w - tau * g vmin = np.min( (np.min(Elist), ElistS.flatten().min(), ElistA.flatten().min(), ElistG.flatten().min() ) ) u = np.log10(ElistS-vmin+1e-20) v = np.log10(ElistA -vmin+1e-20) w = np.log10(ElistG -vmin+1e-20) plt.clf plt.plot(1,np.Inf, 'b') plt.plot(1,np.Inf, 'r') plt.plot(1,np.Inf, 'g') plt.plot( np.arange(0,niter,err_rate), u, 'b' ) plt.plot( np.arange(0,niter,err_rate), v, 'r' ) plt.plot( np.arange(0,niter,err_rate), w, 'g' ) plt.axis((1,niter, np.min(w), np.max(w) )) plt.title('$log(E(w_l) - min E)$') plt.legend( ('SGD', 'SGA', 'SAG') )
[ "wendydi@compute001.mcs.anl.gov" ]
wendydi@compute001.mcs.anl.gov
947d0c8aea8acf28e458806c3f6e092fc46c7f4f
9063052d8e2c294efa3b501d42aef2ac59d84fa0
/codingPractice/python/리스트배열.py
7e7e3af621c60fc3cdba6e367467891d40774964
[]
no_license
yes99/practice2020
ffe5502d23038eabea834ebc2b18ff724f849c4a
100ac281f4fe6d0f991213802fbd8524451f1ac2
refs/heads/master
2021-07-08T00:54:19.728874
2021-06-13T05:52:07
2021-06-13T05:52:07
245,789,109
0
1
null
null
null
null
UTF-8
Python
false
false
583
py
gold = ["박인비", "오혜리", "김소희", "구본찬", "장혜진", "기보배", "진종오", "박상영", "최미선", "김우진", "이승윤"] silver = ["김종현", "안바울", "정보경"] iron = ["차동민", "이태훈", "정경은", "신승찬"] print("금메달 리스트") print(gold) print("은메달 리스트") print(silver) print("동메달 리스트") print(iron) print(gold[0]) print(silver[1:2]) print(iron[:5]) gold[1] = "오혜리2" print(gold) medal = gold + silver + iron print(medal) medalcount = len(gold) + len(silver) + len(iron) print(medalcount)
[ "yes950324@naver.com" ]
yes950324@naver.com
a3da7aaf43b349eb9cfafdd0d2439095ae10b4c0
9743d5fd24822f79c156ad112229e25adb9ed6f6
/xai/brain/wordbase/verbs/_patches.py
25782f805aa8ebaefc49a490339be3c69495d80c
[ "MIT" ]
permissive
cash2one/xai
de7adad1758f50dd6786bf0111e71a903f039b64
e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6
refs/heads/master
2021-01-19T12:33:54.964379
2017-01-28T02:00:50
2017-01-28T02:00:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
233
py
from xai.brain.wordbase.verbs._patch import _PATCH #calss header class _PATCHES(_PATCH, ): def __init__(self,): _PATCH.__init__(self) self.name = "PATCHES" self.specie = 'verbs' self.basic = "patch" self.jsondata = {}
[ "xingwang1991@gmail.com" ]
xingwang1991@gmail.com
40638c5b6177ae097333ebc52d7fc8c752ed6428
583fdb9f37dea28ada24e335f1e44ba6cf587770
/多线程/1114 按序打印.py
8f732076821bc5c73d9944b3679d5b9ff3256511
[]
no_license
Ford-z/LeetCode
8c4c30eeaa3d8f02b24c8d0058c60f09c3a6debe
88eeca3780b4dc77efce4f14d317ed1c872cf650
refs/heads/master
2021-11-21T00:51:05.314084
2021-09-16T15:45:18
2021-09-16T15:45:18
194,425,542
1
0
null
null
null
null
UTF-8
Python
false
false
2,403
py
我们提供了一个类: public class Foo {   public void first() { print("first"); }   public void second() { print("second"); }   public void third() { print("third"); } } 三个不同的线程 A、B、C 将会共用一个 Foo 实例。 一个将会调用 first() 方法 一个将会调用 second() 方法 还有一个将会调用 third() 方法 请设计修改程序,以确保 second() 方法在 first() 方法之后被执行,third() 方法在 second() 方法之后被执行。   示例 1: 输入: [1,2,3] 输出: "firstsecondthird" 解释: 有三个线程会被异步启动。 输入 [1,2,3] 表示线程 A 将会调用 first() 方法,线程 B 将会调用 second() 方法,线程 C 将会调用 third() 方法。 正确的输出是 "firstsecondthird"。 示例 2: 输入: [1,3,2] 输出: "firstsecondthird" 解释: 输入 [1,3,2] 表示线程 A 将会调用 first() 方法,线程 B 将会调用 third() 方法,线程 C 将会调用 second() 方法。 正确的输出是 "firstsecondthird"。   提示: 尽管输入中的数字似乎暗示了顺序,但是我们并不保证线程在操作系统中的调度顺序。 你看到的输入格式主要是为了确保测试的全面性。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/print-in-order 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 class Foo: def __init__(self): #在这题里面功能都是类似的,就是添加阻塞,然后释放线程,只是类初始化的时候不能包含有参数,所以要写一句acquire进行阻塞,调用其他函数的时候按顺序release释放。 self.l1 = threading.Lock() self.l1.acquire() self.l2 = threading.Lock() self.l2.acquire() def first(self, printFirst: 'Callable[[], None]') -> None: # printFirst() outputs "first". Do not change or remove this line. printFirst() self.l1.release() def second(self, printSecond: 'Callable[[], None]') -> None: self.l1.acquire() # printSecond() outputs "second". Do not change or remove this line. printSecond() self.l2.release() def third(self, printThird: 'Callable[[], None]') -> None: self.l2.acquire() # printThird() outputs "third". Do not change or remove this line. printThird()
[ "noreply@github.com" ]
Ford-z.noreply@github.com
a5b460ebd46a40b3cf4f710cd39b082a851aadd9
623c053e83ae0641523d777987a438abd7d67c09
/infra02_blast_info_proc.py
34dc557032a8782bf6c8bb7f8b3280a7ab1435ca
[]
no_license
friedpine/BioModule
601a8d3064fea1e60311a6ce4a3a7114166a98e7
59086d9e484c45ac0406099c0f68be8e5e617802
refs/heads/master
2021-01-01T17:31:45.190621
2015-02-02T06:58:55
2015-02-02T06:58:55
21,689,668
0
0
null
null
null
null
UTF-8
Python
false
false
3,194
py
import re,os,sys import subprocess sys.path.append('/data/Analysis/fanxiaoying/project/project01_polyA-RNAseq/modules') import infra01_pos2info as in01 def blast_fastas(fa_db,fa_target,dbfile,outfile,evalue,wordsize): print "Begin Blasting!" cmd1 = "/data/Analysis/fanxiaoying/software/ncbi-blast-2.2.28+/bin/makeblastdb -dbtype nucl -in %s -out %s " %(fa_db,dbfile) cmd2 = "/data/Analysis/fanxiaoying/software/ncbi-blast-2.2.28+/bin/blastn -query %s -task blastn -db %s -outfmt 7 -gapopen 5 -gapextend 2 -penalty -3 -reward 2 -evalue %s -word_size %s -out %s" %(fa_target,dbfile,evalue,wordsize,outfile) subprocess.call(cmd1,shell=True) subprocess.call(cmd2,shell=True) def blast_fmt7_reading(event,file,match_cuf,report): file = open(file) values = [] for line in file: if re.match('^#',line): continue S1 = re.split('\s+',line) if report == 'RC': if int(S1[9])<int(S1[8]) and int(S1[3])>=match_cuf: values.append([event]+S1[0:12]) return values def blast_fmt7_out_read_db_miRNA(file,DB_NAME,tablename,report): import MySQLdb as mb file = open(file) values = [] for line in file: if re.match('^#',line): continue S1 = re.split('\s+',line) if report == 'RC': if int(S1[9])<int(S1[8]): values.append((S1[0],S1[1],S1[6])) conn=mb.connect(host="localhost",user="root",passwd="123456",db=DB_NAME) cursor = conn.cursor() cursor.executemany("insert into "+tablename+" values(%s,%s,%s) ",values); conn.commit() def blast_ref_positions(cursor,species,ref,pos_list1,pos_list2,list1_name,list2_name,evalue,wordsize,match_cuf,folder,record,report,server="TANG"): seq1=in01.get_pos_seqs(cursor,species,ref,pos_list1,server) seq2=in01.get_pos_seqs(cursor,species,ref,pos_list2,server) r1_file = folder+'/'+record+'_r1.fa' r2_file = folder+'/'+record+'_r2.fa' db_file = folder+'/'+record+'_db.db' result_file = folder+'/'+record+'_blast.txt' if len(list1_name) != len(seq1) or len(list1_name) != len(seq1): print "Names not the Same length with Sequences!" return 0 f = open(r1_file,'w') for x in range(len(seq1)): f.write('>%s\n%s\n' %(list1_name[x],seq1[x])) f.close() f = open(r2_file,'w') for x in range(len(seq2)): f.write('>%s\n%s\n' %(list2_name[x],seq2[x])) f.close() blast_fastas(r1_file,r2_file,db_file,result_file,evalue,wordsize) return blast_fmt7_reading(record,result_file,match_cuf,report) def blast_genome_multi_positions(species,r1,r2,evalue,wordsize,report): genome = ref[species]['fa']['genome'] r1_file = './r1.fa' r2_file = './r2.fa' in1.genome_ranges_2_fa_file('mm10',r1,r1_file,'r1') in1.genome_ranges_2_fa_file('mm10',r2,r2_file,'r2') blast_fastas(r1_file,r2_file,'./temp_db.db','./temp_blast_r1r2.txt',evalue,wordsize) result = blast_fmt7_out_read('./temp_blast_r1r2.txt',report) return result def blast_two_sequences(seq1,seq2,evalue,wordsize,report): r1_file = open('./r1.fa','w') r2_file = open('./r2.fa','w') print >>r1_file,'>'+'r1\n'+seq1+'\n' print >>r2_file,'>'+'r2\n'+seq2+'\n' r1_file.close() r2_file.close() blast_fastas('./r1.fa','./r2.fa','./temp_db.db','./temp_blast_r1r2.txt',evalue,wordsize) result = blast_fmt7_out_read('./temp_blast_r1r2.txt',report) return result
[ "friedpine@gmail.com" ]
friedpine@gmail.com
381eea3f35bcda39830a030b2fa50af90ff2ab13
daffa2518efcf00aec9d798c7e32cbb53bd66f01
/fragmenstein/victor/_victor_mode.py
9f0914654d2402a248066a05322bc48b87b4ff6a
[ "MIT" ]
permissive
matteoferla/Fragmenstein
9023235594a002458f7d46eaa8344f3b5df54fb2
c03945c089beec35b7aabb83dc1efd9cc57ac281
refs/heads/master
2023-09-01T09:40:52.695247
2023-08-30T06:30:22
2023-08-30T06:30:22
254,173,036
120
10
MIT
2023-07-06T23:08:02
2020-04-08T18:48:30
Python
UTF-8
Python
false
false
338
py
import enum class VictorMinMode(enum.Enum): """Victor mode for minimisation TODO this is not used yet """ NULL = -1 #: no minimisation at all IGOR = 0 #: use Igor's minimisation (PyRosetta) IGOR_NODISK = 1 #: use Igor's minimisation without writing to disk FRITZ = 2 #: use Fritz's minimisation (openMM)
[ "matteo.ferla@gmail.com" ]
matteo.ferla@gmail.com
4d07e3354d036c43888b12b846be7bc48a1d0f97
527a8837c449d7fd0ccacf33cd6e6be0d6308038
/postAnalysis/combineArffs.py
046b297815849f6e17cea1a83ecc64030741dba0
[]
no_license
nparslow/L2FrenchWritingAnalyser
c4539cf67f6885224d83890c31d95080c49fa175
6708e560d65120d1946f1d08a460ca8fe97a548f
refs/heads/master
2020-12-07T03:50:12.090153
2015-07-18T18:28:12
2015-07-18T18:28:12
39,304,412
0
0
null
null
null
null
UTF-8
Python
false
false
1,792
py
import codecs import re __author__ = 'nparslow' def readarff( filename ): vars = [] rows = [] header = "" with codecs.open( filename, mode="r", encoding="utf8") as f1: indata = False for line in f1: if line.lower().startswith("@attribute"): att, name, typ = re.split(ur'\s', line.strip(), flags=re.UNICODE) vars.append( (att, name, typ) ) elif line.lower().startswith("@data"): indata = True elif indata: row = line.strip().split(',') rows.append(row) else: # add to header header += line return header, vars, rows def main(): arff1 = "/home/nparslow/Documents/AutoCorrige/Corpora/figures/testclass.arff" arff2 = "/home/nparslow/Documents/AutoCorrige/Corpora/figures/testtrees.arff" outarff = "/home/nparslow/Documents/AutoCorrige/Corpora/figures/testcombined.arff" header = "" header1, vars1, rows1 = readarff(arff1) header2, vars2, rows2 = readarff(arff2) with codecs.open( outarff, mode="w", encoding="utf8") as of: of.write(header1) nvars = 0 for i_var in range(len(vars1)-1): var = vars1[i_var] #print var of.write( u"\t".join(var) + "\n") nvars += 1 for i_var in range(len(vars2)): var = vars2[i_var] of.write( "\t".join(var) + "\n") nvars += 1 of.write("\n") of.write("@DATA\n") rowlen = 0 for row1, row2 in zip(rows1, rows2): of.write(",".join(row1[:-1]+row2) + "\n") rowlen = len(row1[:-1] + row2) print "vars", nvars, rowlen if __name__ == "__main__": main()
[ "nparslow@yahoo.com.au" ]
nparslow@yahoo.com.au
0a34545753e9dae7e7f451a5885ac854f7f9310c
be5d853783fab4162981c460c35856bf44bf2148
/mayan/apps/quotas/tests/test_hooks.py
b700c3a9e5d8e422d53b5c8f22e742b1ece03aba
[ "Apache-2.0" ]
permissive
Hita-K/Mayan-EDMS
50900189cf504807aa6e41d72fd8e4fc50d5d5b3
a5b691b28f765d9eea7bf6b2016657c943fbbe4a
refs/heads/master
2023-08-29T08:20:58.859259
2021-11-08T04:40:39
2021-11-08T04:40:39
295,247,959
0
0
NOASSERTION
2021-11-08T04:40:40
2020-09-13T22:21:57
Python
UTF-8
Python
false
false
4,315
py
import logging from mayan.apps.common.tests.base import GenericViewTestCase from mayan.apps.documents.models.document_models import Document from mayan.apps.documents.permissions import ( permission_document_create, permission_document_new_version ) from mayan.apps.documents.tests.base import DocumentTestMixin from mayan.apps.documents.tests.literals import TEST_SMALL_DOCUMENT_PATH from mayan.apps.sources.tests.mixins import ( DocumentUploadWizardViewTestMixin, DocumentVersionUploadViewTestMixin, SourceTestMixin ) from ..classes import QuotaBackend from ..exceptions import QuotaExceeded from ..quota_backends import DocumentCountQuota, DocumentSizeQuota class QuotaHooksTestCase( DocumentTestMixin, DocumentUploadWizardViewTestMixin, DocumentVersionUploadViewTestMixin, SourceTestMixin, GenericViewTestCase ): auto_upload_test_document = False def setUp(self): super(QuotaHooksTestCase, self).setUp() # Increase the initial usage count to 1 by uploading a document # as the test case user. self._upload_test_document(_user=self._test_case_user) self.test_case_silenced_logger_new_level = logging.FATAL + 10 self._silence_logger(name='mayan.apps.sources.views') self._silence_logger(name='mayan.apps.common.middleware.error_logging') def tearDown(self): QuotaBackend.connect_signals() super(QuotaHooksTestCase, self).tearDown() def test_document_quantity_quota_and_source_upload_wizard_view_with_permission(self): self.test_quota_backend = DocumentCountQuota self.test_quota = DocumentCountQuota.create( documents_limit=1, document_type_all=True, document_type_ids=(), group_ids=(), user_all=True, user_ids=(), ) self.test_quota_backend.signal.disconnect( dispatch_uid='quotas_handler_process_signal', sender=self.test_quota_backend.sender ) self.grant_permission(permission=permission_document_create) document_count = Document.objects.count() with self.assertRaises(expected_exception=QuotaExceeded): self._request_upload_wizard_view() self.assertEqual(Document.objects.count(), document_count) def test_document_size_quota_and_source_upload_wizard_view_with_permission(self): self.test_quota_backend = DocumentSizeQuota self.test_quota = DocumentSizeQuota.create( document_size_limit=0.01, document_type_all=True, document_type_ids=(), group_ids=(), user_all=True, user_ids=(), ) self.test_quota_backend.signal.disconnect( dispatch_uid='quotas_handler_process_signal', sender=self.test_quota_backend.sender ) self.grant_permission(permission=permission_document_create) document_count = Document.objects.count() with self.assertRaises(expected_exception=QuotaExceeded): self._request_upload_wizard_view() self.assertEqual(Document.objects.count(), document_count) def test_document_size_quota_and_document_version_upload_with_access(self): self.test_quota_backend = DocumentSizeQuota self.test_quota = DocumentSizeQuota.create( document_size_limit=0.01, document_type_all=True, document_type_ids=(), group_ids=(), user_all=True, user_ids=(), ) self.test_quota_backend.signal.disconnect( dispatch_uid='quotas_handler_process_signal', sender=self.test_quota_backend.sender ) self.grant_access( obj=self.test_document, permission=permission_document_new_version ) version_count = self.test_document.versions.count() with self.assertRaises(expected_exception=QuotaExceeded): with open(TEST_SMALL_DOCUMENT_PATH, mode='rb') as file_object: self._request_document_version_upload_view( source_file=file_object ) self.test_document.refresh_from_db() self.assertEqual( self.test_document.versions.count(), version_count )
[ "roberto.rosario@mayan-edms.com" ]
roberto.rosario@mayan-edms.com
bf4d1ed9fc87262204919ea3353d134aad41ab79
30eb942d849dab9250bbd541a8d7128d15be8556
/rimware_impl/peripheral_simulator/characteristics/DeviceInfo.py
f90cbb756673fe3a8f42f6ed4623ff64bea671bd
[]
no_license
cjhuo/Lab_projects-EcoBT-HOST-N-SERVER
55e42b1e4d5f88bc978f5b6c07ab3798626a88fa
396cb823ed74552985f4afa157fe3887afe48b65
refs/heads/master
2020-06-06T12:25:23.111232
2014-01-31T07:03:02
2014-01-31T07:03:02
26,940,140
0
0
null
null
null
null
UTF-8
Python
false
false
1,461
py
''' Created on Jan 25, 2014 @author: cjhuo ''' from Foundation import * #from PyObjCTools import AppHelper from config_peripheral import * from objc import * import struct, binascii from Characteristic import Characteristic class DeviceInfo(Characteristic): def initializeInstance(self): print "Initializing Characteristic Instance" self.instance = CBMutableCharacteristic.alloc().initWithType_properties_value_permissions_(CBUUID.UUIDWithString_(self.UUID), CBCharacteristicPropertyRead, nil, # ensures the value is treated dynamically CBAttributePermissionsReadable) def initializeDescriptors(self): print "Initializing descriptors.." self.instance._.descriptors = [CBMutableDescriptor.alloc(). initWithType_value_(CBUUID.UUIDWithString_(CBUUIDCharacteristicUserDescriptionString), u'DeviceInformation')] ''' return unencrypted return value, but should pre-packed into string if value is not a string ''' def handleReadRequest(self): message = 0xC8E0EBFFFE16B31A data = struct.pack("@Q", message) return NSData.alloc().initWithBytes_length_(data, len(data))
[ "chengjia.huo@gmail.com" ]
chengjia.huo@gmail.com
985bbe4a43dea75355373e07eedc193387f121d0
98cb310b3a8dea5e07dc2359a07ef623e9a153d1
/web-env/bin/html2text
e2e734afa81cc52de74bedd9ed310e0c7fce4171
[ "MIT" ]
permissive
Amirsorouri00/web-search-engine
6c600fb924f3b2e883f746e8075e33954effcc79
00bf463b29490f5285ee44cd351c6de131f04f3a
refs/heads/master
2020-06-01T12:46:37.612714
2019-07-24T14:25:54
2019-07-24T14:25:54
190,783,910
0
0
MIT
2019-06-07T17:30:51
2019-06-07T17:30:51
null
UTF-8
Python
false
false
308
#!/home/amirsorouri00/Desktop/search-engine/myproject/ui/search-engine/web-search-engine/web-env/bin/python3.7 # -*- coding: utf-8 -*- import re import sys from html2text.cli import main if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit(main())
[ "amirsorouri26@gmail.com" ]
amirsorouri26@gmail.com
d1450be5d59eb3da24bfbe1d94a664b1aa7aeebe
9743d5fd24822f79c156ad112229e25adb9ed6f6
/xai/brain/wordbase/nouns/_leaved.py
bdb9559efe761b1e3540d4581ec7bf021b77e9ab
[ "MIT" ]
permissive
cash2one/xai
de7adad1758f50dd6786bf0111e71a903f039b64
e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6
refs/heads/master
2021-01-19T12:33:54.964379
2017-01-28T02:00:50
2017-01-28T02:00:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
231
py
from xai.brain.wordbase.nouns._leave import _LEAVE #calss header class _LEAVED(_LEAVE, ): def __init__(self,): _LEAVE.__init__(self) self.name = "LEAVED" self.specie = 'nouns' self.basic = "leave" self.jsondata = {}
[ "xingwang1991@gmail.com" ]
xingwang1991@gmail.com
e29494b2115d7a7c7d0572aa10dc2e2accfe0c66
ef875440cf82b6eed61bf6d9d0c6acfae5f90ef4
/Assument/1.py
a444598961f3afee6b63ec45bdecaa2c7788745a
[]
no_license
Nitesh101/test
5ab9b1e23167f8496d90d15484d57328b7f1430e
4c413b3a056a633c5bcf93ae21c999ff67eeaa95
refs/heads/master
2020-03-29T09:04:32.723099
2018-09-21T09:33:41
2018-09-21T09:33:41
149,740,238
0
0
null
null
null
null
UTF-8
Python
false
false
147
py
x = int(input("Enter a x value : ")) y = int(input("Enter a y value : ")) for i in range(1,x+1): for j in range(1,y+1): print i*j, print "\n"
[ "m.veeranitesh@gmail.com" ]
m.veeranitesh@gmail.com
eef711bdb5d2e6ade393c56e5b4d273b3421f4be
3f7d5999bb7e5a75454c8df2c5a8adcd1a8341ff
/tests/unit/modules/network/fortios/test_fortios_log_webtrends_setting.py
769546de3cc54d9be79f8ace802727bdb7211b7d
[]
no_license
ansible-collection-migration/ansible.fortios
f7b1a7a0d4b69c832403bee9eb00d99f3be65e74
edad6448f7ff4da05a6c856b0e7e3becd0460f31
refs/heads/master
2020-12-18T13:08:46.739473
2020-02-03T22:10:49
2020-02-03T22:10:49
235,393,556
0
0
null
null
null
null
UTF-8
Python
false
false
6,106
py
# Copyright 2019 Fortinet, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <https://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import json import pytest from mock import ANY from ansible_collections.ansible.fortios.plugins.module_utils.network.fortios.fortios import FortiOSHandler try: from ansible_collections.ansible.fortios.plugins.modules import fortios_log_webtrends_setting except ImportError: pytest.skip("Could not load required modules for testing", allow_module_level=True) @pytest.fixture(autouse=True) def connection_mock(mocker): connection_class_mock = mocker.patch('ansible_collections.ansible.fortios.plugins.modules.fortios_log_webtrends_setting.Connection') return connection_class_mock fos_instance = FortiOSHandler(connection_mock) def test_log_webtrends_setting_creation(mocker): schema_method_mock = mocker.patch('ansible_collections.ansible.fortios.plugins.module_utils.network.fortios.fortios.FortiOSHandler.schema') set_method_result = {'status': 'success', 'http_method': 'POST', 'http_status': 200} set_method_mock = mocker.patch('ansible_collections.ansible.fortios.plugins.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result) input_data = { 'username': 'admin', 'state': 'present', 'log_webtrends_setting': { 'server': '192.168.100.3', 'status': 'enable' }, 'vdom': 'root'} is_error, changed, response = fortios_log_webtrends_setting.fortios_log_webtrends(input_data, fos_instance) expected_data = { 'server': '192.168.100.3', 'status': 'enable' } set_method_mock.assert_called_with('log.webtrends', 'setting', data=expected_data, vdom='root') schema_method_mock.assert_not_called() assert not is_error assert changed assert response['status'] == 'success' assert response['http_status'] == 200 def test_log_webtrends_setting_creation_fails(mocker): schema_method_mock = mocker.patch('ansible_collections.ansible.fortios.plugins.module_utils.network.fortios.fortios.FortiOSHandler.schema') set_method_result = {'status': 'error', 'http_method': 'POST', 'http_status': 500} set_method_mock = mocker.patch('ansible_collections.ansible.fortios.plugins.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result) input_data = { 'username': 'admin', 'state': 'present', 'log_webtrends_setting': { 'server': '192.168.100.3', 'status': 'enable' }, 'vdom': 'root'} is_error, changed, response = fortios_log_webtrends_setting.fortios_log_webtrends(input_data, fos_instance) expected_data = { 'server': '192.168.100.3', 'status': 'enable' } set_method_mock.assert_called_with('log.webtrends', 'setting', data=expected_data, vdom='root') schema_method_mock.assert_not_called() assert is_error assert not changed assert response['status'] == 'error' assert response['http_status'] == 500 def test_log_webtrends_setting_idempotent(mocker): schema_method_mock = mocker.patch('ansible_collections.ansible.fortios.plugins.module_utils.network.fortios.fortios.FortiOSHandler.schema') set_method_result = {'status': 'error', 'http_method': 'DELETE', 'http_status': 404} set_method_mock = mocker.patch('ansible_collections.ansible.fortios.plugins.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result) input_data = { 'username': 'admin', 'state': 'present', 'log_webtrends_setting': { 'server': '192.168.100.3', 'status': 'enable' }, 'vdom': 'root'} is_error, changed, response = fortios_log_webtrends_setting.fortios_log_webtrends(input_data, fos_instance) expected_data = { 'server': '192.168.100.3', 'status': 'enable' } set_method_mock.assert_called_with('log.webtrends', 'setting', data=expected_data, vdom='root') schema_method_mock.assert_not_called() assert not is_error assert not changed assert response['status'] == 'error' assert response['http_status'] == 404 def test_log_webtrends_setting_filter_foreign_attributes(mocker): schema_method_mock = mocker.patch('ansible_collections.ansible.fortios.plugins.module_utils.network.fortios.fortios.FortiOSHandler.schema') set_method_result = {'status': 'success', 'http_method': 'POST', 'http_status': 200} set_method_mock = mocker.patch('ansible_collections.ansible.fortios.plugins.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result) input_data = { 'username': 'admin', 'state': 'present', 'log_webtrends_setting': { 'random_attribute_not_valid': 'tag', 'server': '192.168.100.3', 'status': 'enable' }, 'vdom': 'root'} is_error, changed, response = fortios_log_webtrends_setting.fortios_log_webtrends(input_data, fos_instance) expected_data = { 'server': '192.168.100.3', 'status': 'enable' } set_method_mock.assert_called_with('log.webtrends', 'setting', data=expected_data, vdom='root') schema_method_mock.assert_not_called() assert not is_error assert changed assert response['status'] == 'success' assert response['http_status'] == 200
[ "ansible_migration@example.com" ]
ansible_migration@example.com
7bba4954b0a42558a69b51b0de935e1b954ee6d7
cc1ca9bd521e74905ce5c251c1c199772a85f457
/c7n/filters/health.py
fd0197698f705dde5c5639ee66b96dbde0a7293f
[ "Apache-2.0" ]
permissive
anup19991/cloud-custodian
17d2899a8f7875f4a309fd9189f152e8411a9fcb
b9d7083f8688d41950d264526d064b62d030ed9b
refs/heads/master
2021-01-18T14:42:21.899375
2018-02-11T01:15:22
2018-02-11T01:15:22
89,010,520
0
0
null
2017-04-21T18:01:54
2017-04-21T18:01:54
null
UTF-8
Python
false
false
3,523
py
# Copyright 2016 Capital One Services, 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. import itertools from c7n.utils import local_session, chunks, type_schema from .core import Filter class HealthEventFilter(Filter): """Check if there are health events related to the resources Health events are stored as annotation on a resource. """ schema = type_schema( 'health-event', types={'type': 'array', 'items': {'type': 'string'}}, statuses={'type': 'array', 'items': { 'type': 'string', 'enum': ['open', 'upcoming', 'closed'] }}) permissions = ('health:DescribeEvents', 'health:DescribeAffectedEntities', 'health:DescribeEventDetails') def process(self, resources, event=None): if not resources: return resources client = local_session(self.manager.session_factory).client('health') f = self.get_filter() resource_map = {r[self.manager.get_model().id]: r for r in resources} found = set() seen = set() for resource_set in chunks(resource_map.keys(), 100): f['entityValues'] = resource_set events = client.describe_events(filter=f)['events'] events = [e for e in events if e['arn'] not in seen] entities = [] self.process_event(events, entities) event_map = {e['arn']: e for e in events} for e in entities: rid = e['entityValue'] if rid not in resource_map: continue resource_map[rid].setdefault( 'c7n:HealthEvent', []).append(event_map[e['eventArn']]) found.add(rid) seen.update(event_map.keys()) return [resource_map[rid] for rid in found] def get_filter(self): m = self.manager if m.data['resource'] == 'ebs': service = 'EBS' else: service = m.get_model().service.upper() f = {'services': [service], 'eventStatusCodes': self.data.get( 'statuses', ['open', 'upcoming'])} if self.data.get('types'): f['eventTypeCodes'] = self.data.get('types') return f def process_event(self, health_events, entities): client = local_session(self.manager.session_factory).client('health') for event_set in chunks(health_events, 10): event_map = {e['arn']: e for e in event_set} for d in client.describe_event_details( eventArns=event_map.keys()).get('successfulSet', ()): event_map[d['event']['arn']]['Description'] = d[ 'eventDescription']['latestDescription'] paginator = client.get_paginator('describe_affected_entities') entities.extend(list(itertools.chain( *[p['entities']for p in paginator.paginate( filter={'eventArns': event_map.keys()})])))
[ "kapilt@gmail.com" ]
kapilt@gmail.com
3d2c196a911f8a01f1c1859e684b2e8d2cb128c1
ccf94dcb6b1500fcbbd56964ae8c4832a496b8b3
/python/baiduads-sdk-auto/test/test_get_label_data_request_wrapper.py
15931040218f882420fd9f73bfbedbf4b353fd59
[ "Apache-2.0" ]
permissive
baidu/baiduads-sdk
24c36b5cf3da9362ec5c8ecd417ff280421198ff
176363de5e8a4e98aaca039e4300703c3964c1c7
refs/heads/main
2023-06-08T15:40:24.787863
2023-05-20T03:40:51
2023-05-20T03:40:51
446,718,177
16
11
Apache-2.0
2023-06-02T05:19:40
2022-01-11T07:23:17
Python
UTF-8
Python
false
false
984
py
""" dev2 api schema 'dev2.baidu.com' api schema # noqa: E501 Generated by: https://openapi-generator.tech """ import sys import unittest import baiduads from baiduads.common.model.api_request_header import ApiRequestHeader from baiduads.videodata.model.label_data_request import LabelDataRequest globals()['ApiRequestHeader'] = ApiRequestHeader globals()['LabelDataRequest'] = LabelDataRequest from baiduads.videodata.model.get_label_data_request_wrapper import GetLabelDataRequestWrapper class TestGetLabelDataRequestWrapper(unittest.TestCase): """GetLabelDataRequestWrapper unit test stubs""" def setUp(self): pass def tearDown(self): pass def testGetLabelDataRequestWrapper(self): """Test GetLabelDataRequestWrapper""" # FIXME: construct object with mandatory attributes with example values # model = GetLabelDataRequestWrapper() # noqa: E501 pass if __name__ == '__main__': unittest.main()
[ "jiangyuan04@baidu.com" ]
jiangyuan04@baidu.com
6f3406da83fa8c0692c04a30a556eac010749755
95495baeb47fd40b9a7ecb372b79d3847aa7a139
/test/test_prefer_life_time.py
e4414159a58df5761302ecb4da13ca46c2fb3b58
[]
no_license
pt1988/fmc-api
b1d8ff110e12c13aa94d737f3fae9174578b019c
075f229585fcf9bd9486600200ff9efea5371912
refs/heads/main
2023-01-07T09:22:07.685524
2020-10-30T03:21:24
2020-10-30T03:21:24
308,226,669
0
0
null
null
null
null
UTF-8
Python
false
false
1,194
py
# coding: utf-8 """ Cisco Firepower Management Center Open API Specification **Specifies the REST URLs and methods supported in the Cisco Firepower Management Center API. Refer to the version specific [REST API Quick Start Guide](https://www.cisco.com/c/en/us/support/security/defense-center/products-programming-reference-guides-list.html) for additional information.** # noqa: E501 OpenAPI spec version: 1.0.0 Contact: tac@cisco.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest import swagger_client from swagger_client.models.prefer_life_time import PreferLifeTime # noqa: E501 from swagger_client.rest import ApiException class TestPreferLifeTime(unittest.TestCase): """PreferLifeTime unit test stubs""" def setUp(self): pass def tearDown(self): pass def testPreferLifeTime(self): """Test PreferLifeTime""" # FIXME: construct object with mandatory attributes with example values # model = swagger_client.models.prefer_life_time.PreferLifeTime() # noqa: E501 pass if __name__ == '__main__': unittest.main()
[ "pt1988@gmail.com" ]
pt1988@gmail.com
acc28517932c94119c7bdabb55a776e1622cd13c
3637fe729395dac153f7abc3024dcc69e17f4e81
/reference/ucmdb/discovery/plugins_weblogic_server_domain.py
8f752e1bf03c9a7c22e458a8f667ce33641411a7
[]
no_license
madmonkyang/cda-record
daced6846c2456f20dddce7f9720602d1583a02a
c431e809e8d0f82e1bca7e3429dd0245560b5680
refs/heads/master
2023-06-15T08:16:46.230569
2021-07-15T16:27:36
2021-07-15T16:27:36
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,831
py
#coding=utf-8 from plugins import Plugin from appilog.common.system.types.vectors import ObjectStateHolderVector from appilog.common.system.types import ObjectStateHolder import ip_addr import netutils import weblogic import modeling import weblogic_by_shell import jee import file_system from java.lang import Exception as JException import weblogic_discoverer import logger class WeblogicPlugin: def __init__(self): Plugin.__init__(self) def getProcessName(self): raise NotImplementedError() def isApplicable(self, context): return context.application.getProcess(self.getProcessName()) is not None def process(self, context): self.enrichAppServerOsh(context, self.getProcessName()) def enrichAppServerOsh(self, context, processName): r'''Goal of this is to set for reported Weblogic AS - administrative domain name - application type as Application Server (AS) @types: applications.ApplicationSignatureContext, str ''' # @types: ProcessObject process = context.application.getProcess(processName) # compose function to get process by PID required to get # domain root directory path appComponent = context.application.getApplicationComponent() applicationSignature = appComponent.getApplicationSignature() processInfoManager = applicationSignature.getProcessesManager() # here it is - function accept PID and returns process or None getProcessByPid = (processInfoManager and processInfoManager.getProcessByPid or (lambda *args: None) ) # first of all set application type as AS for the server OSH serverOsh = context.application.getOsh() modeling.setAppServerType(serverOsh) # initialize required data loadExternalDtd = 0 shell = context.client # for shell jobs we have shellutils.Shell instance fs = file_system.createFileSystem(shell) servers = None try: # find out path of domain root directory domainRootPath = weblogic_by_shell.getDomainRootDirPath(shell, fs, process, getProcessByPid) except: logger.debug("Domain root directory path cannot be found from the runtime information.") return try: domainLayout = weblogic_discoverer.createDomainLayout(fs, domainRootPath) parser = weblogic_discoverer.createDomainConfigParserByLayout(domainLayout, loadExternalDtd) domainDescriptorFile = domainLayout.getFileContent( domainLayout.getDomainConfigFilePath() ) domainDescriptor = parser.parseConfiguration(domainDescriptorFile.content) except ValueError, ex: logger.reportWarning("Not supported DomainLayout and so weblogic discovery will be partial") logger.debugException("Not supported DomainLayout and so weblogic discovery will be partial") except (Exception, JException): logger.warnException("Failed to process config.xml") else: # get version of the platform versionInfo = domainDescriptor.versionInfo logger.info("Platform version is %s" % versionInfo) domainName = domainDescriptor.getName() # update server administrative domain attribute modeling.setJ2eeServerAdminDomain(serverOsh, domainName) servers = domainDescriptor.getServers() for server in servers: if server.getName() == serverOsh.getAttributeValue('name'): serverFullName = jee.ServerTopologyBuilder()._composeFullName(server) serverOsh.setAttribute('j2eeserver_fullname', serverFullName) break ##reportEndpointByConfigFile self.reportEndpointByConfigFile(context,shell,servers) def reportEndpointByConfigFile(self,context,shell,servers): logger.debug("reporting endpoints for weblogic using configfile") endpointOSHV = ObjectStateHolderVector() for server in servers: serverRole = server.getRole(weblogic.ServerRole) port = None if serverRole: port = serverRole.getPort() host = server.address ip = None if port: if not host or host == '*' or host == '127.0.0.1': if context.application.getApplicationIp(): ip = context.application.getApplicationIp() elif netutils.isValidIp(host): ip = host else: ip = netutils.resolveIP(shell,host) endpoint = netutils.Endpoint(port, netutils.ProtocolType.TCP_PROTOCOL, ip) endpointOSH = modeling.createIpServerOSH(endpoint) hostosh = modeling.createHostOSH(ip) endpointOSH.setContainer(hostosh) if server.getName() == context.application.getOsh().getAttributeValue('name'): linkOsh = modeling.createLinkOSH("usage", context.application.getOsh(), endpointOSH) endpointOSHV.add(linkOsh) endpointOSHV.add(endpointOSH) logger.debug('Get ip using configfile config.xml:',ip) logger.debug('Get port using configfile config.xml:', port) if endpointOSHV: context.resultsVector.addAll(endpointOSHV) class WeblogicServerDomainPluginWindows(WeblogicPlugin, Plugin): def getProcessName(self): return 'java.exe' class WeblogicServerDomainPluginUnix(WeblogicPlugin, Plugin): def getProcessName(self): return 'java'
[ "silentbalanceyh@126.com" ]
silentbalanceyh@126.com
834f4414c63dd5c819065c0268b730a14f7cb13b
14373275670c1f3065ce9ae195df142146e2c1a4
/stubs/influxdb-client/influxdb_client/domain/import_declaration.pyi
559312f7d5ec4379c951710d415c7ad89c794866
[ "Apache-2.0", "MIT" ]
permissive
sobolevn/typeshed
eb7af17c06a9722f23c337e6b9a4726223155d58
d63a82640390a9c130e0fe7d409e8b0b836b7c31
refs/heads/master
2023-08-04T05:59:29.447015
2023-06-14T21:27:53
2023-06-14T21:27:53
216,265,622
2
0
Apache-2.0
2022-02-08T10:40:53
2019-10-19T20:21:25
Python
UTF-8
Python
false
false
585
pyi
from _typeshed import Incomplete class ImportDeclaration: openapi_types: Incomplete attribute_map: Incomplete discriminator: Incomplete def __init__(self, type: Incomplete | None = None, _as: Incomplete | None = None, path: Incomplete | None = None) -> None: ... @property def type(self): ... @type.setter def type(self, type) -> None: ... @property def path(self): ... @path.setter def path(self, path) -> None: ... def to_dict(self): ... def to_str(self): ... def __eq__(self, other): ... def __ne__(self, other): ...
[ "noreply@github.com" ]
sobolevn.noreply@github.com
f8d0456a377fac7fe3c6207cc8e28e80690af499
0ca435ec92edb5c580c994c29dcab552bfdbc817
/setup.py
4987fdd5cddad4d35abe5c3b3eeac2821ff7d15f
[ "BSD-3-Clause" ]
permissive
gabrielhurley/django-wymeditor
4a28027ce4e5a41ae42cb9c2923c14846fd51dcf
1f45ce696688ee6e849e8dfafd7d55a1bcd4b045
refs/heads/master
2020-06-05T00:11:58.352380
2013-10-23T21:05:03
2013-10-23T21:05:03
1,621,672
0
2
BSD-3-Clause
2018-08-13T22:44:22
2011-04-16T01:48:23
JavaScript
UTF-8
Python
false
false
983
py
from setuptools import setup, find_packages setup(name='django-wymeditor', version='1.0', description='A Django application that contains a widget to render a form field with a WYMEditor interface.', long_description=open('README.rst').read(), author='Gabriel Hurley', author_email='gabriel@strikeawe.com', license='BSD', url='https://github.com/gabrielhurley/django-wymeditor', download_url='git://github.com/gabrielhurley/django-wymeditor.git', packages=find_packages(), include_package_data=True, zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Utilities' ], )
[ "gabriel@strikeawe.com" ]
gabriel@strikeawe.com
2f62aa7e8a4bdb96e448450594d045f0ccf6d831
907b3bbd44c95be1542a36feaadb6a71b724579f
/files/usr/google-cloud-sdk/.install/.backup/lib/surface/compute/scp.py
cd2981521d71cab0a31aa56c33a8dabdd0d6aa96
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
vo0doO/com.termux
2d8f536c1a5dbd7a091be0baf181e51f235fb941
c97dd7b906e5ef3ec157581fd0bcadd3e3fc220e
refs/heads/master
2020-12-24T09:40:30.612130
2016-11-21T07:47:25
2016-11-21T07:47:25
73,282,539
2
2
null
2020-07-24T21:33:03
2016-11-09T12:33:01
Python
UTF-8
Python
false
false
6,781
py
# Copyright 2014 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. """Implements the command for copying files from and to virtual machines.""" import collections from googlecloudsdk.api_lib.compute import ssh_utils from googlecloudsdk.calliope import actions from googlecloudsdk.calliope import base from googlecloudsdk.calliope import exceptions from googlecloudsdk.command_lib.compute import flags from googlecloudsdk.core import log from googlecloudsdk.core import properties RemoteFile = collections.namedtuple( 'RemoteFile', ['user', 'instance_name', 'file_path']) LocalFile = collections.namedtuple( 'LocalFile', ['file_path']) @base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA) class Scp(ssh_utils.BaseSSHCLICommand): """Copy files to and from Google Compute Engine virtual machines.""" @staticmethod def Args(parser): ssh_utils.BaseSSHCLICommand.Args(parser) parser.add_argument( '--port', help='The port to connect to.') parser.add_argument( '--recurse', action='store_true', help='Upload directories recursively.') parser.add_argument( '--compress', action='store_true', help='Enable compression.') parser.add_argument( '--scp-flag', action='append', help='Extra flag to be sent to scp. This flag may be repeated.') parser.add_argument( 'sources', help='Specifies the files to copy.', metavar='[[USER@]INSTANCE:]SRC', nargs='+') parser.add_argument( 'destination', help='Specifies a destination for the source files.', metavar='[[USER@]INSTANCE:]DEST') # TODO(b/21515936): Use flags.AddZoneFlag when copy_files supports URIs zone = parser.add_argument( '--zone', help='The zone of the instance to copy files to/from.', action=actions.StoreProperty(properties.VALUES.compute.zone)) zone.detailed_help = ( 'The zone of the instance to copy files to/from.\n\n' + flags.ZONE_PROPERTY_EXPLANATION) def Run(self, args): super(Scp, self).Run(args) file_specs = [] # Parses the positional arguments. for arg in args.sources + [args.destination]: if ssh_utils.IsScpLocalPath(arg): file_specs.append(LocalFile(arg)) else: user_host, file_path = arg.split(':', 1) user_host_parts = user_host.split('@', 1) if len(user_host_parts) == 1: user = ssh_utils.GetDefaultSshUsername(warn_on_account_user=True) instance = user_host_parts[0] else: user, instance = user_host_parts file_specs.append(RemoteFile(user, instance, file_path)) log.debug('Normalized arguments: %s', file_specs) # Validates the positional arguments. # TODO(b/21515495): Look into relaxing these conditions. sources = file_specs[:-1] destination = file_specs[-1] if isinstance(destination, LocalFile): for source in sources: if isinstance(source, LocalFile): raise exceptions.ToolException( 'All sources must be remote files when the destination ' 'is local.') else: # RemoteFile for source in sources: if isinstance(source, RemoteFile): raise exceptions.ToolException( 'All sources must be local files when the destination ' 'is remote.') instances = set() for file_spec in file_specs: if isinstance(file_spec, RemoteFile): instances.add(file_spec.instance_name) if len(instances) > 1: raise exceptions.ToolException( 'Copies must involve exactly one virtual machine instance; ' 'your invocation refers to [{0}] instances: [{1}].'.format( len(instances), ', '.join(sorted(instances)))) instance_ref = self.CreateZonalReference(instances.pop(), args.zone) instance = self.GetInstance(instance_ref) external_ip_address = ssh_utils.GetExternalIPAddress(instance) # Builds the scp command. scp_args = [self.scp_executable] if not args.plain: scp_args.extend(self.GetDefaultFlags()) scp_args.extend(self.GetHostKeyArgs(args, instance)) # apply args if args.quiet: scp_args.append('-q') if args.port: scp_args.extend(['-P', args.port]) if args.recurse: scp_args.append('-r') if args.compress: scp_args.append('-C') if args.scp_flag: scp_args.extend(args.scp_flag) for file_spec in file_specs: if isinstance(file_spec, LocalFile): scp_args.append(file_spec.file_path) else: scp_args.append('{0}:{1}'.format( ssh_utils.UserHost(file_spec.user, external_ip_address), file_spec.file_path)) self.ActuallyRun(args, scp_args, user, instance) Scp.detailed_help = { 'brief': 'Copy files to and from Google Compute Engine virtual machines ' 'via scp', 'DESCRIPTION': """\ *{command}* copies files between a virtual machine instance and your local machine using the scp command. To denote a remote file, prefix the file name with the virtual machine instance name (e.g., _example-instance_:~/_FILE_). To denote a local file, do not add a prefix to the file name (e.g., ~/_FILE_). For example, to copy a remote directory to your local host, run: $ {command} example-instance:~/REMOTE-DIR ~/LOCAL-DIR --zone us-central1-a In the above example, ``~/REMOTE-DIR'' from ``example-instance'' is copied into the ~/_LOCAL-DIR_ directory. Conversely, files from your local computer can be copied to a virtual machine: $ {command} ~/LOCAL-FILE-1 ~/LOCAL-FILE-2 example-instance:~/REMOTE-DIR --zone us-central1-a If a file contains a colon (``:''), you must specify it by either using an absolute path or a path that begins with ``./''. Under the covers, *scp(1)* or pscp (on Windows) is used to facilitate the transfer. When the destination is local, all sources must be the same virtual machine instance. When the destination is remote, all source must be local. """, }
[ "kirsanov.bvt@gmail.com" ]
kirsanov.bvt@gmail.com
79bf5943ed0355ff765fec1898ec3a9f95176f7d
b3c47795e8b6d95ae5521dcbbb920ab71851a92f
/Nowcoder/剑指Offer/重建二叉树.py
c113259f8d4086abb6711c6d00a80c6348dd2027
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
Wizmann/ACM-ICPC
6afecd0fd09918c53a2a84c4d22c244de0065710
7c30454c49485a794dcc4d1c09daf2f755f9ecc1
refs/heads/master
2023-07-15T02:46:21.372860
2023-07-09T15:30:27
2023-07-09T15:30:27
3,009,276
51
23
null
null
null
null
UTF-8
Python
false
false
532
py
# -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # 返回构造的TreeNode根节点 def reConstructBinaryTree(self, pre, tin): if not pre: return None rv = pre.pop(0) ri = tin.index(rv) root = TreeNode(rv) root.left = self.reConstructBinaryTree(pre[:ri], tin[:ri]) root.right = self.reConstructBinaryTree(pre[ri:], tin[ri + 1:]) return root
[ "noreply@github.com" ]
Wizmann.noreply@github.com
940fbf84801f94dd628850923b61ce9e97a7efe4
61c109344f8bcb822168152cc16c11d05cf6aa70
/django_coverage_plugin/plugin.py
50800f39f54eebb095f6dc3e480f973be846851b
[]
no_license
rfleschenberg/django_coverage_plugin
61a291b0321cb2c3b78ec8bb6719fb550ca35d44
ef46934b55043dbbb8f6a21f60e26477ce7fc8ec
refs/heads/master
2021-01-18T20:27:34.806564
2015-01-16T00:09:28
2015-01-16T00:09:42
null
0
0
null
null
null
null
UTF-8
Python
false
false
7,464
py
"""The Django coverage plugin.""" from __future__ import print_function, unicode_literals import os.path from six.moves import range import coverage.plugin import django from django.template import Lexer, TextNode from django.template.base import TOKEN_MAPPING from django.template import TOKEN_BLOCK, TOKEN_TEXT, TOKEN_VAR SHOW_PARSING = False SHOW_TRACING = False if 0: from blessed import Terminal t = Terminal() # TODO: Add a check for TEMPLATE_DEBUG, and make noise if it is false. class Plugin(coverage.plugin.CoveragePlugin, coverage.plugin.FileTracer): def __init__(self, options): super(Plugin, self).__init__(options) self.django_dir = os.path.dirname(django.__file__) self.django_template_dir = os.path.join(self.django_dir, "template") self.source_map = {} # --- CoveragePlugin methods def file_tracer(self, filename): if filename.startswith(self.django_template_dir): if "templatetags" not in filename: return self return None def file_reporter(self, filename): return FileReporter(filename) # --- FileTracer methods def has_dynamic_source_filename(self): return True def dynamic_source_filename(self, filename, frame): if frame.f_code.co_name != 'render': return None locals = frame.f_locals render_self = locals['self'] if 0: dump_frame(frame) try: source = render_self.source origin = source[0] filename = origin.name return filename except (AttributeError, IndexError): pass return None def line_number_range(self, frame): assert frame.f_code.co_name == 'render' render_self = frame.f_locals['self'] source = render_self.source if SHOW_TRACING: print("{!r}: {}".format(render_self, source)) s_start, s_end = source[1] if isinstance(render_self, TextNode): text = render_self.s first_line = text.splitlines(True)[0] if first_line.isspace(): s_start += len(first_line) line_map = self.get_line_map(source[0].name) start = get_line_number(line_map, s_start) end = get_line_number(line_map, s_end-1) if start < 0 or end < 0: return -1, -1 return start, end # --- FileTracer helpers def get_line_map(self, filename): """The line map for `filename`. A line map is a list of character offsets, indicating where each line in the text begins. For example, a line map like this:: [13, 19, 30] means that line 2 starts at character 13, line 3 starts at 19, etc. Line 1 always starts at character 0. """ if filename not in self.source_map: with open(filename) as template_file: template_source = template_file.read() if 0: # change to see the template text for i in range(0, len(template_source), 10): print("%3d: %r" % (i, template_source[i:i+10])) self.source_map[filename] = make_line_map(template_source) return self.source_map[filename] class FileReporter(coverage.plugin.FileReporter): def __init__(self, filename): # TODO: do we want the .filename attribute to be part of the public # API of the coverage plugin? self.filename = filename # TODO: is self.name required? Can the base class provide it somehow? self.name = os.path.basename(filename) # TODO: html filenames are absolute. def statements(self): source_lines = set() if SHOW_PARSING: print("-------------- {}".format(self.filename)) with open(self.filename) as f: text = f.read() tokens = Lexer(text, self.filename).tokenize() # Are we inside a comment? comment = False # Is this a template that extends another template? extends = False # Are we inside a block? inblock = False for token in tokens: if SHOW_PARSING: print( "%10s %2d: %r" % ( TOKEN_MAPPING[token.token_type], token.lineno, token.contents, ) ) if token.token_type == TOKEN_BLOCK: if token.contents == 'endcomment': comment = False continue if comment: continue if token.token_type == TOKEN_BLOCK: if token.contents.startswith("endblock"): inblock = False elif token.contents.startswith("block"): inblock = True if extends: continue if token.contents == 'comment': comment = True if token.contents.startswith("end"): continue elif token.contents in ("else", "empty"): continue elif token.contents.startswith("elif"): # NOTE: I don't like this, I want to be able to trace elif # nodes, but the Django template engine doesn't track them # in a way that we can get useful information from them. continue elif token.contents.startswith("extends"): extends = True source_lines.add(token.lineno) elif token.token_type == TOKEN_VAR: source_lines.add(token.lineno) elif token.token_type == TOKEN_TEXT: if extends and not inblock: continue # Text nodes often start with newlines, but we don't want to # consider that first line to be part of the text. lineno = token.lineno lines = token.contents.splitlines(True) num_lines = len(lines) if lines[0].isspace(): lineno += 1 num_lines -= 1 source_lines.update(range(lineno, lineno+num_lines)) if SHOW_PARSING: print("\t\t\tNow source_lines is: {!r}".format(source_lines)) return source_lines def running_sum(seq): total = 0 for num in seq: total += num yield total def make_line_map(text): line_lengths = [len(l) for l in text.splitlines(True)] line_map = list(running_sum(line_lengths)) return line_map def get_line_number(line_map, offset): """Find a line number, given a line map and a character offset.""" for lineno, line_offset in enumerate(line_map, start=1): if line_offset > offset: return lineno return -1 def dump_frame(frame): """Dump interesting information about this frame.""" locals = frame.f_locals self = locals.get('self', None) if "__builtins__" in locals: del locals["__builtins__"] print("-- frame -----------------------") print("{}:{}:{}".format( os.path.basename(frame.f_code.co_filename), frame.f_lineno, type(self), )) print(locals) if self: print("self:", self.__dict__)
[ "ned@nedbatchelder.com" ]
ned@nedbatchelder.com
be12fe914a5b9c2f4e1eab08f952edf9dd0ae710
6929a33a7259dad9b45192ca088a492085ed2953
/solutions/0475-heaters/heaters.py
2c9655d2847642ea56cf9df3c164610f4b6ae8c5
[]
no_license
moqi112358/leetcode
70366d29c474d19c43180fd4c282cc02c890af03
fab9433ff7f66d00023e3af271cf309b2d481722
refs/heads/master
2022-12-10T01:46:14.799231
2021-01-14T05:00:09
2021-01-14T05:00:09
218,163,960
3
0
null
2022-07-06T20:26:38
2019-10-28T23:26:47
Python
UTF-8
Python
false
false
3,273
py
# Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses. # # Every house can be warmed, as long as the house is within the heater's warm radius range.  # # Given the positions of houses and heaters on a horizontal line, return the minimum radius standard of heaters so that those heaters could cover all houses. # # Notice that all the heaters follow your radius standard, and the warm radius will the same. # #   # Example 1: # # # Input: houses = [1,2,3], heaters = [2] # Output: 1 # Explanation: The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed. # # # Example 2: # # # Input: houses = [1,2,3,4], heaters = [1,4] # Output: 1 # Explanation: The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the houses can be warmed. # # # Example 3: # # # Input: houses = [1,5], heaters = [2] # Output: 3 # # #   # Constraints: # # # 1 <= houses.length, heaters.length <= 3 * 104 # 1 <= houses[i], heaters[i] <= 109 # # # # @lc app=leetcode id=475 lang=python3 # # [475] Heaters # # https://leetcode.com/problems/heaters/description/ # # algorithms # Easy (32.21%) # Total Accepted: 52K # Total Submissions: 161.3K # Testcase Example: '[1,2,3]\n[2]' # # Winter is coming! Your first job during the contest is to design a standard # heater with fixed warm radius to warm all the houses. # # Now, you are given positions of houses and heaters on a horizontal line, find # out minimum radius of heaters so that all houses could be covered by those # heaters. # # So, your input will be the positions of houses and heaters seperately, and # your expected output will be the minimum radius standard of heaters. # # Note: # # # Numbers of houses and heaters you are given are non-negative and will not # exceed 25000. # Positions of houses and heaters you are given are non-negative and will not # exceed 10^9. # As long as a house is in the heaters' warm radius range, it can be # warmed. # All the heaters follow your radius standard and the warm radius will the # same. # # # # # Example 1: # # # Input: [1,2,3],[2] # Output: 1 # Explanation: The only heater was placed in the position 2, and if we use the # radius 1 standard, then all the houses can be warmed. # # # # # Example 2: # # # Input: [1,2,3,4],[1,4] # Output: 1 # Explanation: The two heater was placed in the position 1 and 4. We need to # use radius 1 standard, then all the houses can be warmed. # # # # # class Solution: def findRadius(self, houses, heaters): # return max([min([abs(j-i) for j in heaters]) for i in houses]) curr = 0 houses.sort() heaters.sort() total_heaters = len(heaters) total_houses = len(houses) res = -sys.maxsize - 1 for i in range(total_houses): dist1 = abs(heaters[curr] - houses[i]) while curr != total_heaters - 1 and (abs(heaters[curr + 1] - houses[i]) <= dist1): curr += 1 dist1 = abs(heaters[curr] - houses[i]) res = max([res, dist1]) return res
[ "983028670@qq.com" ]
983028670@qq.com
72ab34403f47a895dc8cf4d64e46acb9915bb8c6
e9462eeebcac761b34722578f9b297af858710bc
/python/python-vba-word/Win32COM - Word - Table Formulas.py
cb6efd70d8d489073bce97292edec2b13ebb0a24
[ "MIT" ]
permissive
nsethtyler/sigma_coding_youtube
63e72c8f3f144731e6c49e049ed786f2b3219e73
c09f131816bc2d1c1eb45ab9da6de75ee7b855db
refs/heads/master
2022-12-09T12:03:34.757133
2020-08-27T20:50:04
2020-08-27T20:50:04
290,873,388
0
0
MIT
2020-08-27T20:20:10
2020-08-27T20:20:09
null
UTF-8
Python
false
false
2,321
py
import win32com.client as win32 # Grab the Active Instance of Word WrdApp = win32.GetActiveObject("Word.Application") # Grab the current document. WrdDoc = WrdApp.ActiveDocument # Reference the Table in it. WrdTable = WrdDoc.Tables.Item(1) # Grab all the columns SaleColumn = WrdTable.Columns(1) CostColumn = WrdTable.Columns(2) ProfitColumn = WrdTable.Columns(3) # Loop through each cell in the Sales Column. for SaleCell in list(SaleColumn.Cells)[1:]: # Grab the Text SaleCellText = SaleCell.Range.Text # Clear out the old text SaleCell.Range.Text = "" # Create a Formula String formula_string = "={my_number}\#""$#,##0.00;($#,##0.00)""".format(my_number = SaleCellText) # Create the Range SaleCell.Range.Select() # Collapse the Range WrdApp.Selection.Collapse(Direction=1) # Define the new Selection Range SelecRng = WrdApp.Selection.Range # Set the Formula SelecRng.Fields.Add(Range=SelecRng, Type=-1, Text=formula_string, PreserveFormatting=True) # Loop through each cell in the Cost Column. for CostCell in list(CostColumn.Cells)[1:]: # Grab the Text CostCellText = CostCell.Range.Text # Clear the Original Text CostCell.Range.Text = "" # Create a Formula String formula_string = "={my_number}\#""$#,##0.00;($#,##0.00)""".format(my_number = SaleCellText) # Create the Range CostCell.Range.Select() # Collapse the Range WrdApp.Selection.Collapse(Direction=1) # Define the new Selection Range SelecRng = WrdApp.Selection.Range # Set the Formula SelecRng.Fields.Add(Range=SelecRng, Type=-1, Text=formula_string, PreserveFormatting=True) # Loop through each cell in the Profit Column. for ProfitCell in list(ProfitColumn.Cells)[1:]: # Clear the Original Text ProfitCell.Range.Text = "" # Create a Formula String formula_string = "=R{row_number}C1 - R{row_number}C2 \#""$#,##0.00;($#,##0.00)""".format(row_number = ProfitCell.Row.Index) # Create the Range ProfitCell.Range.Select() # Collapse the Range WrdApp.Selection.Collapse(Direction=1) # Define the new Selection Range SelecRng = WrdApp.Selection.Range # Set the Formula SelecRng.Fields.Add(Range=SelecRng, Type=-1, Text=formula_string, PreserveFormatting=True)
[ "alexreed1192@gmail.com" ]
alexreed1192@gmail.com
c8665f57e8b014bb4a0bada9bd7400187cc6c773
f0d713996eb095bcdc701f3fab0a8110b8541cbb
/kxrhqiE5so3AMXWS7_1.py
a567e54546179cbab5298d2f0a11665f16f9e8cf
[]
no_license
daniel-reich/turbo-robot
feda6c0523bb83ab8954b6d06302bfec5b16ebdf
a7a25c63097674c0a81675eed7e6b763785f1c41
refs/heads/main
2023-03-26T01:55:14.210264
2021-03-23T16:08:01
2021-03-23T16:08:01
350,773,815
0
0
null
null
null
null
UTF-8
Python
false
false
670
py
""" A man has `n` number of apples. If he eats a percentage `p` of the apples (if apples are available), his children will share the remainder of the apples. Create a function to determine the number of 'whole' apples his children got. If his children did not get any apples, return `"The children didn't get any apples"`. ### Examples get_number_of_apples(10, "90%") ➞ 1 get_number_of_apples(25, "10%") ➞ 22 get_number_of_apples(0, "10%") ➞ "The children didn't get any apples" ### Notes `p` will always be given. """ def get_number_of_apples(n, p): return n * (100 - int(p[:-1])) // 100 or "The children didn't get any apples"
[ "daniel.reich@danielreichs-MacBook-Pro.local" ]
daniel.reich@danielreichs-MacBook-Pro.local
049fba86a17445a1cd47636ce635d7512068a5df
c80ec1805a7e6cb1bd3f4b3e383ef4f4cf164765
/gen/filters/rules/person/_hasnoteregexp.py
fbb7fa8c1925049716fcab430b77a4c9100507fb
[]
no_license
balrok/gramps_addon
57c8e976c47ea3c1d1298d3fd4406c13909ac933
0c79561bed7ff42c88714edbc85197fa9235e188
refs/heads/master
2020-04-16T03:58:27.818732
2015-02-01T14:17:44
2015-02-01T14:17:44
30,111,898
2
1
null
null
null
null
UTF-8
Python
false
false
1,706
py
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2002-2006 Donald N. Allingham # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # #------------------------------------------------------------------------- # # Standard Python modules # #------------------------------------------------------------------------- from ....const import GRAMPS_LOCALE as glocale _ = glocale.translation.gettext #------------------------------------------------------------------------- # # GRAMPS modules # #------------------------------------------------------------------------- from .._hasnoteregexbase import HasNoteRegexBase #------------------------------------------------------------------------- # "People having notes that contain a substring" #------------------------------------------------------------------------- class HasNoteRegexp(HasNoteRegexBase): name = _('People having notes containing <text>') description = _("Matches people whose notes contain text " "matching a regular expression")
[ "carl.schoenbach@gmail.com" ]
carl.schoenbach@gmail.com
12dcdf99e66883812b53494f15fcd2ba332a7379
8d598140ac081e17ce6a549c85feb9684ef79ea3
/config/default.py
0ecdb196401e9db03328e20af185a2d91087b888
[]
no_license
thuunivercity/xichuangzhu
fae1f68fb0a6de8bf875fd21427210a3170f74ca
c0622bed831b9d4cdf776138a6fc66a2da67bf0d
refs/heads/master
2021-12-30T17:41:55.652212
2015-10-21T03:14:48
2015-10-21T03:14:48
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,846
py
# coding: utf-8 import os class Config(object): """配置基类""" # Flask app config DEBUG = False TESTING = False SECRET_KEY = "\xb5\xb3}#\xb7A\xcac\x9d0\xb6\x0f\x80z\x97\x00\x1e\xc0\xb8+\xe9)\xf0}" PERMANENT_SESSION_LIFETIME = 3600 * 24 * 7 SESSION_COOKIE_NAME = 'xcz_session' # Root path of project PROJECT_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) # Site domain SITE_DOMAIN = "http://localhost:5000" # SQLAlchemy config # See: # https://pythonhosted.org/Flask-SQLAlchemy/config.html#connection-uri-format # http://docs.sqlalchemy.org/en/rel_0_9/core/engines.html#database-urls SQLALCHEMY_DATABASE_URI = "mysql://root:@localhost/xcz" # SMTP config MAIL_SERVER = '' MAIL_PORT = 25 MAIL_USE_TLS = False MAIL_USE_SSL = False MAIL_DEBUG = DEBUG MAIL_USERNAME = '' MAIL_PASSWORD = '' MAIL_DEFAULT_SENDER = '' MAIL_MAX_EMAILS = None MAIL_ADMIN_ADDR = '' # 管理员邮箱 # UploadSets config UPLOADS_DEFAULT_DEST = "/var/www/xcz_uploads" # 上传文件存储路径 UPLOADS_DEFAULT_URL = "http://localhost/xcz_uploads/" # 上传文件访问URL # Flask-DebugToolbar DEBUG_TB_INTERCEPT_REDIRECTS = False # Sentry config SENTRY_DSN = '' # Host string, used by fabric HOST_STRING = "" # Douban OAuth2 config DOUBAN_CLIENT_ID = '0cf909cba46ce67526eb1d62ed46b35f' DOUBAN_SECRET = '4c87a8ef33e6c6be' DOUBAN_REDIRECT_URI = '%s/account/signin' % SITE_DOMAIN DOUBAN_LOGIN_URL = "https://www.douban.com/service/auth2/auth?client_id=%s&redirect_uri=%s" \ "&response_type=code" % (DOUBAN_CLIENT_ID, DOUBAN_REDIRECT_URI) # Aliyun OSS config OSS_HOST = 'oss.aliyuncs.com' OSS_KEY = '' OSS_SECRET = '' OSS_URL = ''
[ "hustlzp@qq.com" ]
hustlzp@qq.com
374048fea69e0a66ffbb5fa9fa42e53287967cc4
7110d018f0474388e18bc9c760f306c5b8593aae
/app/client/models.py
4d9febe84b05dc0166fdb6c8333590e5ad974d84
[ "MIT" ]
permissive
alexiuasse/django-system-iuasse
6a9a4d27fee5ec864fe6ec5901b539aba2e9b0a5
fa22519f2d2b6256e5334f032a95fd19366e5df4
refs/heads/main
2023-05-14T21:25:35.021196
2021-06-03T17:00:56
2021-06-03T17:00:56
369,536,237
0
0
null
null
null
null
UTF-8
Python
false
false
2,817
py
from django.db import models from django.utils import timezone from django.utils.translation import gettext as _ from django.urls import reverse_lazy from app.models import TimeStampMixin class Occupation(TimeStampMixin): """ Model to set the Occupation, used to identify a client.""" name = models.CharField(verbose_name=_("Name"), max_length=128, blank=False, null=False) def __str__(self) -> str: return self.name class Client(TimeStampMixin): """ Model to specify a client.""" name = models.CharField(verbose_name=_("Name"), max_length=128) email = models.EmailField(verbose_name=_("E-mail"), blank=True, null=True) address = models.TextField(verbose_name=_("Address"), blank=True, null=True) # max_length is in real 16 (66) 9 9205-4030 but with the mask it must be 17 phone = models.CharField(verbose_name=_("Phone"), max_length=17, blank=True, null=True) birthday = models.DateField(verbose_name=_("Birthday"), blank=True, null=True) occupation = models.ForeignKey("client.Occupation", on_delete=models.SET_NULL, null=True, blank=True, verbose_name=_("Occupation")) date = models.DateField( verbose_name=_("Date"), default=timezone.now, help_text=_("This date is used for statistics, build charts. "), ) def __str__(self) -> str: return self.name def get_absolute_url(self): return reverse_lazy(f'{self._meta.app_label}:{self._meta.model_name}:details') @staticmethod def get_exclude_fields(): """ Fields of the current model that is marked to get excluded from visualization. """ return [] def get_add_fields(self): """ Custom fields to be added for visualization. Need to be a dict with {'name': content} """ return {} def get_dict_data(self): """ This method automatically gathers all the fields in the current model and returns them as a dictionary, used mainly to build a layout. """ exclude = self.get_exclude_fields() data = dict([(field.verbose_name, getattr(self, field.name)) for field in self._meta.fields if field.name not in exclude]) data.update(self.get_add_fields()) return data
[ "alexiuasse@gmail.com" ]
alexiuasse@gmail.com
f1cc588717cf958753e27ba5146ec48527a2a847
834e1884dcd2551a7f2610c5d65199103a14af67
/Notes/kivyA/kivyCalculatorA/main.py
c8c899b653b9dd10de9635ff18b06bf128fbf3a3
[]
no_license
fwparkercode/Programming2_SP2019
b8ece0fe98fe8260ff20859c80a73ce5ba38a5e6
4938a66979cd9f7cbb82d3d447a5ae2bfd6766b0
refs/heads/master
2020-04-19T05:07:43.800906
2019-05-23T21:23:15
2019-05-23T21:23:15
167,978,933
0
1
null
null
null
null
UTF-8
Python
false
false
437
py
from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.core.window import Window Window.size = (300, 400) class CalculatorApp(App): def build(self): return CalculatorLayout() class CalculatorLayout(BoxLayout): # root widget def calculate(self): answer = eval(self.display.text) self.display.text = str(answer) if __name__ == "__main__": app = CalculatorApp() app.run()
[ "alee@fwparker.org" ]
alee@fwparker.org
1415d8bba5a688bff8491421c00411f76e869d4e
ac1fdf53359b53e183fb9b2602328595b07cf427
/ParlAI/parlai/tasks/convai_chitchat/__init__.py
5799539a22004d2cd8989bf2143289815efc44f1
[]
no_license
Ufukdogann/MasterThesis
780410c5df85b789136b525bce86ba0831409233
b09ede1e3c88c4ac3047800f5187c671eeda18be
refs/heads/main
2023-01-24T18:09:52.285718
2020-11-27T16:14:29
2020-11-27T16:14:29
312,416,173
0
0
null
null
null
null
UTF-8
Python
false
false
128
py
version https://git-lfs.github.com/spec/v1 oid sha256:3fd485c3f7deada658caa392a4950fbf1531c77db9ba58fa9948d13d9d8ea490 size 222
[ "134679852Ufuk*" ]
134679852Ufuk*
5bc28abe7faa596eada6d769cc702ae804e44e90
f07a42f652f46106dee4749277d41c302e2b7406
/Data Set/bug-fixing-1/7da9bb68ce9ad08b3a648b49d52eddd1cc153137-<delete_dag>-bug.py
c76a57772d4c18f939e94cb8e62aacf36607bf5b
[]
no_license
wsgan001/PyFPattern
e0fe06341cc5d51b3ad0fe29b84098d140ed54d1
cc347e32745f99c0cd95e79a18ddacc4574d7faa
refs/heads/main
2023-08-25T23:48:26.112133
2021-10-23T14:11:22
2021-10-23T14:11:22
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,376
py
def delete_dag(dag_id, keep_records_in_log=True): '\n :param dag_id: the dag_id of the DAG to delete\n :type dag_id: str\n :param keep_records_in_log: whether keep records of the given dag_id\n in the Log table in the backend database (for reasons like auditing).\n The default value is True.\n :type keep_records_in_log: bool\n ' session = settings.Session() DM = models.DagModel dag = session.query(DM).filter((DM.dag_id == dag_id)).first() if (dag is None): raise DagNotFound('Dag id {} not found'.format(dag_id)) if (dag.fileloc and (not os.path.exists(dag.fileloc))): raise DagFileExists('Dag id {} is still in DagBag. Remove the DAG file first: {}'.format(dag_id, dag.fileloc)) count = 0 for m in models.base.Base._decl_class_registry.values(): if hasattr(m, 'dag_id'): if (keep_records_in_log and (m.__name__ == 'Log')): continue cond = or_((m.dag_id == dag_id), m.dag_id.like((dag_id + '.%'))) count += session.query(m).filter(cond).delete(synchronize_session='fetch') if dag.is_subdag: (p, c) = dag_id.rsplit('.', 1) for m in (models.DagRun, models.TaskFail, models.TaskInstance): count += session.query(m).filter((m.dag_id == p), (m.task_id == c)).delete() session.commit() return count
[ "dg1732004@smail.nju.edu.cn" ]
dg1732004@smail.nju.edu.cn
ab913b549c945e35ccf4e56526cc50b5f608c3bb
69f43872d7ca655912dcf46d246702e5ee5b1068
/apps/sad/models.py
e9976ad1406a6342062239d786ead6d7a03ce241
[ "BSD-3-Clause" ]
permissive
tiposaurio/backenddj
d0d5884d1880c9b09b20aaa35e20da0173520535
e16f609eca0c292c8c694c7eb279fe99296b45e3
refs/heads/master
2021-01-16T21:51:00.352923
2014-05-16T03:59:52
2014-05-16T03:59:52
null
0
0
null
null
null
null
UTF-8
Python
false
false
7,833
py
# _*_ coding: utf-8 _*_ """ @copyright Copyright (c) 2014 Submit Consulting @author Angel Sullon (@asullom) @package sad Descripcion: Registro de los modelos de la app sad """ from django.db import models from django.contrib.auth.models import User, Group, Permission from apps.params.models import Person from apps.space.models import Solution, Association, Enterprise, Headquar # Usaremos las tablas de django: # User # Group (para nosotros Perfil) # Permission+ContentType (para nosostros Recursos) class Profile(models.Model): """ Tabla que amplia la informacion de los usuarios del sistema """ last_headquar_id = models.CharField(max_length=50, null=True, blank=True) last_module_id = models.CharField(max_length=50, null=True, blank=True) user = models.OneToOneField(User) person = models.OneToOneField(Person) class Meta: permissions = ( # ("profile", "Puede hacer TODAS las operaciones del perfil"), ) def __unicode__(self): return self.user.username ''' def create_user_profile(sender, instance, created, **kwargs): if created : Profile.objects.create(user=instance) post_save.connect(create_user_profile, sender=User) ''' class UserState(models.Model): """ Tabla que registra el historial de los estados de los usuarios """ ON = "ON" OFF = "OFF" USER_STATES = ( (ON, "Activate"), (OFF, "Deactivate"), ) state = models.CharField(max_length=50, choices=USER_STATES, default=ON) description = models.TextField(null=True, blank=True) user = models.ForeignKey(User) registered_at = models.DateTimeField(auto_now_add=True) class Meta: permissions = ( # ("profile", "Puede hacer TODAS las operaciones del perfil"), ) def __unicode__(self): return "%s %s" % (self.user.username, self.state) ''' def create_user_profile(sender, instance, created, **kwargs): if created : Profile.objects.create(user=instance) post_save.connect(create_user_profile, sender=User) ''' class Access(models.Model): """ Tabla que registra los accesos de los usuarios al sistema """ INPUT = "INPUT" OUTPUT = "OUTPUT" ACCESS_TYPES = ( (INPUT, "Input"), (OUTPUT, "Output"), ) access_type = models.CharField(max_length=50, choices=ACCESS_TYPES, default=INPUT) ip = models.CharField(max_length=50, null=True, blank=True) session_key = models.TextField(null=True, blank=True) user = models.ForeignKey(User) registered_at = models.DateTimeField(auto_now_add=True) class Meta: permissions = ( ("access", "Puede hacer TODAS las operaciones del access"), ) def __unicode__(self): return "%s %s" % (self.user.username, self.access_type) class Backup(models.Model): """ Tabla que registra los accesos de los usuarios al sistema """ file_name = models.CharField(max_length=50) description = models.TextField(null=True, blank=True) size = models.CharField(max_length=50, null=True, blank=True) user = models.ForeignKey(User) registered_at = models.DateTimeField(auto_now_add=True) class Meta: permissions = ( ("backup", "Puede hacer TODAS las operaciones de backup"), ) def __unicode__(self): return self.file_name class Module(models.Model): """ Modulos del sistema """ PRO = "PRO" WEB = "WEB" VENTAS = "VENTAS" BACKEND = "BACKEND" MODULES = ( (PRO, "Profesional"), (WEB, "Web informativa"), (VENTAS, "Ventas"), (BACKEND, "Backend Manager"), ) module = models.CharField(max_length=50, choices=MODULES, default=BACKEND) name = models.CharField(max_length=50) is_active = models.BooleanField(default=True) icon = models.CharField(max_length=50, null=True, blank=True) description = models.TextField(null=True, blank=True) registered_at = models.DateTimeField(auto_now_add=True) modified_in = models.DateTimeField(auto_now=True) solutions = models.ManyToManyField(Solution, verbose_name="solutions", null=True, blank=True) groups = models.ManyToManyField(Group, related_name="module_set", verbose_name="groups", null=True, blank=True) # verbose_name es para Module initial_groups = models.ManyToManyField(Group, related_name="initial_groups_module_set", verbose_name="initial_groups", null=True, blank=True) # related_name cambia module_set x initial_groups_module_set class Meta: permissions = ( ("module", "Puede hacer TODAS las operaciones de modulos"), ) def __unicode__(self): return "%s %s" % (self.module, self.name) class Menu(models.Model): """ Menús del sistema. """ MODULES = Module.MODULES module = models.CharField(max_length=50, choices=MODULES, default=Module.BACKEND) title = models.CharField(max_length=50) url = models.CharField(max_length=150, default="#") pos = models.IntegerField(max_length=50, default=1) icon = models.CharField(max_length=50, null=True, blank=True, default="") is_active = models.BooleanField(default=True) description = models.TextField(null=True, blank=True) registered_at = models.DateTimeField(auto_now_add=True) modified_in = models.DateTimeField(auto_now=True) permission = models.ForeignKey(Permission, null=True, blank=True) parent = models.ForeignKey("Menu", verbose_name="parent", null=True, blank=True) # related_name="parent", class Meta: permissions = ( ("menu", "Puede hacer TODAS las operaciones de menús"), ) def __unicode__(self): return "%s %s" % (self.module, self.title) class UserProfileEnterprise(models.Model): """ Permisos a nivel de empresa """ # is_admin = models.BooleanField(default=False) registered_at = models.DateTimeField(auto_now_add=True) modified_in = models.DateTimeField(auto_now=True) user = models.ForeignKey(User) group = models.ForeignKey(Group) enterprise = models.ForeignKey(Enterprise) class Meta: permissions = ( # ("userprofileenterprise", "Puede hacer TODAS las operaciones de userprofileenterprise"), ) def __unicode__(self): return "%s %s - %s" % (self.user.username, self.group.name, self.enterprise.name) class UserProfileHeadquar(models.Model): """ Permisos a nivel de sede """ # is_admin = models.BooleanField(default=False) registered_at = models.DateTimeField(auto_now_add=True) modified_in = models.DateTimeField(auto_now=True) user = models.ForeignKey(User) group = models.ForeignKey(Group) headquar = models.ForeignKey(Headquar) class Meta: permissions = ( # ("userprofileheadquar", "Puede hacer TODAS las operaciones de userprofileheadquar"), ) def __unicode__(self): return "%s %s - %s" % (self.user.username, self.group.name, self.headquar.name) class UserProfileAssociation(models.Model): """ Permisos a nivel de association """ # is_admin = models.BooleanField(default=False) registered_at = models.DateTimeField(auto_now_add=True) modified_in = models.DateTimeField(auto_now=True) user = models.ForeignKey(User) group = models.ForeignKey(Group) association = models.ForeignKey(Association) class Meta: permissions = ( # ("userprofileassociation", "Puede hacer TODAS las operaciones de userprofileassociation"), ) def __unicode__(self): return "%s %s - %s" % (self.user.username, self.group.name, self.association.name)
[ "asullom@gmail.com" ]
asullom@gmail.com
db3983df30bc88f8057cdd776e83c68efde56582
06acfec630a30695d79b77df4d682cb27dce64a2
/wev/test_resolver.py
1d9bd12b34fad7aa80bbb99495a328793a2b8fdc
[]
permissive
cariad/wev
b828bd7b5b47117bf571ae1e3e3a60abb619f396
2abf38485d86c593bbedcb7c295143104e385b77
refs/heads/main
2023-04-11T20:15:40.548185
2021-05-13T06:50:05
2021-05-13T06:50:05
317,793,612
5
0
MIT
2021-05-13T06:50:06
2020-12-02T08:14:41
Python
UTF-8
Python
false
false
2,559
py
from datetime import datetime, timedelta from typing import Iterator, Optional from mock import Mock, patch from pytest import fixture, mark, raises from wev.mock_plugin import MockPlugin from wev.resolver import fresh_resolution, resolve from wev.sdk import PluginBase, Resolution from wev.sdk.exceptions import CannotResolveError from wev.state import MockState @fixture def get_plugin() -> Iterator[PluginBase]: plugin = MockPlugin({}, return_value=("(value)",), return_expires_at=True) with patch("wev.resolver.get_plugin", return_value=plugin) as patched: yield patched @fixture def get_non_caching_plugin() -> Iterator[PluginBase]: plugin = MockPlugin({}, return_value=("(value)",), return_expires_at=False) with patch("wev.resolver.get_plugin", return_value=plugin) as patched: yield patched @fixture def get_plugin_cannot_resolve_error() -> Iterator[PluginBase]: plugin = MockPlugin({}, raises_cannot_resolve_error=True) with patch("wev.resolver.get_plugin", return_value=plugin) as patched: yield patched @mark.parametrize( "resolution, expect", [ (None, False), (Resolution.make(value=""), False), ( Resolution.make( value=None, expires_at=datetime.now() - timedelta(seconds=60) ), False, ), ( Resolution.make( value=None, expires_at=datetime.now() + timedelta(seconds=60) ), True, ), ], ) def test_fresh_resolution(resolution: Optional[Resolution], expect: bool) -> None: expect_resolution = resolution if expect else None assert fresh_resolution(resolution=resolution) == expect_resolution def test_resolve(get_plugin: Mock) -> None: environs = resolve(state=MockState()) assert environs["alpha"] == "(value)" assert environs["beta"] == "(value)" assert environs["gamma"] == "gamma-value-old" assert environs["delta"] == "(value)" def test_resolve__removes_cache(get_non_caching_plugin: Mock) -> None: state = MockState() state.resolution_cache.update(names=("alpha",), resolution=Mock()) assert ("alpha",) in state.resolution_cache.resolutions resolve(state=state) assert ("alpha",) not in state.resolution_cache.resolutions def test_resolve__cannot_resolve_error(get_plugin_cannot_resolve_error: Mock) -> None: with raises(CannotResolveError) as ex: resolve(state=MockState()) assert str(ex.value) == '"alpha-handler" failed: cannot reticulate splines'
[ "noreply@github.com" ]
cariad.noreply@github.com
40fc1773b286492d28d12972d62a9df0239d6aea
3c41443364da8b44c74dce08ef94a1acd1b66b3e
/osf/migrations/0012_refactor_sessions.py
bbb8897ebfd22c094898150c9cd99591c3967d5e
[ "MIT", "BSD-3-Clause", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-warranty-disclaimer", "AGPL-3.0-only", "LGPL-2.0-or-later", "LicenseRef-scancode-proprietary-license", "MPL-1.1", "CPAL-1.0", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause", "Apache-2.0" ]
permissive
CenterForOpenScience/osf.io
71d9540be7989f7118a33e15bc4a6ce2d2492ac1
a3e0a0b9ddda5dd75fc8248d58f3bcdeece0323e
refs/heads/develop
2023-09-04T03:21:14.970917
2023-08-31T14:49:20
2023-08-31T14:49:20
10,199,599
683
390
Apache-2.0
2023-09-14T17:07:52
2013-05-21T15:53:37
Python
UTF-8
Python
false
false
1,371
py
# Generated by Django 3.2.17 on 2023-05-08 19:26 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django_extensions.db.fields import osf.models.base import osf.utils.fields class Migration(migrations.Migration): dependencies = [ ('osf', '0011_institution_rework_post_release'), ] operations = [ migrations.CreateModel( name='UserSessionMap', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', django_extensions.db.fields.CreationDateTimeField(auto_now_add=True, verbose_name='created')), ('modified', django_extensions.db.fields.ModificationDateTimeField(auto_now=True, verbose_name='modified')), ('session_key', models.CharField(max_length=255)), ('expire_date', osf.utils.fields.NonNaiveDateTimeField()), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'unique_together': {('user', 'session_key')}, }, bases=(models.Model, osf.models.base.QuerySetExplainMixin), ), migrations.DeleteModel( name='Session', ), ]
[ "noreply@github.com" ]
CenterForOpenScience.noreply@github.com
8f47220d6c0dfacdbf4b8aa948170400d4c06dec
21ad3868aec282c45f813941c76a287eef6dd071
/AirBnB_Clone/config/settings.py
4bfb6cc1689916cd26c88e48b09e629befc917c1
[]
no_license
BKLemontea/NomadCode-Clonecoding
5f4cb919f872c4c4c699fbe451c72571e40621b9
e84079a3f8f9d7ae58b1a2cfc8b75fee4fdf0c53
refs/heads/master
2023-04-30T16:29:13.087156
2020-01-23T13:15:17
2020-01-23T13:15:17
232,075,064
0
0
null
2023-04-21T20:46:55
2020-01-06T10:15:10
Python
UTF-8
Python
false
false
3,088
py
""" Django settings for config project. Generated by 'django-admin startproject' using Django 2.2.5. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'y($0$dge8lb@w@l3!8*k40v2s!v52&jo0qm2^69%q^1=es-c4s' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'config.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'config.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/'
[ "jyf1128@naver.com" ]
jyf1128@naver.com
d527e98714fbd97b33b6c55fea8ef13ac609e987
0fc55f28bf0ce73b85c9d78ea9dc7c26a497fa69
/semana_11/exercicios/1248.py
b7103a6e9d555cd2642d025ca7e8b6657e533dd9
[]
no_license
valeriacavalcanti/IP-2020.2---R
6083f84b33242217e51e0a9a7440362179f3fcc3
d376b4c4b55f7042cc5ae1520296eae570154e75
refs/heads/main
2023-05-08T01:08:45.757978
2021-06-08T03:09:56
2021-06-08T03:09:56
341,371,219
0
2
null
null
null
null
UTF-8
Python
false
false
670
py
qtde = int(input()) for i in range(qtde): dieta = list(input()) cafe = list(input()) almoco = list(input()) cheater = False for i in range(len(cafe)): if (cafe[i] in dieta): dieta.remove(cafe[i]) else: cheater = True break if (cheater == False): for i in range(len(almoco)): if (almoco[i] in dieta): dieta.remove(almoco[i]) else: cheater = True break if (cheater): print('CHEATER') else: dieta.sort() for i in range(len(dieta)): print(dieta[i], end='') print()
[ "valeria.cavalcanti@ifpb.edu.br" ]
valeria.cavalcanti@ifpb.edu.br
b0c5cf73141ec8203c4acb05630c125f46231006
7d274ce8dae971228a23157a409b561020c22f66
/tools/packages/SCons/Tool/suncc.py
c062324709a9e119578f5e8b109c3106f9a330b9
[]
no_license
Eigenlabs/EigenD-Contrib
a212884d4fdf9ae0e1aeb73f6311606212e02f94
586fe17471571802295c792697f255e6cab51b17
refs/heads/master
2020-05-17T07:54:48.668925
2013-02-05T10:20:56
2013-02-05T10:20:56
3,239,072
3
2
null
null
null
null
UTF-8
Python
false
false
1,972
py
"""SCons.Tool.suncc Tool-specific initialization for Sun Solaris (Forte) CC and cc. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/suncc.py 4577 2009/12/27 19:43:56 scons" import SCons.Util import cc def generate(env): """ Add Builders and construction variables for Forte C and C++ compilers to an Environment. """ cc.generate(env) env['CXX'] = 'CC' env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS -KPIC') env['SHOBJPREFIX'] = 'so_' env['SHOBJSUFFIX'] = '.o' def exists(env): return env.Detect('CC') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
[ "jim@eigenlabs.com" ]
jim@eigenlabs.com
c1e2d760b3e39b54a462df6259a94f9c704c993a
52b5773617a1b972a905de4d692540d26ff74926
/.history/ASCII_20200609152320.py
9c4300c8b62b762a900df3b70afab9afaed6c1d2
[]
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
162
py
def ASCIIConversion(s): s = s.split() num = "" for i in s: for j in i: num += str(ord(j)) num +=" " print # code goes here return num
[ "mary.jereh@gmail.com" ]
mary.jereh@gmail.com
f21e48568f4a7f9a9b38bf99752af0ac2f1dd7d2
6fa0d5d3b61fbce01fad5a7dd50258c09298ee00
/Algorithm/BOJ/15_backtracking/15649.py
4be9c6e515ee78768022769a7f81acf75e08e4fd
[]
no_license
athletejuan/TIL
c8e6bd9f7e2c6f999dbac759adcdb6b2959de384
16b854928af2f27d91ba140ebc1aec0007e5eb04
refs/heads/master
2023-02-19T13:59:06.495110
2022-03-23T15:08:04
2022-03-23T15:08:04
188,750,527
1
0
null
2023-02-15T22:54:50
2019-05-27T01:27:09
Python
UTF-8
Python
false
false
286
py
N,M = map(int, input().split()) picked = [] def array(N,M): if M == 0: return print(' '.join(picked)) for _ in range(1, N+1): if not picked or str(_) not in picked: picked.append(str(_)) array(N, M-1) picked.pop() array(N,M)
[ "vanillasky84.0627@gmail.com" ]
vanillasky84.0627@gmail.com
bb804b5c1ee9166b23fa7afc639d8fc0121178a5
d0801bc2efc2d66bf371cd532f43a53b0aaad935
/simpleui/templatetags/simpletags.py
40e99e83be8846d87e6e0bf0f27fe00bf21745d8
[]
no_license
cn-zhangcx/simpleui
6702d274a1a5cced11ffbaf9ec0c0b3c20235ecf
54583ef4d033f4eb62e18f1f70f83df5004165eb
refs/heads/master
2020-05-14T23:38:54.127174
2019-04-16T05:25:03
2019-04-16T05:25:03
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,662
py
# -*- coding: utf-8 -*- import django from django import template from django.utils.html import format_html from django.conf import settings from django.utils.safestring import mark_safe from django.templatetags import static import os import json import platform import socket import simpleui import base64 import time from django.db import models register = template.Library() @register.filter def get_icon(name): # 默认为文件图标 cls = "" return format_html('<i class="icon {}"></i>', cls) @register.simple_tag(takes_context=True) def context_test(context): print(context) pass # context.get('cl').filter_specs[1].links @register.simple_tag(takes_context=True) def load_dates(context): data = {} cl = context.get('cl') if cl.has_filters: for spec in cl.filter_specs: field = spec.field field_type = None if isinstance(field, models.DateTimeField): field_type = 'datetime' elif isinstance(field, models.DateField): field_type = 'date' elif isinstance(field, models.TimeField): field_type = 'time' if field_type: data[field.name] = field_type context['date_field'] = data return '<script type="text/javascript">var searchDates={}</script>'.format(json.dumps(data)) @register.filter def get_date_type(spec): field = spec.field field_type = '' if isinstance(field, models.DateTimeField): field_type = 'datetime' elif isinstance(field, models.DateField): field_type = 'date' elif isinstance(field, models.TimeField): field_type = 'time' return field_type @register.filter def test(obj): print(obj) # pass return '' @register.filter def to_str(obj): return str(obj) @register.filter def date_to_json(obj): return json.dumps(obj.date_params) @register.simple_tag(takes_context=True) def home_page(context): ''' 处理首页,通过设置判断打开的是默认页还是自定义的页面 :return: ''' home = __get_config('SIMPLEUI_HOME_PAGE') if home: context['home'] = home title = __get_config('SIMPLEUI_HOME_TITLE') if not title: title = '首页' icon = __get_config('SIMPLEUI_HOME_ICON') if not icon: icon = 'el-icon-menu' context['title'] = title context['icon'] = icon return '' def __get_config(name): value = os.environ.get(name, getattr(settings, name, None)) return value @register.filter def get_config(key): return __get_config(key) @register.simple_tag def get_server_info(): dict = { 'Network': platform.node(), 'OS': platform.platform(), } try: dict['IP'] = socket.gethostbyname(socket.gethostname()) except: dict['IP'] = '无法获取' return format_table(dict) @register.simple_tag def get_app_info(): dict = { 'Python': platform.python_version(), 'Django': django.get_version(), 'Simpleui': simpleui.get_version() } return format_table(dict) def format_table(dict): html = '<table class="simpleui-table"><tbody>' for key in dict: html += '<tr><th>{}</th><td>{}</td></tr>'.format(key, dict.get(key)) html += '</tbody></table>' return format_html(html) @register.simple_tag(takes_context=True) def menus(context): data = [] # return request.user.has_perm("%s.%s" % (opts.app_label, codename)) config = get_config('SIMPLEUI_CONFIG') # 如果有menu 就读取,没有就调用系统的 if config and 'menus' in config: data=config.get('menus') pass else: app_list = context.get('app_list') for app in app_list: models = [] if app.get('models'): for m in app.get('models'): models.append({ 'name': str(m.get('name')), 'icon': get_icon(m.get('object_name')), 'url': m.get('admin_url'), 'addUrl': m.get('add_url'), 'breadcrumbs': [str(app.get('name')), str(m.get('name'))] }) module = { 'name': str(app.get('name')), 'icon': get_icon(app.get('app_label')), 'models': models } data.append(module) return '<script type="text/javascript">var menus={}</script>'.format(json.dumps(data)) def get_icon(obj): dict = { 'auth': 'fas fa-shield-alt', 'User': 'far fa-user', 'Group': 'fas fa-users-cog' } temp = dict.get(obj) if not temp: return 'far fa-file' return temp @register.simple_tag(takes_context=True) def load_message(context): messages = context.get('messages') array = [] if messages: for msg in messages: array.append({ 'msg': msg.message, 'tag': msg.tags }) return '<script type="text/javascript"> var messages={}</script>'.format(array) @register.simple_tag(takes_context=True) def context_to_json(context): json_str = '{}' return mark_safe(json_str) @register.simple_tag() def get_language(): return django.utils.translation.get_language() @register.filter def get_language_code(val): return django.utils.translation.get_language() def get_analysis_config(): val = __get_config('SIMPLEUI_ANALYSIS') if not val and val == False: return False return True @register.simple_tag(takes_context=True) def load_analysis(context): try: if get_analysis_config() == False: return '' # 理论上值一天只上报一次 key = 'simpleui_' + time.strftime('%Y%m%d', time.localtime()) if key in context.request.session: return '' b64 = "" j = { "n": platform.node(), "o": platform.platform(), "p": platform.python_version(), "d": django.get_version(), "s": simpleui.get_version(), } if 'theme_name' in context.request.COOKIES: j['t'] = context.request.COOKIES['theme_name'] else: j['t'] = 'Default' b64 = base64.b64encode(str(j).encode('utf-8')) url = '//simpleui.88cto.com/analysis' b64 = b64.decode('utf-8') html = '<script async type="text/javascript" src="{}/{}"></script>'.format(url, b64); context.request.session[key] = True return mark_safe(html) except: return ''
[ "newpanjing@163.com" ]
newpanjing@163.com
1d64cc710271280fcbcc423dd7aff0ce53d04cca
9e988c0dfbea15cd23a3de860cb0c88c3dcdbd97
/sdBs/AllRun/ec_12348-3001/sdB_ec_12348-3001_coadd.py
886846dc958ceb1fa79b323df15547fbb52c6935
[]
no_license
tboudreaux/SummerSTScICode
73b2e5839b10c0bf733808f4316d34be91c5a3bd
4dd1ffbb09e0a599257d21872f9d62b5420028b0
refs/heads/master
2021-01-20T18:07:44.723496
2016-08-08T16:49:53
2016-08-08T16:49:53
65,221,159
0
0
null
null
null
null
UTF-8
Python
false
false
437
py
from gPhoton.gMap import gMap def main(): gMap(band="NUV", skypos=[189.3895,-30.306328], skyrange=[0.0333333333333,0.0333333333333], stepsz = 30., cntfile="/data2/fleming/GPHOTON_OUTPUT/LIGHTCURVES/sdBs/sdB_ec_12348-3001/sdB_ec_12348-3001_movie_count.fits", cntcoaddfile="/data2/fleming/GPHOTON_OUTPUT/LIGHTCURVES/sdB/sdB_ec_12348-3001/sdB_ec_12348-3001_count_coadd.fits", overwrite=True, verbose=3) if __name__ == "__main__": main()
[ "thomas@boudreauxmail.com" ]
thomas@boudreauxmail.com
4dcd7b99114efd81e8ac45c656c7038f8db526f7
1ff9adfdb9d559e6f81ed9470467bab25e93b5ab
/src/ta_lib/_vendor/tigerml/automl/custom_configs/classification/popular.py
e9ec0db5fa11ef900db2a1a6bbcf1db75e7db9ab
[]
no_license
Seemant-tiger/housing-price-prediction
a39dbefcb11bc460edeeee92e6becf77d35ff3a8
be5d8cca769c7e267cfee1932eb82b70c2855bc1
refs/heads/main
2023-06-24T00:25:49.776720
2021-07-18T16:44:28
2021-07-18T16:44:28
387,222,852
0
0
null
null
null
null
UTF-8
Python
false
false
5,149
py
# -*- coding: utf-8 -*- """This file is part of the TPOT library. TPOT was primarily developed at the University of Pennsylvania by: - Randal S. Olson (rso@randalolson.com) - Weixuan Fu (weixuanf@upenn.edu) - Daniel Angell (dpa34@drexel.edu) - and many more generous open source contributors TPOT is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. TPOT is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with TPOT. If not, see <http://www.gnu.org/licenses/>. """ import numpy as np # Check the TPOT documentation for information on the structure of config dicts config = { # Classifiers "sklearn.ensemble.RandomForestClassifier": { "n_estimators": [100, 200, 400], "criterion": ["gini", "entropy"], "max_features": np.arange(0.05, 1.01, 0.05), "min_samples_split": range(2, 21), "min_samples_leaf": range(1, 21), "bootstrap": [True, False], }, "sklearn.ensemble.GradientBoostingClassifier": { "n_estimators": [100], "learning_rate": [1e-3, 1e-2, 1e-1, 0.5, 1.0], "max_depth": range(1, 11), "min_samples_split": range(2, 21), "min_samples_leaf": range(1, 21), "subsample": np.arange(0.05, 1.01, 0.05), "max_features": np.arange(0.05, 1.01, 0.05), }, "sklearn.svm.LinearSVC": { "penalty": ["l1", "l2"], "loss": ["hinge", "squared_hinge"], "dual": [True, False], "tol": [1e-5, 1e-4, 1e-3, 1e-2, 1e-1], "C": [1e-4, 1e-3, 1e-2, 1e-1, 0.5, 1.0, 5.0, 10.0, 15.0, 20.0, 25.0], }, "sklearn.linear_model.LogisticRegression": { "penalty": ["l1", "l2"], "C": [1e-4, 1e-3, 1e-2, 1e-1, 0.5, 1.0, 5.0, 10.0, 15.0, 20.0, 25.0], "dual": [True, False], }, "xgboost.XGBClassifier": { "n_estimators": [100], "max_depth": range(1, 11), "learning_rate": [1e-3, 1e-2, 1e-1, 0.5, 1.0], "subsample": np.arange(0.05, 1.01, 0.05), "min_child_weight": range(1, 21), "nthread": [1], }, # Preprocesssors "sklearn.preprocessing.Binarizer": {"threshold": np.arange(0.0, 1.01, 0.05)}, # 'sklearn.decomposition.FastICA': { # 'tol': np.arange(0.0, 1.01, 0.05) # }, "sklearn.cluster.FeatureAgglomeration": { "linkage": ["ward", "complete", "average"], "affinity": ["euclidean", "l1", "l2", "manhattan", "cosine"], }, "sklearn.preprocessing.MaxAbsScaler": {}, "sklearn.preprocessing.MinMaxScaler": {}, "sklearn.preprocessing.Normalizer": {"norm": ["l1", "l2", "max"]}, # 'sklearn.kernel_approximation.Nystroem': { # 'kernel': ['rbf', 'cosine', 'chi2', 'laplacian', 'polynomial', 'poly', 'linear', 'additive_chi2', 'sigmoid'], # 'gamma': np.arange(0.0, 1.01, 0.05), # 'n_components': range(1, 11) # }, # 'sklearn.decomposition.PCA': { # 'svd_solver': ['randomized'], # 'iterated_power': range(1, 11) # }, # 'sklearn.preprocessing.PolynomialFeatures': { # 'degree': [2], # 'include_bias': [False], # 'interaction_only': [False] # }, # 'sklearn.kernel_approximation.RBFSampler': { # 'gamma': np.arange(0.0, 1.01, 0.05) # }, "sklearn.preprocessing.RobustScaler": {}, "sklearn.preprocessing.StandardScaler": {}, # 'tpot.builtins.ZeroCount': { # }, "tpot.builtins.OneHotEncoder": { "minimum_fraction": [0.05, 0.1, 0.15, 0.2, 0.25], "sparse": [False], "threshold": [10], }, # Selectors "sklearn.feature_selection.SelectFwe": { "alpha": np.arange(0, 0.05, 0.001), "score_func": {"sklearn.feature_selection.f_classif": None}, }, "sklearn.feature_selection.SelectPercentile": { "percentile": range(1, 100), "score_func": {"sklearn.feature_selection.f_classif": None}, }, "sklearn.feature_selection.VarianceThreshold": { "threshold": [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.05, 0.1, 0.2] }, "sklearn.feature_selection.RFE": { "step": np.arange(0.05, 1.01, 0.05), "estimator": { "sklearn.ensemble.ExtraTreesClassifier": { "n_estimators": [100], "criterion": ["gini", "entropy"], "max_features": np.arange(0.05, 1.01, 0.05), } }, }, "sklearn.feature_selection.SelectFromModel": { "threshold": np.arange(0, 1.01, 0.05), "estimator": { "sklearn.ensemble.ExtraTreesClassifier": { "n_estimators": [100], "criterion": ["gini", "entropy"], "max_features": np.arange(0.05, 1.01, 0.05), } }, }, }
[ "seemantsingh1199@gmail.com" ]
seemantsingh1199@gmail.com
3ff6bc094a8db9af718df9fc0297f36c708d2486
cfd39f470d13f089d7d853b7ea0d0260c0ae6f95
/experiments/inverse_problems_science/dkfz_eval.py
0e57426c957fd763d7b16883f195603beaceace0
[ "MIT" ]
permissive
JackBrady/FrEIA
d1c32c1c6a60a43b25d0011d3525dcd5cdcb4244
5d836494489e5b210a577815b89c4c2988fd8658
refs/heads/master
2020-12-22T07:15:51.914427
2020-05-07T02:48:19
2020-05-07T02:48:19
236,707,547
0
0
MIT
2020-01-28T10:18:01
2020-01-28T10:18:00
null
UTF-8
Python
false
false
3,777
py
import pickle import numpy as np import matplotlib import matplotlib.pyplot as plt import torch import dkfz_train import model import config as c model.load('output/dkfz_inn.pt') print('Trainable parameters:') print(sum([p.numel() for p in model.params_trainable])) def concatenate_test_set(): x_all, y_all = [], [] for x,y in c.test_loader: x_all.append(x) y_all.append(y) return torch.cat(x_all, 0), torch.cat(y_all, 0) x_all, y_all = concatenate_test_set() def sample_posterior(y_it, N=4096): outputs = [] for y in y_it: rev_inputs = torch.cat([torch.randn(N, c.ndim_z + c.ndim_pad_zy), torch.zeros(N, c.ndim_y)], 1).to(c.device) if c.ndim_pad_zy: rev_inputs[:, c.ndim_z:-c.ndim_y] *= c.add_pad_noise rev_inputs[:, -c.ndim_y:] = y with torch.no_grad(): x_samples = model.model(rev_inputs, rev=True) outputs.append(x_samples.data.cpu().numpy()) return outputs def show_posteriors(): # how many different posteriors to show: n_plots = 5 # how many dimensions of x to use: n_x = 3 def hists(x): results = [] for j in range(n_x): h, b = np.histogram(x[:, j], bins=100, range=(-2,2), density=True) h /= np.max(h) results.append([b[:-1],h]) return results prior_hists = hists(x_all) x_gt = x_all[:n_plots] y_gt = y_all[:n_plots] posteriors = sample_posterior(y_gt) confidence = 0.68 q_low = 100. * 0.5 * (1 - confidence) q_high = 100. * 0.5 * (1 + confidence) for i in range(n_plots): hist_i = hists(posteriors[i]) for j in range(n_x): plt.subplot(n_plots, n_x, n_x*i + j + 1) plt.step(*(prior_hists[j]), where='post', color='grey') plt.step(*(hist_i[j]), where='post', color='blue') x_low, x_high = np.percentile(posteriors[i][:,j], [q_low, q_high]) plt.plot([x_gt[i,j], x_gt[i,j]], [0,1], color='black') plt.plot([x_low, x_low], [0,1], color='orange') plt.plot([x_high, x_high], [0,1], color='orange') plt.tight_layout() def calibration_error(): # which parameter to look at (0: SO2) x_ind = 0 # how many different confidences to look at n_steps = 100 q_values = [] confidences = np.linspace(0., 1., n_steps+1, endpoint=False)[1:] uncert_intervals = [[] for i in range(n_steps)] inliers = [[] for i in range(n_steps)] for conf in confidences: q_low = 0.5 * (1 - conf) q_high = 0.5 * (1 + conf) q_values += [q_low, q_high] from tqdm import tqdm for x,y in tqdm(zip(x_all, y_all), total=x_all.shape[0], disable=False): post = sample_posterior([y])[0][:, x_ind] x_margins = list(np.quantile(post, q_values)) for i in range(n_steps): x_low, x_high = x_margins.pop(0), x_margins.pop(0) uncert_intervals[i].append(x_high - x_low) inliers[i].append(int(x[x_ind] < x_high and x[x_ind] > x_low)) inliers = np.mean(inliers, axis=1) uncert_intervals = np.median(uncert_intervals, axis=1) calib_err = inliers - confidences print(F'Median calibration error: {np.median(np.abs(calib_err))}') print(F'Calibration error at 68% confidence: {calib_err[68]}') print(F'Med. est. uncertainty at 68% conf.: {uncert_intervals[68]}') plt.subplot(2, 1, 1) plt.plot(confidences, calib_err) plt.ylabel('Calibration error') plt.subplot(2, 1, 2) plt.plot(confidences, uncert_intervals) plt.ylabel('Median estimated uncertainty') plt.xlabel('Confidence') show_posteriors() calibration_error() plt.show()
[ "lynton.ardizzone@iwr.uni-heidelberg.de" ]
lynton.ardizzone@iwr.uni-heidelberg.de
aad1a11cfde52faaf3be013f179124ca06ee7ceb
8ad18381b31acbfe4f81f85c19cf5c020938bb94
/Products/migrations/0002_auto_20210814_2159.py
fae9d5ade9ad59a5e60628c1ee4a94db56c3c59e
[]
no_license
prathmesh2048/Tradexa_assignment
52796c80c269175b22aa131cb40f4cddd7c6b14f
7e5c4201eec35415516fafa32e81730ffabfab0c
refs/heads/master
2023-07-08T12:06:24.151983
2021-08-14T16:38:36
2021-08-14T16:38:36
396,067,031
0
0
null
null
null
null
UTF-8
Python
false
false
682
py
# Generated by Django 3.2.6 on 2021-08-14 16:29 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Products', '0001_initial'), ] operations = [ migrations.RenameField( model_name='product', old_name='title', new_name='name', ), migrations.AddField( model_name='product', name='price', field=models.PositiveBigIntegerField(null=True), ), migrations.AddField( model_name='product', name='weight', field=models.PositiveBigIntegerField(null=True), ), ]
[ "prathmeshnandurkar123@gmail.com" ]
prathmeshnandurkar123@gmail.com
ab43ee6cdbe330f55b39387b7e1104be8e5bd9e4
518bf342bc4138982af3e2724e75f1d9ca3ba56c
/solutions/1392. Longest Happy Prefix/1392.py
b1c6d9edded10615aa7d40e3a7f7c328eae58194
[ "MIT" ]
permissive
walkccc/LeetCode
dae85af7cc689882a84ee5011f0a13a19ad97f18
a27be41c174565d365cbfe785f0633f634a01b2a
refs/heads/main
2023-08-28T01:32:43.384999
2023-08-20T19:00:45
2023-08-20T19:00:45
172,231,974
692
302
MIT
2023-08-13T14:48:42
2019-02-23T15:46:23
C++
UTF-8
Python
false
false
568
py
class Solution: def longestPrefix(self, s: str) -> str: kBase = 26 kMod = 1_000_000_007 n = len(s) maxLength = 0 pow = 1 prefixHash = 0 # hash of s[0..i] suffixHash = 0 # hash of s[j..n) def val(c: str) -> int: return ord(c) - ord('a') j = n - 1 for i in range(n - 1): prefixHash = (prefixHash * kBase + val(s[i])) % kMod suffixHash = (val(s[j]) * pow + suffixHash) % kMod pow = pow * kBase % kMod if prefixHash == suffixHash: maxLength = i + 1 j -= 1 return s[:maxLength]
[ "me@pengyuc.com" ]
me@pengyuc.com
e33eb0468b760e44fa55435a7441d67b25911100
e46392a087706a3cbd726822a3735892becaeaac
/selfsup/multi/methods/video_saliency.py
fcbddd3435c09c6bfe31f73ff153377b4cad6904
[ "BSD-3-Clause" ]
permissive
Pandinosaurus/self-supervision
39d44d864d140e35bb35fc76adb7412403ea92ea
fe99e707bcccc0eed39dfe8a4651c433caf6f8c4
refs/heads/master
2021-04-06T03:06:38.970572
2017-09-05T03:29:46
2017-09-05T03:34:58
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,857
py
from __future__ import division, print_function, absolute_import import selfsup import tensorflow as tf import os from .base import Method from collections import OrderedDict class VideoSaliency(Method): def __init__(self, name, basenet, loader): self.name = name self.basenet = basenet self._loader = loader self._classes = 32 @property def basenet_settings(self): return {'convolutional': False} def batch(self): x, extra = self._loader.batch() assert 'saliency' in extra return x, extra def build_network(self, network, extra, phase_test, global_step): info = selfsup.info.create(scale_summary=True) z = network['activations']['top'] logits = self.basenet.decoder(z, channels=self._classes, multiple=4) y = tf.image.resize_bilinear(extra['saliency'], logits.get_shape().as_list()[1:3]) labels = tf.to_int32(tf.floor(y[..., 0] * self._classes * 0.99999)) with tf.variable_scope('primary_loss'): loss_each = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=labels, logits=logits) primary_loss = tf.reduce_mean(loss_each) #with tf.name_scope('weight_decay'): #wd = 0.0005 #l2_loss = tf.nn.l2_loss(fc8W) #weight_decay = wd * l2_loss with tf.name_scope('loss'): loss = primary_loss variables = info['vars'] self.losses = OrderedDict([('main', primary_loss)]) self.primary_loss = primary_loss self.loss = loss self.feedback_variables = [] info['activations']['primary_loss'] = primary_loss info['activations']['loss'] = loss #info['activations']['weight_decay'] = weight_decay return info def feedback(self, variables, iteration): pass
[ "gustav.m.larsson@gmail.com" ]
gustav.m.larsson@gmail.com
c102fd6f1a8a65e61fd3accf92c9d824f2db3265
fe04ba6b41745a4f16864aaacf9f1b0005a92e37
/src/TCA/execute.py
b1aeeaf1678b10a4f004860b04abf12c365294b5
[]
no_license
bellwethers-in-se/effort
3148552866911949c4dcf16f3e77ace65b113f5b
1138919c16036c58d11c6764cdcac89026f0d36d
refs/heads/master
2021-01-12T02:14:23.456485
2017-08-07T17:36:22
2017-08-07T17:36:22
78,490,932
0
0
null
null
null
null
UTF-8
Python
false
false
6,977
py
from __future__ import print_function, division import os import sys root = os.path.join(os.getcwd().split('src')[0], 'src') if root not in sys.path: sys.path.append(root) from oracle.model import rf_model from utils import * from mklaren.kernel.kinterface import Kinterface from mklaren.kernel.kernel import * from mklaren.projection.icd import ICD from pdb import set_trace import numpy as np from scipy.spatial.distance import pdist, squareform import pandas from tabulate import tabulate from datasets.handler import get_all_datasets from random import uniform def get_kernel_matrix(dframe, n_dim=15): """ This returns a Kernel Transformation Matrix $\Theta$ It uses kernel approximation offered by the MKlaren package For the sake of completeness (and for my peace of mind, I use the best possible approx.) :param dframe: input data as a pandas dataframe. :param n_dim: Number of dimensions for the kernel matrix (default=15) :return: $\Theta$ matrix """ ker = Kinterface(data=dframe.values, kernel=linear_kernel) model = ICD(rank=n_dim) model.fit(ker) g_nystrom = model.G return g_nystrom def map_transform(src, tgt, n_components=10): """ Run a map and transform x and y onto a new space using TCA :param src: IID samples :param tgt: IID samples :return: Mapped x and y """ s_col = [col for col in src.columns[:-1] if '?' not in col] t_col = [col for col in tgt.columns[:-1] if '?' not in col] S = src[s_col] T = tgt[t_col] # set_trace() col_name = ["Col_" + str(i) for i in xrange(n_components)] x0 = pd.DataFrame(get_kernel_matrix(S, n_components), columns=col_name) y0 = pd.DataFrame(get_kernel_matrix(T, n_components), columns=col_name) x0.loc[:, src.columns[-1]] = pd.Series(src[src.columns[-1]], index=x0.index) y0.loc[:, tgt.columns[-1]] = pd.Series(tgt[tgt.columns[-1]], index=y0.index) return x0, y0 def predict_defects(train, test, weka=False, cutoff=0.6): """ :param train: :type train: :param test: :type test: :param weka: :type weka: :return: """ actual = test[test.columns[-1]].values predicted = rf_model(train, test) return actual, predicted def get_dcv(src, tgt): """Get dataset characteristic vector.""" s_col = [col for col in src.columns[:-1] if '?' not in col] t_col = [col for col in tgt.columns[:-1] if '?' not in col] S = src[s_col] T = tgt[t_col] def self_dist_mtx(arr): try: dist_arr = pdist(arr) except: set_trace() return squareform(dist_arr) dist_src = self_dist_mtx(S.values) dist_tgt = self_dist_mtx(T.values) dcv_src = [np.mean(dist_src), np.median(dist_src), np.min(dist_src), np.max(dist_src), np.std(dist_src), len(S.values)] dcv_tgt = [np.mean(dist_tgt), np.median(dist_tgt), np.min(dist_tgt), np.max(dist_tgt), np.std(dist_tgt), len(T.values)] return dcv_src, dcv_tgt def sim(c_s, c_t, e=0): if c_s[e] * 1.6 < c_t[e]: return "VH" # Very High if c_s[e] * 1.3 < c_t[e] <= c_s[e] * 1.6: return "H" # High if c_s[e] * 1.1 < c_t[e] <= c_s[e] * 1.3: return "SH" # Slightly High if c_s[e] * 0.9 <= c_t[e] <= c_s[e] * 1.1: return "S" # Same if c_s[e] * 0.7 <= c_t[e] < c_s[e] * 0.9: return "SL" # Slightly Low if c_s[e] * 0.4 <= c_t[e] < c_s[e] * 0.7: return "L" # Low if c_t[e] < c_s[e] * 0.4: return "VL" # Very Low def smart_norm(src, tgt, c_s, c_t): """ ARE THESE NORMS CORRECT?? OPEN AN ISSUE REPORT TO VERIFY :param src: :param tgt: :param c_s: :param c_t: :return: """ try: # !!GUARD: PLEASE REMOVE AFTER DEBUGGING!! # Rule 1 if sim(c_s, c_t, e=0) == "S" and sim(c_s, c_t, e=-2) == "S": return src, tgt # Rule 2 elif sim(c_s, c_t, e=2) == "VL" or "VH" \ and sim(c_s, c_t, e=3) == "VL" or "VH" \ and sim(c_s, c_t, e=-1) == "VL" or "VH": return df_norm(src), df_norm(tgt) # Rule 3.1 elif sim(c_s, c_t, e=-2) == "VH" and c_s[-1] > c_t[-1] or \ sim(c_s, c_t, e=-2) == "VL" and c_s[-1] < c_t[-1]: return df_norm(src, type="normal"), df_norm(tgt) # Rule 4 elif sim(c_s, c_t, e=-2) == "VH" and c_s[-1] < c_t[-1] or \ sim(c_s, c_t, e=-2) == "VL" and c_s[-1] > c_t[-1]: return df_norm(src), df_norm(tgt, type="normal") else: return df_norm(src, type="normal"), df_norm(tgt, type="normal") except: set_trace() return src, tgt def get_mar_p0(trn, tst, n_rep): effort = trn[trn.columns[-1]].values.tolist() \ + tst[tst.columns[-1]].values.tolist() hi, lo = max(effort), min(effort) res = [] for _ in xrange(n_rep): actual = tst[tst.columns[-1]].values predicted = np.array([uniform(lo, hi) for __ in xrange(len(actual))]) res.append(abs((actual - predicted) / actual)) return np.mean(res) def tca_plus(source, target, n_rep=12): """ TCA: Transfer Component Analysis :param source: :param target: :param n_rep: number of repeats :return: result """ result = dict() for tgt_name, tgt_path in target.iteritems(): stats = [] print("{} \r".format(tgt_name[0].upper() + tgt_name[1:])) for src_name, src_path in source.iteritems(): if not src_name == tgt_name: src = pandas.read_csv(src_path) tgt = pandas.read_csv(tgt_path) # set_trace() dcv_src, dcv_tgt = get_dcv(src, tgt) for _ in xrange(n_rep): norm_src, norm_tgt = smart_norm(src, tgt, dcv_src, dcv_tgt) _train, __test = map_transform(norm_src.dropna(axis=1, inplace=False), norm_tgt.dropna(axis=1, inplace=False)) actual, predicted = predict_defects(train=_train, test=__test) MAR = abs((actual - predicted) / actual) MAR_p0 = get_mar_p0(_train, __test, n_rep=1000) SA = (1-MAR/MAR_p0) stats.append([src_name, round(np.mean(SA), 1), round(np.std(SA), 1)]) # , stats = pandas.DataFrame(sorted(stats, key=lambda lst: lst[1], reverse=False), # Sort by G Score columns=["Name", "SA (Mean)", "SA (Std)"]) # , print(tabulate(stats, headers=["Name", "SA (Mean)", "SA (Std)"], tablefmt="fancy_grid")) result.update({tgt_name: stats}) # set_trace() return result def tca_jur(): all = get_all_datasets() tca_plus(all, all, n_rep=10) if __name__ == "__main__": tca_jur()
[ "i.m.ralk@gmail.com" ]
i.m.ralk@gmail.com
51a9212611db2eb748f1976a7bc1337e75df00c1
ecff4b18a49ce5952c5f9125dc027cebdecf10a8
/azure-mgmt-scheduler/azure/mgmt/scheduler/models/storage_queue_message.py
084b78ccb0f84eeaa5695d9ebae6f5beae3eb764
[ "Apache-2.0" ]
permissive
jehine-MSFT/azure-sdk-for-python
a56c18020ecd5f4c245c093fd6a33e1b1d7c95e1
6d0f94b39406eab374906c683bd2150217132a9c
refs/heads/master
2020-12-06T19:17:38.153819
2016-04-08T21:03:16
2016-04-08T21:03:16
55,809,131
0
0
null
2016-04-08T20:54:00
2016-04-08T20:54:00
null
UTF-8
Python
false
false
1,878
py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft and contributors. 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. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class StorageQueueMessage(Model): """StorageQueueMessage :param storage_account: Gets or sets the storage account name. :type storage_account: str :param queue_name: Gets or sets the queue name. :type queue_name: str :param sas_token: Gets or sets the SAS key. :type sas_token: str :param message: Gets or sets the message. :type message: str """ _attribute_map = { 'storage_account': {'key': 'storageAccount', 'type': 'str'}, 'queue_name': {'key': 'queueName', 'type': 'str'}, 'sas_token': {'key': 'sasToken', 'type': 'str'}, 'message': {'key': 'message', 'type': 'str'}, } def __init__(self, storage_account=None, queue_name=None, sas_token=None, message=None, **kwargs): self.storage_account = storage_account self.queue_name = queue_name self.sas_token = sas_token self.message = message
[ "lmazuel@microsoft.com" ]
lmazuel@microsoft.com
ce49b89ea66dbef7873d318f3b750d748ff2e565
32eeb97dff5b1bf18cf5be2926b70bb322e5c1bd
/benchmark/redreader/testcase/firstcases/testcase3_003.py
f6c5f5c88712dbe125e58521efd7afe148cee248
[]
no_license
Prefest2018/Prefest
c374d0441d714fb90fca40226fe2875b41cf37fc
ac236987512889e822ea6686c5d2e5b66b295648
refs/heads/master
2021-12-09T19:36:24.554864
2021-12-06T12:46:14
2021-12-06T12:46:14
173,225,161
5
0
null
null
null
null
UTF-8
Python
false
false
3,529
py
#coding=utf-8 import os import subprocess import time import traceback from appium import webdriver from appium.webdriver.common.touch_action import TouchAction from selenium.common.exceptions import NoSuchElementException, WebDriverException desired_caps = { 'platformName' : 'Android', 'deviceName' : 'Android Emulator', 'platformVersion' : '4.4', 'appPackage' : 'org.quantumbadger.redreader', 'appActivity' : 'org.quantumbadger.redreader.activities.MainActivity', 'resetKeyboard' : True, 'androidCoverage' : 'org.quantumbadger.redreader/org.quantumbadger.redreader.JacocoInstrumentation', 'noReset' : True } def command(cmd, timeout=5): p = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=True) time.sleep(timeout) p.terminate() return def getElememt(driver, str) : for i in range(0, 5, 1): try: element = driver.find_element_by_android_uiautomator(str) except NoSuchElementException: time.sleep(1) else: return element os.popen("adb shell input tap 50 50") element = driver.find_element_by_android_uiautomator(str) return element def getElememtBack(driver, str1, str2) : for i in range(0, 2, 1): try: element = driver.find_element_by_android_uiautomator(str1) except NoSuchElementException: time.sleep(1) else: return element for i in range(0, 5, 1): try: element = driver.find_element_by_android_uiautomator(str2) except NoSuchElementException: time.sleep(1) else: return element os.popen("adb shell input tap 50 50") element = driver.find_element_by_android_uiautomator(str2) return element def swipe(driver, startxper, startyper, endxper, endyper) : size = driver.get_window_size() width = size["width"] height = size["height"] try: driver.swipe(start_x=int(width * startxper), start_y=int(height * startyper), end_x=int(width * endxper), end_y=int(height * endyper), duration=2000) except WebDriverException: time.sleep(1) driver.swipe(start_x=int(width * startxper), start_y=int(height * startyper), end_x=int(width * endxper), end_y=int(height * endyper), duration=2000) return # testcase003 try : starttime = time.time() driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps) element = getElememtBack(driver, "new UiSelector().text(\"askreddit\")", "new UiSelector().className(\"android.widget.TextView\").instance(8)") TouchAction(driver).tap(element).perform() element = getElememt(driver, "new UiSelector().className(\"android.widget.ImageView\").description(\"More options\")") TouchAction(driver).long_press(element).release().perform() element = getElememtBack(driver, "new UiSelector().text(\"Submit Post\")", "new UiSelector().className(\"android.widget.TextView\").instance(1)") TouchAction(driver).tap(element).perform() element = getElememt(driver, "new UiSelector().className(\"android.widget.ImageView\").description(\"View Comments\")") TouchAction(driver).long_press(element).release().perform() except Exception, e: print 'FAIL' print 'str(e):\t\t', str(e) print 'repr(e):\t', repr(e) print traceback.format_exc() else: print 'OK' finally: cpackage = driver.current_package endtime = time.time() print 'consumed time:', str(endtime - starttime), 's' command("adb shell am broadcast -a com.example.pkg.END_EMMA --es name \"3_003\"") jacocotime = time.time() print 'jacoco time:', str(jacocotime - endtime), 's' driver.quit() if (cpackage != 'org.quantumbadger.redreader'): cpackage = "adb shell am force-stop " + cpackage os.popen(cpackage)
[ "prefest2018@gmail.com" ]
prefest2018@gmail.com
6eab960a7bf55df7445028b3576e9aca186fc866
9892b74a8c5913ef77725129885f9cb7b65a9eba
/src/Learners.py
99de5284f6ebf8311521302bde1d2c32bd8329d7
[]
no_license
ai-se/Smotuned_FFT
8e2884eaf3192f845d638a1167f7e17dd2c07dcb
df06749cca3e507f963c4ffcb2330cdc031dded1
refs/heads/master
2021-09-28T05:20:01.762515
2018-11-14T17:26:18
2018-11-14T17:26:18
116,091,269
4
1
null
null
null
null
UTF-8
Python
false
false
3,414
py
from __future__ import print_function, division __author__ = 'amrit' import sys sys.dont_write_bytecode = True from ABCD import ABCD import numpy as np from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.svm import SVC, LinearSVC from sklearn.neighbors import KNeighborsClassifier from sklearn.linear_model import LogisticRegression from sklearn.naive_bayes import GaussianNB from scores import * import smote from helper import * recall, precision, specificity, accuracy, f1, g, f2, d2h = 8, 7, 6, 5, 4, 3, 2, 1 def DT(train_data,train_labels,test_data): model = DecisionTreeClassifier(criterion='entropy').fit(train_data, train_labels) prediction=model.predict(test_data) return prediction def KNN(train_data,train_labels,test_data): model = KNeighborsClassifier(n_neighbors=8,n_jobs=-1).fit(train_data, train_labels) prediction = model.predict(test_data) return prediction def LR(train_data,train_labels,test_data): model = LogisticRegression().fit(train_data, train_labels) prediction = model.predict(test_data) return prediction def NB(train_data,train_labels,test_data): model = GaussianNB().fit(train_data, train_labels) prediction = model.predict(test_data) return prediction def RF(train_data,train_labels,test_data): model = RandomForestClassifier(criterion='entropy').fit(train_data, train_labels) prediction = model.predict(test_data) return prediction def SVM(train_data,train_labels,test_data): model = LinearSVC().fit(train_data, train_labels) prediction = model.predict(test_data) return prediction def evaluation(measure, prediction, test_labels, test_data): abcd = ABCD(before=test_labels, after=prediction) stats = np.array([j.stats() for j in abcd()]) labels = list(set(test_labels)) if labels[0] == 0: target_label = 1 else: target_label = 0 if measure == "accuracy": return stats[target_label][-accuracy] if measure == "recall": return stats[target_label][-recall] if measure == "precision": return stats[target_label][-precision] if measure == "specificity": return stats[target_label][-specificity] if measure == "f1": return stats[target_label][-f1] if measure == "f2": return stats[target_label][-f2] if measure == "d2h": return stats[target_label][-d2h] if measure == "g": return stats[target_label][-g] if measure == "popt20": df1 = pd.DataFrame(prediction, columns=["prediction"]) df2 = pd.concat([test_data, df1], axis=1) return get_popt(df2) def main(*x): l = np.asarray(x) function=l[1] measure=l[2] data=l[3] split = split_two(data) pos = split['pos'] neg = split['neg'] ## 20% train and grow cut_pos, cut_neg = cut_position(pos, neg, percentage=80) data_train, data_test = divide_train_test(pos, neg, cut_pos, cut_neg) data_train = smote.execute(l[0].values(), samples=data_train.iloc[:, :-1], labels=data_train.iloc[:, -1:]) lab = [y for x in data_train.iloc[:, -1:].values.tolist() for y in x] prediction=function(data_train.iloc[:, :-1].values, lab, data_test.iloc[:, :-1].values) lab = [y for x in data_test.iloc[:, -1:].values.tolist() for y in x] return evaluation(measure, prediction,lab, data_test)
[ "amritbhanu@gmail.com" ]
amritbhanu@gmail.com
a7494ef2f8a2d3630920a5abc0c0faaec8d9e6cf
7b6c038da851b1d2a3dde5f1158fce03482bc3c1
/luna/gateware/usb/devices/__init__.py
7d057f0bc40e42c7c707fd866713cd9551e6e83b
[ "BSD-3-Clause", "CERN-OHL-P-2.0" ]
permissive
greatscottgadgets/luna
77b636481a3bef13137c7125de970e86a1fdda22
1d8e9cfa6a3e577f255ff3544384a1442b3b015b
refs/heads/main
2023-09-02T02:32:58.944632
2023-09-01T13:00:54
2023-09-01T13:00:54
215,722,076
842
160
BSD-3-Clause
2023-09-13T14:59:36
2019-10-17T06:45:30
Python
UTF-8
Python
false
false
201
py
# # This file is part of LUNA. # # Copyright (c) 2020 Great Scott Gadgets <info@greatscottgadgets.com> # SPDX-License-Identifier: BSD-3-Clause """ Convenience gateware with pre-made device logic. """
[ "k@ktemkin.com" ]
k@ktemkin.com
ed5228f11b7cd0a05ba799e26b2bfc45f18cc59c
43a00df3c162b6279ebda161c2ebd85ce7f9cb64
/generate_s_label.py
dddd6bf2e1f38891f0cb893d4fa2e17cf1543c94
[]
no_license
selous123/SRNet-zoom-pytorch
d5845d6a8b55fef81fdc16e728371486939d243e
08b647e121d70ca69e04719684bcdce8ca8b65d3
refs/heads/master
2020-07-14T15:00:31.497397
2020-03-06T13:47:20
2020-03-06T13:47:20
205,339,265
1
0
null
null
null
null
UTF-8
Python
false
false
1,721
py
import argparse parser = argparse.ArgumentParser() parser.add_argument("--data_dir", type=str, default="/store/dataset/SRRAW/X4/train", help="root folder that contains the images") parser.add_argument("--labels", type=str, default="Edge+Diff", help="root folder that contains the images") ARGS = parser.parse_args() #traindataRootDir = "/store2/dataset/SR/train_data/SRRAW/X4/train" traindataRootDir = ARGS.data_dir subDirs = ["HR", "LR"] ## Generate Edge Information import os from PIL import Image, ImageFilter, ImageChops file_names = os.listdir(os.path.join(traindataRootDir,subDirs[0])) file_names.sort() dir_label = ARGS.labels.split("+") for d_label in dir_label: os.makedirs(os.path.join(traindataRootDir, d_label),exist_ok=True) for i, file_name in enumerate(file_names): imgPath = os.path.join(traindataRootDir, subDirs[0], file_name) desPath = os.path.join(traindataRootDir,"Edge",file_name) img = Image.open(imgPath) img_edge = img.filter(ImageFilter.FIND_EDGES).filter( ImageFilter.EDGE_ENHANCE_MORE) #.filter(ImageFilter.DETAIL) img_edge.save(desPath) print("file_name:%s, Index:%d" %(file_name,i)) for i, file_name in enumerate(file_names): imgPath = os.path.join(traindataRootDir, subDirs[0], file_name) imgLRPath = os.path.join(traindataRootDir, subDirs[1], file_name) desPath = os.path.join(traindataRootDir,"Diff",file_name) img = Image.open(imgPath) img_lr = Image.open(imgLRPath) u_img_lr = img_lr.resize(img.size) d = ImageChops.difference(img,u_img_lr).filter( ImageFilter.EDGE_ENHANCE_MORE).filter(ImageFilter.DETAIL) d.save(desPath) print("file_name:%s, Index:%d" %(file_name,i))
[ "lrhselous@163.com" ]
lrhselous@163.com
917a51c81202012da9c84549d807bcf36aadd226
04141e207a7cc88a58245fa412b2a841901d504f
/otn.mit.edu/otn/web/forms.py
1893ee1db091bfb83f4c3f24b699f62b7486469b
[]
no_license
mwidner/socialsaver
bbda2cefea2b8f74d2bbbad2705e616a88a5d582
3b6a1d8f0522735e462f9d2bf6ef12a999d8cc85
refs/heads/master
2021-01-15T20:29:35.288919
2012-04-16T18:27:30
2012-04-16T18:27:30
null
0
0
null
null
null
null
UTF-8
Python
false
false
173
py
from django import forms from django.forms import ModelForm class BuxferLoginForm(forms.Form): email = forms.EmailField() password = forms.CharField()
[ "kwan@media.mit.edu" ]
kwan@media.mit.edu
7e8f73697561d7e8ee084ee9c1e6a02d06b75021
c24ad19b65992dd2be3d3210b889d970e43b9cdc
/class/phase1/day09/exercise05.py
79e8a0e0b6539289fae06c370f41ccd4439e02e6
[]
no_license
ivoryli/myproject
23f39449a0bd23abcc3058c08149cebbfd787d12
cebfa2594198060d3f8f439c971864e0639bbf7e
refs/heads/master
2020-05-30T06:25:41.345645
2019-05-31T11:15:55
2019-05-31T11:15:55
189,578,491
0
0
null
null
null
null
UTF-8
Python
false
false
3,982
py
''' 创建技能类(技能名称,冷却时间,持续时间,攻击距离......) name cd td ad 要求:使用属性封装变量 创建技能列表(技能对象的列表) -- 查找名称是"降龙十八掌"的技能对象 -- 查找名称是持续时间大于10秒的的所有技能对象 -- 查找攻击距离最远的技能对象 -- 按照持续时间,对列表升序排列. ''' #myself # class Skill: # def __init__(self,name,cd,td,ad): # self.name = name # self.cd = cd # self.td = td # self.ad = ad # # def print_self(self): # print(self.name,self.cd,self.td,self.ad) # # @property # def name(self): # return self.__name # # @name.setter # def name(self,value): # self.__name = value # # @property # def cd(self): # return self.__cd # # @cd.setter # def cd(self,value): # self.__cd = value # # @property # def td(self): # return self.__td # # @td.setter # def td(self,value): # self.__td = value # # @property # def ad(self): # return self.__ad # # @ad.setter # def ad(self, value): # self.__ad = value # # L = [ # Skill('降龙十八掌',1,6,20), # Skill('金刚伏魔',2,5,9), # Skill('飞龙在天',3,19,13), # Skill('天下无狗',4,11,2), # Skill('亢龙有悔',5,8,7) # ] # # def find_name(list_target,name): # for item in list_target: # if item.name == name: # return item # # find_name(L,"降龙十八掌").print_self() # print() # # L2 = [] # for item in L: # if item.td > 10: # L2.append(item) # # for item in L2: # item.print_self() # # print(max([x.ad for x in L])) # print() # # L = sorted(L,key = lambda Teacher:Teacher.td) # for item in L: # item.print_self() #-------------------------------------------------------------------------------------------------- class SkillData: def __init__(self, name, cd, time, distance): self.name = name self.cd = cd self.time = time self.atk_distance = distance @property def name(self): return self.__name @name.setter def name(self, value): self.__name = value @property def cd(self): return self.__cd @cd.setter def cd(self, value): self.__cd = value @property def time(self): return self.__time @time.setter def time(self, value): self.__time = value @property def atk_distance(self): return self.__atk_distance @atk_distance.setter def atk_distance(self, value): self.__atk_distance = value def print_self(self): print(self.name, self.cd, self.time, self.atk_distance) list_skills = [ SkillData("降龙十八掌", 60, 10, 5), SkillData("如来神掌", 50, 5, 15), SkillData("六脉神剑", 80, 20, 8), SkillData("一阳指", 20, 50, 15), SkillData("冷酷追击", 15, 30, 9), ] # -- 查找名称是"降龙十八掌"的技能对象 for item in list_skills: if item.name == "降龙十八掌": item.print_self() # -- 查找名称是持续时间大于10秒的的所有技能对象 result = [] for item in list_skills: if item.time > 10: result.append(item) # -- 查找攻击距离最远的技能对象 result = list_skills[0] for i in range(1, len(list_skills)): # 后面的技能对象 if result.atk_distance < list_skills[i].atk_distance: result = list_skills[i] # result.atk_distance = list_skills[i].atk_distance result.print_self() # -- 按照持续时间,对列表升序排列. for r in range(len(list_skills) - 1): for c in range(r + 1, len(list_skills)): if list_skills[r].time > list_skills[c].time: list_skills[r],list_skills[c] = list_skills[c],list_skills[r] # 请用调试,查看列表的取值. print(list_skills)
[ "2712455490@qq.com" ]
2712455490@qq.com
c152e031f9a7c91cfde2dd249fba12f4f1b3cb78
f3d38d0e1d50234ce5f17948361a50090ea8cddf
/백준/Silver/Silver 5/1158번 ; 요세푸스 문제.py
446a4ad3871ead236aa291b9fccaf9596278359c
[]
no_license
bright-night-sky/algorithm_study
967c512040c183d56c5cd923912a5e8f1c584546
8fd46644129e92137a62db657187b9b707d06985
refs/heads/main
2023-08-01T10:27:33.857897
2021-10-04T14:36:21
2021-10-04T14:36:21
323,322,211
0
0
null
null
null
null
UTF-8
Python
false
false
315
py
# https://www.acmicpc.net/problem/1158 # 첫째 줄에 N, K를 빈 칸으로 구분해 입력합니다. # 1 <= K <= N <= 5,000 N, K = map(int, input().split()) circle = [number for number in range(1, N + 1)] poped_number = [] while True: circle_length = len(circle) if circle_length == 0: break
[ "bright_night_sky@naver.com" ]
bright_night_sky@naver.com
a0a260eae98611dd8badfb76589c148bf4846f3d
2a1b8a671aceda6bc446f8ce26400aa84fa444a6
/Packs/CommunityCommonScripts/Scripts/PHash/PHash.py
a65682627380ca763287b167d2edc08522c75a03
[ "MIT" ]
permissive
demisto/content
6d4722d46f0ff0beea2748e9f7de585bf91a78b4
890def5a0e0ae8d6eaa538148249ddbc851dbb6b
refs/heads/master
2023-09-04T00:02:25.618032
2023-09-03T21:56:22
2023-09-03T21:56:22
60,525,392
1,023
1,921
MIT
2023-09-14T20:55:24
2016-06-06T12:17:02
Python
UTF-8
Python
false
false
389
py
import demistomock as demisto # noqa: F401 import imagehash from CommonServerPython import * # noqa: F401 from PIL import Image ImageID = demisto.args()['image'] ImageFilePath = demisto.getFilePath(ImageID) hash = imagehash.phash(Image.open(ImageFilePath['path'])) context = { "PHash": str(hash) } command_results = CommandResults(outputs=context) return_results(command_results)
[ "noreply@github.com" ]
demisto.noreply@github.com
5d1de9164de59d2aaa12d87d853da062ae8caca6
a7f83dbecc14470645de7f502292394f38bc4661
/router/asgi.py
7df5255ada09b87226a02a56174c19568f56aa37
[]
no_license
erllan/ROUTER
f6ab0530b3106c3e3bffe33e46b8ddedb08ab64a
5b2a2b76edd28887b5b0b2b0ad4a340344bd399a
refs/heads/master
2023-01-20T10:20:23.355230
2020-11-22T19:23:13
2020-11-22T19:23:13
310,087,275
0
1
null
null
null
null
UTF-8
Python
false
false
389
py
""" ASGI config for router project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'router.settings') application = get_asgi_application()
[ "erlan.kubanychbekov.000@gmail.com" ]
erlan.kubanychbekov.000@gmail.com
032de7d294c7805f6c78214f7adb90542a8f2a4f
2a54e8d6ed124c64abb9e075cc5524bb859ba0fa
/.history/3-OO-Python/7-private-public_20200415234405.py
3f7ad76390081dccb1d9fb972a71267ff401dc12
[]
no_license
CaptainStorm21/Python-Foundation
01b5fbaf7a913506518cf22e0339dd948e65cea1
a385adeda74f43dd7fb2d99d326b0be23db25024
refs/heads/master
2021-05-23T01:29:18.885239
2020-04-23T19:18:06
2020-04-23T19:18:06
253,171,611
0
0
null
null
null
null
UTF-8
Python
false
false
213
py
# def speak(self): print(f'my name is {self.name}. I am {self.age}') player1 = PlayerCharacter('Andy', 1000) player1.name = 'Wolverine' player1.speak = 'BooBoo!' print(player1.speak)
[ "tikana4@yahoo.com" ]
tikana4@yahoo.com
cf81714c80096d8ff059fc3b666ec1cf12d22ab7
aee144770c8f4ec5987777aebe5b064e558fc474
/doc/integrations/pytorch/parlai/tasks/qazre/build.py
30cde0347bc725cd13474e5283b0f140a383fba7
[ "MIT", "CC-BY-SA-3.0", "Apache-2.0", "AGPL-3.0-only" ]
permissive
adgang/cortx
1d8e6314643baae0e6ee93d4136013840ead9f3b
a73e1476833fa3b281124d2cb9231ee0ca89278d
refs/heads/main
2023-04-22T04:54:43.836690
2021-05-11T00:39:34
2021-05-11T00:39:34
361,394,462
1
0
Apache-2.0
2021-04-25T10:12:59
2021-04-25T10:12:59
null
UTF-8
Python
false
false
1,232
py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # # Download and build the data if it does not exist. import parlai.core.build_data as build_data import os from parlai.core.build_data import DownloadableFile RESOURCES = [ DownloadableFile( 'http://nlp.cs.washington.edu/zeroshot/relation_splits.tar.bz2', 'relation_splits.tar.bz2', 'e33d0e367b6e837370da17a2d09d217e0a92f8d180f7abb3fd543a2d1726b2b4', ) ] def build(opt): dpath = os.path.join(opt['datapath'], 'QA-ZRE') version = None if not build_data.built(dpath, version_string=version): print('[building data: ' + dpath + ']') if build_data.built(dpath): # An older version exists, so remove these outdated files. build_data.remove_dir(dpath) build_data.make_dir(dpath) # Download the data. for downloadable_file in RESOURCES: downloadable_file.download_file(dpath) # Mark the data as built. build_data.mark_done(dpath, version_string=version)
[ "noreply@github.com" ]
adgang.noreply@github.com
52411521d4c4848047d6566be95021f633aac53f
480cc056ae6f2c8e098468d13858d01851b3fa5c
/tools/create_json
1558ac765a7822481868c2a24dc700655088dbcf
[ "MIT" ]
permissive
blechta/betterbib
1300d18364c717676c54b8a76b3f1043f2249c5b
ba2c6b1c3a599d5397c3c913a1fe7725875665b3
refs/heads/master
2020-03-23T08:32:44.704257
2018-06-20T20:16:14
2018-06-20T20:16:14
141,333,072
0
0
MIT
2018-07-17T19:16:59
2018-07-17T19:16:59
null
UTF-8
Python
false
false
1,262
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # """This tool is used for converting JabRef's journal name abbreviation files, <https://github.com/JabRef/jabref/tree/master/src/main/resources/journals>, into JSON. Usage example: ``` cat IEEEJournalListText.txt journalList.txt | ./create_json - journals.json ``` """ import argparse import sys import json def _main(): args = _parse_cmd_arguments() # read input file into dictionary out = {} for line in args.infile: sline = line.strip() if sline[0] == "#": continue k, v = sline.split("=") out[k.strip()] = v.strip() json.dump(out, args.outfile, indent=2) return def _parse_cmd_arguments(): parser = argparse.ArgumentParser( description="Creates YAML file from `=` input files." ) parser.add_argument( "infile", nargs="?", type=argparse.FileType("r"), default=sys.stdin, help="input `=` files (default: stdin)", ) parser.add_argument( "outfile", nargs="?", type=argparse.FileType("w"), default=sys.stdout, help="output YAML file (default: stdout)", ) return parser.parse_args() if __name__ == "__main__": _main()
[ "nico.schloemer@gmail.com" ]
nico.schloemer@gmail.com
3691f1fd4f857ea86bcecfaf74e4c30c1db3f4f9
71e214849d65fb119ac7d82b8bb852cb09953caa
/pin_tester.py
a2b0e7f4181ea684610902968bd2196fed705d72
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
nanuxbe/microbit-files
daabd2d0685786696f5dd4554b1370175669f3c1
70fd249fc98635ad8764d0a65b528f79648c6034
refs/heads/master
2021-01-17T20:22:27.575172
2016-10-20T09:24:26
2016-10-20T09:24:26
68,598,147
3
1
null
null
null
null
UTF-8
Python
false
false
288
py
from microbit import * PINS = [pin0, pin1, pin2, pin8, pin16] while True: if button_a.is_pressed(): display.show("1") for pin in PINS: pin.write_digital(1) else: display.show(Image.NO) for pin in PINS: pin.write_digital(0)
[ "emma@levit.be" ]
emma@levit.be
63c498bd4d2d283e7d36c07193348b6caeb20f9d
ee1258111670dc0d12d93099a1bcc5ae5ac6b948
/chainer/nn.py
609878ea2b1cb0c007ba454ee4063ab6db3ecc36
[]
no_license
cpple/mnistCUDNN
d5bf0a4680892b023d6875fe845d97a025ad1652
0f1a3395fd9c5b6e87a9903e94845a5833e46cee
refs/heads/master
2021-09-23T23:24:21.871321
2018-09-29T01:56:44
2018-09-29T01:56:44
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,145
py
from chainer import Chain import chainer.functions as F import chainer.links as L # ネットワーク定義 k = 16 fcl = 256 class NN(Chain): def __init__(self): super(NN, self).__init__() with self.init_scope(): self.conv1 = L.Convolution2D(in_channels = 1, out_channels = k, ksize = 3, pad = 1) self.conv2 = L.Convolution2D(in_channels = k, out_channels = k, ksize = 3, pad = 1) self.conv3 = L.Convolution2D(in_channels = k, out_channels = k, ksize = 3, pad = 1) self.l4 = L.Linear(7*7*k, fcl) self.l5 = L.Linear(fcl, 10) self.bn1 = L.BatchNormalization(k) self.bn2 = L.BatchNormalization(k) def __call__(self, x): h = self.conv1(F.reshape(x, (len(x), 1, 28, 28))) h = self.bn1(h) h1 = F.relu(h) # resnet block h = self.conv2(h1) h = self.bn2(h) h = h + h1 h = F.max_pooling_2d(F.relu(h), 2) h = self.conv3(h) h = F.max_pooling_2d(F.relu(h), 2) h = F.relu(self.l4(h)) h = F.dropout(h, ratio=0.4) return self.l5(h)
[ "tadaoyamaoka@gmail.com" ]
tadaoyamaoka@gmail.com
bd6477e67f2ed7e8fd503b734b36b9f9138ec3c2
21dbd7e2e91636a24b4482d4f49acd29bf87664e
/spell/__init__.py
0afe6077a092df621805351c2215040e094ed674
[ "MIT" ]
permissive
sbuvaneshkumar/open-tamil
688f8826f0fc285c1cd4098ef8d448a10193fc61
903297c8fe6510077d8d65a41adaaeb7da9c5e97
refs/heads/master
2021-04-06T08:26:23.403276
2018-03-11T02:51:56
2018-03-11T02:51:56
124,749,654
0
0
MIT
2018-03-11T11:28:18
2018-03-11T11:28:18
null
UTF-8
Python
false
false
130
py
## -*- coding: utf-8 -*- ## (C) 2016-17 Muthiah Annamalai, from .spell import LoadDictionary, Mayangoli, OttruSplit, Speller
[ "ezhillang@gmail.com" ]
ezhillang@gmail.com
a631f571b4f65d85fb6322bd065ab83755349a3c
52b5773617a1b972a905de4d692540d26ff74926
/.history/uniquePaths_20200728102526.py
971197f817b1ca80f65931fe080d5b65235b275c
[]
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
890
py
def uniquePath(arr): # mark one as None or -1 thatway in the case where # we have to only calculate the once where there is no none m = len(arr) for i in range(len(arr)): for j in range(len(arr[i])): if arr[i][j] == 1: arr[i][j] = "None" elif i == 0 or j == 0: arr[i][j] = 1 for i in range(len(arr)): for j in range(len(arr[i])): if arr[i][j] == "None": arr[i][j-1] = 1 arr[i-1][j] = 1 arr[i+1][j] = 1 arr[i][j+1] = 1 else: if arr[i-1][j] != "None" and arr[i][j-1] != "None": arr[i][j] = arr[i-1][j] + arr[i][j-1] print(arr[]) uniquePath([ [0,0,0], [0,1,0], [0,0,0] ])
[ "mary.jereh@gmail.com" ]
mary.jereh@gmail.com
8f5e5805d30d579a4a7c72aac4eced82ef28fdf3
58db5cdab90e34107018892b69c6b4ed63fc2604
/findMissing.py
8e48c7a6e0db6498a9ba5f40e0fc8b5c3462c4cf
[]
no_license
jamiejamiebobamie/pythonPlayground
2b329d0a8741146f7a715b15b33c4e2f24a9a677
b622eeb78b22760d2570cc085716f74b344072e8
refs/heads/master
2020-04-14T15:03:01.127800
2019-10-03T23:34:32
2019-10-03T23:34:32
163,914,975
0
0
null
null
null
null
UTF-8
Python
false
false
1,090
py
# following along to this video: https://interviewing.io/recordings/Python-Airbnb-4 # write a fucntion that takes in two arrays # and finds the one element that is missing from the second array # a good question to ask is if the items are sorted and all unique? def findMissing(A1, A2): # n is the number of elements in A1 matches = set(A2) #O(n-1) for item in A1: # less than O(n) if not item in matches: return item return "wrong input" A1 = [1,2,3,4,5,6,7,8,9,10] A2 = [1,2,3,4,5,6,8,9,10] print(findMissing(A1, A2)) # time complexity is less than O(2n) def findMissingLowSpace(A1, A2): # O(2n) time, O(1ish) space though you can't be sure of size of int sum1 = sum2 = 0 for item in A1: sum1 += item for item in A2: sum2 += item return sum1 - sum2 print(findMissingLowSpace(A1,A2)) #interview O(1) space solution: def find_missing_xor(A1, A2): xor_sum = 0 for num in A1: xor_sum ^= num for num in A2: xor_sum ^= num return xor_sum print(find_missing_xor(A1, A2))
[ "jmccrory@vt.edu" ]
jmccrory@vt.edu
021797fb0a2fbaf4c5a693862c72aa1bd145dc71
f96a40b46adf8820150ac26fcc62b477035ef799
/python re/re2.py
63bf2abcda2c169f8d6b256a973a343bef91c751
[]
no_license
borkarfaiz/python
0cacf85b262ea0b2040488d7ec1b83565f85d736
a4f5d98af2455bd3176003ca43aeefaa31e85dc3
refs/heads/master
2020-05-23T05:23:39.628953
2017-07-13T15:02:34
2017-07-13T15:02:34
56,511,268
0
0
null
null
null
null
UTF-8
Python
false
false
233
py
import re f = open('random.txt') strToSearch = "" for line in f: strToSearch += line print(strToSearch) patFinder1 = re.compile('a+$') findPat = re.search(patFinder1, strToSearch) print(re.findall(patFinder1, strToSearch))
[ "borkarfaiz@gmail.com" ]
borkarfaiz@gmail.com
abcc5cdd9a7ab07f52f6ffd956775be41121d4e3
35b6013c1943f37d1428afd2663c8aba0a02628d
/trace/trace-python-sample-opentelemetry/main_test.py
2e5b0e80eaaa1083b24f5cb64928ffba3491e7e6
[ "Apache-2.0" ]
permissive
GoogleCloudPlatform/python-docs-samples
d2a251805fbeab15d76ed995cf200727f63f887d
44e819e713c3885e38c99c16dc73b7d7478acfe8
refs/heads/main
2023-08-28T12:52:01.712293
2023-08-28T11:18:28
2023-08-28T11:18:28
35,065,876
7,035
7,593
Apache-2.0
2023-09-14T20:20:56
2015-05-04T23:26:13
Jupyter Notebook
UTF-8
Python
false
false
1,279
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. import os import main def test_index() -> None: project_id = os.environ["GOOGLE_CLOUD_PROJECT"] main.app.testing = True main.app.config["TRACER"] = main.initialize_tracer(project_id) client = main.app.test_client() resp = client.get("/index.html") assert resp.status_code == 200 assert "Tracing requests" in resp.data.decode("utf-8") def test_redirect() -> None: project_id = os.environ["GOOGLE_CLOUD_PROJECT"] main.app.testing = True main.app.config["TRACER"] = main.initialize_tracer(project_id) client = main.app.test_client() resp = client.get("/") assert resp.status_code == 302 assert "/index.html" in resp.headers.get("location", "")
[ "noreply@github.com" ]
GoogleCloudPlatform.noreply@github.com
555bc475cdfcfef2a817eebd802725e0e3bcb899
059038f86df6c285cc9bfbd8e1924eea37906160
/jobplus/handlers/front.py
fc45cb5d17b71d3ff01ad42ab99170dbffa4f8c1
[]
no_license
LouPlus/jobplus11-1
f6249279a625b8d151eb5e23e7ce16e63aade2af
59dc0e2437f69dec3a4665a8074e3fd286e97f00
refs/heads/master
2023-02-17T19:54:15.335352
2019-05-18T11:00:15
2019-05-18T11:00:15
183,372,297
2
2
null
2023-02-02T06:25:14
2019-04-25T06:39:54
Python
UTF-8
Python
false
false
1,390
py
from flask import Blueprint,render_template from flask import flash,redirect,url_for from flask_login import login_user,logout_user,login_required from jobplus.forms import LoginForm,RegisterForm from jobplus.models import User front = Blueprint('front',__name__) @front.route('/') def index(): return render_template('index.html') @front.route('/login',methods=['GET','POST']) def login(): form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() login_user(user,form.remember_me.data) return redirect(url_for('.index')) return render_template('login.html',form=form) @front.route('/company_register',methods=['GET','POST']) def company_register(): form = RegisterForm() if form.validate_on_submit(): form.create_company_user() flash('注册成功,请登录!','success') return redirect(url_for('.login')) return render_template('company_register.html',form=form) @front.route('/user_register',methods=['GET','POST']) def user_register(): form = RegisterForm() if form.validate_on_submit(): form.create_user() flash('注册成功,请登录!','success') return redirect(url_for('.login')) return render_template('user_register.html',form=form) @front.route('/logout') @login_required def logout(): logout_user() flash('您已经退出登录','success') return redirect(url_for('.index'))
[ "34020606+LouPlus@users.noreply.github.com" ]
34020606+LouPlus@users.noreply.github.com
b693d2d08b70e91e1f82b7f83dd5f455b55e0309
fda3405523689654b35b8f1c62cb8ed2728470d1
/stests/core/clx/stream.py
eb135ed7060f6399c39bc40e652d6ac28d57f122
[]
no_license
piokuc/stests
f5d98e17b4883bf2bd19761be15485c484b1eabc
2d1301e01576dde574c25609671daf1821edfa0c
refs/heads/master
2021-03-18T10:25:13.457975
2020-03-18T17:37:09
2020-03-18T17:37:09
247,066,284
0
0
null
2020-03-13T12:28:15
2020-03-13T12:28:14
null
UTF-8
Python
false
false
1,777
py
import typing from stests.core.clx.utils import get_client from stests.core.clx.utils import clx_op from stests.core.domain import NetworkIdentifier from stests.core.domain import NodeIdentifier from stests.core.utils import logger @clx_op def stream_events( src: typing.Union[NodeIdentifier, NetworkIdentifier], on_block_added: typing.Callable = None, on_block_finalized: typing.Callable = None ): """Hooks upto network streaming events. :param src: The source from which a network node will be derived. :param on_block_added: Callback to invoke whenever a block is added to chain. :param on_block_finalized: Callback to invoke whenever a block is finalized. """ for node, event in _yield_events(src, on_block_added, on_block_finalized): if on_block_added and event.HasField("block_added"): bhash = event.block_added.block.summary.block_hash.hex() logger.log(f"PYCLX :: stream_events :: block added :: {bhash}") on_block_added(node, bhash) elif on_block_finalized and event.HasField("new_finalized_block"): bhash = event.new_finalized_block.block_hash.hex() logger.log(f"PYCLX :: stream_events :: block finalized :: {bhash}") on_block_finalized(node, bhash) def _yield_events( src: typing.Union[NodeIdentifier, NetworkIdentifier], on_block_added: typing.Optional[typing.Callable], on_block_finalized: typing.Optional[typing.Callable] ): """Yields events from event source (i.e. a CLX chain). """ node, client = get_client(src) for event in client.stream_events( block_added=on_block_added is not None, block_finalized=on_block_finalized is not None ): yield node, event
[ "mark@casperlabs.io" ]
mark@casperlabs.io
8f957c13ca72094e0b2e99956969a9d18eb2eb1e
a3482e5b922bcc5b8d8fd3dc49a29a3073176191
/source_py3/python_toolbox/introspection_tools.py
1d884ef81347a915596dd9d03d1740f187712b53
[ "MIT" ]
permissive
apddup/python_toolbox
4d2079826218255240a27b9b977b3a4fc2045ee3
2d336f361122ad4216669b7a3e1d794fa2a76db1
refs/heads/master
2021-01-18T17:09:02.879773
2013-10-06T18:20:34
2013-10-06T18:20:34
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,188
py
# Copyright 2009-2013 Ram Rachum. # This program is distributed under the MIT license. '''Defines various introspection tools, similar to the stdlib's `inspect`.''' from python_toolbox import cute_inspect from python_toolbox.nifty_collections import OrderedDict def get_default_args_dict(function): ''' Get ordered dict from arguments which have a default to their default. Example: >>> def f(a, b, c=1, d='meow'): pass >>> get_default_args_dict(f) OrderedDict([('c', 1), ('d', 'meow')]) ''' arg_spec = cute_inspect.getargspec(function) (s_args, s_star_args, s_star_kwargs, s_defaults) = arg_spec # `getargspec` has a weird policy, when inspecting a function with no # defaults, to give a `defaults` of `None` instead of the more consistent # `()`. We fix that here: if s_defaults is None: s_defaults = () # The number of args which have default values: n_defaultful_args = len(s_defaults) defaultful_args = s_args[-n_defaultful_args:] if n_defaultful_args \ else [] return OrderedDict(zip(defaultful_args, s_defaults))
[ "ram@rachum.com" ]
ram@rachum.com
1e467b51e3c06ca572cb48209a76785c48c96df6
163bbb4e0920dedd5941e3edfb2d8706ba75627d
/Code/CodeRecords/2826/60659/260490.py
971d4304f27404a9a57c1a1c15e77cfa27a8b55d
[]
no_license
AdamZhouSE/pythonHomework
a25c120b03a158d60aaa9fdc5fb203b1bb377a19
ffc5606817a666aa6241cfab27364326f5c066ff
refs/heads/master
2022-11-24T08:05:22.122011
2020-07-28T16:21:24
2020-07-28T16:21:24
259,576,640
2
1
null
null
null
null
UTF-8
Python
false
false
249
py
n=int(input()) num=input().split(" ") for i in range(n): num[i]=int(num[i]) num.sort() result=0 for i in range(1,n): if num[i]<num[i-1]: result+=num[i-1]-num[i]+1 num[i]=num[i-1]+1 elif num[i]==num[i-1]: num[i]+=1 result+=1 print(result)
[ "1069583789@qq.com" ]
1069583789@qq.com
4aaa3c796e97075709ceef44423a81d11391d236
7950c4faf15ec1dc217391d839ddc21efd174ede
/problems/1658.0_Minimum_Operations_to_Reduce_X_to_Zero.py
7d298d830bc7aa62f9dadacedb3fc628f5fc96c5
[]
no_license
lixiang2017/leetcode
f462ecd269c7157aa4f5854f8c1da97ca5375e39
f93380721b8383817fe2b0d728deca1321c9ef45
refs/heads/master
2023-08-25T02:56:58.918792
2023-08-22T16:43:36
2023-08-22T16:43:36
153,090,613
5
0
null
null
null
null
UTF-8
Python
false
false
6,854
py
''' prefix sum + binary search T: O(7 * N + NlogN) = O(NlogN) S: O(2N) Runtime: 2397 ms, faster than 8.98% of Python3 online submissions for Minimum Operations to Reduce X to Zero. Memory Usage: 28.4 MB, less than 44.81% of Python3 online submissions for Minimum Operations to Reduce X to Zero. ''' class Solution: def minOperations(self, nums: List[int], x: int) -> int: n = len(nums) left = list(accumulate(nums)) if left[-1] < x or (nums[0] > x and nums[-1] > x): return -1 if nums[0] == x or nums[-1] == x: return 1 right = list(reversed(list(accumulate(reversed(nums))))) ans = n + 1 for i in range(1, n): if right[i] == x: ans = min(ans, n - i) elif left[i] == x: ans = min(ans, i + 1) else: idx = bisect_left(left, x - right[i], 0, i - 1) if left[idx] + right[i] == x: # for right, i...n-1 ans = min(ans, idx + 1 + n - i) return -1 if ans == n + 1 else ans ''' nums.reverse() Runtime: 1515 ms, faster than 60.15% of Python3 online submissions for Minimum Operations to Reduce X to Zero. Memory Usage: 28.1 MB, less than 50.24% of Python3 online submissions for Minimum Operations to Reduce X to Zero. ''' class Solution: def minOperations(self, nums: List[int], x: int) -> int: n = len(nums) left = list(accumulate(nums)) if left[-1] < x or (nums[0] > x and nums[-1] > x): return -1 if nums[0] == x or nums[-1] == x: return 1 nums.reverse() right = list(accumulate(nums)) right.reverse() ans = n + 1 for i in range(1, n): if right[i] == x: ans = min(ans, n - i) elif left[i] == x: ans = min(ans, i + 1) else: idx = bisect_left(left, x - right[i], 0, i - 1) if left[idx] + right[i] == x: # for right, i...n-1 ans = min(ans, idx + 1 + n - i) return -1 if ans == n + 1 else ans ''' right[i] = right[i + 1] + nums[i] Runtime: 2933 ms, faster than 5.20% of Python3 online submissions for Minimum Operations to Reduce X to Zero. Memory Usage: 28.2 MB, less than 50.24% of Python3 online submissions for Minimum Operations to Reduce X to Zero. ''' class Solution: def minOperations(self, nums: List[int], x: int) -> int: n = len(nums) left = list(accumulate(nums)) if left[-1] < x or (nums[0] > x and nums[-1] > x): return -1 if nums[0] == x or nums[-1] == x: return 1 right = [nums[-1]] * n for i in range(n - 2, -1, -1): right[i] = right[i + 1] + nums[i] ans = n + 1 for i in range(1, n): if right[i] == x: ans = min(ans, n - i) elif left[i] == x: ans = min(ans, i + 1) else: idx = bisect_left(left, x - right[i], 0, i - 1) if left[idx] + right[i] == x: # for right, i...n-1 ans = min(ans, idx + 1 + n - i) return -1 if ans == n + 1 else ans ''' sliding window / two pointers T: O(N) S: O(1) Runtime: 1683 ms, faster than 46.23% of Python3 online submissions for Minimum Operations to Reduce X to Zero. Memory Usage: 27.9 MB, less than 96.23% of Python3 online submissions for Minimum Operations to Reduce X to Zero. ''' class Solution: def minOperations(self, nums: List[int], x: int) -> int: # to find complementary n, s = len(nums), sum(nums) if s < x or (nums[0] > x and nums[-1] > x): return -1 if s == x: return n com = s - x i = j = 0 subsum = 0 longest_sub = 0 while i < n and j <= n: if subsum < com: if j == n: break subsum += nums[j] if subsum == com: longest_sub = max(longest_sub, j - i + 1) # [i...j] j += 1 else: subsum -= nums[i] i += 1 if subsum == com: longest_sub = max(longest_sub, j - i) # [i...j-1], caused by `j += 1` return -1 if longest_sub == 0 else n - longest_sub ''' Input: [8828,9581,49,9818,9974,9869,9991,10000,10000,10000,9999,9993,9904,8819,1231,6309] 134365 Output: -1 Expected: 16 Input [5,1,4,2,3] 6 Output -1 Expected 2 ''' ''' sliding window / two pointers T: O(N) S: O(1) Runtime: 1460 ms, faster than 64.63% of Python3 online submissions for Minimum Operations to Reduce X to Zero. Memory Usage: 28 MB, less than 62.03% of Python3 online submissions for Minimum Operations to Reduce X to Zero. ''' class Solution: def minOperations(self, nums: List[int], x: int) -> int: # to find complementary n, s = len(nums), sum(nums) if s < x or (nums[0] > x and nums[-1] > x): return -1 if s == x: return n com = s - x i = j = 0 subsum = 0 longest_sub = 0 while i < n and j <= n: if subsum < com: if j == n: break subsum += nums[j] j += 1 elif subsum > com: subsum -= nums[i] i += 1 else: longest_sub = max(longest_sub, j - i) # [i...j-1] subsum -= nums[i] if j == n: break subsum += nums[j] i += 1 j += 1 return -1 if longest_sub == 0 else n - longest_sub ''' hash table T: O(2N) = O(N) S: O(N) Runtime: 2198 ms, faster than 13.69% of Python3 online submissions for Minimum Operations to Reduce X to Zero. Memory Usage: 35.8 MB, less than 29.25% of Python3 online submissions for Minimum Operations to Reduce X to Zero. ''' class Solution: def minOperations(self, nums: List[int], x: int) -> int: # postsum -> idx post, postsum = {}, 0 n = len(nums) post[0] = n for i in range(n - 1, -1, -1): postsum += nums[i] post[postsum] = i presum = 0 ans = n + 1 if x in post: ans = n - post[x] for i in range(n): presum += nums[i] if x - presum in post and post[x - presum] > i: idx = post[x - presum] ans = min(ans, i + 1 + n - idx) return -1 if ans == n + 1 else ans
[ "laoxing201314@outlook.com" ]
laoxing201314@outlook.com
af447697d230967e564b8d43cc5849a419c7d3b1
0cf6cc52e2d8f230d4a4265e955dd3e0810653c0
/my_prj/test_utils/factories/poll.py
bc027b22d8667a7ea48fd6f6c4c5fdef0d0218e7
[]
no_license
miphreal/dev2dev-testing
c67c4fc2934d8ec4831e676e6d46071bca89fa25
c09e64984f3e53d8f61e4b0b5236482eaa38b663
refs/heads/master
2021-01-11T00:06:03.503707
2016-10-25T15:02:42
2016-10-25T15:02:42
70,728,818
0
0
null
null
null
null
UTF-8
Python
false
false
613
py
from my_prj.polls.models import Question, Choice from my_prj.test_utils import * class ChoiceFactory(factory.DjangoModelFactory): class Meta: model = Choice choice_text = factory.Faker('text') votes = 0 class QuestionFactory(factory.DjangoModelFactory): class Meta: model = Question question_text = factory.Faker('text') pub_date = FuzzyAttribute(lambda: timezone.now() + timedelta(days=7)) @factory.post_generation def choices(self, create, extracted, **kwargs): if create and not extracted: ChoiceFactory.create_batch(5, question=self)
[ "miphreal@gmail.com" ]
miphreal@gmail.com
0d523cbadea58db5844fa5dd87a4eff41050d77b
aad164e4efe1d55cc189c35956bfd435b14a0f52
/eve-8.21.494548/lib/carbonstdlib/contextlib.py
9fd6320c1f1294c1aa557a4f38f9c87283acba88
[]
no_license
Pluckyduck/eve
61cc41fe8fd4dca4fbdcc4761a37bcfeb27ed84f
9a277707ab1f162c6bd9618faf722c0be3ea93ad
refs/heads/master
2020-12-28T23:35:29.992875
2013-05-06T14:24:33
2013-05-06T14:24:33
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,185
py
#Embedded file name: c:\depot\games\branches\release\EVE-TRANQUILITY\carbon\common\stdlib\contextlib.py import sys from functools import wraps from warnings import warn __all__ = ['contextmanager', 'nested', 'closing'] class GeneratorContextManager(object): def __init__(self, gen): self.gen = gen def __enter__(self): try: return self.gen.next() except StopIteration: raise RuntimeError("generator didn't yield") def __exit__(self, type, value, traceback): if type is None: try: self.gen.next() except StopIteration: return raise RuntimeError("generator didn't stop") else: if value is None: value = type() try: self.gen.throw(type, value, traceback) raise RuntimeError("generator didn't stop after throw()") except StopIteration as exc: return exc is not value except: if sys.exc_info()[1] is not value: raise def contextmanager(func): @wraps(func) def helper(*args, **kwds): return GeneratorContextManager(func(*args, **kwds)) return helper @contextmanager def nested(*managers): warn('With-statements now directly support multiple context managers', DeprecationWarning, 3) exits = [] vars = [] exc = (None, None, None) try: for mgr in managers: exit = mgr.__exit__ enter = mgr.__enter__ vars.append(enter()) exits.append(exit) yield vars except: exc = sys.exc_info() finally: while exits: exit = exits.pop() try: if exit(*exc): exc = (None, None, None) except: exc = sys.exc_info() if exc != (None, None, None): raise exc[0], exc[1], exc[2] class closing(object): def __init__(self, thing): self.thing = thing def __enter__(self): return self.thing def __exit__(self, *exc_info): self.thing.close()
[ "ferox2552@gmail.com" ]
ferox2552@gmail.com
f3c2f424721aba59acfd050755659e84ff609db8
759653bf8bd290e023d8f71a0cd5faa95c1687b0
/code/771.py
eba1126050396bc1573007cc45ac457e4b9518bf
[]
no_license
RuidongZ/LeetCode
6032fc02d3f996155c4f6965f2ad2fc48de6c3c2
ef8f9edd7857f4ef103924e21224dcd878c87196
refs/heads/master
2022-02-27T12:32:00.261851
2019-10-17T08:54:34
2019-10-17T08:54:34
115,314,228
4
1
null
null
null
null
UTF-8
Python
false
false
939
py
# -*- Encoding:UTF-8 -*- # 771. Jewels and Stones # You're given strings J representing the types of stones that are jewels, and S representing the stones you have. # Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels. # # The letters in J are guaranteed distinct, and all characters in J and S are letters. # Letters are case sensitive, so "a" is considered a different type of stone from "A". # # Example 1: # # Input: J = "aA", S = "aAAbbbb" # Output: 3 # Example 2: # # Input: J = "z", S = "ZZ" # Output: 0 # Note: # # S and J will consist of letters and have length at most 50. # The characters in J are distinct. class Solution(object): def numJewelsInStones(self, J, S): """ :type J: str :type S: str :rtype: int """ cnt = 0 for i in S: if i in J: cnt += 1 return cnt
[ "459597855@qq.com" ]
459597855@qq.com
cfea9560e5ec1f92438c4d1bfe85bfcbed0afd05
9d862dd68f8b4ea4e7de9397fef8592824c77449
/app/top/api/rest/WlbOrderCancelRequest.py
09660e9157ded1486da3eb9a863973538165a9b6
[]
no_license
hi-noikiy/tmall-sku-outer_id
ffaca630dfb288ca33d962b8a050932d1047b9c8
1bcf29386a513bcb210bf5d91016e0dcb1ebc1ad
refs/heads/master
2021-05-09T18:20:27.150316
2017-03-08T06:43:57
2017-03-08T06:43:57
null
0
0
null
null
null
null
UTF-8
Python
false
false
301
py
''' Created by auto_sdk on 2016.04.14 ''' from app.top.api.base import RestApi class WlbOrderCancelRequest(RestApi): def __init__(self,domain='gw.api.taobao.com',port=80): RestApi.__init__(self,domain, port) self.wlb_order_code = None def getapiname(self): return 'taobao.wlb.order.cancel'
[ "1037096435@qq.com" ]
1037096435@qq.com
40ca69a149cf8e465343e98e58f19e00a9b53ce6
33faef69c6ceb5944edae07d76175dafe8c7ec17
/web_robotframework/migrations/0014_auto_20181116_1501.py
df6c256eb6a1124c4a6d077221ffdc13cac5f18f
[]
no_license
waterfronter/AutoZone
86edfe45f8d92839f31d1e4608f13d309017fc8d
dec180c4aaa88dc015ff7ca1d8e75f1967062a6b
refs/heads/master
2020-06-11T07:25:59.439326
2019-06-06T09:02:42
2019-06-06T09:02:42
193,890,095
0
1
null
2019-06-26T11:19:39
2019-06-26T11:19:39
null
UTF-8
Python
false
false
454
py
# Generated by Django 2.1.1 on 2018-11-16 07:01 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('web_robotframework', '0013_auto_20181116_1452'), ] operations = [ migrations.AlterField( model_name='add_web_steps', name='webtestresult', field=models.CharField(default=None, max_length=50, verbose_name='测试结果'), ), ]
[ "1633235633@qq.com" ]
1633235633@qq.com
22e3d0ce7d47a5f3494e82146632cd45c24f84d9
6b699b7763a0ff8c32b85014d96f6faf02514a2e
/models/official/utils/logs/hooks_helper.py
f4f14492389a8885bf6deb8eeb607c1422e0548f
[ "Apache-2.0" ]
permissive
leizeling/Base_tensorflow-object_detection_2Dcord
df7c195685fed21fd456f1dd79881a198cf8b6e0
d07418eb68543adc2331211ccabbc27137c8676e
refs/heads/master
2020-03-19T11:51:57.961688
2018-06-07T14:47:16
2018-06-07T14:47:16
136,481,479
0
1
null
null
null
null
UTF-8
Python
false
false
5,802
py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Hooks helper to return a list of TensorFlow hooks for training by name. More hooks can be added to this set. To add a new hook, 1) add the new hook to the registry in HOOKS, 2) add a corresponding function that parses out necessary parameters. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf # pylint: disable=g-bad-import-order from official.utils.logs import hooks from official.utils.logs import logger from official.utils.logs import metric_hook _TENSORS_TO_LOG = dict((x, x) for x in ['learning_rate', 'cross_entropy', 'train_accuracy']) def get_train_hooks(name_list, **kwargs): """Factory for getting a list of TensorFlow hooks for training by name. Args: name_list: a list of strings to name desired hook classes. Allowed: LoggingTensorHook, ProfilerHook, ExamplesPerSecondHook, which are defined as keys in HOOKS **kwargs: a dictionary of arguments to the hooks. Returns: list of instantiated hooks, ready to be used in a classifier.train call. Raises: ValueError: if an unrecognized name is passed. """ if not name_list: return [] train_hooks = [] for name in name_list: hook_name = HOOKS.get(name.strip().lower()) if hook_name is None: raise ValueError('Unrecognized training hook requested: {}'.format(name)) else: train_hooks.append(hook_name(**kwargs)) return train_hooks def get_logging_tensor_hook(every_n_iter=100, tensors_to_log=None, **kwargs): # pylint: disable=unused-argument """Function to get LoggingTensorHook. Args: every_n_iter: `int`, print the values of `tensors` once every N local steps taken on the current worker. tensors_to_log: List of tensor names or dictionary mapping labels to tensor names. If not set, log _TENSORS_TO_LOG by default. **kwargs: a dictionary of arguments to LoggingTensorHook. Returns: Returns a LoggingTensorHook with a standard set of tensors that will be printed to stdout. """ if tensors_to_log is None: tensors_to_log = _TENSORS_TO_LOG return tf.train.LoggingTensorHook( tensors=tensors_to_log, every_n_iter=every_n_iter) def get_profiler_hook(save_steps=1000, **kwargs): # pylint: disable=unused-argument """Function to get ProfilerHook. Args: save_steps: `int`, print profile traces every N steps. **kwargs: a dictionary of arguments to ProfilerHook. Returns: Returns a ProfilerHook that writes out timelines that can be loaded into profiling tools like chrome://tracing. """ return tf.train.ProfilerHook(save_steps=save_steps) def get_examples_per_second_hook(every_n_steps=100, batch_size=128, warm_steps=5, **kwargs): # pylint: disable=unused-argument """Function to get ExamplesPerSecondHook. Args: every_n_steps: `int`, print current and average examples per second every N steps. batch_size: `int`, total batch size used to calculate examples/second from global time. warm_steps: skip this number of steps before logging and running average. **kwargs: a dictionary of arguments to ExamplesPerSecondHook. Returns: Returns a ProfilerHook that writes out timelines that can be loaded into profiling tools like chrome://tracing. """ return hooks.ExamplesPerSecondHook(every_n_steps=every_n_steps, batch_size=batch_size, warm_steps=warm_steps) def get_logging_metric_hook(benchmark_log_dir=None, tensors_to_log=None, every_n_secs=600, **kwargs): # pylint: disable=unused-argument """Function to get LoggingMetricHook. Args: benchmark_log_dir: `string`, directory path to save the metric log. tensors_to_log: List of tensor names or dictionary mapping labels to tensor names. If not set, log _TENSORS_TO_LOG by default. every_n_secs: `int`, the frequency for logging the metric. Default to every 10 mins. Returns: Returns a ProfilerHook that writes out timelines that can be loaded into profiling tools like chrome://tracing. """ logger.config_benchmark_logger(benchmark_log_dir) if tensors_to_log is None: tensors_to_log = _TENSORS_TO_LOG return metric_hook.LoggingMetricHook( tensors=tensors_to_log, metric_logger=logger.get_benchmark_logger(), every_n_secs=every_n_secs) # A dictionary to map one hook name and its corresponding function HOOKS = { 'loggingtensorhook': get_logging_tensor_hook, 'profilerhook': get_profiler_hook, 'examplespersecondhook': get_examples_per_second_hook, 'loggingmetrichook': get_logging_metric_hook, }
[ "1072113944@qq.comm" ]
1072113944@qq.comm
82f1aa278d2d713ff7e37345ceae2c185accee21
c074ce302e0a2a09ebe8b0a94e342380afbaa911
/beakjoon_PS/no17144.py
74a99479091ac9aefa711ffac7d15e85ca9d1f48
[]
no_license
elrion018/CS_study
eeea7a48e9e9b116ddf561ebf10633670d305722
3d5478620c4d23343ae0518d27920b3211f686fd
refs/heads/master
2021-06-10T13:35:20.258335
2021-04-25T10:12:17
2021-04-25T10:12:17
169,424,097
1
0
null
null
null
null
UTF-8
Python
false
false
3,424
py
import sys def four_way_spread(y,x, room, temp1, temp2): dy = [0,0,1,-1] dx = [1,-1,0,0] if room[y][x] > 0: for k in range(4): ay = y + dy[k] ax = x + dx[k] if ay >= 0 and ay <r and ax>=0 and ax <c and room[ay][ax] != -1: part = room[y][x] // 5 temp1[ay][ax] += part temp2[y][x] += part return room, temp1, temp2 def sum_dust(r,c,room, temp1,temp2): for y in range(r): for x in range(c): room[y][x] += temp1[y][x] room[y][x] -= temp2[y][x] return room def spread_dust(r,c,room): temp1 = [[0]*c for _ in range(r)] temp2 = [[0]*c for _ in range(r)] for y in range(r): for x in range(c): room, temp1, temp2 = four_way_spread(y,x, room, temp1, temp2) room = sum_dust(r,c, room, temp1, temp2) return room def wind_dust(r,c, room): cleaner_y = None for y in range(r): for x in range(c): if room[y][x] == -1: cleaner_y = y break area1 = room[0:cleaner_y] area2 = room[cleaner_y:] # area 1 (반시계 방향) area1 = wind_area1(area1,c) area2 = wind_area2(area2,c) return area1 + area2 # area 2 (시계 방향) def wind_area1(area1,c): temp = [[0]*c for _ in range(len(area1))] for y in range(len(area1)): for x in range(c): if y-1 < 0 and x-1 < 0: #왼쪽 상단 구석 temp[y+1][x] = area1[y][x] elif y-1 <0 and x +1 == c: #오른쪽 상단 구석 temp[y][x-1] = area1[y][x] elif y+1 == len(area1) and x -1 <0: # 왼쪽 하단 구석 temp[y][x+1] = area1[y][x] elif y+1 == len(area1) and x + 1 == c: # 오른쪽 하단 구석 temp[y-1][x] = area1[y][x] elif y-1 <0: temp[y][x-1] = area1[y][x] elif y+1 == len(area1): temp[y][x+1] = area1[y][x] elif x-1 <0: temp[y+1][x] = area1[y][x] elif x+1 == c: temp[y-1][x] = area1[y][x] else: temp[y][x] = area1[y][x] area1 = overwrite_area(temp, area1, c) return area1 def wind_area2(area2,c): temp = [[0]*c for _ in range(len(area2))] for y in range(len(area2)): for x in range(c): if y-1 < 0 and x-1 < 0: #왼쪽 상단 구석 temp[y][x+1] = area2[y][x] elif y-1 <0 and x +1 == c: #오른쪽 상단 구석 temp[y+1][x] = area2[y][x] elif y+1 == len(area2) and x -1 <0: # 왼쪽 하단 구석 temp[y-1][x] = area2[y][x] elif y+1 == len(area2) and x + 1 == c: # 오른쪽 하단 구석 temp[y][x-1] = area2[y][x] elif y-1 <0: temp[y][x+1] = area2[y][x] elif y+1 == len(area2): temp[y][x-1] = area2[y][x] elif x-1 <0: temp[y-1][x] = area2[y][x] elif x+1 == c: temp[y+1][x] = area2[y][x] else: temp[y][x] = area2[y][x] area2 = overwrite_area(temp, area2, c) return area2 def overwrite_area(temp, area,c): for y in range(len(area)): for x in range(c): if area[y][x] != -1: if temp[y][x] == -1: area[y][x] = 0 else: area[y][x] = temp[y][x] return area def get_answer(r,c, room): answer = 0 for y in range(r): for x in range(c): if room[y][x] != -1: answer += room[y][x] return answer def solution(r,c,t, room): for _ in range(t): room = spread_dust(r,c,room) room = wind_dust(r,c, room) return get_answer(r,c,room) r,c,t = map(int, sys.stdin.readline().split()) room = [list(map(int, sys.stdin.readline().split())) for _ in range(r)] print(solution(r,c,t, room))
[ "elrion018@gmail.com" ]
elrion018@gmail.com
1a0e35d230b3b14fdb921c31b726a5c7fe3ab471
4cf5b34118daa3c26a47c7213eaaa656b3ab57f0
/src/treeminer.py
2e40ad5b834c7f67b85145bdbe3f55bcbf42e320
[]
no_license
vrthra/Cmimid
a177b5dbd3ef69852b6746ee09a140f35cbc0580
25465201830b35a0338407b0a4e13ef512881731
refs/heads/master
2020-06-17T08:24:46.465783
2019-11-11T15:17:25
2019-11-11T15:17:25
195,860,435
0
1
null
2019-09-10T09:22:53
2019-07-08T17:49:25
Python
UTF-8
Python
false
false
6,808
py
import sys import json import itertools as it from operator import itemgetter from fuzzingbook.GrammarFuzzer import tree_to_string def reconstruct_method_tree(method_map): first_id = None tree_map = {} for key in method_map: m_id, m_name, m_children = method_map[key] children = [] if m_id in tree_map: # just update the name and children assert not tree_map[m_id] tree_map[m_id]['id'] = m_id tree_map[m_id]['name'] = m_name tree_map[m_id]['indexes'] = [] tree_map[m_id]['children'] = children else: assert first_id is None tree_map[m_id] = {'id': m_id, 'name': m_name, 'children': children, 'indexes': []} first_id = m_id for c in m_children: assert c not in tree_map val = {} tree_map[c] = val children.append(val) return first_id, tree_map def last_comparisons(comparisons): HEURISTIC = True last_cmp_only = {} last_idx = {} # get the last indexes compared in methods. # first, for each method, find the index that # was accessed in that method invocation last. for idx, char, mid in comparisons: if mid in last_idx: if idx > last_idx[mid]: last_idx[mid] = idx else: last_idx[mid] = idx # next, for each index, find the method that # accessed it last. for idx, char, mid in comparisons: if HEURISTIC: if idx in last_cmp_only: if last_cmp_only[idx] > mid: # do not clobber children unless it was the last character # for that child. if last_idx[mid] > idx: # if it was the last index, may be the child used it # as a boundary check. continue last_cmp_only[idx] = mid return last_cmp_only def attach_comparisons(method_tree, comparisons): for idx in comparisons: mid = comparisons[idx] method_tree[mid]['indexes'].append(idx) def to_node(idxes, my_str): assert len(idxes) == idxes[-1] - idxes[0] + 1 assert min(idxes) == idxes[0] assert max(idxes) == idxes[-1] return my_str[idxes[0]:idxes[-1] + 1], [], idxes[0], idxes[-1] def indexes_to_children(indexes, my_str): lst = [ list(map(itemgetter(1), g)) for k, g in it.groupby(enumerate(indexes), lambda x: x[0] - x[1]) ] return [to_node(n, my_str) for n in lst] def does_item_overlap(s, e, s_, e_): return (s_ >= s and s_ <= e) or (e_ >= s and e_ <= e) or (s_ <= s and e_ >= e) def is_second_item_included(s, e, s_, e_): return (s_ >= s and e_ <= e) def has_overlap(ranges, s_, e_): return {(s, e) for (s, e) in ranges if does_item_overlap(s, e, s_, e_)} def is_included(ranges, s_, e_): return {(s, e) for (s, e) in ranges if is_second_item_included(s, e, s_, e_)} def remove_overlap_from(original_node, orange): node, children, start, end = original_node new_children = [] if not children: return None start = -1 end = -1 for child in children: if does_item_overlap(*child[2:4], *orange): new_child = remove_overlap_from(child, orange) if new_child: # and new_child[1]: if start == -1: start = new_child[2] new_children.append(new_child) end = new_child[3] else: new_children.append(child) if start == -1: start = child[2] end = child[3] if not new_children: return None assert start != -1 assert end != -1 return (node, new_children, start, end) def no_overlap(arr): my_ranges = {} for a in arr: _, _, s, e = a included = is_included(my_ranges, s, e) if included: continue # we will fill up the blanks later. else: overlaps = has_overlap(my_ranges, s, e) if overlaps: # unlike include which can happen only once in a set of # non-overlapping ranges, overlaps can happen on multiple parts. # The rule is, the later child gets the say. So, we recursively # remove any ranges that overlap with the current one from the # overlapped range. # assert len(overlaps) == 1 #oitem = list(overlaps)[0] for oitem in overlaps: v = remove_overlap_from(my_ranges[oitem], (s,e)) del my_ranges[oitem] if v: my_ranges[v[2:4]] = v my_ranges[(s, e)] = a else: my_ranges[(s, e)] = a res = my_ranges.values() # assert no overlap, and order by starting index s = sorted(res, key=lambda x: x[2]) return s def to_tree(node, my_str): method_name = ("<%s>" % node['name']) if node['name'] is not None else '<START>' indexes = node['indexes'] node_children = [] for c in node.get('children', []): t = to_tree(c, my_str) if t is None: continue node_children.append(t) idx_children = indexes_to_children(indexes, my_str) children = no_overlap(node_children + idx_children) if not children: return None start_idx = children[0][2] end_idx = children[-1][3] si = start_idx my_children = [] # FILL IN chars that we did not compare. This is likely due to an i + n # instruction. for c in children: if c[2] != si: sbs = my_str[si: c[2]] my_children.append((sbs, [], si, c[2] - 1)) my_children.append(c) si = c[3] + 1 m = (method_name, my_children, start_idx, end_idx) return m import os.path, copy, random random.seed(0) def miner(call_traces): my_trees = [] for call_trace in call_traces: method_map = call_trace['method_map'] first, method_tree = reconstruct_method_tree(method_map) comparisons = call_trace['comparisons'] attach_comparisons(method_tree, last_comparisons(comparisons)) my_str = call_trace['inputstr'] #print("INPUT:", my_str, file=sys.stderr) tree = to_tree(method_tree[first], my_str) #print("RECONSTRUCTED INPUT:", tree_to_string(tree), file=sys.stderr) my_tree = {'tree': tree, 'original': call_trace['original'], 'arg': call_trace['arg']} assert tree_to_string(tree) == my_str my_trees.append(my_tree) return my_trees def main(tracefile): with open(tracefile) as f: my_trace = json.load(f) mined_trees = miner(my_trace) json.dump(mined_trees, sys.stdout) main(sys.argv[1])
[ "rahul@gopinath.org" ]
rahul@gopinath.org
810b7d95938ec105f9de7bc48d3eb11b3338bb3f
471ea669e21abdb4e4915610b4b5eb43ea3cffe9
/剑指Offer/27.字符串的排列.py
ca20aaf9bf80c69e0f52a5f8cce2ced8237e0549
[]
no_license
JiahuaLink/nowcoder-leetcode
26aed099e215cfc1d8e8afffc62fafa26b26b06f
0155fc33511cbe892f58550d561d3aa3efcd56b9
refs/heads/master
2023-07-09T03:05:31.227720
2021-08-03T06:50:36
2021-08-03T06:50:36
null
0
0
null
null
null
null
UTF-8
Python
false
false
224
py
# 使用迭代工具类的排列方法 import itertools class Solution: def Permutation(self, ss): if not ss: return [] return sorted(list(set(map(''.join, itertools.permutations(ss)))))
[ "noreply@github.com" ]
JiahuaLink.noreply@github.com