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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ed34b4061a235eb40a137794dc28449b27e5436b | 09e57dd1374713f06b70d7b37a580130d9bbab0d | /data/p2DJ/New/program/qiskit/simulator/startQiskit325.py | 33adb47f5c3fce107177c1c0a20149f4ec2ba249 | [
"BSD-3-Clause"
] | permissive | UCLA-SEAL/QDiff | ad53650034897abb5941e74539e3aee8edb600ab | d968cbc47fe926b7f88b4adf10490f1edd6f8819 | refs/heads/main | 2023-08-05T04:52:24.961998 | 2021-09-19T02:56:16 | 2021-09-19T02:56:16 | 405,159,939 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,279 | py | # qubit number=2
# total number=18
import cirq
import qiskit
from qiskit import IBMQ
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import BasicAer, execute, transpile
from pprint import pprint
from qiskit.test.mock import FakeVigo
from math import log2,floor, sqrt, pi
import numpy as np
import networkx as nx
def build_oracle(n: int, f) -> QuantumCircuit:
# implement the oracle O_f^\pm
# NOTE: use U1 gate (P gate) with \lambda = 180 ==> CZ gate
# or multi_control_Z_gate (issue #127)
controls = QuantumRegister(n, "ofc")
target = QuantumRegister(1, "oft")
oracle = QuantumCircuit(controls, target, name="Of")
for i in range(2 ** n):
rep = np.binary_repr(i, n)
if f(rep) == "1":
for j in range(n):
if rep[j] == "0":
oracle.x(controls[j])
oracle.mct(controls, target[0], None, mode='noancilla')
for j in range(n):
if rep[j] == "0":
oracle.x(controls[j])
# oracle.barrier()
# oracle.draw('mpl', filename='circuit/deutsch-oracle.png')
return oracle
def make_circuit(n:int,f) -> QuantumCircuit:
# circuit begin
input_qubit = QuantumRegister(n, "qc")
target = QuantumRegister(1, "qt")
prog = QuantumCircuit(input_qubit, target)
# inverse last one (can be omitted if using O_f^\pm)
prog.x(target)
# apply H to get superposition
for i in range(n):
prog.h(input_qubit[i])
prog.h(input_qubit[1]) # number=1
prog.h(input_qubit[1]) # number=6
prog.cz(input_qubit[0],input_qubit[1]) # number=7
prog.h(input_qubit[1]) # number=9
prog.h(input_qubit[1]) # number=8
prog.h(target)
prog.barrier()
# apply oracle O_f
oracle = build_oracle(n, f)
prog.append(
oracle.to_gate(),
[input_qubit[i] for i in range(n)] + [target])
# apply H back (QFT on Z_2^n)
for i in range(n):
prog.h(input_qubit[i])
prog.barrier()
# measure
#for i in range(n):
# prog.measure(input_qubit[i], classicals[i])
prog.y(input_qubit[1]) # number=2
prog.h(input_qubit[1]) # number=15
prog.cz(input_qubit[0],input_qubit[1]) # number=16
prog.h(input_qubit[1]) # number=17
prog.y(input_qubit[1]) # number=3
prog.cx(input_qubit[1],input_qubit[0]) # number=12
prog.x(input_qubit[0]) # number=13
prog.cx(input_qubit[1],input_qubit[0]) # number=14
prog.x(input_qubit[0]) # number=11
# circuit end
return prog
if __name__ == '__main__':
n = 2
f = lambda rep: rep[-1]
# f = lambda rep: "1" if rep[0:2] == "01" or rep[0:2] == "10" else "0"
# f = lambda rep: "0"
prog = make_circuit(n, f)
sample_shot =2800
backend = BasicAer.get_backend('qasm_simulator')
circuit1 = transpile(prog,FakeVigo())
circuit1.x(qubit=3)
circuit1.x(qubit=3)
circuit1.measure_all()
prog = circuit1
info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()
writefile = open("../data/startQiskit325.csv","w")
print(info,file=writefile)
print("results end", file=writefile)
print(circuit1.depth(),file=writefile)
print(circuit1,file=writefile)
writefile.close()
| [
"wangjiyuan123@yeah.net"
] | wangjiyuan123@yeah.net |
7109e8e13667c1c7f696373dc35820f9bd770370 | cd9f819b968def4f9b57448bdd926dc5ffa06671 | /B_物件導向Python與TensorFlow應用_鄭仲平_廣稅文化_2019/Ch06/ex06-03.py | 8976d4215762f50fb806716b35b3a5f7f1364038 | [] | no_license | AaronCHH/jb_pyoop | 06c67f3c17e722cf18147be4ae0fac81726e4cbc | 356baf0963cf216db5db7e11fb67234ff9b31b68 | refs/heads/main | 2023-04-02T05:55:27.477763 | 2021-04-07T01:48:04 | 2021-04-07T01:48:13 | 344,676,005 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 519 | py | class Person():
def setValue(self, na, a):
self.name = na
self.age = a
def birthYear(self):
return 2019 - self.age
def display(self):
print("Name:", self.name, ", Age:", self.age)
class Teacher(Person):
def tr_setValue(self, na, a, sa):
super().setValue(na, a)
self.salary = sa
def pr(self):
super().display()
print("Salary:", self.salary)
if __name__ == '__main__':
steven = Teacher()
steven.tr_setValue("Steven", 35, 35000)
steven.pr()
| [
"aaronhsu219@gmail.com"
] | aaronhsu219@gmail.com |
c46ebf8cdb0a24a044fd4e262375317feee5ce94 | a2b20597759990445081057d35d113434cfcf970 | /stubs/typeshed/typeshed/stdlib/xml/sax/handler.pyi | 63b725bd6da65689b17b801b7aeb9354f6b0496b | [
"Apache-2.0",
"MIT"
] | permissive | facebook/pyre-check | 34059599c02b65605c574f13555229f3b931fd4e | fe8ccedc572cc1faa1fd01e9138f65e982875002 | refs/heads/main | 2023-09-03T19:10:11.587028 | 2023-09-02T07:40:35 | 2023-09-02T07:40:35 | 110,274,488 | 6,703 | 575 | MIT | 2023-09-13T17:02:32 | 2017-11-10T17:31:36 | OCaml | UTF-8 | Python | false | false | 1,799 | pyi | import sys
from typing import NoReturn
version: str
class ErrorHandler:
def error(self, exception: BaseException) -> NoReturn: ...
def fatalError(self, exception: BaseException) -> NoReturn: ...
def warning(self, exception: BaseException) -> None: ...
class ContentHandler:
def setDocumentLocator(self, locator): ...
def startDocument(self): ...
def endDocument(self): ...
def startPrefixMapping(self, prefix, uri): ...
def endPrefixMapping(self, prefix): ...
def startElement(self, name, attrs): ...
def endElement(self, name): ...
def startElementNS(self, name, qname, attrs): ...
def endElementNS(self, name, qname): ...
def characters(self, content): ...
def ignorableWhitespace(self, whitespace): ...
def processingInstruction(self, target, data): ...
def skippedEntity(self, name): ...
class DTDHandler:
def notationDecl(self, name, publicId, systemId): ...
def unparsedEntityDecl(self, name, publicId, systemId, ndata): ...
class EntityResolver:
def resolveEntity(self, publicId, systemId): ...
feature_namespaces: str
feature_namespace_prefixes: str
feature_string_interning: str
feature_validation: str
feature_external_ges: str
feature_external_pes: str
all_features: list[str]
property_lexical_handler: str
property_declaration_handler: str
property_dom_node: str
property_xml_string: str
property_encoding: str
property_interning_dict: str
all_properties: list[str]
if sys.version_info >= (3, 10):
class LexicalHandler:
def comment(self, content: str) -> object: ...
def startDTD(self, name: str, public_id: str | None, system_id: str | None) -> object: ...
def endDTD(self) -> object: ...
def startCDATA(self) -> object: ...
def endCDATA(self) -> object: ...
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
6ed656d22e34c2dc9dcb2f294cb3055988dfdf00 | 53fab060fa262e5d5026e0807d93c75fb81e67b9 | /backup/user_169/ch44_2020_03_25_20_16_39_893946.py | 784575c0785aa795f3087944dc42a9aac186e797 | [] | 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 | 492 | py |
lista_mes = [0]*13
lista_mes [1] = "janeiro"
lista_mes [2] = "jevereiro"
lista_mes [3] = "março"
lista_mes [4] = "abril"
lista_mes [5] = "maio"
lista_mes [6] = "junho"
lista_mes [7] = "julho"
lista_mes [8] = "agosto"
lista_mes [9] = "setembro"
lista_mes [10] = "outubro"
lista_mes [11] = "novembro"
lista_mes [12] = "dezembro"
mês=input("Qual é o nome do mês")
contador=1
while contador<=12:
contador+=1
if lista_mes[contador]==mês:
print (contador)
| [
"you@example.com"
] | you@example.com |
087679b41aee1885a60bb037f5cca27319cde741 | ac1bbabc7c1b3149711c416dd8b5f5969a0dbd04 | /Programming Basics/exams/balls.py | 43f9e211ba23edf1b8f3e5887a29124833f8f148 | [] | no_license | AssiaHristova/SoftUni-Software-Engineering | 9e904221e50cad5b6c7953c81bc8b3b23c1e8d24 | d4910098ed5aa19770d30a7d9cdf49f9aeaea165 | refs/heads/main | 2023-07-04T04:47:00.524677 | 2021-08-08T23:31:51 | 2021-08-08T23:31:51 | 324,847,727 | 1 | 0 | null | 2021-08-08T23:31:52 | 2020-12-27T20:58:01 | Python | UTF-8 | Python | false | false | 889 | py | N = int(input())
points = 0
red_balls = 0
orange_balls = 0
yellow_balls = 0
white_balls = 0
others = 0
black_balls = 0
for i in range(1, N + 1):
color = input()
if color == 'red':
points += 5
red_balls += 1
elif color == 'orange':
points += 10
orange_balls +=1
elif color == 'yellow':
points += 15
yellow_balls += 1
elif color == 'white':
points += 20
white_balls += 1
elif color == 'black':
points = points / 2
black_balls += 1
else:
others += 1
print(f'Total points: {points}')
print(f'Points from red balls: {red_balls}')
print(f'Points from orange balls: {orange_balls}')
print(f'Points from yellow balls: {yellow_balls}')
print(f'Points from white balls: {white_balls}')
print(f'Other colors picked: {others}')
print(f'Divides from black balls: {black_balls}')
| [
"assiaphristova@gmail.com"
] | assiaphristova@gmail.com |
1a6b8ba604f0daa92e8b7444c4245498b70e2cdf | 01242a981b234d7dd178ceb3d4b2fb4e4d939935 | /catalog/migrations/0003_auto_20201007_1652.py | 8d8ca31e5b75572fc2d5ccd9c4bb1fc9fd0da945 | [] | no_license | nouhben/locallibrary | 701b986eb7527919ffbc8eda762c16dd57fa8469 | 20d4b93c392d718c5262f80f0c9335e5bcacecc2 | refs/heads/main | 2023-01-11T14:41:36.114039 | 2020-10-10T15:05:22 | 2020-10-10T15:05:22 | 302,029,263 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 432 | py | # Generated by Django 3.1.2 on 2020-10-07 16:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('catalog', '0002_auto_20201007_1650'),
]
operations = [
migrations.AlterField(
model_name='bookinstance',
name='due_back_date',
field=models.DateField(blank=True, null=True, verbose_name='Due Back'),
),
]
| [
"benkadi.nouh@icloud.com"
] | benkadi.nouh@icloud.com |
1dcebde42e7512b66620deb4ab99c6491a7c2060 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p02256/s461624254.py | 6ce0966053c0fbeceeee1a0932ea3a140e293ab9 | [] | no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 240 | py | def gcd(x, y):
if x < y:
tmp = x
x = y
y = tmp
while y > 0:
r = x % y
x = y
y = r
return print(x)
x_y = input()
tmp = list(map(int, x_y.split()))
x = tmp[0]
y = tmp[1]
gcd(x, y)
| [
"66529651+Aastha2104@users.noreply.github.com"
] | 66529651+Aastha2104@users.noreply.github.com |
a0f645c5cebd63e21b309ab7d2d78f3fbef7d247 | e97e727972149063b3a1e56b38961d0f2f30ed95 | /knetik_cloud/models/stripe_create_payment_method.py | 8f7a7c5158f2b60f7ce8ec8fd15357909c2e39bf | [] | no_license | knetikmedia/knetikcloud-python-client | f3a485f21c6f3e733a864194c9acf048943dece7 | 834a24415385c906732437970db105e1bc71bde4 | refs/heads/master | 2021-01-12T10:23:35.307479 | 2018-03-14T16:04:24 | 2018-03-14T16:04:24 | 76,418,830 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,219 | py | # coding: utf-8
"""
Knetik Platform API Documentation latest
This is the spec for the Knetik API. Use this in conjunction with the documentation found at https://knetikcloud.com.
OpenAPI spec version: latest
Contact: support@knetik.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class StripeCreatePaymentMethod(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'details': 'PaymentMethodDetails',
'token': 'str',
'user_id': 'int'
}
attribute_map = {
'details': 'details',
'token': 'token',
'user_id': 'user_id'
}
def __init__(self, details=None, token=None, user_id=None):
"""
StripeCreatePaymentMethod - a model defined in Swagger
"""
self._details = None
self._token = None
self._user_id = None
self.discriminator = None
if details is not None:
self.details = details
self.token = token
if user_id is not None:
self.user_id = user_id
@property
def details(self):
"""
Gets the details of this StripeCreatePaymentMethod.
Additional optional details to store on the payment method. If included, all fields in the details will override any defaults
:return: The details of this StripeCreatePaymentMethod.
:rtype: PaymentMethodDetails
"""
return self._details
@details.setter
def details(self, details):
"""
Sets the details of this StripeCreatePaymentMethod.
Additional optional details to store on the payment method. If included, all fields in the details will override any defaults
:param details: The details of this StripeCreatePaymentMethod.
:type: PaymentMethodDetails
"""
self._details = details
@property
def token(self):
"""
Gets the token of this StripeCreatePaymentMethod.
A token from Stripe to identify payment info to be tied to the customer
:return: The token of this StripeCreatePaymentMethod.
:rtype: str
"""
return self._token
@token.setter
def token(self, token):
"""
Sets the token of this StripeCreatePaymentMethod.
A token from Stripe to identify payment info to be tied to the customer
:param token: The token of this StripeCreatePaymentMethod.
:type: str
"""
if token is None:
raise ValueError("Invalid value for `token`, must not be `None`")
self._token = token
@property
def user_id(self):
"""
Gets the user_id of this StripeCreatePaymentMethod.
The id of the user, if null the logged in user is used. Admin privilege need to specify other users
:return: The user_id of this StripeCreatePaymentMethod.
:rtype: int
"""
return self._user_id
@user_id.setter
def user_id(self, user_id):
"""
Sets the user_id of this StripeCreatePaymentMethod.
The id of the user, if null the logged in user is used. Admin privilege need to specify other users
:param user_id: The user_id of this StripeCreatePaymentMethod.
:type: int
"""
self._user_id = user_id
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_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:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
if not isinstance(other, StripeCreatePaymentMethod):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
| [
"shawn.stout@knetik.com"
] | shawn.stout@knetik.com |
3659a2b734a8ae7a6fb2ade9e3989db5b07aa27a | b6bcaae5169cf20a84edafae98ba649dab6fc67c | /crowdsourcing/migrations/0031_auto_20150814_1743.py | 44b83d71cb9a9fb2a1703c1b2b240fc19baec9be | [
"MIT"
] | permissive | shriyanka/daemo-forum | b7eb84a46799d8c6bcb29a4f5c9996a3d2f40351 | 58c555f69208beedbb0c09f7b7d1e32ab741b2c5 | refs/heads/master | 2023-01-12T05:13:48.804930 | 2015-09-20T01:52:29 | 2015-09-20T01:52:29 | 40,193,653 | 1 | 0 | MIT | 2022-12-26T19:49:24 | 2015-08-04T15:42:57 | Python | UTF-8 | Python | false | false | 536 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('crowdsourcing', '0030_module_is_prototype'),
]
operations = [
migrations.AlterField(
model_name='taskworker',
name='task_status',
field=models.IntegerField(default=1, choices=[(1, b'Created'), (2, b'In Progress'), (3, b'Accepted'), (4, b'Rejected'), (5, b'Returned'), (6, b'Skipped')]),
),
]
| [
"vnarwal95@gmail.com"
] | vnarwal95@gmail.com |
ed2696ece2c7f11ae5a1804ceebdb5ac0c189e4b | 1b5802806cdf2c3b6f57a7b826c3e064aac51d98 | /tensorrt-basic-1.10-3rd-plugin/TensorRT-main/tools/Polygraphy/tests/util/test_util.py | 603cfe59290d516f76cf0746061529cd2862496a | [
"Apache-2.0",
"MIT",
"BSD-3-Clause",
"ISC",
"BSD-2-Clause"
] | permissive | jinmin527/learning-cuda-trt | def70b3b1b23b421ab7844237ce39ca1f176b297 | 81438d602344c977ef3cab71bd04995c1834e51c | refs/heads/main | 2023-05-23T08:56:09.205628 | 2022-07-24T02:48:24 | 2022-07-24T02:48:24 | 517,213,903 | 36 | 18 | null | 2022-07-24T03:05:05 | 2022-07-24T03:05:05 | null | UTF-8 | Python | false | false | 4,759 | py | #
# Copyright (c) 2021, NVIDIA CORPORATION. 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.
#
import os
import tempfile
import random
import numpy as np
import pytest
from polygraphy import util
VOLUME_CASES = [
((1, 1, 1), 1),
((2, 3, 4), 24),
(tuple(), 1),
]
@pytest.mark.parametrize("case", VOLUME_CASES)
def test_volume(case):
it, vol = case
assert util.volume(it) == vol
class FindStrInIterableCase(object):
def __init__(self, name, seq, index, expected):
self.name = name
self.seq = seq
self.index = index
self.expected = expected
FIND_STR_IN_ITERABLE_CASES = [
# Case insensitve, plus function should return element from sequence, not name.
FindStrInIterableCase("Softmax:0", seq=["Softmax:0"], index=None, expected="Softmax:0"),
FindStrInIterableCase("Softmax:0", seq=["softmax:0"], index=None, expected="softmax:0"),
# Exact matches should take priority
FindStrInIterableCase("exact_name", seq=["exact_name_plus", "exact_name"], index=0, expected="exact_name"),
# Index should come into play when no matches are found
FindStrInIterableCase("non-existent", seq=["test", "test2"], index=1, expected="test2"),
]
@pytest.mark.parametrize("case", FIND_STR_IN_ITERABLE_CASES)
def test_find_str_in_iterable(case):
actual = util.find_str_in_iterable(case.name, case.seq, case.index)
assert actual == case.expected
SHAPE_OVERRIDE_CASES = [
((1, 3, 224, 224), (None, 3, 224, 224), True),
]
@pytest.mark.parametrize("case", SHAPE_OVERRIDE_CASES)
def test_is_valid_shape_override(case):
override, shape, expected = case
assert util.is_valid_shape_override(new_shape=override, original_shape=shape) == expected
def arange(shape):
return np.arange(util.volume(shape)).reshape(shape)
SHAPE_MATCHING_CASES = [
(arange((1, 1, 3, 3)), (3, 3), arange((3, 3))), # Squeeze array shape
(
arange((1, 3, 3, 1)),
(1, 1, 3, 3),
arange((1, 1, 3, 3)),
), # Permutation should make no difference as other dimensions are 1s
(arange((3, 3)), (1, 1, 3, 3), arange((1, 1, 3, 3))), # Unsqueeze where needed
(arange((3, 3)), (-1, 3), arange((3, 3))), # Infer dynamic
(arange((3 * 2 * 2,)), (None, 3, 2, 2), arange((1, 3, 2, 2))), # Reshape with inferred dimension
(arange((1, 3, 2, 2)), (None, 2, 2, 3), np.transpose(arange((1, 3, 2, 2)), [0, 2, 3, 1])), # Permute
]
@pytest.mark.parametrize("arr, shape, expected", SHAPE_MATCHING_CASES)
def test_shape_matching(arr, shape, expected):
arr = util.try_match_shape(arr, shape)
assert np.array_equal(arr, expected)
UNPACK_ARGS_CASES = [
((0, 1, 2), 3, (0, 1, 2)), # no extras
((0, 1, 2), 4, (0, 1, 2, None)), # 1 extra
((0, 1, 2), 2, (0, 1)), # 1 fewer
]
@pytest.mark.parametrize("case", UNPACK_ARGS_CASES)
def test_unpack_args(case):
args, num, expected = case
assert util.unpack_args(args, num) == expected
UNIQUE_LIST_CASES = [
([], []),
([3, 1, 2], [3, 1, 2]),
([1, 2, 3, 2, 1], [1, 2, 3]),
([0, 0, 0, 0, 1, 0, 0], [0, 1]),
([5, 5, 5, 5, 5], [5]),
]
@pytest.mark.parametrize("case", UNIQUE_LIST_CASES)
def test_unique_list(case):
lst, expected = case
assert util.unique_list(lst) == expected
def test_find_in_dirs():
with tempfile.TemporaryDirectory() as topdir:
dirs = list(map(lambda x: os.path.join(topdir, x), ["test0", "test1", "test2", "test3", "test4"]))
for subdir in dirs:
os.makedirs(subdir)
path_dir = random.choice(dirs)
path = os.path.join(path_dir, "cudart64_11.dll")
with open(path, "w") as f:
f.write("This file should be found by find_in_dirs")
assert util.find_in_dirs("cudart64_*.dll", dirs) == [path]
@pytest.mark.parametrize(
"val,key,default,expected",
[
(1.0, None, None, 1.0), # Basic
({"inp": "hi"}, "inp", "", "hi"), # Per-key
({"inp": "hi"}, "out", "default", "default"), # Per-key missing
({"inp": 1.0, "": 2.0}, "out", 1.5, 2.0), # Per-key with default
],
)
def test_value_or_from_dict(val, key, default, expected):
actual = util.value_or_from_dict(val, key, default)
assert actual == expected
| [
"dujw@deepblueai.com"
] | dujw@deepblueai.com |
1114c5c8cae950b5a1a32610189346dec1a28cab | e2de3f6fe4373f1d98b67af61dd558a813250d54 | /Algorithm/SWEA/1979_어디에단어가들어갈수있을까.py | 93175b21e67cf70eb4adb26f4ef9209d87578ccf | [] | no_license | Hansung-Lee/TIL | 3fd6d48427a8b24f7889116297143855d493535b | c24ebab8b631f5c1b835fdc8bd036acbebc8d187 | refs/heads/master | 2020-04-14T11:18:54.035863 | 2019-04-05T07:26:55 | 2019-04-05T07:26:55 | 163,810,436 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 897 | py | T = int(input())
for t in range(T):
N, K = map(int, input().split())
li = []
for n in range(N):
li.append(list(map(int, input().split())))
result = 0
# 가로 탐색
for i in range(N):
cnt = 0
li_cnt = []
for j in range(N):
if li[i][j]:
cnt += 1
else:
li_cnt.append(cnt)
cnt = 0
li_cnt.append(cnt)
for c in li_cnt:
if c == K:
result += 1
# 세로 탐색
for j in range(N):
cnt = 0
li_cnt = []
for i in range(N):
if li[i][j]:
cnt += 1
else:
li_cnt.append(cnt)
cnt = 0
li_cnt.append(cnt)
for c in li_cnt:
if c == K:
result += 1
print("#{} {}".format(t + 1, result)) | [
"ajtwlsgkst@naver.com"
] | ajtwlsgkst@naver.com |
f03a7eab93285755d3e953c76c98e043ae312ed6 | 3345eb032afa159a5b4b32fe0b62e4435dac523f | /dingtalk/api/rest/OapiWorkrecordGetbyuseridRequest.py | d717bd7a3da8a6c204e0b0fb304418cb8cfb37c8 | [] | no_license | xududu/dingDingApi | ada6c17e5c6e25fd00bdc4b444171b99bc9ebad7 | b1e7c384eb8fb7f79f6f5a6879faadfa95d3eda3 | refs/heads/master | 2023-08-31T03:04:48.438185 | 2021-10-13T08:52:13 | 2021-10-13T08:52:13 | 416,558,271 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 386 | py | '''
Created by auto_sdk on 2021.04.12
'''
from dingtalk.api.base import RestApi
class OapiWorkrecordGetbyuseridRequest(RestApi):
def __init__(self,url=None):
RestApi.__init__(self,url)
self.limit = None
self.offset = None
self.status = None
self.userid = None
def getHttpMethod(self):
return 'POST'
def getapiname(self):
return 'dingtalk.oapi.workrecord.getbyuserid'
| [
"739893589@qq.com"
] | 739893589@qq.com |
04555a00292a4fcd962bc617a3d285383b9fc443 | 72ce57d187fb6a4730f1390e280b939ef8087f5d | /tests/programs/multiprocessing_using/foo/entry.py | afae227cf29a41243320848b45366e758e91565f | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | tommyli3318/Nuitka | c5b7681b73d96cb8859210ed1a78f09149a23825 | ae52b56024d53159a72a5acbfaac792ca207c418 | refs/heads/develop | 2020-05-02T17:02:10.578065 | 2019-10-27T15:53:32 | 2019-10-27T15:53:32 | 178,086,582 | 1 | 0 | Apache-2.0 | 2019-06-06T00:32:48 | 2019-03-27T22:53:31 | Python | UTF-8 | Python | false | false | 1,758 | py | # Copyright 2019, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Python tests originally created or extracted from other peoples work. The
# parts were too small to be protected.
#
# 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 multiprocessing import Pipe, Process
class MyProcess(Process):
def __init__(self, connection):
super(MyProcess, self).__init__()
self.connection = connection
self.close_issued = False
def run(self):
while not self.close_issued:
op, arg = self.connection.recv()
if op == "add":
self.connection.send(arg + 1)
elif op == "close":
self.close_issued = True
elif op == "method":
self.connection.send(repr(self.run))
def main():
server_channel, client_channel = Pipe()
my_process = MyProcess(client_channel)
my_process.start()
server_channel.send(("add", 4))
print(server_channel.recv())
server_channel.send(("add", 12))
print(server_channel.recv())
server_channel.send(("method", None))
print(("compiled" in server_channel.recv()) == ("compiled" in repr(MyProcess.run)))
server_channel.send(("close", 0))
| [
"kay.hayen@gmail.com"
] | kay.hayen@gmail.com |
02d21508b93f498e1bd78a092c39577fe979db7f | 0e478f3d8b6c323c093455428c9094c45de13bac | /src/OTLMOW/PostenMapping/Model/Post060352180.py | 00f34193546de433cc344122133141ebd1cbd094 | [
"MIT"
] | permissive | davidvlaminck/OTLMOW | c6eae90b2cab8a741271002cde454427ca8b75ba | 48f8c357c475da1d2a1bc7820556843d4b37838d | refs/heads/main | 2023-01-12T05:08:40.442734 | 2023-01-10T15:26:39 | 2023-01-10T15:26:39 | 432,681,113 | 3 | 1 | MIT | 2022-06-20T20:36:00 | 2021-11-28T10:28:24 | Python | UTF-8 | Python | false | false | 3,848 | py | # coding=utf-8
from OTLMOW.PostenMapping.StandaardPost import StandaardPost
from OTLMOW.PostenMapping.StandaardPostMapping import StandaardPostMapping
# Generated with PostenCreator. To modify: extend, do not edit
class Post060352180(StandaardPost):
def __init__(self):
super().__init__(
nummer='0603.52180',
beschrijving='Bestrating van gebakken straatstenen, standaardkwaliteitsklasse B volgens 6-3.6, waalformaat, hoogte ca. 80 mm',
meetstaateenheid='M2',
mappings=[StandaardPostMapping(
typeURI='https://wegenenverkeer.data.vlaanderen.be/ns/onderdeel#BestratingVanGebakkenStraatsteen',
attribuutURI='https://wegenenverkeer.data.vlaanderen.be/ns/onderdeel#BestratingVanGebakkenStraatsteen.formaatVanBestratingselement',
dotnotation='formaatVanBestratingselement',
defaultWaarde='waalformaat-(ca.-200-x-ca.-50-mm)',
range='',
usagenote='',
isMeetstaatAttr=0,
isAltijdInTeVullen=0,
isBasisMapping=1,
mappingStatus='gemapt 2.0',
mappingOpmerking='',
standaardpostnummer='0603.52180')
, StandaardPostMapping(
typeURI='https://wegenenverkeer.data.vlaanderen.be/ns/onderdeel#BestratingVanGebakkenStraatsteen',
attribuutURI='https://wegenenverkeer.data.vlaanderen.be/ns/abstracten#Laag.laagRol',
dotnotation='laagRol',
defaultWaarde='straatlaag',
range='',
usagenote='',
isMeetstaatAttr=0,
isAltijdInTeVullen=0,
isBasisMapping=1,
mappingStatus='gemapt 2.0',
mappingOpmerking='',
standaardpostnummer='0603.52180')
, StandaardPostMapping(
typeURI='https://wegenenverkeer.data.vlaanderen.be/ns/onderdeel#BestratingVanGebakkenStraatsteen',
attribuutURI='https://wegenenverkeer.data.vlaanderen.be/ns/onderdeel#BestratingVanGebakkenStraatsteen.standaardkwaliteitsklasse',
dotnotation='standaardkwaliteitsklasse',
defaultWaarde='b',
range='',
usagenote='',
isMeetstaatAttr=0,
isAltijdInTeVullen=0,
isBasisMapping=1,
mappingStatus='gemapt 2.0',
mappingOpmerking='',
standaardpostnummer='0603.52180')
, StandaardPostMapping(
typeURI='https://wegenenverkeer.data.vlaanderen.be/ns/onderdeel#BestratingVanGebakkenStraatsteen',
attribuutURI='https://wegenenverkeer.data.vlaanderen.be/ns/abstracten#LaagDikte.dikte',
dotnotation='dikte',
defaultWaarde='8',
range='',
usagenote='cm^^cdt:ucumunit',
isMeetstaatAttr=0,
isAltijdInTeVullen=0,
isBasisMapping=1,
mappingStatus='gemapt 2.0',
mappingOpmerking='',
standaardpostnummer='0603.52180')
, StandaardPostMapping(
typeURI='https://wegenenverkeer.data.vlaanderen.be/ns/onderdeel#BestratingVanGebakkenStraatsteen',
attribuutURI='https://wegenenverkeer.data.vlaanderen.be/ns/abstracten#Laag.oppervlakte',
dotnotation='oppervlakte',
defaultWaarde='',
range='',
usagenote='m2^^cdt:ucumunit',
isMeetstaatAttr=1,
isAltijdInTeVullen=1,
isBasisMapping=1,
mappingStatus='gemapt 2.0',
mappingOpmerking='',
standaardpostnummer='0603.52180')])
| [
"david.vlaminck@mow.vlaanderen.be"
] | david.vlaminck@mow.vlaanderen.be |
ad4309aaad99aafddfef6960b654f2844af01886 | 2d13b3206b04d663eed9c5cfe7b6d273abaab33e | /APS/pycharm/humming_bird/1952_swim.py | 7dca279aac14b2798c75f9db2208bd11c860a6c3 | [] | no_license | hdp0545/TIL | 0ba5378274f0076cd2b029581b292785a77207da | 6d6e5e54373bd71606823e97b3a5fb2d63a2784e | refs/heads/master | 2023-05-24T12:37:33.690750 | 2023-05-19T06:57:49 | 2023-05-19T06:57:49 | 235,004,133 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 832 | py | import sys
sys.stdin = open('input.txt', 'r')
def backtrack(check, i, r, k=0):
c = []
global min1
if r > min1:
return
if i == k:
min1 = r
else:
for i in range(10):
if check[i]:
c.append(i)
for i in range(10):
check[c[i]] = False
backtrack(check, k+1, r + prices[2] - plan[c[i]] - plan[c[i]+1] - plan[c[i]+2])
check[c[i]] = True
for test_case in range(1, int(input()) + 1):
prices = list(map(int, input().split()))
plan = list(map(int, input().split()))
check = [True]*12
plan = [prices[1] if plan[i] * prices[0] > prices[1] else plan[i] * prices[0] for i in range(12)]
min1 = sum(plan)
for i in range(1, 5):
backtrack(check, i, min1)
print('#{} {}'.format(test_case, min1))
| [
"hdp0545@gmail.com"
] | hdp0545@gmail.com |
47cd6abdbcf8ebced0d5301d75c1383d027e6fc8 | 638fdc6e95bee246cd8784a3a442bda584295d77 | /prj/main/migrations/0002_auto_20180831_0843.py | 39b0ad364fba271386daa465b8e7e9a307a358c6 | [] | no_license | zdimon/loyer | ac00faf94c4277eb77d6cdc51e8bf99ef2f7ecb2 | 6df6bc76599bc0fab9ef2bdb600cc3b92daf38c1 | refs/heads/master | 2020-03-27T16:03:36.358793 | 2019-04-18T10:05:18 | 2019-04-18T10:05:18 | 146,757,036 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 627 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-08-31 08:43
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='documents',
name='title',
field=models.TextField(blank=True, db_index=True, null=True),
),
migrations.AlterField(
model_name='documents',
name='uid',
field=models.IntegerField(db_index=True, default=0),
),
]
| [
"zdimon@example.com"
] | zdimon@example.com |
1978453a158a8692ae863d135c40bf2facb82ad3 | cc9a87e975546e2ee2957039cceffcb795850d4f | /venv/lib/python3.7/site-packages/pip-19.0.3-py3.7.egg/pip/_internal/utils/glibc.py | 33451aaf3fdfaf6db9a7dd2b7050ff08b8be2151 | [] | no_license | CodeHunterDev/Belajar-Python | 304d3243801b91b3605d2b9bd09e49a30735e51b | 9dd2ffb556eed6b2540da19c5f206fedb218ae99 | refs/heads/master | 2023-03-19T22:12:46.330272 | 2020-02-04T08:02:00 | 2020-02-04T08:02:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,339 | py | # Copyright (c) 2020. Adam Arthur Faizal
from __future__ import absolute_import
import ctypes
import re
import warnings
from pip._internal.utils.typing import MYPY_CHECK_RUNNING
if MYPY_CHECK_RUNNING:
from typing import Optional, Tuple # noqa: F401
def glibc_version_string():
# type: () -> Optional[str]
"Returns glibc version string, or None if not using glibc."
# ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen
# manpage says, "If filename is NULL, then the returned handle is for the
# main program". This way we can let the linker do the work to figure out
# which libc our process is actually using.
process_namespace = ctypes.CDLL(None)
try:
gnu_get_libc_version = process_namespace.gnu_get_libc_version
except AttributeError:
# Symbol doesn't exist -> therefore, we are not linked to
# glibc.
return None
# Call gnu_get_libc_version, which returns a string like "2.5"
gnu_get_libc_version.restype = ctypes.c_char_p
version_str = gnu_get_libc_version()
# py2 / py3 compatibility:
if not isinstance(version_str, str):
version_str = version_str.decode("ascii")
return version_str
# Separated out from have_compatible_glibc for easier unit testing
def check_glibc_version(version_str, required_major, minimum_minor):
# type: (str, int, int) -> bool
# Parse string and check against requested version.
#
# We use a regexp instead of str.split because we want to discard any
# random junk that might come after the minor version -- this might happen
# in patched/forked versions of glibc (e.g. Linaro's version of glibc
# uses version strings like "2.20-2014.11"). See gh-3588.
m = re.match(r"(?P<major>[0-9]+)\.(?P<minor>[0-9]+)", version_str)
if not m:
warnings.warn("Expected glibc version with 2 components major.minor,"
" got: %s" % version_str, RuntimeWarning)
return False
return (int(m.group("major")) == required_major and
int(m.group("minor")) >= minimum_minor)
def have_compatible_glibc(required_major, minimum_minor):
# type: (int, int) -> bool
version_str = glibc_version_string() # type: Optional[str]
if version_str is None:
return False
return check_glibc_version(version_str, required_major, minimum_minor)
# platform.libc_ver regularly returns completely nonsensical glibc
# versions. E.g. on my computer, platform says:
#
# ~$ python2.7 -c 'import platform; print(platform.libc_ver())'
# ('glibc', '2.7')
# ~$ python3.5 -c 'import platform; print(platform.libc_ver())'
# ('glibc', '2.9')
#
# But the truth is:
#
# ~$ ldd --version
# ldd (Debian GLIBC 2.22-11) 2.22
#
# This is unfortunate, because it means that the linehaul data on libc
# versions that was generated by pip 8.1.2 and earlier is useless and
# misleading. Solution: instead of using platform, use our code that actually
# works.
def libc_ver():
# type: () -> Tuple[str, str]
"""Try to determine the glibc version
Returns a tuple of strings (lib, version) which default to empty strings
in case the lookup fails.
"""
glibc_version = glibc_version_string()
if glibc_version is None:
return ("", "")
else:
return ("glibc", glibc_version)
| [
"adam.faizal.af6@gmail.com"
] | adam.faizal.af6@gmail.com |
753c4c3e24bac3182235acb0a7cee84059e81741 | f0d713996eb095bcdc701f3fab0a8110b8541cbb | /r9y4yrSAGRaqTT7nM_15.py | 7b62749e1863b060425e123beb46d6163901c3ca | [] | no_license | daniel-reich/turbo-robot | feda6c0523bb83ab8954b6d06302bfec5b16ebdf | a7a25c63097674c0a81675eed7e6b763785f1c41 | refs/heads/main | 2023-03-26T01:55:14.210264 | 2021-03-23T16:08:01 | 2021-03-23T16:08:01 | 350,773,815 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,025 | py | """
Create a function that takes a list of lists and return the length of the
missing list.
### Examples
find_missing([[1], [1, 2], [4, 5, 1, 1], [5, 6, 7, 8, 9]]) ➞ 3
find_missing([[5, 6, 7, 8, 9], [1, 2], [4, 5, 1, 1], [1]]) ➞ 3
find_missing([[4, 4, 4, 4], [1], [3, 3, 3]]) ➞ 2
### Notes
* Test input lists won't always be sorted in order of length.
* If the list of lists is `None` or empty, your function should return `False`.
* If a list within the parent list is `None` or empty, return `False`.
* There will always be a missing element and its length will be between the given lists.
"""
def handle_nonsense(f):
def g(lst):
if not lst or [] in lst:
return False
return f(lst)
return g
@handle_nonsense
def find_missing(lst):
sizes = set(len(subl) for subl in lst)
high, low = max(sizes), min(sizes)
intended_sizes = set(range(low, high+1))
missing_sizes = intended_sizes - sizes
return missing_sizes.pop()
| [
"daniel.reich@danielreichs-MacBook-Pro.local"
] | daniel.reich@danielreichs-MacBook-Pro.local |
f112df2231e948cf0244cc3c56d20923a3597f51 | 982539edb302b6bee5dd9285e9de00ad866b4cfd | /Transform/TransformH5/main.py | b3e608eb7900102705e76ae1dcd40c31ba29d973 | [] | no_license | chennqqi/OpenSaaSProj | 2149a2066c607636ce2106801be2cb722cc0934d | 0f861a61d1bd1499599207a70a8e180930d96573 | refs/heads/master | 2020-04-04T16:14:08.943396 | 2017-06-01T06:50:32 | 2017-06-01T06:50:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,101 | py | # -*- coding: utf-8 -*-
import sys
import time
import gzip
from Transform import Transform
from LogStore import LogStore
import json
import re
ip_pattern = re.compile(r'''"((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))"''')
def main(timestamp, src_logpath_format="/data1/nginxlogs/jhsaaslogs_h5/access_jhlogs.%(yyyymmddhhmm)s",
errlog_path_format="/data1/logs/transformh5/err/%(yyyymmdd)s/%(hhmm)s.err",
filename_format="/data1/logs/transformh5/%(datatype)s/%(yyyymmdd)s/%(hhmm)s.log"):
yyyymmddhhmm = time.strftime('%Y%m%d%H%M', time.localtime(timestamp))
yyyymmdd = time.strftime('%Y%m%d', time.localtime(timestamp))
hhmm = time.strftime('%H%M', time.localtime(timestamp))
src_logpath = src_logpath_format % {"yyyymmddhhmm": yyyymmddhhmm, "yyyymmdd": yyyymmdd}
errlog_path = errlog_path_format % {"yyyymmddhhmm": yyyymmddhhmm, "yyyymmdd": yyyymmdd, "hhmm": hhmm}
print src_logpath
if src_logpath.endswith(".gz"):
src_logpath_file = gzip.open(src_logpath)
else:
src_logpath_file = open(src_logpath)
try:
transform = Transform(timestamp=timestamp)
except:
transform = Transform()
for line in src_logpath_file:
try:
# ip = line.split(",")[0].strip()
# # 如果为内网ip,做单独处理
# try:
# if ip.startswith("127"):
# ip = ip_pattern.search(line).group(1)
# except:
# import traceback
# print(traceback.print_exc())
data = transform.transform(line)
# data = json.loads(lod_line)
# data["ip"] = ip
if not data:
continue
datatype = data["appkey"]
filename = filename_format % {"datatype": datatype, "yyyymmdd": yyyymmdd, "hhmm": hhmm}
LogStore(filename, json.dumps(data))
except Exception, e:
LogStore(errlog_path, "%s, %s"%(e, line.strip()))
if not src_logpath.endswith(".gz"):
src_logpath_file.close()
LogStore.finished(iszip=True)
if __name__ == "__main__":
if 'transform_h5' in sys.argv:
src_logpath_format = "/data1/nginxlogs/jhsaaslogs_h5/access_jhlogs.%(yyyymmddhhmm)s"
errlog_path_format = "/data1/logs/transformh5/err/%(yyyymmdd)s/%(hhmm)s.err"
filename_format = "/data1/logs/transformh5/%(datatype)s/%(yyyymmdd)s/%(hhmm)s.log"
timestamp = int(time.time()-60*5)
main(timestamp, src_logpath_format=src_logpath_format,
errlog_path_format=errlog_path_format,
filename_format=filename_format)
if 'store' in sys.argv:
# startstamp = time.mktime(time.strptime('20160501+000100', '%Y%m%d+%H%M%S'))
# endstamp = time.mktime(time.strptime('20160602+000000', '%Y%m%d+%H%M%S'))
startstamp = time.mktime(time.strptime('20161124+000000', '%Y%m%d+%H%M%S'))
# startstamp = time.mktime(time.strptime('20160808+000000', '%Y%m%d+%H%M%S'))
endstamp = time.mktime(time.strptime('20161206+235900', '%Y%m%d+%H%M%S'))
while startstamp <= endstamp:
today = time.strftime("%Y%m%d", time.localtime(time.time()))
today_begin_stamp = time.mktime(time.strptime("".join([today, "000000"]), "%Y%m%d%H%M%S"))
# main(endstamp, src_logpath_format = "/data1/nginxlogs/jhlogs/%(yyyymmdd)s/access_jhlogs.%(yyyymmddhhmm)s.gz")
try:
if endstamp >= today_begin_stamp:
main(endstamp,
src_logpath_format = "/data1/nginxlogs/jhsaaslogs_h5/access_jhlogs.%(yyyymmddhhmm)s")
else:
main(endstamp,
src_logpath_format="/data1/nginxlogs/jhsaaslogs_h5/%(yyyymmdd)s/access_jhlogs.%(yyyymmddhhmm)s.gz")
# main(endstamp, src_logpath_format = "/data1/nginxlogs/jhlogs/access_jhlogs.%(yyyymmddhhmm)s")
except:
import traceback
print traceback.print_exc()
endstamp -= 60
| [
"sudazhuang1@163.com"
] | sudazhuang1@163.com |
fa408f0d646001c72d5862e1fca3ef6a15a7a714 | 3851d5eafcc5fd240a06a7d95a925518412cafa0 | /Django_Code/gs122/gs122/asgi.py | c85136de3ebbdca091f1249ffba5478c629e3e76 | [] | no_license | Ikshansaleem/DjangoandRest | c0fafaecde13570ffd1d5f08019e04e1212cc2f3 | 0ccc620ca609b4ab99a9efa650b5893ba65de3c5 | refs/heads/master | 2023-01-31T04:37:57.746016 | 2020-12-10T06:27:24 | 2020-12-10T06:27:24 | 320,180,735 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 403 | py | """
ASGI config for gs122 project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'gs122.settings')
application = get_asgi_application()
| [
"ikshan3108@gmail.com"
] | ikshan3108@gmail.com |
d589011ac89500a27079781cb8e2f5df0d7c1348 | b1d8ae9f007b45075c67fc7c4006e9e72a604544 | /clases-daniel_python/ejercicios/2_ejercicio.py | 092d942e4605afabc4426c97e34c89f50800cbab | [] | no_license | WilliamPerezBeltran/studying_python | 019b488818934c471c9322d9a1cb16f095df193e | 4b4140bfce41192506b569787ba7aae50baeae62 | refs/heads/master | 2023-02-07T11:26:37.190849 | 2020-12-26T02:31:12 | 2020-12-26T02:31:12 | 263,965,428 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 744 | py | """
valor suministrado 5
resultado 1335555777777779999999999999999
n = 5 => 1 33 5555 77777777 9999999999999999
tenemos que 1,3,5,7,9 son impares
1. la secuencia esta formada por numeros impares
2. cada numero impar se escribe tantas veces como lo indique
la potencia de 2 correspondiente
2**0 = 1
2**1 = 2
2**2 = 4
2**3 = 8
2**4 = 16
3. la cantidad de grupos de numeros impares coincide con el valor dado por el usuario
"""
import sys
import pdb
def serie(n):
impar = 1
nuevo_array = []
for p in range(n):
for x in range(2**p):
nuevo_array.append(impar)
impar +=2
return nuevo_array
def main():
arg = sys.argv[1:]
print(*serie(int(arg[0])),sep=" ")
if __name__=='__main__':
main()
| [
"williampbeltranprogramador@gmail.com"
] | williampbeltranprogramador@gmail.com |
cfdd02f3fa46bf4d815b93c065a34ccc6a1de9da | 1825283527f5a479204708feeaf55f4ab6d1290b | /leetcode/python/269/sol.py | 5e90e005dcb2da2d492583fdd25737e164210050 | [] | no_license | frankieliu/problems | b82c61d3328ffcc1da2cbc95712563355f5d44b5 | 911c6622448a4be041834bcab25051dd0f9209b2 | refs/heads/master | 2023-01-06T14:41:58.044871 | 2019-11-24T03:47:22 | 2019-11-24T03:47:22 | 115,065,956 | 1 | 0 | null | 2023-01-04T07:25:52 | 2017-12-22T02:06:57 | HTML | UTF-8 | Python | false | false | 2,689 | py |
16/18 lines Python, 30 lines C++
https://leetcode.com/problems/alien-dictionary/discuss/70137
* Lang: python3
* Author: StefanPochmann
* Votes: 74
Two similar solutions. Both first go through the word list to find letter pairs `(a, b)` where `a` must come before `b` in the alien alphabet. The first solution just works with these pairs, the second is a bit smarter and uses successor/predecessor sets. Doesn't make a big difference here, though, I got both accepted in 48 ms.
**Solution 1**
def alienOrder(self, words):
less = []
for pair in zip(words, words[1:]):
for a, b in zip(*pair):
if a != b:
less += a + b,
break
chars = set(''.join(words))
order = []
while less:
free = chars - set(zip(*less)[1])
if not free:
return ''
order += free
less = filter(free.isdisjoint, less)
chars -= free
return ''.join(order + list(chars))
**Solution 2**
def alienOrder(self, words):
pre, suc = collections.defaultdict(set), collections.defaultdict(set)
for pair in zip(words, words[1:]):
for a, b in zip(*pair):
if a != b:
suc[a].add(b)
pre[b].add(a)
break
chars = set(''.join(words))
free = chars - set(pre)
order = ''
while free:
a = free.pop()
order += a
for b in suc[a]:
pre[b].discard(a)
if not pre[b]:
free.add(b)
return order * (set(order) == chars)
**C++ version of solution 2**
string alienOrder(vector<string>& words) {
map<char, set<char>> suc, pre;
set<char> chars;
string s;
for (string t : words) {
chars.insert(t.begin(), t.end());
for (int i=0; i<min(s.size(), t.size()); ++i) {
char a = s[i], b = t[i];
if (a != b) {
suc[a].insert(b);
pre[b].insert(a);
break;
}
}
s = t;
}
set<char> free = chars;
for (auto p : pre)
free.erase(p.first);
string order;
while (free.size()) {
char a = *begin(free);
free.erase(a);
order += a;
for (char b : suc[a]) {
pre[b].erase(a);
if (pre[b].empty())
free.insert(b);
}
}
return order.size() == chars.size() ? order : "";
}
| [
"frankie.y.liu@gmail.com"
] | frankie.y.liu@gmail.com |
b4d44bc8958e2e1127f9bec0857c5cb993327ab9 | 4e4e18eb93925ff60b35632e09e93ab1ed1f583b | /schedule_sim/tools/graphic_utils.py | e2255614289b463a1a137fd1d97ddbffde1f6455 | [
"MIT"
] | permissive | DanielLSM/schedule-sim | 47d440356268622b2c962ff8950098f2397e674b | 9230ea3db774105eebe643c8baf054a518f4f7e7 | refs/heads/master | 2020-04-17T08:59:13.640648 | 2019-03-19T14:23:25 | 2019-03-19T14:23:25 | 166,437,907 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,168 | py | colors = {
'white': [255] * 4,
'black': [0] * 4,
'red': [255, 0, 0, 255],
'yellow': [255, 255, 0, 255],
'blue': [0, 0, 255, 255],
'green': [0, 255, 0, 255]
}
RESOURCES_PATH = "../../resources/"
def state_to_color(state):
if state < 0:
return colors['red']
elif 0 <= state < 0.1:
return colors['yellow']
elif 0.1 <= state <= 1:
#saturated green
return [0, 255, 0, int(convert_to_saturation(state))]
else:
import ipdb
ipdb.set_trace()
raise ("STATE IS INVALID!!!")
# Convert from 0 to 1 to 0 to 255
def convert_to_saturation(saturation_level):
return (round(saturation_level * 255))
def scale_to_window(image, width, height):
# https://stackoverflow.com/questions/24788003/how-do-you-resize-an-image-in-python-using-pyglet
# image.scale = min(image.height, height)/max(image.height, height)), max(min(width, image.width)/max(width, image.width)
scale_x = min(width, image.width) / max(width, image.width)
scale_y = min(image.height, height) / max(image.height, height)
return scale_x, scale_y
if __name__ == '__main__':
print("hello") | [
"daniellsmarta@gmail.com"
] | daniellsmarta@gmail.com |
73011ee72cca0a99a4d1f0535d01af66c35d80e6 | 674b823a735f9fffa7a20fbb1ef977a6c9652667 | /Lesson_6/some test/log.py | a69c64b50eac96be6bf881dd1aa1eb3f6ebf06ad | [] | no_license | igoregizarov/clientservapp | fc141cc093037c4442a650291e137e1369584752 | 1c6b9f37acf1c173001a1237d8b0d21b23005b57 | refs/heads/master | 2023-03-25T06:14:00.291558 | 2021-03-21T06:57:54 | 2021-03-21T06:57:54 | 334,572,078 | 0 | 0 | null | 2021-03-21T09:33:51 | 2021-01-31T04:29:05 | Python | UTF-8 | Python | false | false | 513 | py | import logging
logger = logging.getLogger('app')
format = logging.Formatter('%(levelname)-10s %(asctime)s %(message)s')
file_handler = logging.FileHandler('app.log', encoding='utf-8')
file_handler.setLevel(logging.INFO)
file_handler.setFormatter(format)
logger.addHandler(file_handler)
logger.setLevel(logging.INFO)
if __name__ == '__main__':
console = logging.StreamHandler()
console.setLevel(logging.INFO)
console.setFormatter(format)
logger.addHandler(console)
logger.info('my logger') | [
"i_gor88@mail.ru"
] | i_gor88@mail.ru |
4fa932368de8c1a9a54b7f71b537ee4dc62ff0ba | fd1dba8223ad1938916369b5eb721305ef197b30 | /AtCoder/ABC/abc089/abc089d.py | 7b074ee3fa719b25e44bdebb03df55da23940c2d | [] | no_license | genkinanodesu/competitive | a3befd2f4127e2d41736655c8d0acfa9dc99c150 | 47003d545bcea848b409d60443655edb543d6ebb | refs/heads/master | 2020-03-30T07:41:08.803867 | 2019-06-10T05:22:17 | 2019-06-10T05:22:17 | 150,958,656 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 546 | py | import numpy as np
H, W, D = map(int, input().split())
grid = np.array([[0, 0]] * (H * W))
for i in range(H):
Ai = list(map(int, input().split()))
for j in range(W):
grid[Ai[j] - 1] = [i, j]
Q = int(input())
tasks = [list(map(int, input().split())) for _ in range(Q)]
accum = [0] * (H*W)
for i in range(H * W):
if i >= D:
accum[i] = accum[i - D] + abs(grid[i][0] - grid[i - D][0]) + abs(grid[i][1] - grid[i - D][1])
for q in range(Q):
Li, Ri = tasks[q]
print(accum[Ri - 1] - accum[Li - 1])
| [
"s.genki0605@gmail.com"
] | s.genki0605@gmail.com |
40d0d4730eca07faba09f725f7b01a531e1bfcdf | 9abe914e718155f3a560915c56a55996155159fb | /billing_profiles/models.py | a5dcaf5c9fc4962638c32d5531865441525d0eae | [] | no_license | Chaoslecion123/Tienda-Django | 07c8e2abe8cf659a4fce910c2b8fc858d9276e3b | d06e0c789bab69472d0931b2322e7da4f2eaa3bd | refs/heads/master | 2022-03-28T18:07:38.083362 | 2019-12-11T20:01:59 | 2019-12-11T20:01:59 | 227,241,041 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,138 | py | from django.db import models
from users.models import User
from stripeAPI.card import create_card
class BillingProfileManager(models.Manager):
def create_by_stripe_token(self,user,stripe_token):
if user.has_customer() and stripe_token:
source = create_card(user,stripe_token)
return self.create(
user=user,
card_id=source.id,
last4=source.last4,
token=stripe_token,
brand=source.brand,
default= not user.has_billing_profile()
)
class BillingProfile(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE)
token = models.CharField(max_length=50,null=False,blank=False)
card_id = models.CharField(max_length=50,null=False,blank=False)
last4 = models.CharField(max_length=4,null=False,blank=False)
brand = models.CharField(max_length=10,null=False,blank=False)
default = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
objects = BillingProfileManager()
def __str__(self):
return self.card_id | [
"chaoslecion71@gmail.com"
] | chaoslecion71@gmail.com |
306cff00aa1430a3834005bd05e292ce9a245b64 | 39689ee725bc7183d5d59fb34f7d2ffe5fd6ad36 | /ARC_A/ARC039A.py | 784579704af3c60ba55bb0c218f9b23ceaf8e357 | [] | no_license | yu5shi8/AtCoder | b6eb920a9046bdfa98012dd3fc65f75f16214ffe | f9ca69001ece8379e3a70c993c44b540f8be2217 | refs/heads/master | 2021-06-15T17:58:07.027699 | 2021-03-20T14:04:03 | 2021-03-20T14:04:03 | 177,757,053 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 432 | py | # -*- coding: utf-8 -*-
# A - A - B problem
# https://atcoder.jp/contests/arc039/tasks/arc039_a
A, B = input().split()
ans = []
ans.append(int('9' + A[1:]) - int(B))
ans.append(int(A[:1] + '9' + A[2:]) - int(B))
ans.append(int(A[:2] + '9') - int(B))
ans.append(int(A) - int('1' + B[1:]))
ans.append(int(A) - int(B[:1] + '0' + B[2:]))
ans.append(int(A) - int(B[:2] + '0'))
print(max(ans))
# 13:45 - 13:52(WA)- 14:35(AC)
| [
"royal_unicorn411@hotmail.co.jp"
] | royal_unicorn411@hotmail.co.jp |
d2071f73be7b293cffa348e5572eabc7ab442d13 | 7f4b1d5e9963d63dd45b31c6cad8ced70d823217 | /Crypto/websockets_btcusd.py | b81750d26f341253848c146deaa7a67c4c3c3f05 | [] | no_license | mdhatmaker/Misc-python | b8be239619788ed343eb55b24734782e227594dc | 92751ea44f4c1d0d4ba60f5a1bb9c0708123077b | refs/heads/master | 2023-08-24T05:23:44.938059 | 2023-08-09T08:30:12 | 2023-08-09T08:30:12 | 194,360,769 | 3 | 4 | null | 2022-12-27T15:19:06 | 2019-06-29T03:39:13 | Python | UTF-8 | Python | false | false | 2,327 | py | import websocket
import ast
import json
import sqlite3
class DataFeed():
def __init__(self):
#create database
file = "myDB.db"
self.path = "/Users/michael/Dropbox/dev/PROJECTS/python-projects/data/"+file
self.db = sqlite3.connect(self.path)
self.cursor = self.db.cursor()
self.cursor.execute(
"""CREATE TABLE ok_btcusd_depth(
bid REAL,
bid_amount REAL,
ask REAL,
ask_amount REAL)
""")
self.cursor.execute(
"""CREATE TABLE ok_btcusd_trades(
price REAL,
amount REAL,
time TEXT,
type TEXT)
""")
self.db.commit()
#connect to websocket
url = "wss://real.okcoin.com:10440/websocket/okcoinapi"
self.ws = websocket.WebSocketApp(url,
on_message=self.on_message,
on_error=self.on_error
)
self.ws.on_open = self.on_open
self.ws.run_forever()
def on_message(self,ws,msg):
msg = ast.literal_eval(msg) #convert string to list
table = msg[0]["channel"]
data = msg[0]["data"]
if table == "ok_btcusd_depth":
bid_info = data["bids"][0]
ask_info = data["asks"][0]
Tuple = (bid_info[0],bid_info[1],ask_info[0],ask_info[1])
self.cursor.execute(
"""INSERT INTO ok_btcusd_depth(
bid,bid_amount,ask,ask_amount)
VALUES(?,?,?,?)""",Tuple )
else:
for trade in data:
Tuple = (float(trade[0]),float(trade[1]),trade[2],trade[3])
self.cursor.execute(
"""INSERT INTO ok_btcusd_trades(price,amount,time,type)
VALUES(?,?,?,?)""",Tuple)
self.db.commit()
def on_error(self,ws,error):
print(error)
def on_open(self,ws):
request = [{"event":"addChannel","channel":"ok_btcusd_depth"},
{"event":"addChannel","channel":"ok_btcusd_trades"}]
request = json.dumps(request)
request = request.encode("utf-8")
ws.send(request)
if __name__ == "__main__":
DataFeed()
| [
"mhatmaker@gmail.com"
] | mhatmaker@gmail.com |
87aea39f12b2409411d0d135b8b3d23715f8c1dd | 93ebc4c7a8ebb82fe54838c28fa8b70008cdf4cd | /src/lib/Bcfg2/Server/FileMonitor/Fam.py | d1420c105b1c60af9cda5c4a3ccf695a32e9a243 | [
"mpich2",
"LicenseRef-scancode-other-permissive",
"BSD-2-Clause"
] | permissive | psteinbachs/bcfg2 | 74026df83522a358b8f720010f833bfdd6742159 | be3b4dc28b8e4adfb9e0de86d7297599adac77f5 | refs/heads/master | 2020-12-25T10:23:54.687681 | 2012-10-11T17:13:21 | 2012-10-11T17:13:21 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,835 | py | """ Fam provides FAM support for file alteration events """
import os
import _fam
import stat
import logging
from time import time
from Bcfg2.Server.FileMonitor import FileMonitor
LOGGER = logging.getLogger(__name__)
class Fam(FileMonitor):
""" file monitor with support for FAM """
__priority__ = 90
def __init__(self, ignore=None, debug=False):
FileMonitor.__init__(self, ignore=ignore, debug=debug)
self.filemonitor = _fam.open()
self.users = {}
def fileno(self):
"""Return fam file handle number."""
return self.filemonitor.fileno()
def handle_event_set(self, _=None):
self.Service()
def handle_events_in_interval(self, interval):
now = time()
while (time() - now) < interval:
if self.Service():
now = time()
def AddMonitor(self, path, obj, _=None):
"""Add a monitor to path, installing a callback to obj.HandleEvent."""
mode = os.stat(path)[stat.ST_MODE]
if stat.S_ISDIR(mode):
handle = self.filemonitor.monitorDirectory(path, None)
else:
handle = self.filemonitor.monitorFile(path, None)
self.handles[handle.requestID()] = handle
if obj != None:
self.users[handle.requestID()] = obj
return handle.requestID()
def Service(self, interval=0.50):
"""Handle all fam work."""
count = 0
collapsed = 0
rawevents = []
start = time()
now = time()
while (time() - now) < interval:
if self.filemonitor.pending():
while self.filemonitor.pending():
count += 1
rawevents.append(self.filemonitor.nextEvent())
now = time()
unique = []
bookkeeping = []
for event in rawevents:
if self.should_ignore(event):
continue
if event.code2str() != 'changed':
# process all non-change events
unique.append(event)
else:
if (event.filename, event.requestID) not in bookkeeping:
bookkeeping.append((event.filename, event.requestID))
unique.append(event)
else:
collapsed += 1
for event in unique:
if event.requestID in self.users:
try:
self.users[event.requestID].HandleEvent(event)
except: # pylint: disable=W0702
LOGGER.error("Handling event for file %s" % event.filename,
exc_info=1)
end = time()
LOGGER.info("Processed %s fam events in %03.03f seconds. "
"%s coalesced" % (count, (end - start), collapsed))
return count
| [
"chris.a.st.pierre@gmail.com"
] | chris.a.st.pierre@gmail.com |
43e02b8e529339b6e6fc7eb8cef2a4f061e9dc65 | 2161711dcdc06abe39d96082edcc91ba4de95668 | /swagger_client/models/inline_response_200_45.py | 4a9e83e87873419314bec5a1ecd0cf3556609bdd | [] | no_license | PriceTT/swagger-piwebapi-python | 7eb25c329b33a76785cdb0484fae0dfb354722e2 | 20a4a47a38dfe7051b1a35831fb6cd3d2a19679a | refs/heads/master | 2021-06-18T21:21:48.808589 | 2017-06-15T18:44:48 | 2017-06-15T18:44:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,417 | py | # coding: utf-8
"""
PI Web API 2017 Swagger Spec
Swagger Spec file that describes PI Web API
OpenAPI spec version: 1.9.0.266
Contact: techsupport@osisoft.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class InlineResponse20045(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, product_title=None, product_version=None, links=None):
"""
InlineResponse20045 - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition.
"""
self.swagger_types = {
'product_title': 'str',
'product_version': 'str',
'links': 'InlineResponse20045Links'
}
self.attribute_map = {
'product_title': 'ProductTitle',
'product_version': 'ProductVersion',
'links': 'Links'
}
self._product_title = product_title
self._product_version = product_version
self._links = links
@property
def product_title(self):
"""
Gets the product_title of this InlineResponse20045.
:return: The product_title of this InlineResponse20045.
:rtype: str
"""
return self._product_title
@product_title.setter
def product_title(self, product_title):
"""
Sets the product_title of this InlineResponse20045.
:param product_title: The product_title of this InlineResponse20045.
:type: str
"""
self._product_title = product_title
@property
def product_version(self):
"""
Gets the product_version of this InlineResponse20045.
:return: The product_version of this InlineResponse20045.
:rtype: str
"""
return self._product_version
@product_version.setter
def product_version(self, product_version):
"""
Sets the product_version of this InlineResponse20045.
:param product_version: The product_version of this InlineResponse20045.
:type: str
"""
self._product_version = product_version
@property
def links(self):
"""
Gets the links of this InlineResponse20045.
:return: The links of this InlineResponse20045.
:rtype: InlineResponse20045Links
"""
return self._links
@links.setter
def links(self, links):
"""
Sets the links of this InlineResponse20045.
:param links: The links of this InlineResponse20045.
:type: InlineResponse20045Links
"""
self._links = links
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_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:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
if not isinstance(other, InlineResponse20045):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
| [
"eng@dstcontrols.com"
] | eng@dstcontrols.com |
f2fe34339d878e77d9419f0c501fb8660eb39dc6 | 2e682fd72e3feaa70e3f7bf2a3b83c50d783ec02 | /PyTorch/contrib/cv/detection/FCOS/configs/_base_/models/cascade_rcnn_r50_fpn.py | 303276b845fecd041d093e240046de08b6016638 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference",
"GPL-1.0-or-later"
] | permissive | Ascend/ModelZoo-PyTorch | 4c89414b9e2582cef9926d4670108a090c839d2d | 92acc188d3a0f634de58463b6676e70df83ef808 | refs/heads/master | 2023-07-19T12:40:00.512853 | 2023-07-17T02:48:18 | 2023-07-17T02:48:18 | 483,502,469 | 23 | 6 | Apache-2.0 | 2022-10-15T09:29:12 | 2022-04-20T04:11:18 | Python | UTF-8 | Python | false | false | 6,001 | py | # model settings
model = dict(
type='CascadeRCNN',
pretrained='torchvision://resnet50',
backbone=dict(
type='ResNet',
depth=50,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dict(type='BN', requires_grad=True),
norm_eval=True,
style='pytorch'),
neck=dict(
type='FPN',
in_channels=[256, 512, 1024, 2048],
out_channels=256,
num_outs=5),
rpn_head=dict(
type='RPNHead',
in_channels=256,
feat_channels=256,
anchor_generator=dict(
type='AnchorGenerator',
scales=[8],
ratios=[0.5, 1.0, 2.0],
strides=[4, 8, 16, 32, 64]),
bbox_coder=dict(
type='DeltaXYWHBBoxCoder',
target_means=[.0, .0, .0, .0],
target_stds=[1.0, 1.0, 1.0, 1.0]),
loss_cls=dict(
type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0),
loss_bbox=dict(type='SmoothL1Loss', beta=1.0 / 9.0, loss_weight=1.0)),
roi_head=dict(
type='CascadeRoIHead',
num_stages=3,
stage_loss_weights=[1, 0.5, 0.25],
bbox_roi_extractor=dict(
type='SingleRoIExtractor',
roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=0),
out_channels=256,
featmap_strides=[4, 8, 16, 32]),
bbox_head=[
dict(
type='Shared2FCBBoxHead',
in_channels=256,
fc_out_channels=1024,
roi_feat_size=7,
num_classes=80,
bbox_coder=dict(
type='DeltaXYWHBBoxCoder',
target_means=[0., 0., 0., 0.],
target_stds=[0.1, 0.1, 0.2, 0.2]),
reg_class_agnostic=True,
loss_cls=dict(
type='CrossEntropyLoss',
use_sigmoid=False,
loss_weight=1.0),
loss_bbox=dict(type='SmoothL1Loss', beta=1.0,
loss_weight=1.0)),
dict(
type='Shared2FCBBoxHead',
in_channels=256,
fc_out_channels=1024,
roi_feat_size=7,
num_classes=80,
bbox_coder=dict(
type='DeltaXYWHBBoxCoder',
target_means=[0., 0., 0., 0.],
target_stds=[0.05, 0.05, 0.1, 0.1]),
reg_class_agnostic=True,
loss_cls=dict(
type='CrossEntropyLoss',
use_sigmoid=False,
loss_weight=1.0),
loss_bbox=dict(type='SmoothL1Loss', beta=1.0,
loss_weight=1.0)),
dict(
type='Shared2FCBBoxHead',
in_channels=256,
fc_out_channels=1024,
roi_feat_size=7,
num_classes=80,
bbox_coder=dict(
type='DeltaXYWHBBoxCoder',
target_means=[0., 0., 0., 0.],
target_stds=[0.033, 0.033, 0.067, 0.067]),
reg_class_agnostic=True,
loss_cls=dict(
type='CrossEntropyLoss',
use_sigmoid=False,
loss_weight=1.0),
loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0))
]))
# model training and testing settings
train_cfg = dict(
rpn=dict(
assigner=dict(
type='MaxIoUAssigner',
pos_iou_thr=0.7,
neg_iou_thr=0.3,
min_pos_iou=0.3,
match_low_quality=True,
ignore_iof_thr=-1),
sampler=dict(
type='RandomSampler',
num=256,
pos_fraction=0.5,
neg_pos_ub=-1,
add_gt_as_proposals=False),
allowed_border=0,
pos_weight=-1,
debug=False),
rpn_proposal=dict(
nms_across_levels=False,
nms_pre=2000,
nms_post=2000,
max_num=2000,
nms_thr=0.7,
min_bbox_size=0),
rcnn=[
dict(
assigner=dict(
type='MaxIoUAssigner',
pos_iou_thr=0.5,
neg_iou_thr=0.5,
min_pos_iou=0.5,
match_low_quality=False,
ignore_iof_thr=-1),
sampler=dict(
type='RandomSampler',
num=512,
pos_fraction=0.25,
neg_pos_ub=-1,
add_gt_as_proposals=True),
pos_weight=-1,
debug=False),
dict(
assigner=dict(
type='MaxIoUAssigner',
pos_iou_thr=0.6,
neg_iou_thr=0.6,
min_pos_iou=0.6,
match_low_quality=False,
ignore_iof_thr=-1),
sampler=dict(
type='RandomSampler',
num=512,
pos_fraction=0.25,
neg_pos_ub=-1,
add_gt_as_proposals=True),
pos_weight=-1,
debug=False),
dict(
assigner=dict(
type='MaxIoUAssigner',
pos_iou_thr=0.7,
neg_iou_thr=0.7,
min_pos_iou=0.7,
match_low_quality=False,
ignore_iof_thr=-1),
sampler=dict(
type='RandomSampler',
num=512,
pos_fraction=0.25,
neg_pos_ub=-1,
add_gt_as_proposals=True),
pos_weight=-1,
debug=False)
])
test_cfg = dict(
rpn=dict(
nms_across_levels=False,
nms_pre=1000,
nms_post=1000,
max_num=1000,
nms_thr=0.7,
min_bbox_size=0),
rcnn=dict(
score_thr=0.05,
nms=dict(type='nms', iou_threshold=0.5),
max_per_img=100))
| [
"wangjiangben@huawei.com"
] | wangjiangben@huawei.com |
b43f026cb592af4b22ac9eaf0451a1c813df7f99 | 9b82b0275f7b8365fbe8437c1b59b492e8ac0f82 | /speech_recog.py | ae0d69f3aacff9470419c4029f1ccf53c0f46232 | [] | no_license | aspiringguru/FastAI_Part1_Version2_2018 | 6414f80adf26efe32785add68d0f7cf845376c38 | d1a215fa8ec2cc70807976f46b45cba9c1eb4cd9 | refs/heads/master | 2021-04-15T14:50:16.542383 | 2018-04-02T10:51:16 | 2018-04-02T10:51:16 | 126,747,845 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 795 | py | #pip install SpeechRecognition
#https://github.com/Uberi/speech_recognition
#https://stackoverflow.com/questions/41525200/convert-mp4-sound-to-text-in-python?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
import urllib
import speech_recognition as sr
import subprocess
import os
#url = 'https://blah'
#mp4file = urllib.urlopen(url)
#with open("input_file.mp4", "wb") as handle:
# handle.write(mp4file.read())
cmdline = ['avconv',
'-i',
'test.mp4',
'-vn',
'-f',
'wav',
'test.wav']
subprocess.call(cmdline)
r = sr.Recognizer()
with sr.AudioFile('test.wav') as source:
audio = r.record(source)
command = r.recognize_google(audio)
print (command)
#os.remove("test.mp4")
#os.remove("test.wav")
| [
"bmatthewtaylor@gmail.com"
] | bmatthewtaylor@gmail.com |
9db36c59cd13dc2a71fedd9cc08cc17c83185b33 | 678e276a81c6b9f7c58b4e8e40d35ac7a9c3d770 | /apps/core/urls.py | 7cd68d43bd12a9835e6e47eef036f2344bb32512 | [] | no_license | jaimeceballos/tp_final | dd030d6876f7a59d8ef66f9ff58e26589c0fa2ee | 614b8f6d30fe23f75df69399088b317c68f600c8 | refs/heads/master | 2021-03-30T19:45:54.376363 | 2016-07-06T14:01:20 | 2016-07-06T14:01:20 | 59,871,513 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,700 | py | from django.conf.urls import include, url
from .views import *
urlpatterns = [
#url(r'^$', auth_views.login, {'template_name': 'login.html'},name='login'),
url(r'^contacto/$',contacto_emergencia,name='contacto'),
url(r'^contacto_save/$',save_contacto,name='contacto_save'),
url(r'^obtenerciudades/(?P<provincia>[0-9A-Za-z]+)/$', obtener_ciudades, name = 'obtener_ciudades'),
url(r'^ver_contactos/$',ver_contactos, name='ver_contactos'),
url(r'^obtenercontactos/(?P<provincia>[0-9A-Za-z]+)/(?P<localidad>[0-9A-Za-z]+)/$', obtener_contactos, name = 'obtener_contactos'),
url(r'^compartir_contacto/$',compartir_contacto,name='compartir_contacto'),
url(r'^verificar_sugeridos/$',verificar_sugeridos,name='verificar_sugeridos'),
url(r'^sugeridos/$',sugeridos,name='sugeridos'),
url(r'^sugerido/(?P<id>[0-9A-Za-z]+)/$',sugerido,name='sugerido'),
url(r'^validar/(?P<id>[0-9A-Za-z]+)/$',validar,name='validar'),
url(r'^editar/(?P<id>[0-9A-Za-z]+)/$',editar,name='editar'),
url(r'^editar_contacto/$',editar_contacto,name='editar_contacto'),
url(r'^editar_contacto/(?P<id>[0-9A-Za-z]+)/$',editar_contacto_id,name='editar_contacto_id'),
url(r'^cantidad_en_provincia/(?P<provincia>[0-9A-Za-z]+)/$',cantidad_en_provincia,name='cantidad_en_provincia'),
url(r'^cantidad_en_ciudad/(?P<ciudad>[0-9A-Za-z]+)/$',cantidad_en_ciudad,name='cantidad_en_ciudad'),
url(r'^contactos_provincia/(?P<provincia>[0-9A-Za-z]+)/$',contactos_provincia,name='contactos_provincia'),
url(r'^contactos_ciudad/(?P<ciudad>[0-9A-Za-z]+)/$',contactos_ciudad,name='contactos_ciudad'),
url(r'^obtener_localidad/(?P<ciudad>[0-9A-Za-z]+)/$',obtener_localidad,name='obtener_localidad'),
]
| [
"jaimeceballos_rw@hotmail.com"
] | jaimeceballos_rw@hotmail.com |
e259c562d3d0b337f7e3a471f7f3367b280a26ee | a001987fbdf7b81b2da938574b5c86332578f054 | /json/dump.py | 12d3311fbab9d56f0fb9500268ed463558a02d07 | [] | no_license | mr-kaveh/serverManagement | 5229b6c446d0e5504a1468d59dff1045a37c75a5 | 500d17acca6b8a23b35f2cd706be50abbc5a7102 | refs/heads/master | 2020-03-17T18:49:35.752087 | 2019-08-05T08:09:02 | 2019-08-05T08:09:02 | 133,835,071 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 824 | py | #!/usr/bin/env python3.6
import json
import requests
data = {
"president": {
"name": "Ghazanfar Darko",
"species": "GoldenMiner"
}
}
json_string = """
{
"researcher": {
"name": "Ford Prefect",
"species": "Betelgeusian",
"relatives": [
{
"name": "Zaphod Beeblebrox",
"species": "Betelgeusian"
}
]
}
}
"""
print(json.dumps(data, indent=4)) # Serialization
with open('output_file.json', 'w') as write_file:
json.dump(data, write_file) # Serialization
data = json.loads(json_string) # Deserialization
print(data)
response = requests.get("https://jsonplaceholder.typicode.com/todos")
todos = json.loads(response.text) # Deserialization
print(todos[0]['title'])
for i in todos:
print(i['title']) | [
"mr.hdavoodi@gmail.com"
] | mr.hdavoodi@gmail.com |
4cf20cd5c5d4053b816f8409f2a5b5c22f95abe3 | 7d90019c8f480a4dd65202a901b37dae1c1f6064 | /dump_hparams_to_json.py | d67e88d3e864fdff9536acf19cc9909e989c0c71 | [
"MIT"
] | permissive | r9y9/deepvoice3_pytorch | d3e85f54d46e809f6fffc0d619e0b4a9d1b13488 | f90255c96177c344cd18b5a52651b420a4d8062d | refs/heads/master | 2023-08-23T08:00:32.174896 | 2023-06-29T18:32:26 | 2023-06-29T18:32:26 | 108,992,863 | 1,964 | 511 | NOASSERTION | 2023-08-11T16:51:15 | 2017-10-31T12:31:44 | Python | UTF-8 | Python | false | false | 725 | py | # coding: utf-8
"""
Dump hyper parameters to json file.
usage: dump_hparams_to_json.py [options] <output_json_path>
options:
-h, --help Show help message.
"""
from docopt import docopt
import sys
import os
from os.path import dirname, join, basename, splitext
import audio
# The deepvoice3 model
from deepvoice3_pytorch import frontend
from hparams import hparams
import json
if __name__ == "__main__":
args = docopt(__doc__)
output_json_path = args["<output_json_path>"]
j = hparams.values()
# for compat legacy
for k in ["preset", "presets"]:
if k in j:
del j[k]
with open(output_json_path, "w") as f:
json.dump(j, f, indent=2)
sys.exit(0)
| [
"zryuichi@gmail.com"
] | zryuichi@gmail.com |
945b83811bb1aaf75f2fc46cc91172afbf54d095 | e08cdae39a5aae8ec95abc6aa36169bc367eebec | /15_pandas_data_aggregation.py | 9a2cce690c6e4806665ff2c37de1165927083350 | [
"MIT"
] | permissive | rohit98077/python_wrldc_training | 9784d4f49a583da34489c78e02983ca62af4dc22 | ec65392aa2cfa3e8564a852f380bf8d1da9f172a | refs/heads/master | 2022-12-22T14:50:41.923278 | 2020-09-21T05:46:31 | 2020-09-21T05:46:31 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,223 | py | '''
Lesson 4 - Day 3 - perform aggregation on pandas dataframe
'''
# %%
import pandas as pd
# %%
# read dc data from csv and skip first 2 rows and skip last 6 rows
df = pd.read_csv('data/dc_data.csv', skipfooter=6, skiprows=2)
# %%
# calculate average value of a column using mean() function
avgVal = df['KHARGONE-I(3)'].mean()
print('average value of the column KHARGONE-I(3) is {0:.2f}'.format(avgVal))
# %%
# calculate sum of a column using sum() function
sumVal = df['KHARGONE-I(3)'].sum()
print('sum of values of the column KHARGONE-I(3) is {0:.2f}'.format(sumVal))
# %%
# calculate average using for loop
avgVal = 0
for itr in range(df.shape[0]):
avgVal = avgVal + df['KHARGONE-I(3)'].iloc[itr]
avgVal = avgVal/df.shape[0]
print('average value of the column KHARGONE-I(3) is {0:.2f}'.format(avgVal))
# %%
# create a new column called 'Total' which is the sum of all columns but exclude 1st 2 columns and last column
sumVals = []
for itr in range(df.shape[0]):
sum = 0
for col in df.columns.tolist()[2:-1]:
sum += df[col].iloc[itr]
sumVals.append(sum)
df['Total'] = sumVals
# %%
# implementing the above task in one line
df['Total1'] = df[df.columns.tolist()[2:-2]].sum(axis=1)
# %%
| [
"nagasudhirpulla@gmail.com"
] | nagasudhirpulla@gmail.com |
c0f3a2427f4911be79d4b7017a0521b24d21b3c6 | dc7a8662a40b6e71997f4fa11db454868c4cb70e | /CodingRacing/decorators.py | 528555d8aa9677ad610a50de81bdb07a222eb06e | [] | no_license | kingmonstr/codingracing | 79ca55164019e15c82004d0740eadb8a4c101b14 | 77eaa33f6555d1b62f6e7931135515e8860d6f4e | refs/heads/master | 2020-03-10T09:09:41.690654 | 2017-03-31T06:07:45 | 2017-03-31T06:07:45 | 129,303,627 | 0 | 0 | null | 2018-04-12T19:48:58 | 2018-04-12T19:48:57 | null | UTF-8 | Python | false | false | 1,568 | py | import hashlib
import django.http
import CodingRacing.models as models
import CodingRacing.local_settings as local_settings
def get_auth_cookie(user_id):
data = str(user_id) + local_settings.COOKIE_HASH
return hashlib.md5(data.encode()).hexdigest()
def get_user_by_request(request):
if 'vk_id' not in request.COOKIES or 'auth' not in request.COOKIES:
return False
try:
vk_id = int(request.COOKIES['vk_id'])
except ValueError:
return False
auth_cookie = request.COOKIES['auth']
if auth_cookie != get_auth_cookie(vk_id):
return False
try:
user = models.User.objects.get(vk_id=vk_id)
return user
except models.User.DoesNotExist:
return False
def auth_only(function):
def wrap(request, *args, **kwargs):
user = get_user_by_request(request)
if not user:
return django.http.HttpResponseRedirect('/')
request.user = user
return function(request, *args, **kwargs)
wrap.__doc__ = function.__doc__
wrap.__name__ = function.__name__
return wrap
def manage_only(function):
def wrap(request, *args, **kwargs):
user = get_user_by_request(request)
if not user:
return django.http.HttpResponseRedirect('/')
if user.vk_id not in local_settings.MANAGERS:
return django.http.HttpResponseRedirect('/')
request.user = user
return function(request, *args, **kwargs)
wrap.__doc__ = function.__doc__
wrap.__name__ = function.__name__
return wrap
| [
"andgein@yandex.ru"
] | andgein@yandex.ru |
c50712be4a37db4cc840fe67d3d72745f78da896 | f576f0ea3725d54bd2551883901b25b863fe6688 | /sdk/dynatrace/azure-mgmt-dynatrace/generated_samples/tag_rules_get_maximum_set_gen.py | d58364b9693128d29182fa8bc30109d734b7a057 | [
"MIT",
"LicenseRef-scancode-generic-cla",
"LGPL-2.1-or-later"
] | permissive | Azure/azure-sdk-for-python | 02e3838e53a33d8ba27e9bcc22bd84e790e4ca7c | c2ca191e736bb06bfbbbc9493e8325763ba990bb | refs/heads/main | 2023-09-06T09:30:13.135012 | 2023-09-06T01:08:06 | 2023-09-06T01:08:06 | 4,127,088 | 4,046 | 2,755 | MIT | 2023-09-14T21:48:49 | 2012-04-24T16:46:12 | Python | UTF-8 | Python | false | false | 1,632 | py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from azure.identity import DefaultAzureCredential
from azure.mgmt.dynatrace import DynatraceObservabilityMgmtClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-dynatrace
# USAGE
python tag_rules_get_maximum_set_gen.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = DynatraceObservabilityMgmtClient(
credential=DefaultAzureCredential(),
subscription_id="00000000-0000-0000-0000-000000000000",
)
response = client.tag_rules.get(
resource_group_name="myResourceGroup",
monitor_name="myMonitor",
rule_set_name="default",
)
print(response)
# x-ms-original-file: specification/dynatrace/resource-manager/Dynatrace.Observability/stable/2023-04-27/examples/TagRules_Get_MaximumSet_Gen.json
if __name__ == "__main__":
main()
| [
"noreply@github.com"
] | Azure.noreply@github.com |
9ecb0567e7023936d815976c6f093f774c7dc47a | a33368744a38bed09eca6230b651653874f89f6b | /Physics/P441/Homework/HW5/hw_5.py | 8c07236fc7566e8393dafea6a669bcec2b034ccc | [] | no_license | IanMadlenya/BYUclasses | 797be225ff7d6a4dccd2151f2be2526eb80ccace | 9f61a6f0d6f42032518fe43e21d8b080a49ee666 | refs/heads/master | 2020-05-31T10:46:28.442186 | 2013-07-06T21:08:59 | 2013-07-06T21:08:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 409 | py | # Problem 4.2
import sympy as sym
r, a, q, z = sym.symbols('r, a, q, z, d')
epsilon_0 = sym.symbols('epsilon_0')
pi = sym.pi
Q = 4*pi*q / (pi*a**3) * sym.integrate(sym.exp(-2*r / a) * r **2 , (r, 0, r))
print sym.latex(sym.factor(Q))
E = 1 / (4*pi*epsilon_0*r**2) * sym.factor(Q)
print sym.latex(E)
expansion = sym.simplify(sym.series(E.subs({r/a: z}), z, n=4).subs({z:r/a}))
print sym.latex(expansion)
| [
"spencerlyon2@gmail.com"
] | spencerlyon2@gmail.com |
31619ebbd664533dd4bb165fbf6bcd18c860bea9 | ef1d38cfef63f22e149d6c9dd14e98955693c50d | /webhook/protos/pogoprotos/settings/poi_global_settings_pb2.py | c1c85d746e535dd00a17df25d6feb4b2e695bdcd | [] | no_license | Kneckter/WebhookListener | 4c186d9012fd6af69453d9d51ae33a38aa19b5fd | ea4ff29b66d6abf21cc1424ed976af76c3da5511 | refs/heads/master | 2022-10-09T04:26:33.466789 | 2019-11-24T17:30:59 | 2019-11-24T17:30:59 | 193,372,117 | 2 | 0 | null | 2022-09-23T22:26:10 | 2019-06-23T16:39:34 | Python | UTF-8 | Python | false | true | 2,136 | py | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: pogoprotos/settings/poi_global_settings.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='pogoprotos/settings/poi_global_settings.proto',
package='pogoprotos.settings',
syntax='proto3',
serialized_pb=_b('\n-pogoprotos/settings/poi_global_settings.proto\x12\x13pogoprotos.settings\"\'\n\x11PoiGlobalSettings\x12\x12\n\nis_enabled\x18\x01 \x01(\x08\x62\x06proto3')
)
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
_POIGLOBALSETTINGS = _descriptor.Descriptor(
name='PoiGlobalSettings',
full_name='pogoprotos.settings.PoiGlobalSettings',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='is_enabled', full_name='pogoprotos.settings.PoiGlobalSettings.is_enabled', index=0,
number=1, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=70,
serialized_end=109,
)
DESCRIPTOR.message_types_by_name['PoiGlobalSettings'] = _POIGLOBALSETTINGS
PoiGlobalSettings = _reflection.GeneratedProtocolMessageType('PoiGlobalSettings', (_message.Message,), dict(
DESCRIPTOR = _POIGLOBALSETTINGS,
__module__ = 'pogoprotos.settings.poi_global_settings_pb2'
# @@protoc_insertion_point(class_scope:pogoprotos.settings.PoiGlobalSettings)
))
_sym_db.RegisterMessage(PoiGlobalSettings)
# @@protoc_insertion_point(module_scope)
| [
"kasmar@gitlab.com"
] | kasmar@gitlab.com |
15529e07ef78dfe0cb345b4d0c4d9897155632ef | 9452f681ea486fc53ad88d05392aed5fc450805c | /data_language_all/python/python_570.txt | 6d3567b6740fc02b535044b10dae8878bd9c560e | [] | no_license | CoryCollins/src-class | 11a6df24f4bd150f6db96ad848d7bfcac152a695 | f08a2dd917f740e05864f51ff4b994c368377f97 | refs/heads/master | 2023-08-17T11:53:28.754781 | 2021-09-27T21:13:23 | 2021-09-27T21:13:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,726 | txt | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
http://code.activestate.com/recipes/131499-observer-pattern/
*TL;DR80
Maintains a list of dependents and notifies them of any state changes.
"""
from __future__ import print_function
class Subject(object):
def __init__(self):
self._observers = []
def attach(self, observer):
if observer not in self._observers:
self._observers.append(observer)
def detach(self, observer):
try:
self._observers.remove(observer)
except ValueError:
pass
def notify(self, modifier=None):
for observer in self._observers:
if modifier != observer:
observer.update(self)
# Example usage
class Data(Subject):
def __init__(self, name=''):
Subject.__init__(self)
self.name = name
self._data = 0
@property
def data(self):
return self._data
@data.setter
def data(self, value):
self._data = value
self.notify()
class HexViewer:
def update(self, subject):
print(u'HexViewer: Subject %s has data 0x%x' % (subject.name, subject.data))
class DecimalViewer:
def update(self, subject):
print(u'DecimalViewer: Subject %s has data %d' % (subject.name, subject.data))
# Example usage...
def main():
data1 = Data('Data 1')
data2 = Data('Data 2')
view1 = DecimalViewer()
view2 = HexViewer()
data1.attach(view1)
data1.attach(view2)
data2.attach(view2)
data2.attach(view1)
print(u"Setting Data 1 = 10")
data1.data = 10
print(u"Setting Data 2 = 15")
data2.data = 15
print(u"Setting Data 1 = 3")
data1.data = 3
print(u"Setting Data 2 = 5")
data2.data = 5
print(u"Detach HexViewer from data1 and data2.")
data1.detach(view2)
data2.detach(view2)
print(u"Setting Data 1 = 10")
data1.data = 10
print(u"Setting Data 2 = 15")
data2.data = 15
if __name__ == '__main__':
main()
### OUTPUT ###
# Setting Data 1 = 10
# DecimalViewer: Subject Data 1 has data 10
# HexViewer: Subject Data 1 has data 0xa
# Setting Data 2 = 15
# HexViewer: Subject Data 2 has data 0xf
# DecimalViewer: Subject Data 2 has data 15
# Setting Data 1 = 3
# DecimalViewer: Subject Data 1 has data 3
# HexViewer: Subject Data 1 has data 0x3
# Setting Data 2 = 5
# HexViewer: Subject Data 2 has data 0x5
# DecimalViewer: Subject Data 2 has data 5
# Detach HexViewer from data1 and data2.
# Setting Data 1 = 10
# DecimalViewer: Subject Data 1 has data 10
# Setting Data 2 = 15
# DecimalViewer: Subject Data 2 has data 15
| [
"znsoft@163.com"
] | znsoft@163.com |
421c419391645d8a1437c9143a65d5cb1c949a40 | 5b24b236bff794520e8139913a9b976f5cc5ab9f | /ptsites/sites/torrentleech.py | cee27285b27aeb827eb4ba8826e43f3bd69ca13e | [
"MIT"
] | permissive | SKIYET/flexget_qbittorrent_mod | 2868ad02c179172d242ab0e24087e5b8d477c10c | d66b904542126e9d4fc99c7e0f2acb8de923725f | refs/heads/master | 2023-04-22T01:52:19.689554 | 2021-05-22T07:29:29 | 2021-05-22T07:29:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,730 | py | from dateutil.parser import parse
from ..schema.site_base import SiteBase, Work, SignState
class MainClass(SiteBase):
URL = 'https://www.torrentleech.org/none.torrent'
USER_CLASSES = {
'uploaded': [54975581388800],
'share_ratio': [8],
'days': [364]
}
@classmethod
def build_workflow(cls):
return [
Work(
url='/',
method='get',
succeed_regex='<span class="link" style="margin-right: 1em;white-space: nowrap;" onclick="window.location.href=\'.+?\'">.+?</span>',
fail_regex=None,
check_state=('final', SignState.SUCCEED),
is_base_content=True
)
]
def get_message(self, entry, config):
self.get_torrentleech_message(entry, config)
def get_details(self, entry, config):
self.get_details_base(entry, config, self.build_selector())
def build_selector(self):
return {
'user_id': '/profile/(.*)?/view',
'detail_sources': {
'default': {
'do_not_strip': True,
'link': '/profile/{}/view',
'elements': {
'bar': '.row',
'table': '.profileViewTable'
}
}
},
'details': {
'uploaded': {
'regex': 'Uploaded.+?([\\d.]+ [ZEPTGMK]?B)'
},
'downloaded': {
'regex': 'Downloaded.+?([\\d.]+ [ZEPTGMK]?B)'
},
'share_ratio': {
'regex': 'ratio-details">(&inf|∞|[\\d.]+)',
'handle': self.handle_share_ratio
},
'points': {
'regex': 'total-TL-points.+?([\\d,.]+)'
},
'join_date': {
'regex': 'Register date</td>.*?<td>(.*?)</td>',
'handle': self.handle_join_date
},
'seeding': {
'regex': ('Uploaded.+?([\\d.]+ [ZEPTGMK]?B).*?\\((\\d+)\\)', 2)
},
'leeching': {
'regex': ('Downloaded.+?([\\d.]+ [ZEPTGMK]?B).*?\\((\\d+)\\)', 2)
},
'hr': None
}
}
def get_torrentleech_message(self, entry, config, messages_url='/messages.php'):
entry['result'] += '(TODO: Message)'
def handle_share_ratio(self, value):
if value in ['&inf', '∞']:
return '0'
else:
return value
def handle_join_date(self, value):
return parse(value).date()
| [
"12468675@qq.com"
] | 12468675@qq.com |
b02815d7d98abe5a29e03add4285f3b2640dadbc | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p02975/s102896717.py | 3b8174d5d10f55a0dcd65cf9092907fe558a04c3 | [] | no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 327 | py | from collections import*
n=int(input())
a=list(map(int,input().split()))
ans=a[0]
for i in a[1:]:
ans^=i
a=dict(Counter(a))
ak=list(a.keys())
if len(a)==1 and ak[0]!=0:ans=1
elif len(a)==2 and a.get(0)!=n//3:ans=1
elif len(a)==3 and not(a[ak[0]]==a[ak[1]]==a[ak[2]]==n//3):ans=1
elif len(a)>3:ans=1
print(['Yes','No'][ans>0]) | [
"66529651+Aastha2104@users.noreply.github.com"
] | 66529651+Aastha2104@users.noreply.github.com |
a5fe78ca5b4490b9053350ad2f3fb8f0804569c6 | e0b50a8ff40097b9896ad69d098cbbbbe4728531 | /dcorch/db/sqlalchemy/migration.py | 168c47fcfe8d30009d2e70c403a0f2e51b7de340 | [
"Apache-2.0"
] | permissive | aleks-kozyrev/stx-distcloud | ccdd5c76dd358b8aa108c524138731aa2b0c8a53 | a4cebb85c45c8c5f1f0251fbdc436c461092171c | refs/heads/master | 2020-03-27T11:11:09.348241 | 2018-08-27T14:33:50 | 2018-08-27T14:33:50 | 146,470,708 | 0 | 0 | Apache-2.0 | 2018-08-28T15:47:12 | 2018-08-28T15:47:08 | Python | UTF-8 | Python | false | false | 1,383 | py | # Copyright (c) 2015 Ericsson AB.
# 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.
import os
from oslo_db.sqlalchemy import migration as oslo_migration
INIT_VERSION = 0
def db_sync(engine, version=None):
path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
'migrate_repo')
return oslo_migration.db_sync(engine, path, version,
init_version=INIT_VERSION)
def db_version(engine):
path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
'migrate_repo')
return oslo_migration.db_version(engine, path, INIT_VERSION)
def db_version_control(engine, version=None):
path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
'migrate_repo')
return oslo_migration.db_version_control(engine, path, version)
| [
"scott.little@windriver.com"
] | scott.little@windriver.com |
fc3b875d97c771bc0686a51aa56902a739c751bc | ad13583673551857615498b9605d9dcab63bb2c3 | /output/models/ms_data/additional/enum1_xsd/__init__.py | 2fb178cb32a77e13a2bbf3dad700855bbba78d2e | [
"MIT"
] | permissive | tefra/xsdata-w3c-tests | 397180205a735b06170aa188f1f39451d2089815 | 081d0908382a0e0b29c8ee9caca6f1c0e36dd6db | refs/heads/main | 2023-08-03T04:25:37.841917 | 2023-07-29T17:10:13 | 2023-07-30T12:11:13 | 239,622,251 | 2 | 0 | MIT | 2023-07-25T14:19:04 | 2020-02-10T21:59:47 | Python | UTF-8 | Python | false | false | 130 | py | from output.models.ms_data.additional.enum1_xsd.enum1 import (
Doc,
EnumType,
)
__all__ = [
"Doc",
"EnumType",
]
| [
"tsoulloftas@gmail.com"
] | tsoulloftas@gmail.com |
2fd2475ea5421f3afe7c767cc58c0ebb7d2b5b66 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p03722/s529252608.py | 70cd01b9d97eb5f7c13c9b324f7e0ee5d76b27cc | [] | no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,008 | py | n,m = map(int,input().split( ))
E = [[] for _ in range(n+1)]
for i in range(m):
ai,bi,ci = map(int, input().split( ))
ai-=1;bi-=1
E[ai].append((bi,-ci))
#「nまでの経路で」負閉路が要る
#https://tjkendev.github.io/procon-library/python/graph/bellman-ford.html
# V: グラフの頂点数
# r: 始点
# G[v] = [(w, cost), ...]: 頂点vからコストcostで到達できる頂点w
INF = 10**18
dist = [INF] * n
dist[0] = 0
update = 1
for _ in range(n):
update = 0
for v, e in enumerate(E):
for t, cost in e:
if dist[v] != INF and dist[v] + cost < dist[t]:
dist[t] = dist[v] + cost
update = 1
if not update:
break
ans = dist[n-1]
for _ in range(n):
update = 0
for v, e in enumerate(E):
for t, cost in e:
if dist[v] != INF and dist[v] + cost < dist[t]:
dist[t] = dist[v] + cost
update = 1
if ans > dist[n-1]:
print("inf")
else:
print(-ans)###-
| [
"66529651+Aastha2104@users.noreply.github.com"
] | 66529651+Aastha2104@users.noreply.github.com |
8f2f1b1565e3a73148c21fd46d79f30418a682f0 | f62fd455e593a7ad203a5c268e23129473d968b6 | /glance-14.0.0/glance/api/middleware/version_negotiation.py | 62a26c08cebc3bb9bdaaf1a291779a59d2de861e | [
"Apache-2.0"
] | permissive | MinbinGong/OpenStack-Ocata | 5d17bcd47a46d48ff9e71e2055f667836174242f | 8b7650128cfd2fdf5d6c8bc4613ac2e396fb2fb3 | refs/heads/master | 2021-06-23T05:24:37.799927 | 2017-08-14T04:33:05 | 2017-08-14T04:33:05 | 99,709,985 | 0 | 2 | null | 2020-07-22T22:06:22 | 2017-08-08T15:48:44 | Python | UTF-8 | Python | false | false | 4,653 | py | # Copyright 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.
"""
A filter middleware that inspects the requested URI for a version string
and/or Accept headers and attempts to negotiate an API controller to
return
"""
from oslo_config import cfg
from oslo_log import log as logging
from glance.api.glare import versions as artifacts_versions
from glance.api import versions
from glance.common import wsgi
CONF = cfg.CONF
LOG = logging.getLogger(__name__)
class VersionNegotiationFilter(wsgi.Middleware):
def __init__(self, app):
self.versions_app = versions.Controller()
self.allowed_versions = None
self.vnd_mime_type = 'application/vnd.openstack.images-'
super(VersionNegotiationFilter, self).__init__(app)
def process_request(self, req):
"""Try to find a version first in the accept header, then the URL"""
args = {'method': req.method, 'path': req.path, 'accept': req.accept}
LOG.debug("Determining version of request: %(method)s %(path)s "
"Accept: %(accept)s", args)
# If the request is for /versions, just return the versions container
if req.path_info_peek() == "versions":
return self.versions_app.index(req, explicit=True)
accept = str(req.accept)
if accept.startswith(self.vnd_mime_type):
LOG.debug("Using media-type versioning")
token_loc = len(self.vnd_mime_type)
req_version = accept[token_loc:]
else:
LOG.debug("Using url versioning")
# Remove version in url so it doesn't conflict later
req_version = self._pop_path_info(req)
try:
version = self._match_version_string(req_version)
except ValueError:
LOG.debug("Unknown version. Returning version choices.")
return self.versions_app
req.environ['api.version'] = version
req.path_info = ''.join(('/v', str(version), req.path_info))
LOG.debug("Matched version: v%d", version)
LOG.debug('new path %s', req.path_info)
return None
def _get_allowed_versions(self):
allowed_versions = {}
if CONF.enable_v1_api:
allowed_versions['v1'] = 1
allowed_versions['v1.0'] = 1
allowed_versions['v1.1'] = 1
if CONF.enable_v2_api:
allowed_versions['v2'] = 2
allowed_versions['v2.0'] = 2
allowed_versions['v2.1'] = 2
allowed_versions['v2.2'] = 2
allowed_versions['v2.3'] = 2
allowed_versions['v2.4'] = 2
allowed_versions['v2.5'] = 2
return allowed_versions
def _match_version_string(self, subject):
"""
Given a string, tries to match a major and/or
minor version number.
:param subject: The string to check
:returns: version found in the subject
:raises: ValueError if no acceptable version could be found
"""
if self.allowed_versions is None:
self.allowed_versions = self._get_allowed_versions()
if subject in self.allowed_versions:
return self.allowed_versions[subject]
else:
raise ValueError()
def _pop_path_info(self, req):
"""
'Pops' off the next segment of PATH_INFO, returns the popped
segment. Do NOT push it onto SCRIPT_NAME.
"""
path = req.path_info
if not path:
return None
while path.startswith('/'):
path = path[1:]
idx = path.find('/')
if idx == -1:
idx = len(path)
r = path[:idx]
req.path_info = path[idx:]
return r
class GlareVersionNegotiationFilter(VersionNegotiationFilter):
def __init__(self, app):
super(GlareVersionNegotiationFilter, self).__init__(app)
self.versions_app = artifacts_versions.Controller()
self.vnd_mime_type = 'application/vnd.openstack.artifacts-'
def _get_allowed_versions(self):
return {
'v0.1': 0.1
}
| [
"gongwayne@hotmail.com"
] | gongwayne@hotmail.com |
a7e36e6c5f69c8f5ffc59d85782cad36bf8e5448 | d051c100fcebd9c73a9e7ca85f8af6fefe24c854 | /group_buying/profiles/urls.py | 5f8686796ff4ecf49e12cbeac565e3028ec14634 | [] | no_license | kvenkataharsha/group_buying | 2837e6a7868aee074c2459eb7700bc46d044727c | f219dd6291cc2a1533e46ed79c5effba406a4d36 | refs/heads/master | 2022-11-17T18:10:55.937752 | 2020-07-14T13:34:52 | 2020-07-14T13:34:52 | 279,548,803 | 0 | 0 | null | 2020-07-14T13:34:53 | 2020-07-14T10:02:00 | null | UTF-8 | Python | false | false | 460 | py | from django.urls import path,include
from django.conf.urls import url
from . import views
# app_name = 'home'
urlpatterns = [
# path('update',)
path('update',views.update,name='update'),
path('view/<name>',views.profile,name='view'),
path('create/',views.create,name='create'),
path('phone',views.phone_number,name='phone_number'),
path('change',views.change_phone,name='change_phone'),
path('otp',views.validate_otp,name='otp')
]
| [
"saisantosh.c17@iiits.in"
] | saisantosh.c17@iiits.in |
60f8432b399946de8ef4a18f76687f30530c26e5 | 47243c719bc929eef1475f0f70752667b9455675 | /bungeni.main/branches/njoka-transcripts/bungeni/ui/file.py | 9123e55ff05d29e128444418efbd9dd4a42a1992 | [] | no_license | malangalanga/bungeni-portal | bbf72ce6d69415b11287a8796b81d4eb6520f03a | 5cf0ba31dfbff8d2c1b4aa8ab6f69c7a0ae9870d | refs/heads/master | 2021-01-19T15:31:42.943315 | 2014-11-18T09:03:00 | 2014-11-18T09:03:00 | 32,453,405 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,900 | py | # encoding: utf-8
# download view to download a file or image
from zope.interface import implements
from zope.publisher.interfaces import IPublishTraverse
from zope.publisher.browser import BrowserView
from zope.security import proxy
from tempfile import TemporaryFile
class RawView(BrowserView):
implements(IPublishTraverse)
def __init__(self, context, request):
self.context = context
self.request = request
self.traverse_subpath = []
def publishTraverse(self, request, name):
self.traverse_subpath.append(name)
return self
def __call__(self):
"""Return File/Image Raw Data"""
context = proxy.removeSecurityProxy( self.context )
response = self.request.response
#response.setHeader('Content-Type', 'application/octect-stream')
if len(self.traverse_subpath) != 1:
return
fname = self.traverse_subpath[0]
tempfile = TemporaryFile()
data = getattr(context,fname,None)
if type(data) == buffer:
tempfile.write(data)
return tempfile
class FileDownload(BrowserView):
def __call__(self):
context = proxy.removeSecurityProxy( self.context )
response = self.request.response
mimetype = getattr(context,'file_mimetype',None)
if mimetype == None:
mimetype='application/octect-stream'
filename=getattr(context,'file_name',None)
if filename == None:
filename=getattr(context,'file_title',None)
tempfile = TemporaryFile()
data = getattr(context,'file_data',None)
if type(data) == buffer:
tempfile.write(data)
self.request.response.setHeader('Content-type', mimetype)
self.request.response.setHeader('Content-disposition', 'attachment;filename="%s"' % filename)
return tempfile
| [
"ashok.hariharan@fc5d704a-7d24-0410-8c4a-57ddeba10ffc"
] | ashok.hariharan@fc5d704a-7d24-0410-8c4a-57ddeba10ffc |
ddc93608d06834edf31a2e8118767a6cc5f1b952 | a4a44ad46cd1306e2da72ff89483b0102fc9787d | /SamplePython/samplePython/Networking/dari_buku_python_network_programming/Bab2_multiplexing_socket/_03_penggunaan_select_select.py | 5fb880ea695f27d87080899c3908107640bc4fce | [] | no_license | okipriyadi/NewSamplePython | 640eb3754de98e6276f0aa1dcf849ecea22d26b1 | e12aeb37e88ffbd16881a20a3c37cd835b7387d0 | refs/heads/master | 2020-05-22T01:15:17.427350 | 2017-02-21T04:47:08 | 2017-02-21T04:47:08 | 30,009,299 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,904 | py | """
We would like to run this script thrice: once for the chat server and twice for two chat clients.
For the server, we pass -name=server and port=8800 . For client1 , we change the name
argument --name=client1 and for client2 , we put --name=client2 . Then from the
client1 value prompt we send the message "Hello from client 1" , which is printed in
the prompt of the client2 . Similarly, we send "hello from client 2 " from the prompt
of the client2 , which is shown in the prompt of the client1 .
"""
import select
import socket
import sys
import signal
import cPickle
import struct
import argparse
SERVER_HOST = 'localhost'
CHAT_SERVER_NAME = 'server'
# Some utilities
def send(channel, *args):
buffer = cPickle.dumps(args)
value = socket.htonl(len(buffer))
size = struct.pack("L",value)
channel.send(size)
channel.send(buffer)
def receive(channel):
size = struct.calcsize("L")
size = channel.recv(size)
try:
size = socket.ntohl(struct.unpack("L", size)[0])
except struct.error, e:
return ''
buf = ""
while len(buf) < size:
buf = channel.recv(size - len(buf))
return cPickle.loads(buf)[0]
class ChatServer(object):
""" An example chat server using select """
def __init__(self, port, backlog=5):
self.clients = 0
self.clientmap = {}
self.outputs = [] # list output sockets
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Enable re-using socket address
self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.server.bind((SERVER_HOST, port))
print 'Server listening to port: %s ...' %port
self.server.listen(backlog)
# Catch keyboard interrupts
signal.signal(signal.SIGINT, self.sighandler)
def sighandler(self, signum, frame):
""" Clean up client outputs"""
# Close the server
print 'Shutting down server...'
# Close existing client sockets
for output in self.outputs:
output.close()
self.server.close()
def get_client_name(self, client):
""" Return the name of the client """
info = self.clientmap[client]
host, name = info[0][0], info[1]
return '@'.join((name, host))
def run(self):
inputs = [self.server, sys.stdin]
self.outputs = []
running = True
while running:
try:
readable, writeable, exceptional = select.select(inputs, self.outputs, [])
except select.error, e:
break
for sock in readable:
if sock == self.server:
# handle the server socket
client, address = self.server.accept()
print "Chat server: got connection %d from %s" %(client.fileno(), address)
# Read the login name
cname = receive(client).split('NAME: ')[1]
# Compute client name and send back
self.clients += 1
send(client, 'CLIENT: ' + str(address[0]))
inputs.append(client)
self.clientmap[client] = (address, cname)
# Send joining information to other clients
msg = "\n(Connected: New client (%d) from %s)" %(self.clients, self.get_client_name(client))
for output in self.outputs:
send(output, msg)
self.outputs.append(client)
elif sock == sys.stdin:
# handle standard input
junk = sys.stdin.readline()
running = False
else:
# handle all other sockets
try:
data = receive(sock)
if data:
# Send as new client's message...
msg = '\n#[' + self.get_client_name(sock)+ ']>>' + data
# Send data to all except ourself
for output in self.outputs:
if output != sock:
send(output, msg)
else:
print "Chat server: %d hung up" % \
sock.fileno()
self.clients -= 1
sock.close()
inputs.remove(sock)
self.outputs.remove(sock)
# Sending client leaving info to others
msg = "\n(Now hung up: Client from %s)" %self.get_client_name(sock)
for output in self.outputs:
send(output, msg)
except socket.error, e:
# Remove
inputs.remove(sock)
self.outputs.remove(sock)
self.server.close()
class ChatClient(object):
""" A command line chat client using select """
def __init__(self, name, port, host=SERVER_HOST):
self.name = name
self.connected = False
self.host = host
self.port = port
# Initial prompt
self.prompt='[' + '@'.join((name, socket.gethostname().split('.')[0])) + ']> '
# Connect to server at port
try:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((host, self.port))
print "Now connected to chat server@ port %d" % self.port
self.connected = True
# Send my name...
send(self.sock,'NAME: ' + self.name)
data = receive(self.sock)
# Contains client address, set it
addr = data.split('CLIENT: ')[1]
self.prompt = '[' + '@'.join((self.name, addr)) + ']> '
except socket.error, e:
print "Failed to connect to chat server @ port %d" % self.port
sys.exit(1)
def run(self):
""" Chat client main loop """
while self.connected:
try:
sys.stdout.write(self.prompt)
sys.stdout.flush()
# Wait for input from stdin and socket
readable, writeable,exceptional = select.select([0,self.sock], [],[])
for sock in readable:
if sock == 0:
data = sys.stdin.readline().strip()
if data:
send(self.sock, data)
elif sock == self.sock:
data = receive(self.sock)
if not data:
print 'Client shutting down.'
self.connected = False
break
else:
sys.stdout.write(data + '\n')
sys.stdout.flush()
except KeyboardInterrupt:
print " Client interrupted. """
self.sock.close()
break
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Socket Server Example with Select')
parser.add_argument('--name', action="store", dest="name", required=True)
parser.add_argument('--port', action="store", dest="port", type=int, required=True)
given_args = parser.parse_args()
port = given_args.port
name = given_args.name
if name == CHAT_SERVER_NAME:
server = ChatServer(port)
server.run()
else:
client = ChatClient(name=name, port=port)
client.run() | [
"oki.priyadi@pacificavionics.net"
] | oki.priyadi@pacificavionics.net |
b8d860e435180eb9f1ef5fcdaffb9382b3a35115 | 9a93258702bc92121e39ebb6ff8a5bd89d482207 | /cvsfileread.py | 55506990871f848fe2f9e6c9d2616c2405b28017 | [] | no_license | Python-lab-cycle/swetha | d476e174094620d7f2eadfba5590157edd4e2fb9 | 59e8f371db1deca36374ff11704bb34d7b92782a | refs/heads/main | 2023-06-10T16:18:59.946931 | 2021-07-02T09:48:18 | 2021-07-02T09:48:18 | 325,941,769 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 128 | py | import csv
with open('employee.csv','r')as file1:
reader1=csv.reader(file1)
for row in reader1:
print(row)
| [
"noreply@github.com"
] | Python-lab-cycle.noreply@github.com |
7af2579af4523010983f8361d20189ac00598d07 | 43842089122512e6b303ebd05fc00bb98066a5b2 | /interviews/amazon/647_palindrome_substrings.py | 3dacd8be72e5dc2fd6a972286565fe9cd85e6186 | [] | no_license | mistrydarshan99/Leetcode-3 | a40e14e62dd400ddb6fa824667533b5ee44d5f45 | bf98c8fa31043a45b3d21cfe78d4e08f9cac9de6 | refs/heads/master | 2022-04-16T11:26:56.028084 | 2020-02-28T23:04:06 | 2020-02-28T23:04:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,519 | py | """
647. Palindromic Substrings
Medium
1248
65
Favorite
Share
Given a string, your task is to count how many palindromic substrings in this string.
The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.
Example 1:
Input: "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".
Example 2:
Input: "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
"""
class Solution(object):
def countSubstrings(self, s):
"""
:type s: str
:rtype: int
"""
# self.matrix = [[None] * len(s) for _ in range(len(s))]
self.results = []
for i in range(len(s)):
self.if_palindrome(i, i, s)
self.if_palindrome(i, i + 1, s)
return len(self.results)
def if_palindrome(self, b, e, s):
while b >= 0 and e < len(s):
if s[b] == s[e]:
self.results.append(s[b:e + 1])
b -= 1
e += 1
else:
break
string = "aa"
s = Solution()
r = s.countSubstrings(string)
print("string:{}, r:{}".format(string, r))
string = ""
s = Solution()
r = s.countSubstrings(string)
print("string:{}, r:{}".format(string, r))
string = "aaa"
s = Solution()
r = s.countSubstrings(string)
print("string:{}, r:{}".format(string, r))
string = "ab"
s = Solution()
r = s.countSubstrings(string)
print("string:{}, r:{}".format(string, r))
string = "aba"
s = Solution()
r = s.countSubstrings(string)
print("string:{}, r:{}".format(string, r))
| [
"maplesuger@hotmail.com"
] | maplesuger@hotmail.com |
6d1cb66bca1662f5c23093dcabd5295b55e3ed7f | f8da830331428a8e1bbeadf23345f79f1750bd98 | /msgraph-cli-extensions/beta/usersfunctions_beta/azext_usersfunctions_beta/vendored_sdks/usersfunctions/operations/_user_calendar_group_calendar_event_exception_occurrence_operations.py | 9f3ca13f99e10ad7e4cea48478fe14c024239b64 | [
"MIT"
] | permissive | ezkemboi/msgraph-cli | e023e1b7589461a738e42cbad691d9a0216b0779 | 2ceeb27acabf7cfa219c8a20238d8c7411b9e782 | refs/heads/main | 2023-02-12T13:45:03.402672 | 2021-01-07T11:33:54 | 2021-01-07T11:33:54 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,915 | py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRequest, HttpResponse
from azure.mgmt.core.exceptions import ARMErrorFormat
from .. import models
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from typing import Any, Callable, Dict, Generic, List, Optional, TypeVar
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
class UserCalendarGroupCalendarEventExceptionOccurrenceOperations(object):
"""UserCalendarGroupCalendarEventExceptionOccurrenceOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~users_functions.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
def delta(
self,
user_id, # type: str
calendar_group_id, # type: str
calendar_id, # type: str
event_id, # type: str
**kwargs # type: Any
):
# type: (...) -> List["models.MicrosoftGraphEvent"]
"""Invoke function delta.
Invoke function delta.
:param user_id: key: id of user.
:type user_id: str
:param calendar_group_id: key: id of calendarGroup.
:type calendar_group_id: str
:param calendar_id: key: id of calendar.
:type calendar_id: str
:param event_id: key: id of event.
:type event_id: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: list of MicrosoftGraphEvent, or the result of cls(response)
:rtype: list[~users_functions.models.MicrosoftGraphEvent]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType[List["models.MicrosoftGraphEvent"]]
error_map = {404: ResourceNotFoundError, 409: ResourceExistsError}
error_map.update(kwargs.pop('error_map', {}))
accept = "application/json"
# Construct URL
url = self.delta.metadata['url'] # type: ignore
path_format_arguments = {
'user-id': self._serialize.url("user_id", user_id, 'str'),
'calendarGroup-id': self._serialize.url("calendar_group_id", calendar_group_id, 'str'),
'calendar-id': self._serialize.url("calendar_id", calendar_id, 'str'),
'event-id': self._serialize.url("event_id", event_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
header_parameters['Accept'] = 'application/json'
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize(models.OdataError, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('[MicrosoftGraphEvent]', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
delta.metadata = {'url': '/users/{user-id}/calendarGroups/{calendarGroup-id}/calendars/{calendar-id}/events/{event-id}/exceptionOccurrences/microsoft.graph.delta()'} # type: ignore
| [
"japhethobalak@gmail.com"
] | japhethobalak@gmail.com |
6dbd8b33926dfe3f130dc3387a490099717baac2 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5634947029139456_0/Python/nrpeterson/A.py | fd90569bbd059e400924efd8359b3d3ecae02be4 | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | Python | false | false | 2,037 | py | import sys
from itertools import product
def check(flows, reqs, choice):
flows2 = [tuple(int(flow[i] != choice[i]) for i in range(L)) for flow in
flows]
return set(reqs) == set(flows2)
basename = "A-small-attempt2"
input_filename = basename + ".in"
output_filename = basename + ".out"
input_file = open(input_filename, 'r')
output_file = open(output_filename, 'w')
test_cases = int(input_file.readline().rstrip())
irritating = 0
for case in range(1, test_cases+1):
N, L = [int(i) for i in input_file.readline().rstrip().split()]
flows = []
for string in input_file.readline().rstrip().split():
flows.append(tuple(int(i) for i in string))
reqs = []
for string in input_file.readline().rstrip().split():
reqs.append(tuple(int(i) for i in string))
#Check to see if it is possible
reqsums = tuple(sum(req[i] for req in reqs) for i in range(L))
flowsums = tuple(sum(flow[i] for flow in flows) for i in range(L))
if all(reqsums[i] == flowsums[i] or reqsums[i] == N - flowsums[i] for i in
range(L)):
swappos = [i for i in range(L) if reqsums[i] != flowsums[i]]
choicepos = [i for i in range(L) if reqsums[i] == flowsums[i] and
reqsums[i] == N - flowsums[i]]
choices = []
for i in range(L):
if i in swappos:
choices.append([1])
elif i in choicepos:
choices.append([0,1])
else:
choices.append([0])
found = False
for choice in product(*choices):
if check(flows, reqs, choice):
found = True
solution = sum(choice)
break
if not found:
solution = "NOT POSSIBLE"
else:
solution = "NOT POSSIBLE"
# Output all goes below here. Make sure to define var 'solution'
output_file.write("Case #" + str(case) + ": " + str(solution))
if case < test_cases:
output_file.write('\n')
| [
"eewestman@gmail.com"
] | eewestman@gmail.com |
a863222fb1e91defe2c86d0d38f569ade5aba177 | 36222fc73431a89d41a342aa176158b8868bc41a | /solicitudes/migrations/0039_auto_20170503_1538.py | e0488c7dac0bd81f961e1af10ef56dcbc8757261 | [] | no_license | dxviidmg/CITNOVA | 9e3f555e192d4e875fc4b990b70c52e3f6fc8bc0 | f18d6e74082d0ddf58eaba439d5e20f2d48af7b9 | refs/heads/master | 2021-01-18T23:34:41.179481 | 2017-05-20T13:59:11 | 2017-05-20T13:59:11 | 87,117,216 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 618 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-05-03 20:38
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('solicitudes', '0038_solicitudrecursofinanciero_cuenta_bancaria_del_programa'),
]
operations = [
migrations.AlterField(
model_name='solicitudrecursofinanciero',
name='mes',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='presupuesto.Mes'),
),
]
| [
"dmg_92@hotmail.com"
] | dmg_92@hotmail.com |
8f12f95b70ea336181886ab5320b3c7e13923fe8 | 53d0b80b64d201def809ef11acbeca38da2c1574 | /existencias/urls.py | fe608f35a314cee248e242d8298c178593790a80 | [] | no_license | NOKIA-NI/niproyecciones | 068558b27afd26bc2eb6ab9c32f98a37742817ce | 90c5829250643443f90ae4cbb9b234464a2fcaef | refs/heads/master | 2022-12-11T18:22:32.928214 | 2018-10-25T14:52:52 | 2018-10-25T14:52:52 | 127,053,712 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,051 | py | from django.urls import path
from .views import (
ListExistencia,
DetailExistencia,
CreateExistencia,
UpdateExistencia,
DeleteExistencia,
SearchExistencia,
FilterExistencia,
export_existencia,
# calculate_existencia,
)
app_name = 'existencias'
urlpatterns = [
path('list/existencia/', ListExistencia.as_view(), name='list_existencia'),
path('detail/existencia/<int:pk>/', DetailExistencia.as_view(), name='detail_existencia'),
path('create/existencia/', CreateExistencia.as_view(), name='create_existencia'),
path('update/existencia/<int:pk>/', UpdateExistencia.as_view(), name='update_existencia'),
path('delete/existencia/<int:pk/', DeleteExistencia.as_view(), name='delete_existencia'),
path('search/existencia/', SearchExistencia.as_view(), name='search_existencia'),
path('filter/existencia/', FilterExistencia.as_view(), name='filter_existencia'),
path('export/existencia/', export_existencia, name='export_existencia'),
# path('calculate/existencia/', calculate_existencia, name='calculate_existencia'),
]
| [
"jucebridu@gmail.com"
] | jucebridu@gmail.com |
d9cc9a117f428a12f40c8b4b8d27458a10fce42d | 739fb6eb19eccf179d9cdce8d79169c31610b5d9 | /solarsan/storage/device/backend_parted.py | 54a710ff45ead4cadbeff7680ecad86ff904674d | [] | no_license | akatrevorjay/solarsan | af17a8eccbe78c550236143ccb9796423eeec98c | 8ed19bc7d481e398bce318b7d513f4583f1e623f | refs/heads/master | 2020-04-09T22:59:37.896355 | 2013-05-03T02:19:13 | 2013-05-03T02:19:13 | 7,585,765 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,348 | py |
raise NotImplemented
from solarsan.utils import convert_bytes_to_human
#import os
import parted
RawDevice = parted.Device
def get_device_by_path(device):
"""Returns parted device for given device file"""
dev = parted.getDevice(device)
dsk = parted.Disk(dev)
return dsk
def get_devices():
"""Enumerates parted devies"""
return parted.getAllDevices()
class BaseDevice(object):
"""
Device Info
"""
# Vendor is apparently 'ATA' ? Doesn't make sense, not including this for
# now. If needed just split(self.model)[0].
#@property
#def vendor(self):
# return self._backend_device.DriveVendor
@property
def model(self):
return self._backend_device.DriveModel
@property
def revision(self):
return self._backend_device.DriveRevision
@property
def serial(self):
return self._backend_device.DriveSerial
# Partitions only
#@property
#def uuid(self):
# return self._backend_device.DriveUuid
@property
def wwn(self):
return self._backend_device.DriveWwn
def size(self, human=False):
ret = self._backend_device.DeviceSize
if human:
ret = convert_bytes_to_human(ret)
return ret
@property
def block_size(self):
return self._backend_device.DeviceBlockSize
def paths(self, by_id=True, by_path=True):
ret = set([self._backend_device.path])
return list(ret)
"""
SMART
"""
@property
def smart_status(self):
return self._backend_device.DriveAtaSmartStatus
@property
def is_smart_available(self):
return self._backend_device.DriveAtaSmartIsAvailable
# Not yet implemented in udisks OR in python-udisks
#def smart_self_test(self):
# return self._backend_device.DriveAtaInitiateSelfTest()
"""
Device Properties
"""
@property
def is_rotational(self):
#return self._backend_device.DriveIsRotational
return True
@property
def is_partitioned(self):
#return self._backend_device.DeviceIsPartitionTable
return True
@property
def is_mounted(self):
return self._backend_device.DeviceIsMounted
@property
def mount_paths(self):
return self._backend_device.DeviceMountPaths
@property
def is_removable(self):
#return self._backend_device.DeviceIsRemovable
return False
@property
def is_readonly(self):
return self._backend_device.DeviceIsReadOnly
"""
Hmm, not sure if these even belong here
"""
@property
def is_drive(self):
return self._backend_device.DeviceIsDrive
@property
def is_partition(self):
return self._backend_device.DeviceIsPartition
"""
LVM2
"""
@property
def is_lvm2_lv(self):
return self._backend_device.DeviceIsLinuxLvm2LV
@property
def is_lvm2_pv(self):
return self._backend_device.DeviceIsLinuxLvm2PV
"""
mdraid
"""
@property
def is_mdraid(self):
return self._backend_device.DeviceIsLinuxMd
@property
def is_mdraid_degraded(self):
return self._backend_device.LinuxMdIsDegraded
@property
def is_mdraid_component(self):
return self._backend_device.DeviceIsLinuxMdComponent
| [
"trevorj@localhostsolutions.com"
] | trevorj@localhostsolutions.com |
80137d902667e854909bc7e04fed7030374b6f67 | 163bbb4e0920dedd5941e3edfb2d8706ba75627d | /Code/CodeRecords/2798/60642/259052.py | 97b49143c4b9a7d990acae98a29e2f49c9208ed6 | [] | 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 | 749 | py | input()
a = input().split()
list = []
for i in range(len(a)):
list.append(int(a[i]))
listsum = sum(list)/3
middlesum = 0
flexible = 0
one = 1
two = 1
thrid = 0
#listsum==0 and max(list)==0
if(listsum==0 and max(list)==0):
print(int((len(list)-1)*(len(list)-2)/2))
else:
for i in range(len(list)):
middlesum = middlesum + list[i]
if (middlesum == listsum):
while (i < len(list) - 2 and list[i + 1] == 0 and i != 0):
if(thrid==0):
one=one+1
else:
two=two+1
i=i+1
middlesum = 0
thrid+=1
if (one!=1 or two!=1):
print(one*two)
elif(thrid==3):
print(1)
else:
print(0) | [
"1069583789@qq.com"
] | 1069583789@qq.com |
c5df86b21683747859ac8b04bfb51ce1fba576f6 | ef7a5e1445706482a0e20d2632f6cd3d0e279031 | /amy/workshops/migrations/0068_auto_20160119_1247.py | 1938629e7f6a75bd9603042e9a143da8d137ed05 | [
"MIT"
] | permissive | pbanaszkiewicz/amy | 7bf054463f4ecfa217cc9e52a7927d22d32bcd84 | f97631b2f3dd8e8f502e90bdb04dd72f048d4837 | refs/heads/develop | 2022-11-17T18:56:18.975192 | 2022-11-03T23:19:41 | 2022-11-03T23:19:41 | 28,005,098 | 0 | 3 | MIT | 2018-03-20T18:48:55 | 2014-12-14T19:25:22 | Python | UTF-8 | Python | false | false | 1,400 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('workshops', '0067_person_username_regexvalidator'),
]
operations = [
migrations.AddField(
model_name='event',
name='instructors_post',
field=models.URLField(verbose_name='Pre-workshop assessment survey for instructors', blank=True, default=''),
),
migrations.AddField(
model_name='event',
name='instructors_pre',
field=models.URLField(verbose_name='Pre-workshop assessment survey for instructors', blank=True, default=''),
),
migrations.AddField(
model_name='event',
name='learners_longterm',
field=models.URLField(verbose_name='Long-term assessment survey for learners', blank=True, default=''),
),
migrations.AddField(
model_name='event',
name='learners_post',
field=models.URLField(verbose_name='Post-workshop assessment survey for learners', blank=True, default=''),
),
migrations.AddField(
model_name='event',
name='learners_pre',
field=models.URLField(verbose_name='Pre-workshop assessment survey for learners', blank=True, default=''),
),
]
| [
"piotr@banaszkiewicz.org"
] | piotr@banaszkiewicz.org |
19ab24349e495605f1cd9e93d8a2710dd41a232c | 7fcdb9f3d8dfd39bf196fdb473fba5566cd97500 | /test/output/util.py | 87658fe16bda1560684da2c5355493ff62797e9c | [
"MIT"
] | permissive | tek/myo-py | 4ccf7892a8317d54a02ed8f3d65ea54f07d984b4 | 3772a00a021cbf4efb55786e26881767d854afe8 | refs/heads/master | 2021-10-19T20:45:24.774281 | 2019-02-23T15:16:58 | 2019-02-23T15:16:58 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 590 | py | from amino import List, do, Do
from ribosome.nvim.api.command import nvim_command_output
from ribosome.nvim.io.compute import NvimIO
def myo_syntax_items(lines: List[str]) -> List[str]:
return lines.filter(lambda a: a.startswith('Myo')).rstrip
@do(NvimIO[List[str]])
def myo_syntax() -> Do:
syntax = yield nvim_command_output('syntax')
return myo_syntax_items(syntax)
@do(NvimIO[List[str]])
def myo_highlight() -> Do:
syntax = yield nvim_command_output('highlight')
return myo_syntax_items(syntax)
__all__ = ('myo_syntax_items', 'myo_syntax', 'myo_highlight',)
| [
"torstenschmits@gmail.com"
] | torstenschmits@gmail.com |
895c1c57ee896fd80be22acead95bf4099357fd2 | 398c86f15d919eb6b5a7fa1d400383d4d3968fa8 | /pvasync/callback_registry.py | 45fd9d3d9b52db5cf94d1e32fcf80547ff560c67 | [
"EPICS",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | klauer/pypvasync | 7aab887abf2cc14bcbc1a4fc637e80d913518493 | 1096624d95dda4973c1bea6a2f2e7241b91469ef | refs/heads/async | 2020-04-09T22:00:58.547815 | 2016-06-22T21:58:43 | 2016-06-22T21:58:48 | 50,545,232 | 1 | 2 | NOASSERTION | 2018-10-18T16:33:20 | 2016-01-27T23:23:06 | Python | UTF-8 | Python | false | false | 5,968 | py | import asyncio
import sys
import logging
import functools
from collections import OrderedDict
from . import ca
from . import dbr
logger = logging.getLogger(__name__)
loop = asyncio.get_event_loop()
def _locked(func):
'''Lock functions with the context's subscription lock'''
@functools.wraps(func)
def inner(self, *args, **kwargs):
with self._sub_lock:
return func(self, *args, **kwargs)
return inner
class ChannelCallbackBase:
sig = None
def __init__(self, registry, chid):
self.registry = registry
self.chid = ca.channel_id_to_int(chid)
self.handler_id = None
self.context = registry.context
self.pvname = self.context.channel_to_pv[self.chid]
self._sub_lock = registry._sub_lock
self.callbacks = OrderedDict()
self.oneshots = []
def create(self):
pass
def destroy(self):
for cbid in list(self.callbacks.keys()):
self.remove_callback(cbid, destroy_if_empty=False)
@_locked
def add_callback(self, cbid, func, *, oneshot=False):
self.callbacks[cbid] = func
if oneshot:
self.oneshots.append(cbid)
return cbid
def clear_callbacks(self):
for cbid in list(self.callbacks.keys()):
self.remove_callback(cbid)
@_locked
def remove_callback(self, cbid, *, destroy_if_empty=True):
del self.callbacks[cbid]
try:
self.oneshots.remove(cbid)
except ValueError:
pass
if len(self.callbacks) == 0 and destroy_if_empty:
self.destroy()
@_locked
def process(self, **kwargs):
with self.context._sub_lock:
exceptions = []
for cbid, func in self.callbacks.items():
try:
func(chid=self.chid, **kwargs)
except Exception as ex:
exceptions.append((ex, sys.exc_info()[2]))
logger.error('Unhandled callback exception (chid: %s kw: '
'%s)', self.chid, kwargs, exc_info=ex)
for cbid in list(self.oneshots):
self.remove_callback(cbid)
return exceptions
def __repr__(self):
return '{0}({1.pvname!r})'.format(self.__class__.__name__, self)
class ChannelCallbackRegistry:
def __init__(self, context, sig_classes):
self.context = context
self.sig_classes = sig_classes
self.handlers_by_chid = {}
self.handlers = {}
self.cbid_owner = {}
self._cbid = 0
self._handler_id = 0
self._sub_lock = context._sub_lock
def __getstate__(self):
# We cannot currently pickle the callables in the registry, so
# return an empty dictionary.
return {}
def __setstate__(self, state):
# re-initialise an empty callback registry
self.__init__()
@_locked
def subscribe(self, sig, chid, func, *, oneshot=False, **kwargs):
if sig not in self.sig_classes:
raise ValueError("Allowed signals are {0}".format(
tuple(self.sig_classes.keys())))
self._cbid += 1
cbid = self._cbid
chid = ca.channel_id_to_int(chid)
if chid not in self.handlers_by_chid:
self.handlers_by_chid[chid] = {sig: []
for sig in self.sig_classes.keys()}
sig_handlers = self.handlers_by_chid[chid][sig]
handler_class = self.sig_classes[sig]
new_handler = handler_class(self, chid, **kwargs)
# fair warning to anyone looking to make this more efficient (you know
# who you are): there shouldn't be enough entries in the callback list
# to make it worth optimizing
for handler in sig_handlers:
if handler >= new_handler:
new_handler = handler
break
self.cbid_owner[cbid] = new_handler
new_handler.add_callback(cbid, func, oneshot=oneshot)
if new_handler not in sig_handlers:
self._handler_id += 1
new_handler.handler_id = self._handler_id
self.handlers[new_handler.handler_id] = new_handler
sig_handlers.append(new_handler)
new_handler.create()
return new_handler, cbid
@_locked
def unsubscribe(self, cbid):
"""Disconnect the callback registered with callback id *cbid*
Parameters
----------
cbid : int
The callback index and return value from ``connect``
"""
owner = self.cbid_owner.pop(cbid)
owner.remove_callback(cbid)
if not owner.callbacks:
chid, sig = owner.chid, owner.sig
self.handlers_by_chid[chid][sig].remove(owner)
# TODO here is where chid can be checked to see if it's in use
# anywhere and can potentially be cleared
subs = list(self.subscriptions_by_chid(chid))
if not subs:
self.context.clear_channel(chid)
@_locked
def process(self, sig, chid, *, cbid=None, handler_id=None, **kwargs):
try:
if sig == 'connection':
handler = self.handlers_by_chid[chid]['connection'][0]
elif handler_id is not None:
handler = self.handlers[handler_id]
elif cbid is not None:
handler = self.cbid_owner[cbid]
else:
logger.debug('Handler information not present?')
return
except (KeyError, IndexError) as ex:
logger.debug('Cannot determine callback event handler',
exc_info=ex)
return
return handler.process(**kwargs)
def subscriptions_by_chid(self, chid):
for sig, handlers in self.handlers_by_chid[chid].items():
for handler in handlers:
yield sig, handler
| [
"klauer@bnl.gov"
] | klauer@bnl.gov |
7c8c1246c4ae27a94b5448c892bd003dd5c6ef9d | f0d713996eb095bcdc701f3fab0a8110b8541cbb | /Wd9cCvFKC3fHzgqSx_15.py | a3c8d74a1ece8c3f345eb9e427d5ac7b18bc5bf6 | [] | 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 | 478 | py | """
Create a function that takes a number `num` and returns each place value in
the number.
### Examples
num_split(39) ➞ [30, 9]
num_split(-434) ➞ [-400, -30, -4]
num_split(100) ➞ [100, 0, 0]
### Notes
N/A
"""
def num_split(num):
sign = 1 if num >= 0 else -1
num, res, power = abs(num), [], 0
while num:
num, rem = divmod(num, 10)
res.append(sign * rem * pow(10, power))
power += 1
return res[::-1]
| [
"daniel.reich@danielreichs-MacBook-Pro.local"
] | daniel.reich@danielreichs-MacBook-Pro.local |
99f1805f15b943698cbc96aebb89ecc9472d1efc | 164e0f43ef3ad4cb7f6b28dfdd2bfbaa66d38ce2 | /Greatest_Common_Divisor_of _Strings/Greatest_Common_Divisor_of _Strings.py | 246a75b2eb062011518f55ab93c08a9b5b458647 | [] | no_license | maoxx241/code | b217f2d10065d90f52cfa38788c99e238565b892 | 16e97ec5ee7ae9ffa69da2e001d15a86d73d2040 | refs/heads/master | 2021-07-11T14:25:35.098241 | 2020-11-25T14:01:56 | 2020-11-25T14:01:56 | 222,544,519 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 585 | py | class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
def gcd(a, b):
while b:
a, b = b, a%b
return a
g=gcd(len(str1),len(str2))
if g!=str2:
index=0
for i in range(0,len(str2)//g):
if str2[0:g]!=str2[index:index+g]:
return ""
index+=g
index=0
for i in range(0,len(str1)//g):
if str2[0:g]!=str1[index:index+g]:
return ""
index+=g
return str1[0:g] | [
"maomaoyu870@gmail.com"
] | maomaoyu870@gmail.com |
7bef6226d124ff3588cc3ee4c3ac4cf64ceb1072 | fbd98eadeb1cd8cd9ecbe2c53fb08c79a6f1e6ad | /m3_functions_pass_functions_to_functions.py | a016f5065e06080563a223bdfaa35c36060e331f | [] | no_license | kolibril13/tricks_for_python | 2061de206078158dc0743548969a6ab5ed44438a | 73fda8eb07ce39dbf4f87be6a25dd868270395f9 | refs/heads/master | 2023-03-19T15:22:34.519240 | 2023-03-13T13:32:28 | 2023-03-13T13:32:28 | 173,735,731 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,047 | py |
# Example with lambda function
# generic function takes op and its argument
def runOp(op, val):
return op(val)
# declare full function
def add(x, y):
return x+y
# run example
f = lambda y: add(3, y)
result = runOp(f, 1) # is 4
print(result)
#Example2: is a little faster
from functools import partial
# generic function takes op and its argument
def runOp(op, val):
return op(val)
# declare full function
def add(x, y):
return x+y
# run example
f = partial(add, 3)
print(runOp(f, 1)) # is 4
#Example 3: write own wrapper:
# generic function takes op and its argument
def runOp(op, val):
return op(val)
# declare full function
def add(x, y):
return x+y
# declare partial function
def addPartial(x):
def _wrapper(y):
return add(x, y)
return _wrapper
# run example
f = addPartial(3)
print(runOp(f, 1)) # is 4
#EXAMPLE with two inputs:
#In short:
def multipy(func, val,val2):
result= func(val)*val2
return result
def func(a,b):
return a+b
print(multipy(lambda x: func(1,x),3,10)) | [
"jan-hendrik.mueller@gmx.net"
] | jan-hendrik.mueller@gmx.net |
e71da042cbba6e2807a6795eb19a7d33ac711c9a | b9dd413023bb129263ed8fccc765f215a8764879 | /house/tenant/views.py | bcadf4fd430affe2d0af948f9275c54519ddd2f3 | [] | no_license | CollinsMuiruri/what-a-house | 3c849b32fcb2f89eac01260224d87d98408bd08f | 3cbe26913f141521dd74371965e1c52a6737b317 | refs/heads/master | 2020-03-22T21:25:08.857285 | 2018-07-17T19:55:13 | 2018-07-17T19:55:13 | 140,686,345 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 244 | py | from django.shortcuts import render
# from django.contrib.auth.decorators import login_required
# Create your views here.
# @login_required(login_url='accounts/login/')
def tenant_homepage(request):
return render(request, 'tenant.html')
| [
"wanyekicollins@gmail.com"
] | wanyekicollins@gmail.com |
dc96753a802f68ee76c1e13cf2268857af2307a1 | 5085dfd5517c891a1f5f8d99bf698cd4bf3bf419 | /094.py | ca59918b4a2d34b7cddaabb4781e84d1d35e4018 | [] | no_license | Lightwing-Ng/100ExamplesForPythonStarter | 01ffd4401fd88a0b997656c8c5f695c49f226557 | 56c493d38a2f1a1c8614350639d1929c474de4af | refs/heads/master | 2020-03-10T22:07:37.340512 | 2018-04-15T13:16:30 | 2018-04-15T13:16:30 | 129,611,532 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,314 | py | #!/usr/bin/env python
# _*_ coding:utf-8 _*_
"""
* @author: Lightwing Ng
* email: rodney_ng@iCloud.com
* created on Apr 15, 2018, 8:43 PM
* Software: PyCharm
* Project Name: Tutorial
题目:时间函数举例4,一个猜数游戏,判断一个人反应快慢。
程序分析:无。
"""
import time
import random
play_it = input('do you want to play it.(\'y\' or \'n\')')
while play_it == 'y':
c = input('input a character: \n')
i = random.randint(0, 2 ** 32) % 100
print('please input number you guess: \n')
start = time.clock()
a = time.time()
guess = int(input('input your guess: \n'))
while guess != i:
if guess > i:
print('please input a little smaller')
guess = int(input('input your guess: \n'))
else:
print('please input a little bigger')
guess = int(input('input your guess: \n'))
end = time.clock()
b = time.time()
var = (end - start) / 18.2
print(var)
# print 'It took you %6.3 seconds' % time.difftime(b,a))
if var < 15:
print('you are very clever!')
elif var < 25:
print('you are normal!')
else:
print('you are stupid!')
print('Congratulations')
print('The number you guess is %d' % i)
play_it = input('do you want to play it.')
| [
"rodney_ng@icloud.com"
] | rodney_ng@icloud.com |
c8e1ed88505a2e750f8c49e8faa777aa7610333a | de23fa7b6a2ea9b85f994ccc06b4c16625c17153 | /photoprocessor/utils.py | 42a4c078ccb56f15741de031406e3973c3503cac | [
"BSD-3-Clause"
] | permissive | cuker/django-photoprocessor | 19341d486784ddc0a74fc56f967edb579e21d913 | 5d8093b86f364d71789b39b458dbd51a6b285136 | refs/heads/master | 2021-01-19T17:21:42.877817 | 2013-04-02T00:15:21 | 2013-04-02T00:15:21 | 2,556,736 | 13 | 6 | NOASSERTION | 2019-11-05T21:04:58 | 2011-10-11T17:00:53 | Python | UTF-8 | Python | false | false | 1,621 | py | """ Photoprocessor utility functions """
import tempfile
import math
from lib import Image
def img_to_fobj(img, info, **kwargs):
tmp = tempfile.TemporaryFile()
# Preserve transparency if the image is in Pallette (P) mode.
if img.mode == 'P':
kwargs['transparency'] = len(img.split()[-1].getcolors())
else:
img.convert('RGB')
if 'quality' in info:
kwargs['quality'] = info['quality']
img.save(tmp, info['format'], **kwargs)
tmp.seek(0)
return tmp
def image_entropy(im):
"""
Calculate the entropy of an image. Used for "smart cropping".
"""
#if not isinstance(im, Image):
# # Can only deal with PIL images. Fall back to a constant entropy.
# return 0
hist = im.histogram()
hist_size = float(sum(hist))
hist = [h / hist_size for h in hist]
return -sum([p * math.log(p, 2) for p in hist if p != 0])
def _compare_entropy(start_slice, end_slice, slice, difference):
"""
Calculate the entropy of two slices (from the start and end of an axis),
returning a tuple containing the amount that should be added to the start
and removed from the end of the axis.
"""
start_entropy = image_entropy(start_slice)
end_entropy = image_entropy(end_slice)
if end_entropy and abs(start_entropy / end_entropy - 1) < 0.01:
# Less than 1% difference, remove from both sides.
if difference >= slice * 2:
return slice, slice
half_slice = slice // 2
return half_slice, slice - half_slice
if start_entropy > end_entropy:
return 0, slice
else:
return slice, 0
| [
"jasonk@cukerinteractive.com"
] | jasonk@cukerinteractive.com |
bf3f547dfad3d98a6faf9cce9a0c70fac2f77080 | 00904c49ee6072ce86a92326ad67b45071ab5695 | /tests/cli/test_rasa_train.py | 78f91469963399e7039e7345e64b8ad6f4600172 | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0",
"MIT"
] | permissive | cvphelps/rasa | b19d3c8c78ec45382960a9f12f241b69a64e18d7 | 315f0878cf66c39143bc298acd665a05bff8510b | refs/heads/master | 2020-05-25T00:18:15.882021 | 2019-05-18T18:30:01 | 2019-05-18T18:30:01 | 187,530,323 | 0 | 1 | null | 2019-05-19T21:33:32 | 2019-05-19T21:33:32 | null | UTF-8 | Python | false | false | 5,091 | py | import os
import shutil
from rasa.nlu.utils import list_files
def test_train(run_in_default_project):
temp_dir = os.getcwd()
run_in_default_project(
"train",
"-c",
"config.yml",
"-d",
"domain.yml",
"--data",
"data",
"--out",
"train_models",
"--fixed-model-name",
"test-model",
)
assert os.path.exists(os.path.join(temp_dir, "train_models"))
files = list_files(os.path.join(temp_dir, "train_models"))
assert len(files) == 1
assert os.path.basename(files[0]) == "test-model.tar.gz"
def test_train_skip_on_model_not_changed(run_in_default_project):
temp_dir = os.getcwd()
assert os.path.exists(os.path.join(temp_dir, "models"))
files = list_files(os.path.join(temp_dir, "models"))
assert len(files) == 1
file_name = files[0]
run_in_default_project("train")
assert os.path.exists(os.path.join(temp_dir, "models"))
files = list_files(os.path.join(temp_dir, "models"))
assert len(files) == 1
assert file_name == files[0]
def test_train_force(run_in_default_project):
temp_dir = os.getcwd()
assert os.path.exists(os.path.join(temp_dir, "models"))
files = list_files(os.path.join(temp_dir, "models"))
assert len(files) == 1
run_in_default_project("train", "--force")
assert os.path.exists(os.path.join(temp_dir, "models"))
files = list_files(os.path.join(temp_dir, "models"))
assert len(files) == 2
def test_train_with_only_nlu_data(run_in_default_project):
temp_dir = os.getcwd()
assert os.path.exists(os.path.join(temp_dir, "data/stories.md"))
os.remove(os.path.join(temp_dir, "data/stories.md"))
shutil.rmtree(os.path.join(temp_dir, "models"))
run_in_default_project("train", "--fixed-model-name", "test-model")
assert os.path.exists(os.path.join(temp_dir, "models"))
files = list_files(os.path.join(temp_dir, "models"))
assert len(files) == 1
assert os.path.basename(files[0]) == "nlu-test-model.tar.gz"
def test_train_with_only_core_data(run_in_default_project):
temp_dir = os.getcwd()
assert os.path.exists(os.path.join(temp_dir, "data/nlu.md"))
os.remove(os.path.join(temp_dir, "data/nlu.md"))
shutil.rmtree(os.path.join(temp_dir, "models"))
run_in_default_project("train", "--fixed-model-name", "test-model")
assert os.path.exists(os.path.join(temp_dir, "models"))
files = list_files(os.path.join(temp_dir, "models"))
assert len(files) == 1
assert os.path.basename(files[0]) == "core-test-model.tar.gz"
def test_train_core(run_in_default_project):
run_in_default_project(
"train",
"core",
"-c",
"config.yml",
"-d",
"domain.yml",
"--stories",
"data",
"--out",
"train_rasa_models",
"--store-uncompressed",
"--fixed-model-name",
"rasa-model",
)
assert os.path.exists("train_rasa_models/core-rasa-model")
assert os.path.isdir("train_rasa_models/core-rasa-model")
def test_train_nlu(run_in_default_project):
run_in_default_project(
"train",
"nlu",
"-c",
"config.yml",
"--nlu",
"data/nlu.md",
"--out",
"train_models",
)
assert os.path.exists("train_models")
files = list_files("train_models")
assert len(files) == 1
assert os.path.basename(files[0]).startswith("nlu-")
def test_train_help(run):
output = run("train", "--help")
help_text = """usage: rasa train [-h] [-v] [-vv] [--quiet] [--data DATA [DATA ...]]
[-c CONFIG] [-d DOMAIN] [--out OUT]
[--augmentation AUGMENTATION] [--debug-plots]
[--dump-stories] [--fixed-model-name FIXED_MODEL_NAME]
[--force] [--store-uncompressed]
{core,nlu} ..."""
lines = help_text.split("\n")
for i, line in enumerate(lines):
assert output.outlines[i] == line
def test_train_nlu_help(run):
output = run("train", "nlu", "--help")
help_text = """usage: rasa train nlu [-h] [-v] [-vv] [--quiet] [-c CONFIG] [--out OUT]
[-u NLU] [--fixed-model-name FIXED_MODEL_NAME]
[--store-uncompressed]"""
lines = help_text.split("\n")
for i, line in enumerate(lines):
assert output.outlines[i] == line
def test_train_core_help(run):
output = run("train", "core", "--help")
help_text = """usage: rasa train core [-h] [-v] [-vv] [--quiet] [-s STORIES] [-d DOMAIN]
[-c CONFIG [CONFIG ...]] [--out OUT]
[--augmentation AUGMENTATION] [--debug-plots]
[--dump-stories] [--force]
[--fixed-model-name FIXED_MODEL_NAME]
[--store-uncompressed]
[--percentages [PERCENTAGES [PERCENTAGES ...]]]
[--runs RUNS]"""
lines = help_text.split("\n")
for i, line in enumerate(lines):
assert output.outlines[i] == line
| [
"tabergma@gmail.com"
] | tabergma@gmail.com |
2de02136b9c5552790172158ee4bc3b34622aacf | 2cd24ddd86e97d01c20a96bfc8ed8b541a80d608 | /apps/venta/migrations/0002_detalle_venta_subtotal.py | 3586355c67519594b57ec74976acb9da199b81a7 | [] | no_license | chrisstianandres/don_chuta | 1c048db633246effb06800f28a3a4d8af2cac199 | e20abeb892e6de572a470cd71c5830c6f9d1dafa | refs/heads/master | 2023-01-07T09:14:52.837462 | 2020-11-18T20:55:10 | 2020-11-18T20:55:10 | 293,209,494 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 414 | py | # Generated by Django 2.2.14 on 2020-09-09 14:49
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('venta', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='detalle_venta',
name='subtotal',
field=models.DecimalField(decimal_places=2, default=0.0, max_digits=9),
),
]
| [
"Chrisstianandres@gmail.com"
] | Chrisstianandres@gmail.com |
5c2d8defcee32e7acd95804186488aa2afb6c268 | 25279384025751b3b400aea006f164d66c167104 | /lianxi_xuexi/appium_frame/demo/002.py | 166325be457361628dc0b84e4ae67c970e2f59d9 | [] | no_license | linruohan/my_study | 6fda0b49f4c671919ec7a7fc6ba596b49ec66e59 | 7666f93259495b6928751d50eb1bab114e118038 | refs/heads/master | 2020-03-28T18:26:47.776943 | 2018-09-17T05:52:17 | 2018-09-17T05:52:17 | 148,882,060 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,488 | py | #coding=utf-8
import time
import os
from appium import webdriver
# 获取当前目录的根路径
apk_path=os.path.abspath(os.path.join(os.path.dirname(__file__),".."))
print(apk_path)
desired_caps ={}
desired_caps['platformName'] = 'Android' #设备系统
desired_caps['platformVersion'] = '5.1.1' #设备系统版本
desired_caps['deviceName'] = 'SCL-AL00' #设备名称
# 测试包的路径
desired_caps['app']=apk_path+'\\app\\baidu.apk'
# 不需要每次都安装apk
desired_caps['noReset'] = True
# 应用程序的包名
desired_caps['appPackage']='com.baidu.searchbox'
desired_caps['appActivity']='com.baidu.searchbox.SplashActivity'
#如果设置的是app包的路径,则不需要配appPackage和appActivity,同理反之
driver=webdriver.Remote('http://193.169.100.238:8888/wd/hub',desired_caps)#启动app
print('已经打开app。。。')
time.sleep(15)
# 根据元素id来定位
# driver.find_element_by_id('com.baidu.searchbox:id/baidu_searchbox').click()
# 根据元素id来定位
# 点击“热点”频道
#hot = driver.find_element_by_id('com.baidu.searchbox:id/tab_indi_title')
hot = driver.find_element_by_android_uiautomator("text(\"热点\")")
hot.click()
# 点击“推荐”频道
rec = driver.find_element_by_android_uiautomator("text(\"推荐\")")
rec.click()
# 根据元素class 来定位
# 点击“输入框”
# searchBox = driver.find_element_by_class_name('android.widget.Button')
# searchBox.click()
time.sleep(12)
''' 这样来回切换点击是运行不成功,
如果每次只点击一个,发现点击麦克风的index是1,
但是ui automator viewer给出的是index是2,
这个地方是有问题的。'''
# 点击“我的”
driver.find_element_by_xpath("//*[@class='android.widget.FrameLayout' and @index='4']").click()
time.sleep(2)
# 点击“默认主页“
driver.find_element_by_xpath("//*[@class='android.widget.FrameLayout' and @index='0']").click()
time.sleep(2)
# 点击““视频
driver.find_element_by_xpath("//*[@class='android.widget.FrameLayout' and @index='1']").click()
time.sleep(2)
# 点击“我的关注“
driver.find_element_by_xpath("//*[@class='android.widget.FrameLayout' and @index='3']").click()
time.sleep(2)
# 点击“麦克风“
driver.find_element_by_xpath("//*[@class='android.widget.FrameLayout' and @index='2']").click()
time.sleep(2)
# 点击“我的”
# my_home = driver.find_element_by_xpath("//*[@class='android.widget.FrameLayout'][5]").click()
time.sleep(2)
driver.quit()
| [
"mjt1220@126.com"
] | mjt1220@126.com |
e2bd2ab5edd7f0b2b6ecee50a088961eda9c023e | 402be2009a7fb4fd1996adce889d9c945e992067 | /project/L1-regularization.py | 962301e7948f5eeff4bb6fb8e7719b091ee0ccd9 | [] | no_license | pekkipo/Linear-regression | 538475729edc246c3fac37665b42fc0589c374d7 | b1907dbcafd585989d579aea4a8fb5f78225d2e6 | refs/heads/master | 2021-01-11T16:31:53.941814 | 2017-01-26T20:20:10 | 2017-01-26T20:20:10 | 80,103,811 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,363 | py | # The idea is to generate the fat matrix with lots of features
# Use L1 regularization to see if we can find a sparse set of weights that identifies the useful dimensions of x
import numpy as np
import matplotlib.pyplot as plt
# Fat matrix
N = 50 # number of points
D = 50 # number of dimensions
# uniformly distributed numbers between -5, +5
X = (np.random.random((N, D)) - 0.5)*10
# centered around zero from -5 to 5
# true weights - only the first 3 dimensions of X affect Y
true_w = np.array([1, 0.5, -0.5] + [0]*(D - 3)) # last D - 3 (47) are zeroes and do not influence the output
# generate Y - add noise with variance 0.5
Y = X.dot(true_w) + np.random.randn(N)*0.5 # + gaussian random noise
# perform gradient descent to find w
costs = [] # keep track of squared error cost
w = np.random.randn(D) / np.sqrt(D) # randomly initialize w
learning_rate = 0.001
l1 = 10.0 # Also try 5.0, 2.0, 1.0, 0.1 - what effect does it have on w?
for t in range(500):
# update w
Y_hat = X.dot(w) # prediction
delta = Y_hat - Y
w = w - learning_rate*(X.T.dot(delta) + l1*np.sign(w))
# find and store the cost
mse = delta.dot(delta) / N
costs.append(mse)
# plot the costs
plt.plot(costs)
plt.show()
print("final w:", w)
# plot our w vs true w
plt.plot(true_w, label='true w')
plt.plot(w, label='w_MAP')
plt.legend()
plt.show() | [
"pekkipodev@gmail.com"
] | pekkipodev@gmail.com |
35c461e0597498996611e72c7cb8981e69a30b0a | 748526cd3d906140c2975ed1628277152374560f | /DEInterview/Python/get_average_word_length.py | 17a5c1befdb0464b12b03e8629507eec58a7697c | [] | no_license | librar127/PythonDS | d27bb3af834bfae5bd5f9fc76f152e13ce5485e1 | ec48cbde4356208afac226d41752daffe674be2c | refs/heads/master | 2021-06-14T10:37:01.303166 | 2021-06-11T03:39:08 | 2021-06-11T03:39:08 | 199,333,950 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 224 | py | def getAverageLength(string):
return round(sum([len(each.strip()) for each in string.split()])/len(string.split()), 2)
string = "Firstlydddd this is the firstcccc string "
print(getAverageLength(string))
| [
"librar127@gmail.com"
] | librar127@gmail.com |
a550a98dfa80bc116f1ebbe5e5590be4f3422d5f | ca507259c36a4299666f4c064f25832f5c3f45c1 | /symbol_openapi_client/models/resolution_entry_dto.py | a2fb6cf944cc30c7e374bc4736d80a7e823cd470 | [] | no_license | fullcircle23/symbol-openapi-python-client | ae38a2537d1f2eebca115733119c444b79ec4962 | 3728d30eb1b5085a5a5e991402d180fac8ead68b | refs/heads/master | 2022-04-15T06:20:47.821281 | 2020-04-16T02:39:14 | 2020-04-16T02:39:14 | 254,701,919 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,444 | py | # coding: utf-8
"""
****************************************************************************
Copyright (c) 2016-present,
Jaguar0625, gimre, BloodyRookie, Tech Bureau, Corp. All rights reserved.
This file is part of Catapult.
Catapult is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Catapult is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Catapult. If not, see <http://www.gnu.org/licenses/>.
****************************************************************************
Catapult REST Endpoints
OpenAPI Specification of catapult-rest 1.0.20.22 # noqa: E501
The version of the OpenAPI document: 0.8.9
Contact: ravi@nem.foundation
NOTE: This file is auto generated by Symbol OpenAPI Generator:
https://github.com/nemtech/symbol-openapi-generator
Do not edit this file manually.
"""
import pprint
import re # noqa: F401
import six
from symbol_openapi_client.configuration import Configuration
class ResolutionEntryDTO(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
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.
"""
openapi_types = {
'source': 'SourceDTO',
'resolved': 'object'
}
attribute_map = {
'source': 'source',
'resolved': 'resolved'
}
def __init__(self, source=None, resolved=None, local_vars_configuration=None): # noqa: E501
"""ResolutionEntryDTO - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._source = None
self._resolved = None
self.discriminator = None
self.source = source
self.resolved = resolved
@property
def source(self):
"""Gets the source of this ResolutionEntryDTO. # noqa: E501
:return: The source of this ResolutionEntryDTO. # noqa: E501
:rtype: SourceDTO
"""
return self._source
@source.setter
def source(self, source):
"""Sets the source of this ResolutionEntryDTO.
:param source: The source of this ResolutionEntryDTO. # noqa: E501
:type: SourceDTO
"""
if self.local_vars_configuration.client_side_validation and source is None: # noqa: E501
raise ValueError("Invalid value for `source`, must not be `None`") # noqa: E501
self._source = source
@property
def resolved(self):
"""Gets the resolved of this ResolutionEntryDTO. # noqa: E501
:return: The resolved of this ResolutionEntryDTO. # noqa: E501
:rtype: object
"""
return self._resolved
@resolved.setter
def resolved(self, resolved):
"""Sets the resolved of this ResolutionEntryDTO.
:param resolved: The resolved of this ResolutionEntryDTO. # noqa: E501
:type: object
"""
if self.local_vars_configuration.client_side_validation and resolved is None: # noqa: E501
raise ValueError("Invalid value for `resolved`, must not be `None`") # noqa: E501
self._resolved = resolved
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:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, ResolutionEntryDTO):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, ResolutionEntryDTO):
return True
return self.to_dict() != other.to_dict()
| [
"fullcircle2324@gmail.com"
] | fullcircle2324@gmail.com |
76a8042442217a8467899aa4f7425bcf6900eafe | 85a32fc66050b5590f6a54774bbb4b88291894ab | /python/classes/class-1-dealing-with-complex-numbers/python3.py | deb197c1fe5bacca41482dc70132134bbd0e6409 | [] | no_license | charlesartbr/hackerrank-python | 59a01330a3a6c2a3889e725d4a29a45d3483fb01 | bbe7c6e2bfed38132f511881487cda3d5977c89d | refs/heads/master | 2022-04-29T07:40:20.244416 | 2022-03-19T14:26:33 | 2022-03-19T14:26:33 | 188,117,284 | 46 | 37 | null | 2022-03-19T14:26:34 | 2019-05-22T21:38:18 | Python | UTF-8 | Python | false | false | 1,582 | py | import math
class Complex(object):
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary
def __add__(self, no):
c = complex(self.real, self.imaginary) + complex(no.real, no.imaginary)
return Complex(c.real, c.imag)
def __sub__(self, no):
c = complex(self.real, self.imaginary) - complex(no.real, no.imaginary)
return Complex(c.real, c.imag)
def __mul__(self, no):
c = complex(self.real, self.imaginary) * complex(no.real, no.imaginary)
return Complex(c.real, c.imag)
def __truediv__(self, no):
c = complex(self.real, self.imaginary) / complex(no.real, no.imaginary)
return Complex(c.real, c.imag)
def mod(self):
c = abs(complex(self.real, self.imaginary))
return Complex(c.real, c.imag)
def __str__(self):
if self.imaginary == 0:
result = "%.2f+0.00i" % (self.real)
elif self.real == 0:
if self.imaginary >= 0:
result = "0.00+%.2fi" % (self.imaginary)
else:
result = "0.00-%.2fi" % (abs(self.imaginary))
elif self.imaginary > 0:
result = "%.2f+%.2fi" % (self.real, self.imaginary)
else:
result = "%.2f-%.2fi" % (self.real, abs(self.imaginary))
return result
if __name__ == '__main__':
c = map(float, input().split())
d = map(float, input().split())
x = Complex(*c)
y = Complex(*d)
print(*map(str, [x+y, x-y, x*y, x/y, x.mod(), y.mod()]), sep='\n') | [
"e-mail@charles.art.br"
] | e-mail@charles.art.br |
2c5ca58c715a0cb4cf4ecd20746dd765e1bb8e0a | 15f0514701a78e12750f68ba09d68095172493ee | /Python3/1131.py | f345ab1b9dd81cc9c7f3ea7adba2488065b16885 | [
"MIT"
] | permissive | strengthen/LeetCode | 5e38c8c9d3e8f27109b9124ae17ef8a4139a1518 | 3ffa6dcbeb787a6128641402081a4ff70093bb61 | refs/heads/master | 2022-12-04T21:35:17.872212 | 2022-11-30T06:23:24 | 2022-11-30T06:23:24 | 155,958,163 | 936 | 365 | MIT | 2021-11-15T04:02:45 | 2018-11-03T06:47:38 | null | UTF-8 | Python | false | false | 1,107 | py | __________________________________________________________________________________________________
sample 124 ms submission
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
ans = 0
n = len(arr1)
for a, b in (1, 1), (1, -1), (-1, -1), (-1, 1):
mn = a * arr1[0] + b * arr2[0] + 0
for i in range(n):
cur = a * arr1[i] + b * arr2[i] + i
ans = max(ans, cur - mn)
mn = min(mn, cur)
return ans
__________________________________________________________________________________________________
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
n = len(arr1)
rtn = 0
for sign1 in [-1, 1]:
for sign2 in [-1, 1]:
b = []
for i in range(n):
b.append(arr1[i] * sign1 + arr2[i] * sign2 + i)
rtn = max(rtn, max(b) - min(b))
return rtn
__________________________________________________________________________________________________
| [
"strengthen@users.noreply.github.com"
] | strengthen@users.noreply.github.com |
b46dbf659c56de992717890d00386c889de4e04e | 803dff6904c555ba0794ea5741eb426037988b3d | /iliad/routing.py | 9fda465baa8d23b800d81ddbb997c65ebc5182c1 | [] | no_license | grammteus-dev/iliad | 07f8734d74af03214c7549a6ac28dfdae4bb9cdb | bbb74784213914b31e6b3ac22c55984426226508 | refs/heads/master | 2022-11-26T13:38:11.360525 | 2020-01-21T06:26:02 | 2020-01-21T06:26:02 | 233,435,257 | 0 | 0 | null | 2022-11-04T19:31:24 | 2020-01-12T18:02:14 | Python | UTF-8 | Python | false | false | 325 | py |
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
# from authentication.routing import websocket_urlpatterns as authentication_urlpatterns
application = ProtocolTypeRouter({
# 'websocket': AuthMiddlewareStack(
# URLRouter(authentication_urlpatterns),
# ),
})
| [
"nicholas.d.piano@gmail.com"
] | nicholas.d.piano@gmail.com |
251d8dfb549b2d594599a7d179ebfe70f6ad041f | da1d21bb8d0760bfba61cd5d9800400f928868aa | /apps/stats/synchronize.py | f0206127ed14daa9633e2754855ad1acee86a2ec | [] | no_license | biznixcn/WR | 28e6a5d10f53a0bfe70abc3a081c0bf5a5457596 | 5650fbe59f8dfef836503b8092080f06dd214c2c | refs/heads/master | 2021-01-20T23:53:52.887225 | 2014-05-13T02:00:33 | 2014-05-13T02:00:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,751 | py | # -*- coding: utf-8 -*-
import redis
from stats.constants import *
from recsys.utils.synchronize import RedisSync
class RedisStatsSync(RedisSync):
"""
This class synchronizes the redis structures and is intended to be
called when a signal to the DB is generated, once instantiated an object
of this class, call self.Redis_disconnect() after you finished working,
has methods of Father for synchronizing user_favorite_circuits for example
"""
def incr_circuit_fav_count(self, circuit_id):
"""
Increases the counter of times a circuit has been favorited
"""
key = ':'.join(
[CIRCUIT_NMBR_FAVS_1,
str(circuit_id),
CIRCUIT_NMBR_FAVS_2]
)
self.RS.incr(key)
def decr_circuit_fav_count(self, circuit_id):
"""
Decreases the counter of times a circuit has been favorited
"""
key = ':'.join(
[CIRCUIT_NMBR_FAVS_1,
str(circuit_id),
CIRCUIT_NMBR_FAVS_2]
)
if self.RS.get(key) < 0:
self.RS.set(key,1)
self.RS.decr(key)
def set_circuit_fav_count(self, circuit_id, number):
"""
sets the counter of circuit favorites to number
"""
key = ':'.join(
[CIRCUIT_NMBR_FAVS_1,
str(circuit_id),
CIRCUIT_NMBR_FAVS_2]
)
self.RS.set(key, number)
def add_favoriting_user_id(self, circuit_id, user_id):
"""
Add a user id to the circuit's set of favoriting users.
"""
key = ':'.join(
[CIRCUIT_FAV_USRS_1,
str(circuit_id),
CIRCUIT_FAV_USRS_2]
)
self.RS.sadd(key, user_id)
def rm_favoriting_user_id(self, circuit_id, user_id):
"""
Remove a user id from the circuit's set of favoriting users.
"""
key = ':'.join(
[CIRCUIT_FAV_USRS_1,
str(circuit_id),
CIRCUIT_FAV_USRS_2]
)
self.RS.srem(key, user_id)
def incr_circuit_remix_count(self, circuit_id):
"""
Increases the counter of times a circuit has been remixed
"""
key = ':'.join(
[CIRCUIT_NMBR_RMX_1,
str(circuit_id),
CIRCUIT_NMBR_RMX_2]
)
self.RS.incr(key)
def decr_circuit_remix_count(self, circuit_id):
"""
Decreases the counter of times a circuit has been remixed
"""
key = ':'.join(
[CIRCUIT_NMBR_RMX_1,
str(circuit_id),
CIRCUIT_NMBR_RMX_2]
)
if self.RS.get(key) < 0:
self.RS.set(key,1)
self.RS.decr(key)
def set_circuit_remix_count(self, circuit_id, number):
"""
sets the counter of times a circuit has been remixed
"""
key = ':'.join(
[CIRCUIT_NMBR_RMX_1,
str(circuit_id),
CIRCUIT_NMBR_RMX_2]
)
self.RS.set(key, number)
def add_remixed_circuit_id(self, original_id, remixed_id):
"""
Add a remixed circuit id to the original circuit's set of remixed
circuits.
"""
key = ':'.join(
[CIRCUIT_RMX_CTS_1,
str(original_id),
CIRCUIT_RMX_CTS_2]
)
self.RS.sadd(key, remixed_id)
def rm_remixed_circuit_id(self, original_id, remixed_id):
"""
Remove a remixed circuit id from the original circuit's set of
remixed circuits.
"""
key = ':'.join(
[CIRCUIT_RMX_CTS_1,
str(original_id),
CIRCUIT_RMX_CTS_2]
)
self.RS.srem(key, remixed_id)
| [
"mbc@Mathiass-MacBook-Pro.local"
] | mbc@Mathiass-MacBook-Pro.local |
f63601406e233a475aaee8c53f3c416d7c95956d | 8c3b184561d38347df5fcb0299ddf6c28f0bcd75 | /tests/models/test_resource.py | 94b7d552bec9e6999a3ef5131df5cdfcbca35754 | [
"MIT"
] | permissive | bmwant/chemister | fe0d4073c7c45ccef47b485607ed26da9842a2d3 | fbefcc9f548acc69966b6fbe19c4486f471fb390 | refs/heads/master | 2021-07-17T05:55:51.258568 | 2019-06-26T20:07:56 | 2019-06-26T20:07:56 | 129,266,373 | 0 | 0 | MIT | 2020-04-29T23:35:22 | 2018-04-12T14:44:29 | CSS | UTF-8 | Python | false | false | 278 | py | import pytest
from crawler.models.resource import get_resource_by_name
@pytest.mark.run_loop
async def test_get_resource_by_name(pg_engine):
async with pg_engine.acquire() as conn:
result = await get_resource_by_name(conn, 'noname')
assert result is None
| [
"bmwant@gmail.com"
] | bmwant@gmail.com |
211e9cd9ecf3e41d32bfeaa87fae86a696bb9f3e | b592eaa683d5d117057cc77ad5e14bf1d4ffae6c | /leetcode/254-factor-combinations/main.py | 05520487fd0586220545cb0a1ebd1b7a3a6d9f8c | [] | no_license | soninishank/AlgoDaily | 97b4dbc5721660c83f6e71e97767a430378cf35d | 1ecb944dc39c33b042f1ce259dbccea68135f0ce | refs/heads/master | 2020-06-12T20:36:32.153719 | 2019-06-29T03:53:39 | 2019-06-29T03:53:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,890 | py | import math
"""
1st approach: recursion
- for every number from 2 to n-1, if it can divide the current number, it is one of the factors
e.g. 252
252%2 = 0
252%3 = 0
252%4 != 0
....
Time I am not sure
Space I am not sure
LTE
"""
class Solution(object):
def __init__(self):
self.res = []
def getFactors(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
self.dfs(n, 2, [])
return self.res
def dfs(self, num, start, path):
if num == 1:
if len(path) > 1:
self.res.append(path)
return
for i in range(start, num+1):
if num % i == 0:
self.dfs(num/i, i, path+[i])
print(Solution().getFactors(252))
"""
2nd approach: recursion
- for every number from 2 to n-1, if it can divide the current number, it is one of the factors
- the diffrence from the 1st approach is THAT all prime factors must be less than/equal to a sqrt of a number
e.g. 252
252%2 = 0
252%3 = 0
252%4 != 0
....
Time I am not sure
Space I am not sure
16 ms, faster than 97.78%
"""
class Solution(object):
def __init__(self):
self.res = []
def getFactors(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
self.dfs(n, 2, [])
return self.res
def dfs(self, num, start, path):
# the num never gets down to 1, because we use sqrt to factorize
# e.g. 9 => 3 * 3 when it comes to 3, since sqrt(3) = 1, we cant factorize any more
if len(path) > 0:
self.res.append(path+[num])
n = int(math.sqrt(num))
for i in range(start, n+1):
if num % i == 0:
self.dfs(num/i, i, path+[i])
print(Solution().getFactors(252))
| [
"chan9118kin@gmail.com"
] | chan9118kin@gmail.com |
d3692d2fdc9adcd58a55f848a1ea12ffddebd533 | 1f42ca6bbe600eefbf80cbe5c1b8485003b2cb35 | /session_09_working_files/inclass_exercises/inclass_9.4.py | 625689f8be2c227355d4bad9a37608e615e361d9 | [] | no_license | jongiles/python_data_apy | a4589e39b3a3eaed850d0177ee79f649dd3a0ee1 | 343bd649635e98897d3924041374e9ad58eb345d | refs/heads/master | 2023-05-12T22:43:16.299571 | 2021-06-07T22:00:27 | 2021-06-07T22:00:27 | 374,784,872 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 298 | py | # 9.4: Convert a function to lambda. The following function
# takes one argument and returns the value doubled. Convert
# to lambda and use in the map() function.
def doubleit(arg):
return arg * 2
seq = [1, 2, 3, 4]
seq2 = map(doubleit, seq)
print(list(seq2)) # [2, 4, 6, 8]
| [
"jgiles@MacBook-Pro.local"
] | jgiles@MacBook-Pro.local |
7352eedfbd1046fb58fea33ff769cd70365b3620 | 9e988c0dfbea15cd23a3de860cb0c88c3dcdbd97 | /sdBs/AllRun/sdssj_031339.21+042028.1/sdB_sdssj_031339.21+042028.1_lc.py | 4eda8823f6bdc5afb9901eadaf2464ff316fee07 | [] | 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 | 369 | py | from gPhoton.gAperture import gAperture
def main():
gAperture(band="NUV", skypos=[48.413375,4.341139], stepsz=30., csvfile="/data2/fleming/GPHOTON_OUTPU/LIGHTCURVES/sdBs/sdB_sdssj_031339.21+042028.1/sdB_sdssj_031339.21+042028.1_lc.csv", maxgap=1000., overwrite=True, radius=0.00555556, annulus=[0.005972227,0.0103888972], verbose=3)
if __name__ == "__main__":
main()
| [
"thomas@boudreauxmail.com"
] | thomas@boudreauxmail.com |
5e7c34cb743f27828c13a76f466133a4f3de113b | 23a3f7fb0684de95b89ab4e6cdff98dad8237338 | /Plotting/python/joosep/cuts.py | 777cbe67b3b8f4e698c32e179f8f7a088833f686 | [] | no_license | camclean/tthbb13 | 1ff3c1f5e68bd3ca85cfe0efc3bf9f7c45d03200 | 7d738c44f6596e153837248354c6f514ff06d651 | refs/heads/master | 2020-12-30T23:08:39.712119 | 2015-01-14T16:11:44 | 2015-01-14T16:11:44 | 29,531,749 | 0 | 0 | null | 2015-01-20T13:45:15 | 2015-01-20T13:45:15 | null | UTF-8 | Python | false | false | 1,328 | py |
#use only nominal systematic
cut_nom = "(syst == 0)"
#from mem_categories
cut_cat1 = cut_nom + "&&" + "(( type==0 || (type==3 && flag_type3>0)) && btag_LR>=0.)"
cut_cat2 = cut_nom + "&&" + "(( type==1 || (type==3 && flag_type3<=0) ) && btag_LR>=0.)"
cut_cat3 = cut_nom + "&&" + "(type==2 && flag_type2<=999 && btag_LR>=0.)"
cut_cat6 = cut_nom + "&&" + "(type==6 && btag_LR>=0.)"
cut_cat1_H = cut_nom + "&&" + "(( type==0 || (type==3 && flag_type3>0)) && btag_LR>=0.995)"
cut_cat1_L = cut_nom + "&&" + "(( type==0 || (type==3 && flag_type3>0)) && btag_LR<0.995 && btag_LR>=0.960)"
cut_cat2_H = cut_nom + "&&" + "(( type==1 || (type==3 && flag_type3<=0) ) && btag_LR>=0.9925)"
cut_cat2_L = cut_nom + "&&" + "(( type==1 || (type==3 && flag_type3<=0) ) && btag_LR<0.9925 && btag_LR>=0.960)"
cut_cat3_H = cut_nom + "&&" + "(type==2 && flag_type2<=999 && btag_LR>=0.995)"
cut_cat3_L = cut_nom + "&&" + "(type==2 && flag_type2<=999 && btag_LR<0.995 && btag_LR>=0.970)"
cut_cat6_H = cut_nom + "&&" + "(type==6 && btag_LR>=0.925)"
cut_cat6_L = cut_nom + "&&" + "(type==6 && btag_LR<0.925 && btag_LR>=0.850)";
#jet multiplicities
cut_bb = "( nMatchSimBs>=2 && nMatchSimCs<=0 )"
cut_bj = "( nMatchSimBs==1 && nMatchSimCs<=0)"
cut_cc = "( nMatchSimBs==0 && nMatchSimCs>=1 )"
cut_jj = "( nMatchSimBs==0 && nMatchSimCs==0 )"
| [
"joosep.pata@gmail.com"
] | joosep.pata@gmail.com |
6fb9a1f7086612ce5af83a82594ae9ec89b45151 | 1e660b183cbbaaff83ba9283b319fc3dfbf54503 | /teach3QXhf/test.py | 737d229e3f2cf8292f1ca053f1f16cc30aa9a761 | [] | no_license | amtfbky/hfpy191008 | d29787ae19d772fa38f8b5ba44ea97b745529d3a | c6640ff8314cd37f617ef2abf669084ae5141d61 | refs/heads/master | 2020-08-07T15:07:08.763044 | 2020-04-04T16:19:24 | 2020-04-04T16:19:24 | 213,496,959 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 332 | py | # try:
# d = open('xxx.txt')
# print(d.readline(), end='')
# except IOError as err:
# print('File error: ' + str(err))
# finally:
# if 'data' in locals():
# d.close()
try:
with open('its.txt', "w") as data:
print("It's...", file=data)
except IOError as err:
print('File error: ' + str(err))
| [
"xjbrhnhh@163.com"
] | xjbrhnhh@163.com |
ea8e042d5253fa367f42938ab883c7307f35bcde | 9ec58308459dc95405d1a32fcf8fae7f687a207b | /test/test_k_softpasswords.py | 417a90dfb754d74aee146ad7d00137d04ef68159 | [
"MIT"
] | permissive | ivanlyon/exercises | 067aed812486dbd7a3d7de6e47a692c8b9383163 | 0792976ae2acb85187b26a52812f9ebdd119b5e8 | refs/heads/master | 2021-05-24T04:17:29.012329 | 2021-05-11T17:26:50 | 2021-05-11T17:26:50 | 65,584,450 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,720 | py | import io
import unittest
from unittest.mock import patch
from kattis import k_softpasswords
###############################################################################
class SampleInput(unittest.TestCase):
'''Problem statement sample inputs and outputs'''
def test_sample_input_1(self):
'''Run and assert problem statement sample 1 input and output.'''
inputs = '123\n123a\n'
outputs = 'No\n'
with patch('sys.stdin', io.StringIO(inputs)) as stdin,\
patch('sys.stdout', new_callable=io.StringIO) as stdout:
k_softpasswords.main()
self.assertEqual(stdout.getvalue(), outputs)
self.assertEqual(stdin.read(), '')
def test_sample_input_2(self):
'''Run and assert problem statement sample 2 input and output.'''
inputs = 'abc\nABC\n'
outputs = 'Yes\n'
with patch('sys.stdin', io.StringIO(inputs)) as stdin,\
patch('sys.stdout', new_callable=io.StringIO) as stdout:
k_softpasswords.main()
self.assertEqual(stdout.getvalue(), outputs)
self.assertEqual(stdin.read(), '')
def test_description(self):
'''Run and assert problem statement description example.'''
inputs = 'c0deninja5\nc0deninja\n'
outputs = 'Yes\n'
with patch('sys.stdin', io.StringIO(inputs)) as stdin,\
patch('sys.stdout', new_callable=io.StringIO) as stdout:
k_softpasswords.main()
self.assertEqual(stdout.getvalue(), outputs)
self.assertEqual(stdin.read(), '')
###############################################################################
if __name__ == '__main__':
unittest.main()
| [
"roblyon00@gmail.com"
] | roblyon00@gmail.com |
4368b6ecde546b076566eca501715730f0c7c583 | 056adbbdfb968486ecc330f913f0de6f51deee33 | /386-lexicographical-numbers/lexicographical-numbers.py | e6e8c56c510efd18725c4cfeff71c6fb442f63c3 | [] | no_license | privateHmmmm/leetcode | b84453a1a951cdece2dd629c127da59a4715e078 | cb303e610949e953b689fbed499f5bb0b79c4aea | refs/heads/master | 2021-05-12T06:21:07.727332 | 2018-01-12T08:54:52 | 2018-01-12T08:54:52 | 117,215,642 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 820 | py | # -*- coding:utf-8 -*-
#
# Given an integer n, return 1 - n in lexicographical order.
#
#
#
# For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9].
#
#
#
# Please optimize your algorithm to use less time and space. The input size may be as large as 5,000,000.
#
class Solution(object):
def lexicalOrder(self, n):
"""
:type n: int
:rtype: List[int]
"""
lists = []
cur = 1
while len(lists) < n:
lists.append(cur)
if cur * 10 <= n:
cur = cur * 10
elif cur % 10 != 9 and (cur + 1)<=n:
cur += 1
else:
while (cur / 10) % 10 == 9:
cur = cur/10
cur = cur/10 + 1
return lists
| [
"hyan90@ucsc.edu"
] | hyan90@ucsc.edu |
db2e44707d54608d6c674da6bc14c348c8b06ef3 | 32f5bc330388a96877d93fdd7b21599a40735400 | /Python/basicprogramming2.py | dbe900760039498ad38997904e08560c268ab4c8 | [] | no_license | alexlwn123/kattis | 670180d86f0863328a16e12ed937c2fefb3226a2 | c1163bae3fdaf95c1087b216c48e7e19059d3d38 | refs/heads/master | 2021-06-21T16:26:15.642449 | 2020-12-24T20:59:10 | 2020-12-24T20:59:10 | 152,286,208 | 1 | 1 | null | 2018-10-14T22:40:09 | 2018-10-09T16:40:48 | Java | UTF-8 | Python | false | false | 1,016 | py | def main():
n, t = map(int, input().split())
arr = list(map(int, input().split()))
if t == 1:
S = set()
for x in arr:
S.add(7777 - x)
for x in arr:
if x in S:
print('Yes')
return
print('No')
return
elif t == 2:
S = set(arr)
print('Unique' if len(set(arr)) == n else 'Contains duplicate')
return
elif t == 3:
D = {}
for x in arr:
if x not in D:
D[x] = 0
D[x] += 1
m,a = -1, -1
for x,y in D.items():
if y > n/2:
print(x)
return
print(-1)
return
elif t == 4:
arr.sort()
if n%2==1:
print(arr[n//2])
else:
print(arr[n//2-1],arr[n//2])
return
else:
arr.sort()
s,e = 0, 1
while s < n and arr[s] < 100:
s += 1
while e < n+1 and arr[-e] > 999:
e += 1
if e == 1:
print(' '.join(list(map(str, arr[s:]))))
else:
print(' '.join(list(map(str, arr[s:-e+1]))))
if __name__ == '__main__':
main()
| [
"asl0028@auburn.edu"
] | asl0028@auburn.edu |
9f62c3f35c14eb521e6e9d267c5c4394b04e713e | b5d6219ac738ed05485439540f38d63d21694c51 | /DAT/ED6_DT01/E0410.py | a66ff28875cafdda4066c4442f9637f248fd8078 | [] | no_license | otoboku/ED6-FC-Steam-CN | f87ffb2ff19f9272b986fa32a91bec360c21dffa | c40d9bc5aaea9446dda27e7b94470d91cb5558c5 | refs/heads/master | 2021-01-21T02:37:30.443986 | 2015-11-27T07:41:41 | 2015-11-27T07:41:41 | 46,975,651 | 1 | 0 | null | 2015-11-27T10:58:43 | 2015-11-27T10:58:42 | null | UTF-8 | Python | false | false | 1,934 | py | from ED6ScenarioHelper import *
def main():
CreateScenaFile(
FileName = 'E0410 ._SN',
MapName = 'Event',
Location = 'E0410.x',
MapIndex = 1,
MapDefaultBGM = "ed60010",
Flags = 0,
EntryFunctionIndex = 0xFFFF,
Reserved = 0,
IncludedScenario = [
'',
'',
'',
'',
'',
'',
'',
''
],
)
BuildStringList(
'@FileName', # 8
)
DeclEntryPoint(
Unknown_00 = 0,
Unknown_04 = 0,
Unknown_08 = 6000,
Unknown_0C = 4,
Unknown_0E = 0,
Unknown_10 = 0,
Unknown_14 = 9500,
Unknown_18 = -10000,
Unknown_1C = 0,
Unknown_20 = 0,
Unknown_24 = 0,
Unknown_28 = 2800,
Unknown_2C = 262,
Unknown_30 = 45,
Unknown_32 = 0,
Unknown_34 = 360,
Unknown_36 = 0,
Unknown_38 = 0,
Unknown_3A = 0,
InitScenaIndex = 0,
InitFunctionIndex = 0,
EntryScenaIndex = 0,
EntryFunctionIndex = 1,
)
ScpFunction(
"Function_0_AA", # 00, 0
"Function_1_AB", # 01, 1
)
def Function_0_AA(): pass
label("Function_0_AA")
Return()
# Function_0_AA end
def Function_1_AB(): pass
label("Function_1_AB")
Return()
# Function_1_AB end
SaveToFile()
Try(main)
| [
"Hiromi.Kaede@gmail.com"
] | Hiromi.Kaede@gmail.com |
662b68291d3fa8f3db88900044c8c1b5722ed9cb | 1799fe1d9dfcf5f9619a87a11f3fa6170e1864fc | /00080/test_remove_duplicates_from_sorted_array_ii.py | 1ccba713894c2cddd56392314196d615c03b711e | [] | no_license | SinCatGit/leetcode | 5e52b49324d16a96de1ba4804e3d17569377e804 | 399e40e15cd64781a3cea295bf29467d2284d2ae | refs/heads/master | 2021-07-05T18:51:46.018138 | 2020-04-25T04:06:48 | 2020-04-25T04:06:48 | 234,226,791 | 1 | 1 | null | 2021-04-20T19:17:43 | 2020-01-16T03:27:08 | Python | UTF-8 | Python | false | false | 530 | py | import unittest
from remove_duplicates_from_sorted_array_ii import Solution
class TestSolution(unittest.TestCase):
def test_Calculate_Solution(self):
sol = Solution()
nums = [1, 1, 1, 2, 2, 3]
self.assertEqual(5, sol.removeDuplicates(nums))
self.assertEqual([1, 1, 2, 2, 3], nums[:5])
nums = [0, 0, 1, 1, 1, 1, 2, 3, 3]
self.assertEqual(7, sol.removeDuplicates(nums))
self.assertEqual([0, 0, 1, 1, 2, 3, 3], nums[:7])
if __name__ == '__main__':
unittest.main()
| [
"sincat@126.com"
] | sincat@126.com |
f2a8975ec53c9e2446612231af9ced7759ec64b7 | 52855d750ccd5f2a89e960a2cd03365a3daf4959 | /ABC/ABC120_B.py | e3df3cf9bd33a81be6c089b5fa9fc4db7c854f42 | [] | no_license | takuwaaan/Atcoder_Study | b15d4f3d15d48abb06895d5938bf8ab53fb73c08 | 6fd772c09c7816d147abdc50669ec2bbc1bc4a57 | refs/heads/master | 2021-03-10T18:56:04.416805 | 2020-03-30T22:36:49 | 2020-03-30T22:36:49 | 246,477,394 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 309 | py | # 公約数列挙
# 重複する約数は1つにまとまるので注意
def make_common_divisors(x1, x2):
cd = [1]
for i in range(2, min(x1, x2) + 1):
if x1 % i == 0 and x2 % i == 0:
cd.append(i)
return cd
A,B,K = map(int,input().split())
print(make_common_divisors(A,B)[-K]) | [
"takutotakuwan@gmail.com"
] | takutotakuwan@gmail.com |
9af1f8b3aa6f082e151b27f43ec145cb45a9d62f | 163bbb4e0920dedd5941e3edfb2d8706ba75627d | /Code/CodeRecords/2500/59018/294456.py | 39ddef16398424593ba7f554559b5551ce23bbe4 | [] | 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 | 743 | py | import numpy
def pancakeSort(A):
# 思路:对每一个子列表,将最大的数排到最后面
def reverse_list(a_list, k):
# 对列表的k位置进行反转
b = a_list[0:k + 1][::-1]
return b + a_list[k + 1:]
res = []
def max_last(a_list):
if len(a_list) == 1:
return
max_idx = numpy.argmax(a_list)
if max_idx != len(a_list) - 1:
a_list = reverse_list(a_list, max_idx)
if max_idx != 0:
res.append(max_idx + 1)
a_list = reverse_list(a_list, len(a_list) - 1)
res.append(len(a_list))
max_last(a_list[0:len(a_list) - 1])
max_last(A)
return res
A=eval(input())
print(pancakeSort(A)) | [
"1069583789@qq.com"
] | 1069583789@qq.com |
71ad3c4b515673223c68c37f75e31bf80ab4864b | 6f72b3f844c0234649cef7a0ac9e80b8728b9b00 | /Python/FEWZtoROOTHist.py | d13951ee862a6709c21060d1fb5aae6f14e17fca | [] | no_license | KyeongPil-Lee/FEWZTool | c2c31fe8b21d39effadb227de5b790bd78d4fa5b | 00286b81a07af74781d9c809229f1af95a1a9ec4 | refs/heads/master | 2021-07-25T11:59:13.115019 | 2018-10-17T14:10:00 | 2018-10-17T14:10:00 | 148,044,071 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,845 | py | import sys, math
from ROOT import TFile, TH1D
from array import array
class FEWZtoROOTHist:
def __init__(self):
self.FEWZOutput = ""
self.dic_histName = []
self.outputFileName = ""
self.isCustomBin = False
self.dic_customBin = {}
def Convert(self):
# print "+" * 100
# print "Warning: currently only the histograms with equal bin width are supported"
# print "+" * 100
self.CheckOptions()
self.PrintOptions()
f_output = TFile(self.outputFileName, "RECREATE")
f_output.cd()
for FEWZHistName in self.dic_histName.keys():
(h_temp, h_temp_integErr, h_temp_PDFErr) = self.ConvertToTH1D(FEWZHistName)
h_temp.Write()
h_temp_integErr.Write()
h_temp_PDFErr.Write()
f_output.Close()
print "Done.\n"
def ConvertToTH1D(self, FEWZHistName):
print "[ConvertToTH1D] FEWZ histogram name: %s" % FEWZHistName
f = open(self.FEWZOutput, "r")
# -- find the bin values in FEWZ output
list_binValue = []
isFound = False
lines = f.readlines()
for line in lines:
# -- numbers in each bin
list_number = []
if isFound:
if "----" in line: # -- if the histogram is finished -- #
break
else:
for item in line.split():
if self.isNumber(item):
list_number += [float(item)]
if len(list_number) == 4:
print "\t(BinCenter, X-sec, Integration error, PDF error (symmetric)) = (%lf, %lf, %lf, %lf)" % (list_number[0], list_number[1], list_number[2], list_number[3])
dic_binValue = {
"binCenter": list_number[0],
"binContent": list_number[1],
"integErr": list_number[2],
"PDFErr": list_number[3],
}
list_binValue.append( dic_binValue )
if FEWZHistName in line:
isFound = True
nBin = len(list_binValue)
if nBin == 0:
print "No corresponding histogram is found (FEWZ hist name: %s)" % (FEWZHistName)
sys.exit()
if self.isCustomBin and FEWZHistName in self.dic_customBin.keys():
(h_ROOT, h_ROOT_integErr, h_ROOT_PDFErr) = self.ProduceTH1D_CustomBin(list_binValue, FEWZHistName )
return (h_ROOT, h_ROOT_integErr, h_ROOT_PDFErr)
binWidth = list_binValue[1]["binCenter"] - list_binValue[0]["binCenter"]
lowerEdge = list_binValue[0]["binCenter"] - (binWidth / 2.0)
upperEdge = list_binValue[-1]["binCenter"] + (binWidth / 2.0)
# h_ROOT = TH1D(self.dic_histName[FEWZHistName], "", nBin, array("d", list_binEdge) )
h_ROOT = TH1D(self.dic_histName[FEWZHistName], "", nBin, lowerEdge, upperEdge )
h_ROOT_integErr = TH1D(self.dic_histName[FEWZHistName]+"_integErr", "", nBin, lowerEdge, upperEdge )
h_ROOT_PDFErr = TH1D(self.dic_histName[FEWZHistName]+"_PDFErr", "", nBin, lowerEdge, upperEdge )
for i in range(0, nBin):
i_bin = i+1
binValue = list_binValue[i]
h_ROOT.SetBinContent(i_bin, binValue["binContent"])
integErr = binValue["integErr"]
PDFErr = binValue["PDFErr"]
error = math.sqrt( integErr*integErr + PDFErr*PDFErr )
h_ROOT.SetBinError(i_bin, error)
h_ROOT_integErr.SetBinContent(i_bin, integErr)
h_ROOT_integErr.SetBinError(i_bin, 0)
h_ROOT_PDFErr.SetBinContent(i_bin, PDFErr)
h_ROOT_PDFErr.SetBinError(i_bin, 0)
print " Successfully converted (ROOT histogram name: %s)" % self.dic_histName[FEWZHistName]
return (h_ROOT, h_ROOT_integErr, h_ROOT_PDFErr)
def ProduceTH1D_CustomBin(self, list_binValue, FEWZHistName ):
list_binEdge = self.dic_customBin[FEWZHistName]
nBin = len(list_binEdge) - 1
nPoint = len(list_binValue)
# print "(nBin, nPoint) = (%d, %d)" % (nBin, nPoint)
if nBin != nPoint:
print "(nBin from customized bin, nPoint) = (%d, %d): NOT SAME!" % (nBin, nPoint)
sys.exit()
h_ROOT = TH1D(self.dic_histName[FEWZHistName], "", nBin, array("d", list_binEdge) )
h_ROOT_integErr = TH1D(self.dic_histName[FEWZHistName]+"_integErr", "", nBin, array("d", list_binEdge) )
h_ROOT_PDFErr = TH1D(self.dic_histName[FEWZHistName]+"_PDFErr", "", nBin, array("d", list_binEdge) )
for i in range(0, nBin):
i_bin = i+1
binValue = list_binValue[i]
binCenter = binValue["binCenter"]
binCenter_fromCustomBin = ( list_binEdge[i] + list_binEdge[i+1] ) / 2.0
if binCenter != binCenter_fromCustomBin:
print "[%02d bin]" % i_bin
print " binCenter from FEWZ output: %lf" % binCenter
print " binCenter from customized bin: %lf (%lf - %lf)" % (binCenter_fromCustomBin, list_binEdge[i], list_binEdge[i+1] )
sys.exit()
# print "[%02d bin]" % i_bin
# print " bin content = %lf\n" % binValue["binContent"]
# print " PDFErr = %lf\n" % binValue["PDFErr"]
h_ROOT.SetBinContent(i_bin, binValue["binContent"])
integErr = binValue["integErr"]
PDFErr = binValue["PDFErr"]
error = math.sqrt( integErr*integErr + PDFErr*PDFErr )
h_ROOT.SetBinError(i_bin, error)
h_ROOT_integErr.SetBinContent(i_bin, integErr)
h_ROOT_integErr.SetBinError(i_bin, 0)
h_ROOT_PDFErr.SetBinContent(i_bin, PDFErr)
h_ROOT_PDFErr.SetBinError(i_bin, 0)
print " Successfully converted with customized bin (ROOT histogram name: %s)" % self.dic_histName[FEWZHistName]
return (h_ROOT, h_ROOT_integErr, h_ROOT_PDFErr)
def CheckOptions(self):
if self.FEWZOutput == "" or \
len(self.dic_histName) == 0 or \
self.outputFileName == "":
print "Mandatory options are missing ... please check"
self.PrintOptions()
def PrintOptions(self):
print "FEWZ output to be read: ", self.FEWZOutput
print "list of histograms that will be converted to ROOT histogram (TH1D): "
for FEWZHistName in self.dic_histName.keys():
print " %s (FEWZ) -> %s (ROOT)" % (FEWZHistName, self.dic_histName[FEWZHistName])
print "output file name:", self.outputFileName
def isNumber(self, s):
try:
float(s)
return True
except ValueError:
return False | [
"kplee@cern.ch"
] | kplee@cern.ch |
dde07ffee1df8cbe6116788ca831a585bb2932a4 | 2dc17d12ff6ea9794177c81aa4f385e4e09a4aa5 | /archive/836. Rectangle Overlap.py | f5674230e4f9420e4cdd19b17f8e3e664363143f | [] | no_license | doraemon1293/Leetcode | 924b19f840085a80a9e8c0092d340b69aba7a764 | 48ba21799f63225c104f649c3871444a29ab978a | refs/heads/master | 2022-10-01T16:20:07.588092 | 2022-09-08T02:44:56 | 2022-09-08T02:44:56 | 122,086,222 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 338 | py | class Solution:
def isRectangleOverlap(self, rec1, rec2):
"""
:type rec1: List[int]
:type rec2: List[int]
:rtype: bool
"""
x_overlap=max(0,min(rec2[2],rec1[2])-max(rec2[0],rec1[0]))
y_overlap=max(0,min(rec2[3],rec1[3])-max(rec2[1],rec1[1]))
return x_overlap*y_overlap>0
| [
"yanhuang1293@gmail.com"
] | yanhuang1293@gmail.com |
a3f7e498f73946e5cfd4ab5bc134e06a2a7b0a9d | 8d580456e4e0547cf7348f7ccfe39b0e13e1ea09 | /agency/views.py | 73336aa99db068ba73b2c40969d7c7dae67c835b | [] | no_license | kmvit/Estate | 440c7c878747406065480713abc282ba2183d9ea | c11ba59f3bc7e23a8c43210634578223ffba3728 | refs/heads/master | 2016-09-06T07:07:37.756970 | 2014-12-06T12:29:49 | 2014-12-06T12:29:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,564 | py | from django.shortcuts import render
from agency.models import Category, Estate, Page
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.views.generic import ListView, DetailView
from datetime import datetime
def index(request):
category_list = Category.objects.filter(parent_category__isnull=True)
estates = Estate.objects.all()
context_dict = {'categories': category_list, 'estates': estates}
visits = request.session.get('visits')
if not visits:
visits = 0
reset_last_visit_time = False
last_visit = request.session.get('last_visit')
if last_visit:
last_visit_time = datetime.strptime(last_visit[:-7], "%Y-%m-%d %H:%M:%S")
if (datetime.now() - last_visit_time).seconds > 0:
# ...reassign the value of the cookie to +1 of what it was before...
visits = visits + 1
# ...and update the last visit cookie, too.
reset_last_visit_time = True
else:
# Cookie last_visit doesn't exist, so create it to the current date/time.
reset_last_visit_time = True
context_dict = {'estates':estates , 'visits':visits, 'last_visit': last_visit}
request.session['visits'] = visits
if reset_last_visit_time:
request.session['last_visit'] = str(datetime.now())
response = render(request, 'agency/index.html', context_dict)
return response
def category(request, category_name_slug):
category = Category.objects.get(slug=category_name_slug)
estates = Estate.objects.filter(category=category)
context_dict = {'estates': estates, 'category': category}
return render(request, 'agency/category.html', context_dict)
def search(request):
errors = [ ]
if 'price' and 'code' and 'room' in request.GET:
q = request.GET['price']
w = request.GET['code']
r = request.GET['room']
if not q and not w and not r:
errors.append('Enter a search term.')
else:
newestate = Estate.objects.filter(price__icontains=q, code__icontains=w, room__icontains=r)
return render_to_response('agency/search_results.html',
{'newestate': newestate, 'q': q, 'w':w, 'r':r,})
return render_to_response('agency/search_form.html', {'errors': errors})
class EstateDetailView(DetailView):
model = Estate
def count(self, **kwargs):
visits =self.request.session.get('visits')
if not visits:
visits = 0
reset_last_visit_time = False
last_visit = self.request.session.get('last_visit')
if last_visit:
last_visit_time = datetime.strptime(last_visit[:-7], "%Y-%m-%d %H:%M:%S")
if (datetime.now() - last_visit_time).days > 0:
# ...reassign the value of the cookie to +1 of what it was before...
visits = visit
s + 1
# ...and update the last visit cookie, too.
reset_last_visit_time = True
else:
# Cookie last_visit doesn't exist, so create it to the current date/time.
reset_last_visit_time = True
context_dict = {}
context_dict['last_visit'] = last_visit
context_dict['visits'] = visits
self.request.session['visits'] = visits
if reset_last_visit_time:
self.request.session['last_visit'] = str(datetime.now())
response = render(request, 'agency/estate_detail.html', context_dict)
return response
class PageDetailView(DetailView):
model = Page
| [
"kmv-it@yandex.ru"
] | kmv-it@yandex.ru |
4d6b302ee199dc9c1d861cffb64197f46bab3dcd | 3b22b066db9acb897439397508236c8326f0f049 | /Assignment Backtracking and searching and sorting applications/sorting the skills.py | 1279a5976c5e849fd3cb82a3cb2d0b0ce4596c25 | [] | no_license | Adityaraj1711/Eminance-coding-ninjas | e633245f3d4638a042511bea9acda22dbc22d9ed | 8b7393fe8db10dd047d8841b15f332899e52daf3 | refs/heads/master | 2020-05-16T14:00:43.044296 | 2020-04-16T01:48:53 | 2020-04-16T01:48:53 | 183,090,072 | 14 | 17 | null | 2019-07-02T06:08:37 | 2019-04-23T20:21:54 | C++ | UTF-8 | Python | false | false | 1,379 | py | '''
Sorting the Skills
Send Feedback
There is a company named James Peterson & Co. The company has ‘n’ employees. The employees have skills from 0 to n-1. All the employees have distinct skills. The manager of James Peterson & Co. wants to sort the employees on the basis of their skills in ascending order. He is only allowed to swap two employees which are adjacent to each other. He is given the skills of employees in an array of size ‘n’. He can swap the skills as long as the absolute difference between their skills is 1. You need to help the manager out and tell whether it is possible to sort the skills of employees or not.
Input Format:
First Line will have an integer ‘t’ denoting the no. of test cases.
First line of each test case contains an integer ‘n’ denoting the no. of employees in the company.
Second line of each test case contains ‘n’ distinct integers in the range [0, n-1].
Output Format:
For each test case, print “Yes” if it is possible to sort the skills otherwise “No”.
Constraints:
1 <= t <= 10
1 <= n <= 10^5
Sample Input:
2
4
1 0 3 2
3
2 1 0
'''
t = int(input())
while t:
t-=1
flag = True
l = int(input())
ar = list(map(int,input().split()))
for idx,a in enumerate(ar):
if a<=(idx+1) and a>=(idx-1):
pass
else:
flag = False
break
if flag:
print("Yes")
else:
print("No")
| [
"adityamailbox0@gmail.com"
] | adityamailbox0@gmail.com |
ae7f7b5ce33219b18c4fd9886bf527c3652c59e0 | 55ceefc747e19cdf853e329dba06723a44a42623 | /_CodeTopics/LeetCode/401-600/000405/000405_handmovedoghead.py | 5bb76ba784fe94c205f3f073f550ac4621cbe6de | [] | 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 | 530 | py | class Solution(object):
def toHex(self, num):
"""
:type num: int
:rtype: str
"""
# 手动狗头题
return hex(num)[2:] if num >= 0 else hex(0xffffffff + num + 1)[2:]
"""
https://leetcode-cn.com/submissions/detail/225055334/
100 / 100 个通过测试用例
状态:通过
执行用时: 12 ms
内存消耗: 12.8 MB
执行用时:12 ms, 在所有 Python 提交中击败了92.19%的用户
内存消耗:12.8 MB, 在所有 Python 提交中击败了95.31%的用户
"""
| [
"noreply@github.com"
] | BIAOXYZ.noreply@github.com |
b8007a0e23814e7c49fd8ba2c5f5a98d25383670 | 2451ca9bc9ae43bd3b070fa362aa13646ff06f13 | /02_Python_Cookbook/object_oriented_programming/magic_method/_note___iter____next__.py | 681ac4cac27f7309b8f1026f3cc6f418dbea4514 | [] | no_license | MacHu-GWU/six-demon-bag | 5cd1cf5d56d4c42cff013ab80dd4fc838add7195 | 10d772d6b876086f64db39f6ddbc07e08e35a122 | refs/heads/master | 2020-05-17T17:26:15.961833 | 2015-09-15T21:50:20 | 2015-09-15T21:50:20 | 26,669,763 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,461 | py | ##################################
#encoding=utf8 #
#version =py27, py33 #
#author =sanhe #
#date =2014-10-29 #
# #
# (\ (\ #
# ( -.-)o I am a Rabbit! #
# o_(")(") #
# #
##################################
"""
self.__iter__ 定义了 for i in self: 的行为
self.__next__ 定义了 next(self) 的行为
"""
from __future__ import print_function
def example1():
"""对象本身的某一个属性是list, dict, set等默认可循环类。我们希望在
for i in class 的时候是对这个属性作为循环。
"""
class DictContainer(object):
def __init__(self):
self.data = dict()
def __str__(self):
return str(self.data)
def __iter__(self):
return iter(self.data) ## <== 直接对这个属性进行循环
dc = DictContainer()
dc.data = {1:"a", 2:"b"}
print(dc)
for i in dc: # 可以对其循环
print(i)
# example1()
def example2():
"""在部分属性之间按照顺序进行循环
"""
class Cat(object):
def __init__(self, name):
self.name = name
self.head = "cat_head"
self.body = "cat_body"
self.feet = "cat_feet"
self.tail = "cat_tail"
def __str__(self):
return ("%s, %s, %s, %s, %s" % (self.name, self.head, self.body, self.feet, self.tail))
def __iter__(self):
iterable_attrs = [self.head, self.body, self.feet, self.tail] ## <== 定义可被循环到的属性
return iter(iterable_attrs)
cat = Cat("tom")
print(cat)
for i in cat:
print(i)
# example2()
def example3():
"""
用generator expression括号,和iter实现:
对待字典中的key,有选择的迭代
"""
class Myclass():
def __init__(self):
self.data = dict()
def __iter__(self):
return (key for key in self.data if key != "special")
mc = Myclass()
mc.data = {"a": 3, "b":1, "c":2, "special":0}
for key in mc:
print(key)
# example3()
def example4():
"""
stackoverflow上面看来的一个recipe
"""
class Myclass():
def __init__(self):
self.data = dict()
self.current = 1
def __iter__(self):
return self
def next(self):
key = [k for k, v in self.data.items() if v == self.current]
if not key:
raise StopIteration
self.current += 1
return next(iter(key))
mc = Myclass()
mc.data = {"a": 3, "b":1, "c":2, "d":4, "e": 2}
for key in mc:
print(key)
# example4()
def example5():
"""python3 only
"""
class Fib(object):
def __init__(self, max):
self.max = max
def __iter__(self):
self.a = 0
self.b = 1
return self
def __next__(self):
fib = self.a
if fib > self.max:
raise StopIteration
self.a, self.b = self.b, self.a + self.b
return fib
fib = Fib(10)
for i in fib:
print(i)
example5() | [
"husanhe@gmail.com"
] | husanhe@gmail.com |
e7094970621c61fe26fadced45b5b35b0d857f7f | f7574ee7a679261e758ba461cb5a5a364fdb0ed1 | /dp/EditDistance.py | 95b15ffdba551771551f99fa8944cf3d2c73794f | [] | no_license | janewjy/Leetcode | 807050548c0f45704f2f0f821a7fef40ffbda0ed | b4dccd3d1c59aa1e92f10ed5c4f7a3e1d08897d8 | refs/heads/master | 2021-01-10T19:20:22.858158 | 2016-02-26T16:03:19 | 2016-02-26T16:03:19 | 40,615,255 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,256 | py | # A Naive recursive Python program to fin minimum number
# operations to convert str1 to str2
def editDistance(str1, str2, m , n):
print str1[:m],str2[:n]
# If first string is empty, the only option is to
# insert all characters of second string into first
if m==0:
return n
# If second string is empty, the only option is to
# remove all characters of first string
if n==0:
return m
# If last characters of two strings are same, nothing
# much to do. Ignore last characters and get count for
# remaining strings.
if str1[m-1]==str2[n-1]:
return editDistance(str1,str2,m-1,n-1)
# If last characters are not same, consider all three
# operations on last character of first string, recursively
# compute minimum cost for all three operations and take
# minimum of three values.
return 1 + min(editDistance(str1, str2, m, n-1), # Insert
editDistance(str1, str2, m-1, n), # Remove
editDistance(str1, str2, m-1, n-1) # Replace
)
# Driver program to test the above function
str1 = "sund"
str2 = "sarud"
print editDistance(str1, str2, len(str1), len(str2))
# This code is contributed by Bhavya Jain | [
"janewjy87@gmail.com"
] | janewjy87@gmail.com |
c7521d849016609c0d1118eb8305c9125405559a | 4bd207d288c95b9f20785bb841224b914f05c280 | /code-master/lib/bitbots/modules/basic/network/__init__.py | 67628be7d7f0dc366d60988e7060d08492fbe7b0 | [] | no_license | hendrikvgl/RoboCup-Spielererkennung | 435e17ee540c4b4c839e26d54db2528a60e6a110 | c41269a960f4b5ea0814a49f5a20ae17eb0a9d71 | refs/heads/master | 2021-01-10T10:39:00.586760 | 2015-10-21T12:42:27 | 2015-10-21T12:42:27 | 44,675,342 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 288 | py | def get_network_modules():
return ["bitbots.modules.basic.network.game_controller_module",
"bitbots.modules.basic.network.mite_com_module",
"bitbots.modules.basic.network.network_controller_module",
"bitbots.modules.basic.network.team_data_module"] | [
"hendrik.vgl@gmail.com"
] | hendrik.vgl@gmail.com |
3e863f51924dbb1a5c41b84ea6e66b2fa08e7956 | 7fbb4f70493a27d2b0fe2c107a1055e493bf7188 | /taobao-tianmao/Qimen/top/api/rest/OrderCancelRequest.py | 27e244bfd69bef73943bb50f656022a5b76abdbd | [
"Apache-2.0"
] | permissive | ScottLeeF/python-example | da9d78a85cce914153f1c5ad662d28cddde0fc0f | 0b230ba80fe5020d70329a9d73e058013f0ca111 | refs/heads/master | 2022-12-03T00:24:47.035304 | 2020-04-21T09:51:12 | 2020-04-21T09:51:12 | 242,459,649 | 0 | 0 | Apache-2.0 | 2022-11-22T05:29:21 | 2020-02-23T05:03:19 | Python | UTF-8 | Python | false | false | 552 | py | '''
Created by auto_sdk on 2018.07.26
'''
from top.api.base import RestApi
class OrderCancelRequest(RestApi):
def __init__(self, domain='gw.api.taobao.com', port=80):
RestApi.__init__(self, domain, port)
self.cancelReason = None
self.extendProps = None
self.orderCode = None
self.orderId = None
self.orderType = None
self.ownerCode = None
self.remark = None
self.warehouseCode = None
def getapiname(self):
return 'taobao.qimen.order.cancel'
| [
"fei.li@tuanche.com"
] | fei.li@tuanche.com |
065a6539fc3148973e7d5fa88e5da10cf9e139a9 | 53fab060fa262e5d5026e0807d93c75fb81e67b9 | /backup/user_337/ch80_2020_04_12_19_17_53_955986.py | a9498a022d72664c4c3a450be484537b0fe83825 | [] | 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 | 240 | py | def interseccao_chaves(dic1, dic2):
lista = []
for i in dic1:
if i in dic2:
lista.append(i)
for i in dic2:
if not i in lista:
if i in dic1:
lista.append(i)
return lista | [
"you@example.com"
] | you@example.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.