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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
14ebd393b7eb8046d3b0633dd9cde072d9aa2afe
|
6061ebee9fbce8eb5b48ed7ccd2aecb196156598
|
/modulo02-basico/desafios/desafio04.py
|
6b061eeeb1901a297582e79d7c39ea815235dd66
|
[] |
no_license
|
DarioCampagnaCoutinho/logica-programacao-python
|
fdc64871849bea5f5bbf2c342db5fda15778110b
|
b494bb6ef226c89f4bcfc66f964987046aba692d
|
refs/heads/master
| 2023-02-24T11:45:29.551278
| 2021-01-26T22:02:49
| 2021-01-26T22:02:49
| 271,899,650
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 167
|
py
|
import random
nome1 = 'Dario'
nome2 = 'Maria'
nome3 = 'Ana'
nome4 = 'José'
x = random.choice([nome1, nome2, nome3, nome4])
print('O escolhido foi = {} '.format(x))
|
[
"campagnacoutinho67@gmail.com"
] |
campagnacoutinho67@gmail.com
|
dea33f85af7f66f7636b976164a57c513d9e0b8c
|
59166105545cdd87626d15bf42e60a9ee1ef2413
|
/test/test_gaelic_games_player_api.py
|
652e74921fb7bba2124a47a636a082cc9d1127cd
|
[] |
no_license
|
mosoriob/dbpedia_api_client
|
8c594fc115ce75235315e890d55fbf6bd555fa85
|
8d6f0d04a3a30a82ce0e9277e4c9ce00ecd0c0cc
|
refs/heads/master
| 2022-11-20T01:42:33.481024
| 2020-05-12T23:22:54
| 2020-05-12T23:22:54
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,057
|
py
|
# coding: utf-8
"""
DBpedia
This is the API of the DBpedia Ontology # noqa: E501
The version of the OpenAPI document: v0.0.1
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unittest
import dbpedia
from dbpedia.api.gaelic_games_player_api import GaelicGamesPlayerApi # noqa: E501
from dbpedia.rest import ApiException
class TestGaelicGamesPlayerApi(unittest.TestCase):
"""GaelicGamesPlayerApi unit test stubs"""
def setUp(self):
self.api = dbpedia.api.gaelic_games_player_api.GaelicGamesPlayerApi() # noqa: E501
def tearDown(self):
pass
def test_gaelicgamesplayers_get(self):
"""Test case for gaelicgamesplayers_get
List all instances of GaelicGamesPlayer # noqa: E501
"""
pass
def test_gaelicgamesplayers_id_get(self):
"""Test case for gaelicgamesplayers_id_get
Get a single GaelicGamesPlayer by its id # noqa: E501
"""
pass
if __name__ == '__main__':
unittest.main()
|
[
"maxiosorio@gmail.com"
] |
maxiosorio@gmail.com
|
ca3562bb02d7bbdba2a3884a09cb3e1ef762c919
|
f76e11d4da15768bf8683380b1b1312f04060f9a
|
/sample_conlls_for_files_in_folder.py
|
a41592d79ee73224376e3b60857161c7a140304b
|
[] |
no_license
|
rasoolims/scripts
|
0804a2e5f7f405846cb659f9f8199f6bd93c4af6
|
fd8110558fff1bb5a7527ff854eeea87b0b3c597
|
refs/heads/master
| 2021-07-07T03:53:20.507765
| 2021-04-13T14:53:00
| 2021-04-13T14:53:00
| 24,770,177
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 364
|
py
|
import os,sys
sampler = os.path.dirname(os.path.abspath(sys.argv[0]))+'/sample_conlls.py'
folder = os.path.abspath(sys.argv[1])+'/'
o_folder = os.path.abspath(sys.argv[2])+'/'
max_num = int(sys.argv[3])
for f in sorted(os.listdir(folder)):
command = 'python ' + sampler + ' '+folder+f +' '+o_folder+f + ' '+str(max_num) + '&'
print command
os.system(command)
|
[
"rasooli.ms@gmail.com"
] |
rasooli.ms@gmail.com
|
2a12122d9d5b99a129dc3fa2a52bf6b57a7b4e4d
|
a8b2ab984cf02660efce5a7696cd3218d7023883
|
/python/598.range-addition-ii.py
|
a16fc8861d35c55faac849acfad8d6b4554fd525
|
[
"MIT"
] |
permissive
|
vermouth1992/Leetcode
|
b445f51de3540ef453fb594f04d5c9d9ad934c0c
|
386e794861f37c17cfea0c8baa3f544c8e5ca7a8
|
refs/heads/master
| 2022-11-07T13:04:00.393597
| 2022-10-28T02:59:22
| 2022-10-28T02:59:22
| 100,220,916
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,460
|
py
|
#
# @lc app=leetcode id=598 lang=python3
#
# [598] Range Addition II
#
# https://leetcode.com/problems/range-addition-ii/description/
#
# algorithms
# Easy (50.41%)
# Total Accepted: 47.5K
# Total Submissions: 94.3K
# Testcase Example: '3\n3\n[[2,2],[3,3]]'
#
# You are given an m x n matrix M initialized with all 0's and an array of
# operations ops, where ops[i] = [ai, bi] means M[x][y] should be incremented
# by one for all 0 <= x < ai and 0 <= y < bi.
#
# Count and return the number of maximum integers in the matrix after
# performing all the operations.
#
#
# Example 1:
#
#
# Input: m = 3, n = 3, ops = [[2,2],[3,3]]
# Output: 4
# Explanation: The maximum integer in M is 2, and there are four of it in M. So
# return 4.
#
#
# Example 2:
#
#
# Input: m = 3, n = 3, ops =
# [[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3]]
# Output: 4
#
#
# Example 3:
#
#
# Input: m = 3, n = 3, ops = []
# Output: 9
#
#
#
# Constraints:
#
#
# 1 <= m, n <= 4 * 10^4
# 1 <= ops.length <= 10^4
# ops[i].length == 2
# 1 <= ai <= m
# 1 <= bi <= n
#
#
#
from typing import List
class Solution:
def maxCount(self, m: int, n: int, ops: List[List[int]]) -> int:
# find min_x and min_y
min_x = m
min_y = n
for position in ops:
x, y = position
if x < min_x:
min_x = x
if y < min_y:
min_y = y
return min_x * min_y
|
[
"czhangseu@gmail.com"
] |
czhangseu@gmail.com
|
3a346913704674caee5c77cd75948fe136288495
|
375f29655b966e7dbac2297b3f79aadb5d03b737
|
/Image/Morphw.py
|
480c580be1281ed1523a76b52adc5b0beb2b5854
|
[
"MIT"
] |
permissive
|
pection-zz/FindJointwithImageprocessing
|
33e0b47ca3629d85e739edcd88dcd1663af88631
|
3dd4563be88dfcf005c32f19ae97d03f9bf715ad
|
refs/heads/master
| 2022-12-23T11:09:04.391591
| 2020-10-05T16:35:21
| 2020-10-05T16:35:21
| 301,473,183
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,051
|
py
|
import sys
# import urllib2
import cv2 as cv
src = 0
image = 0
dest = 0
element_shape = cv.CV_SHAPE_RECT
def Opening(pos):
element = cv.CreateStructuringElementEx(pos*2+1, pos*2+1, pos, pos, element_shape)
cv.Erode(src, image, element, 1)
cv.Dilate(image, dest, element, 1)
cv.ShowImage("Opening & Closing", dest)
def Closing(pos):
element = cv.CreateStructuringElementEx(pos*2+1, pos*2+1, pos, pos, element_shape)
cv.Dilate(src, image, element, 1)
cv.Erode(image, dest, element, 1)
cv.ShowImage("Opening & Closing", dest)
def Erosion(pos):
element = cv.CreateStructuringElementEx(pos*2+1, pos*2+1, pos, pos, element_shape)
cv.Erode(src, dest, element, 1)
cv.ShowImage("Erosion & Dilation", dest)
def Dilation(pos):
element = cv.CreateStructuringElementEx(pos*2+1, pos*2+1, pos, pos, element_shape)
cv.Dilate(src, dest, element, 1)
cv.ShowImage("Erosion & Dilation", dest)
if __name__ == "__main__":
if len(sys.argv) > 1:
src = cv.LoadImage(sys.argv[1], cv.CV_LOAD_IMAGE_COLOR)
else:
url = 'https://code.ros.org/svn/opencv/trunk/opencv/samples/c/fruits.jpg'
filedata = urllib2.urlopen(url).read()
imagefiledata = cv.CreateMatHeader(1, len(filedata), cv.CV_8UC1)
cv.SetData(imagefiledata, filedata, len(filedata))
src = cv.DecodeImage(imagefiledata, cv.CV_LOAD_IMAGE_COLOR)
image = cv.CloneImage(src)
dest = cv.CloneImage(src)
cv.NamedWindow("Opening & Closing", 1)
cv.NamedWindow("Erosion & Dilation", 1)
cv.ShowImage("Opening & Closing", src)
cv.ShowImage("Erosion & Dilation", src)
cv.CreateTrackbar("Open", "Opening & Closing", 0, 10, Opening)
cv.CreateTrackbar("Close", "Opening & Closing", 0, 10, Closing)
cv.CreateTrackbar("Dilate", "Erosion & Dilation", 0, 10, Dilation)
cv.CreateTrackbar("Erode", "Erosion & Dilation", 0, 10, Erosion)
cv.WaitKey(0)
cv.DestroyWindow("Opening & Closing")
cv.DestroyWindow("Erosion & Dilation")
|
[
"pection.naphat@gmail.com"
] |
pection.naphat@gmail.com
|
7537600bafe78ac26d429c8c02a71a336bd9f55a
|
63ace5832d453e325681d02f6496a0999b72edcb
|
/bip_utils/addr/ergo_addr.py
|
3866b51985ebe93e5c043e028807fdc3bf08fece
|
[
"MIT"
] |
permissive
|
ebellocchia/bip_utils
|
c9ec04c687f4247e57434319e36b2abab78f0b32
|
d15c75ddd74e4838c396a0d036ef6faf11b06a4b
|
refs/heads/master
| 2023-09-01T13:38:55.567370
| 2023-08-16T17:04:14
| 2023-08-16T17:04:14
| 251,130,186
| 244
| 88
|
MIT
| 2023-08-23T13:46:19
| 2020-03-29T20:42:48
|
Python
|
UTF-8
|
Python
| false
| false
| 6,215
|
py
|
# Copyright (c) 2022 Emanuele Bellocchia
#
# 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.
"""Module for Ergo address encoding/decoding."""
# Imports
from enum import IntEnum, unique
from typing import Any, Union
from bip_utils.addr.addr_dec_utils import AddrDecUtils
from bip_utils.addr.addr_key_validator import AddrKeyValidator
from bip_utils.addr.iaddr_decoder import IAddrDecoder
from bip_utils.addr.iaddr_encoder import IAddrEncoder
from bip_utils.base58 import Base58Decoder, Base58Encoder
from bip_utils.ecc import IPublicKey, Secp256k1PublicKey
from bip_utils.utils.crypto import Blake2b256
from bip_utils.utils.misc import IntegerUtils
@unique
class ErgoAddressTypes(IntEnum):
"""Enumerative for Ergo address types."""
P2PKH = 0x01
P2SH = 0x02
@unique
class ErgoNetworkTypes(IntEnum):
"""Enumerative for Ergo network types."""
MAINNET = 0x00
TESTNET = 0x10
class ErgoAddrConst:
"""Class container for Ergo address constants."""
# Checksum length in bytes
CHECKSUM_BYTE_LEN: int = 4
class _ErgoAddrUtils:
"""Ergo address utility class."""
@staticmethod
def ComputeChecksum(pub_key_bytes: bytes) -> bytes:
"""
Compute checksum in Ergo format.
Args:
pub_key_bytes (bytes): Public key bytes
Returns:
bytes: Computed checksum
"""
return Blake2b256.QuickDigest(pub_key_bytes)[:ErgoAddrConst.CHECKSUM_BYTE_LEN]
@staticmethod
def EncodePrefix(addr_type: ErgoAddressTypes,
net_type: ErgoNetworkTypes) -> bytes:
"""
Encode prefix.
Args:
addr_type (ErgoAddressTypes): Address type
net_type (ErgoNetworkTypes) : Network type
Returns:
bytes: Prefix byte
"""
return IntegerUtils.ToBytes(addr_type + net_type)
class ErgoP2PKHAddrDecoder(IAddrDecoder):
"""
Ergo P2PKH address decoder class.
It allows the Ergo P2PKH address decoding.
"""
@staticmethod
def DecodeAddr(addr: str,
**kwargs: Any) -> bytes:
"""
Decode an Ergo P2PKH address to bytes.
Args:
addr (str): Address string
Other Parameters:
net_type (ErgoNetworkTypes): Expected network type (default: main net)
Returns:
bytes: Public key bytes
Raises:
ValueError: If the address encoding is not valid
TypeError: If the network tag is not a ErgoNetworkTypes enum
"""
net_type = kwargs.get("net_type", ErgoNetworkTypes.MAINNET)
if not isinstance(net_type, ErgoNetworkTypes):
raise TypeError("Address type is not an enumerative of ErgoNetworkTypes")
# Decode from base58
addr_dec_bytes = Base58Decoder.Decode(addr)
# Validate length
AddrDecUtils.ValidateLength(addr_dec_bytes,
Secp256k1PublicKey.CompressedLength() + ErgoAddrConst.CHECKSUM_BYTE_LEN + 1)
# Get back checksum and public key bytes
addr_with_prefix, checksum_bytes = AddrDecUtils.SplitPartsByChecksum(addr_dec_bytes,
ErgoAddrConst.CHECKSUM_BYTE_LEN)
# Validate checksum
AddrDecUtils.ValidateChecksum(addr_with_prefix, checksum_bytes, _ErgoAddrUtils.ComputeChecksum)
# Validate and remove prefix
pub_key_bytes = AddrDecUtils.ValidateAndRemovePrefix(
addr_with_prefix,
_ErgoAddrUtils.EncodePrefix(ErgoAddressTypes.P2PKH, net_type)
)
# Validate public key
AddrDecUtils.ValidatePubKey(pub_key_bytes, Secp256k1PublicKey)
return pub_key_bytes
class ErgoP2PKHAddrEncoder(IAddrEncoder):
"""
Ergo P2PKH address encoder class.
It allows the Ergo P2PKH address encoding.
"""
@staticmethod
def EncodeKey(pub_key: Union[bytes, IPublicKey],
**kwargs: Any) -> str:
"""
Encode a public key to Ergo P2PKH address.
Args:
pub_key (bytes or IPublicKey): Public key bytes or object
Other Parameters:
net_type (ErgoNetworkTypes): Network type (default: main net)
Returns:
str: Address string
Raised:
ValueError: If the public key is not valid
TypeError: If the public key is not secp256k1 or the network tag is not a ErgoNetworkTypes enum
"""
net_type = kwargs.get("net_type", ErgoNetworkTypes.MAINNET)
if not isinstance(net_type, ErgoNetworkTypes):
raise TypeError("Address type is not an enumerative of ErgoNetworkTypes")
pub_key_obj = AddrKeyValidator.ValidateAndGetSecp256k1Key(pub_key)
pub_key_bytes = pub_key_obj.RawCompressed().ToBytes()
prefix_byte = _ErgoAddrUtils.EncodePrefix(ErgoAddressTypes.P2PKH, net_type)
addr_payload_bytes = prefix_byte + pub_key_bytes
return Base58Encoder.Encode(addr_payload_bytes + _ErgoAddrUtils.ComputeChecksum(addr_payload_bytes))
# Deprecated: only for compatibility, Encoder class shall be used instead
ErgoP2PKHAddr = ErgoP2PKHAddrEncoder
|
[
"54482000+ebellocchia@users.noreply.github.com"
] |
54482000+ebellocchia@users.noreply.github.com
|
71f2f3f6ab8c82d999fdc5604d74c6ca35798e00
|
a4df0ee67d0d56fc8595877470318aed20dd4511
|
/vplexapi-6.2.0.3/vplexapi/api/system_config_api.py
|
0cf62487a151978bcac867ff393426037a25be5b
|
[
"Apache-2.0"
] |
permissive
|
QD888/python-vplex
|
b5a7de6766840a205583165c88480d446778e529
|
e2c49faee3bfed343881c22e6595096c7f8d923d
|
refs/heads/main
| 2022-12-26T17:11:43.625308
| 2020-10-07T09:40:04
| 2020-10-07T09:40:04
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,577
|
py
|
# coding: utf-8
"""
VPlex REST API
A defnition for the next-gen VPlex API # noqa: E501
OpenAPI spec version: 0.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from vplexapi.api_client import ApiClient
class SystemConfigApi(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
def get_system_config(self, **kwargs): # noqa: E501
"""Return the system configuration # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_system_config(async=True)
>>> result = thread.get()
:param async bool
:return: SystemConfig
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return self.get_system_config_with_http_info(**kwargs) # noqa: E501
else:
(data) = self.get_system_config_with_http_info(**kwargs) # noqa: E501
return data
def get_system_config_with_http_info(self, **kwargs): # noqa: E501
"""Return the system configuration # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_system_config_with_http_info(async=True)
>>> result = thread.get()
:param async bool
:return: SystemConfig
If the method is called asynchronously,
returns the request thread.
"""
all_params = [] # noqa: E501
all_params.append('async')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_system_config" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# Authentication setting
auth_settings = ['basicAuth', 'jwtAuth'] # noqa: E501
return self.api_client.call_api(
'/system_config', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='SystemConfig', # noqa: E501
auth_settings=auth_settings,
async=params.get('async'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
|
[
"anil.degwekar@emc.com"
] |
anil.degwekar@emc.com
|
bbe80be9f9fff0ea613053c45361bc9ec7a96a24
|
abaa806550f6e6e7bcdf71b9ec23e09a85fe14fd
|
/data/global-configuration/packs/sshd/collectors/collector_sshd.py
|
c0b458e04e59a61fc4c9e68ec80c8eb193eddf40
|
[
"MIT"
] |
permissive
|
naparuba/opsbro
|
02809ddfe22964cd5983c60c1325c965e8b02adf
|
98618a002cd47250d21e7b877a24448fc95fec80
|
refs/heads/master
| 2023-04-16T08:29:31.143781
| 2019-05-15T12:56:11
| 2019-05-15T12:56:11
| 31,333,676
| 34
| 7
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 825
|
py
|
import os
from opsbro.collector import Collector
class Sshd(Collector):
def launch(self):
self.logger.debug('get_sshd: starting')
if not os.path.exists('/etc/ssh'):
self.set_not_eligible('There is no ssh server. Missing /etc/ssh directory.')
return
res = {}
if os.path.exists('/etc/ssh/ssh_host_rsa_key.pub'):
f = open('/etc/ssh/ssh_host_rsa_key.pub', 'r')
buf = f.read().strip()
f.close()
res['host_rsa_key_pub'] = buf.replace('ssh-rsa ', '')
if os.path.exists('/etc/ssh/ssh_host_dsa_key.pub'):
f = open('/etc/ssh/ssh_host_dsa_key.pub', 'r')
buf = f.read().strip()
f.close()
res['host_dsa_key_pub'] = buf.replace('ssh-dss ', '')
return res
|
[
"naparuba@gmail.com"
] |
naparuba@gmail.com
|
3262ca2157e7e55a7bc3b144133ddefce3b3e3a7
|
f07a42f652f46106dee4749277d41c302e2b7406
|
/Data Set/bug-fixing-5/44a9b167bda9654ce60588cf2dcee88e4bad831d-<test_apply_with_reduce_empty>-bug.py
|
2a11ec39a3f937351a774e71f7fba648b2061694
|
[] |
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
| 665
|
py
|
def test_apply_with_reduce_empty(self):
x = []
result = self.empty.apply(x.append, axis=1, result_type='expand')
assert_frame_equal(result, self.empty)
result = self.empty.apply(x.append, axis=1, result_type='reduce')
assert_series_equal(result, Series([], index=pd.Index([], dtype=object)))
empty_with_cols = DataFrame(columns=['a', 'b', 'c'])
result = empty_with_cols.apply(x.append, axis=1, result_type='expand')
assert_frame_equal(result, empty_with_cols)
result = empty_with_cols.apply(x.append, axis=1, result_type='reduce')
assert_series_equal(result, Series([], index=pd.Index([], dtype=object)))
assert (x == [])
|
[
"dg1732004@smail.nju.edu.cn"
] |
dg1732004@smail.nju.edu.cn
|
9ee850f579c896ce0e8288b66817cca063a7a3d0
|
c67f2d0677f8870bc1d970891bbe31345ea55ce2
|
/zippy/lib-python/3/tkinter/font.py
|
5425b060132a7f3319d4038b8185c548b23e4efa
|
[
"BSD-3-Clause"
] |
permissive
|
securesystemslab/zippy
|
a5a1ecf5c688504d8d16128ce901406ffd6f32c2
|
ff0e84ac99442c2c55fe1d285332cfd4e185e089
|
refs/heads/master
| 2022-07-05T23:45:36.330407
| 2018-07-10T22:17:32
| 2018-07-10T22:17:32
| 67,824,983
| 324
| 27
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 6,135
|
py
|
# Tkinter font wrapper
#
# written by Fredrik Lundh, February 1998
#
# FIXME: should add 'displayof' option where relevant (actual, families,
# measure, and metrics)
#
__version__ = "0.9"
import tkinter
# weight/slant
NORMAL = "normal"
ROMAN = "roman"
BOLD = "bold"
ITALIC = "italic"
def nametofont(name):
"""Given the name of a tk named font, returns a Font representation.
"""
return Font(name=name, exists=True)
class Font:
"""Represents a named font.
Constructor options are:
font -- font specifier (name, system font, or (family, size, style)-tuple)
name -- name to use for this font configuration (defaults to a unique name)
exists -- does a named font by this name already exist?
Creates a new named font if False, points to the existing font if True.
Raises _tkinter.TclError if the assertion is false.
the following are ignored if font is specified:
family -- font 'family', e.g. Courier, Times, Helvetica
size -- font size in points
weight -- font thickness: NORMAL, BOLD
slant -- font slant: ROMAN, ITALIC
underline -- font underlining: false (0), true (1)
overstrike -- font strikeout: false (0), true (1)
"""
def _set(self, kw):
options = []
for k, v in kw.items():
options.append("-"+k)
options.append(str(v))
return tuple(options)
def _get(self, args):
options = []
for k in args:
options.append("-"+k)
return tuple(options)
def _mkdict(self, args):
options = {}
for i in range(0, len(args), 2):
options[args[i][1:]] = args[i+1]
return options
def __init__(self, root=None, font=None, name=None, exists=False, **options):
if not root:
root = tkinter._default_root
if font:
# get actual settings corresponding to the given font
font = root.tk.splitlist(root.tk.call("font", "actual", font))
else:
font = self._set(options)
if not name:
name = "font" + str(id(self))
self.name = name
if exists:
self.delete_font = False
# confirm font exists
if self.name not in root.tk.call("font", "names"):
raise tkinter._tkinter.TclError(
"named font %s does not already exist" % (self.name,))
# if font config info supplied, apply it
if font:
root.tk.call("font", "configure", self.name, *font)
else:
# create new font (raises TclError if the font exists)
root.tk.call("font", "create", self.name, *font)
self.delete_font = True
# backlinks!
self._root = root
self._split = root.tk.splitlist
self._call = root.tk.call
def __str__(self):
return self.name
def __eq__(self, other):
return isinstance(other, Font) and self.name == other.name
def __getitem__(self, key):
return self.cget(key)
def __setitem__(self, key, value):
self.configure(**{key: value})
def __del__(self):
try:
if self.delete_font:
self._call("font", "delete", self.name)
except (KeyboardInterrupt, SystemExit):
raise
except Exception:
pass
def copy(self):
"Return a distinct copy of the current font"
return Font(self._root, **self.actual())
def actual(self, option=None):
"Return actual font attributes"
if option:
return self._call("font", "actual", self.name, "-"+option)
else:
return self._mkdict(
self._split(self._call("font", "actual", self.name))
)
def cget(self, option):
"Get font attribute"
return self._call("font", "config", self.name, "-"+option)
def config(self, **options):
"Modify font attributes"
if options:
self._call("font", "config", self.name,
*self._set(options))
else:
return self._mkdict(
self._split(self._call("font", "config", self.name))
)
configure = config
def measure(self, text):
"Return text width"
return int(self._call("font", "measure", self.name, text))
def metrics(self, *options):
"""Return font metrics.
For best performance, create a dummy widget
using this font before calling this method."""
if options:
return int(
self._call("font", "metrics", self.name, self._get(options))
)
else:
res = self._split(self._call("font", "metrics", self.name))
options = {}
for i in range(0, len(res), 2):
options[res[i][1:]] = int(res[i+1])
return options
def families(root=None):
"Get font families (as a tuple)"
if not root:
root = tkinter._default_root
return root.tk.splitlist(root.tk.call("font", "families"))
def names(root=None):
"Get names of defined fonts (as a tuple)"
if not root:
root = tkinter._default_root
return root.tk.splitlist(root.tk.call("font", "names"))
# --------------------------------------------------------------------
# test stuff
if __name__ == "__main__":
root = tkinter.Tk()
# create a font
f = Font(family="times", size=30, weight=NORMAL)
print(f.actual())
print(f.actual("family"))
print(f.actual("weight"))
print(f.config())
print(f.cget("family"))
print(f.cget("weight"))
print(names())
print(f.measure("hello"), f.metrics("linespace"))
print(f.metrics())
f = Font(font=("Courier", 20, "bold"))
print(f.measure("hello"), f.metrics("linespace"))
w = tkinter.Label(root, text="Hello, world", font=f)
w.pack()
w = tkinter.Button(root, text="Quit!", command=root.destroy)
w.pack()
fb = Font(font=w["font"]).copy()
fb.config(weight=BOLD)
w.config(font=fb)
tkinter.mainloop()
|
[
"thezhangwei@gmail.com"
] |
thezhangwei@gmail.com
|
d0676c8bf7212cd46f2beb1288e21d745b2f5132
|
dd3ee2babd81d7d37399fd92f637c5600661b408
|
/latest_changes/wagtail_hooks.py
|
b9b2ac9588fa27f8e9aa842568a27b12208540e4
|
[] |
no_license
|
andsimakov/wagtail-latest-changes
|
2dc65f6e8212f02be51e3da957ce8804b08054f7
|
055004fd1e8fa65558bf030e258b82ec7891999c
|
refs/heads/master
| 2022-06-17T22:01:05.821551
| 2020-05-08T10:47:39
| 2020-05-08T10:47:39
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 810
|
py
|
from django.http import HttpResponse
from django.conf.urls import url
from django.urls import reverse
from wagtail.admin.menu import MenuItem
from wagtail.core import hooks
from wagtail.core.models import UserPagePermissionsProxy
from .views import LatestChangesView
@hooks.register('register_admin_urls')
def urlconf_time():
return [
url(r'^latest_changes/$', LatestChangesView.as_view(), name='latest_changes'),
]
class LatestChangesPagesMenuItem(MenuItem):
def is_shown(self, request):
return UserPagePermissionsProxy(request.user).can_remove_locks()
@hooks.register("register_reports_menu_item")
def register_latest_changes_menu_item():
return LatestChangesPagesMenuItem(
"Latest changes", reverse("latest_changes"), classnames="icon icon-date", order=100,
)
|
[
"spapas@gmail.com"
] |
spapas@gmail.com
|
9c0b5755bd03830f93fded39f854b1e51d9fe91e
|
50015e72ea35113ad40e13cb36c85116b0048aa9
|
/shop_paypal/modifiers.py
|
12daf8625068c27aa5c5550745293b3cf29d2b51
|
[
"MIT"
] |
permissive
|
haricot/djangoshop-paypal
|
30085baf75d7712aa1b4c39eba7256d9b0f39ef5
|
f1c381b4a64201029dcfe60af6e0243dc43fe50c
|
refs/heads/master
| 2020-12-20T12:18:17.495255
| 2020-01-10T22:29:43
| 2020-01-10T22:29:43
| 236,073,186
| 0
| 1
|
MIT
| 2020-01-24T19:54:41
| 2020-01-24T19:54:40
| null |
UTF-8
|
Python
| false
| false
| 1,240
|
py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from shop.payment.modifiers import PaymentModifier as PaymentModifierBase
from .payment import PayPalPayment
class PaymentModifier(PaymentModifierBase):
"""
Cart modifier which handles payment through PayPal.
"""
payment_provider = PayPalPayment()
commision_percentage = None
def get_choice(self):
return (self.identifier, "PayPal")
def is_disabled(self, cart):
return cart.total == 0
def add_extra_cart_row(self, cart, request):
from decimal import Decimal
from shop.serializers.cart import ExtraCartRow
if not self.is_active(cart) or not self.commision_percentage:
return
amount = cart.total * Decimal(self.commision_percentage / 100.0)
instance = {'label': _("plus {}% handling fees").format(self.commision_percentage), 'amount': amount}
cart.extra_rows[self.identifier] = ExtraCartRow(instance)
cart.total += amount
def update_render_context(self, context):
super(PaymentModifier, self).update_render_context(context)
context['payment_modifiers']['paypal_payment'] = True
|
[
"jacob.rief@gmail.com"
] |
jacob.rief@gmail.com
|
b326be0d3157e8e4c6291097ba566e5d4d202d38
|
0247690e0b33e919c8611f6feef37867052bbf51
|
/mayan/apps/events/classes.py
|
7c34b0368df856fcc39496b4c7ed1f8016eb9b45
|
[
"Apache-2.0",
"BSD-3-Clause"
] |
permissive
|
tobennanwokike/mayan-edms
|
2a499daf9ceb5d9a41c71270135fe652ad304ce1
|
89c145adde90eef849903907394b1c79e88470fd
|
refs/heads/master
| 2020-03-28T00:22:12.704262
| 2018-08-17T08:52:12
| 2018-08-17T08:52:12
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 7,928
|
py
|
from __future__ import unicode_literals
import logging
from django.apps import apps
from django.contrib.auth import get_user_model
from django.core.exceptions import PermissionDenied
from django.utils.encoding import force_text, python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from actstream import action
from .permissions import permission_events_view
logger = logging.getLogger(__name__)
@python_2_unicode_compatible
class EventTypeNamespace(object):
_registry = {}
@classmethod
def all(cls):
return sorted(cls._registry.values())
@classmethod
def get(cls, name):
return cls._registry[name]
def __init__(self, name, label):
self.name = name
self.label = label
self.event_types = []
self.__class__._registry[name] = self
def __str__(self):
return force_text(self.label)
def add_event_type(self, name, label):
event_type = EventType(namespace=self, name=name, label=label)
self.event_types.append(event_type)
return event_type
def get_event_types(self):
return EventType.sort(event_type_list=self.event_types)
@python_2_unicode_compatible
class EventType(object):
_registry = {}
@staticmethod
def sort(event_type_list):
return sorted(
event_type_list, key=lambda x: (x.namespace.label, x.label)
)
@classmethod
def all(cls):
# Return sorted permisions by namespace.name
return EventType.sort(event_type_list=cls._registry.values())
@classmethod
def get(cls, name):
try:
return cls._registry[name]
except KeyError:
return _('Unknown or obsolete event type: %s') % name
@classmethod
def refresh(cls):
for event_type in cls.all():
event_type.get_stored_event_type()
def __init__(self, namespace, name, label):
self.namespace = namespace
self.name = name
self.label = label
self.stored_event_type = None
self.__class__._registry[self.id] = self
def __str__(self):
return force_text('{}: {}'.format(self.namespace.label, self.label))
def commit(self, actor=None, action_object=None, target=None):
AccessControlList = apps.get_model(
app_label='acls', model_name='AccessControlList'
)
Action = apps.get_model(
app_label='actstream', model_name='Action'
)
ContentType = apps.get_model(
app_label='contenttypes', model_name='ContentType'
)
Notification = apps.get_model(
app_label='events', model_name='Notification'
)
results = action.send(
actor or target, actor=actor, verb=self.id,
action_object=action_object, target=target
)
for handler, result in results:
if isinstance(result, Action):
for user in get_user_model().objects.all():
notification = None
if user.event_subscriptions.filter(stored_event_type__name=result.verb).exists():
if result.target:
try:
AccessControlList.objects.check_access(
permissions=permission_events_view,
user=user, obj=result.target
)
except PermissionDenied:
pass
else:
notification, created = Notification.objects.get_or_create(
action=result, user=user
)
else:
notification, created = Notification.objects.get_or_create(
action=result, user=user
)
if result.target:
content_type = ContentType.objects.get_for_model(model=result.target)
relationship = user.object_subscriptions.filter(
content_type=content_type,
object_id=result.target.pk,
stored_event_type__name=result.verb
)
if relationship.exists():
try:
AccessControlList.objects.check_access(
permissions=permission_events_view,
user=user, obj=result.target
)
except PermissionDenied:
pass
else:
notification, created = Notification.objects.get_or_create(
action=result, user=user
)
if not notification and result.action_object:
content_type = ContentType.objects.get_for_model(model=result.action_object)
relationship = user.object_subscriptions.filter(
content_type=content_type,
object_id=result.action_object.pk,
stored_event_type__name=result.verb
)
if relationship.exists():
try:
AccessControlList.objects.check_access(
permissions=permission_events_view,
user=user, obj=result.action_object
)
except PermissionDenied:
pass
else:
notification, created = Notification.objects.get_or_create(
action=result, user=user
)
def get_stored_event_type(self):
if not self.stored_event_type:
StoredEventType = apps.get_model('events', 'StoredEventType')
self.stored_event_type, created = StoredEventType.objects.get_or_create(
name=self.id
)
return self.stored_event_type
@property
def id(self):
return '%s.%s' % (self.namespace.name, self.name)
class ModelEventType(object):
"""
Class to allow matching a model to a specific set of events.
"""
_inheritances = {}
_proxies = {}
_registry = {}
@classmethod
def get_for_class(cls, klass):
return cls._registry.get(klass, ())
@classmethod
def get_for_instance(cls, instance):
StoredEventType = apps.get_model(
app_label='events', model_name='StoredEventType'
)
events = []
class_events = cls._registry.get(type(instance))
if class_events:
events.extend(class_events)
proxy = cls._proxies.get(type(instance))
if proxy:
events.extend(cls._registry.get(proxy))
pks = [
event.id for event in set(events)
]
return EventType.sort(
event_type_list=StoredEventType.objects.filter(name__in=pks)
)
@classmethod
def get_inheritance(cls, model):
return cls._inheritances[model]
@classmethod
def register(cls, model, event_types):
cls._registry.setdefault(model, [])
for event_type in event_types:
cls._registry[model].append(event_type)
@classmethod
def register_inheritance(cls, model, related):
cls._inheritances[model] = related
@classmethod
def register_proxy(cls, source, model):
cls._proxies[model] = source
|
[
"roberto.rosario.gonzalez@gmail.com"
] |
roberto.rosario.gonzalez@gmail.com
|
3c63fe02ede7587da3872d2f6648382246af942d
|
09fafd03fc39cb890b57f143285925a48d114318
|
/tool_angle/DynamixelSDK/python/tests/protocol2_0/read_write.py
|
345cc047828cda6bc773f29f448adc7eb29f2018
|
[
"BSD-3-Clause",
"Apache-2.0"
] |
permissive
|
SamKaiYang/robot_control_hiwin_ros
|
83914e1af44da69631b079ad5eeff4bd49e6abc9
|
50457391013b4cad90b932ffc5afa078f00da7bb
|
refs/heads/master
| 2023-08-17T03:21:57.466251
| 2021-09-18T06:32:30
| 2021-09-18T06:32:30
| 292,339,605
| 1
| 2
|
BSD-3-Clause
| 2020-09-22T17:04:20
| 2020-09-02T16:45:12
|
Python
|
UTF-8
|
Python
| false
| false
| 5,851
|
py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################################################
# Copyright 2017 ROBOTIS CO., LTD.
#
# 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.
################################################################################
# Author: Ryu Woon Jung (Leon)
#
# ********* Read and Write Example *********
#
#
# Available Dynamixel model on this example : All models using Protocol 2.0
# This example is designed for using a Dynamixel PRO 54-200, and an USB2DYNAMIXEL.
# To use another Dynamixel model, such as X series, see their details in E-Manual(emanual.robotis.com) and edit below variables yourself.
# Be sure that Dynamixel PRO properties are already set as %% ID : 1 / Baudnum : 1 (Baudrate : 57600)
#
import os
if os.name == 'nt':
import msvcrt
def getch():
return msvcrt.getch().decode()
else:
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
def getch():
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
from dynamixel_sdk import * # Uses Dynamixel SDK library
# Control table address
ADDR_PRO_TORQUE_ENABLE = 64 # Control table address is different in Dynamixel model
ADDR_PRO_GOAL_POSITION = 116
ADDR_PRO_PRESENT_POSITION = 132
# Protocol version
PROTOCOL_VERSION = 2.0 # See which protocol version is used in the Dynamixel
# Default setting
DXL_ID = 1 # Dynamixel ID : 1
BAUDRATE = 57600 # Dynamixel default baudrate : 57600
DEVICENAME = '/dev/ttyUSB0' # Check which port is being used on your controller
# ex) Windows: "COM1" Linux: "/dev/ttyUSB0" Mac: "/dev/tty.usbserial-*"
TORQUE_ENABLE = 1 # Value for enabling the torque
TORQUE_DISABLE = 0 # Value for disabling the torque
DXL_MINIMUM_POSITION_VALUE = 10 # Dynamixel will rotate between this value
DXL_MAXIMUM_POSITION_VALUE = 4000 # and this value (note that the Dynamixel would not move when the position value is out of movable range. Check e-manual about the range of the Dynamixel you use.)
DXL_MOVING_STATUS_THRESHOLD = 20 # Dynamixel moving status threshold
index = 0
dxl_goal_position = [DXL_MINIMUM_POSITION_VALUE, DXL_MAXIMUM_POSITION_VALUE] # Goal position
# Initialize PortHandler instance
# Set the port path
# Get methods and members of PortHandlerLinux or PortHandlerWindows
portHandler = PortHandler(DEVICENAME)
# Initialize PacketHandler instance
# Set the protocol version
# Get methods and members of Protocol1PacketHandler or Protocol2PacketHandler
packetHandler = PacketHandler(PROTOCOL_VERSION)
# Open port
if portHandler.openPort():
print("Succeeded to open the port")
else:
print("Failed to open the port")
print("Press any key to terminate...")
getch()
quit()
# Set port baudrate
if portHandler.setBaudRate(BAUDRATE):
print("Succeeded to change the baudrate")
else:
print("Failed to change the baudrate")
print("Press any key to terminate...")
getch()
quit()
# Enable Dynamixel Torque
dxl_comm_result, dxl_error = packetHandler.write1ByteTxRx(portHandler, DXL_ID, ADDR_PRO_TORQUE_ENABLE, TORQUE_ENABLE)
if dxl_comm_result != COMM_SUCCESS:
print("%s" % packetHandler.getTxRxResult(dxl_comm_result))
elif dxl_error != 0:
print("%s" % packetHandler.getRxPacketError(dxl_error))
else:
print("Dynamixel has been successfully connected")
while 1:
print("Press any key to continue! (or press ESC to quit!)")
if getch() == chr(0x1b):
break
# Write goal position
dxl_comm_result, dxl_error = packetHandler.write4ByteTxRx(portHandler, DXL_ID, ADDR_PRO_GOAL_POSITION, dxl_goal_position[index])
if dxl_comm_result != COMM_SUCCESS:
print("%s" % packetHandler.getTxRxResult(dxl_comm_result))
elif dxl_error != 0:
print("%s" % packetHandler.getRxPacketError(dxl_error))
while 1:
# Read present position
dxl_present_position, dxl_comm_result, dxl_error = packetHandler.read4ByteTxRx(portHandler, DXL_ID, ADDR_PRO_PRESENT_POSITION)
if dxl_comm_result != COMM_SUCCESS:
print("%s" % packetHandler.getTxRxResult(dxl_comm_result))
elif dxl_error != 0:
print("%s" % packetHandler.getRxPacketError(dxl_error))
print("[ID:%03d] GoalPos:%03d PresPos:%03d" % (DXL_ID, dxl_goal_position[index], dxl_present_position))
if not abs(dxl_goal_position[index] - dxl_present_position) > DXL_MOVING_STATUS_THRESHOLD:
break
# Change goal position
if index == 0:
index = 1
else:
index = 0
# Disable Dynamixel Torque
dxl_comm_result, dxl_error = packetHandler.write1ByteTxRx(portHandler, DXL_ID, ADDR_PRO_TORQUE_ENABLE, TORQUE_DISABLE)
if dxl_comm_result != COMM_SUCCESS:
print("%s" % packetHandler.getTxRxResult(dxl_comm_result))
elif dxl_error != 0:
print("%s" % packetHandler.getRxPacketError(dxl_error))
# Close port
portHandler.closePort()
|
[
"tt00621212@gmail.com"
] |
tt00621212@gmail.com
|
351daf0695f3655bb2f5c218f0f16aa10b92f746
|
159a527d5333f848fa58fed8c39ee6303a507c62
|
/RPi_Drone/simpleCali.py
|
1c52e69d2795f1f083679fe9fbd2b707efe1af8c
|
[] |
no_license
|
GitDubs/Pi_Drone
|
ca3f15f4e33797dd276f8b39c6ac62186ace8d10
|
d3bf8817ce12cd6483128b7dd233a7e132b6e2e9
|
refs/heads/master
| 2020-04-15T19:56:46.744054
| 2020-03-24T16:02:14
| 2020-03-24T16:02:14
| 164,971,308
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 455
|
py
|
import pigpio
import time
import os
import atexit
def exit_handler():
pi.set_servo_pulsewidth(ESC, 0)
ESC = 18
pi = pigpio.pi();
pi.set_servo_pulsewidth(ESC, 0)
max_value = 2500
min_value = 1400
pi.set_servo_pulsewidth(ESC, max_value)
print "connect battery"
input = raw_input()
pi.set_servo_pulsewidth(ESC, min_value)
time.sleep(5)
pi.set_servo_pulsewidth(ESC, 1800)
print "press enter to stop"
input = raw_input()
atexit.register(exit_handler)
|
[
"user.email"
] |
user.email
|
45b45006fa8d12f989dc183ab1e0f50b4e2d9667
|
3032a58254a0d61403cc75476438bf60a119c2ea
|
/ADB Scripts/GMLAB Scripts/GM9 Pro/Functional/GPSGoogleMap.py
|
7d7bc345cf7bbd1792137326ec544a1abf74c86b
|
[] |
no_license
|
anithamini/useful-info
|
1e05528d61609ca4249920e41c88957ed1476fd7
|
a393db8d8e727d29d185d75f7920e21770a39e70
|
refs/heads/master
| 2020-04-14T15:42:06.627213
| 2019-01-03T07:02:16
| 2019-01-03T07:02:16
| 163,935,084
| 2
| 3
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,142
|
py
|
import os
import re
from time import sleep
def GPS_ON():
print("Enabling GPS.........")
os.system("adb shell settings put secure location_providers_allowed +gps")
def GPS_OFF():
print("Disabling GPS.........")
os.system("adb shell settings put secure location_providers_allowed -gps")
def kill_map():
print("Closing the GoogleMaps Application.......")
os.system("adb shell am force-stop com.google.android.apps.maps")
sleep(1)
def Google_map_launch():
print("Launching the GoogleMaps Application.......")
os.system("adb shell am start -n com.google.android.apps.maps/com.google.android.maps.MapsActivity")
def search_location():
os.system("adb shell input tap 349 109")
sleep(2)
os.system("adb shell input text 'waverock SEZ'")
os.system("adb shell input keyevent 66")
def sim_test():
os.system("adb shell getprop >gsm.txt ")
with open("gsm.txt","r+") as fh:
lines=fh.readlines()
for line in lines:
#print(line)
string1="[gsm.sim.state]: [READY,READY]"
string2 = "[gsm.sim.state]: [READY,NOT_READY]"
string3 = "[gsm.sim.state]: [NOT_READY,READY]"
string4 = "[gsm.sim.state]: [ABSENT,READY]"
string5 = "[gsm.sim.state]: [READY,ABSENT]"
if (string1 in line or string2 in line or string3 in line or string4 in line or string5 in line):
print("Sim present, so procedding the test")
return 1
else:
print("sim not present, please insert the sim and start the test")
return 0
def switch_mobiledata():
print("Enabling the MobileData")
os.system("adb shell svc data enable")
sleep(3)
def mobiledata_off():
print("Disabling the MobileData")
os.system("adb shell svc data disable")
sleep(1)
def validation():
os.system("adb shell dumpsys location>text.txt")
str1="mStarted=false"
with open("text.txt","r") as fd:
buf=fd.read()
if(re.search(str1,buf,re.I)):
return(True)
else:
return(False)
def checkmobiledata():
os.system("adb shell getprop>mobiledata.txt")
fp=open("mobiledata.txt","r+")
buff=fp.read()
str1="[gsm.defaultpdpcontext.active]: [true]"
if str1 in buff:
print(str1)
return 1
else:
return 0
res=sim_test()
if res:
print("sim is present")
switch_mobiledata()
pre=checkmobiledata()
if pre:
print("mobile data on")
sleep(2)
if(validation()):
print("GPS is disabled.....So enabling GPS now")
GPS_ON()
sleep(3)
kill_map()
Google_map_launch()
sleep(2)
search_location()
sleep(3)
kill_map()
mobiledata_off()
GPS_OFF()
|
[
"akesiboyina@innominds.com"
] |
akesiboyina@innominds.com
|
b1ff178eefe0307fd51681e85df4fbbba93522bc
|
9743d5fd24822f79c156ad112229e25adb9ed6f6
|
/xai/brain/wordbase/otherforms/_freshening.py
|
4611789aff9058da179cb60091496dbac47b7753
|
[
"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
| 230
|
py
|
#calss header
class _FRESHENING():
def __init__(self,):
self.name = "FRESHENING"
self.definitions = freshen
self.parents = []
self.childen = []
self.properties = []
self.jsondata = {}
self.basic = ['freshen']
|
[
"xingwang1991@gmail.com"
] |
xingwang1991@gmail.com
|
2de021e9e85df16452f8d08a2931aff200c9ce8a
|
e7a3961e94ffce63f02a3d5bb92b5850005c7955
|
/django_tuts/forms_tuts/models.py
|
4eca909a170d97954cf1c7b64b0d370e80410ad5
|
[] |
no_license
|
sbhusal123/django-collections
|
219c032c97dd7bc2b3c5961f71fb8da5e4826ec1
|
4efed68d29fd1e383d15b303584fc4eb183aff98
|
refs/heads/master
| 2022-11-06T17:32:25.776023
| 2020-06-20T07:58:54
| 2020-06-20T07:58:54
| 273,394,086
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,007
|
py
|
from _datetime import datetime
from django.db import models
from django.contrib.auth import get_user_model
User = get_user_model()
class Products(models.Model):
"""Products for sale"""
name = models.CharField(max_length=256, unique=True, null=False, blank=False)
price = models.DecimalField(max_digits=8, decimal_places=2)
def __str__(self):
return f'{self.name}: {self.price}'
class OrderItem(models.Model):
"""Item collection in an order"""
product = models.ForeignKey(Products, on_delete=models.CASCADE)
quantity = models.IntegerField(default=1, blank=False, null=False) # validate such that no less than 3
class Order(models.Model):
"""Order information"""
items = models.ManyToManyField('OrderItem')
date = models.DateTimeField(default=datetime.now, blank=False) # validate such that not yesterday
total = models.DecimalField(max_digits=8, decimal_places=2)
user = models.ForeignKey(User, related_name='orders', on_delete=models.CASCADE)
|
[
"suryabhusal11@gmail.com"
] |
suryabhusal11@gmail.com
|
467159dbc7962cddb1433df59cdc1a26132ca3af
|
9743d5fd24822f79c156ad112229e25adb9ed6f6
|
/xai/brain/wordbase/adjectives/_waxiest.py
|
ed828779dd11c8bd004322d280f17905dcb1f528
|
[
"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
| 238
|
py
|
from xai.brain.wordbase.adjectives._waxy import _WAXY
#calss header
class _WAXIEST(_WAXY, ):
def __init__(self,):
_WAXY.__init__(self)
self.name = "WAXIEST"
self.specie = 'adjectives'
self.basic = "waxy"
self.jsondata = {}
|
[
"xingwang1991@gmail.com"
] |
xingwang1991@gmail.com
|
60d734472901344d763d6e229ca2310ce9e90063
|
714cbe0205a4af7b8386116854c1eb85b63fb74d
|
/base.py
|
c506f9f1f78873528074a0dcd48211ca9c54dd1f
|
[] |
no_license
|
hologerry/lincoln
|
8ff7eb0b1ffe6b3792c8908e9db3adbe59e3ce22
|
e3144d949c7e2e85075a2211c1f49bcf40d5b5b2
|
refs/heads/master
| 2021-02-05T19:10:40.708747
| 2020-03-02T16:24:16
| 2020-03-02T16:24:16
| 243,821,199
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,342
|
py
|
from numpy import ndarray
from utils.np_utils import assert_same_shape
class Operation(object):
def __init__(self):
pass
def forward(self,
input_: ndarray,
inference: bool = False) -> ndarray:
self.input_ = input_
self.output = self._output(inference)
return self.output
def backward(self, output_grad: ndarray) -> ndarray:
assert_same_shape(self.output, output_grad)
self.input_grad = self._input_grad(output_grad)
assert_same_shape(self.input_, self.input_grad)
return self.input_grad
def _output(self, inference: bool) -> ndarray:
raise NotImplementedError()
def _input_grad(self, output_grad: ndarray) -> ndarray:
raise NotImplementedError()
class ParamOperation(Operation):
def __init__(self, param: ndarray) -> ndarray:
super().__init__()
self.param = param
def backward(self, output_grad: ndarray) -> ndarray:
assert_same_shape(self.output, output_grad)
self.input_grad = self._input_grad(output_grad)
self.param_grad = self._param_grad(output_grad)
assert_same_shape(self.input_, self.input_grad)
return self.input_grad
def _param_grad(self, output_grad: ndarray) -> ndarray:
raise NotImplementedError()
|
[
"hologerry@gmail.com"
] |
hologerry@gmail.com
|
1b0636fcd3958c905c9dc3f2ad157ad20a18c1c8
|
029aa4fa6217dbb239037dec8f2e64f5b94795d0
|
/Python算法指南/集合、列表、字符串/38_两数之和I_两数之和的应用_背.py
|
9f582ae4669e34cd92b44ea088f6f44037c21e74
|
[] |
no_license
|
tonyyo/algorithm
|
5a3f0bd4395a75703f9ee84b01e42a74283a5de9
|
60dd5281e7ce4dfb603b795aa194a67ff867caf6
|
refs/heads/master
| 2022-12-14T16:04:46.723771
| 2020-09-23T06:59:33
| 2020-09-23T06:59:33
| 270,216,530
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 857
|
py
|
class Solution(object):
def twoSum(self, nums, target):
hash = {0: 1}
size = len(nums)
ans = []
for j in range(size):
if target - nums[j] in hash:
ans.append([hash[target - nums[j]], j])
hash[nums[j]] = j
return ans
def twoSum2(self, nums, target):
hash = {} # hash映射
ans = [] # 存储所有可能结果值
for i in range(len(nums)):
if target - nums[i] in hash:
ans.append([hash[target - nums[i]], i])
hash[nums[i]] = i
return ans
if __name__ == '__main__':
temp = Solution()
List = [5, 4, 3, 4, 11]
nums = 8
print(("输入:" + str(List) + " " + str(nums)))
print(("输出:" + str(temp.twoSum(List, nums))))
print(("输出:" + str(temp.twoSum2(List, nums))))
|
[
"1325338208@qq.com"
] |
1325338208@qq.com
|
e398266ec2bb991e101560d67092ff805b861f66
|
af4761b401ecec831ff42344a33cc1e85996eb64
|
/freq.py
|
6f1636fff4abfdfd953c32d3ee2924b86d831e62
|
[
"MIT"
] |
permissive
|
rayjustinhuang/BitesofPy
|
70aa0bb8fdbffa87810f00210b4cea78211db8cf
|
e5738f4f685bad4c8fb140cbc057faa441d4b34c
|
refs/heads/master
| 2022-08-15T05:02:19.084123
| 2022-08-09T12:26:42
| 2022-08-09T12:26:42
| 219,509,496
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 129
|
py
|
from collections import Counter
def freq_digit(num: int) -> int:
return int(Counter(str(num)).most_common(1)[0][0])
pass
|
[
"rayjustinhuang@gmail.com"
] |
rayjustinhuang@gmail.com
|
5088f6b3f2353635f7d058f8bacc384981913b52
|
5955ea34fd72c719f3cb78fbb3c7e802a2d9109a
|
/MATRIX/Trivial/trivia1.py
|
f67af7e92614c8d5539f7d8a23712859516740da
|
[] |
no_license
|
AndreySperansky/TUITION
|
3c90ac45f11c70dce04008adc1e9f9faad840b90
|
583d3a760d1f622689f6f4f482c905b065d6c732
|
refs/heads/master
| 2022-12-21T21:48:21.936988
| 2020-09-28T23:18:40
| 2020-09-28T23:18:40
| 299,452,924
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 181
|
py
|
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(matrix[1])
print(matrix[1][1])
print(matrix[2][0])
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
print(matrix[1][1])
|
[
"andrey.speransky@gmail.com"
] |
andrey.speransky@gmail.com
|
8ecbc754fb7b5d7fc3b127f5aba3afc90fec38bd
|
55ceefc747e19cdf853e329dba06723a44a42623
|
/_CodeTopics/LeetCode/401-600/000430/000430.py
|
3d1bb3c077f5343fa55b72a6a1472a0b865025c4
|
[] |
no_license
|
BIAOXYZ/variousCodes
|
6c04f3e257dbf87cbe73c98c72aaa384fc033690
|
ee59b82125f100970c842d5e1245287c484d6649
|
refs/heads/master
| 2023-09-04T10:01:31.998311
| 2023-08-26T19:44:39
| 2023-08-26T19:44:39
| 152,967,312
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,241
|
py
|
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
"""
class Solution(object):
def flatten(self, head):
"""
:type head: Node
:rtype: Node
"""
if not head:
return head
res = []
def flatten_one_level(curr):
while curr:
nextNode = curr.next
curr.prev = None
curr.next = None
res.append(curr)
if curr.child:
flatten_one_level(curr.child)
curr.child = None
curr = nextNode
flatten_one_level(head)
for i in range(len(res)-1):
res[i].next = res[i+1]
res[i+1].prev = res[i]
res[-1].next = None
return head
"""
https://leetcode-cn.com/submissions/detail/222579276/
26 / 26 个通过测试用例
状态:通过
执行用时: 28 ms
内存消耗: 13.7 MB
执行用时:28 ms, 在所有 Python 提交中击败了57.78%的用户
内存消耗:13.7 MB, 在所有 Python 提交中击败了66.67%的用户
"""
|
[
"noreply@github.com"
] |
BIAOXYZ.noreply@github.com
|
e33115a19dd732a6c8ce0df64c67a4d22df9a5b5
|
12796e7a68295a5777690cf916197f553dcfc690
|
/plans/manageiq/rhev.py
|
cce05c9c1157767f73a22cb58d304b2c1cdf57a7
|
[
"Apache-2.0"
] |
permissive
|
jruariveiro/kcli
|
294768c25748f8a2281d9d7b3cad6f6d6dd5d9a9
|
2de467f9c74913b030ca8e2f32c7caad59bf53c1
|
refs/heads/master
| 2020-03-26T05:50:58.301210
| 2018-08-13T12:45:04
| 2018-08-13T12:45:04
| 144,577,929
| 0
| 0
|
Apache-2.0
| 2018-08-13T12:39:19
| 2018-08-13T12:39:19
| null |
UTF-8
|
Python
| false
| false
| 655
|
py
|
#!/usr/bin/python
import json
import requests
user = "admin"
password = "[[ password ]]"
rhevuser = "admin@internal"
rhevpassword = "[[ rhev_password ]]"
rhevhost = "[[ rhev_host ]]"
headers = {'content-type': 'application/json', 'Accept': 'application/json'}
postdata = {
"type": "ManageIQ::Providers::Redhat::InfraManager",
"name": "rhev",
"hostname": rhevhost,
"ipaddress": rhevhost,
"credentials": {
"userid": rhevuser,
"password": rhevpassword
}
}
url = "https://127.0.0.1/api/providers"
r = requests.post(url, verify=False, headers=headers, auth=(user, password), data=json.dumps(postdata))
print r.json()
|
[
"karimboumedhel@gmail.com"
] |
karimboumedhel@gmail.com
|
9e3792043fd56915f96a427288025faa54a6a339
|
8b7e9d06fca9d0999eabe7f6906db0e6f1f81d4c
|
/tourney/tournament/management/commands/players.py
|
f7ab85f516eaad2f0ee9ada587ed17b09dacad9e
|
[
"BSD-2-Clause",
"BSD-3-Clause"
] |
permissive
|
jonejone/tourney
|
9efa442e9c27660a7a4544b008e066592011b194
|
1372c635c873b6dc6c085a2bfdb02f6528ef25c3
|
refs/heads/master
| 2021-01-17T11:37:13.876732
| 2015-06-17T13:51:47
| 2015-06-17T13:51:47
| 7,472,571
| 0
| 0
| null | 2013-04-19T10:17:36
| 2013-01-06T20:49:36
|
Python
|
UTF-8
|
Python
| false
| false
| 1,945
|
py
|
from django.core.management.base import BaseCommand, CommandError
from optparse import make_option
from tourney.tournament.models import Player, Tournament
class Command(BaseCommand):
args = ''
help = 'Lists all players with their options'
option_list = BaseCommand.option_list + (
make_option('--with-options-only',
action='store_true',
dest='options-only',
default=False,
help='Only show players that has chosen any options.'),
)
def validate_tournament(self, *args, **options):
# First we must validate tournament
try:
t_slug = args[0]
tournament = Tournament.objects.get(slug=t_slug)
self.tournament = tournament
except IndexError:
raise CommandError('Please enter a tournament slug')
except Tournament.DoesNotExist:
raise CommandError('Tournament slug not found')
def handle(self, *args, **options):
self.validate_tournament(*args, **options)
if options['options-only']:
players = []
for p in self.tournament.tournamentplayer_set.all():
if p.options.count() > 0:
players.append(p)
else:
players = self.tournament.tournamentplayer_set.all()
for player in players:
opts = [opt.name for opt in player.options.all()]
if player.options.count() == 0:
output = '%(player_name)s - %(total_price)s'
else:
output = '%(player_name)s - %(total_price)s - %(options)s'
output_data = {
'player_name': player.player.name,
'options': ', '.join(opts),
'total_price': '%i %s' % (
player.get_player_price(),
self.tournament.currency),
}
self.stdout.write(output % output_data)
|
[
"jone@idev.no"
] |
jone@idev.no
|
2c63726f954f6cb0ed0fa254ffeea056e8545a62
|
3481023b43028c5ee9520a8be0978e914bdcb548
|
/manga_py/providers/nightow_net.py
|
86e53cd25348d31c6966eb6c3205f80499332ff9
|
[
"MIT"
] |
permissive
|
manga-py/manga-py
|
18f6818d8efc96c3e69efee7dff3f3d6c773e32a
|
0db97123acab1f2fb99e808b0ba54db08977e5c8
|
refs/heads/stable_1.x
| 2023-08-20T03:04:06.373108
| 2023-04-16T08:28:15
| 2023-04-16T08:28:15
| 98,638,892
| 444
| 56
|
MIT
| 2023-07-27T13:21:40
| 2017-07-28T10:27:43
|
Python
|
UTF-8
|
Python
| false
| false
| 1,285
|
py
|
from urllib.parse import unquote_plus
from manga_py.provider import Provider
from .helpers.std import Std
class NightowNet(Provider, Std):
_name_re = r'manga=(.+?)(?:&.+)?$'
def get_chapter_index(self) -> str:
ch = unquote_plus(self.chapter)
idx = self.re.search(r'chapter=(?:.+?)\+(\d+(?:\.\d+)?)', ch)
if idx:
return '-'.join(idx.group(1).split('.'))
return self.re.search('chapter=(.+?)(?:&.+)?$', ch).group(1)
def get_content(self):
name = self._get_name(self._name_re)
return self.http_get('{}/online/?manga={}'.format(
self.domain,
name
))
def get_manga_name(self) -> str:
return unquote_plus(self._get_name(self._name_re))
def get_chapters(self):
return self._elements('.selector .options a')
def prepare_cookies(self):
self._storage['referer'] = self.domain + '/online/'
def get_files(self):
content = self.http_get(self.chapter)
items = self.re.findall(r'imageArray\[\d+\]\s*=\s*[\'"](.+)[\'"];', content)
n = self.normalize_uri
return [n(i) for i in items]
def get_cover(self) -> str:
pass
def book_meta(self) -> dict:
# todo meta
pass
main = NightowNet
|
[
"sttv-pc@mail.ru"
] |
sttv-pc@mail.ru
|
8a20174c536f7b7a825e2aa4666c5462ebb3d9a5
|
a6106cedc42dcab94ccc4ee6d681372d2246ce5e
|
/python/활용자료/예제/02/ex2-24.py
|
c858e184ca1d9032edc29dc8ef0b5ed1a39a8b11
|
[] |
no_license
|
leemyoungwoo/pybasic
|
a5a4b68d6b3ddd6f07ff84dc8df76da02650196f
|
481075f15613c5d8add9b8c4d523282510d146d2
|
refs/heads/master
| 2022-10-08T19:57:26.073431
| 2020-06-15T06:50:02
| 2020-06-15T06:50:02
| 267,502,565
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 170
|
py
|
name = '황예린'
age = 18
eyesight = 1.2
a = '이름 : {}'.format(name)
b = '나이 : {}세'.format(age)
c = '시력 : {}'.format(eyesight)
print(a)
print(b)
print(c)
|
[
"mwlee2587@gmail.com"
] |
mwlee2587@gmail.com
|
2de31ce63bf56006e3b69bfa7c958f0145752bff
|
555b9f764d9bca5232360979460bc35c2f5ad424
|
/google/ads/google_ads/v1/proto/services/conversion_adjustment_upload_service_pb2_grpc.py
|
6e9635e57ac9663a3ce02788dfd010e22f15e749
|
[
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] |
permissive
|
juanmacugat/google-ads-python
|
b50256163782bc0223bcd8b29f789d74f4cfad05
|
0fc8a7dbf31d9e8e2a4364df93bec5f6b7edd50a
|
refs/heads/master
| 2021-02-18T17:00:22.067673
| 2020-03-05T16:13:57
| 2020-03-05T16:13:57
| 245,215,877
| 1
| 0
|
Apache-2.0
| 2020-03-05T16:39:34
| 2020-03-05T16:39:33
| null |
UTF-8
|
Python
| false
| false
| 2,255
|
py
|
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
from google.ads.google_ads.v1.proto.services import conversion_adjustment_upload_service_pb2 as google_dot_ads_dot_googleads__v1_dot_proto_dot_services_dot_conversion__adjustment__upload__service__pb2
class ConversionAdjustmentUploadServiceStub(object):
"""Service to upload conversion adjustments.
"""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.UploadConversionAdjustments = channel.unary_unary(
'/google.ads.googleads.v1.services.ConversionAdjustmentUploadService/UploadConversionAdjustments',
request_serializer=google_dot_ads_dot_googleads__v1_dot_proto_dot_services_dot_conversion__adjustment__upload__service__pb2.UploadConversionAdjustmentsRequest.SerializeToString,
response_deserializer=google_dot_ads_dot_googleads__v1_dot_proto_dot_services_dot_conversion__adjustment__upload__service__pb2.UploadConversionAdjustmentsResponse.FromString,
)
class ConversionAdjustmentUploadServiceServicer(object):
"""Service to upload conversion adjustments.
"""
def UploadConversionAdjustments(self, request, context):
"""Processes the given conversion adjustments.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_ConversionAdjustmentUploadServiceServicer_to_server(servicer, server):
rpc_method_handlers = {
'UploadConversionAdjustments': grpc.unary_unary_rpc_method_handler(
servicer.UploadConversionAdjustments,
request_deserializer=google_dot_ads_dot_googleads__v1_dot_proto_dot_services_dot_conversion__adjustment__upload__service__pb2.UploadConversionAdjustmentsRequest.FromString,
response_serializer=google_dot_ads_dot_googleads__v1_dot_proto_dot_services_dot_conversion__adjustment__upload__service__pb2.UploadConversionAdjustmentsResponse.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'google.ads.googleads.v1.services.ConversionAdjustmentUploadService', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
|
[
"noreply@github.com"
] |
juanmacugat.noreply@github.com
|
fc5b935b9f8310e3f6f4113fb0a228bec78d5e73
|
2bb6f9c0a3658acf2bd6b97dcdeace9213723640
|
/namespace/models/list_field.py
|
ee577399fe07b1476580fed945fe7ee0aef6dc04
|
[] |
no_license
|
hugoseabra/mailchimp-service
|
4fee930fd11b30f4c7da3654da2cbb231ca34341
|
0424b90fdc0911b4a6b1d514ba51c88d7d3572b4
|
refs/heads/develop
| 2022-07-20T02:52:06.147740
| 2020-03-17T21:31:37
| 2020-03-17T21:31:37
| 242,433,347
| 0
| 0
| null | 2022-07-06T20:30:14
| 2020-02-23T00:39:43
|
Python
|
UTF-8
|
Python
| false
| false
| 2,475
|
py
|
from django.db import models
from django.utils.translation import ugettext_lazy as _
from core.models import track_data
from core.models.mixins import (
DateTimeManagementMixin,
DeletableModelMixin,
EntityMixin,
UUIDPkMixin,
)
@track_data('namespace_id', 'label', 'tag')
class ListField(UUIDPkMixin,
EntityMixin,
DeletableModelMixin,
DateTimeManagementMixin,
models.Model):
"""
Campo adicionado a uma lista.
"""
class Meta:
verbose_name = _('list field')
verbose_name_plural = _('list fields')
unique_together = (
('namespace_id', 'tag',),
)
FIELD_TYPE_TEXT = 'text'
FIELD_TYPE_NUMBER = 'number'
FIELD_TYPES = (
(FIELD_TYPE_TEXT, _('Text')),
(FIELD_TYPE_NUMBER, _('Number')),
)
namespace = models.ForeignKey(
verbose_name=_('namespace'),
to='namespace.Namespace',
on_delete=models.PROTECT,
null=False,
blank=False,
related_name='fields',
)
field_type = models.CharField(
max_length=6,
verbose_name=_('field type'),
null=False,
blank=False,
choices=FIELD_TYPES,
default=FIELD_TYPE_TEXT,
)
label = models.CharField(
max_length=50,
verbose_name=_('label'),
null=False,
blank=False,
)
tag = models.CharField(
max_length=50,
verbose_name=_('tag'),
null=False,
blank=False,
)
help_text = models.CharField(
max_length=255,
verbose_name=_('help text'),
null=True,
blank=True,
)
active = models.BooleanField(
verbose_name=_('active'),
default=False,
null=False,
blank=False,
help_text=_('If true, it means that the field will be created in list'
' in MailChimp platform.'),
)
def to_sync_data(self):
return {
'name': self.label,
'tag': self.tag,
'type': self.field_type,
'required': False,
'list_id': self.namespace.default_list_id,
'help_text': self.help_text,
}
def __repr__(self):
return '<ListField pk: {}, label: {}, tag: {}'.format(
self.pk,
self.label,
self.tag,
)
def __str__(self):
return '{} ({})'.format(self.label, self.tag)
|
[
"hugoseabra19@gmail.com"
] |
hugoseabra19@gmail.com
|
eae92e47c1d4a062e8b1bbd1f5491ed7c0450eb6
|
64ef180b1725d831891ef075557ddcc540c6e42a
|
/init.py
|
f947e2f7251a20b7e823621b1950cb622574ebbc
|
[
"MIT"
] |
permissive
|
nasingfaund/tkinter-gui-application-examples
|
125acc088133020adae0bfc9c752a8e75c780c73
|
7073d163713829b2ff10a331c7f88f845d89b1bc
|
refs/heads/master
| 2023-07-15T06:41:35.861732
| 2021-08-28T14:36:28
| 2021-08-28T14:36:28
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,703
|
py
|
#!/usr/bin/env python3
# -*- coding:utf-8-*-
import tkinter.messagebox
from tkinter import Button, Label, Tk
from lib.functions import set_window_center
from lib.sqlite_helper import DBHelper
from main import App
class InitWindow(Tk):
"""初始化窗口"""
def __init__(self):
Tk.__init__(self)
self.title("初始化数据")
set_window_center(self, 300, 180)
self.resizable(False, False)
self.win_success = None # 初始化成功的提示窗口
self.init_page()
def init_page(self):
"""加载控件"""
btn_1 = Button(self, text="初始化数据库", command=self.do_init_db)
btn_1.pack(expand="yes", padx=10, pady=10, ipadx=5, ipady=5)
def do_init_db(self):
"""初始化"""
db_helper = DBHelper()
db_helper.reset_database()
db_helper.create_database()
try:
tmp = db_helper.insert_user("admin", "admin") # 默认用户
tmp2 = db_helper.insert_content_by_username(
"admin",
"Hello World !",
"源码仓库地址:https://github.com/doudoudzj/tkinter-app",
"github",
)
tmp3 = db_helper.get_content_by_username("admin")
print("添加用户admin:", tmp)
print("添加内容:", tmp2)
print("查询内容:", tmp3)
self.do_success()
self.destroy()
except KeyError:
print(KeyError)
self.do_failed()
def do_failed(self):
"""是否重试"""
res = tkinter.messagebox.askretrycancel('提示', '初始化失败,是否重试?', parent=self)
if res is True:
self.do_init_db()
elif res is False:
self.destroy()
def do_success(self):
"""初始化成功弹窗"""
self.win_success = Tk()
self.win_success.title("初始化成功")
set_window_center(self.win_success, 250, 150)
self.win_success.resizable(False, False)
msg = Label(self.win_success, text="初始化成功")
msg.pack(expand="yes", fill="both")
btn = Button(self.win_success, text="确定", command=self.quit)
btn.pack(side="right", padx=10, pady=10, ipadx=5, ipady=5)
btn_open_app = Button(self.win_success, text="启动程序", command=self.open_app)
btn_open_app.pack(side="right", padx=10, pady=10, ipadx=5, ipady=5)
def open_app(self):
"""打开应用程序"""
self.quit()
self.win_success.destroy()
self.win_success.quit()
App()
if __name__ == "__main__":
APP_INIT = InitWindow()
APP_INIT.mainloop()
|
[
"doudoudzj@sina.com"
] |
doudoudzj@sina.com
|
243c82d2ac9b47f93c80d5616f675f92d84dc0ea
|
3a69696a2c5debfb24dfacffa6d3b0e311d0375e
|
/src/tests/test_launcher.py
|
80eca716e26f24ebe46b392f600f9e5be84878bf
|
[
"Apache-2.0"
] |
permissive
|
Build-The-Web/bootils
|
7aeab92debc20258d645a70f5595738653ef46a7
|
8ee88f4d0583352f58fbb89c018e7caef8f07ce3
|
refs/heads/master
| 2021-01-17T09:14:18.317535
| 2016-06-03T13:38:01
| 2016-06-03T13:38:01
| 32,890,374
| 3
| 2
|
Apache-2.0
| 2018-03-04T20:46:22
| 2015-03-25T20:57:07
|
Python
|
UTF-8
|
Python
| false
| false
| 1,951
|
py
|
# *- coding: utf-8 -*-
# pylint: disable=wildcard-import, missing-docstring, no-self-use, bad-continuation
# pylint: disable=invalid-name, redefined-outer-name, too-few-public-methods
""" Test «some_module».
"""
# Copyright © 2015 1&1 Group <btw-users@googlegroups.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, unicode_literals, print_function
import os
import getpass
import pytest
from bootils import launcher
def test_signal_name_to_int():
assert launcher.signal2int(1) == 1
assert launcher.signal2int('1') == 1
assert launcher.signal2int('pipe') == 13
assert launcher.signal2int('PIPE') == 13
assert launcher.signal2int('sigPIPE') == 13
def test_signal2int_with_bad_name():
with pytest.raises(ValueError):
launcher.signal2int('foobar')
def test_signal2int_with_bad_type():
with pytest.raises(ValueError):
launcher.signal2int(None)
def test_uid_of_root():
assert launcher.check_uid(0) == 0
assert launcher.check_uid('0') == 0
assert launcher.check_uid('root') == 0
def test_uid_of_current_user():
uid_home = os.stat(os.path.expanduser('~')).st_uid
assert launcher.check_uid(getpass.getuser()) == uid_home
def test_gid_of_root():
assert launcher.check_gid(0) == 0
assert launcher.check_gid('0') == 0
assert launcher.check_gid('root') == 0
def test_gid_of_users():
assert launcher.check_gid('users') > 0
|
[
"jh@web.de"
] |
jh@web.de
|
c8a41a9fd2264a175999475b482f5c7509481456
|
353def93fa77384ee3a5e3de98cfed318c480634
|
/.history/week01/homework02/maoyanspiders/maoyanspiders/spiders/movies_20200627214427.py
|
4ddb627414c18159133e722575fe0e29e8aa2e28
|
[] |
no_license
|
ydbB/Python001-class01
|
d680abc3ea1ccaeb610751e3488421417d381156
|
ad80037ccfc68d39125fa94d2747ab7394ac1be8
|
refs/heads/master
| 2022-11-25T11:27:45.077139
| 2020-07-19T12:35:12
| 2020-07-19T12:35:12
| 272,783,233
| 0
| 0
| null | 2020-06-16T18:28:15
| 2020-06-16T18:28:15
| null |
UTF-8
|
Python
| false
| false
| 932
|
py
|
# -*- coding: utf-8 -*-
import scrapy
from maoyanspiders.items import MaoyanspidersItem
# import xlml.etree
from bs4 import BeautifulSoup as bs
class MoviesSpider(scrapy.Spider):
name = 'movies'
allowed_domains = ['maoyan.com']
start_urls = ['http://maoyan.com/board/4']
# def parse(self, response):
# pass
def start_requests(self):
url = f'https://maoyan.com/board/4'
print(url)
yield scrapy.Request(url=url,callback=self.parse)
def parse(self, response):
soup = bs(response.text,'html.parser')
print(soup.text)
return soup
for i in soup.find_all('div',attrs={'class' : 'movie-item-info'}):\
item = MaoyanspidersItem()
link = i.get('href'.text)
item['films_name'] = 'name'
item['release_time'] = "tiome"
yield scrapy.Request(url=url,callback=self.parse1)
return item
|
[
"31039587+ydbB@users.noreply.github.com"
] |
31039587+ydbB@users.noreply.github.com
|
ef98cfec035e621902aedc72b76f5850fc6e84ca
|
e380663d6a11d05828a040486c85e2dfae358597
|
/djangove/utils/templatetags/navigation_tags.py
|
bafbc92d8d8e0530401dc4ad20eed4c5aac944d7
|
[
"BSD-3-Clause"
] |
permissive
|
djangove/djangove
|
4a2ad9dcd5236ff746bb09d21f2fab1424dfc2f5
|
1fee878d170e52ee0c5cacd1d2813b045d4cbb77
|
refs/heads/master
| 2021-09-10T05:58:01.868815
| 2020-03-09T22:27:58
| 2020-03-09T22:27:58
| 43,475,979
| 1
| 1
|
BSD-3-Clause
| 2021-09-07T23:57:06
| 2015-10-01T03:13:04
|
Python
|
UTF-8
|
Python
| false
| false
| 4,882
|
py
|
from django import template
from wagtail.wagtailcore.models import Page
register = template.Library()
@register.assignment_tag(takes_context=True)
def get_site_root(context):
return context['request'].site.root_page
def has_menu_children(page):
if page.get_children().filter(live=True, show_in_menus=True):
return True
else:
return False
@register.inclusion_tag(
'utils/tags/navigation/top_menu.html', takes_context=True)
def top_menu(context, parent, calling_page=None):
menuitems = parent.get_children().filter(
live=True,
show_in_menus=True
)
for menuitem in menuitems:
menuitem.show_dropdown = has_menu_children(menuitem)
return {
'calling_page': calling_page,
'menuitems': menuitems,
'request': context['request'],
}
# Retrieves the children of the top menu items for the drop downs
@register.inclusion_tag(
'utils/tags/navigation/top_menu_children.html', takes_context=True)
def top_menu_children(context, parent):
menuitems_children = parent.get_children()
menuitems_children = menuitems_children.filter(
live=True,
show_in_menus=True
)
for menuitem in menuitems_children:
menuitem.show_dropdown = has_menu_children(menuitem)
return {
'parent': parent,
'menuitems_children': menuitems_children,
# required by the pageurl tag that we want to use within this template
'request': context['request'],
}
@register.inclusion_tag(
'utils/tags/navigation/site_menu.html', takes_context=True)
def site_menu(context, parent, calling_page=None):
menuitems = parent.get_children().filter(
live=True,
show_in_menus=True
)
for menuitem in menuitems:
menuitem.show_dropdown = has_menu_children(menuitem)
return {
'calling_page': calling_page,
'menuitems': menuitems,
'request': context['request'],
}
@register.inclusion_tag(
'utils/tags/navigation/site_menu_children.html', takes_context=True)
def site_menu_children(context, parent):
menuitems_children = parent.get_children()
menuitems_children = menuitems_children.filter(
live=True,
show_in_menus=True
)
for menuitem in menuitems_children:
menuitem.show_dropdown = has_menu_children(menuitem)
return {
'parent': parent,
'menuitems_children': menuitems_children,
# required by the pageurl tag that we want to use within this template
'request': context['request'],
}
@register.inclusion_tag(
'utils/tags/navigation/secondary_menu.html', takes_context=True)
def secondary_menu(context, calling_page=None):
pages = []
if calling_page:
pages = calling_page.get_children().filter(
live=True,
show_in_menus=True
)
# If no children, get siblings instead
if len(pages) == 0:
pages = calling_page.get_siblings().filter(
live=True,
show_in_menus=True
)
return {
'pages': pages,
# required by the pageurl tag that we want to use within this template
'request': context['request'],
}
@register.inclusion_tag(
'utils/tags/navigation/breadcrumbs.html', takes_context=True)
def breadcrumbs(context):
self = context.get('self')
if self is None or self.depth <= 2:
# When on the home page, displaying breadcrumbs is irrelevant.
ancestors = ()
else:
ancestors = Page.objects.ancestor_of(
self, inclusive=True).filter(depth__gt=2)
return {
'ancestors': ancestors,
'request': context['request'],
}
@register.inclusion_tag(
'utils/tags/navigation/offcanvas_top_menu.html', takes_context=True)
def offcanvas_top_menu(context, parent, calling_page=None):
menuitems = parent.get_children().filter(
live=True,
show_in_menus=True
)
for menuitem in menuitems:
menuitem.show_dropdown = has_menu_children(menuitem)
return {
'calling_page': calling_page,
'menuitems': menuitems,
'request': context['request'],
}
# Retrieves the children of the top menu items for the drop downs
@register.inclusion_tag(
'utils/tags/navigation/offcanvas_top_menu_children.html', takes_context=True)
def offcanvas_top_menu_children(context, parent):
menuitems_children = parent.get_children()
menuitems_children = menuitems_children.filter(
live=True,
show_in_menus=True
)
for menuitem in menuitems_children:
menuitem.show_dropdown = has_menu_children(menuitem)
return {
'parent': parent,
'menuitems_children': menuitems_children,
# required by the pageurl tag that we want to use within this template
'request': context['request'],
}
|
[
"edwar.baron@gmail.com"
] |
edwar.baron@gmail.com
|
2ba56d300f998d10473103a90bf6e35b36c49fec
|
a37b756e34fc39c1237fc68997dbef77df9fa6fc
|
/keras/keras56-61/keras59_3_save_npy.py
|
610895f0e6684a04202781a5817cb6ccdfb0c08d
|
[] |
no_license
|
jvd2n/ai-study
|
e20e38493ad295940a3201fc0cc8061ca9052607
|
a82f7c6d89db532f881c76b553b5ab3eea0bdd59
|
refs/heads/main
| 2023-08-06T03:24:39.182686
| 2021-10-06T14:41:01
| 2021-10-06T14:41:01
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,917
|
py
|
import numpy as np
from tensorflow.keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(
rescale=1./255,
horizontal_flip=True,
vertical_flip=True,
width_shift_range=0.1,
height_shift_range=0.1,
rotation_range=5,
zoom_range=1.2,
shear_range=0.7,
fill_mode='nearest'
)
test_datagen = ImageDataGenerator(rescale=1./255)
xy_train = train_datagen.flow_from_directory(
'../data/brain/train',
target_size=(150, 150),
batch_size=200, # xy_train[0]의 ,5(batch_size) 크기로 생성
class_mode='binary'
)
# Found 160 images belonging to 2 classes.
xy_test = test_datagen.flow_from_directory(
'../data/brain/test',
target_size=(150, 150),
batch_size=200, # xy_train[0]의 ,5(batch_size) 크기로 생성
class_mode='binary',
shuffle=True
)
# Found 120 images belonging to 2 classes.
print(xy_train)
# <tensorflow.python.keras.preprocessing.image.DirectoryIterator object at 0x000002C3A9DB9780>
print(xy_train[0][0]) # x value
print(xy_train[0][1]) # y value
# print(xy_train[0][2]) # None
print(xy_train[0][0].shape, xy_train[0][1].shape) # (160, 150, 150, 3) (160,)
print(xy_test[0][0].shape, xy_test[0][1].shape) # (120, 150, 150, 3) (120,)
# print(xy_train[31][1]) # 마지막 배치 y. 총 32장 * batchsize = 160장의 사진임을 알 수 있다.
# print(xy_train[32][1]) # None
# print(type(xy_train)) # <class 'tensorflow.python.keras.preprocessing.image.DirectoryIterator'>
# print(type(xy_train[0])) # <class 'tuple'>
# print(type(xy_train[0][0])) # <class 'numpy.ndarray'>
# print(type(xy_train[0][1])) # <class 'numpy.ndarray'>
np.save('./_save/_npy/k59_3_train_x.npy', arr=xy_train[0][0])
np.save('./_save/_npy/k59_3_train_y.npy', arr=xy_train[0][1])
np.save('./_save/_npy/k59_3_test_x.npy', arr=xy_test[0][0])
np.save('./_save/_npy/k59_3_test_y.npy', arr=xy_test[0][1])
|
[
"juhnmayer@gmail.com"
] |
juhnmayer@gmail.com
|
8ba2cbaceeb6ecd1f79a0aaa8ad6322d5c9d3954
|
c489a910d1533f0e03a86f3cc483fdba352dc481
|
/tests/platform_tests/cli/test_show_chassis_module.py
|
a16ca7d6baf021ba84013997b905255f0fcb61c9
|
[
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] |
permissive
|
chenkelly/sonic-mgmt
|
1b6dab6e34dac2ac8cb475c4ded1329e53ad31d4
|
7bf848d84af017b0275f75c3a383b6fc63f0ab43
|
refs/heads/master
| 2023-03-08T11:14:22.071818
| 2023-03-02T02:26:05
| 2023-03-02T02:26:05
| 212,235,644
| 0
| 1
|
NOASSERTION
| 2019-10-02T01:53:59
| 2019-10-02T01:53:58
| null |
UTF-8
|
Python
| false
| false
| 3,664
|
py
|
import logging
import pytest
from tests.common.helpers.assertions import pytest_assert
from util import get_field_range, get_fields, get_skip_mod_list
logger = logging.getLogger('__name__')
pytestmark = [
pytest.mark.topology('t2')
]
CMD_SHOW_CHASSIS_MODULE = "show chassis modules"
def parse_chassis_module(output, expected_headers):
assert len(output) > 2
f_ranges = get_field_range(output[1])
headers = get_fields(output[0], f_ranges)
for header_v in expected_headers:
pytest_assert(header_v in headers, "Missing header {}".format(header_v))
result = {}
for a_line in output[2:]:
field_val = get_fields(a_line, f_ranges)
mod_idx = field_val[0]
result[mod_idx] = {}
cur_field = 1
for a_header in headers[1:]:
result[mod_idx][a_header] = field_val[cur_field]
cur_field += 1
return result
def test_show_chassis_module_status(duthosts, enum_rand_one_per_hwsku_hostname):
cmd = " ".join([CMD_SHOW_CHASSIS_MODULE, "status"])
logger.info("verifying output of cli command {}".format(cmd))
duthost = duthosts[enum_rand_one_per_hwsku_hostname]
exp_headers = ["Name", "Description", "Physical-Slot", "Oper-Status", "Admin-Status"]
skip_mod_list = get_skip_mod_list(duthost)
output = duthost.command(cmd)
res = parse_chassis_module(output['stdout_lines'], exp_headers)
# by default will assume all modules should be shown online except in skip_module_list
for mod_idx in res.keys():
if mod_idx in skip_mod_list:
pytest_assert(res[mod_idx]['Oper-Status'] == 'Empty',
"Oper-status for slot {} should be Empty but it is {}".format(
mod_idx, res[mod_idx]['Oper-Status']))
else:
pytest_assert(res[mod_idx]['Oper-Status'] == 'Online',
"Oper-status for slot {} should be Online but it is {}".format(
mod_idx, res[mod_idx]['Oper-Status']))
def test_show_chassis_module_midplane_status(duthosts, enum_rand_one_per_hwsku_hostname):
"""
@summary: Verify output of `show chassis-module midplane-status`
"""
cmd = " ".join([CMD_SHOW_CHASSIS_MODULE, "midplane-status"])
logger.info("verifying output of cli command {}".format(cmd))
expected_headers = ["Name", "IP-Address", "Reachability"]
duthost = duthosts[enum_rand_one_per_hwsku_hostname]
output = duthost.command(cmd)
res_mid_status = parse_chassis_module(output['stdout_lines'], expected_headers)
mod_key= ['line-cards', 'supervisor']
skip_mod_list = get_skip_mod_list(duthost, mod_key)
for mod_idx in res_mid_status:
mod_mid_status = res_mid_status[mod_idx]['Reachability']
if mod_idx not in skip_mod_list:
pytest_assert(mod_mid_status == "True",
"midplane reachability of line card {} expected true but is {}".format(mod_idx,
mod_mid_status))
else:
# There are cases where the chassis is logically divided where some LCs belongs to another chassis and needs to be skipped
# and for those cases we should not assume if skipped means it must be offline.
if "LINE-CARD" in mod_idx:
logger.info("skip checking midplane status for {} since it is on skip_mod_list".format(mod_idx))
else:
pytest_assert(mod_mid_status == "False",
"reachability of {} expected false but is {}".format(mod_idx, mod_mid_status))
|
[
"noreply@github.com"
] |
chenkelly.noreply@github.com
|
3b8dab3caf5ea5bc26f73ce0a695743fc54d1ebd
|
697af415566ba649502bd18751a6521ac526892c
|
/2022_VERSIONS/rename_er2_hiwrap_ratio_files_with_dates.py
|
103b3076f5e91476a83cc6f59c7e187709d01c5d
|
[] |
no_license
|
srbrodzik/impacts-scripts
|
df44c8f34746499b8397b5b1a4ad09859b4cc8d4
|
263c7545bbb912bbcea563a21d0619e5112b1788
|
refs/heads/master
| 2023-05-31T05:01:09.558641
| 2023-05-22T23:24:52
| 2023-05-22T23:24:52
| 215,638,568
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,026
|
py
|
#!/usr/bin/python3
import os
import sys
import shutil
from datetime import datetime
from datetime import timedelta
import datetime as dt
import pytz
if len(sys.argv) != 2:
#print('Usage: sys.argv[0] [YYYYMMDD]')
print('Usage: {} [YYYYMMDD]'.format(sys.argv[0]))
sys.exit()
else:
date = sys.argv[1]
indir = '/home/disk/bob/impacts/radar/er2/postFlight/realtime/hiwrap_ratio'+'/'+date
prefix = 'aircraft.NASA_ER2'
suffix = 'HIWRAP_DWR'
convertEasternToUTC = True
os.chdir(indir)
for file in os.listdir(indir):
print(file)
(base,ext) = os.path.splitext(file)
(radar,ratio,dateTime) = base.split('_')
dateTimeStr = dateTime[:-2]
if convertEasternToUTC:
dateTimeObj = datetime.strptime(dateTimeStr,"%Y%m%d%H%M")
dateTimeObjUTC = dateTimeObj+timedelta(hours=5)
dateTimeStrUTC = dateTimeObjUTC.strftime("%Y%m%d%H%M")
else:
dateTimeStrUTC = datetimeStr
catName = prefix+'.'+dateTimeStrUTC+'.'+suffix+ext
shutil.move(file,catName)
|
[
"brodzik@uw.edu"
] |
brodzik@uw.edu
|
85cd6a7fc3fd30414c7549565e1cf56245d15e74
|
29841982e9d3a70d24faa6bed2397d07419fb409
|
/aula_5/dashboard/routes/auth.py
|
572c567ffdc274cd6a81933ea061133c5086aa66
|
[] |
no_license
|
HiroEu/python-521
|
40d6950b19b6c5a9850177739b3e72be0c0e0ae7
|
d279cb5dac771e11681cdfa91bfe363a2fbaa356
|
refs/heads/master
| 2022-02-24T15:43:49.085686
| 2022-02-08T19:08:58
| 2022-02-08T19:08:58
| 202,603,500
| 0
| 0
| null | 2021-06-02T00:20:44
| 2019-08-15T19:58:07
|
Python
|
UTF-8
|
Python
| false
| false
| 1,593
|
py
|
import flask
import ldap3
import logging
blueprint = flask.Blueprint('auth', __name__)
@blueprint.route('/sign-in', methods=[ 'GET', 'POST' ])
def sign_in():
context = {
'title': 'Python | Sysadmin',
}
EMAIL = 'admin@admin'
PASSWORD = 'admin'
if flask.request.method == 'POST':
email = flask.request.form.get('email')
password = flask.request.form.get('password')
if email == EMAIL and password == PASSWORD:
logging.info('Usuário logado')
else:
logging.warning('Falha na autenticação' + email)
# if flask.request.method == 'POST':
# form = flask.request.form
# email = form.get('email')
# password = form.get('password')
# conn = ldap3.Connection(
# ldap3.Server('ldap://127.0.0.1'),
# 'cn=admin,dc=dexter,dc=com,dc=br',
# '4linux'
# )
# conn.bind()
# conn.search(
# 'uid={},dc=dexter,dc=com,dc=br'.format(email),
# '(objectClass=person)',
# attributes=[
# 'sn',
# 'userPassword'
# ]
# )
# user = None
# try:
# user = conn.entries[0]
# except IndexError:
# return flask.redirect('/sign-in')
# saved_password = user.userPassword[0].decode()
# if saved_password == password:
# flask.session['is-logged'] = True
# return flask.redirect('/docker')
return flask.render_template('sign-in.html', context=context)
|
[
"leonardo.mendes@4linux.com.br"
] |
leonardo.mendes@4linux.com.br
|
3e5f56f3436373330a569dad1bb1f6b35fe1cfe8
|
3d613577d8e5a0b8f128666047043ac672f975af
|
/market/admin.py
|
89dcecee2190326fd074e1a813638735e613a34f
|
[] |
no_license
|
danimaribeiro/bitcoin_market
|
8431773795114706bf482d3b7961ef7e527ead5e
|
6d9256059ed7f35a8a412cb78d3a71a7498d90f9
|
refs/heads/master
| 2016-09-05T12:13:17.741558
| 2014-02-18T13:03:29
| 2014-02-18T13:03:29
| 16,620,172
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,992
|
py
|
from django.contrib import admin
from django.contrib.admin import DateFieldListFilter
from django.contrib.auth.models import User
# Register your models here.
from market.models import Order, Trade, Market, MarketConfiguration, Settings
class TradeAdmin(admin.ModelAdmin):
fields = ['tid', 'date', 'amount', 'price', 'type', 'coin']
list_display = ['tid', 'date', 'amount', 'price', 'type', 'coin']
list_filter = ['type', ('date', DateFieldListFilter), 'coin']
search_fields = ['date']
def has_add_permission(self, request):
return False
def has_delete_permission(self, request, obj=None):
return False
class MarketConfigurationAdmin(admin.ModelAdmin):
fields = ['market', 'access_key', 'access_sign']
list_display = ['market', 'access_key', 'access_sign', 'belongs_to']
def save_model(self, request, obj, form, change):
instance = form.save(commit=False)
instance.belongs_to = request.user
instance.save()
form.save_m2m()
return instance
class OrderAdmin(admin.ModelAdmin):
fields = [ 'price', 'amount', 'type','market', 'status', 'sincronized']
readonly_fields = ['status', 'sincronized']
list_display = ['tid','price', 'amount', 'type','market', 'status', 'sincronized', 'belongs_to']
def get_readonly_fields(self, request, obj=None):
if obj: # editing an existing object
return self.readonly_fields + ['market','price','amount', 'type']
return self.readonly_fields
def save_model(self, request, obj, form, change):
instance = form.save(commit=False)
instance.belongs_to = request.user
instance.save()
form.save_m2m()
return instance
admin.site.register(Order, OrderAdmin)
admin.site.register(Market)
admin.site.register(MarketConfiguration, MarketConfigurationAdmin)
admin.site.register(Settings)
admin.site.register(Trade, TradeAdmin)
|
[
"danimaribeiro@gmail.com"
] |
danimaribeiro@gmail.com
|
fb95b5674453874d8218e5070d12976ce7cde15a
|
c369443df5ff98eccc0eee7f63bb8947f2943605
|
/shop/admin.py
|
950e8733d62ba6d0df356ee67145a865be1b988e
|
[] |
no_license
|
erllan/shop-test
|
d2934f484b25d141a60caa5aca31a61eec48f055
|
1f77de177192ce6a1f8c5ccf1d7ca93ec026acf5
|
refs/heads/master
| 2023-03-06T01:04:38.785383
| 2021-02-27T18:02:07
| 2021-02-27T18:02:07
| 341,929,117
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 141
|
py
|
from django.contrib import admin
from .models import *
admin.site.register(User)
admin.site.register(Product)
admin.site.register(Category)
|
[
"erlan.kubanychbekov.000@gmail.com"
] |
erlan.kubanychbekov.000@gmail.com
|
1e082c416f419960cc8822abb7b30e306623c4e7
|
0e7aed5eef2e1d132a7e75dd8f439ae76c87639c
|
/python/523_Continuous_Subarray_Sum.py
|
1c395d7edb3f718bfdf9111d3fd63749240be388
|
[
"MIT"
] |
permissive
|
liaison/LeetCode
|
2a93df3b3ca46b34f922acdbc612a3bba2d34307
|
bf03743a3676ca9a8c107f92cf3858b6887d0308
|
refs/heads/master
| 2022-09-05T15:04:19.661298
| 2022-08-19T19:29:19
| 2022-08-19T19:29:19
| 52,914,957
| 17
| 4
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 811
|
py
|
class Solution:
def checkSubarraySum(self, nums: List[int], k: int) -> bool:
# the earliest index with the same module remaider of k
prefix_sum_indices = {}
# a virtual prefix sum index.
# for the test case of [0, 0] k = 0
prefix_sum = 0
prefix_sum_indices[0] = -1
for index, num in enumerate(nums):
prefix_sum += num
# group the prefix sums with modulo
if k != 0:
prefix_sum %= k # normalize the sum
if prefix_sum in prefix_sum_indices:
if index - prefix_sum_indices[prefix_sum] > 1:
return True
else:
prefix_sum_indices[prefix_sum] = index
return False
|
[
"lisong.guo@me.com"
] |
lisong.guo@me.com
|
e3405de232c07e7515801124b11d7fee65e18b3f
|
76af281542524f4bb2c80f928b6b5f0786ca1557
|
/code kata/hunterbcs.py
|
c05f27f4aa57fea8b70cbd59253c6abba2faf7c4
|
[] |
no_license
|
sharmishah/guvi
|
1b910042f101265c7628724f994eca1c23c0f59d
|
51d854e38c2013799b24af43501bc8190b150897
|
refs/heads/master
| 2021-07-02T04:20:03.629762
| 2021-06-28T03:08:10
| 2021-06-28T03:08:10
| 191,355,062
| 0
| 4
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,087
|
py
|
class Node:
def __init__(self,d):
self.ddata=d
self.left=None
self.right=None
def insert(root,ins):
if ins.ddata>root.ddata and root.right!=None:
insert(root.right,ins)
elif ins.ddata<=root.ddata and root.left!=None:
insert(root.left,ins)
if ins.ddata>root.ddata and root.right==None:
root.right=ins
return
elif ins.ddata<=root.ddata and root.left==None:
root.left=ins
return
def inorder(root):
if root is None:
return
else:
inorder(root.left)
print(root.ddata,end=" ")
inorder(root.right)
def lcafinder(root,nn1,nn2):
if root is None:
return None
if root.ddata>nn1 and root.ddata>nn2:
return lcafinder(root.left,nn1,nn2)
if root.ddata<nn1 and root.ddata<nn2:
return lcafinder(root.right,nn1,nn2)
return root.ddata
nn=int(input())
az=list(map(int,input().split()))
l,rr1=map(int,input().split())
rr=Node(aa[0])
for i in range(1,nn):
nnn=Node(aa[i])
insert(rr,nnn)
#inorder(rr)
print(lcafinder(rr,l,rr1))
|
[
"noreply@github.com"
] |
sharmishah.noreply@github.com
|
0ee27ac5c2bab74b50ad2464577cd9e7a785b147
|
2eef8688d9f928de1c9fa4de4a045fa0dae97eaa
|
/authentication/urls.py
|
a1547debf84ea68191354dcc0eae804b158ddae7
|
[] |
no_license
|
teefats/GlotiExpenses
|
3a98096642ef6df9008489c5db8c822703e43ab7
|
12aa1c9a37c5cf0148a7f55b114402a3044f4e60
|
refs/heads/master
| 2023-06-22T13:42:37.362537
| 2021-07-26T19:06:31
| 2021-07-26T19:06:31
| 389,741,004
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 219
|
py
|
from .views import RegistrationView,LoginView
from django.urls import path
urlpatterns = [
path('register', RegistrationView.as_view(), name='register'),
path('login', LoginView.as_view(), name='login')
]
|
[
"tee_fats@yahoo.com"
] |
tee_fats@yahoo.com
|
1aa13187b581668799052bae234fe73c77b9b0d3
|
f0d713996eb095bcdc701f3fab0a8110b8541cbb
|
/JEt4kwPtY6CGPsT9t_6.py
|
184ee79d9dfae190511e21dc5f73d8aed48cb2d4
|
[] |
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
| 954
|
py
|
"""
Create a function that takes a mathematical expression as a string, list of
numbers on which the mathematical expression is to be calculated and return
the result as a list of string.
### Examples
mathematical("f(y)=y+1",[1,2]) ➞ ["f(1)=2","f(2)=3"]
mathematical("f(y)=y^2",[1,2,3]) ➞ ["f(1)=1","f(2)=4","f(3)=9"]
mathematical("f(y)=yx3",[1,2,3]) ➞ ["f(1)=3","f(2)=6","f(3)=9"]
### Notes
* List of numbers are positive integers.
* In the algebraic expression x = `*`
"""
def mathematical(exp, numbers):
answers = []
for num in numbers:
expression = exp.replace('y', str(num))
equation, call = expression.split('=')[1], expression.split('=')[0]
if 'x' in equation:
equation = equation.replace('x', '*')
if '^' in equation:
equation = equation.replace('^', '**')
answers.append('{0}={1:.0f}'.format(call, eval(equation)))
else:
return answers
|
[
"daniel.reich@danielreichs-MacBook-Pro.local"
] |
daniel.reich@danielreichs-MacBook-Pro.local
|
b420a3ada2d2d1084035ded8fedf94fab11c7246
|
6f05f7d5a67b6bb87956a22b988067ec772ba966
|
/data/test/python/c6ac49828b465d81fdafb56e8a05c0177a7ec6c2HelloZigguratApiView.py
|
c6ac49828b465d81fdafb56e8a05c0177a7ec6c2
|
[
"MIT"
] |
permissive
|
harshp8l/deep-learning-lang-detection
|
93b6d24a38081597c610ecf9b1f3b92c7d669be5
|
2a54293181c1c2b1a2b840ddee4d4d80177efb33
|
refs/heads/master
| 2020-04-07T18:07:00.697994
| 2018-11-29T23:21:23
| 2018-11-29T23:21:23
| 158,597,498
| 0
| 0
|
MIT
| 2018-11-21T19:36:42
| 2018-11-21T19:36:41
| null |
UTF-8
|
Python
| false
| false
| 786
|
py
|
# HelloZigguratApiView.py
# (C)2013
# Scott Ernst
from ziggurat.view.api.ApiRouterView import ApiRouterView
#___________________________________________________________________________________________________ HelloZigguratApiView
class HelloZigguratApiView(ApiRouterView):
"""A class for..."""
#===================================================================================================
# C L A S S
#___________________________________________________________________________________________________ __init__
def __init__(self, request, **kwargs):
"""Creates a new instance of HelloZigguratApiView."""
super(HelloZigguratApiView, self).__init__(request, **kwargs)
|
[
"aliostad+github@gmail.com"
] |
aliostad+github@gmail.com
|
4756f1ab9f395d38c2dc002023bc87b08d00c0ce
|
fffda6e06cb979e83db15e9142db7c9994400e2f
|
/language/bert_extraction/steal_bert_qa/utils/evaluate_squad.py
|
ea9eef5d7871c98ee1bf95b0138c2334ed1dfee8
|
[
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] |
permissive
|
ZachT1711/language
|
b48e551555a41bf269cc20f22871a9e4c47aacc9
|
de84080fc8a239a7271aad1d447fcb38a895790b
|
refs/heads/master
| 2023-01-05T21:36:59.194404
| 2020-04-14T17:19:25
| 2020-04-14T17:30:20
| 250,185,870
| 1
| 0
|
Apache-2.0
| 2022-12-23T20:28:38
| 2020-03-26T07:09:01
|
Python
|
UTF-8
|
Python
| false
| false
| 6,410
|
py
|
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# 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.
"""Official evaluation script for version 1.1 of the SQuAD dataset."""
from __future__ import print_function
import collections as cll
import json
import re
import string
import tensorflow.compat.v1 as tf
app = tf.compat.v1.app
flags = tf.flags
gfile = tf.gfile
logging = tf.logging
flags.DEFINE_string('dataset_file', None, 'Dataset file')
flags.DEFINE_string('dataset_file2', None, 'Dataset file #2')
flags.DEFINE_string('prediction_file', None, 'Prediction file')
flags.DEFINE_string('prediction_file2', None, 'Prediction file #2')
FLAGS = flags.FLAGS
def normalize_answer(s):
"""Lower text and remove punctuation, articles and extra whitespace."""
def remove_articles(text):
return re.sub(r'\b(a|an|the)\b', ' ', text)
def white_space_fix(text):
return ' '.join(text.split())
def remove_punc(text):
exclude = set(string.punctuation)
return ''.join(ch for ch in text if ch not in exclude)
def lower(text):
return text.lower()
return white_space_fix(remove_articles(remove_punc(lower(s))))
def f1_score(prediction, ground_truth):
"""Calculate word level F1 score."""
prediction_tokens = normalize_answer(prediction).split()
ground_truth_tokens = normalize_answer(ground_truth).split()
if not prediction_tokens and not ground_truth_tokens:
return 1.0
common = cll.Counter(prediction_tokens) & cll.Counter(ground_truth_tokens)
num_same = sum(common.values())
if num_same == 0:
return 0
precision = 1.0 * num_same / len(prediction_tokens)
recall = 1.0 * num_same / len(ground_truth_tokens)
f1 = (2 * precision * recall) / (precision + recall)
return f1
def f1_score_multiple(predictions):
"""Calculate word level F1 score across multiple predictions."""
all_f1 = []
for i, pred1 in enumerate(predictions[:-1]):
for pred2 in predictions[i + 1:]:
all_f1.append(f1_score(pred1, pred2))
return all_f1
def exact_match_score(prediction, ground_truth):
return normalize_answer(prediction) == normalize_answer(ground_truth)
def metric_max_over_ground_truths(metric_fn, prediction, ground_truths):
scores_for_ground_truths = []
for ground_truth in ground_truths:
score = metric_fn(prediction, ground_truth)
scores_for_ground_truths.append(score)
return max(scores_for_ground_truths)
def evaluate_preds_preds(preds1, preds2):
"""Evaluate word level metrics."""
f1 = exact_match = total = any_match = 0
for qa_id, pred1_str in preds1.items():
total += 1
ground_truths = [pred1_str]
prediction = preds2[qa_id]
exact_match += metric_max_over_ground_truths(exact_match_score, prediction,
ground_truths)
f1_current = metric_max_over_ground_truths(f1_score, prediction,
ground_truths)
if f1_current > 0:
any_match += 1
f1 += f1_current
exact_match = 100.0 * exact_match / total
f1 = 100.0 * f1 / total
any_match = 100.0 * any_match / total
return {'exact_match': exact_match, 'f1': f1, 'any_match': any_match}
def evaluate_dataset_preds(dataset, predictions):
"""Evaluate word level metrics."""
f1 = exact_match = total = 0
for article in dataset:
for paragraph in article['paragraphs']:
for qa in paragraph['qas']:
total += 1
if qa['id'] not in predictions:
message = 'Unanswered question ' + qa['id'] + ' will receive score 0.'
print(message)
continue
ground_truths = [x['text'] for x in qa['answers']]
prediction = predictions[qa['id']]
curr_exact_match = metric_max_over_ground_truths(
exact_match_score, prediction, ground_truths)
exact_match += curr_exact_match
f1 += metric_max_over_ground_truths(f1_score, prediction, ground_truths)
exact_match = 100.0 * exact_match / total
f1 = 100.0 * f1 / total
return {'exact_match': exact_match, 'f1': f1}
def evaluate_dataset_dataset(dataset, dataset2):
"""Evaluate word level metrics."""
f1 = exact_match = total = 0
for article, article2 in zip(dataset, dataset2):
for para, para2 in zip(article['paragraphs'], article2['paragraphs']):
assert para['context'].strip() == para2['context'].strip()
assert len(para['qas']) == len(para2['qas'])
for qa, qa2 in zip(para['qas'], para2['qas']):
total += 1
ground_truths = [x['text'] for x in qa['answers']]
prediction = qa2['answers'][0]['text']
exact_match += metric_max_over_ground_truths(exact_match_score,
prediction, ground_truths)
f1 += metric_max_over_ground_truths(f1_score, prediction, ground_truths)
exact_match = 100.0 * exact_match / total
f1 = 100.0 * f1 / total
return {'exact_match': exact_match, 'f1': f1}
def main(_):
def load_dataset_file(dataset_file):
with gfile.Open(dataset_file) as df:
dataset_json = json.load(df)
data = dataset_json['data']
return data
def load_preds_file(prediction_file):
with gfile.Open(prediction_file) as pf:
preds = json.load(pf)
return preds
if FLAGS.dataset_file and FLAGS.dataset_file2:
dataset1 = load_dataset_file(FLAGS.dataset_file)
dataset2 = load_dataset_file(FLAGS.dataset_file2)
print(json.dumps(evaluate_dataset_dataset(dataset1, dataset2)))
elif FLAGS.prediction_file and FLAGS.prediction_file2:
preds1 = load_preds_file(FLAGS.prediction_file)
preds2 = load_preds_file(FLAGS.prediction_file2)
print(json.dumps(evaluate_preds_preds(preds1, preds2)))
else:
dataset = load_dataset_file(FLAGS.dataset_file)
preds = load_preds_file(FLAGS.prediction_file)
print(json.dumps(evaluate_dataset_preds(dataset, preds)))
if __name__ == '__main__':
app.run(main)
|
[
"kentonl@google.com"
] |
kentonl@google.com
|
d4cd42d3ae31fd16daad07315d0e65f6e0c9b818
|
bf73ff4441577074dee2225ac937fbbbf4e85fef
|
/pplbench/ppls/jags/inference.py
|
a09062be1785a08b5530f7b00494eb586446b37a
|
[
"MIT"
] |
permissive
|
rambam613/pplbench
|
632878a359945fe64cf24489aa7669040727c672
|
d69c652fc882ba50f56eb0cfaa3097d3ede295f9
|
refs/heads/master
| 2023-07-07T02:16:19.384357
| 2021-08-13T08:01:55
| 2021-08-13T08:03:49
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,413
|
py
|
# Copyright(C) Facebook, Inc. and its affiliates. All Rights Reserved.
from typing import Dict, Type, cast
import numpy as np
import pyjags
import xarray as xr
from ..base_ppl_impl import BasePPLImplementation
from ..base_ppl_inference import BasePPLInference
from .base_jags_impl import BaseJagsImplementation
class MCMC(BasePPLInference):
def __init__(
self, impl_class: Type[BasePPLImplementation], model_attrs: Dict
) -> None:
# We always expect a BaseJagsImplementation here
self.impl_class = cast(Type[BaseJagsImplementation], impl_class)
self.impl = self.impl_class(**model_attrs)
def compile(self, seed: int, **compile_args):
# JAGS doesn't have a separate compile step.
# The model construction requires the actual data,
# so everything has to be done under inference.
pass
def infer( # type: ignore
self,
data: xr.Dataset,
iterations: int,
num_warmup: int,
seed: int,
RNG_name: str = "base::Mersenne-Twister",
) -> xr.Dataset:
"""
See https://phoenixnap.dl.sourceforge.net/project/mcmc-jags/Manuals/4.x/jags_user_manual.pdf
for JAGS documentation.
:param data: PPLBench dataset
:param iterations: number of samples to create
:param seed: seed for random number generator
:param adapt: the number of adaptive steps
:param RNG_name: the name of the random number generator
:returns: samples dataset
"""
model = pyjags.Model(
code=self.impl.get_code(),
data=self.impl.format_data_to_jags(data),
chains=1,
adapt=num_warmup,
init={".RNG.seed": seed, ".RNG.name": RNG_name},
)
samples = model.sample(iterations - num_warmup, vars=self.impl.get_vars())
# squeeze out the chain dimension from the samples
for varname in samples.keys():
samples[varname] = samples[varname].squeeze(-1)
samples = self.impl.extract_data_from_jags(samples)
# because jags does not return warm up samples, we need to shift the coordinates
# of the actual samples by num_warmup by padding with NaN
samples = samples.assign_coords(draw=samples.draw + num_warmup)
padding = xr.Dataset(coords={"draw": np.arange(num_warmup)})
return padding.merge(samples)
|
[
"facebook-github-bot@users.noreply.github.com"
] |
facebook-github-bot@users.noreply.github.com
|
1126769601d5e7319ee39abc278621ac96e499fd
|
09e57dd1374713f06b70d7b37a580130d9bbab0d
|
/data/p3BR/R1/benchmark/startCirq357.py
|
5a0f49a2276e3598ae1db658dd2b3b7f1d4f5362
|
[
"BSD-3-Clause"
] |
permissive
|
UCLA-SEAL/QDiff
|
ad53650034897abb5941e74539e3aee8edb600ab
|
d968cbc47fe926b7f88b4adf10490f1edd6f8819
|
refs/heads/main
| 2023-08-05T04:52:24.961998
| 2021-09-19T02:56:16
| 2021-09-19T02:56:16
| 405,159,939
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,236
|
py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 5/15/20 4:49 PM
# @File : grover.py
# qubit number=3
# total number=64
import cirq
import cirq.google as cg
from typing import Optional
import sys
from math import log2
import numpy as np
#thatsNoCode
from cirq.contrib.svg import SVGCircuit
# Symbols for the rotation angles in the QAOA circuit.
def make_circuit(n: int, input_qubit):
c = cirq.Circuit() # circuit begin
c.append(cirq.H.on(input_qubit[0])) # number=1
c.append(cirq.rx(-0.09738937226128368).on(input_qubit[2])) # number=2
c.append(cirq.H.on(input_qubit[1])) # number=33
c.append(cirq.Y.on(input_qubit[2])) # number=56
c.append(cirq.CZ.on(input_qubit[2],input_qubit[1])) # number=34
c.append(cirq.H.on(input_qubit[1])) # number=35
c.append(cirq.H.on(input_qubit[1])) # number=3
c.append(cirq.H.on(input_qubit[0])) # number=45
c.append(cirq.CNOT.on(input_qubit[2],input_qubit[1])) # number=60
c.append(cirq.CZ.on(input_qubit[1],input_qubit[0])) # number=46
c.append(cirq.H.on(input_qubit[0])) # number=47
c.append(cirq.Y.on(input_qubit[1])) # number=15
c.append(cirq.H.on(input_qubit[0])) # number=61
c.append(cirq.CZ.on(input_qubit[1],input_qubit[0])) # number=62
c.append(cirq.H.on(input_qubit[0])) # number=63
c.append(cirq.H.on(input_qubit[1])) # number=19
c.append(cirq.CZ.on(input_qubit[0],input_qubit[1])) # number=20
c.append(cirq.rx(-0.6000441968356504).on(input_qubit[1])) # number=28
c.append(cirq.H.on(input_qubit[1])) # number=21
c.append(cirq.H.on(input_qubit[1])) # number=30
c.append(cirq.CZ.on(input_qubit[0],input_qubit[1])) # number=31
c.append(cirq.H.on(input_qubit[1])) # number=32
c.append(cirq.H.on(input_qubit[1])) # number=57
c.append(cirq.CZ.on(input_qubit[0],input_qubit[1])) # number=58
c.append(cirq.H.on(input_qubit[1])) # number=59
c.append(cirq.CNOT.on(input_qubit[0],input_qubit[1])) # number=51
c.append(cirq.X.on(input_qubit[1])) # number=52
c.append(cirq.CNOT.on(input_qubit[0],input_qubit[1])) # number=53
c.append(cirq.CNOT.on(input_qubit[0],input_qubit[1])) # number=50
c.append(cirq.H.on(input_qubit[2])) # number=29
c.append(cirq.H.on(input_qubit[1])) # number=36
c.append(cirq.CZ.on(input_qubit[0],input_qubit[1])) # number=37
c.append(cirq.Y.on(input_qubit[2])) # number=44
c.append(cirq.H.on(input_qubit[1])) # number=38
c.append(cirq.Z.on(input_qubit[1])) # number=55
c.append(cirq.CNOT.on(input_qubit[0],input_qubit[1])) # number=18
c.append(cirq.Z.on(input_qubit[1])) # number=11
c.append(cirq.rx(-1.1780972450961724).on(input_qubit[2])) # number=54
c.append(cirq.H.on(input_qubit[1])) # number=42
c.append(cirq.H.on(input_qubit[0])) # number=39
c.append(cirq.CZ.on(input_qubit[1],input_qubit[0])) # number=40
c.append(cirq.H.on(input_qubit[0])) # number=41
c.append(cirq.CNOT.on(input_qubit[2],input_qubit[1])) # number=26
c.append(cirq.Y.on(input_qubit[1])) # number=14
c.append(cirq.CNOT.on(input_qubit[1],input_qubit[0])) # number=5
c.append(cirq.X.on(input_qubit[1])) # number=6
c.append(cirq.Z.on(input_qubit[1])) # number=8
c.append(cirq.X.on(input_qubit[1])) # number=7
c.append(cirq.H.on(input_qubit[2])) # number=43
c.append(cirq.rx(-2.42845112122491).on(input_qubit[1])) # number=25
# circuit end
c.append(cirq.measure(*input_qubit, key='result'))
return c
def bitstring(bits):
return ''.join(str(int(b)) for b in bits)
if __name__ == '__main__':
qubit_count = 4
input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)]
circuit = make_circuit(qubit_count,input_qubits)
circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap')
circuit_sample_count =2000
simulator = cirq.Simulator()
result = simulator.run(circuit, repetitions=circuit_sample_count)
frequencies = result.histogram(key='result', fold_func=bitstring)
writefile = open("../data/startCirq357.csv","w+")
print(format(frequencies),file=writefile)
print("results end", file=writefile)
print(circuit.__len__(), file=writefile)
print(circuit,file=writefile)
writefile.close()
|
[
"wangjiyuan123@yeah.net"
] |
wangjiyuan123@yeah.net
|
aeddc1d7fbf8ea26f225c60088dd41b3447c6fbe
|
e00186e71a1f52b394315a0cbc27162254cfffb9
|
/durga/full_durga/without_restm2/without_restm2/asgi.py
|
40491539a6ce4db3dc21ec67f0020d7ead8ce036
|
[] |
no_license
|
anilkumar0470/git_practice
|
cf132eb7970c40d0d032520d43e6d4a1aca90742
|
588e7f654f158e974f9893e5018d3367a0d88eeb
|
refs/heads/master
| 2023-04-27T04:50:14.688534
| 2023-04-22T05:54:21
| 2023-04-22T05:54:21
| 100,364,712
| 0
| 1
| null | 2021-12-08T19:44:58
| 2017-08-15T10:02:33
|
Python
|
UTF-8
|
Python
| false
| false
| 405
|
py
|
"""
ASGI config for without_restm2 project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'without_restm2.settings')
application = get_asgi_application()
|
[
"anilkumar.0466@gmail.com"
] |
anilkumar.0466@gmail.com
|
8def5ea4fa1b536a7d27e5ee746a0d7eef26180f
|
17a655d21d7ddaf8cf60e23055e107cb602bd9bc
|
/project/bookmarker/migrations/0001_initial.py
|
7739e40db601749d17b8b704a596aa005e8e6a15
|
[] |
no_license
|
geofferyj/YouTubeVideoBookmarker
|
fedb6913a8c5118c0a51f011244233630cf6f58c
|
fbf10230c5184cd1479dddafbcfd3609d5ac98f1
|
refs/heads/master
| 2023-08-04T22:30:37.636957
| 2021-03-01T08:09:46
| 2021-03-01T08:09:46
| 278,203,783
| 0
| 0
| null | 2021-09-22T19:46:09
| 2020-07-08T22:05:00
|
JavaScript
|
UTF-8
|
Python
| false
| false
| 4,185
|
py
|
# Generated by Django 3.0.8 on 2020-08-09 19:13
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Video',
fields=[
('vid', models.CharField(max_length=11, primary_key=True, serialize=False)),
('timestamps', models.TextField(default='')),
('cost', models.PositiveIntegerField(default=0)),
('locked', models.BooleanField(default=False)),
('last_editor', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='VoicePause',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('has', models.BooleanField(default=False)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='voice_pause', to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='VideoViews',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='views', to=settings.AUTH_USER_MODEL)),
('video', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='views', to='bookmarker.Video')),
],
),
migrations.CreateModel(
name='UserVideo',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='videos', to=settings.AUTH_USER_MODEL)),
('video', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='users', to='bookmarker.Video')),
],
),
migrations.CreateModel(
name='Token',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('amount', models.PositiveIntegerField(default=0)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='tokens', to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Subscription',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('paid_until', models.DateTimeField(blank=True, null=True)),
('date_paid', models.DateTimeField(auto_now_add=True)),
('paypal_subscription_id', models.CharField(blank=True, max_length=64, null=True)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='subscription', to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='ResetableViews',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('count', models.PositiveIntegerField(default=0)),
('video', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='rviews', to='bookmarker.Video')),
],
),
migrations.AddConstraint(
model_name='videoviews',
constraint=models.UniqueConstraint(fields=('user', 'video'), name='video_views_constraint'),
),
migrations.AddConstraint(
model_name='uservideo',
constraint=models.UniqueConstraint(fields=('user', 'video'), name='user_video_constraint'),
),
]
|
[
"geofferyjoseph1@gmail.com"
] |
geofferyjoseph1@gmail.com
|
6bc8cd61d8967b5a2a2913543f445ebafb4b8904
|
4237d975945a3e8fc427bc2aca6c4df80b668d62
|
/Functions/calc/02-Calc.py
|
bd7491222cfc5a00386914d235508ca25ac8c16b
|
[] |
no_license
|
ravi4all/Python_JuneMorningRegular
|
36af0302af382b1a94cc9efc6af2fa1a099565fa
|
5bd36a4be7579e65fbc862521c01042ca841e3cd
|
refs/heads/master
| 2020-03-20T04:10:32.641007
| 2018-07-03T06:38:41
| 2018-07-03T06:38:41
| 137,173,202
| 0
| 4
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 600
|
py
|
def add(x,y):
result = x + y
print("Addition is",result)
def sub(x,y):
result = x - y
print("Subtraction is", result)
def mul(x,y):
result = x * y
print("Multiplication is", result)
def div(x,y):
result = x / y
print("Division is", result)
print("""
1. Add
2. Sub
3. Mul
4. Div
""")
user_choice = input("Enter your choice : ")
num_1 = int(input("Enter first number : "))
num_2 = int(input("Enter second number : "))
todo = {
'1' : add,
'2' : sub,
'3' : mul,
'4' : div
}
todo.get(user_choice)(num_1, num_2)
|
[
"noreply@github.com"
] |
ravi4all.noreply@github.com
|
f09937e2a6f27c882a55d618d69bc747f10d2e4c
|
11bcf60200aaf63704191205d27b52442a08212b
|
/demo/test_brower.py
|
9deee2f98d69b84e498458899d9c8ffe08a66867
|
[] |
no_license
|
Timothyea/uri_pycharm
|
bf893748cd32a045cbaec34dae3f8dfa3a2605ff
|
a1dbe860ba3bcce460da4dd87ec9aebc43cf3499
|
refs/heads/master
| 2020-09-09T08:47:31.943627
| 2019-11-14T10:04:07
| 2019-11-14T10:04:07
| 221,404,034
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 452
|
py
|
#!/user/bin/env python
# -*- conding:utf-8 -*-
from time import sleep
from selenium import webdriver
# 打开游览器
def test_brower(driver):
driver.get("http://www.baidu.com")
sleep(1)
driver.get("http://www.jd.com")
sleep(1)
driver.back()
sleep(1)
driver.forward()
sleep(1)
driver.refresh()
sleep(1)
# 关闭浏览器,不退出driver
# driver.close()
# 关闭浏览器,退出driver
# driver.quit()
|
[
"you@example.com"
] |
you@example.com
|
5094b9b691ae257e044c3742035823ecc3da2227
|
28ef7c65a5cb1291916c768a0c2468a91770bc12
|
/configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/crowdpose/res152_crowdpose_384x288.py
|
44a5db23c7771256902673f3b8449cd9471b3de7
|
[
"Apache-2.0"
] |
permissive
|
bit-scientist/mmpose
|
57464aae1ca87faf5a4669991ae1ea4347e41900
|
9671a12caf63ae5d15a9bebc66a9a2e7a3ce617e
|
refs/heads/master
| 2023-08-03T17:18:27.413286
| 2021-09-29T03:48:37
| 2021-09-29T03:48:37
| 411,549,076
| 0
| 0
|
Apache-2.0
| 2021-09-29T06:01:27
| 2021-09-29T06:01:26
| null |
UTF-8
|
Python
| false
| false
| 4,087
|
py
|
_base_ = ['../../../../_base_/datasets/crowdpose.py']
log_level = 'INFO'
load_from = None
resume_from = None
dist_params = dict(backend='nccl')
workflow = [('train', 1)]
checkpoint_config = dict(interval=10)
evaluation = dict(interval=10, metric='mAP')
optimizer = dict(
type='Adam',
lr=5e-4,
)
optimizer_config = dict(grad_clip=None)
# learning policy
lr_config = dict(
policy='step',
warmup='linear',
warmup_iters=500,
warmup_ratio=0.001,
step=[170, 200])
total_epochs = 210
log_config = dict(
interval=50,
hooks=[
dict(type='TextLoggerHook'),
# dict(type='TensorboardLoggerHook')
])
channel_cfg = dict(
num_output_channels=14,
dataset_joints=14,
dataset_channel=[
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13],
],
inference_channel=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])
# model settings
model = dict(
type='TopDown',
pretrained='torchvision://resnet152',
backbone=dict(type='ResNet', depth=152),
keypoint_head=dict(
type='TopdownHeatmapSimpleHead',
in_channels=2048,
out_channels=channel_cfg['num_output_channels'],
loss_keypoint=dict(type='JointsMSELoss', use_target_weight=True)),
train_cfg=dict(),
test_cfg=dict(
flip_test=True,
post_process='default',
shift_heatmap=True,
modulate_kernel=11))
data_cfg = dict(
image_size=[288, 384],
heatmap_size=[72, 96],
num_output_channels=channel_cfg['num_output_channels'],
num_joints=channel_cfg['dataset_joints'],
dataset_channel=channel_cfg['dataset_channel'],
inference_channel=channel_cfg['inference_channel'],
crowd_matching=False,
soft_nms=False,
nms_thr=1.0,
oks_thr=0.9,
vis_thr=0.2,
use_gt_bbox=False,
det_bbox_thr=0.0,
bbox_file='data/crowdpose/annotations/'
'det_for_crowd_test_0.1_0.5.json',
)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='TopDownRandomFlip', flip_prob=0.5),
dict(
type='TopDownHalfBodyTransform',
num_joints_half_body=6,
prob_half_body=0.3),
dict(
type='TopDownGetRandomScaleRotation', rot_factor=40, scale_factor=0.5),
dict(type='TopDownAffine'),
dict(type='ToTensor'),
dict(
type='NormalizeTensor',
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]),
dict(type='TopDownGenerateTarget', sigma=3),
dict(
type='Collect',
keys=['img', 'target', 'target_weight'],
meta_keys=[
'image_file', 'joints_3d', 'joints_3d_visible', 'center', 'scale',
'rotation', 'bbox_score', 'flip_pairs'
]),
]
val_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='TopDownAffine'),
dict(type='ToTensor'),
dict(
type='NormalizeTensor',
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]),
dict(
type='Collect',
keys=['img'],
meta_keys=[
'image_file', 'center', 'scale', 'rotation', 'bbox_score',
'flip_pairs'
]),
]
test_pipeline = val_pipeline
data_root = 'data/crowdpose'
data = dict(
samples_per_gpu=64,
workers_per_gpu=2,
val_dataloader=dict(samples_per_gpu=32),
test_dataloader=dict(samples_per_gpu=32),
train=dict(
type='TopDownCrowdPoseDataset',
ann_file=f'{data_root}/annotations/mmpose_crowdpose_trainval.json',
img_prefix=f'{data_root}/images/',
data_cfg=data_cfg,
pipeline=train_pipeline,
dataset_info={{_base_.dataset_info}}),
val=dict(
type='TopDownCrowdPoseDataset',
ann_file=f'{data_root}/annotations/mmpose_crowdpose_test.json',
img_prefix=f'{data_root}/images/',
data_cfg=data_cfg,
pipeline=val_pipeline,
dataset_info={{_base_.dataset_info}}),
test=dict(
type='TopDownCrowdPoseDataset',
ann_file=f'{data_root}/annotations/mmpose_crowdpose_test.json',
img_prefix=f'{data_root}/images/',
data_cfg=data_cfg,
pipeline=test_pipeline))
|
[
"noreply@github.com"
] |
bit-scientist.noreply@github.com
|
f4937a200488f1a80a92b5d267bdd363eb26490d
|
5aec9b30005a8a5cc39da3c46ce65aa3e6710cfe
|
/tools/delete_queues.py
|
d499f5f82945a5b4422e2f65b1c1c2283cca3a81
|
[
"MIT"
] |
permissive
|
cloudworkstation/cloudworkstation-api
|
90d0726e712cd403fdbcd7c2b39ec9f1ee1890ad
|
661500aaaa304db13e99d8365428520c2c77f5dd
|
refs/heads/main
| 2023-04-13T07:54:47.717843
| 2021-04-09T20:09:57
| 2021-04-09T20:09:57
| 338,401,801
| 0
| 0
| null | 2021-04-06T09:05:39
| 2021-02-12T18:35:52
|
Python
|
UTF-8
|
Python
| false
| false
| 393
|
py
|
import boto3
sqs = boto3.client("sqs")
def find_and_remove():
response = sqs.list_queues(
QueueNamePrefix="ec2_",
MaxResults=100
)
if "QueueUrls" in response:
for qurl in response["QueueUrls"]:
print(f"Going to delete queue @ {qurl} ...")
sqs.delete_queue(
QueueUrl=qurl
)
print("...Deleted.")
if __name__ == "__main__":
find_and_remove()
|
[
"richard.kendall@gmail.com"
] |
richard.kendall@gmail.com
|
a0bf6e814b457e88e091de90c86fc61a779dc2b4
|
ff4ca069f16041fd49f7c87216b9fdb5c0a5f658
|
/UITest/Android/DxYcUiTest/Scripts/Clue/ClueCommentJumpTest.py
|
f6c06ce66942e809729d9f6555dc04e9073ee951
|
[] |
no_license
|
ban666/UITestForDx
|
cbaf86cca957d40151ae28e2dc81a3016cf778d4
|
5a3ccdc68651e648e7c838fc58b5a9d052a19f6b
|
refs/heads/master
| 2021-01-12T01:36:06.206477
| 2017-02-17T09:09:27
| 2017-02-17T09:09:36
| 78,408,551
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,137
|
py
|
# -*- coding: utf-8 -*-
__author__ = 'liaoben'
import sys
from appium import webdriver
from time import sleep
import unittest
from random import randint
sys.path.append('../../Lib')
import time
import os
from appium_lib import *
from dx_action import *
from ui_comment import *
from ChnlRequest import ChnlRequest
from DbLib import DbLib
from config import *
from loglib import log
from elements_id import *
from configrw import get_case
from TestlinkHandler import TestlinkHandler
from ui_clue import *
from BaoliaoRequest import BaoliaoRequest
class SubTypeTest(unittest.TestCase):
def setUp(self):
#self.testcases = conf.readcfg(__file__)
self.desired_caps = desired_caps
print 'Test Start...................................'
self.result = 'f'
self.msg = ''
self.tsl = TestlinkHandler()
self.mode = MODE
self.db = DbLib()
self.clue = BaoliaoRequest()
subtype_id = self.clue.get_clue_type()[0]['subtype']
self.clue.send_clue_and_review(u'报料测试'+str(randint(1,100)),1,subtype_id)
self.api = ChnlRequest(MODE)
self.driver = webdriver.Remote(APPIUM_URL, self.desired_caps)
start_to_index(self.driver,self.mode)
def tearDown(self):
print 'Test End...................................'
try:
self.tsl.set_tc_status(self.case_id,self.result,self.msg)
self.driver.quit()
except Exception as e:
print u'测试失败,失败环节:tear down',e
def common_check(self):
step = 1
sleep(WAIT_TIME)
go_to_clue(self.driver)
#subtype_id = self.clue.get_clue_type()[0]['subtype'] #获取第一个栏目的报料类型ID
# current_time = time.strftime( ISOTIMEFORMAT, time.localtime() )
# clue_content = 'test for comment button '+str(current_time)
# self.clue.send_clue(clue_content,subtype_id) #使用接口发送报料
# clue_id = self.db.get_clueid_with_content_by_db(clue_content)
comment_count = get_clue_comment_count(self.driver)
assert int(comment_count) == 0
#点击切换
self.driver.find_element_by_id(CLUE_LIST_COMMENT_BUTTON).click()
assert self.driver.current_activity == ACTIVITY.get('clue')
assert element_exsist(self.driver,'id',CLUE_LIST_DESC)
print u'Step %s:报料无评论时,点击列表中评论按钮进入报料正文页:OK' % (str(step))
step+=1
return True
def comment_jump_check(self):
step = 1
sleep(WAIT_TIME)
subtype_id = self.clue.get_clue_type()[0]['subtype']
clue_id = self.clue.get_clue_list(subtype_id)[0]['cid']
for i in range(50):
self.api.send_comment(clue_id,'test for comment anchor')
go_to_clue(self.driver)
slide_down(self.driver)
comment_count = get_clue_comment_count(self.driver)
assert int(comment_count) != 0
#点击切换
self.driver.find_element_by_id(CLUE_LIST_COMMENT_BUTTON).click()
assert self.driver.current_activity == ACTIVITY.get('clue')
assert element_exsist(self.driver,'id',CLUE_LIST_DESC) == False
print u'Step %s:报料有评论时,点击列表中报料的评论按钮,跳转到评论锚点:OK' % (str(step))
step+=1
return True
#excute TestCase
def test(self):
self.case_id = get_case(__file__)
self.result = self.common_check()
def testCommentJump(self):
self.case_id = get_case(__file__)
self.result = self.comment_jump_check()
if __name__ == '__main__':
pass
# a = TestLogin()
# a.setUp()
# a.testFunc1()
# a.tearDown()
#d =DbLib()
import HTMLTestRunner
t = unittest.TestSuite()
t.addTest(unittest.makeSuite(TestComment))
#unittest.TextTestRunner.run(t)
filename = 'F:\\dx_comment.html'
fp = file(filename,'wb')
runner = HTMLTestRunner.HTMLTestRunner(
stream = fp,
title ='Dx_Test',
description = 'Report_discription')
runner.run(t)
fp.close()
|
[
"ban666@qq.com"
] |
ban666@qq.com
|
aca85ae0f0ade02fa6312a6c4f8e8e7885adb341
|
2a9b3bf8758c1199305a01c524be78b7287335b8
|
/plugins/ga/bidsaspx/riverdale.py
|
2693f804d7cf9e493c147f0583e28a7f4e6ca6c5
|
[] |
no_license
|
thayton/bidmap
|
e222f34701c15d4694f1f51999ecc9d894abfe41
|
de279cd64f66c79b253b38101c8ccdf748e540ac
|
refs/heads/master
| 2021-01-21T17:03:14.317309
| 2014-09-26T18:27:45
| 2014-09-26T18:27:45
| 17,402,509
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 429
|
py
|
from bidmap.bidscrapers.bidsaspx.bidsaspx import BidsAspxBidScraper
GOVINFO = {
'name': 'Riverdale Georgia',
'location': 'Riverdale, GA',
'home_page_url': 'http://ga-riverdale2.civicplus.com',
'bids_page_url': 'http://ga-riverdale2.civicplus.com/bids.aspx'
}
def get_scraper():
return BidsAspxBidScraper(GOVINFO)
if __name__ == '__main__':
bid_scraper = get_scraper()
bid_scraper.scrape_bids()
|
[
"thayton@neekanee.com"
] |
thayton@neekanee.com
|
929f9c62dc239284ea660a83c74694b12e148494
|
2aba62d66c2c622bdc148cef451da76cae5fd76c
|
/exercise/crawler_python_dm1920/ch4/ch4_19.py
|
5dc74250957efd13c6fc8b6557fdcafa5be35fb0
|
[] |
no_license
|
NTUT-109AB8011/crawler
|
6a76de2ab1848ebc8365e071e76c08ca7348be62
|
a703ec741b48d3af615a757fed7607b1f8eb66a6
|
refs/heads/master
| 2023-03-26T22:39:59.527175
| 2021-03-30T03:29:22
| 2021-03-30T03:29:22
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 815
|
py
|
# ch4_19.py
import pandas as pd
import matplotlib.pyplot as plt
cities = {'population':[10000000,8500000,8000000,15000000,6000000,8000000],
'area':[400, 500, 850, 300, 200, 320],
'town':['New York','Chicago','Bangkok','Tokyo',
'Singapore','HongKong']}
tw = pd.DataFrame(cities, columns=['population','area'],index=cities['town'])
fig, ax = plt.subplots()
fig.suptitle("City Statistics")
ax.set_ylabel("Population")
ax.set_xlabel("City")
ax2 = ax.twinx()
ax2.set_ylabel("Area")
tw['population'].plot(ax=ax,rot=90) # 繪製人口數線
tw['area'].plot(ax=ax2, style='g-') # 繪製面積線
ax.legend(loc=1) # 圖例位置在右上
ax2.legend(loc=2) # 圖例位置在左上
plt.show()
|
[
"terranandes@gmail.com"
] |
terranandes@gmail.com
|
a16fd3bc38021a1cbd05f2155ca066692604dadd
|
fb82ff30fba273eb4a30b5b2e1aceef6bd44ef16
|
/labs/lab1/test_something.py
|
d8df569aa211c392b5b3c346276505cba1175110
|
[
"LicenseRef-scancode-public-domain-disclaimer"
] |
permissive
|
jpchauvel/python-tdd-lab
|
f882e7684f2793e70064fd45b09928b56a81521f
|
2a2e0ee4da15e36e809cdded56cffb6e2b97d90f
|
refs/heads/master
| 2021-10-10T12:11:53.765289
| 2013-05-31T00:30:20
| 2013-05-31T00:30:20
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,240
|
py
|
#!/usr/bin/env python
import unittest
from mockito import *
from something import Something, Operand
class SomethingTestCase(unittest.TestCase):
def test_init_should_assign_what(self):
# setup
# action
something = Something("what")
# assert
self.assertTrue("what", something.attribute)
def test_doing_something_should_return_string_something(self):
# setup
something = Something("what")
# action
ret = something.doing_something()
# assert
self.assertTrue("something", ret)
def test_doing_something_should_return_string_something_else(self):
# setup
something = Something(any(unicode))
# action
ret = something.doing_something()
# assert
self.assertTrue("something else", ret)
def test_send_result_should_add_op2_to_op1(self):
# setup
something, op1, op2 = self.getSomething()
# action
something.send_result()
# assert
verify(op1).add(op2)
def test_send_result_should_first_sum_op1_op2_then_send_op1(self):
# setup
something, op1, op2 = self.getSomething()
# action
something.send_result()
# assert
inorder.verify(op1, times=1).add(op2)
inorder.verify(op1, times=2).send()
def test_send_result_should_raise_network_problem_exception_when_op1_is_None(self):
# setup
something, op1, op2 = self.getSomething()
something.op1 = None
# assert
with self.assertRaises(Something.NetworkProblemException):
# action
something.send_result()
def test_send_result_should_execute_catch_handler_when_send_raises_exception(self):
# setup
something, op1, op2 = self.getSomething()
when(op1).send().thenRaise(Operand.AException)
# action
something.send_result()
# assert
verify(op1, times=1).rollback()
def getSomething(self):
op1 = mock()
op2 = mock()
something = Something(any())
something.op1 = op1
something.op2 = op2
return (something, op1, op2)
if __name__ == "__main__":
unittest.main()
|
[
"jchauvel@gmail.com"
] |
jchauvel@gmail.com
|
d78ec5d375a61d39378e1c786f504671a0bcd4d4
|
954c493a9105a464bee744c6c78a6d06bf8d531c
|
/simfoni_task/urls.py
|
c513fe902a316543936fb9ae3266b67fefa3af6b
|
[] |
no_license
|
sandeepsajan0/suppliers-api
|
d235bb1e1e632cbd12e4b39ffb73e6b4be9e22f1
|
5b911471a4e02954296cfd2151f96480052d4a70
|
refs/heads/master
| 2023-02-26T01:57:03.408628
| 2021-01-24T12:39:34
| 2021-01-24T12:39:34
| 332,411,678
| 0
| 0
| null | 2021-01-24T12:12:52
| 2021-01-24T09:38:56
|
Python
|
UTF-8
|
Python
| false
| false
| 1,302
|
py
|
"""simfoni_task URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
from django.conf.urls.static import static
from django.conf import settings
schema_view = get_schema_view(
openapi.Info(title="Supplier Module Backend API DOCS", default_version="v1"),
public=True,
)
urlpatterns = [
path('admin/', admin.site.urls),
path(
"",
schema_view.with_ui("swagger", cache_timeout=0),
name="schema-swagger-ui",
),
path('api/suppliers/', include("suppliers.urls"))
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATICFILES_DIRS)
|
[
"sandeepsajan0@gmail.com"
] |
sandeepsajan0@gmail.com
|
ab9df98e59d1a7e7d0481a0ede26e8090d4cd311
|
e3d6f803beece2ecc2cde8de795fdd20291213ff
|
/nova/api/openstack/compute/views/flavors.py
|
fcdd6fcf4ca4d94a039a3ee90651b0c5c0ac1266
|
[
"Apache-2.0"
] |
permissive
|
panguan737/nova
|
437c1adb81f3e9ef82c28ad957144623db13ba52
|
0d177185a439baa228b42c948cab4e934d6ac7b8
|
refs/heads/main
| 2023-01-07T00:08:44.069599
| 2020-11-01T14:00:42
| 2020-11-01T14:00:42
| 309,332,719
| 0
| 0
|
Apache-2.0
| 2020-11-02T10:17:13
| 2020-11-02T10:17:13
| null |
UTF-8
|
Python
| false
| false
| 6,492
|
py
|
# Copyright 2010-2011 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from nova.api.openstack import api_version_request
from nova.api.openstack import common
from nova.policies import flavor_access as fa_policies
from nova.policies import flavor_rxtx as fr_policies
FLAVOR_DESCRIPTION_MICROVERSION = '2.55'
class ViewBuilder(common.ViewBuilder):
_collection_name = "flavors"
def basic(self, request, flavor, include_description=False,
update_is_public=None, update_rxtx_factor=None):
# update_is_public & update_rxtx_factor are placeholder param
# which are not used in this method as basic() method is used by
# index() (GET /flavors) which does not return those keys in response.
flavor_dict = {
"flavor": {
"id": flavor["flavorid"],
"name": flavor["name"],
"links": self._get_links(request,
flavor["flavorid"],
self._collection_name),
},
}
if include_description:
flavor_dict['flavor']['description'] = flavor.description
return flavor_dict
def show(self, request, flavor, include_description=False,
update_is_public=None, update_rxtx_factor=None):
flavor_dict = {
"flavor": {
"id": flavor["flavorid"],
"name": flavor["name"],
"ram": flavor["memory_mb"],
"disk": flavor["root_gb"],
"swap": flavor["swap"] or "",
"OS-FLV-EXT-DATA:ephemeral": flavor["ephemeral_gb"],
"OS-FLV-DISABLED:disabled": flavor["disabled"],
"vcpus": flavor["vcpus"],
"links": self._get_links(request,
flavor["flavorid"],
self._collection_name),
},
}
if include_description:
flavor_dict['flavor']['description'] = flavor.description
# TODO(gmann): 'update_is_public' & 'update_rxtx_factor' are policies
# checks. Once os-flavor-access & os-flavor-rxtx policies are
# removed, 'os-flavor-access:is_public' and 'rxtx_factor' need to be
# added in response without any check.
# Evaluate the policies when using show method directly.
context = request.environ['nova.context']
if update_is_public is None:
update_is_public = context.can(fa_policies.BASE_POLICY_NAME,
fatal=False)
if update_rxtx_factor is None:
update_rxtx_factor = context.can(fr_policies.BASE_POLICY_NAME,
fatal=False)
if update_is_public:
flavor_dict['flavor'].update({
"os-flavor-access:is_public": flavor['is_public']})
if update_rxtx_factor:
flavor_dict['flavor'].update(
{"rxtx_factor": flavor['rxtx_factor'] or ""})
return flavor_dict
def index(self, request, flavors):
"""Return the 'index' view of flavors."""
coll_name = self._collection_name
include_description = api_version_request.is_supported(
request, FLAVOR_DESCRIPTION_MICROVERSION)
return self._list_view(self.basic, request, flavors, coll_name,
include_description=include_description)
def detail(self, request, flavors):
"""Return the 'detail' view of flavors."""
coll_name = self._collection_name + '/detail'
include_description = api_version_request.is_supported(
request, FLAVOR_DESCRIPTION_MICROVERSION)
context = request.environ['nova.context']
update_is_public = context.can(fa_policies.BASE_POLICY_NAME,
fatal=False)
update_rxtx_factor = context.can(fr_policies.BASE_POLICY_NAME,
fatal=False)
return self._list_view(self.show, request, flavors, coll_name,
include_description=include_description,
update_is_public=update_is_public,
update_rxtx_factor=update_rxtx_factor)
def _list_view(self, func, request, flavors, coll_name,
include_description=False, update_is_public=None,
update_rxtx_factor=None):
"""Provide a view for a list of flavors.
:param func: Function used to format the flavor data
:param request: API request
:param flavors: List of flavors in dictionary format
:param coll_name: Name of collection, used to generate the next link
for a pagination query
:param include_description: If the flavor.description should be
included in the response dict.
:param update_is_public: If the flavor.is_public field should be
included in the response dict.
:param update_rxtx_factor: If the flavor.rxtx_factor field should be
included in the response dict.
:returns: Flavor reply data in dictionary format
"""
flavor_list = [func(request, flavor, include_description,
update_is_public, update_rxtx_factor)["flavor"]
for flavor in flavors]
flavors_links = self._get_collection_links(request,
flavors,
coll_name,
"flavorid")
flavors_dict = dict(flavors=flavor_list)
if flavors_links:
flavors_dict["flavors_links"] = flavors_links
return flavors_dict
|
[
"147360410@qq.com"
] |
147360410@qq.com
|
546d5f3d75b16204af7150c593a018202f289b72
|
dc9b0ea6714c29651cfd8b494862f31f07d85f28
|
/project13_Poem_application_v_1_1/venv/Scripts/easy_install-3.7-script.py
|
3ffe0822b1c606782a31dc123f99a0e6002cc984
|
[] |
no_license
|
Papashanskiy/PythonProjects
|
c228269f0aef1677758cb6e2f1acdfa522da0a02
|
cf999867befa7d8213b2b6675b723f2b9f392fd7
|
refs/heads/master
| 2022-12-12T15:23:56.234339
| 2019-02-10T09:14:56
| 2019-02-10T09:14:56
| 148,336,536
| 0
| 0
| null | 2022-12-08T03:01:04
| 2018-09-11T15:10:44
|
Python
|
WINDOWS-1251
|
Python
| false
| false
| 505
|
py
|
#!C:\Users\Игорь\Desktop\Python\PythonProjects\project13_Poem_application_v_1_1\venv\Scripts\python.exe -x
# EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==39.1.0','console_scripts','easy_install-3.7'
__requires__ = 'setuptools==39.1.0'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('setuptools==39.1.0', 'console_scripts', 'easy_install-3.7')()
)
|
[
"apashanskiy@gmail.com"
] |
apashanskiy@gmail.com
|
7ef8f4ec72f930eb88693061e793ec74b5cc19a3
|
19666396c4d56f4dcd2790b6c8a6b18745767f90
|
/task.py
|
cb5e139ed740c0339e517e50b0c4cff7b318fb27
|
[] |
no_license
|
himdhiman/taskpy
|
5504b461f4ae161cfabc3f552752dd2641eabf6f
|
2d343da545bb20b8c30c8d7d6bde83e241ca5493
|
refs/heads/master
| 2023-03-29T09:07:35.797755
| 2021-04-08T07:05:15
| 2021-04-08T07:05:15
| 355,798,080
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,680
|
py
|
from celery import shared_task
from api import models, serializers
from rest_framework.response import Response
import os
from pathlib import Path
from api.models import Problem, Submission
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
import json
from django.core import serializers as djSerializer
BASE_DIR = Path(__file__).resolve().parent.parent
channel_layer = get_channel_layer()
@shared_task
def runCode(body, uid):
response = serializers.SubmissionSerializer(data = body)
if(response.is_valid()):
inst = response.save()
if(inst.inputGiven != ""):
data = {'id' : inst.id, 'code' : inst.code, 'lang' : inst.language, 'inp' : inst.inputGiven, 'problemId' : inst.problemId}
else:
data = {'id' : inst.id, 'code' : inst.code, 'lang' : inst.language, 'problemId' : inst.problemId}
probId = data['problemId']
totaltc = Problem.objects.get(id = probId).totalTC
tempPath = os.path.join(BASE_DIR, "Codes", str(uid))
os.system(f"mkdir {tempPath}")
inpPath = tempPath+"/"+"input.txt"
os.system(f"touch {inpPath}")
outPath = tempPath+"/"+"output.txt"
os.system(f"touch {outPath}")
logPath = tempPath+"/"+"output.log"
os.system(f"touch {logPath}")
progPath = None
bashPath = tempPath+"/"+"a.out"
if data['lang'] == "CP":
progPath = tempPath+"/"+"main.cpp"
os.system(f"touch {progPath}")
f = open(os.path.join(tempPath, 'main.cpp'), "w")
f.write(data['code'])
f.close()
if data['lang'] == "P3":
progPath = tempPath+"/"+"main.py"
os.system(f"touch {progPath}")
f = open(os.path.join(tempPath, 'main.py'), "w")
f.write(data['code'])
f.close()
isInputGiven = False
if('inp' in data.keys() and data['inp'] != None):
isInputGiven = True
f = open(inpPath, "w")
f.write(data['inp'])
f.close()
os.chdir(tempPath)
if data['lang'] == "CP":
os.system(f'g++ {progPath}')
cnt = 0
if(isInputGiven == False):
for i in range(1, totaltc+1):
isSame = True
inpPath = os.path.join(BASE_DIR, "media", 'TestCases', str(probId), 'input'+str(i)+'.txt')
os.system(f'{bashPath} < {inpPath} > {outPath}')
with open(os.path.join(BASE_DIR, "media", 'TestCases', str(probId), 'output'+str(i)+'.txt')) as f1, open(outPath) as f2:
for line1, line2 in zip(f1, f2):
if line1 != line2:
isSame = False
break
if(isSame):
cnt += 1
async_to_sync(channel_layer.group_send)("user_"+str(uid), {'type': 'sendStatus', 'text' : f"1/{i}/{totaltc}"})
else:
async_to_sync(channel_layer.group_send)("user_"+str(uid), {'type': 'sendStatus', 'text' : f"0/{i}/{totaltc}"})
os.system(f"rm -rf {outPath}")
os.system(f"touch {outPath}")
else:
os.system(f'{bashPath} < {inpPath} > {outPath}')
os.system(f'g++ {progPath} 2> {logPath}')
if data['lang'] == "P3":
if(isInputGiven == False):
for i in range(1, totaltc+1):
isSame = True
inpPath = os.path.join(BASE_DIR, "media", 'TestCases', str(probId), 'input'+str(i)+'.txt')
os.system(f'python main.py < {inpPath} > {outPath}')
with open(os.path.join(BASE_DIR, "media", 'TestCases', str(probId), 'output'+str(i)+'.txt')) as f1, open(outPath) as f2:
for line1, line2 in zip(f1, f2):
if line1 != line2:
isSame = False
break
if(isSame):
cnt += 1
async_to_sync(channel_layer.group_send)("user_"+str(uid), {'type': 'sendStatus', 'text' : f"1/{i}/{totaltc}"})
else:
async_to_sync(channel_layer.group_send)("user_"+str(uid), {'type': 'sendStatus', 'text' : f"0/{i}/{totaltc}"})
os.system(f"rm -rf {outPath}")
os.system(f"touch {outPath}")
else:
os.system('python main.py < input.txt > output.txt 2>"output.log"')
os.chdir(BASE_DIR)
out = open(os.path.join(tempPath, 'output.txt'), "r")
code_output = out.read()
out.close()
os.system(f"rm -rf {inpPath}")
os.system(f"touch {inpPath}")
tcString = str(cnt) + "/" + str(totaltc)
if os.stat(os.path.join(tempPath, "output.log")).st_size != 0:
f = open(os.path.join(tempPath, "output.log"), "r")
error = f.read()
f.close()
os.system(f"rm -rf {tempPath}")
Submission.objects.filter(pk = data['id']).update(error = error, status = "CE", testCasesPassed = tcString)
else:
os.system(f"rm -rf {tempPath}")
Submission.objects.filter(pk = data['id']).update(outputGen = code_output, status = "AC", testCasesPassed = tcString)
response = models.Submission.objects.filter(id = inst.id)
async_to_sync(channel_layer.group_send)("user_"+str(uid), {'type': 'sendResult', 'text' : djSerializer.serialize('json', response)})
|
[
"himanshudhiman9313@gmail.com"
] |
himanshudhiman9313@gmail.com
|
516fe6d919ac4f281d58d62191e17b1d1b0915db
|
45f7a9b44ea1c45448703707da793d51151c0527
|
/ui_tests/examples/examples_03.py
|
6cbe239e09666abb076794312777347c51028740
|
[] |
no_license
|
basdijkstra/python-for-testers
|
a40d30432c31712c6d0eadbca9de73056ff10535
|
50bfbabfb2b8426eed8d048b0448959c34f71b61
|
refs/heads/master
| 2023-05-24T18:48:58.557924
| 2023-05-23T05:44:11
| 2023-05-23T05:44:11
| 219,865,075
| 7
| 4
| null | 2023-05-23T05:44:13
| 2019-11-05T22:47:09
|
Python
|
UTF-8
|
Python
| false
| false
| 1,047
|
py
|
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
import pytest
@pytest.fixture
def browser():
driver = webdriver.Chrome()
driver.maximize_window()
yield driver
driver.quit()
def test_successful_google_search(browser):
browser.get("https://www.google.com")
send_keys(browser, By.NAME, "q", "Maserati")
click(browser, By.NAME, "btnK")
assert browser.title == "Maserati - Google zoeken"
assert browser.find_element_by_id("resultStats").is_displayed() is True
def send_keys(driver, locator_strategy, locator, text_to_type):
element = WebDriverWait(driver, 10).until(
ec.element_to_be_clickable((locator_strategy, locator))
)
element.send_keys(text_to_type)
def click(driver, locator_strategy, locator):
element = WebDriverWait(driver, 10).until(
ec.element_to_be_clickable((locator_strategy, locator))
)
element.click()
|
[
"bas@ontestautomation.com"
] |
bas@ontestautomation.com
|
ec2cadeb66e67d4e79bc5fd3c5442916d74ec88b
|
fa0eac5b96fc46ebf8e31a7ccd7fa39f2e200bfc
|
/backend/home/migrations/0002_load_initial_data.py
|
95b530a428d8a00e98272abc6771579b60ad009f
|
[] |
no_license
|
crowdbotics-apps/mobile-7-dec-dev-16399
|
be33b8eb17957c9b8a75b3d089114631f27b9109
|
ab2cbc3e11dfbf709883b3cf49f4be109d779028
|
refs/heads/master
| 2023-06-27T20:39:09.405282
| 2020-12-07T11:38:48
| 2020-12-07T11:38:48
| 319,207,493
| 0
| 0
| null | 2021-08-03T20:05:57
| 2020-12-07T04:51:46
|
JavaScript
|
UTF-8
|
Python
| false
| false
| 1,306
|
py
|
from django.db import migrations
def create_customtext(apps, schema_editor):
CustomText = apps.get_model("home", "CustomText")
customtext_title = "mobile 7 dec"
CustomText.objects.create(title=customtext_title)
def create_homepage(apps, schema_editor):
HomePage = apps.get_model("home", "HomePage")
homepage_body = """
<h1 class="display-4 text-center">mobile 7 dec</h1>
<p class="lead">
This is the sample application created and deployed from the Crowdbotics app.
You can view list of packages selected for this application below.
</p>"""
HomePage.objects.create(body=homepage_body)
def create_site(apps, schema_editor):
Site = apps.get_model("sites", "Site")
custom_domain = "mobile-7-dec-dev-16399.botics.co"
site_params = {
"name": "mobile 7 dec",
}
if custom_domain:
site_params["domain"] = custom_domain
Site.objects.update_or_create(defaults=site_params, id=1)
class Migration(migrations.Migration):
dependencies = [
("home", "0001_initial"),
("sites", "0002_alter_domain_unique"),
]
operations = [
migrations.RunPython(create_customtext),
migrations.RunPython(create_homepage),
migrations.RunPython(create_site),
]
|
[
"team@crowdbotics.com"
] |
team@crowdbotics.com
|
6ff9ff95fefbaa276dd64e822f01857ee7a656b9
|
11aaeaeb55d587a950456fd1480063e1aed1d9e5
|
/.history/ex45-test_20190608162053.py
|
ead3b46f62d91c9428c264a9f24afe6a0e5ba598
|
[] |
no_license
|
Gr4cchus/Learn-Python-3-The-Hard-Way
|
8ce9e68f6a91ea33ea45fe64bfff82d65422c4a8
|
f5fa34db16cdd6377faa7fcf45c70f94bb4aec0d
|
refs/heads/master
| 2020-05-17T23:18:29.483160
| 2019-06-26T18:42:52
| 2019-06-26T18:42:52
| 184,023,439
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 363
|
py
|
class Room1():
def enter():
print("You enter room 1")
class Room2():
def enter():
print("You enter room 2")
class Map():
def __init__(self, starting_room)
self.starting_room = starting_room
self.locations = {
'room1': Room1(),
'room2': Room2()
}
start = Map('room1')
start
|
[
"ahivent@gmail.com"
] |
ahivent@gmail.com
|
83d0a74593c54ec76d33cb5485a9903692decdc3
|
0de5810c702046d8f00c8bcda8543c66f608222f
|
/venv/bin/tor-prompt
|
d17b63310b066687ee943f2ad5db6d165708806a
|
[] |
no_license
|
Subhash1998/product_sale
|
26a688869009035e785791cac1fb2707cab1e221
|
a76f9e75ea1d96832d9280b98da08d0b3c6520fe
|
refs/heads/master
| 2022-12-12T12:13:37.392530
| 2020-06-18T12:46:45
| 2020-06-18T12:46:45
| 128,992,642
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 217
|
#!/home/subhash/payment/venv/bin/python
# Copyright 2014-2017, Damian Johnson and The Tor Project
# See LICENSE for licensing information
import stem.interpreter
if __name__ == '__main__':
stem.interpreter.main()
|
[
"you@example.com"
] |
you@example.com
|
|
c3182071b0e894204d18f4939e191f802569f245
|
c1d68638ccff1d72dd04e4f85bedf5b3146d1c7e
|
/site-packages/PytoClasses.py
|
f61abae06651d5db273c0bf55b7b660deab90c81
|
[
"MIT"
] |
permissive
|
luoyu1993/Pyto
|
ac61f296756a0df9131e50a203cb31efd261b843
|
4f874e0b9203ae8dc0cd447b599358d726c98f10
|
refs/heads/master
| 2022-07-26T10:44:58.987630
| 2018-12-09T19:05:41
| 2018-12-09T19:05:41
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 702
|
py
|
# -*- coding: utf-8 -*-
"""
This module contains classes from the main app used by Pyto.
This module is only for private use. Use the `pyto` API instead.
"""
from rubicon.objc import *
NSBundle = ObjCClass("NSBundle")
def __Class__(name):
return ObjCClass("Pyto."+name)
PyMainThread = __Class__("PyMainThread")
PyThread = __Class__("PyThread")
PyInputHelper = __Class__("PyInputHelper")
PyOutputHelper = __Class__("PyOutputHelper")
PySharingHelper = __Class__("PySharingHelper")
FilePicker = __Class__("PyFilePicker")
Alert = __Class__("PyAlert")
PyContentViewController = __Class__("PyContentViewController")
PyExtensionContext = __Class__("PyExtensionContext")
Python = __Class__("Python")
|
[
"adrilabbelol@gmail.com"
] |
adrilabbelol@gmail.com
|
57a0faa230f7260f44d5ae7dbf3ff16be5f6ad0f
|
5b3bd326998606188b45a7870852643eda024a97
|
/meta_architectures/context_rcnn_lib_tf2.py
|
4989db07136dc450d1fa5058e58e27365b79dd29
|
[] |
no_license
|
KuznetsovIllya/clearml_od_toy
|
31556d0726d15a054c1c18317c361d97801381a4
|
92f15f04a023d4e0e165a250fddc3129144913d0
|
refs/heads/main
| 2023-04-11T05:55:56.248478
| 2021-04-14T15:59:40
| 2021-04-14T15:59:40
| 357,827,336
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 129
|
py
|
version https://git-lfs.github.com/spec/v1
oid sha256:2ba0224b6fe0f919228a83b2f2a2bef6bbff4e7f747358231bdc235456d58197
size 9287
|
[
"illia.kuznietsov@modern-expo.com"
] |
illia.kuznietsov@modern-expo.com
|
d62122698bcb4a6081b643082fd8fb9a2df8278c
|
7b6377050fba4d30f00e9fb5d56dfacb22d388e1
|
/pqu/Check/t07.py
|
e3c5cacee7c2ca293bce9a269a6a1976e4be1703
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
LLNL/fudge
|
0a4fe8e3a68b66d58e42d1f4d209ea3f713c6370
|
6ba80855ae47cb32c37f635d065b228fadb03412
|
refs/heads/master
| 2023-08-16T21:05:31.111098
| 2023-08-01T22:09:32
| 2023-08-01T22:09:32
| 203,678,373
| 21
| 4
|
NOASSERTION
| 2023-06-28T20:51:02
| 2019-08-21T23:22:20
|
Python
|
UTF-8
|
Python
| false
| false
| 972
|
py
|
# <<BEGIN-copyright>>
# Copyright 2022, Lawrence Livermore National Security, LLC.
# See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: BSD-3-Clause
# <<END-copyright>>
import sys
sys.path.insert( 0, '../../' )
from pqu.PQU import PQU
print()
a2 = PQU( "2.300000000000(1) MeV" )
print(a2)
print(a2.info( significantDigits = 15 ))
a2 = PQU( "2.300000000001(1) MeV" )
print(a2)
print(a2.info( significantDigits = 15 ))
print()
a2 = PQU( "2.300000000003(1)", "MeV" )
print(a2)
print(a2.info( significantDigits = 15 ))
print()
l = PQU( 10., 'm' )
big_l = PQU( 10., 'km' )
sum_l = big_l + l
print(sum_l)
print(l.info( significantDigits = 15 ))
print(big_l.info( significantDigits = 15 ))
print(sum_l.info( significantDigits = 15 ))
print()
E = PQU( 1000, 'MeV/c**2' ) # This is similar to the prior one.
print(E)
print(E.info( significantDigits = 15 ))
kg = E.inUnitsOf( 'kg' )
print(kg)
print(kg.info( significantDigits = 15 ))
|
[
"mattoon1@llnl.gov"
] |
mattoon1@llnl.gov
|
6f6d4de96ca0a1c2543a30b808a0d01e7cebf842
|
7b0f8e5e3dd02f47096bc35322063c7581f95aca
|
/chapter12/avazu_ctr/future_selection.py
|
51daffbfe3d66f4915cfa3d050b08282ce2e8a3f
|
[] |
no_license
|
michaelliu03/Search-Recommend-InAction
|
94f8342573fffa0016bc6b66b0100a81423e5438
|
06408c9a4ec23aad0e604267903be96cb2892ea1
|
refs/heads/master
| 2022-02-25T21:57:56.445082
| 2022-02-17T10:45:15
| 2022-02-17T10:45:15
| 226,252,089
| 40
| 17
| null | 2022-01-10T09:53:50
| 2019-12-06T05:24:50
|
Python
|
UTF-8
|
Python
| false
| false
| 3,906
|
py
|
#!/usr/bin/env python
#-*-coding:utf-8-*-
# @File:future_selection.py
# @Author: Michael.liu
# @Date:2020/6/4 17:49
# @Desc: this code is ....
import pandas as pd
import numpy as np
import xgboost as xgb
from xgboost.sklearn import XGBClassifier
from sklearn.metrics import accuracy_score
from sklearn.metrics import roc_auc_score
from sklearn.metrics import log_loss
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
from xgboost import plot_importance
def xgboost_selection_future():
train = pd.read_csv('tr_FE.csv')
y_train = train.click
X_train = train.drop(['click', 'device_ip', 'Unnamed: 0'], axis=1)
cv_params = {'n_estimators': [400, 500, 600, 700, 800]}
other_params ={'learning_rate': 0.1,
'n_estimators': 500,
'max_depth': 5,
'min_child_weight': 1,
'seed': 0,
'subsample': 0.8,
'objective': 'binary:logistic',
'colsample_bytree': 0.8,
'gamma': 0,
}
model = xgb.XGBClassifier(**other_params)
optimized_GBM = GridSearchCV(estimator=model, param_grid=cv_params, scoring='neg_log_loss', cv=5, verbose=1,
n_jobs=4)
optimized_GBM.fit(X_train, y_train)
evalute_result = optimized_GBM.grid_scores_
print('每轮迭代运行结果:{0}'.format(evalute_result))
print('参数的最佳取值:{0}'.format(optimized_GBM.best_params_))
print('最佳模型得分:{0}'.format(optimized_GBM.best_score_))
def modelfit(alg, dtrain, predictors, useTrainCV=True, cv_folds=5, early_stopping_rounds=50):
if useTrainCV:
xgb_param = alg.get_xgb_params() # 参数
xgtrain = xgb.DMatrix(dtrain[predictors].values, label=dtrain[target].values) # 训练集数据与标签
cvresult = xgb.cv(xgb_param, xgtrain, num_boost_round=alg.get_params()['n_estimators'], nfold=cv_folds,
metrics='auc', early_stopping_rounds=early_stopping_rounds, show_progress=False)
alg.set_params(n_estimators=cvresult.shape[0])
alg.fit(dtrain[predictors], dtrain['Disbursed'], eval_metric='auc')
# Predict training set:
dtrain_predictions = alg.predict(dtrain[predictors])
dtrain_predprob = alg.predict_proba(dtrain[predictors])[:, 1]
# Print model report:
print("Model Report")
# print("Accuracy : %.4g" % accuracy_score(dtrain['Disbursed'].values, dtrain_predictions))
# print("AUC Score (Train): %f" % roc_auc_score(dtrain['Disbursed'], dtrain_predprob))
feat_imp = pd.Series(alg.booster().get_fscore()).sort_values(ascending=False)
feat_imp.plot(kind='bar', title='Feature Importances')
plt.ylabel('Feature Importance Score')
def future_important():
train = pd.read_csv("tr_FE.csv")
# test = pd.read_csv("tr_FE.csv")
#features = pd.read_csv('feature.csv')
y_train = train.click
X_train = train.drop(['click'], axis=1)
model = xgb.XGBRegressor(n_estimators=350, max_depth=10, objective='binary:logistic', min_child_weight=50,
subsample=0.8, gamma=0, learning_rate=0.2, colsample_bytree=0.5, seed=27)
model.fit(X_train, y_train)
# y_test = model.predict(X_test)
plot_importance(model, importance_type="gain")
features = X_train.columns
feature_importance_values = model.feature_importances_
feature_importances = pd.DataFrame({'feature': list(features), 'importance': feature_importance_values})
feature_importances.sort_values('importance', inplace=True, ascending=False)
print(feature_importances)
# print(model.get_booster().get_fscore())
print(model.get_booster().get_score(importance_type="gain"))
feature_importances.to_csv('feature.csv')
if __name__ == '__main__':
print("start......")
xgboost_selection_future()
print(">>>>>>>>end")
|
[
"liuyu5@liepin.com"
] |
liuyu5@liepin.com
|
325ef11b155fbaa8e4e993bad295a14bd10f0da1
|
163bbb4e0920dedd5941e3edfb2d8706ba75627d
|
/Code/CodeRecords/2698/60825/298860.py
|
fabee180d1ca0e439e1ce0a2a785aa0d0d867e9a
|
[] |
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
| 345
|
py
|
t=""
while True:
try:
ts=input()
t+=ts
except:
break
if t=='2 2':
print(3, end='')
elif t=='3 5':
print(58871587162270592645034001, end='')
elif t=='2 3':
print(21, end='')
elif t.startswith('2 4'):
print(651, end='')
elif t.startswith('4 3'):
print(83505, end='')
else:
print(t)
|
[
"1069583789@qq.com"
] |
1069583789@qq.com
|
f769efd583a1443d13ef6822ba32e7143583ca0e
|
e909e9bb4b2e54bb64d6bee9cf9fbaf14c584e04
|
/malib/rpc/data/data_client.py
|
9f234eee232e8402b6f1b1d21719a6bc1572db22
|
[
"MIT"
] |
permissive
|
zhihaolyu/malib
|
9cd8fdcdc1c613c11fc1e6f385adac5312474509
|
1c7ca1819325796a6ec604aa1ae8c771708fc50c
|
refs/heads/main
| 2023-05-13T03:41:05.211832
| 2021-06-08T04:35:10
| 2021-06-08T04:35:10
| 374,880,657
| 0
| 0
|
MIT
| 2021-06-08T04:29:26
| 2021-06-08T04:29:25
| null |
UTF-8
|
Python
| false
| false
| 385
|
py
|
import grpc
import sys
sys.path.append("..")
from ..proto import data_pb2_grpc, data_pb2
def send(server_port, **kargs):
with grpc.insecure_channel(server_port) as channel:
stub = data_pb2_grpc.DataRPCStub(channel)
pr = data_pb2.PullRequest(
type=kargs["tid"], schema_id=kargs["sid"], instance_id=kargs["iid"]
)
data = stub.Pull(pr)
|
[
"kornbergfresnel@outlook.com"
] |
kornbergfresnel@outlook.com
|
d5e9da7158d1d9e5da3315f240ce40a568384534
|
be0f3dfbaa2fa3d8bbe59229aef3212d032e7dd1
|
/Gauss_v45r10p1/Gen/DecFiles/options/13114025.py
|
94da046c51675f492cbb850c1728133a7ed747e7
|
[] |
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,779
|
py
|
# file /home/hep/ss4314/cmtuser/Gauss_v45r10p1/Gen/DecFiles/options/13114025.py generated: Wed, 25 Jan 2017 15:25:30
#
# Event Type: 13114025
#
# ASCII decay Descriptor: [B_s0 -> (phi(1020) -> mu+ mu-) mu+ mu-]cc
#
from Configurables import Generation
Generation().EventType = 13114025
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/Bs_phimumu,mm=MS,DecProdCut.dec"
Generation().SignalRepeatedHadronization.CutTool = "DaughtersInLHCb"
Generation().SignalRepeatedHadronization.SignalPIDList = [ 531,-531 ]
# Ad-hoc particle gun code
from Configurables import ParticleGun
pgun = ParticleGun("ParticleGun")
pgun.SignalPdgCode = 531
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 = [ 531,-531 ]
pgun.MomentumSpectrum.InputFile = "$PGUNSDATAROOT/data/Ebeam4000GeV/MomentumSpectrum_531.root"
pgun.MomentumSpectrum.BinningVariables = "pteta"
pgun.MomentumSpectrum.HistogramPath = "h_pteta"
from Configurables import BeamSpotSmearVertex
pgun.addTool(BeamSpotSmearVertex, name="BeamSpotSmearVertex")
pgun.VertexSmearingTool = "BeamSpotSmearVertex"
pgun.EventType = 13114025
|
[
"slavomirastefkova@b2pcx39016.desy.de"
] |
slavomirastefkova@b2pcx39016.desy.de
|
2e32069c83261894997d74d96a146dafe51ebab7
|
4a89841fa3a73a6826d47d1e66f965759335118b
|
/askbot-devel-master/askbot/management/commands/send_unanswered_question_reminders.py
|
42ce51196170a8a2bd64d75309e60f36b0ad5fb4
|
[] |
no_license
|
liyonghelpme/askbotDataWriter
|
38e2515712a8a6f9db45ce69ba21d36fd1e2dcc9
|
f88d343f8fd699b2d55b94d6dff4edda8e352301
|
refs/heads/master
| 2021-01-22T10:08:01.173519
| 2013-07-19T07:12:35
| 2013-07-19T07:12:35
| 11,522,328
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,901
|
py
|
from django.core.management.base import NoArgsCommand
from django.template.loader import get_template
from askbot import models
from askbot import const
from askbot.conf import settings as askbot_settings
from django.utils.translation import ungettext
from askbot import mail
from askbot.utils.classes import ReminderSchedule
from askbot.models.question import Thread
from askbot.utils.html import site_url
from django.template import Context
DEBUG_THIS_COMMAND = False
class Command(NoArgsCommand):
"""management command that sends reminders
about unanswered questions to all users
"""
def handle_noargs(self, **options):
if askbot_settings.ENABLE_EMAIL_ALERTS == False:
return
if askbot_settings.ENABLE_UNANSWERED_REMINDERS == False:
return
#get questions without answers, excluding closed and deleted
#order it by descending added_at date
schedule = ReminderSchedule(
askbot_settings.DAYS_BEFORE_SENDING_UNANSWERED_REMINDER,
askbot_settings.UNANSWERED_REMINDER_FREQUENCY,
max_reminders = askbot_settings.MAX_UNANSWERED_REMINDERS
)
questions = models.Post.objects.get_questions().exclude(
thread__closed = True
).exclude(
deleted = True
).added_between(
start = schedule.start_cutoff_date,
end = schedule.end_cutoff_date
).filter(
thread__answer_count = 0
).order_by('-added_at')
#for all users, excluding blocked
#for each user, select a tag filtered subset
#format the email reminder and send it
for user in models.User.objects.exclude(status = 'b'):
user_questions = questions.exclude(author = user)
user_questions = user.get_tag_filtered_questions(user_questions)
if askbot_settings.GROUPS_ENABLED:
user_groups = user.get_groups()
user_questions = user_questions.filter(groups__in = user_groups)
final_question_list = user_questions.get_questions_needing_reminder(
user = user,
activity_type = const.TYPE_ACTIVITY_UNANSWERED_REMINDER_SENT,
recurrence_delay = schedule.recurrence_delay
)
question_count = len(final_question_list)
if question_count == 0:
continue
threads = Thread.objects.filter(id__in=[qq.thread_id for qq in final_question_list])
tag_summary = Thread.objects.get_tag_summary_from_threads(threads)
subject_line = ungettext(
'%(question_count)d unanswered question about %(topics)s',
'%(question_count)d unanswered questions about %(topics)s',
question_count
) % {
'question_count': question_count,
'topics': tag_summary
}
data = {
'site_url': site_url(''),
'questions': final_question_list,
'subject_line': subject_line
}
template = get_template('email/unanswered_question_reminder.html')
body_text = template.render(Context(data))#todo: set lang
if DEBUG_THIS_COMMAND:
print "User: %s<br>\nSubject:%s<br>\nText: %s<br>\n" % \
(user.email, subject_line, body_text)
else:
mail.send_mail(
subject_line = subject_line,
body_text = body_text,
recipient_list = (user.email,)
)
|
[
"liyonghelpme@gmail.com"
] |
liyonghelpme@gmail.com
|
95217192c353378d62e5bf472e9fe7efb3b4f83e
|
d4f9d104479b6f9a64175a3fe8554860bf0d62b2
|
/popular_words.py
|
77bfe82384de8cab45193f40caf3c730eae4076c
|
[] |
no_license
|
pohily/checkio
|
9a09c9c52b4f07438cfe4e00914e8d1cfe844c5d
|
8a0a49126af6e09b9e5e6067f28efbf085cd87f6
|
refs/heads/master
| 2020-05-16T03:18:18.068186
| 2019-07-06T13:22:20
| 2019-07-06T13:22:20
| 182,674,736
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,259
|
py
|
def popular_words(text: str, words: list) -> dict:
# your code here
text = text.lower()
result = {}
for word in words:
text1 = text
count = 0
while text1:
if word not in text1:
break
found = text1.index(word)
if found != 0:
m = text1[found-1]
if m != ' ' and m != '\n':
text1 = text1[(found + len(word)):]
continue
text1 = text1[(found + len(word)):]
if not text1:
count += 1
break
if text1[0] == " " or text1[0] == "\n" or text1[0] == ',' or text1[0] == '.':
count += 1
if word not in text1:
break
result[word] = count
return result
print(popular_words('''
And the Raven never flitting still is sitting still is sitting
On the pallid bust of Pallas just above my chamber door
And his eyes have all the seeming of a demon’s that is dreaming
And the lamp-light o’er him streaming throws his shadow on the floor
And my soul from out that shadow that lies floating on the floor
Shall be lifted nevermore
''', ["raven","still","is","floor","nevermore"]))
|
[
"mpohily@gmail.com"
] |
mpohily@gmail.com
|
8efe74872adef5632364a95d1cc58619fe6392aa
|
9dded9364d7a5dd969c7ebb3026c884c8bd3053f
|
/AUDIOCATE/APP/migrations/0007_bookmar.py
|
3f48ecfe06144f2fa60f1fab68e12ab87a7f095c
|
[] |
no_license
|
ehizman/AUDIOCATE
|
5a45828b3e1c6de16826e45195e68b8b0e08ab25
|
edbd7677025d4a431240bf253966d11658e7652d
|
refs/heads/master
| 2023-01-31T03:48:05.645443
| 2020-12-16T02:31:02
| 2020-12-16T02:31:02
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 551
|
py
|
# Generated by Django 2.2.4 on 2020-12-14 01:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('APP', '0006_explore_date'),
]
operations = [
migrations.CreateModel(
name='Bookmar',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.TextField()),
('link', models.CharField(max_length=225)),
],
),
]
|
[
"chukslord1@gmail.com"
] |
chukslord1@gmail.com
|
aed9d8a521f0e1c53b73413d7f5f5d17712daaff
|
478a4a0495fafc62000dc53cef749b87b7a9be55
|
/virtual/bin/pip3
|
95352667bd7817eab73dd4a6da56bdc610064dcd
|
[] |
no_license
|
DavidNganga/simple-error
|
696a0f9e6482b38c5670b5d618120a9220b7fcaf
|
351c5ace3c1487570d19ee0b5e0ade70d40f1b1c
|
refs/heads/master
| 2020-03-18T23:38:56.974235
| 2018-06-03T15:30:48
| 2018-06-03T15:30:48
| 135,416,314
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 235
|
#!/home/david/simple-error/virtual/bin/python3.6
# -*- coding: utf-8 -*-
import re
import sys
from pip import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(main())
|
[
"ngashiedavid@gmail.com"
] |
ngashiedavid@gmail.com
|
|
6451035e29061d208fd1945893c984c0c86d26a1
|
cc5a3fa80d2ae90afc2626e4a82b9a927726dfa0
|
/huaweicloud-sdk-frs/huaweicloudsdkfrs/v2/model/add_faces_by_url_response.py
|
a0b5174b327a3d9e652b2d8df2e8c1d453bf59e8
|
[
"Apache-2.0"
] |
permissive
|
Logan118/huaweicloud-sdk-python-v3
|
eca15e9b08bdccef7122e40735d444ddc958efa8
|
bb230c03bd00225b9f5780a56adce596e9456420
|
refs/heads/master
| 2023-07-17T14:57:50.799564
| 2021-08-25T10:40:43
| 2021-08-25T10:40:43
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,991
|
py
|
# coding: utf-8
import re
import six
from huaweicloudsdkcore.sdk_response import SdkResponse
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class AddFacesByUrlResponse(SdkResponse):
"""
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 = {
'face_set_id': 'str',
'face_set_name': 'str',
'faces': 'list[FaceSetFace]'
}
attribute_map = {
'face_set_id': 'face_set_id',
'face_set_name': 'face_set_name',
'faces': 'faces'
}
def __init__(self, face_set_id=None, face_set_name=None, faces=None):
"""AddFacesByUrlResponse - a model defined in huaweicloud sdk"""
super(AddFacesByUrlResponse, self).__init__()
self._face_set_id = None
self._face_set_name = None
self._faces = None
self.discriminator = None
if face_set_id is not None:
self.face_set_id = face_set_id
if face_set_name is not None:
self.face_set_name = face_set_name
if faces is not None:
self.faces = faces
@property
def face_set_id(self):
"""Gets the face_set_id of this AddFacesByUrlResponse.
人脸库ID。 调用失败时无此字段。
:return: The face_set_id of this AddFacesByUrlResponse.
:rtype: str
"""
return self._face_set_id
@face_set_id.setter
def face_set_id(self, face_set_id):
"""Sets the face_set_id of this AddFacesByUrlResponse.
人脸库ID。 调用失败时无此字段。
:param face_set_id: The face_set_id of this AddFacesByUrlResponse.
:type: str
"""
self._face_set_id = face_set_id
@property
def face_set_name(self):
"""Gets the face_set_name of this AddFacesByUrlResponse.
人脸库名称。 调用失败时无此字段。
:return: The face_set_name of this AddFacesByUrlResponse.
:rtype: str
"""
return self._face_set_name
@face_set_name.setter
def face_set_name(self, face_set_name):
"""Sets the face_set_name of this AddFacesByUrlResponse.
人脸库名称。 调用失败时无此字段。
:param face_set_name: The face_set_name of this AddFacesByUrlResponse.
:type: str
"""
self._face_set_name = face_set_name
@property
def faces(self):
"""Gets the faces of this AddFacesByUrlResponse.
人脸库当中的人脸结构,详见[FaceSetFace](zh-cn_topic_0106912070.xml)。 调用失败时无此字段。
:return: The faces of this AddFacesByUrlResponse.
:rtype: list[FaceSetFace]
"""
return self._faces
@faces.setter
def faces(self, faces):
"""Sets the faces of this AddFacesByUrlResponse.
人脸库当中的人脸结构,详见[FaceSetFace](zh-cn_topic_0106912070.xml)。 调用失败时无此字段。
:param faces: The faces of this AddFacesByUrlResponse.
:type: list[FaceSetFace]
"""
self._faces = faces
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):
"""Returns the string representation of the model"""
import simplejson as json
if six.PY2:
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)
def __repr__(self):
"""For `print`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, AddFacesByUrlResponse):
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
|
48d3d2345ecb774006b7797e6dfb19ea0489873f
|
de24f83a5e3768a2638ebcf13cbe717e75740168
|
/moodledata/vpl_data/63/usersdata/147/28536/submittedfiles/swamee.py
|
87c492832ea836815b97f42dfba4a884abe8852b
|
[] |
no_license
|
rafaelperazzo/programacao-web
|
95643423a35c44613b0f64bed05bd34780fe2436
|
170dd5440afb9ee68a973f3de13a99aa4c735d79
|
refs/heads/master
| 2021-01-12T14:06:25.773146
| 2017-12-22T16:05:45
| 2017-12-22T16:05:45
| 69,566,344
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 513
|
py
|
# -*- coding: utf-8 -*-
import math
#COMECE SEU CÓDIGO AQUI
g=9.81
epsilon=0.000005
f=float(input('digite valor de f:'))
L=float(input('digite valor de L:'))
Q=float(input('digite valor de Q:'))
deltaH=float(input('digite valor de deltaH:'))
v=float(input('digite valor de v:'))
d=((8*f*L*(Q**2))/((math.pi**2)*g*deltaH))**0.5
rey=(4*Q)/(math.pi*d*v)
k=(0.25)/math.log10((epsilon/(3.7*d))+(5.7/(rey**0.9))**2)
print('o valor de d é %.2f' %d)
print('o valor de rey é %.2f' %rey)
print('o valor de k é %.2f' %k)
|
[
"rafael.mota@ufca.edu.br"
] |
rafael.mota@ufca.edu.br
|
0079ec1753397ec8e2d4db72f17762047e237974
|
53fab060fa262e5d5026e0807d93c75fb81e67b9
|
/backup/user_113/ch20_2020_09_16_11_25_21_743333.py
|
2edf4921f042e6256794183644e3ed17b47e767a
|
[] |
no_license
|
gabriellaec/desoft-analise-exercicios
|
b77c6999424c5ce7e44086a12589a0ad43d6adca
|
01940ab0897aa6005764fc220b900e4d6161d36b
|
refs/heads/main
| 2023-01-31T17:19:42.050628
| 2020-12-16T05:21:31
| 2020-12-16T05:21:31
| 306,735,108
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 225
|
py
|
dist = int(input('Qual a distancia de sua viajem?: '))
if dist <= 200:
preco = dist * 0.5
print(preco)
elif dist > 200:
dist -= 200
preco = dist * 0.45
preco += 100
print ('{0:.2f}'.format(preco))
|
[
"you@example.com"
] |
you@example.com
|
33986ed30f53a19439cdd7d07c782a582f0d133e
|
18d087b0fca0f80018861da6197e30d712fc248b
|
/S05/question_files/main.com.py
|
9a975a8ffc12d8004a7b40ff9d66beceaed06180
|
[] |
no_license
|
pymft/mft-05
|
6a92f3e9e9e9568b602f0de8daae310e76646fac
|
dde1ff239163123494535ab1b4c3c86c4b01599f
|
refs/heads/master
| 2020-06-03T21:56:12.289836
| 2019-08-29T13:52:02
| 2019-08-29T13:52:02
| 191,747,168
| 1
| 5
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,104
|
py
|
import glob
def path_to_root(dct, number):
parent = dct[number]
if parent == 0:
return [number]
return path_to_root(dct, parent) + [number]
def convert(parents):
children = {0: []}
for k in parents:
children[k] = []
for k in parents:
val = parents[k]
children[val].append(k)
return children
def find_no_children_nodes(parent_to_children):
res = []
for k in parent_to_children:
if parent_to_children[k] == []:
res.append(k)
return res
child_to_parent = {}
list_of_files = glob.glob('./files/*.txt')
for f in list_of_files:
child = f[8:-4]
parent = open(f).read()
child = int(child)
parent = int(parent)
child_to_parent[child] = parent
parent_to_children = convert(child_to_parent)
print(child_to_parent)
print(parent_to_children)
max_path = []
for node in find_no_children_nodes(parent_to_children):
path = path_to_root(child_to_parent, node)
if len(path) > len(max_path):
max_path = path
print(path_to_root(child_to_parent, 6638932548))
print(max_path)
|
[
"naeini.v@gmail.com"
] |
naeini.v@gmail.com
|
7ebfec0556e46db57e2c4d1eca4d13ef6452d0ce
|
005a6421cd6159fb6be8c61cc675654377e8f226
|
/cairis/core/TemplateObstacleParameters.py
|
dd6ad8c3e8c2351b3464509195afd601d5e88470
|
[
"Apache-2.0"
] |
permissive
|
cairis-platform/cairis
|
d667bc91ba28f0b7cd4fc88e6528eb3339e4ee6f
|
55abb93a9377664f5b03c027bad7ce3cf168c5ad
|
refs/heads/master
| 2023-04-06T17:04:08.781186
| 2023-02-17T22:51:15
| 2023-02-17T22:51:15
| 3,790,944
| 105
| 36
|
Apache-2.0
| 2022-03-19T15:04:14
| 2012-03-21T20:17:05
|
Python
|
UTF-8
|
Python
| false
| false
| 1,712
|
py
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
__author__ = 'Shamal Faily'
from . import ObjectCreationParameters
class TemplateObstacleParameters(ObjectCreationParameters.ObjectCreationParameters):
def __init__(self,obsName,obsCat,obsDef,obsConcerns,obsResp,obsProb,obsProbRat):
ObjectCreationParameters.ObjectCreationParameters.__init__(self)
self.theName = obsName
self.theCategory = obsCat
self.theDefinition = obsDef
self.theConcerns = obsConcerns
self.theResponsibilities = obsResp
self.theProbability = obsProb
self.theProbabilityRationale = obsProbRat
def name(self): return self.theName
def category(self): return self.theCategory
def definition(self): return self.theDefinition
def concerns(self): return self.theConcerns
def responsibilities(self): return self.theResponsibilities
def probability(self): return self.theProbability
def probabilityRationale(self): return self.theProbabilityRationale
|
[
"shamal.faily@googlemail.com"
] |
shamal.faily@googlemail.com
|
e0cef3709184ba38a5b1c49088dd488ff94fe2d7
|
5a4436884af5341ce855c0e84866b972a0f61c05
|
/day4/classes/student/13.py
|
42d32a7eccc68bd225d21bb75b5d00847af1380c
|
[] |
no_license
|
sreejithev/pythoncodes
|
74a420c4f025b893e27f17ba85632a4a096f17fd
|
70df14871a9687916d1c4ada76c055607f13e8ce
|
refs/heads/master
| 2021-01-21T20:59:47.056167
| 2017-06-19T09:43:17
| 2017-06-19T09:43:17
| 92,292,259
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 435
|
py
|
class student:
def __init__(self, name, age, rank):
self.name = name
self.age = age
self.rank = rank
def __str__(self):
return 'name = %s, age = %d, rank = %d' % (self.name, self.age, self.rank)
def __lt__(self, other):
if self.rank > other.rank:
return True
else:
return False
student1 = student('John', 20, 100)
student2 = student('Ram', 19, 120)
s = student2 < student1
print s
# s = student2__lt__(student1)
|
[
"sreejithevwyd@gmail.com"
] |
sreejithevwyd@gmail.com
|
d251d96aa118620cf5b52cd71eb9e82cbb437e15
|
8a41a7f9340cfa784cb36d35dca1ecb1630e4097
|
/Programming/Python/TestFrameworks/pytest_practice/test_pytest_requests.py
|
f15e998dc821c7bb5c3b6d0ca5291bb0d4f895cd
|
[] |
no_license
|
anishst/Learn
|
02e6b6cce43cf21621d328ef0fc25168267a9a3d
|
a1aed8b78b19acdb23e20be57b67fb242e0aefc5
|
refs/heads/master
| 2022-05-13T10:17:40.293640
| 2022-03-30T12:44:21
| 2022-03-30T12:44:21
| 173,595,812
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 812
|
py
|
# http://pythontesting.net/framework/pytest/pytest-fixtures-nuts-bolts/#scope
import pytest
@pytest.fixture()
def my_fixture(request):
print('\n-----------------')
print('fixturename : %s' % request.fixturename)
print('scope : %s' % request.scope)
print('function : %s' % request.function.__name__)
print('cls : %s' % request.cls)
print('module : %s' % request.module.__name__)
print('fspath : %s' % request.fspath)
print('-----------------')
if request.function.__name__ == 'test_three':
request.applymarker(pytest.mark.xfail)
def test_one(my_fixture):
print('test_one():')
class TestClass():
def test_two(self, my_fixture):
print('test_two()')
def test_three(my_fixture):
print('test_three()')
assert False
|
[
"sebastian_anish@bah.com"
] |
sebastian_anish@bah.com
|
14082e84e8cc42dec1bcbc028a0ce10087db4dd4
|
4d4fcde3efaa334f7aa56beabd2aa26fbcc43650
|
/server/src/uds/migrations/0039_auto_20201111_1329.py
|
4d48ca91318e70def9c7828155e6812d0e528f18
|
[] |
no_license
|
xezpeleta/openuds
|
a8b11cb34eb0ef7bb2da80f67586a81b2de229ef
|
840a7a02bd7c9894e8863a8a50874cdfdbf30fcd
|
refs/heads/master
| 2023-08-21T17:55:48.914631
| 2021-10-06T10:39:06
| 2021-10-06T10:39:06
| 414,489,331
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 676
|
py
|
# Generated by Django 3.1.2 on 2020-11-11 13:29
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('uds', '0038_auto_20200505_config'),
]
operations = [
migrations.RemoveField(
model_name='metapool',
name='accessCalendars',
),
migrations.RemoveField(
model_name='metapool',
name='pools',
),
migrations.RemoveField(
model_name='servicepool',
name='accessCalendars',
),
migrations.RemoveField(
model_name='servicepool',
name='actionsCalendars',
),
]
|
[
"dkmaster@dkmon.com"
] |
dkmaster@dkmon.com
|
ac9cbff6616993fe2ea2f872485ef2cd05863776
|
419873dd3b7412f704b1a7907b64a60b44cedf39
|
/python/树/1448. 统计二叉树中好节点的数目.py
|
00d74027dba7eea0cc91e63759b58e33a3e74545
|
[] |
no_license
|
Weless/leetcode
|
0585c5bfa260713f44dabc51fa58ebf8a10e7814
|
0566622daa5849f7deb0cfdc6de2282fb3127f4c
|
refs/heads/master
| 2021-11-13T07:59:20.299920
| 2021-10-25T02:09:53
| 2021-10-25T02:09:53
| 203,720,668
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,627
|
py
|
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def goodNodes(self, root: TreeNode) -> int:
if not root:
return 0
from collections import deque
queue = deque()
queue.appendleft((root.val,root))
count = 1
while queue:
nodeVal,node = queue.pop()
if node.left:
if node.left.val >= nodeVal:
queue.appendleft((node.left.val,node.left))
count+=1
else:
queue.appendleft((nodeVal,node.left))
if node.right:
if node.right.val >= nodeVal:
queue.appendleft((node.right.val,node.right))
count+=1
else:
queue.appendleft((nodeVal,node.right))
return count
class Solution:
def goodNodes(self, root: TreeNode) -> int:
if not root:
return 0
self.res = 0
def dfs(root,val):
if not root:
return
if root.left:
if root.left.val >= val:
self.res +=1
dfs(root.left,root.left.val)
else:
dfs(root.left,val)
if root.right:
if root.right.val >= val:
self.res +=1
dfs(root.right,root.right.val)
else:
dfs(root.right,val)
dfs(root,root.val)
return self.res
|
[
"twzcxx1@163.com"
] |
twzcxx1@163.com
|
17371c0c05eb0a54d12cfae1089ffbf4af13250e
|
0a2167a58687db61423fa71dc3982194c8dbf3a4
|
/photo_upload_js/search/urls.py
|
57e7e59472bb8529fa18d1bbca7daf94b1e18388
|
[] |
no_license
|
nilldiggonto/js_with_django3
|
e6728192bc45313b43fc8c1696207ee0eb990445
|
ec8df007732ada06aba8956460a2ecb0d5f20b27
|
refs/heads/main
| 2023-03-13T18:17:13.465079
| 2021-03-01T12:43:40
| 2021-03-01T12:43:40
| 338,062,634
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 213
|
py
|
from django.urls import path
from .views import SearchListView,post_with_photo_view
urlpatterns = [
path('',SearchListView.as_view(),name='search-list'),
path('up/',post_with_photo_view,name='up-post'),
]
|
[
"nilldiggonto@gmail.com"
] |
nilldiggonto@gmail.com
|
726b58567c2d9b96312f1a2247fda43614f50976
|
1eedb7439266cc63df179aac8fae28cdcf83b3d5
|
/nuwe_data_viewer/plugin/project_explorer/model/container_node.py
|
311b62d82ec1eb6b6954727a6b4e65bfa9ca2073
|
[] |
no_license
|
perillaroc/nuwe-data-viewer
|
6f11d19de920bbe2c9937ee4c3169cbe20dfafcc
|
12a49844980946f07523f87786b054aa6d9c2e10
|
refs/heads/master
| 2020-03-27T04:59:41.085059
| 2019-05-11T14:24:44
| 2019-05-11T14:24:44
| 145,986,751
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 220
|
py
|
# coding: utf-8
from nuwe_data_viewer.plugin.project_explorer.model.node import Node
class ContainerNode(Node):
def __init__(self, display_name="", node_id=None):
Node.__init__(self, display_name, node_id)
|
[
"perillaroc@gmail.com"
] |
perillaroc@gmail.com
|
f09d106fdba174b4d50bd24e47c76d79bcff3de6
|
9e988c0dfbea15cd23a3de860cb0c88c3dcdbd97
|
/sdBs/AllRun/galex_j16155+5048/sdB_galex_j16155+5048_coadd.py
|
910403f482b6eda6d8e12bdf3a0cae2ad2051389
|
[] |
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
| 453
|
py
|
from gPhoton.gMap import gMap
def main():
gMap(band="NUV", skypos=[243.88925,50.807131], skyrange=[0.0333333333333,0.0333333333333], stepsz = 30., cntfile="/data2/fleming/GPHOTON_OUTPUT/LIGHTCURVES/sdBs/sdB_galex_j16155+5048/sdB_galex_j16155+5048_movie_count.fits", cntcoaddfile="/data2/fleming/GPHOTON_OUTPUT/LIGHTCURVES/sdB/sdB_galex_j16155+5048/sdB_galex_j16155+5048_count_coadd.fits", overwrite=True, verbose=3)
if __name__ == "__main__":
main()
|
[
"thomas@boudreauxmail.com"
] |
thomas@boudreauxmail.com
|
767c2bfac9638826491205fbf82df7b3dfcd3672
|
6169a0af24553278c9493c9ac14d2351e9085afd
|
/tests/providers/pagerduty/hooks/test_pagerduty_events.py
|
3c68ba8247954e373fa2502a56287ba653a750a3
|
[
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] |
permissive
|
Nextdoor/airflow
|
c994f8fbaf48bebd891300f44dd78a58fd0b057b
|
863ec46e25ea49d6d5b006d8fd3a83f50aa9db79
|
refs/heads/master
| 2023-06-12T19:25:58.052324
| 2023-01-20T17:43:14
| 2023-01-20T17:43:14
| 54,076,271
| 7
| 8
|
Apache-2.0
| 2023-06-05T20:38:53
| 2016-03-17T00:34:45
|
Python
|
UTF-8
|
Python
| false
| false
| 2,285
|
py
|
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from __future__ import annotations
import pytest
from airflow.models import Connection
from airflow.providers.pagerduty.hooks.pagerduty import PagerdutyEventsHook
from airflow.utils import db
DEFAULT_CONN_ID = "pagerduty_events_default"
@pytest.fixture(scope="class")
def events_connections():
db.merge_conn(Connection(conn_id=DEFAULT_CONN_ID, conn_type="pagerduty_events", password="events_token"))
class TestPagerdutyEventsHook:
def test_get_integration_key_from_password(self, events_connections):
hook = PagerdutyEventsHook(pagerduty_events_conn_id=DEFAULT_CONN_ID)
assert hook.integration_key == "events_token", "token initialised."
def test_token_parameter_override(self, events_connections):
hook = PagerdutyEventsHook(integration_key="override_key", pagerduty_events_conn_id=DEFAULT_CONN_ID)
assert hook.integration_key == "override_key", "token initialised."
def test_create_event(self, requests_mock, events_connections):
hook = PagerdutyEventsHook(pagerduty_events_conn_id=DEFAULT_CONN_ID)
mock_response_body = {
"status": "success",
"message": "Event processed",
"dedup_key": "samplekeyhere",
}
requests_mock.post("https://events.pagerduty.com/v2/enqueue", json=mock_response_body)
resp = hook.create_event(
summary="test",
source="airflow_test",
severity="error",
)
assert resp == mock_response_body
|
[
"noreply@github.com"
] |
Nextdoor.noreply@github.com
|
f446b6c8b2833b421592915d637db99761f2c596
|
18aee5d93a63eab684fe69e3aa0abd1372dd5d08
|
/python/paddle/nn/layer/distance.py
|
e2fb10f252f1008f0ddc5e41e1e48afbedb8d67c
|
[
"Apache-2.0"
] |
permissive
|
Shixiaowei02/Paddle
|
8d049f4f29e281de2fb1ffcd143997c88078eadb
|
3d4d995f26c48f7792b325806ec3d110fc59f6fc
|
refs/heads/develop
| 2023-06-26T06:25:48.074273
| 2023-06-14T06:40:21
| 2023-06-14T06:40:21
| 174,320,213
| 2
| 1
|
Apache-2.0
| 2022-12-28T05:14:30
| 2019-03-07T10:09:34
|
C++
|
UTF-8
|
Python
| false
| false
| 3,333
|
py
|
# Copyright (c) 2022 PaddlePaddle 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.
from .. import functional as F
from .layers import Layer
__all__ = []
class PairwiseDistance(Layer):
r"""
It computes the pairwise distance between two vectors. The
distance is calculated by p-oreder norm:
.. math::
\Vert x \Vert _p = \left( \sum_{i=1}^n \vert x_i \vert ^ p \right) ^ {1/p}.
Parameters:
p (float, optional): The order of norm. Default: :math:`2.0`.
epsilon (float, optional): Add small value to avoid division by zero.
Default: :math:`1e-6`.
keepdim (bool, optional): Whether to reserve the reduced dimension
in the output Tensor. The result tensor is one dimension less than
the result of ``|x-y|`` unless :attr:`keepdim` is True. Default: False.
name (str, optional): For details, please refer to :ref:`api_guide_Name`.
Generally, no setting is required. Default: None.
Shape:
- x: :math:`[N, D]` or :math:`[D]`, where :math:`N` is batch size, :math:`D`
is the dimension of the data. Available data type is float16, float32, float64.
- y: :math:`[N, D]` or :math:`[D]`, y have the same dtype as x.
- output: The same dtype as input tensor.
- If :attr:`keepdim` is True, the output shape is :math:`[N, 1]` or :math:`[1]`,
depending on whether the input has data shaped as :math:`[N, D]`.
- If :attr:`keepdim` is False, the output shape is :math:`[N]` or :math:`[]`,
depending on whether the input has data shaped as :math:`[N, D]`.
Examples:
.. code-block:: python
import paddle
x = paddle.to_tensor([[1., 3.], [3., 5.]], dtype=paddle.float64)
y = paddle.to_tensor([[5., 6.], [7., 8.]], dtype=paddle.float64)
dist = paddle.nn.PairwiseDistance()
distance = dist(x, y)
print(distance)
# Tensor(shape=[2], dtype=float64, place=Place(gpu:0), stop_gradient=True,
# [4.99999860, 4.99999860])
"""
def __init__(self, p=2.0, epsilon=1e-6, keepdim=False, name=None):
super().__init__()
self.p = p
self.epsilon = epsilon
self.keepdim = keepdim
self.name = name
def forward(self, x, y):
return F.pairwise_distance(
x, y, self.p, self.epsilon, self.keepdim, self.name
)
def extra_repr(self):
main_str = 'p={p}'
if self.epsilon != 1e-6:
main_str += ', epsilon={epsilon}'
if self.keepdim is not False:
main_str += ', keepdim={keepdim}'
if self.name is not None:
main_str += ', name={name}'
return main_str.format(**self.__dict__)
|
[
"noreply@github.com"
] |
Shixiaowei02.noreply@github.com
|
61b29b234ac538819a506f9b35ad04235d880747
|
6e1f550b71e212cec90f070e2e9a1dd714de55d6
|
/setup.py
|
1586e43ed05c743040c5c403f039e0139055220a
|
[
"MIT"
] |
permissive
|
wbond/gears-libsass
|
b4f7986ffa642b79a5b1ab3125c9d9056d6777fc
|
a861089306572b5250c3d3716abd916dc140fa20
|
refs/heads/master
| 2020-04-10T06:21:20.079859
| 2018-12-07T17:09:42
| 2018-12-07T17:09:42
| 160,851,933
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,004
|
py
|
import os
from setuptools import setup, find_packages
def read(filename):
return open(os.path.join(os.path.dirname(__file__), filename)).read()
setup(
name='gears-libsass',
version='0.1.0',
url='https://github.com/wbond/gears-libsass',
license='MIT',
author='Will Bond',
author_email='will@wbond.net',
description='Python libsass-based SCSS compiler for Gears',
long_description=read('README.rst'),
packages=find_packages(),
include_package_data=True,
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
],
install_requires=[
"libsass >= 0.16.1"
],
)
|
[
"will@wbond.net"
] |
will@wbond.net
|
4b0cd507b0fe4a7edf15fe8c9200e2b3b34115f5
|
59522e46a73630181f19251b8bfef90e497c2f82
|
/coop_cms/apps/test_app/forms.py
|
a28945b3361774cf45cf14979bb0f7de7f2e8161
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
ljean/coop_cms
|
9befe74edda007686007f8566cd2555856099ae8
|
9e6c70afb61b57dc0326fbb64f9d6b19c04f48a1
|
refs/heads/master
| 2023-07-11T16:02:35.945029
| 2023-06-30T12:16:26
| 2023-06-30T12:16:26
| 5,846,409
| 3
| 5
|
NOASSERTION
| 2019-08-30T10:55:02
| 2012-09-17T19:53:56
|
Python
|
UTF-8
|
Python
| false
| false
| 1,084
|
py
|
# -*- coding: utf-8 -*-
"""forms"""
import floppyforms as forms
from coop_html_editor.widgets import get_inline_html_widget
from ...forms.articles import NewArticleForm, ArticleSettingsForm
from ...forms.base import InlineHtmlEditableModelForm
from ...forms.newsletters import NewsletterSettingsForm
from .models import TestClass
class TestClassForm(InlineHtmlEditableModelForm):
"""for unit-testing"""
class Meta:
model = TestClass
fields = ('field1', 'field2', 'field3', 'bool_field', 'int_field', 'float_field')
widgets = {
'field2': get_inline_html_widget(),
}
no_inline_html_widgets = ('field2', 'field3', 'bool_field', 'int_field', 'float_field')
class MyNewArticleForm(NewArticleForm):
"""for unit-testing"""
dummy = forms.CharField(required=False)
class MyArticleSettingsForm(ArticleSettingsForm):
"""for unit-testing"""
dummy = forms.CharField(required=False)
class MyNewsletterSettingsForm(NewsletterSettingsForm):
"""for unit-testing"""
dummy = forms.CharField(required=False)
|
[
"ljean@apidev.fr"
] |
ljean@apidev.fr
|
dd1221db4a088cf90bcdefff2c489c4642863126
|
9c3934402046850104523e9d942d62e42175b512
|
/theblog/urls.py
|
e8d6cd26d99ae97986d6defb2b4be29934047079
|
[] |
no_license
|
Dekatron322/myblog
|
39954bf26ac7468dae2e888aba1a1855a0832835
|
4d4118eecb458dc53073cd8c3ff9eaa0235926c8
|
refs/heads/master
| 2022-06-18T07:01:57.218863
| 2020-05-08T08:35:57
| 2020-05-08T08:35:57
| 262,269,197
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 531
|
py
|
from django.urls import path, include
from .import views
urlpatterns = [
path('', views.index, name="index"),
path('blog/', views.blog, name="post-list"),
path('post/<id>/', views.post, name="post-detail"),
path('search/', views.search, name='search'),
path('tinymce/', include('tinymce.urls')),
path('post/<id>/update', views.post_update, name="post-update"),
path('post/<id>/delete', views.post_delete, name="post-delete"),
path('create/', views.post_create, name="post-create"),
]
|
[
"muritalaibrahim097@gmail.com"
] |
muritalaibrahim097@gmail.com
|
97d31bc99318da98c36566bc2f7a502e1953d6d9
|
54e4c1a57765519c77d04fc02112c7f3bbacc595
|
/prob_1317.py
|
11e01b22fc965fafc4a81f4f1b4e4ef0ee88e358
|
[] |
no_license
|
Hrishikesh-3459/leetCode
|
80a864228a8a2ae41ac2623f970a13f409234eed
|
42def57b8f70d179ca688314ae43747fc1e410a0
|
refs/heads/master
| 2023-05-07T01:37:19.375229
| 2021-05-25T01:58:05
| 2021-05-25T01:58:05
| 254,803,743
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 744
|
py
|
class Solution:
def sortString(self, s: str) -> str:
x = list(s)
ans = []
ans_2 = []
fin = []
count = 0
while True:
for i in sorted(x):
if (i not in ans):
ans.append(i)
count +=1
x.pop(x.index(i))
for j in sorted(x)[::-1]:
if (j not in ans_2):
count +=1
ans_2.append(j)
x.pop(x.index(j))
fin += ans + ans_2
if (count == len(s)):
break
ans.clear()
ans_2.clear()
ans_str = ""
for j in fin:
ans_str += j
return ans_str
|
[
"noreply@github.com"
] |
Hrishikesh-3459.noreply@github.com
|
9cf95ea8c8587547eda0ba121e569f8022e1aa55
|
19172e15355d4ef8ae4622d0ed6993c0cd4d80ea
|
/watchmen/pipeline/single/stage/unit/utils/units_func.py
|
1092797ba1dbe85e75457093d67cdc1b76bc612d
|
[
"MIT"
] |
permissive
|
TSRAW/watchmen-matryoshka-doll
|
d5b50fc4014fbea11c2765f377ca904d17a4c579
|
ab17e36a0f26f8e461296a222e6f7f2a4532c877
|
refs/heads/master
| 2023-03-18T05:40:08.354019
| 2021-03-17T15:52:34
| 2021-03-17T15:52:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,313
|
py
|
from datetime import datetime
from watchmen.common.constants import parameter_constants, pipeline_constants
from watchmen.topic.factor.factor import Factor
from watchmen.topic.topic import Topic
INSERT = "insert"
UPDATE = "update"
SEQUENCE = "sequence"
NUMBER = "number"
UNSIGNED = "unsigned" # 0 & positive
TEXT = "text"
TIME = 'time'
# address
ADDRESS = "address"
CONTINENT = "continent"
REGION = "region"
COUNTRY = "country"
PROVINCE = "province"
CITY = "city"
DISTRICT = "district"
ROAD = "road"
COMMUNITY = "community"
FLOOR = "floor"
RESIDENCE_TYPE = "residence-type"
RESIDENTIAL_AREA = "residential-area"
EMAIL = "email"
PHONE = "phone"
MOBILE = "mobile"
FAX = "fax"
DATETIME = "datetime" # YYYY - MM - DD
DATE = "date" # YYYY - MM - DD
TIME = "time" # HH: mm:ss
YEAR = "year" # 4
HALF_YEAR = "half-year" # 1: first
QUARTER = "quarter" # 1 - 4
SEASON = "season" # 1: spring, 2: summer, 3: autumn, 4: winter
MONTH = "month" # 1 - 12
HALF_MONTH = "half-month" # 1: first
TEN_DAYS = "ten-days" # 1, 2, 3
WEEK_OF_YEAR = "week-of-year" # 1 - 53
WEEK_OF_MONTH = "week-of-month" # 1 - 6
HALF_WEEK = "half-week" # 1: first
DAY_OF_MONTH = "day-of-month" # 1 - 31, according
DAY_OF_WEEK = "day-of-week" # 1 - 7
DAY_KIND = "day-kind" # 1: workday, 2: weekend, 3: holiday
HOUR = "hour" # 0 - 23
HOUR_KIND = "hour-kind" # 1: work
MINUTE = "minute" # 0 - 59
SECOND = "second" # 0 - 59
AM_PM = "am-pm" # 1, 2
# individual
GENDER = "gender"
OCCUPATION = "occupation"
DATE_OF_BIRTH = "date-of-birth" # YYYY - MM - DD
AGE = "age"
ID_NO = "id-no"
RELIGION = "religion"
NATIONALITY = "nationality"
# organization
BIZ_TRADE = "biz-trade"
BIZ_SCALE = "biz-scale"
BOOLEAN = "boolean"
ENUM = "enum"
OBJECT = "object"
ARRAY = "array"
def check_condition(operator, left_value, right_value):
if operator == "equals":
return left_value == right_value
elif operator == "not-equals":
return left_value != right_value
elif operator == "less":
return left_value < right_value
elif operator == "less-equals":
return left_value <= right_value
elif operator == "more":
return left_value > right_value
elif operator == "more-equals":
return left_value >= right_value
else:
raise Exception("NotImplemented:", operator)
def convert_factor_type(value, factor_type):
if factor_type == TEXT:
return str(value)
elif factor_type == NUMBER:
# TODO process number type
return float(value)
elif factor_type == DATETIME:
return datetime.fromisoformat(value)
elif factor_type == BOOLEAN:
return bool(value)
elif factor_type == SEQUENCE:
return int(value)
elif factor_type == YEAR:
return int(value)
elif factor_type == MONTH:
return int(value)
elif factor_type == TIME:
return round(value * 1000)
else:
return value
def build_factor_dict(topic: Topic):
factor_dict = {}
for factor in topic.factors:
factor_dict[factor.factorId] = factor
return factor_dict
def get_factor(factor_id, target_topic):
for factor in target_topic.factors:
if factor.factorId == factor_id:
return factor
def get_execute_time(start_time):
time_elapsed = datetime.now() - start_time
execution_time = time_elapsed.microseconds / 1000
return execution_time
def get_value(factor: Factor, data):
if factor.name in data:
value = data[factor.name]
return convert_factor_type(value, factor.type)
elif factor.type == "number":
return None
elif factor.type == "text":
return None
else:
return None
def add_audit_columns(dictionary, audit_type):
if audit_type == INSERT:
dictionary[pipeline_constants.INSERT_TIME] = datetime.now()
elif audit_type == UPDATE:
dictionary[pipeline_constants.UPDATE_TIME] = datetime.now()
else:
raise Exception("unknown audit_type")
def add_trace_columns(dictionary, trace_type, pipeline_uid):
dictionary[trace_type] = pipeline_uid
def process_variable(variable_name):
if variable_name.startswith("{"):
return "memory", variable_name.replace("{", "").replace("}", "")
else:
return parameter_constants.CONSTANT, variable_name
|
[
"luke0623@outlook.com"
] |
luke0623@outlook.com
|
b393f63f6ac9ee26aceb40dd7bb00e64e25785d3
|
d806dd4a6791382813d2136283a602207fb4b43c
|
/sirius/blueprints/api/remote_service/tula/passive/childbirth/views.py
|
1e86681447f1b9f6b1e9f4f7d3e504d827b7a501
|
[] |
no_license
|
MarsStirner/sirius
|
5bbf2a03dafb7248db481e13aff63ff989fabbc2
|
8839460726cca080ca8549bacd3a498e519c8f96
|
refs/heads/master
| 2021-03-24T12:09:14.673193
| 2017-06-06T16:28:53
| 2017-06-06T16:28:53
| 96,042,947
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,382
|
py
|
#! coding:utf-8
"""
@author: BARS Group
@date: 03.10.2016
"""
import sys
from flask import request
from sirius.blueprints.api.remote_service.tula.app import module
from sirius.blueprints.api.remote_service.tula.entities import TulaEntityCode
from sirius.blueprints.api.remote_service.tula.passive.childbirth.xform import \
ChildbirthTulaXForm
from sirius.blueprints.monitor.exception import remote_api_method
from sirius.blueprints.monitor.logformat import hook
parent_id_name = 'card_id'
@module.route('/api/integration/<int:api_version>/card/<' + parent_id_name + '>/childbirth/',
methods=['POST', 'PUT', 'DELETE'])
@remote_api_method(hook=hook)
def api_childbirth_change(api_version, **kwargs):
# main_id = kwargs.get(main_id_name)
parent_id = kwargs.get(parent_id_name)
stream_id = kwargs.get('stream_id')
data = None
delete = request.method == 'DELETE'
xform = ChildbirthTulaXForm(api_version, stream_id)
if not delete:
data = request.get_json()
xform.validate(data)
# main_id = data.get('main_id')
# xform.check_params(card_id, main_id, data)
service_name = sys._getframe().f_code.co_name
parents_params = {
parent_id_name: {'entity': TulaEntityCode.CARD, 'id': parent_id},
}
xform.send_messages(parent_id, parent_id_name, data, service_name, request.method, parents_params)
|
[
"paschenko@bars-open.ru"
] |
paschenko@bars-open.ru
|
c6569d076ffb391b828b0b0ad13e3266739a768b
|
82b946da326148a3c1c1f687f96c0da165bb2c15
|
/sdk/python/pulumi_azure_native/attestation/v20210601preview/_enums.py
|
647247b71cec4cfaee5ae075082eafac95c1b2cc
|
[
"BSD-3-Clause",
"Apache-2.0"
] |
permissive
|
morrell/pulumi-azure-native
|
3916e978382366607f3df0a669f24cb16293ff5e
|
cd3ba4b9cb08c5e1df7674c1c71695b80e443f08
|
refs/heads/master
| 2023-06-20T19:37:05.414924
| 2021-07-19T20:57:53
| 2021-07-19T20:57:53
| 387,815,163
| 0
| 0
|
Apache-2.0
| 2021-07-20T14:18:29
| 2021-07-20T14:18:28
| null |
UTF-8
|
Python
| false
| false
| 921
|
py
|
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
from enum import Enum
__all__ = [
'PrivateEndpointServiceConnectionStatus',
'PublicNetworkAccessType',
]
class PrivateEndpointServiceConnectionStatus(str, Enum):
"""
Indicates whether the connection has been Approved/Rejected/Removed by the owner of the service.
"""
PENDING = "Pending"
APPROVED = "Approved"
REJECTED = "Rejected"
class PublicNetworkAccessType(str, Enum):
"""
Controls whether traffic from the public network is allowed to access the Attestation Provider APIs.
"""
ENABLED = "Enabled"
"""Enables public network connectivity to the Attestation Provider REST APIs."""
DISABLED = "Disabled"
"""Disables public network connectivity to the Attestation Provider REST APIs."""
|
[
"noreply@github.com"
] |
morrell.noreply@github.com
|
45403bc3673f7fdd17f2e29878219415405ea12a
|
9e538305f9263d86e780a4a3f205c972f658f54d
|
/src/order/models/managers.py
|
7b7538f837adf7cf43e89ce2fef561ffcab76f9c
|
[] |
no_license
|
tanjibpa/mednet
|
bb188582b0d90407015622b34f0291557acb1919
|
19a7535d583077fec7b7030c298fceb4c4df3207
|
refs/heads/main
| 2023-05-26T07:44:27.615506
| 2021-06-10T06:30:19
| 2021-06-10T06:30:19
| 355,774,065
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 178
|
py
|
from django.db import models
class SupplierOrderList(models.Manager):
def supplier_order(self):
return super().get_queryset().filter(producer__org_type="supplier")
|
[
"ikram.tanjib@gmail.com"
] |
ikram.tanjib@gmail.com
|
77e3a3bf9a976c804784f6bbc248d5188678a70b
|
9743d5fd24822f79c156ad112229e25adb9ed6f6
|
/xai/brain/wordbase/nouns/_fawn.py
|
260afb89b3b0bae13a38db08457adb7aad8566e8
|
[
"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
| 322
|
py
|
#calss header
class _FAWN():
def __init__(self,):
self.name = "FAWN"
self.definitions = [u'a young deer', u'a pale yellowish-brown colour']
self.parents = []
self.childen = []
self.properties = []
self.jsondata = {}
self.specie = 'nouns'
def run(self, obj1 = [], obj2 = []):
return self.jsondata
|
[
"xingwang1991@gmail.com"
] |
xingwang1991@gmail.com
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.