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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1a6c349482a32dd6f302abf1c4292833b754d0c1 | f151d2e8ce0f09069f76a2719fcc4bc106f90e15 | /config.py | afe05ab4494fe3e5491ab130e7960f456b01545f | [] | no_license | Ali-Khakpash/flask-admin | b8d71e85edb644f8f3754ea8bdbcc8f79e0425e3 | f2beab858368dabe5c9f48b2e41ff8ddbca0fdae | refs/heads/master | 2020-12-02T04:10:38.978578 | 2020-06-05T09:47:17 | 2020-06-05T09:47:17 | 230,882,040 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 789 | py | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
#SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'
SECRET_KEY = os.urandom(24)
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
FLASKY_MAIL_SUBJECT_PREFIX = '[Flasky]'
FLASKY_MAIL_SENDER = 'Flasky Admin <flasky@example.com>'
FLASKY_ADMIN = os.environ.get('FLASKY_ADMIN')
@staticmethod
def init_app(app):
pass
class DevelopmentConfig(Config):
DEBUG = True
class TestingConfig(Config):
TESTING = True
SQLALCHEMY_DATABASE_URI = ''
class ProductionConfig(Config):
SQLALCHEMY_DATABASE_URI = ''
config = {
'development': DevelopmentConfig,
'testing': TestingConfig,
'production': ProductionConfig,
'default': DevelopmentConfig
} | [
"ali.khakpash@gmail.com"
] | ali.khakpash@gmail.com |
c377866aad88f931fedcf91312e31f92701861f1 | 44e1f22280921216c8ef9acabec761cbe450030a | /src/models/train_funcs.py | 4e4419dcd6969838bb147df62c7aa30da36305f0 | [] | no_license | EstherWMaina/kenya-crop-mask | 69e727874ad2305f6a1fc159061f85f632b4f795 | b51c21e73c296b70ffa79ebd57162d23553e99a1 | refs/heads/master | 2023-06-15T09:50:48.156473 | 2021-06-01T19:04:15 | 2021-06-01T19:04:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 557 | py | from argparse import Namespace
import pytorch_lightning as pl
from pytorch_lightning.callbacks import EarlyStopping
def train_model(model: pl.LightningModule, hparams: Namespace) -> pl.LightningModule:
early_stop_callback = EarlyStopping(
monitor="val_loss", min_delta=0.00, patience=hparams.patience, verbose=True, mode="min",
)
trainer = pl.Trainer(
default_save_path=hparams.data_folder,
max_epochs=hparams.max_epochs,
early_stop_callback=early_stop_callback,
)
trainer.fit(model)
return model
| [
"gabriel.tseng@mail.mcgill.ca"
] | gabriel.tseng@mail.mcgill.ca |
f09b8f651cefa953c0742615d4f262d8e9c98712 | e4ab984c6d27167849f6c6e2d8ced3c0ee167c7c | /Edabit/Say_Hello_to_Guests.py | f28b89fb446b0024e359066dc21b26dc4ffc8239 | [] | no_license | ravalrupalj/BrainTeasers | b3bc2a528edf05ef20291367f538cf214c832bf9 | c3a48453dda29fe016ff89f21f8ee8d0970a3cf3 | refs/heads/master | 2023-02-10T02:09:59.443901 | 2021-01-06T02:03:34 | 2021-01-06T02:03:34 | 255,720,400 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 684 | py | #Say Hello to Guests
#In this exercise you will have to:
#Take a list of names.
#Add "Hello" to every name.
#Make one big string with all greetings.
#The solution should be one string with a comma in between every "Hello (Name)".
#Each greeting has to be separated with a comma and a space.
#If you're given an empty list [], return an empty string "".
def greet_people(names):
r=[]
for i in names:
t=('Hello '+i)
r.append(t)
return ', '.join(r)
print(greet_people(["Joe"]))
#➞ "Hello Joe"
print(greet_people(["Angela", "Joe"]) )
#➞ "Hello Angela, Hello Joe"
print(greet_people(["Frank", "Angela", "Joe"]) )
#➞ "Hello Frank, Hello Angela, Hello Joe"
| [
"63676082+ravalrupalj@users.noreply.github.com"
] | 63676082+ravalrupalj@users.noreply.github.com |
db3ccdd045b929d6f0651b9eddf8263751f07e22 | 2b8f1b067a6602a6520e9846a2df8b83a359623a | /BOJ/단계별로 풀어보기/18_ 그리디 알고리즘/11047.py | 261066b1e4355ae315db35c339efe4c72692125d | [] | no_license | ymink716/PS | 3f9df821a1d4db110cd9d56b09b4c1d756951dd8 | e997ecf5a3bec1d840486b8d90b934ae1cbafe94 | refs/heads/master | 2023-08-18T18:21:45.416083 | 2023-08-16T07:26:18 | 2023-08-16T07:26:18 | 218,685,650 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 207 | py | n, k = map(int, input().split())
coins = [int(input()) for _ in range(n)]
count = 0
for i in range(n-1, -1, -1):
if k >= coins[i]:
count += (k // coins[i])
k = k % coins[i]
print(count) | [
"ymink716@gmail.com"
] | ymink716@gmail.com |
f6c6735da757355ba46dec2b33f48b3df3694037 | 45129489b5556a70d3caa6020b0f035de8019a94 | /probn/01.04/27.py | 2b62b314c4fb4d838ef574020e8bdfce27aa20b8 | [] | no_license | trofik00777/EgeInformatics | 83d853b1e8fd1d1a11a9d1f06d809f31e6f986c0 | 60f2587a08d49ff696f50b68fe790e213c710b10 | refs/heads/main | 2023-06-06T13:27:34.627915 | 2021-06-23T20:15:28 | 2021-06-23T20:15:28 | 362,217,172 | 3 | 1 | null | null | null | null | UTF-8 | Python | false | false | 706 | py | n = int(input())
h1, h2, h_a = 0, 0, 0
is_ch_nech = 0
diff = []
for _ in range(n):
a, b, c = sorted(map(int, input().split()))
h1 += a
h2 += b
h_a += c
if (a + b) % 2:
is_ch_nech += 1
ac, bc = c - a, c - b
k = []
if ac % 2:
k.append(ac)
if bc % 2:
k.append(bc)
if k:
diff.append(min(k))
diff.sort()
if h1 % 2 == 0 and h2 % 2 == 0:
print("cool")
print(h_a)
else:
if (h1 + h2) % 2 == 0:
if is_ch_nech > 1:
print("chnch")
print(h_a)
else:
print("not chnch")
print(h_a - diff[0] - diff[1])
else:
print("bad")
| [
"noreply@github.com"
] | trofik00777.noreply@github.com |
f496c9ca6c2d179194b41af953114afe4dbcd9df | 32aa7d3f9a90bafaf0ff89d01fe71e970cbe64a6 | /pytext/torchscript/tensorizer/roberta.py | 7a72df0d120cb39d6dced64be2d96f6fddf2a497 | [
"BSD-3-Clause"
] | permissive | HarounH/pytext | 67135563939723c47076de3c4d213549ba6246b6 | 6dd8fccac0b366782b5319af6236d2d337a25b42 | refs/heads/master | 2020-09-12T21:34:35.749162 | 2019-11-18T23:07:53 | 2019-11-18T23:12:13 | 222,563,726 | 0 | 0 | NOASSERTION | 2019-11-18T23:17:42 | 2019-11-18T23:17:41 | null | UTF-8 | Python | false | false | 3,733 | py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from typing import List, Optional, Tuple
import torch
from pytext.torchscript.utils import pad_2d, pad_2d_mask
from .bert import ScriptBERTTensorizerBase
class ScriptRoBERTaTensorizer(ScriptBERTTensorizerBase):
@torch.jit.script_method
def _lookup_tokens(self, tokens: List[Tuple[str, int, int]]) -> List[int]:
return self.vocab_lookup(
tokens,
bos_idx=self.vocab.bos_idx,
eos_idx=self.vocab.eos_idx,
use_eos_token_for_bos=False,
max_seq_len=self.max_seq_len,
)[0]
class ScriptRoBERTaTensorizerWithIndices(ScriptBERTTensorizerBase):
@torch.jit.script_method
def _lookup_tokens(
self, tokens: List[Tuple[str, int, int]]
) -> Tuple[List[int], List[int], List[int]]:
return self.vocab_lookup(
tokens,
bos_idx=self.vocab.bos_idx,
eos_idx=self.vocab.eos_idx,
use_eos_token_for_bos=False,
max_seq_len=self.max_seq_len,
)
@torch.jit.script_method
def numberize(
self, text_row: Optional[List[str]], token_row: Optional[List[List[str]]]
) -> Tuple[List[int], int, List[int], List[int], List[int]]:
token_ids: List[int] = []
seq_len: int = 0
start_indices: List[int] = []
end_indices: List[int] = []
positions: List[int] = []
per_sentence_tokens: List[List[Tuple[str, int, int]]] = self.tokenize(
text_row, token_row
)
for idx, per_sentence_token in enumerate(per_sentence_tokens):
lookup_ids, start_ids, end_ids = self._lookup_tokens(per_sentence_token)
lookup_ids = self._wrap_numberized_tokens(lookup_ids, idx)
token_ids.extend(lookup_ids)
start_indices.extend(start_ids)
end_indices.extend(end_ids)
seq_len = len(token_ids)
positions = [i for i in range(seq_len)]
return token_ids, seq_len, start_indices, end_indices, positions
@torch.jit.script_method
def tensorize(
self,
texts: Optional[List[List[str]]] = None,
tokens: Optional[List[List[List[str]]]] = None,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
tokens_2d: List[List[int]] = []
seq_len_2d: List[int] = []
start_indices_2d: List[List[int]] = []
end_indices_2d: List[List[int]] = []
positions_2d: List[List[int]] = []
for idx in range(self.batch_size(texts, tokens)):
numberized: Tuple[
List[int], int, List[int], List[int], List[int]
] = self.numberize(
self.get_texts_by_index(texts, idx),
self.get_tokens_by_index(tokens, idx),
)
tokens_2d.append(numberized[0])
seq_len_2d.append(numberized[1])
start_indices_2d.append(numberized[2])
end_indices_2d.append(numberized[3])
positions_2d.append(numberized[4])
tokens, pad_mask = pad_2d_mask(tokens_2d, pad_value=self.vocab.pad_idx)
start_indices = torch.tensor(
pad_2d(start_indices_2d, seq_lens=seq_len_2d, pad_idx=self.vocab.pad_idx),
dtype=torch.long,
)
end_indices = torch.tensor(
pad_2d(end_indices_2d, seq_lens=seq_len_2d, pad_idx=self.vocab.pad_idx),
dtype=torch.long,
)
positions = torch.tensor(
pad_2d(positions_2d, seq_lens=seq_len_2d, pad_idx=self.vocab.pad_idx),
dtype=torch.long,
)
return tokens, pad_mask, start_indices, end_indices, positions
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
e7c56cdf9130241750530b46da969e1b3999db5a | 01b7728c138818a43a967b1129c7cf328d1620c2 | /built-in/tickets/create_ticket.py | 2136677d04b3cce6bf50f1f074970c639d8e3b94 | [] | no_license | lliurex/n4d | 62d303947bc4ae0ff20cb1f2217e532ef17091a5 | 09e5f15acbb1ce584a074dc7540959258c165f66 | refs/heads/master | 2023-08-31T23:34:04.859965 | 2023-04-14T11:17:12 | 2023-04-14T11:17:12 | 133,468,639 | 0 | 1 | null | 2023-02-16T08:57:32 | 2018-05-15T06:22:13 | Python | UTF-8 | Python | false | false | 344 | py | import n4d.responses
def create_ticket(self,user):
ret=self.tickets_manager.create_ticket(user)
if ret:
return n4d.responses.build_successful_call_response(True,"Ticket created for user %s"%user)
else:
CREATE_TICKET_ERROR=-5
return n4d.responses.build_failed_call_response(CREATE_TICKET_ERROR,"Failed to create ticket")
#def test
| [
"hectorgh@gmail.com"
] | hectorgh@gmail.com |
c2a1ec30d6c85e49248724ac2e7f709f702411e3 | 9df267613fe858c7f8dac85255fdf1f592c8bdf9 | /image/image-open.py | 97f958ba4fadfede8820597af1b5e029d31ce44f | [
"MIT"
] | permissive | martinmcbride/python-imaging-book-examples | 6ad44067dd20919ff6e8af0f482bc245a8338756 | 37e4ccf9b7b2fc3ff75b1fdb9f772de452a843b2 | refs/heads/main | 2023-07-17T12:01:19.851394 | 2021-08-22T20:49:46 | 2021-08-22T20:49:46 | 365,778,031 | 2 | 2 | null | null | null | null | UTF-8 | Python | false | false | 474 | py | # Author: Martin McBride
# Created: 2021-07-17
# Copyright (C) 2021, Martin McBride
# License: MIT
# Open an image
from PIL import Image
# Open an image of any supported format
image = Image.open("boat-small.jpg")
image.close()
# Only open PNG or JPEG images
image = Image.open("boat-small.jpg", formats=['PNG', 'JPEG'])
image.close()
# Only open PNG images. This will fail, because it is a JPEG file
image = Image.open("boat-small.jpg", formats=['PNG'])
image.close() | [
"mcbride.martin@gmail.com"
] | mcbride.martin@gmail.com |
b40b07274f7adcd1bfcfcbb81396f652db3b129c | 4d6975caece0acdc793a41e8bc6d700d8c2fec9a | /leetcode/1501.circle-and-rectangle-overlapping/1501.circle-and-rectangle-overlapping.py | fa66d6e63ecac5efece6056e67d08b33212fa829 | [] | no_license | guiconti/workout | 36a3923f2381d6e7023e127100409b3a2e7e4ccb | 5162d14cd64b720351eb30161283e8727cfcf376 | refs/heads/master | 2021-08-03T10:32:02.108714 | 2021-07-26T04:38:14 | 2021-07-26T04:38:14 | 221,025,113 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 139 | py | class Solution:
def checkOverlap(self, radius: int, x_center: int, y_center: int, x1: int, y1: int, x2: int, y2: int) -> bool:
| [
"guibasconti@gmail.com"
] | guibasconti@gmail.com |
219dea222cde58156d3ae38cb078aea71abb1c9c | 90c6262664d013d47e9a3a9194aa7a366d1cabc4 | /tests/contracts/KT1G72fc8TP3C7WgnaMB8uG3ZbDgfkJNBWEr/test_michelson_coding_KT1G72.py | 981ba4b2284f21132fc049c53a0e55ab6f03c747 | [
"MIT"
] | permissive | tqtezos/pytezos | 3942fdab7aa7851e9ea81350fa360180229ec082 | a4ac0b022d35d4c9f3062609d8ce09d584b5faa8 | refs/heads/master | 2021-07-10T12:24:24.069256 | 2020-04-04T12:46:24 | 2020-04-04T12:46:24 | 227,664,211 | 1 | 0 | MIT | 2020-12-30T16:44:56 | 2019-12-12T17:47:53 | Python | UTF-8 | Python | false | false | 5,342 | py | from unittest import TestCase
from tests import get_data
from pytezos.michelson.micheline import michelson_to_micheline
from pytezos.michelson.formatter import micheline_to_michelson
class MichelsonCodingTestKT1G72(TestCase):
def setUp(self):
self.maxDiff = None
def test_michelson_parse_code_KT1G72(self):
expected = get_data(
path='contracts/KT1G72fc8TP3C7WgnaMB8uG3ZbDgfkJNBWEr/code_KT1G72.json')
actual = michelson_to_micheline(get_data(
path='contracts/KT1G72fc8TP3C7WgnaMB8uG3ZbDgfkJNBWEr/code_KT1G72.tz'))
self.assertEqual(expected, actual)
def test_michelson_format_code_KT1G72(self):
expected = get_data(
path='contracts/KT1G72fc8TP3C7WgnaMB8uG3ZbDgfkJNBWEr/code_KT1G72.tz')
actual = micheline_to_michelson(get_data(
path='contracts/KT1G72fc8TP3C7WgnaMB8uG3ZbDgfkJNBWEr/code_KT1G72.json'),
inline=True)
self.assertEqual(expected, actual)
def test_michelson_inverse_code_KT1G72(self):
expected = get_data(
path='contracts/KT1G72fc8TP3C7WgnaMB8uG3ZbDgfkJNBWEr/code_KT1G72.json')
actual = michelson_to_micheline(micheline_to_michelson(expected))
self.assertEqual(expected, actual)
def test_michelson_parse_storage_KT1G72(self):
expected = get_data(
path='contracts/KT1G72fc8TP3C7WgnaMB8uG3ZbDgfkJNBWEr/storage_KT1G72.json')
actual = michelson_to_micheline(get_data(
path='contracts/KT1G72fc8TP3C7WgnaMB8uG3ZbDgfkJNBWEr/storage_KT1G72.tz'))
self.assertEqual(expected, actual)
def test_michelson_format_storage_KT1G72(self):
expected = get_data(
path='contracts/KT1G72fc8TP3C7WgnaMB8uG3ZbDgfkJNBWEr/storage_KT1G72.tz')
actual = micheline_to_michelson(get_data(
path='contracts/KT1G72fc8TP3C7WgnaMB8uG3ZbDgfkJNBWEr/storage_KT1G72.json'),
inline=True)
self.assertEqual(expected, actual)
def test_michelson_inverse_storage_KT1G72(self):
expected = get_data(
path='contracts/KT1G72fc8TP3C7WgnaMB8uG3ZbDgfkJNBWEr/storage_KT1G72.json')
actual = michelson_to_micheline(micheline_to_michelson(expected))
self.assertEqual(expected, actual)
def test_michelson_parse_parameter_onmWHA(self):
expected = get_data(
path='contracts/KT1G72fc8TP3C7WgnaMB8uG3ZbDgfkJNBWEr/parameter_onmWHA.json')
actual = michelson_to_micheline(get_data(
path='contracts/KT1G72fc8TP3C7WgnaMB8uG3ZbDgfkJNBWEr/parameter_onmWHA.tz'))
self.assertEqual(expected, actual)
def test_michelson_format_parameter_onmWHA(self):
expected = get_data(
path='contracts/KT1G72fc8TP3C7WgnaMB8uG3ZbDgfkJNBWEr/parameter_onmWHA.tz')
actual = micheline_to_michelson(get_data(
path='contracts/KT1G72fc8TP3C7WgnaMB8uG3ZbDgfkJNBWEr/parameter_onmWHA.json'),
inline=True)
self.assertEqual(expected, actual)
def test_michelson_inverse_parameter_onmWHA(self):
expected = get_data(
path='contracts/KT1G72fc8TP3C7WgnaMB8uG3ZbDgfkJNBWEr/parameter_onmWHA.json')
actual = michelson_to_micheline(micheline_to_michelson(expected))
self.assertEqual(expected, actual)
def test_michelson_parse_parameter_onnQTu(self):
expected = get_data(
path='contracts/KT1G72fc8TP3C7WgnaMB8uG3ZbDgfkJNBWEr/parameter_onnQTu.json')
actual = michelson_to_micheline(get_data(
path='contracts/KT1G72fc8TP3C7WgnaMB8uG3ZbDgfkJNBWEr/parameter_onnQTu.tz'))
self.assertEqual(expected, actual)
def test_michelson_format_parameter_onnQTu(self):
expected = get_data(
path='contracts/KT1G72fc8TP3C7WgnaMB8uG3ZbDgfkJNBWEr/parameter_onnQTu.tz')
actual = micheline_to_michelson(get_data(
path='contracts/KT1G72fc8TP3C7WgnaMB8uG3ZbDgfkJNBWEr/parameter_onnQTu.json'),
inline=True)
self.assertEqual(expected, actual)
def test_michelson_inverse_parameter_onnQTu(self):
expected = get_data(
path='contracts/KT1G72fc8TP3C7WgnaMB8uG3ZbDgfkJNBWEr/parameter_onnQTu.json')
actual = michelson_to_micheline(micheline_to_michelson(expected))
self.assertEqual(expected, actual)
def test_michelson_parse_parameter_ooGRZm(self):
expected = get_data(
path='contracts/KT1G72fc8TP3C7WgnaMB8uG3ZbDgfkJNBWEr/parameter_ooGRZm.json')
actual = michelson_to_micheline(get_data(
path='contracts/KT1G72fc8TP3C7WgnaMB8uG3ZbDgfkJNBWEr/parameter_ooGRZm.tz'))
self.assertEqual(expected, actual)
def test_michelson_format_parameter_ooGRZm(self):
expected = get_data(
path='contracts/KT1G72fc8TP3C7WgnaMB8uG3ZbDgfkJNBWEr/parameter_ooGRZm.tz')
actual = micheline_to_michelson(get_data(
path='contracts/KT1G72fc8TP3C7WgnaMB8uG3ZbDgfkJNBWEr/parameter_ooGRZm.json'),
inline=True)
self.assertEqual(expected, actual)
def test_michelson_inverse_parameter_ooGRZm(self):
expected = get_data(
path='contracts/KT1G72fc8TP3C7WgnaMB8uG3ZbDgfkJNBWEr/parameter_ooGRZm.json')
actual = michelson_to_micheline(micheline_to_michelson(expected))
self.assertEqual(expected, actual)
| [
"mz@baking-bad.org"
] | mz@baking-bad.org |
fdd6cd19067be398e034485ffed4ce17161ee1f1 | 5acc20092ee93935594a7e0522924245a43e5531 | /decision_trees/plot_tree_regression.py | d4307a1f717e2be72689a8cbfde8de070109e9ce | [] | no_license | shengchaohua/sklearn-examples | aae2332c4382a57a70c1887777c125e6dc4579d6 | 1dac6a9b5e703185a8da1df7c724022fbd56a9e4 | refs/heads/master | 2020-05-05T01:19:20.037746 | 2019-10-18T08:55:01 | 2019-10-18T08:55:01 | 179,599,221 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 885 | py | import numpy as np
from sklearn.tree import DecisionTreeRegressor
import matplotlib.pyplot as plt
# Create a random data set
rng = np.random.RandomState(1)
X = np.sort(5 * rng.rand(80, 1), axis=0)
y = np.sin(X).ravel()
y[::5] += 3 * (0.5 - rng.rand(16))
# Fit regression model
regr_1 = DecisionTreeRegressor(max_depth=2)
regr_2 = DecisionTreeRegressor(max_depth=5)
regr_1.fit(X, y)
regr_2.fit(X, y)
# Predict
X_test = np.arange(0.0, 5.0, 0.01)[:, np.newaxis]
y_1 = regr_1.predict(X_test)
y_2 = regr_2.predict(X_test)
# Plot the results
plt.figure()
plt.scatter(X, y, s=20, edgecolor="black", c="darkorange", label="data")
plt.plot(X_test, y_1, color="cornflowerblue", label="max_depth=2", linewidth=2)
plt.plot(X_test, y_2, color="yellowgreen", label="max_depth=5", linewidth=2)
plt.xlabel("data")
plt.ylabel("target")
plt.title("Decision Tree Regression")
plt.legend()
plt.show()
| [
"shengchaohua163@163.com"
] | shengchaohua163@163.com |
ca9258e6924e408fc0176eaaf8cc9f02aa0c7bfa | 3844678a0fb3b1f0838fb04bc57fd93dee6ee631 | /siteApps/ecrisApps/css/ECRIS/script/glassman_set_value.py | fcce39d050b67b9e8f1089766248385506406dbb | [] | no_license | jeonghanlee/Work | daa9295da3af3ff6c3a68daf51fac804dd1942cd | bef817911ea29fe091547f001ac35ac3765d8258 | refs/heads/master | 2022-09-28T03:59:29.435017 | 2022-09-15T18:26:34 | 2022-09-15T18:26:34 | 91,843,357 | 3 | 0 | null | 2019-01-08T16:10:37 | 2017-05-19T20:34:36 | VHDL | UTF-8 | Python | false | false | 468 | py | from org.csstudio.opibuilder.scriptUtil import PVUtil
from org.csstudio.opibuilder.scriptUtil import ConsoleUtil
sys = widget.getMacroValue("SYS")
subsys = widget.getMacroValue("SUBSYS")
dev= widget.getMacroValue("DEV")
par= widget.getMacroValue("PAR")
pv_name=sys + "-" + subsys + ":" + dev + ":" + "v0set"
text_box="text_set_voltage_" + par
value=display.getWidget(text_box).getPropertyValue("text")
PVUtil.writePV(pv_name, value)
#ConsoleUtil.writeInfo(value)
| [
"silee7103@gmail.com"
] | silee7103@gmail.com |
25f96cedec9f44d673e174f26f7009c567e4d75e | 6daaf3cecb19f95265188adc9afc97e640ede23c | /python_design/pythonprogram_design/Ch4/4-2-E55.py | 3183e603b8e24766d0c7c8793cf4ac19b5a5405c | [] | no_license | guoweifeng216/python | 723f1b29610d9f536a061243a64cf68e28a249be | 658de396ba13f80d7cb3ebd3785d32dabe4b611d | refs/heads/master | 2021-01-20T13:11:47.393514 | 2019-12-04T02:23:36 | 2019-12-04T02:23:36 | 90,457,862 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 450 | py | def main():
## Sort New England states by land area.
NE = [("Maine", 30840, 1.329), ("Vermont", 9217, .626),
("New Hampshire", 8953, 1.321), ("Massachusetts", 7800, 6.646),
("Connecticut", 4842, 3.59), ("Rhode Island", 1044, 1.05)]
NE.sort(key=lambda state: state[1], reverse=True)
print("Sorted by land area in descending order:")
for state in NE:
print(state[0], " ", end="")
print()
main()
| [
"weifeng.guo@cnexlabs.com"
] | weifeng.guo@cnexlabs.com |
9682c7a2b7ccafa088bfb89d7104ae3684b1c697 | 3691259d4be62b60d8d52f38b36d6a24e5fd4536 | /libcloud/compute/drivers/ktucloud.py | 75a5eef6eafc0c674f4fdb81343b669158f21aba | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | chenjiang1985/libcloud | f385fac278777c2bbfedaf440d353c9ad9eb5c69 | 587212da626dfe0e2936737108bcc49d666cf4b4 | refs/heads/master | 2021-07-16T14:29:21.821490 | 2019-11-27T02:20:43 | 2019-11-27T02:20:43 | 222,844,781 | 1 | 2 | Apache-2.0 | 2020-10-27T22:06:36 | 2019-11-20T03:41:31 | Python | UTF-8 | Python | false | false | 3,610 | py | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from libcloud.compute.providers import Provider
from libcloud.compute.base import Node, NodeImage, NodeSize
from libcloud.compute.drivers.cloudstack import CloudStackNodeDriver
class KTUCloudNodeDriver(CloudStackNodeDriver):
"""Driver for KTUCloud Compute platform."""
EMPTY_DISKOFFERINGID = '0'
type = Provider.KTUCLOUD
name = 'KTUCloud'
website = 'https://ucloudbiz.olleh.com/'
def list_images(self, location=None):
args = {
'templatefilter': 'executable'
}
if location is not None:
args['zoneid'] = location.id
imgs = self._sync_request(command='listAvailableProductTypes',
method='GET')
images = []
for img in imgs['producttypes']:
images.append(
NodeImage(
img['serviceofferingid'],
img['serviceofferingdesc'],
self,
{'hypervisor': '',
'format': '',
'os': img['templatedesc'],
'templateid': img['templateid'],
'zoneid': img['zoneid']}
)
)
return images
def list_sizes(self, location=None):
szs = self._sync_request('listAvailableProductTypes')
sizes = []
for sz in szs['producttypes']:
diskofferingid = sz.get('diskofferingid',
self.EMPTY_DISKOFFERINGID)
sizes.append(NodeSize(
diskofferingid,
sz['diskofferingdesc'],
0, 0, 0, 0, self)
)
return sizes
def create_node(self, name, size, image, location=None, **kwargs):
params = {'displayname': name,
'serviceofferingid': image.id,
'templateid': str(image.extra['templateid']),
'zoneid': str(image.extra['zoneid'])}
usageplantype = kwargs.pop('usageplantype', None)
if usageplantype is None:
params['usageplantype'] = 'hourly'
else:
params['usageplantype'] = usageplantype
if size.id != self.EMPTY_DISKOFFERINGID:
params['diskofferingid'] = size.id
result = self._async_request(
command='deployVirtualMachine',
params=params,
method='GET')
node = result['virtualmachine']
return Node(
id=node['id'],
name=node['displayname'],
state=self.NODE_STATE_MAP[node['state']],
public_ips=[],
private_ips=[],
driver=self,
extra={
'zoneid': image.extra['zoneid'],
'ip_addresses': [],
'forwarding_rules': [],
}
)
| [
"jacob.cj@alibaba-inc.com"
] | jacob.cj@alibaba-inc.com |
8b6ba1d95b208bc8087ef5dc27da02b1de14f438 | d7f64c3929642836691f4312cd936dd5647a2d80 | /ast.py | 93adf258d453a2a01bbb6c06fbdbc8a327e71293 | [] | no_license | folkol/imp | bb09528f5e1f2376ecaec6be94cbdee54fd306fe | ac1a085360d0f75f7326a731d51475cca386e923 | refs/heads/master | 2021-01-25T14:33:46.808721 | 2018-03-03T19:18:44 | 2018-03-03T19:18:44 | 123,711,862 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,844 | py | class ArithmeticExpression(object):
pass
class IntExp(ArithmeticExpression):
def __init__(self, i):
self.i = i
def eval(self, ignored):
return self.i
class Variable(ArithmeticExpression):
def __init__(self, name):
self.name = name
def eval(self, env):
if self.name in env:
return env[self.name]
else:
return 0
class BinaryOperator(ArithmeticExpression):
def __init__(self, op, left, right):
self.op = op
self.left = left
self.right = right
def eval(self, env):
left_value = self.left.eval(env)
right_value = self.right.eval(env)
if self.op == '+':
value = left_value + right_value
elif self.op == '-':
value = left_value - right_value
elif self.op == '*':
value = left_value * right_value
elif self.op == '/':
value = left_value / right_value
else:
raise RuntimeError('unknown operator: ' + self.op)
return value
class BooleanExpression(object):
pass
class RelationalExpression(BooleanExpression):
def __init__(self, op, left, right):
self.op = op
self.left = left
self.right = right
def eval(self, env):
left_value = self.left.eval(env)
right_value = self.right.eval(env)
if self.op == '<':
value = left_value < right_value
elif self.op == '<=':
value = left_value <= right_value
elif self.op == '>':
value = left_value > right_value
elif self.op == '>=':
value = left_value >= right_value
elif self.op == '=':
value = left_value == right_value
elif self.op == '!=':
value = left_value != right_value
else:
raise RuntimeError('unknown operator: ' + self.op)
return value
class And(BooleanExpression):
def __init__(self, left, right):
self.left = left
self.right = right
def eval(self, env):
left_value = self.left.eval(env)
right_value = self.right.eval(env)
return left_value and right_value
class Or(BooleanExpression):
def __init__(self, left, right):
self.left = left
self.right = right
def eval(self, env):
left_value = self.left.eval(env)
right_value = self.right.eval(env)
return left_value or right_value
class Not(BooleanExpression):
def __init__(self, exp):
self.exp = exp
def eval(self, env):
value = self.exp.eval(env)
return not value
class Statement(object):
pass
class Assignment(Statement):
def __init__(self, name, aexp):
self.name = name
self.aexp = aexp
def eval(self, env):
value = self.aexp.eval(env)
env[self.name] = value
class CompoundStatement(Statement):
def __init__(self, first, second):
self.second = second
self.first = first
def eval(self, env):
self.first.eval(env)
self.second.eval(env)
class If(Statement):
def __init__(self, condition, true_stmt, false_stmt):
self.condition = condition
self.true_stmt = true_stmt
self.false_stmt = false_stmt
def eval(self, env):
condition_value = self.condition.eval(env)
if condition_value:
self.true_stmt.eval(env)
else:
if self.false_stmt:
self.false_stmt.eval(env)
class While(Statement):
def __init__(self, condition, body):
self.condition = condition
self.body = body
def eval(self, env):
condition_value = self.condition.eval(env)
while condition_value:
self.body.eval(env)
condition_value = self.condition.eval(env)
| [
"mattias4@kth.se"
] | mattias4@kth.se |
fc0b6f99fcb1be107a0ce98c126476be63146522 | e68a40e90c782edae9d8f89b827038cdc69933c4 | /res_bw/scripts/common/lib/plat-mac/lib-scriptpackages/_builtinsuites/builtin_suite.py | 44040300db7fa8e6ef5204fd93a23f5516945284 | [] | no_license | webiumsk/WOT-0.9.16 | 2486f8b632206b992232b59d1a50c770c137ad7d | 71813222818d33e73e414e66daa743bd7701492e | refs/heads/master | 2021-01-10T23:12:33.539240 | 2016-10-11T21:00:57 | 2016-10-11T21:00:57 | 70,634,922 | 0 | 0 | null | null | null | null | WINDOWS-1250 | Python | false | false | 4,654 | py | # 2016.10.11 22:22:11 Střední Evropa (letní čas)
# Embedded file name: scripts/common/Lib/plat-mac/lib-scriptpackages/_builtinSuites/builtin_Suite.py
"""Suite builtin_Suite: Every application supports open, reopen, print, run, and quit
Level 1, version 1
"""
import aetools
import MacOS
_code = 'aevt'
class builtin_Suite_Events:
def open(self, _object, _attributes = {}, **_arguments):
"""open: Open the specified object(s)
Required argument: list of objects to open
Keyword argument _attributes: AppleEvent attribute dictionary
"""
_code = 'aevt'
_subcode = 'odoc'
if _arguments:
raise TypeError, 'No optional args expected'
_arguments['----'] = _object
_reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes)
if _arguments.get('errn', 0):
raise aetools.Error, aetools.decodeerror(_arguments)
if _arguments.has_key('----'):
return _arguments['----']
def run(self, _no_object = None, _attributes = {}, **_arguments):
"""run: Run an application. Most applications will open an empty, untitled window.
Keyword argument _attributes: AppleEvent attribute dictionary
"""
_code = 'aevt'
_subcode = 'oapp'
if _arguments:
raise TypeError, 'No optional args expected'
if _no_object is not None:
raise TypeError, 'No direct arg expected'
_reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes)
if _arguments.get('errn', 0):
raise aetools.Error, aetools.decodeerror(_arguments)
if _arguments.has_key('----'):
return _arguments['----']
else:
return
def reopen(self, _no_object = None, _attributes = {}, **_arguments):
"""reopen: Reactivate a running application. Some applications will open a new untitled window if no window is open.
Keyword argument _attributes: AppleEvent attribute dictionary
"""
_code = 'aevt'
_subcode = 'rapp'
if _arguments:
raise TypeError, 'No optional args expected'
if _no_object is not None:
raise TypeError, 'No direct arg expected'
_reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes)
if _arguments.get('errn', 0):
raise aetools.Error, aetools.decodeerror(_arguments)
if _arguments.has_key('----'):
return _arguments['----']
else:
return
def _print(self, _object, _attributes = {}, **_arguments):
"""print: Print the specified object(s)
Required argument: list of objects to print
Keyword argument _attributes: AppleEvent attribute dictionary
"""
_code = 'aevt'
_subcode = 'pdoc'
if _arguments:
raise TypeError, 'No optional args expected'
_arguments['----'] = _object
_reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes)
if _arguments.get('errn', 0):
raise aetools.Error, aetools.decodeerror(_arguments)
if _arguments.has_key('----'):
return _arguments['----']
_argmap_quit = {'saving': 'savo'}
def quit(self, _no_object = None, _attributes = {}, **_arguments):
"""quit: Quit an application
Keyword argument saving: specifies whether to save currently open documents
Keyword argument _attributes: AppleEvent attribute dictionary
"""
_code = 'aevt'
_subcode = 'quit'
aetools.keysubst(_arguments, self._argmap_quit)
if _no_object is not None:
raise TypeError, 'No direct arg expected'
aetools.enumsubst(_arguments, 'savo', _Enum_savo)
_reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes)
if _arguments.get('errn', 0):
raise aetools.Error, aetools.decodeerror(_arguments)
if _arguments.has_key('----'):
return _arguments['----']
else:
return
_argmap_close = {'saving': 'savo',
'saving_in': 'kfil'}
_Enum_savo = {'yes': 'yes ',
'no': 'no ',
'ask': 'ask '}
_classdeclarations = {}
_propdeclarations = {}
_compdeclarations = {}
_enumdeclarations = {'savo': _Enum_savo}
# okay decompyling c:\Users\PC\wotsources\files\originals\res_bw\scripts\common\lib\plat-mac\lib-scriptpackages\_builtinsuites\builtin_suite.pyc
# decompiled 1 files: 1 okay, 0 failed, 0 verify failed
# 2016.10.11 22:22:11 Střední Evropa (letní čas)
| [
"info@webium.sk"
] | info@webium.sk |
e4fdcb98e8edf08861cc723590e7f6122279a99c | b2ddc8011a4048d810bf4611c53b561293dd9452 | /testcube/settings.py | ec405de5927a291fe6e7c342a2d79d4ab3ae6c6a | [
"MIT"
] | permissive | RainYang0925/testcube | 677f6955d8a12e45b8c53037aad053482ab45f4f | a294c35a781e8495400ae7e04c342b326bc9c8ac | refs/heads/master | 2021-01-25T08:00:51.443311 | 2017-06-07T03:52:25 | 2017-06-07T03:52:25 | 93,696,358 | 1 | 0 | null | 2017-06-08T01:49:25 | 2017-06-08T01:49:25 | null | UTF-8 | Python | false | false | 3,973 | py | """
Django settings for testcube project.
Generated by 'django-admin startproject' using Django 1.11.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
from os import environ
from os.path import join, dirname, abspath
SETTINGS_DIR = dirname(abspath(__file__))
BASE_DIR = dirname(SETTINGS_DIR)
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = environ.get('TESTCUBG_SECRET_KEY', 'hard to guess key')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG_VALUE = environ.get('TESTCUBE_DEBUG', '').lower()
DEBUG = DEBUG_VALUE in ('true', 'yes', 'y', 'enabled', '1')
if environ.get('TESTCUBE_ALLOWED_HOSTS'):
ALLOWED_HOSTS = environ['TESTCUBE_ALLOWED_HOSTS'].split(',')
DB_ENGINE = environ.get('TESTCUBE_DB_ENGINE') or 'django.db.backends.sqlite3'
DB_NAME = environ.get('TESTCUBE_DB_NAME') or 'db.sqlite3'
STATIC_URL = environ.get('TESTCUBE_STATIC_URL') or '/static/'
STATIC_ROOT = environ.get('TESTCUBE_STATIC_ROOT') or join(BASE_DIR, 'dist')
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'bootstrapform',
'testcube.core',
'testcube.users'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'testcube.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [join(SETTINGS_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
'debug': DEBUG
},
},
]
WSGI_APPLICATION = 'testcube.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': DB_ENGINE,
'NAME': DB_NAME,
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = False
USE_L10N = False
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATICFILES_DIRS = [
join(SETTINGS_DIR, 'static')
]
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
],
'PAGE_SIZE': 10
}
| [
"toby.qin@live.com"
] | toby.qin@live.com |
3245aee47e4ac2131d988470aa907e073849400c | 7bd82b4fa83ca2442e204d3d2a721e3759f44baa | /project_name/admin.py | 590a114047ce337fde50dc3f4f01b9488a88c2c9 | [
"MIT"
] | permissive | rupin/heroku-django-template | 0b43455739772292feda6c5d89fbc0793799e64e | bdb117d73a7c1e85c6c82778784319787f15bacf | refs/heads/master | 2020-06-29T08:24:14.601479 | 2019-10-24T04:52:26 | 2019-10-24T04:52:26 | 200,485,262 | 0 | 0 | null | 2019-08-04T11:38:44 | 2019-08-04T11:38:43 | null | UTF-8 | Python | false | false | 494 | py | from import_export.admin import ImportExportModelAdmin
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from .forms import CustomUserCreationForm, CustomUserChangeForm
from .models import *
class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreationForm
form = CustomUserChangeForm
model = CustomUser
list_display = ['email', 'username',]
admin.site.register(CustomUser, CustomUserAdmin)
| [
"rupin.chheda@gmail.com"
] | rupin.chheda@gmail.com |
cc9fdcd55675b096709fb144e7d45b92487833b2 | ba2dbc19e899faaa17b994a1224e455a3de5b9ad | /02 Data Science/2. Analysis/1. CSV/3pandas_value_meets_condition.py | d1d763c6537a94766d202df868af4bb5e45b9337 | [] | no_license | xsky21/bigdata2019 | 52d3dc9379a05ba794c53a28284de2168d0fc366 | 19464a6f8862b6e6e3d4e452e0dab85bdd954e40 | refs/heads/master | 2020-04-21T10:56:34.637812 | 2019-04-16T04:16:27 | 2019-04-16T04:16:27 | 169,503,618 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 432 | py | #!/usr/bin/env python3
import pandas as pd
import sys
input_file = sys.argv[1]
output_file = sys.argv[2]
data_frame = pd.read_csv(input_file)
k = data_frame['Cost']
data_frame['Cost'] = data_frame['Cost'].str.strip('$').astype(float)
data_frame_value_meets_condition = data_frame.loc[(data_frame['Supplier Name'].str.contains('Z'))|(data_frame['Cost']> 600.0),:]
data_frame_value_meets_condition.to_csv(output_file,index=False)
| [
"studerande5@gmail.com"
] | studerande5@gmail.com |
f9771dc0b891f65fb7526cfd3c55da8d270457c1 | 9680ba23fd13b4bc0fc3ce0c9f02bb88c6da73e4 | /Brian Heinold (243) ile Python/p10506.py | bd4165bb54bc3dcc03caa0f97cad5ca92ee31c40 | [] | no_license | mnihatyavas/Python-uygulamalar | 694091545a24f50a40a2ef63a3d96354a57c8859 | 688e0dbde24b5605e045c8ec2a9c772ab5f0f244 | refs/heads/master | 2020-08-23T19:12:42.897039 | 2020-04-24T22:45:22 | 2020-04-24T22:45:22 | 216,670,169 | 0 | 0 | null | null | null | null | ISO-8859-9 | Python | false | false | 1,237 | py | # coding:iso-8859-9 Türkçe
from random import randint
from math import trunc
# Virgüllerle ayrık 2 ayrı veri giriş yöntemi
a, b = eval (input ('Virgüllerle ayrık 2 sayı girin: '))
if a<b: a,b=b,a # (küçük/büyük) kontrolsüz, biçimsiz sonuçlar üretebiliyor...
print (a, "+", b, "=", a+b)
print (a, "-", b, "=", a-b)
print (a, "*", b, "=", a*b)
print (a, "/", b, "=", a/b)
""" Her 2 sayının da negatif olması durumunda, sonucun pozitif ve
sıfırdan büyük çıkmasını isterseniz negatif küçüğü üste alabilirsiniz:
Yani eğer a=-5, b=-15 ise a, b'den büyük olduğu halde
print (b, "/", a, "=", b/a)
ifadesi sonucu +3 yansıtır
"""
print (a, "^", b, "=", a**b)
print (a, "%", b, "=", a%b)
print (a, "yüzde", b, "= %", (a-b)/b*100)
""" Çoklu yorum satırı
Program adı: Tek ve çok satırlı python yorumları
Kodlayan: M.Nihat Yavaş
Tarih: 29.09.2018-23:23 """
""" veya
Çoklu yorum satırı
Program adı: Tek ve çok satırlı python yorumları
Kodlayan: M.Nihat Yavaş
Tarih: 29.09.2018-23:23
"""
Çıktı=""" veya
Çoklu yorum satırı
Program adı: Tek ve çok satırlı python yorumları
Kodlayan: M.Nihat Yavaş
Tarih: 29.09.2018-23:23
""" | [
"noreply@github.com"
] | mnihatyavas.noreply@github.com |
0875ce4acd4136ebb9d8128af0cd76afdae5a06e | b4ca78134c296d8e03c39496bcc57369fd5f619b | /kubehub/views/k8s_cluster_view.py | 4305fb86a5f76432fac40d1bc2aa06664faecb27 | [] | no_license | dedicatted/kubehub-backend | 7f4b57033962f1ef8604a2cee0cf55bebd533ec9 | 3b944e462f5366b2dbad55063f325e4aa1b19b0e | refs/heads/master | 2023-02-05T04:44:50.213133 | 2020-06-10T15:02:03 | 2020-06-10T15:02:03 | 236,169,121 | 1 | 1 | null | 2023-01-24T23:19:38 | 2020-01-25T12:45:32 | Python | UTF-8 | Python | false | false | 5,236 | py | from django.http import JsonResponse
from django.forms.models import model_to_dict
from django.views.decorators.csrf import csrf_exempt
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import api_view, permission_classes
from json import loads
from ..models.proxmox_vm_group import ProxmoxVmGroup
from ..models.k8s_cluster import KubernetesCluster
from ..models.kubespray_deploy import KubesprayDeploy
from ..proxmox.vm_group_delete import vm_group_delete
from ..k8s_deploy.kubespray_deploy import kubespray_deploy
from ..serializers.vm_group_from_img_serializer import VmGroupFromImageSerializer
from ..serializers.k8s_cluster_serializer import KubernetesClusterSerializer
@api_view(['GET'])
@permission_classes([IsAuthenticated])
@csrf_exempt
def kubernetes_cluster_list(request):
if request.method == 'GET':
try:
k8s_clusters = []
for k8s_cluster in KubernetesCluster.objects.all():
kubespray_deploy_list = KubesprayDeploy.objects.filter(k8s_cluster=k8s_cluster)
k8s_cluster_dict = model_to_dict(k8s_cluster)
k8s_cluster_dict['kubespray_deployments'] = [
model_to_dict(kubespray_deploy_attempt)
for kubespray_deploy_attempt in kubespray_deploy_list
]
k8s_clusters.append(k8s_cluster_dict)
return JsonResponse({'kubernetes_cluster_list': k8s_clusters})
except Exception as e:
return JsonResponse({'errors': {f'{type(e).__name__}': [str(e)]}})
@api_view(['POST'])
@permission_classes([IsAuthenticated])
@csrf_exempt
def kubernetes_cluster_add(request):
if request.method == 'POST':
try:
kubernetes_cluster = loads(request.body)
kcs = KubernetesClusterSerializer(data=kubernetes_cluster)
kubernetes_cluster['status'] = 'deploying'
if kcs.is_valid():
kc = kcs.create(kcs.validated_data)
deploy = kubespray_deploy(
k8s_cluster_id=kc.id
)
if deploy.get('status') == 'successful':
k8s_cluster_status_update(
pk=kc.id,
status='running'
)
else:
k8s_cluster_status_update(
pk=kc.id,
status='error'
)
return JsonResponse(model_to_dict(kc))
else:
return JsonResponse({'errors': kcs.errors})
except Exception as e:
return JsonResponse({'errors': {f'{type(e).__name__}': [str(e)]}})
@api_view(['POST'])
@permission_classes([IsAuthenticated])
@csrf_exempt
def kubernetes_cluster_remove(request):
if request.method == 'POST':
try:
data = loads(request.body)
data['vm_group_id'] = KubernetesCluster.objects.get(pk=data['k8s_cluster_id']).vm_group.id
vm_group_pk = data.get('vm_group_id')
k8s_cluster_pk = data.get('k8s_cluster_id')
try:
k8s_cluster_status_update(
pk=k8s_cluster_pk,
status='removing'
)
vm_group_status_update(
pk=vm_group_pk,
status='removing'
)
delete = vm_group_delete(data)
if delete:
vm_group_status_update(
pk=vm_group_pk,
status='removed'
)
k8s_cluster_status_update(
pk=k8s_cluster_pk,
status='removed'
)
k8s_cluster_instance = KubernetesCluster.objects.get(pk=k8s_cluster_pk)
k8s_cluster_instance.delete()
vm_group_instance = ProxmoxVmGroup.objects.get(pk=vm_group_pk)
vm_group_instance.delete()
return JsonResponse({'deleted': model_to_dict(k8s_cluster_instance)})
except Exception as e:
k8s_cluster_status_update(
pk=k8s_cluster_pk,
status='error'
)
vm_group_status_update(
pk=vm_group_pk,
status='error'
)
return JsonResponse({'errors': {f'{type(e).__name__}': [str(e)]}})
except Exception as e:
return JsonResponse({'errors': {f'{type(e).__name__}': [str(e)]}})
def k8s_cluster_status_update(pk, status):
instance = KubernetesCluster.objects.get(pk=pk)
data = {'status': status}
k8scs = KubernetesClusterSerializer(data=data, partial=True)
if k8scs.is_valid():
k8sc = k8scs.update(instance, k8scs.validated_data)
return model_to_dict(k8sc)
def vm_group_status_update(pk, status):
instance = ProxmoxVmGroup.objects.get(pk=pk)
data = {'status': status}
vmgs = VmGroupFromImageSerializer(data=data, partial=True)
if vmgs.is_valid():
vmg = vmgs.update(instance, vmgs.validated_data)
return model_to_dict(vmg)
| [
"noreply@github.com"
] | dedicatted.noreply@github.com |
497314bfc946aa25317f6658dd9d4e8e9f00df30 | 2e3349340d12733892c6208b32ba955b4360d1db | /kunsplash/models/image_urls.py | 24794fa55f8b194bf76145715ce67f9bb4eb67ac | [] | no_license | kkristof200/py_unsplash | 4b8a6d7148dbd738de1caa44a551a30dce3a94eb | 9b4a428580de8e36a77e01b3f27501cbe73d1b83 | refs/heads/main | 2023-01-06T07:36:36.323854 | 2020-11-15T23:01:19 | 2020-11-15T23:01:19 | 313,140,199 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 896 | py | # ----------------------------------------------------------- class: ImageUrls ----------------------------------------------------------- #
class ImageUrls:
# ------------------------------------------------------------- Init ------------------------------------------------------------- #
def __init__(
self,
d: dict
):
self.raw = d['raw']
self.full = d['full']
self.regular = d['regular']
self.small = d['small']
self.thumb = d['thumb']
core = self.raw.split('?')[0]
self.hd = core + '?ixlib=rb-1.2.1&fm=jpg&crop=entropy&cs=tinysrgb&w={}&fit=max'.format(720)
self.fullHD = core + '?ixlib=rb-1.2.1&fm=jpg&crop=entropy&cs=tinysrgb&w={}&fit=max'.format(1080)
# ---------------------------------------------------------------------------------------------------------------------------------------- # | [
"kovacskristof200@gmail.com"
] | kovacskristof200@gmail.com |
f806d3225b073d92885ee4e935e1b1b677ff49af | b54d2b785d324828decd84941c7dbe6e1d2c5cf0 | /venv/Session10B.py | aadd65c5d21d207830a51fbf3430fbd0b8888195 | [] | no_license | ishantk/GW2019PA1 | 193c30dd930d17dacdd36f3adff20246c17ae6f9 | 120a63b05160a78a2c05c6e9f8561a7c02c6b88e | refs/heads/master | 2020-05-31T06:36:48.814161 | 2019-07-19T06:20:48 | 2019-07-19T06:20:48 | 190,145,890 | 14 | 15 | null | null | null | null | UTF-8 | Python | false | false | 1,029 | py | class Parent:
def __init__(self, fname, lname):
self.fname = fname
self.lname = lname
print(">> Parent Constructor Executed")
def showDetails(self):
print(">> Hello, ",self.fname, self.lname)
class Child(Parent): # Relationship -> IS-A
def __init__(self, fname, lname, vehicles, salary):
Parent.__init__(self, fname, lname)
self.vehicles = vehicles
self.salary = salary
print(">> Child Constructor Executed")
# Overriding
def showDetails(self):
Parent.showDetails(self)
print(">> Hello in Child, ", self.vehicles, self.salary)
print("Parent Class Dictionary: ",Parent.__dict__)
print("Child Class Dictionary: ",Child.__dict__)
ch = Child("John", "Watson", 2, 30000)
print(ch.__dict__)
ch.showDetails() # Child.showDetails(ch)
# Parent.showDetails(ch)
# Rule 2 : In Child to have customizations, we shall access Parent's Properties :)
# Funda : If same function with the same name is also available in Child -> OVERRIDING
| [
"er.ishant@gmail.com"
] | er.ishant@gmail.com |
406b3a67d50ad721e4827ee2929ce4120881cd16 | 133cbe0eeccd42d3e0f77de56a48032a4d8a5dd6 | /astropy_timeseries/io/kepler.py | decaccf371fcb10b59a170b8ac1c2919e8c9186c | [] | no_license | barentsen/astropy-timeseries | 5d1a4c4af8aaa4bd7271d0284d32b7101d4c2b2e | 1a0852efcf37854c4088d2cd3f86b1e38eb71b8f | refs/heads/master | 2020-05-01T02:08:36.803144 | 2019-02-25T16:04:07 | 2019-02-25T16:04:07 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 876 | py | from astropy.io import registry
from astropy.table import Table
from astropy.time import Time
from ..sampled import TimeSeries
__all__ = ['kepler_fits_reader']
def kepler_fits_reader(filename):
# Parse Kepler FITS file with regular FITS reader
tab = Table.read(filename, format='fits')
for colname in tab.colnames:
# Fix units
if tab[colname].unit == 'e-/s':
tab[colname].unit = 'electron/s'
# Rename columns to lowercase
tab.rename_column(colname, colname.lower())
# Compute Time object
time = Time(tab['time'].data + 2454833, scale='tcb', format='jd')
# Remove original time column
tab.remove_column('time')
# Create time series
ts = TimeSeries(time=time, data=tab)
ts.time.format = 'isot'
return ts
registry.register_reader('kepler.fits', TimeSeries, kepler_fits_reader)
| [
"thomas.robitaille@gmail.com"
] | thomas.robitaille@gmail.com |
3672299abcf38d60edba474bdaa16a910e9e2918 | 6413fe58b04ac2a7efe1e56050ad42d0e688adc6 | /tempenv/lib/python3.7/site-packages/plotly/validators/bar/marker/_reversescale.py | 0643f12996715a3baf7cbdc908afd0a358154f87 | [
"MIT"
] | permissive | tytechortz/Denver_temperature | 7f91e0ac649f9584147d59193568f6ec7efe3a77 | 9d9ea31cd7ec003e8431dcbb10a3320be272996d | refs/heads/master | 2022-12-09T06:22:14.963463 | 2019-10-09T16:30:52 | 2019-10-09T16:30:52 | 170,581,559 | 1 | 0 | MIT | 2022-06-21T23:04:21 | 2019-02-13T21:22:53 | Python | UTF-8 | Python | false | false | 476 | py | import _plotly_utils.basevalidators
class ReversescaleValidator(_plotly_utils.basevalidators.BooleanValidator):
def __init__(
self, plotly_name='reversescale', parent_name='bar.marker', **kwargs
):
super(ReversescaleValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop('edit_type', 'plot'),
role=kwargs.pop('role', 'style'),
**kwargs
)
| [
"jmswank7@gmail.com"
] | jmswank7@gmail.com |
e7cdbdb4afd52e49b81f4f1fbd4b703332ea426d | 05b0162d5ee7ab74f71ad4f21d5188a8735dfaef | /plugins/action/sg_mapping_deploy_all.py | 0c785231f7c774872d04b7ffa8364529096202eb | [
"MIT"
] | permissive | steinzi/ansible-ise | 567b2e6d04ce3ca6fbdbb6d0f15cd1913a1e215a | 0add9c8858ed8e0e5e7219fbaf0c936b6d7cc6c0 | refs/heads/main | 2023-06-25T15:28:22.252820 | 2021-07-23T14:21:40 | 2021-07-23T14:21:40 | 388,820,896 | 0 | 0 | MIT | 2021-07-23T14:03:07 | 2021-07-23T14:03:06 | null | UTF-8 | Python | false | false | 2,511 | py | from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.plugins.action import ActionBase
try:
from ansible_collections.ansible.utils.plugins.module_utils.common.argspec_validate import (
AnsibleArgSpecValidator,
)
except ImportError:
ANSIBLE_UTILS_IS_INSTALLED = False
else:
ANSIBLE_UTILS_IS_INSTALLED = True
from ansible.errors import AnsibleActionFail
from ansible_collections.cisco.ise.plugins.module_utils.ise import (
ISESDK,
ise_argument_spec,
)
# Get common arguements specification
argument_spec = ise_argument_spec()
# Add arguments specific for this module
argument_spec.update(dict(
))
required_if = []
required_one_of = []
mutually_exclusive = []
required_together = []
class ActionModule(ActionBase):
def __init__(self, *args, **kwargs):
if not ANSIBLE_UTILS_IS_INSTALLED:
raise AnsibleActionFail("ansible.utils is not installed. Execute 'ansible-galaxy collection install ansible.utils'")
super(ActionModule, self).__init__(*args, **kwargs)
self._supports_async = True
self._result = None
# Checks the supplied parameters against the argument spec for this module
def _check_argspec(self):
aav = AnsibleArgSpecValidator(
data=self._task.args,
schema=dict(argument_spec=argument_spec),
schema_format="argspec",
schema_conditionals=dict(
required_if=required_if,
required_one_of=required_one_of,
mutually_exclusive=mutually_exclusive,
required_together=required_together,
),
name=self._task.action,
)
valid, errors, self._task.args = aav.validate()
if not valid:
raise AnsibleActionFail(errors)
def get_object(self, params):
new_object = dict(
)
return new_object
def run(self, tmp=None, task_vars=None):
self._task.diff = False
self._result = super(ActionModule, self).run(tmp, task_vars)
self._result["changed"] = False
self._check_argspec()
ise = ISESDK(params=self._task.args)
response = ise.exec(
family="ip_to_sgt_mapping",
function='deploy_all_ip_to_sgt_mapping',
params=self.get_object(self._task.args),
).response
self._result.update(dict(ise_response=response))
self._result.update(ise.exit_json())
return self._result
| [
"wastorga@altus.co.cr"
] | wastorga@altus.co.cr |
f0191ceb0448c8b6eacede545dd5863c69667797 | cb1d59b57510d222efcfcd37e7e4e919b6746d6e | /python/serialize_and_deserialize_BST.py | b07ff5bbbf5e37248ebf473b88bb3d16d5bafbd1 | [] | no_license | pzmrzy/LeetCode | 416adb7c1066bc7b6870c6616de02bca161ef532 | ef8c9422c481aa3c482933318c785ad28dd7703e | refs/heads/master | 2021-06-05T14:32:33.178558 | 2021-05-17T03:35:49 | 2021-05-17T03:35:49 | 49,551,365 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,219 | py | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
ret = []
def preorder(root):
if root:
ret.append(root.val)
preorder(root.left)
preorder(root.right)
preorder(root)
return ' '.join(map(str, ret))
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
nums = collections.deque(int(n) for n in data.split())
def build(mmin, mmax):
if nums and mmin < nums[0] < mmax:
n = nums.popleft()
node = TreeNode(n)
node.left = build(mmin, n)
node.right = build(n, mmax)
return node
return build(float('-inf'), float('inf'))
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))
| [
"pzmrzy@gmail.com"
] | pzmrzy@gmail.com |
a25e58ffc121cdabeac8d4d10d327c475e84b51a | e2e08d7c97398a42e6554f913ee27340226994d9 | /pyautoTest-master(ICF-7.5.0)/test_case/scg/scg_LOG/test_c142758.py | 9a8984479db4dc8ffc54e5244552c4f02ae21dfe | [] | no_license | lizhuoya1111/Automated_testing_practice | 88e7be512e831d279324ad710946232377fb4c01 | b3a532d33ddeb8d01fff315bcd59b451befdef23 | refs/heads/master | 2022-12-04T08:19:29.806445 | 2020-08-14T03:51:20 | 2020-08-14T03:51:20 | 287,426,498 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,310 | py | import pytest
import time
import sys
from os.path import dirname, abspath
sys.path.insert(0, dirname(dirname(abspath(__file__))))
from page_obj.scg.scg_def_physical_interface import *
from page_obj.scg.scg_def_vlan_interface import *
from page_obj.scg.scg_def_bridge import *
from page_obj.common.rail import *
from page_obj.scg.scg_def_log import *
from page_obj.common.ssh import *
from page_obj.scg.scg_def_dhcp import *
from page_obj.scg.scg_dev import *
from page_obj.scg.scg_def_ifname_OEM import *
from page_obj.scg.scg_def import *
test_id = 142758
def test_c142758(browser):
try:
login_web(browser, url=dev1)
edit_log_localdb_traffic_jyl(browser, traffic="5000", traffic_num="50")
edit_log_localdb_traffic_jyl(browser, traffic="800000", traffic_num="50")
loginfo1 = get_log(browser, 管理日志)
try:
assert "配置 [LogDB]对象成功" in loginfo1
rail_pass(test_run_id, test_id)
except:
rail_fail(test_run_id, test_id)
assert "配置 [LogDB]对象成功" in loginfo1
except Exception as err:
# 如果上面的步骤有报错,重新设备,恢复配置
print(err)
reload(hostip=dev1)
rail_fail(test_run_id, test_id)
assert False
if __name__ == '__main__':
pytest.main(["-v", "-s", "test_c" + str(test_id) + ".py"])
| [
"15501866985@163.com"
] | 15501866985@163.com |
f56c525467ade5e3001eaa43d9726b72abff18cd | 19a7cbef5ccfdba8cfcaab0ab2382faea37b0fc6 | /backend/task_profile/migrations/0001_initial.py | 6253f2bb0e045f5037b01bc5d7cb47da1e50101e | [] | no_license | crowdbotics-apps/test-2-20753 | 6457b3d87abda53344537f0595d92ad0283efda8 | 6f59ab7cef1bd3d31adea98d4ecb74ba8044a180 | refs/heads/master | 2022-12-17T22:50:24.918623 | 2020-09-27T13:14:18 | 2020-09-27T13:14:18 | 299,032,653 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,518 | py | # Generated by Django 2.2.16 on 2020-09-27 13:00
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name="TaskerProfile",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("mobile_number", models.CharField(max_length=20)),
("photo", models.URLField()),
("timestamp_created", models.DateTimeField(auto_now_add=True)),
("last_updated", models.DateTimeField(auto_now=True)),
("last_login", models.DateTimeField(blank=True, null=True)),
("description", models.TextField(blank=True, null=True)),
("city", models.CharField(blank=True, max_length=50, null=True)),
("vehicle", models.CharField(blank=True, max_length=50, null=True)),
("closing_message", models.TextField(blank=True, null=True)),
("work_area_radius", models.FloatField(blank=True, null=True)),
(
"user",
models.OneToOneField(
on_delete=django.db.models.deletion.CASCADE,
related_name="taskerprofile_user",
to=settings.AUTH_USER_MODEL,
),
),
],
),
migrations.CreateModel(
name="Notification",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("type", models.CharField(max_length=20)),
("message", models.TextField()),
("timestamp_created", models.DateTimeField(auto_now_add=True)),
(
"user",
models.ManyToManyField(
related_name="notification_user", to=settings.AUTH_USER_MODEL
),
),
],
),
migrations.CreateModel(
name="InviteCode",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("code", models.CharField(max_length=20)),
("timestamp_created", models.DateTimeField(auto_now_add=True)),
(
"user",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="invitecode_user",
to=settings.AUTH_USER_MODEL,
),
),
],
),
migrations.CreateModel(
name="CustomerProfile",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("mobile_number", models.CharField(max_length=20)),
("photo", models.URLField()),
("timestamp_created", models.DateTimeField(auto_now_add=True)),
("last_updated", models.DateTimeField(auto_now=True)),
("last_login", models.DateTimeField(blank=True, null=True)),
(
"user",
models.OneToOneField(
on_delete=django.db.models.deletion.CASCADE,
related_name="customerprofile_user",
to=settings.AUTH_USER_MODEL,
),
),
],
),
]
| [
"team@crowdbotics.com"
] | team@crowdbotics.com |
6f508176b3ca094892486adba3d54a24a15695e5 | 268568ff2d483f39de78a5b29d941ce499cace33 | /spyder/app/tests/test_tour.py | 8119b0810110005f285b4bacd55f36840f505b6a | [
"MIT"
] | permissive | MarkMoretto/spyder-master | 61e7f8007144562978da9c6adecaa3022758c56f | 5f8c64edc0bbd203a97607950b53a9fcec9d2f0b | refs/heads/master | 2023-01-10T16:34:37.825886 | 2020-08-07T19:07:56 | 2020-08-07T19:07:56 | 285,901,914 | 2 | 1 | MIT | 2022-12-20T13:46:41 | 2020-08-07T19:03:37 | Python | UTF-8 | Python | false | false | 519 | py | # -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
#
"""
Tests for tour.py
"""
# Test library imports
import pytest
# Local imports
from spyder.app.tour import TourTestWindow
@pytest.fixture
def tour(qtbot):
"Setup the QMainWindow for the tour."
tour = TourTestWindow()
qtbot.addWidget(tour)
return tour
def test_tour(tour, qtbot):
"""Test tour."""
tour.show()
assert tour
if __name__ == "__main__":
pytest.main()
| [
"mark.moretto@forcepoint.com"
] | mark.moretto@forcepoint.com |
bf43e790286174e15d0347f8e37777dde97aa064 | b932ddc6d1187a795ef3c2b2af0ef5b186c8463f | /clients/views.py | 6522a5f469990285833849200e9da9f4437b00aa | [] | no_license | FlashBanistan/drf-property-management | 77f7ce487878b08298627e08dbaf5b9599768e73 | 016fb3e512dafa901de70e0b75ce0a6f6de38933 | refs/heads/master | 2021-11-16T18:55:48.314808 | 2020-09-09T03:13:36 | 2020-09-09T03:13:36 | 98,379,119 | 1 | 0 | null | 2021-09-22T17:37:36 | 2017-07-26T04:21:59 | Python | UTF-8 | Python | false | false | 979 | py | from rest_framework import viewsets
from rest_framework.response import Response
from django.shortcuts import get_object_or_404
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import user_passes_test
from .models import Client
from .serializers import ClientSerializer
@method_decorator(user_passes_test(lambda u: u.is_superuser), name="dispatch")
class ClientViewSet(viewsets.ModelViewSet):
queryset = Client.objects.all()
serializer_class = ClientSerializer
def client_from_request(request):
return request.user.client
class ClientAwareViewSet(viewsets.ModelViewSet):
def get_queryset(self):
return super().get_queryset().filter(client=client_from_request(self.request))
def perform_create(self, serializer, *args, **kwargs):
client = client_from_request(self.request)
serializer.save(client=client)
super(ClientAwareViewSet, self).perform_create(serializer, *args, **kwargs)
| [
"FlashBanistan66@gmail.com"
] | FlashBanistan66@gmail.com |
9d67d310c01d76d57b2c16257c4455828651f443 | 9e87897c988af634c3fddc42113992a65ec006f4 | /sandbox/pytorch/gmm.py | ffdc083af1b3e4f5ad2a1eb80ca3c16f29bd22be | [
"MIT"
] | permissive | luiarthur/cytof5 | 152eb06030785fdff90220f0d0a244a02204c2e9 | 6b4df5e9fd94bfd586e96579b8c618fdf6f913ed | refs/heads/master | 2021-07-20T13:39:45.821597 | 2021-03-02T23:27:35 | 2021-03-02T23:27:35 | 145,253,611 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,204 | py | # https://www.kaggle.com/aakashns/pytorch-basics-linear-regression-from-scratch
# https://angusturner.github.io/generative_models/2017/11/03/pytorch-gaussian-mixture-model.html
# https://pytorch.org/tutorials/beginner/examples_autograd/two_layer_net_custom_function.html
import torch
import time
import math
from gmm_data_gen import genData
# Set random seed for reproducibility
torch.manual_seed(1)
# Set number of cpus to use
torch.set_num_threads(4)
# Define data type
dtype = torch.float64
# Define device-type (cpu / gpu)
device = torch.device("cpu")
# Param dimensions
J = 3
data = genData()
y_data = torch.tensor(data['y'])
y_mean = torch.mean(y_data).item()
y_sd = torch.std(y_data).item()
y_cs = (y_data - y_mean) / y_sd
N = len(y_cs)
# Create random Tensors for weights.
mu = torch.randn(J, device=device, dtype=dtype)
mu.requires_grad=True
log_sig2 = torch.empty(J, device=device, dtype=dtype).fill_(-5)
log_sig2.requires_grad=True
logit_w = torch.empty(J, device=device, dtype=dtype).fill_(1 / J)
logit_w.requires_grad=True
# logpdf of Normal
def lpdf_normal(x, m, v):
return -(x - m) ** 2 / (2 * v) - 0.5 * torch.log(2 * math.pi * v)
def pdf_normal(x, m, v):
return torch.exp(lpdf_normal(x, m, v))
def lpdf_loginvgamma_kernel(x, a, b):
return -a * x - b * torch.exp(-x)
def loglike(yi, m, log_s2, logit_w):
s2 = torch.exp(log_s2)
log_w = torch.log_softmax(logit_w, 0)
return torch.logsumexp(log_w + lpdf_normal(yi, m, s2), 0)
# which is equivalent to and more numerically stable to:
# w = torch.softmax(logit_w, 0)
# return torch.log(w.dot(pdf_normal(yi, mu, sig2)))
# loglike(y_data[0], mu, log_sig2, logit_w)
learning_rate = 1e-3
eps = 1E-8
optimizer = torch.optim.Adam([mu, log_sig2, logit_w], lr=learning_rate)
ll_out = [-math.inf, ]
for t in range(100000):
# zero out the gradient
optimizer.zero_grad()
# Forward pass
ll = torch.stack([loglike(yi, mu, log_sig2, logit_w) for yi in y_cs]).sum()
ll_out.append(ll.item())
lp_logsig2 = lpdf_loginvgamma_kernel(log_sig2, 3, 2).sum()
lp_logit_w = 0 # TODO
lp = lp_logsig2 + lp_logit_w
# Compute and print loss using operations on Tensors.
log_post = ll + lp
loss = -(log_post) / N
ll_diff = ll_out[-1] - ll_out[-2]
if ll_diff / N < eps:
break
else:
print('ll mean improvement: {}'.format(ll_diff / N))
print("{}: loglike: {}".format(t, ll.item() / N))
print('mu: {}'.format(list(map(lambda m: m * y_sd + y_mean, mu.tolist()))))
print('sig2: {}'.format(list(map(lambda s2: s2 * y_sd * y_sd, torch.exp(log_sig2).tolist()))))
print('w: {}'.format(torch.softmax(logit_w, 0).tolist()))
# Use autograd to compute the backward pass.
loss.backward()
# Update weights
optimizer.step()
# SAME AS ABOVE.
#
# Update weights using gradient descent.
# with torch.no_grad():
# mu -= mu.grad * learning_rate
# log_sig2 -= log_sig2.grad * learning_rate
# logit_w -= logit_w.grad * learning_rate
#
# # Manually zero the gradients after updating weights
# mu.grad.zero_()
# log_sig2.grad.zero_()
# logit_w.grad.zero_()
| [
"luiarthur@gmail.com"
] | luiarthur@gmail.com |
a816b6057d723ea0010e5dff9f5f61c79b1e910f | 64e3b825b050d5e2a998e6bb809098e95d16b83c | /basemap_matplotlib_使用案例/003_basemap_绘制中国地图_GitHub上的中国地图数据.py | a2bf5acafa3f99bef68d273e5932c2fdb4c8aa52 | [] | no_license | jackyin68/wuhan_2019-nCoV | a119828c32e7b8479c68b6a48993ab3aeab98805 | 340909ad6d012863452c6a2ffc61e4c3f091d7be | refs/heads/master | 2022-04-10T03:09:59.726502 | 2020-03-17T07:40:42 | 2020-03-17T07:40:42 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,489 | py | # -*- coding:utf-8 -*-
# project_xxx\venv\Scripts python
'''
Author: Felix
WeiXin: AXiaShuBai
Email: xiashubai@gmail.com
Blog: https://blog.csdn.net/u011318077
Date: 2020/1/31 15:31
Desc:
'''
# 首先导入绘图包和地图包
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
# 第一步:设置图片大小及分辨率
plt.figure(figsize=(16, 8), dpi=300)
# 第二步:创建一个地图,设置经度纬度范围,只显示中国区域范围,projection选择投影模式,兰勃特投影
m = Basemap(llcrnrlon=77, llcrnrlat=14, urcrnrlon=140, urcrnrlat=51, projection='lcc', lat_1=33, lat_2=45, lon_0=100)
# 读取中国行政区文件,使用GitHub上已经整理好的地图文件,drawbounds参数显示图形
# 藏南区域和岛屿都有明显的标注,可以对比002结果,信息更加丰富,藏南更准确
m.readshapefile('../china_shapfiles/china-shapefiles-simple-version/china', 'china', drawbounds=True)
# 九段线地图数据
m.readshapefile('../china_shapfiles/china-shapefiles-simple-version/china_nine_dotted_line', 'china', drawbounds=True)
# 上面使用读取了本地地图文件,就不需要使用basemap绘制海岸线和国界线了,避免混乱
# 第三步:绘制地图上的线条,比如海岸线,国界线
# m.drawcoastlines(linewidth=1,linestyle='solid',color='black') # 绘制海岸线
# m.drawcountries(linewidth=1,linestyle='solid',color='black') # 绘制国界线
# 第四步:显示图形
plt.show() | [
"18200116656@qq.com"
] | 18200116656@qq.com |
1046870de0c05a4a728d3ef2a523485617239418 | b0717aeda1942dd35221e668b5d793077c074169 | /env/lib/python3.7/site-packages/twilio/rest/messaging/v1/__init__.py | 3f1e4ca3869413abfe1a5e499e1c2a2bec60d919 | [
"MIT"
] | permissive | stevehind/sms-steve-server | 3fdeed6de19f29aeaeb587fe7341831036455a25 | 9b0dac19f2e6ccf6452e738017132d93e993870b | refs/heads/master | 2022-12-21T23:34:10.475296 | 2020-01-27T16:24:39 | 2020-01-27T16:24:39 | 231,842,510 | 0 | 0 | MIT | 2022-05-25T05:03:16 | 2020-01-04T23:25:23 | Python | UTF-8 | Python | false | false | 1,615 | py | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base.version import Version
from twilio.rest.messaging.v1.service import ServiceList
from twilio.rest.messaging.v1.session import SessionList
from twilio.rest.messaging.v1.webhook import WebhookList
class V1(Version):
def __init__(self, domain):
"""
Initialize the V1 version of Messaging
:returns: V1 version of Messaging
:rtype: twilio.rest.messaging.v1.V1.V1
"""
super(V1, self).__init__(domain)
self.version = 'v1'
self._services = None
self._sessions = None
self._webhooks = None
@property
def services(self):
"""
:rtype: twilio.rest.messaging.v1.service.ServiceList
"""
if self._services is None:
self._services = ServiceList(self)
return self._services
@property
def sessions(self):
"""
:rtype: twilio.rest.messaging.v1.session.SessionList
"""
if self._sessions is None:
self._sessions = SessionList(self)
return self._sessions
@property
def webhooks(self):
"""
:rtype: twilio.rest.messaging.v1.webhook.WebhookList
"""
if self._webhooks is None:
self._webhooks = WebhookList(self)
return self._webhooks
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Messaging.V1>'
| [
"steve.hind@gmail.com"
] | steve.hind@gmail.com |
b1f20e1c4908222e39f3237763cab46248ac30e6 | 741ee09b8b73187fab06ecc1f07f46a6ba77e85c | /AutonomousSourceCode/data/raw/squareroot/83e76566-5f8e-4c9d-bea6-8a3c1519efe1__square_root.py | c1d2251d2f20561b14fcba31b5ee9d1797198cb8 | [] | no_license | erickmiller/AutomatousSourceCode | fbe8c8fbf215430a87a8e80d0479eb9c8807accb | 44ee2fb9ac970acf7389e5da35b930d076f2c530 | refs/heads/master | 2021-05-24T01:12:53.154621 | 2020-11-20T23:50:11 | 2020-11-20T23:50:11 | 60,889,742 | 6 | 1 | null | null | null | null | UTF-8 | Python | false | false | 700 | py | """ Comparing different ways of finding square root
1st column number a
2nd col square root from written function
3rd col square root computed by math.sqrt
4th col absolute value of difference between the two estimates
"""
def findsquare(a):
epsilon = 0.0000001
x = a/2.0
while True:
y = (x + a/x) / 2.0
if abs(y-x) < epsilon:
return x
x = y
def test_square(a):
import math
print a,
print (10-len(str(a)))*' ',
b = findsquare(a)
print b,
print (10-len(str(b)))*' ',
c = math.sqrt(a)
print c,
print (10-len(str(c)))*' ',
print abs(c - b)
test_square(35)
test_square(1001)
test_square(30000)
test_square(2)
| [
"erickmiller@gmail.com"
] | erickmiller@gmail.com |
e010a539cfed9506356780db88110ebfec463503 | 77dd413b4d4bcbe503785d9e16daacfc71febb78 | /salt/roster/flat.py | a562e16741c7cc622f385c18963d105b38e3cbe6 | [
"Apache-2.0"
] | permissive | amarnath/salt | 77bd308f431a8d70c6cf46212cfbb2b319019e63 | 0f458d7df5b9419ba9e8d68961f2ead197025d24 | refs/heads/develop | 2021-01-17T22:42:11.455863 | 2013-08-29T23:00:24 | 2013-08-29T23:00:24 | 12,478,872 | 0 | 2 | null | 2017-07-04T11:33:51 | 2013-08-30T05:36:29 | Python | UTF-8 | Python | false | false | 2,325 | py | '''
Read in the roster from a flat file using the renderer system
'''
# Import python libs
import os
import fnmatch
import re
# Import Salt libs
import salt.loader
from salt.template import compile_template
def targets(tgt, tgt_type='glob', **kwargs):
'''
Return the targets from the flat yaml file, checks opts for location but
defaults to /etc/salt/roster
'''
if os.path.isfile(__opts__['conf_file']) or not os.path.exists(__opts__['conf_file']):
template = os.path.join(
os.path.dirname(__opts__['conf_file']),
'roster')
else:
template = os.path.join(__opts__['conf_file'], 'roster')
rend = salt.loader.render(__opts__, {})
raw = compile_template(template, rend, __opts__['renderer'], **kwargs)
rmatcher = RosterMatcher(raw, tgt, tgt_type, 'ipv4')
return rmatcher.targets()
class RosterMatcher(object):
'''
Matcher for the roster data structure
'''
def __init__(self, raw, tgt, tgt_type, ipv='ipv4'):
self.tgt = tgt
self.tgt_type = tgt_type
self.raw = raw
self.ipv = ipv
def targets(self):
'''
Execute the correct tgt_type routine and return
'''
try:
return getattr(self, 'ret_{0}_minions'.format(self.tgt_type))()
except AttributeError:
return {}
def ret_glob_minions(self):
'''
Return minions that match via glob
'''
minions = {}
for minion in self.raw:
if fnmatch.fnmatch(minion, self.tgt):
data = self.get_data(minion)
if data:
minions[minion] = data
return minions
def ret_pcre_minions(self):
'''
Return minions that match via pcre
'''
minions = {}
for minion in self.raw:
if re.match(self.tgt, minion):
data = self.get_data(minion)
if data:
minions[minion] = data
return minions
def get_data(self, minion):
'''
Return the configured ip
'''
if isinstance(self.raw[minion], basestring):
return {'host': self.raw[minion]}
if isinstance(self.raw[minion], dict):
return self.raw[minion]
return False
| [
"thatch45@gmail.com"
] | thatch45@gmail.com |
1f052b4b2809f6daa1ec11d1b1292d2d680d53f5 | 4cdb3d1f9d0022284507877928d8f42d2fb0a5ee | /scripts/api/fetch_to_library.py | 6c497bcb402b8ba73fef0d49167a4497575da63e | [
"CC-BY-2.5",
"AFL-2.1",
"AFL-3.0",
"CC-BY-3.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | phnmnl/galaxy | 9051eea65cc0885d6b3534f0ce7c4baea3b573e4 | 45a541f5c76c4d328c756b27ff58c9d17c072eeb | refs/heads/dev | 2020-12-28T21:39:38.829279 | 2018-03-22T18:13:01 | 2018-03-22T18:13:01 | 53,574,877 | 2 | 4 | NOASSERTION | 2018-10-09T09:17:06 | 2016-03-10T10:11:26 | Python | UTF-8 | Python | false | false | 1,013 | py | import argparse
import json
import requests
import yaml
def main():
parser = argparse.ArgumentParser(description='Upload a directory into a data library')
parser.add_argument("-u", "--url", dest="url", required=True, help="Galaxy URL")
parser.add_argument("-a", "--api", dest="api_key", required=True, help="API Key")
parser.add_argument('target', metavar='FILE', type=str,
help='file describing data library to fetch')
args = parser.parse_args()
with open(args.target, "r") as f:
target = yaml.load(f)
histories_url = args.url + "/api/histories"
new_history_response = requests.post(histories_url, data={'key': args.api_key})
fetch_url = args.url + '/api/tools/fetch'
payload = {
'key': args.api_key,
'targets': json.dumps([target]),
'history_id': new_history_response.json()["id"]
}
response = requests.post(fetch_url, data=payload)
print(response.content)
if __name__ == '__main__':
main()
| [
"jmchilton@gmail.com"
] | jmchilton@gmail.com |
f44a44c690da1bfd0c74d3ad297d84b89c3b0f3e | fb19849a37b3fa11908bd1654d62b40b8f6bf227 | /udoy_4.py | 858fa8cec22f6cea676338288e0cc195875192ec | [] | no_license | udoy382/PyCourseBT | 51593b0e9775dd95b1ee7caa911818863837fabf | cff88fe33d7a8b313f0a2dbf4d218160db863b48 | refs/heads/main | 2023-03-25T03:44:09.173235 | 2021-03-25T14:29:19 | 2021-03-25T14:29:19 | 351,466,229 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 322 | py | # Privacy in Classes
class __Private:
def __init__(self, a, b):
# self.__a = a
self._a = a
self.b = b
print("Private class is created")
def _sum(self):
# return self.__a + self.b
return self._a + self.b
priv = __Private(10, 20)
print(priv._sum())
print(priv._a) | [
"srudoy436@gmail.com"
] | srudoy436@gmail.com |
9f8f92e26f9d76cf09b8fc8dab1a2a0bd6f94e30 | 9fda7a515674a76c80874f9deb63a6c472195711 | /demo/office31/best_classifier/Amazon2Webcam/exp_Temp_FL_IW.py | 1eaf35e0bd93235aaff5a5495d9a14ccaf2abde6 | [
"Apache-2.0"
] | permissive | sangdon/calibration-under-covariateshift | c1f65062ed8a8df108747162b0385b69ad4c8a50 | b1ed33d253a0c2539f8dd910b9ffa63150a14383 | refs/heads/main | 2023-03-23T00:33:27.350912 | 2021-03-19T04:19:20 | 2021-03-19T04:19:20 | 347,825,644 | 4 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,015 | py | import os, sys
##--------------------------------------------------
from exp_Amazon2Webcam import exp
sys.path.append("../../")
sys.path.append("../../../../../")
## param
from params import Temp_FL_IW_AmazonParamParser as ParamParser
## model
from train_model import train_model as netS
from models.DAForecasters import SimpleDiscriminatorNet as netD
from models.DAForecasters import SimpleFNNForecaster as netF
from models.DAForecasters import DAForecaster_Temp_FL_IW as DAF
model_init_fn = lambda params: DAF(netS(False),
netD(params.F_n_hiddens, params.D_n_hiddens),
netF(params.n_features, params.F_n_hiddens, params.n_labels))
## algorithm
from calibration.DA import Temp_FL_IW as DACalibrator
##--------------------------------------------------
if __name__ == "__main__":
## meta
exp_name = os.path.splitext(os.path.basename(__file__))[0]
## run exps
exp(exp_name, ParamParser, model_init_fn, netS, DACalibrator)
| [
"ggdons@gmail.com"
] | ggdons@gmail.com |
29eb355dde09276ea14d9335e447f6f8488466b2 | fd4163b9032ea17ea34e7575855a33746c1772c6 | /src/azure-cli/azure/cli/command_modules/ams/tests/latest/test_ams_sp_scenarios.py | 55ca18445ab2a90c6d7f433ac505010554a6f9e2 | [
"MIT"
] | permissive | ebencarek/azure-cli | b1524ed579353ee61feb9a2ec88b134f7252d5cd | ede3aaa83aa4ac8e352e508408cada685f9f8275 | refs/heads/az-cli-private-env | 2021-06-02T04:51:29.831098 | 2020-05-01T00:15:31 | 2020-05-01T00:15:31 | 137,520,442 | 2 | 9 | MIT | 2020-05-01T00:15:33 | 2018-06-15T18:33:10 | Python | UTF-8 | Python | false | false | 2,501 | py | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
import mock
from azure.cli.testsdk import ScenarioTest, ResourceGroupPreparer, StorageAccountPreparer
from azure_devtools.scenario_tests import AllowLargeResponse
class AmsSpTests(ScenarioTest):
@ResourceGroupPreparer()
@StorageAccountPreparer(parameter_name='storage_account_for_create')
@AllowLargeResponse()
def test_ams_sp_create_reset(self, resource_group, storage_account_for_create):
with mock.patch('azure.cli.command_modules.ams._utils._gen_guid', side_effect=self.create_guid):
amsname = self.create_random_name(prefix='ams', length=12)
self.kwargs.update({
'amsname': amsname,
'storageAccount': storage_account_for_create,
'location': 'westus2'
})
self.cmd('az ams account create -n {amsname} -g {rg} --storage-account {storageAccount} -l {location}', checks=[
self.check('name', '{amsname}'),
self.check('location', 'West US 2')
])
spPassword = self.create_random_name(prefix='spp!', length=16)
spNewPassword = self.create_random_name(prefix='spp!', length=16)
self.kwargs.update({
'spName': 'http://{}'.format(resource_group),
'spPassword': spPassword,
'spNewPassword': spNewPassword,
'role': 'Owner'
})
try:
self.cmd('az ams account sp create -a {amsname} -n {spName} -g {rg} -p {spPassword} --role {role}', checks=[
self.check('AadSecret', '{spPassword}'),
self.check('ResourceGroup', '{rg}'),
self.check('AccountName', '{amsname}')
])
self.cmd('az ams account sp reset-credentials -a {amsname} -n {spName} -g {rg} -p {spNewPassword} --role {role}', checks=[
self.check('AadSecret', '{spNewPassword}'),
self.check('ResourceGroup', '{rg}'),
self.check('AccountName', '{amsname}')
])
finally:
self.cmd('ad app delete --id {spName}')
| [
"tjprescott@users.noreply.github.com"
] | tjprescott@users.noreply.github.com |
52c9a144a025ca9815e448130e5b5ffb0d68d30f | 12a5b72982291ac7c074210afc2c9dfe2c389709 | /online_judges/URI/Data_Structures/1069/code.py | a63f5171a71f9481b3f88fb686a8311ec953073a | [] | no_license | krantirk/Algorithms-and-code-for-competitive-programming. | 9b8c214758024daa246a1203e8f863fc76cfe847 | dcf29bf976024a9d1873eadc192ed59d25db968d | refs/heads/master | 2020-09-22T08:35:19.352751 | 2019-05-21T11:56:39 | 2019-05-21T11:56:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 306 | py | from Queue import LifoQueue
n = int(raw_input())
for i in xrange(n):
s = raw_input()
fila = LifoQueue()
resposta = 0
for e in s:
if e == '<':
fila.put(1)
elif e == '>' and not fila.empty():
fila.get()
resposta += 1
print resposta
| [
"mariannelinharesm@gmail.com"
] | mariannelinharesm@gmail.com |
02c7599b6c6cee78be601d154db584e40d18d55f | 0b0abc06caa25dd269e1855d3cc6c72d34dc436c | /escuela/visitante/migrations/0005_detalle.py | aee59eb1e0833cae2e4229a9d2672e655bc22458 | [] | no_license | escuela2021/escuelagithub | 0130589214681d1ff9da36ffafd8aafb99c9b96d | f35897d1918af3a22d66b163153fc72a927516e8 | refs/heads/master | 2023-09-03T21:36:00.513263 | 2021-11-11T18:38:08 | 2021-11-11T18:38:08 | 427,109,636 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,052 | py | # Generated by Django 3.2.4 on 2021-11-06 15:31
import ckeditor.fields
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('visitante', '0004_tema'),
]
operations = [
migrations.CreateModel(
name='detalle',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nombre', models.TextField()),
('descripcion', models.TextField(blank=True, null=True)),
('imagen', models.ImageField(blank=True, null=True, upload_to='core')),
('dirurl', models.URLField(blank=True)),
('media', models.FileField(blank=True, null=True, upload_to='visitante')),
('texto', ckeditor.fields.RichTextField(blank=True, null=True)),
('tema', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='visitante.tema')),
],
),
]
| [
"gjangoinminutes@gmail.com"
] | gjangoinminutes@gmail.com |
1299544a9cd69674c4b9a5513dbb3441d4e300e5 | a63d907ad63ba6705420a6fb2788196d1bd3763c | /src/api/auth/core/ticket.py | 93fce93d029c09cdfef3a405f923fcb67d61ff8a | [
"MIT"
] | permissive | Tencent/bk-base | a38461072811667dc2880a13a5232004fe771a4b | 6d483b4df67739b26cc8ecaa56c1d76ab46bd7a2 | refs/heads/master | 2022-07-30T04:24:53.370661 | 2022-04-02T10:30:55 | 2022-04-02T10:30:55 | 381,257,882 | 101 | 51 | NOASSERTION | 2022-04-02T10:30:56 | 2021-06-29T06:10:01 | Python | UTF-8 | Python | false | false | 7,563 | py | # -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-BASE 蓝鲸基础平台 is licensed under the MIT License.
License for BK-BASE 蓝鲸基础平台:
--------------------------------------------------------------------
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
from auth.config.ticket import TICKET_FLOW_CONFIG, TICKET_TYPE_CHOICES
from auth.constants import DISPLAY_STATUS, FAILED, STOPPED, SUCCEEDED
from auth.core.ticket_objects import (
ApprovalController,
BatchReCalcObj,
CommonTicketObj,
DataTokenTicketObj,
ProjectDataTicketObj,
ResourceGroupTicketObj,
RoleTicketObj,
)
from auth.core.ticket_serializer import TicketStateSerializer
from auth.exceptions import UnexpectedTicketTypeErr
from common.business import Business
from django.db import transaction
class TicketFactory:
TICKET_OBJECTS = [
ProjectDataTicketObj,
ResourceGroupTicketObj,
RoleTicketObj,
DataTokenTicketObj,
BatchReCalcObj,
CommonTicketObj,
]
TICKET_OBJECT_CONFIG = {cls.__name__: cls for cls in TICKET_OBJECTS}
def __init__(self, ticket_type):
self.ticket_type = ticket_type
if ticket_type not in TICKET_FLOW_CONFIG:
raise UnexpectedTicketTypeErr()
_ticket_flow = TICKET_FLOW_CONFIG[ticket_type]
self.ticket_obj = self.TICKET_OBJECT_CONFIG[_ticket_flow.ticket_object](ticket_type)
def generate_ticket_data(self, data):
"""
生成ticket数据
@param data:
@return:
"""
return self.ticket_obj.generate_ticket_data(data)
def add_permission(self, ticket):
"""
添加权限
@param ticket:
@return:
"""
self.ticket_obj.add_permission(ticket)
def after_terminate(self, ticket, status):
"""
单据终止后的回调
@param ticket:
@param status:
@return:
"""
if hasattr(self.ticket_obj, "after_terminate"):
self.ticket_obj.after_terminate(ticket, status)
@classmethod
def list_ticket_types(cls):
return [{"id": item[0], "name": item[1]} for item in TICKET_TYPE_CHOICES]
@classmethod
def list_ticket_status(cls):
return [{"id": item[0], "name": item[1]} for item in DISPLAY_STATUS]
@classmethod
def serialize_ticket_queryset(cls, data, many=False, show_display=False):
"""
序列化单据
@param data:
@param many:
@param show_display:
@return:
"""
if many:
# 查询列表时暂时不需要列出所有显示名
results = []
for item in data:
results.append(cls(item.ticket_type).ticket_obj.SERIALIZER(item).data)
return results
else:
# 查询详情时把对象的显示名补充
result = cls(data.ticket_type).ticket_obj.SERIALIZER(data).data
if show_display:
result = cls(data.ticket_type).ticket_obj.SERIALIZER(data).wrap_permissions_display(result)
return result
@classmethod
def serialize_state_queryset(cls, data, ticket_type=None, many=True, show_display=False):
"""
序列化单据状态节点
@param data:
@param ticket_type: 单据类型
@param many:
@param show_display:
@return:
"""
if many:
result = []
# 指定单据类型时,同一state下的单据类型一定是一致的,不指定单据类型时则从各自state下取值
ticket_types = list({state.ticket.ticket_type for state in data})
if ticket_type:
if len(ticket_types) != 1:
raise UnexpectedTicketTypeErr()
else:
if ticket_type != ticket_types[0]:
raise UnexpectedTicketTypeErr()
else:
if len(ticket_types) == 1:
ticket_type = ticket_types[0]
for state in data:
item = TicketStateSerializer(state).data
item["ticket"] = cls(ticket_type or state.ticket.ticket_type).ticket_obj.SERIALIZER(state.ticket).data
result.append(item)
# 暂不支持不统一单据类型的权限显示名展示(效率较慢且暂无需求
if ticket_type and show_display:
result = cls(ticket_type).ticket_obj.SERIALIZER.wrap_permissions_display(result)
else:
result = TicketStateSerializer(data).data
result["ticket"] = cls(ticket_type).ticket_obj.SERIALIZER(data.ticket).data
if show_display:
result["ticket"]["permissions"] = (
cls(ticket_type).ticket_obj.SERIALIZER(data.ticket).wrap_permissions_display(result)
)
return result
@classmethod
def approve(cls, state, status, process_message, processed_by, add_biz_list=False):
"""
审批
@param state:
@param status:
@param process_message:
@param processed_by:
@param add_biz_list:
@return:
"""
context = None
if add_biz_list:
context = {"business": Business.get_name_dict()}
ApprovalController.approve(state, status, process_message, processed_by)
state_data = TicketStateSerializer(state).data
state_data["ticket"] = cls(state.ticket.ticket_type).ticket_obj.SERIALIZER(state.ticket, context=context).data
return state_data
@classmethod
def withdraw(cls, ticket, process_message, processed_by):
ticket.has_owner_permission(processed_by, raise_exception=True)
with transaction.atomic(using="basic"):
if not ticket.is_process_finish():
ticket.withdraw(process_message, processed_by)
return cls.serialize_ticket_queryset(ticket)
def get_content_for_notice(self, ticket):
"""
获取通知消息内容
@param [Ticket] ticket:
@return:
"""
return self.ticket_obj.get_content_for_notice(ticket)
def approve_finished(ticket, status, **kwargs):
if status == SUCCEEDED:
TicketFactory(ticket.ticket_type).add_permission(ticket)
if status in [FAILED, STOPPED]:
TicketFactory(ticket.ticket_type).after_terminate(ticket, status)
| [
"terrencehan@tencent.com"
] | terrencehan@tencent.com |
060e3d3c52f7c8946fc6ce8307a4633642f9db33 | 7b437e095068fb3f615203e24b3af5c212162c0d | /enaml/widgets/container.py | 1421529ddfd2d0cd52357c3dcb904f215742c914 | [
"BSD-3-Clause"
] | permissive | ContinuumIO/enaml | d8200f97946e5139323d22fba32c05231c2b342a | 15c20b035a73187e8e66fa20a43c3a4372d008bd | refs/heads/master | 2023-06-26T16:16:56.291781 | 2013-03-26T21:13:52 | 2013-03-26T21:13:52 | 9,047,832 | 2 | 3 | null | null | null | null | UTF-8 | Python | false | false | 7,031 | py | #------------------------------------------------------------------------------
# Copyright (c) 2013, Nucleic Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#------------------------------------------------------------------------------
from atom.api import (
Bool, Constant, Coerced, ForwardTyped, Typed, observe, set_default
)
from enaml.core.declarative import d_
from enaml.layout.geometry import Box
from enaml.layout.layout_helpers import vbox
from .constraints_widget import (
ConstraintsWidget, ProxyConstraintsWidget, ConstraintMember
)
class ProxyContainer(ProxyConstraintsWidget):
""" The abstract definition of a proxy Container object.
"""
#: A reference to the Container declaration.
declaration = ForwardTyped(lambda: Container)
class Container(ConstraintsWidget):
""" A ConstraintsWidget subclass that provides functionality for
laying out constrainable children according to their system of
constraints.
The Container is the canonical component used to arrange child
widgets using constraints-based layout. Given a heierarchy of
components, the top-most Container will be charged with the actual
layout of the decendents. This allows constraints to cross the
boundaries of Containers, enabling powerful and flexible layouts.
There are widgets whose boundaries constraints may not cross. Some
examples of these would be a ScrollArea or a TabGroup. See the
documentation of a given container component as to whether or not
constraints may cross its boundaries.
"""
#: A boolean which indicates whether or not to allow the layout
#: ownership of this container to be transferred to an ancestor.
#: This is False by default, which means that every container
#: get its own layout solver. This improves speed and reduces
#: memory use (by keeping a solver's internal tableaux small)
#: but at the cost of not being able to share constraints
#: across Container boundaries. This flag must be explicitly
#: marked as True to enable sharing.
share_layout = d_(Bool(False))
#: A constant symbolic object that represents the internal left
#: boundary of the content area of the container.
contents_left = ConstraintMember()
#: A constant symbolic object that represents the internal right
#: boundary of the content area of the container.
contents_right = ConstraintMember()
#: A constant symbolic object that represents the internal top
#: boundary of the content area of the container.
contents_top = ConstraintMember()
#: A constant symbolic object that represents the internal bottom
#: boundary of the content area of the container.
contents_bottom = ConstraintMember()
#: A constant symbolic object that represents the internal width of
#: the content area of the container.
contents_width = Constant()
def _default_contents_width(self):
return self.contents_right - self.contents_left
#: A constant symbolic object that represents the internal height of
#: the content area of the container.
contents_height = Constant()
def _default_contents_height(self):
return self.contents_bottom - self.contents_top
#: A constant symbolic object that represents the internal center
#: along the vertical direction the content area of the container.
contents_v_center = Constant()
def _default_contents_v_center(self):
return self.contents_top + self.contents_height / 2.0
#: A constant symbolic object that represents the internal center
#: along the horizontal direction of the content area of the container.
contents_h_center = Constant()
def _default_contents_h_center(self):
return self.contents_left + self.contents_width / 2.0
#: A box object which holds the padding for this component. The
#: padding is the amount of space between the outer boundary box
#: and the content box. The default padding is (10, 10, 10, 10).
#: Certain subclasses, such as GroupBox, may provide additional
#: margin than what is specified by the padding.
padding = d_(Coerced(Box, (10, 10, 10, 10)))
#: Containers freely exapnd in width and height. The size hint
#: constraints for a Container are used when the container is
#: not sharing its layout. In these cases, expansion of the
#: container is typically desired.
hug_width = set_default('ignore')
hug_height = set_default('ignore')
#: A reference to the ProxyContainer object.
proxy = Typed(ProxyContainer)
#--------------------------------------------------------------------------
# Public API
#--------------------------------------------------------------------------
def widgets(self):
""" Get the child ConstraintsWidgets defined on the container.
"""
return [c for c in self.children if isinstance(c, ConstraintsWidget)]
#--------------------------------------------------------------------------
# Child Events
#--------------------------------------------------------------------------
def child_added(self, child):
""" Handle the child added event on the container.
This event handler will request a relayout if the added child
is an instance of 'ConstraintsWidget'.
"""
super(Container, self).child_added(child)
if isinstance(child, ConstraintsWidget):
self.request_relayout()
def child_removed(self, child):
""" Handle the child removed event on the container.
This event handler will request a relayout if the removed child
is an instance of 'ConstraintsWidget'.
"""
super(Container, self).child_removed(child)
if isinstance(child, ConstraintsWidget):
self.request_relayout()
#--------------------------------------------------------------------------
# Observers
#--------------------------------------------------------------------------
@observe(('share_layout', 'padding'))
def _layout_invalidated(self, change):
""" A private observer which invalidates the layout.
"""
# The superclass handler is sufficient.
super(Container, self)._layout_invalidated(change)
#--------------------------------------------------------------------------
# Constraints Generation
#--------------------------------------------------------------------------
def _get_default_constraints(self):
""" The default constraints for a Container.
This method supplies default vbox constraint to the children of
the container if other constraints are not given.
"""
cns = super(Container, self)._get_default_constraints()
ws = (c for c in self.children if isinstance(c, ConstraintsWidget))
cns.append(vbox(*ws))
return cns
| [
"sccolbert@gmail.com"
] | sccolbert@gmail.com |
87f5c24314b39490e8e74e0b1de8d082502121b4 | fd7720dfc136eb92dbff8cc31e0f83bb8bbced16 | /db/queries.py | 7180c0c49d977ee644b04f66463964b52d135018 | [] | no_license | Villux/golden_goal | d134a1660dd32f0b4d05f720993dd23f8a064faf | f36f4dd0297e2e52c0f990cb3ac134f70fc16780 | refs/heads/master | 2020-03-27T01:53:09.863147 | 2018-11-15T15:40:04 | 2018-11-15T15:40:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,326 | py | create_elo_table = '''CREATE TABLE elo_table
(id integer PRIMARY KEY AUTOINCREMENT,
date TIMESTAMP,
team text,
elo real,
match_id integer,
season_id INTEGER NOT NULL,
FOREIGN KEY(season_id) REFERENCES season_table(id),
FOREIGN KEY(match_id) REFERENCES match_table(id));'''
drop_elo_table = "DROP TABLE IF EXISTS elo_table;"
create_odds_table = '''CREATE TABLE odds_table
(id integer PRIMARY KEY AUTOINCREMENT,
date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
home_win REAL,
draw REAL,
away_win REAL,
description TEXT,
match_id integer,
FOREIGN KEY(match_id) REFERENCES match_table(id));'''
drop_odds_table = "DROP TABLE IF EXISTS odds_table;"
create_division_table = '''CREATE TABLE division_table
(id integer PRIMARY KEY AUTOINCREMENT,
data_tag text,
description text);'''
drop_division_table = "DROP TABLE IF EXISTS division_table;"
create_season_table = '''CREATE TABLE season_table
(id integer PRIMARY KEY AUTOINCREMENT,
start_date TIMESTAMP,
end_date TIMESTAMP,
description text,
division_id INTEGER,
FOREIGN KEY(division_id) REFERENCES division_table(id));'''
drop_season_table = "DROP TABLE IF EXISTS season_table;"
create_lineup_table = '''CREATE TABLE lineup_table
(id integer PRIMARY KEY AUTOINCREMENT,
url text,
hp1 integer,
hp2 integer,
hp3 integer,
hp4 integer,
hp5 integer,
hp6 integer,
hp7 integer,
hp8 integer,
hp9 integer,
hp10 integer,
hp11 integer,
hs1 integer,
hs2 integer,
hs3 integer,
hs4 integer,
hs5 integer,
hs6 integer,
hs7 integer,
ap1 integer,
ap2 integer,
ap3 integer,
ap4 integer,
ap5 integer,
ap6 integer,
ap7 integer,
ap8 integer,
ap9 integer,
ap10 integer,
ap11 integer,
as1 integer,
as2 integer,
as3 integer,
as4 integer,
as5 integer,
as6 integer,
as7 integer,
match_id integer UNIQUE,
FOREIGN KEY(hp1) REFERENCES player_identity_table(id),
FOREIGN KEY(hp2) REFERENCES player_identity_table(id),
FOREIGN KEY(hp3) REFERENCES player_identity_table(id),
FOREIGN KEY(hp4) REFERENCES player_identity_table(id),
FOREIGN KEY(hp5) REFERENCES player_identity_table(id),
FOREIGN KEY(hp6) REFERENCES player_identity_table(id),
FOREIGN KEY(hp7) REFERENCES player_identity_table(id),
FOREIGN KEY(hp8) REFERENCES player_identity_table(id),
FOREIGN KEY(hp9) REFERENCES player_identity_table(id),
FOREIGN KEY(hp10) REFERENCES player_identity_table(id),
FOREIGN KEY(hp11) REFERENCES player_identity_table(id),
FOREIGN KEY(hs1) REFERENCES player_identity_table(id),
FOREIGN KEY(hs2) REFERENCES player_identity_table(id),
FOREIGN KEY(hs3) REFERENCES player_identity_table(id),
FOREIGN KEY(hs4) REFERENCES player_identity_table(id),
FOREIGN KEY(hs5) REFERENCES player_identity_table(id),
FOREIGN KEY(hs6) REFERENCES player_identity_table(id),
FOREIGN KEY(hs7) REFERENCES player_identity_table(id),
FOREIGN KEY(ap1) REFERENCES player_identity_table(id),
FOREIGN KEY(ap2) REFERENCES player_identity_table(id),
FOREIGN KEY(ap3) REFERENCES player_identity_table(id),
FOREIGN KEY(ap4) REFERENCES player_identity_table(id),
FOREIGN KEY(ap5) REFERENCES player_identity_table(id),
FOREIGN KEY(ap6) REFERENCES player_identity_table(id),
FOREIGN KEY(ap7) REFERENCES player_identity_table(id),
FOREIGN KEY(ap8) REFERENCES player_identity_table(id),
FOREIGN KEY(ap9) REFERENCES player_identity_table(id),
FOREIGN KEY(ap10) REFERENCES player_identity_table(id),
FOREIGN KEY(ap11) REFERENCES player_identity_table(id),
FOREIGN KEY(as1) REFERENCES player_identity_table(id),
FOREIGN KEY(as2) REFERENCES player_identity_table(id),
FOREIGN KEY(as3) REFERENCES player_identity_table(id),
FOREIGN KEY(as4) REFERENCES player_identity_table(id),
FOREIGN KEY(as5) REFERENCES player_identity_table(id),
FOREIGN KEY(as6) REFERENCES player_identity_table(id),
FOREIGN KEY(as7) REFERENCES player_identity_table(id),
FOREIGN KEY(match_id) REFERENCES match_table(id));'''
drop_lineup_table = "DROP TABLE IF EXISTS lineup_table;"
create_match_id_index = "CREATE INDEX match_id_index ON lineup_table (match_id);"
create_player_identity_table = '''CREATE TABLE player_identity_table
(fifa_name text,
goalcom_name text,
fifa_id INTEGER PRIMARY KEY,
goalcom_url text);'''
drop_player_identity_table = "DROP TABLE IF EXISTS player_identity_table;"
create_fifa_id_index = "CREATE INDEX pit_fifa_id_index ON player_identity_table (fifa_id);"
| [
"villej.toiviainen@gmail.com"
] | villej.toiviainen@gmail.com |
ca79e5fd9f9270aabed432701bd25c1f14e6fdc8 | 29881fa0c087f3d3ce0e27fb51309384266203e1 | /price_register/forms.py | 62c7c641dab7ec7fc4fbd7a250098d5eaf789c6f | [] | no_license | aidant842/mymo | 0e5ec2a5c73b6755d994467e4afba10141f449ea | 877e7a38198d1b5effc6c3a63ad12e7166c20a77 | refs/heads/master | 2023-07-17T15:30:21.350974 | 2021-08-24T12:43:18 | 2021-08-24T12:43:18 | 340,033,414 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,271 | py | from django import forms
class PropertyRegsiterFilter(forms.Form):
IE_COUNTY_CHOICES = [
(None, 'County'), ('carlow', 'Carlow'), ('cavan', 'Cavan'),
('clare', 'Clare'), ('cork', 'Cork'),
('donegal', 'Donegal'), ('dublin', 'Dublin'),
('galway', 'Galway'), ('kerry', 'Kerry'),
('kildare', 'Kildare'), ('kilkenny', 'Kilkenny'),
('laois', 'Laois'), ('leitrim', 'Leitrim'),
('limerick', 'Limerick'), ('longford', 'Longford'),
('louth', 'Louth'), ('mayo', 'Mayo'),
('meath', 'Meath'), ('monaghan', 'Monaghan'),
('offaly', 'Offaly'), ('roscommon', 'Roscommon'),
('sligo', 'Sligo'), ('tipperary', 'Tipperary'),
('waterford', 'Waterford'), ('westmeath', 'Westmeath'),
('wexford', 'Wexford'), ('wicklow', 'Wicklow'),
]
county = forms.CharField(widget=forms.Select
(choices=IE_COUNTY_CHOICES,
attrs={'class': 'form-select'}),
label='',
required=False)
area = forms.CharField(widget=forms.TextInput(
attrs={'placeholder': 'Area/Town'}),
label="",
required=False) | [
"aidant842@gmail.com"
] | aidant842@gmail.com |
734e216421a945afd8daef96e60cedf08644860b | 9743d5fd24822f79c156ad112229e25adb9ed6f6 | /xai/brain/wordbase/nouns/_initial.py | d1cef3978d2c3fa4aabf672c80ed94a85932a083 | [
"MIT"
] | permissive | cash2one/xai | de7adad1758f50dd6786bf0111e71a903f039b64 | e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6 | refs/heads/master | 2021-01-19T12:33:54.964379 | 2017-01-28T02:00:50 | 2017-01-28T02:00:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 352 | py |
#calss header
class _INITIAL():
def __init__(self,):
self.name = "INITIAL"
self.definitions = [u'the first letter of a name, especially when used to represent a name: ']
self.parents = []
self.childen = []
self.properties = []
self.jsondata = {}
self.specie = 'nouns'
def run(self, obj1 = [], obj2 = []):
return self.jsondata
| [
"xingwang1991@gmail.com"
] | xingwang1991@gmail.com |
573446d0eb0db0b59632fc96555a27bbc131d18f | bf8870d923adca9877d4b4dacef67f0a454727a8 | /codeforces.com/contest/133/a/pr.py | 63730bff7c0f31101ef62f87f15e0b187a1c0c68 | [] | no_license | artkpv/code-dojo | 6f35a785ee5ef826e0c2188b752134fb197b3082 | 0c9d37841e7fc206a2481e4640e1a024977c04c4 | refs/heads/master | 2023-02-08T22:55:07.393522 | 2023-01-26T16:43:33 | 2023-01-26T16:43:33 | 158,388,327 | 1 | 0 | null | 2023-01-26T08:39:46 | 2018-11-20T12:45:44 | C# | UTF-8 | Python | false | false | 400 | py | #!python3
from collections import deque, Counter
from itertools import combinations, permutations
from math import sqrt
import unittest
def read_int():
return int(input().strip())
def read_int_array():
return [int(i) for i in input().strip().split(' ')]
######################################################
s = input().strip()
print('YES' if any((c in 'HQ9') for c in s) else 'NO')
| [
"artyomkarpov@gmail.com"
] | artyomkarpov@gmail.com |
442f658071a199deed2ea39033e67851ce549cd2 | c50e5af8f72de6ef560ee6c0bbfa756087824c96 | /刷题/Leetcode/p974_Subarray_Sums_Divisible_by_K.py | 5515fb9f32761fd960718a1bc96ae72209273fe2 | [] | no_license | binghe2402/learnPython | 5a1beef9d446d8316aaa65f6cc9d8aee59ab4d1c | 2b9e21fe4a8eea0f8826c57287d59f9d8f3c87ce | refs/heads/master | 2022-05-27T03:32:12.750854 | 2022-03-19T08:00:19 | 2022-03-19T08:00:19 | 252,106,387 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 637 | py | from typing import List
import collections
'''
前缀和
n*K = sum[i+1:j+1] = prefixSum[j]-prefixSum[i]
(prefixSum[i] - prefixSum[j]) % K == 0
prefixSum[i] % K == prefixSum[j] % K
'''
class Solution:
def subarraysDivByK(self, A: List[int], K: int) -> int:
prefixSum = 0
prefix_cnt = collections.Counter({0: 1})
cnt = 0
for i in A:
prefixSum += i
prefixSum_mod = prefixSum % K
cnt += prefix_cnt[prefixSum_mod]
prefix_cnt[prefixSum_mod] += 1
return cnt
A = [4, 5, 0, -2, -3, 1]
K = 5
s = Solution()
res = s.subarraysDivByK(A, K)
print(res)
| [
"binghe2402@hotmail.com"
] | binghe2402@hotmail.com |
bf36f0203b6e49922be55bdbe48c77f4e48f19a7 | 1e3dba48c257b8b17d21690239d51858e5009280 | /exit_server/config/wsgi.py | 2d6f7b7f4d45020bc3a0deda128c173c13eea691 | [] | no_license | JEJU-SAMDASU/EXIT-Server | e3eb87707e5f79b0399dc614507c8d5889a85a4a | ac1b73703c9fff54866c979a620fd22470345b07 | refs/heads/master | 2023-02-12T13:29:18.508066 | 2020-11-23T12:42:18 | 2020-11-23T12:42:18 | 315,288,514 | 0 | 0 | null | 2020-11-24T17:16:29 | 2020-11-23T11:07:47 | Python | UTF-8 | Python | false | false | 394 | py | """
WSGI config for exit_server project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
application = get_wsgi_application()
| [
"hanbin8269@gmail.com"
] | hanbin8269@gmail.com |
1dc58d55719d5e8c779ab8d96e4b0646be1a8a93 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5634697451274240_1/Python/Mathuyama/pancake.py | 4fee8c53da1db866b82b5bceb88e8abef431eec2 | [] | 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 | 1,396 | py | import numpy as np
def getInfo(line):
t = []
for c in line:
if c == '-': t.append(-1);
if c == '+' : t.append(+1);
return t
def parse(path):
file = open(path,"r");
nbCases = int(file.readline());
txt = file.readlines();
cases = []
for line in txt:
cases.append(getInfo(line));
file.close()
return cases
def workpancake(t):
n = len(t);
plusIterator = n;
counter = 0;
while (plusIterator > 0):
while (plusIterator>0 and t[plusIterator-1] == +1):
plusIterator -= 1;
if (plusIterator > 0):
if (t[0] == (-1)):
t = flip(t,plusIterator);
else:
flipIndex = plusIterator-1;
while not(t[flipIndex] == 1):
flipIndex -= 1;
t = flip(t,flipIndex+1);
counter += 1;
return counter;
def flip(t,i):
if (i%2 == 1):
r = i-1;
t[i/2] = -t[i/2]
else:
r = i;
for k in range(r/2):
tmp = t[k];
t[k] = -t[i-k-1];
t[i-k-1] = -tmp;
return t;
def outputpancake(tablal,path):
file = open(path,'w');
for i in range(len(tablal)):
R = workpancake(tablal[i]);
file.write("Case #"+str(i+1)+": "+str(R)+"\n");
file.close();
tablal = parse("B-large.in");
outputpancake(tablal,"outputpancake.out");
| [
"alexandra1.back@gmail.com"
] | alexandra1.back@gmail.com |
bc6e0d7cce5ab4a2ff4d4c76a1ff404a38342888 | 30a866abd8b0aba8355ce0bc858cc679565032c2 | /wrk/python/global_variables.py | 13037f1c1b163b84ac9b8a6b917f5ae40a8aa723 | [] | no_license | srbcheema1/CheemaFy_legacy | d8a354e0f3463cb19ffbcf948d7be55c15c51faa | c929211729860887a82e0663bfcf5b85da6b6967 | refs/heads/master | 2021-10-15T23:48:57.259057 | 2019-01-31T11:33:46 | 2019-02-07T01:32:07 | 102,012,212 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 613 | py | hell = 1
debug = True
def read_only():
# here we are not writing it so no need of global keyword
read_debug = debug # works fine
if(debug): print("debug") # works fine
def strange():
bad_debug = debug # error
debug = True # maybe it thinks it is local
# it is to be declared global if we try to write it. else it is regarded as local
if(debug): print("debug")
def global_change():
global num
num = 3
def local_change():
num = 5
global_change() # works as expected
print(num)
local_change() # works as expected
print(num)
read_only()
strange() # explain why it dows so
| [
"srbcheema1@gmail.com"
] | srbcheema1@gmail.com |
0c3b71d557eed98f99e54ee483dfe08d43e50239 | a411a55762de11dc2c9d913ff33d2f1477ac02cf | /dp/cloud/python/magma/db_service/migrations/versions/016_remove_grant_attempts.py | 419ad005c1380af097689952c5a3b1ca7f4c6603 | [
"BSD-3-Clause"
] | permissive | magma/magma | 0dc48c1513d9968bd05fb7589f302c192b7c0f94 | 0e1d895dfe625681229e181fbc2dbad83e13c5cb | refs/heads/master | 2023-09-04T09:31:56.140395 | 2023-08-29T13:54:49 | 2023-08-29T13:54:49 | 170,803,235 | 1,219 | 525 | NOASSERTION | 2023-09-07T17:45:42 | 2019-02-15T04:46:24 | C++ | UTF-8 | Python | false | false | 782 | py | """empty message
Revision ID: 58a1b16ef73c
Revises: 530b18568ad9
Create Date: 2022-07-22 16:03:01.235285
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '58a1b16ef73c'
down_revision = '530b18568ad9'
branch_labels = None
depends_on = None
def upgrade():
"""
Run upgrade
"""
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('cbsds', 'grant_attempts')
# ### end Alembic commands ###
def downgrade():
"""
Run downgrade
"""
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('cbsds', sa.Column('grant_attempts', sa.INTEGER(), server_default=sa.text('0'), autoincrement=False, nullable=False))
# ### end Alembic commands ###
| [
"noreply@github.com"
] | magma.noreply@github.com |
dfde0dc15bc68d98164c3eed4e245d1a312dd74d | efc3bf4f88a2bfc885de5495c87433d345b54429 | /ZOJ/1115.py | 92f3352989a7d4a7c5a3053e24b7a7b9b4ac4e23 | [] | no_license | calvinxiao/Algorithm-Solution | 26ff42cc26aaca87a4706b82a325a92829878552 | afe254a4efa779598be8a82c5c5bcfcc94f80272 | refs/heads/master | 2016-09-05T21:08:35.852486 | 2015-08-23T15:13:23 | 2015-08-23T15:13:23 | 20,149,077 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 361 | py | #Problem ID: 1115
#Submit Time: 2012-08-16 00:49:47
#Run Time: 10
#Run Memory: 320
#ZOJ User: calvinxiao
import sys
def todo(n):
if n < 10:
return n
ans = 0
while n != 0:
ans += n % 10
n /= 10
return todo(ans)
while 1:
n = int(sys.stdin.readline())
if not n:
break
print todo(n) | [
"calvin.xiao@scaurugby.com"
] | calvin.xiao@scaurugby.com |
443b6a78e2121b70b47d9cb55a84223089801ef3 | 7d44994155d57a01fdd1b405018e2a83eb670bfe | /hub/src/light/effect/color_effects/triple_linear_color_transition.py | 24d6c76ab3ef0e923e7a64bf7b690f641dc416b9 | [] | no_license | jonlabroad/drum-lite | e05e2904c28f19101dfb0c43ecdf0b1b1f836e13 | e60e21a2f5d1f03e3e939163c101c286a3cfa7d2 | refs/heads/master | 2022-12-31T11:00:44.075176 | 2020-07-25T17:19:01 | 2020-07-25T17:19:01 | 214,287,587 | 0 | 0 | null | 2022-12-10T09:56:49 | 2019-10-10T21:18:57 | TypeScript | UTF-8 | Python | false | false | 937 | py | from light.effect.partial_effect import PartialEffect
from light.effect.resolved_effect import ResolvedEffect
from util.color_transition import ColorTransition
from light.effect.effect_priority import EffectPriority
class TripleLinearColorTransition(PartialEffect):
def __init__(self, srcRgb, dstRgb1, dstRgb2, duration):
super().__init__(0)
self.src = srcRgb
self.dst1 = dstRgb1
self.dst2 = dstRgb2
self.duration = duration
def getEffect(self, t):
dt = t - self.startTime
tNorm = dt / self.duration
dst = self.dst1 if dt <= 0.5 else self.dst2
src = self.src if dt <= 0.5 else self.dst1
tNormAdjusted = (tNorm * 2) if dt <= 0.5 else ((tNorm - 0.5) * 2)
return ResolvedEffect.createRgbw(ColorTransition.linear(tNormAdjusted, src, dst))
def isTemporal(self):
return False
def isComplete(self, t):
return False | [
"="
] | = |
fa587f4efbb32030d5aeb6a0a371f9f0cddf5bad | d9296d3b420d8f5c1aeca094d00dd6bc38a3d57d | /blog/migrations/0007_auto_20201007_0027.py | af9d531851ee81b2ee2d718dbd0c0b433ae67098 | [] | no_license | Anthony88888/mysite | 57f5f40530886b12cf1364c10c6206983b022c6c | 7130715ef3acac054b96fa22dcf19fec1f31e019 | refs/heads/master | 2023-01-09T12:15:11.720225 | 2020-10-25T14:48:35 | 2020-10-25T14:48:35 | 305,168,092 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 396 | py | # Generated by Django 2.0.13 on 2020-10-06 16:27
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('blog', '0006_auto_20201006_1456'),
]
operations = [
migrations.RemoveField(
model_name='readnum',
name='blog',
),
migrations.DeleteModel(
name='ReadNum',
),
]
| [
"admin@example.com"
] | admin@example.com |
fc47543b429550c01bcea133e396d425c978ea1f | 335c8167b2093359113abbd2b2ad6561e46f28f9 | /myereporter/report_display.py | 3692dc6e7596d69f3b53194d1138530ddd132a2c | [] | no_license | mdornseif/my_ereporter | ce67fadc512153327aa289b57e4abdc34065bdcd | 4c362d356d3e674cf47175ce7977a1a794ff1a9f | refs/heads/master | 2020-05-30T21:59:41.963554 | 2014-02-12T07:40:08 | 2014-02-12T07:40:08 | 3,323,415 | 0 | 0 | null | 2014-02-12T07:40:09 | 2012-02-01T09:14:12 | Python | UTF-8 | Python | false | false | 3,276 | py | #!/usr/bin/env python
#
# Copyright 2007 Google Inc.
# Copyright 2012 Dr. Maximillian Dornseif
#
# 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.
#
"""Displays exception reports.
See google/appengine/ext/ereporter/__init__.py for usage details.
"""
import datetime
import itertools
import os
import re
from xml.sax import saxutils
from google.appengine.api import mail
from google.appengine.ext import db
from google.appengine.ext import ereporter
from google.appengine.ext import webapp
from google.appengine.ext.webapp import _template
from google.appengine.ext.webapp.util import run_wsgi_app
class ReportGenerator(webapp.RequestHandler):
"""Handler class to generate and email an exception report."""
DEFAULT_MAX_RESULTS = 100
def __init__(self, *args, **kwargs):
super(ReportGenerator, self).__init__(*args, **kwargs)
def GetQuery(self):
"""Creates a query object that will retrieve the appropriate exceptions.
Returns:
A query to retrieve the exceptions required.
"""
q = ereporter.ExceptionRecord.all()
q.filter('major_version =', self.major_version)
q.filter('date >=', self.yesterday)
return q
def GenerateReport(self, exceptions):
"""Generates an HTML exception report.
Args:
exceptions: A list of ExceptionRecord objects. This argument will be
modified by this function.
Returns:
An HTML exception report.
"""
exceptions.sort(key=lambda e: (e.minor_version, -e.count))
versions = [(minor, list(excs)) for minor, excs
in itertools.groupby(exceptions, lambda e: "%s.%s" % (e.major_version, e.minor_version))]
template_values = {
'version_filter': self.version_filter,
'version_count': len(versions),
'exception_count': sum(len(excs) for _, excs in versions),
'occurrence_count': sum(y.count for x in versions for y in x[1]),
'app_id': self.app_id,
'major_version': self.major_version,
'date': self.yesterday,
'versions': versions,
}
path = os.path.join(os.path.dirname(__file__), 'templates', 'report.html')
return _template.render(path, template_values)
def get(self):
self.version_filter = 'all'
self.app_id = os.environ['APPLICATION_ID']
version = os.environ['CURRENT_VERSION_ID']
self.major_version, self.minor_version = version.rsplit('.', 1)
self.minor_version = int(self.minor_version)
self.yesterday = datetime.date.today() - datetime.timedelta(days=1)
exceptions = self.GetQuery().fetch(100)
report = self.GenerateReport(exceptions)
self.response.out.write(report)
application = webapp.WSGIApplication([('.*', ReportGenerator)])
def main():
run_wsgi_app(application)
if __name__ == '__main__':
main()
| [
"md@hudora.de"
] | md@hudora.de |
57d0f000bba622f8ae58fd6246384fdb6171a4c2 | 0e25538b2f24f1bc002b19a61391017c17667d3d | /xsqlps/win_xsqlhaendpoint.py | d63cff41b4b48b8eaa76153f1709cb850bf709e7 | [] | no_license | trondhindenes/Ansible-Auto-Generated-Modules | 725fae6ba9b0eef00c9fdc21179e2500dfd6725f | efa6ac8cd2b545116f24c1929936eb8cc5c8d337 | refs/heads/master | 2020-04-06T09:21:00.756651 | 2016-10-07T07:08:29 | 2016-10-07T07:08:29 | 36,883,816 | 12 | 2 | null | null | null | null | UTF-8 | Python | false | false | 2,205 | py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# <COPYRIGHT>
# <CODEGENMETA>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# this is a windows documentation stub. actual code lives in the .ps1
# file of the same name
DOCUMENTATION = '''
---
module: win_xsqlhaendpoint
version_added:
short_description: Generated from DSC module xsqlps version 1.4.0.0 at 07.10.2016 03.07.37
description:
- SQL module.
options:
AllowedUser:
description:
-
required: True
default:
aliases: []
InstanceName:
description:
-
required: True
default:
aliases: []
Name:
description:
-
required: True
default:
aliases: []
PortNumber:
description:
-
required: False
default:
aliases: []
PsDscRunAsCredential_username:
description:
-
required: False
default:
aliases: []
PsDscRunAsCredential_password:
description:
-
required: False
default:
aliases: []
AutoInstallModule:
description:
- If true, the required dsc resource/module will be auto-installed using the Powershell package manager
required: False
default: false
aliases: []
choices:
- true
- false
AutoConfigureLcm:
description:
- If true, LCM will be auto-configured for directly invoking DSC resources (which is a one-time requirement for Ansible DSC modules)
required: False
default: false
aliases: []
choices:
- true
- false
| [
"trond@hindenes.com"
] | trond@hindenes.com |
8cebe11dc2d30677fef4d45822d56ad632eb8314 | 277290f8cd6cc5bcb77faaf69a045f5074a988e5 | /reveal-cards-in-incr.py | db0e4830da4c2241050bac7bada38bfbe9788efc | [] | no_license | shankarkrishnamurthy/problem-solving | aed0252d9ca6d6b51e9a7d8d5e648343b4abf322 | f9bc1db1cc99b10a87a2fa51869924aa10df4c99 | refs/heads/master | 2023-03-20T18:48:45.107058 | 2023-03-06T03:24:53 | 2023-03-06T03:24:53 | 123,035,515 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 665 | py | class Solution(object):
def deckRevealedIncreasing(self, d):
"""
:type deck: List[int]
:rtype: List[int]
"""
n = len(d)
d.sort()
il, c, i = range(n),0,0
ans = [0]*n
while c < n-1:
ans[il[i]] = d[c]
i += 2
c += 1
il.append(il[i-1])
ans[il[-1]] = d[c]
return ans
print Solution().deckRevealedIncreasing([17])
print Solution().deckRevealedIncreasing([17,12])
print Solution().deckRevealedIncreasing([17,7,12])
print Solution().deckRevealedIncreasing([17,13,11,2,3,5,7])
print Solution().deckRevealedIncreasing([17,13,11,2,5,7])
| [
"kshan_77@yahoo.com"
] | kshan_77@yahoo.com |
d3bc11a9aab7b31c0267628c2f3dd7308ec7e8e1 | 9743d5fd24822f79c156ad112229e25adb9ed6f6 | /xai/brain/wordbase/nouns/_candling.py | 0473570aa258d1a60c7225076a74ed253110aa0b | [
"MIT"
] | permissive | cash2one/xai | de7adad1758f50dd6786bf0111e71a903f039b64 | e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6 | refs/heads/master | 2021-01-19T12:33:54.964379 | 2017-01-28T02:00:50 | 2017-01-28T02:00:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 240 | py |
from xai.brain.wordbase.nouns._candle import _CANDLE
#calss header
class _CANDLING(_CANDLE, ):
def __init__(self,):
_CANDLE.__init__(self)
self.name = "CANDLING"
self.specie = 'nouns'
self.basic = "candle"
self.jsondata = {}
| [
"xingwang1991@gmail.com"
] | xingwang1991@gmail.com |
897ddd4b655379b68902d88d5eb70456f63dc56b | d554b1aa8b70fddf81da8988b4aaa43788fede88 | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4149/codes/1638_869.py | 76e2f745bcfc37ccead6e31a4844f49410cd0660 | [] | no_license | JosephLevinthal/Research-projects | a3bc3ca3b09faad16f5cce5949a2279cf14742ba | 60d5fd6eb864a5181f4321e7a992812f3c2139f9 | refs/heads/master | 2022-07-31T06:43:02.686109 | 2020-05-23T00:24:26 | 2020-05-23T00:24:26 | 266,199,309 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 133 | py | preco=float(input("digite o valor: "))
if(preco>=200):
pago= preco-((5*preco)/100)
print(round(pago,2))
else:
print(preco) | [
"jvlo@icomp.ufam.edu.br"
] | jvlo@icomp.ufam.edu.br |
701d53be3b220a15773d4bae7c650509950ea474 | 5daece6b3ee3e928d101c8614dbcb90a8569626f | /files/Exercícios Livro/c05e01.py | bc282a6143d6bb605b74864d13352c4e1506c4a1 | [
"MIT"
] | permissive | heltonricardo/estudo-python | 506b400af93039bbdca70e1bc604c588fae62af1 | e82eb8ebc15378175b03d367a6eeea66e8858cff | refs/heads/master | 2022-12-24T03:10:52.202102 | 2020-10-06T13:58:05 | 2020-10-06T13:58:05 | 294,190,313 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 216 | py | def somatorio(n):
s = 0
for i in range(1, n + 1):
s += i
return s
valor = int(float(input('Entre um valor inteiro: ')))
print('A soma de 1 até {} é {}'.format(valor, somatorio(valor)))
input()
| [
"50843386+heltonr13@users.noreply.github.com"
] | 50843386+heltonr13@users.noreply.github.com |
63b8ad3ebadc2a5c26750c091d69b542c6a4c249 | 06f7ffdae684ac3cc258c45c3daabce98243f64f | /vsts/vsts/gallery/v4_0/models/publisher.py | 6850a11a0f84d8920e40a5e224ddaa6f1d608c0b | [
"MIT",
"LicenseRef-scancode-generic-cla"
] | permissive | kenkuo/azure-devops-python-api | 7dbfb35f1c9637c9db10207824dd535c4d6861e8 | 9ac38a97a06ee9e0ee56530de170154f6ed39c98 | refs/heads/master | 2020-04-03T17:47:29.526104 | 2018-10-25T17:46:09 | 2018-10-25T17:46:09 | 155,459,045 | 0 | 0 | MIT | 2018-10-30T21:32:43 | 2018-10-30T21:32:42 | null | UTF-8 | Python | false | false | 2,466 | py | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# Generated file, DO NOT EDIT
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------------------------
from msrest.serialization import Model
class Publisher(Model):
"""Publisher.
:param display_name:
:type display_name: str
:param email_address:
:type email_address: list of str
:param extensions:
:type extensions: list of :class:`PublishedExtension <gallery.v4_0.models.PublishedExtension>`
:param flags:
:type flags: object
:param last_updated:
:type last_updated: datetime
:param long_description:
:type long_description: str
:param publisher_id:
:type publisher_id: str
:param publisher_name:
:type publisher_name: str
:param short_description:
:type short_description: str
"""
_attribute_map = {
'display_name': {'key': 'displayName', 'type': 'str'},
'email_address': {'key': 'emailAddress', 'type': '[str]'},
'extensions': {'key': 'extensions', 'type': '[PublishedExtension]'},
'flags': {'key': 'flags', 'type': 'object'},
'last_updated': {'key': 'lastUpdated', 'type': 'iso-8601'},
'long_description': {'key': 'longDescription', 'type': 'str'},
'publisher_id': {'key': 'publisherId', 'type': 'str'},
'publisher_name': {'key': 'publisherName', 'type': 'str'},
'short_description': {'key': 'shortDescription', 'type': 'str'}
}
def __init__(self, display_name=None, email_address=None, extensions=None, flags=None, last_updated=None, long_description=None, publisher_id=None, publisher_name=None, short_description=None):
super(Publisher, self).__init__()
self.display_name = display_name
self.email_address = email_address
self.extensions = extensions
self.flags = flags
self.last_updated = last_updated
self.long_description = long_description
self.publisher_id = publisher_id
self.publisher_name = publisher_name
self.short_description = short_description
| [
"tedchamb@microsoft.com"
] | tedchamb@microsoft.com |
78b90c5ccf52433ac0fa36490bf09ee3a9537df0 | b288e79bc4aa3a3ea2e11b2fe5d9d707fc36b916 | /wen_python_18/color_term.py | bff244b69e87f087214b38f7a0db261cf928d44f | [] | no_license | pylinx64/wen_python_18 | 88e780e7045419a8c14d26f1dbb42c0d98e8856c | 173f21e046904cdc24f846e19004d2a007deb2d3 | refs/heads/main | 2023-04-17T19:36:37.485510 | 2021-05-05T10:07:41 | 2021-05-05T10:07:41 | 336,603,726 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 194 | py | import tqdm, random, time
progresBar = tqdm.tqdm(range(0, 100), desc='Loading virus...', ascii=True, bar_format='{desc}: {bar} {percentage:3.0f}% ')
for x in progresBar:
time.sleep(.05)
| [
"noreply@github.com"
] | pylinx64.noreply@github.com |
baae2fe0650b8a44e41fd46c23db0f242cd1e344 | eef2fea06f1a18b410e51dcae2ce602093ce086f | /string Valiadtor method 2.py | 9eb7c9062a78871b4fb0a2cf0e4fefc1060b6ffb | [] | no_license | vkgitmaster/HackerRank_Practice | 43de4723c31788a56b848d30ea6e69a95c305bd8 | e774a3bfedd59519c3cbb5369d472727b87655e5 | refs/heads/master | 2023-01-19T21:29:03.295968 | 2020-12-05T06:44:22 | 2020-12-05T06:44:22 | 318,719,167 | 0 | 0 | null | 2020-12-05T06:30:10 | 2020-12-05T06:30:10 | null | UTF-8 | Python | false | false | 245 | py | import re
if __name__ == '__main__':
s = input()
print(bool(re.search('[a-zA-Z0-9]', s)))
print(bool(re.search('[a-zA-Z]', s)))
print(bool(re.search('[0-9]', s)))
print(bool(re.search('[a-z]', s)))
print(bool(re.search('[A-Z]', s))) | [
"VKvision@venu.com"
] | VKvision@venu.com |
07800d09d0b326125fa78d95f54f9f1796ed958a | 8d014a0120864b42748ef63dddfa3c733370118c | /layint_api/models/user_groups.py | b9ba7c7bbbe6c943e647dc66a058e83bdcca50f2 | [
"LicenseRef-scancode-unknown",
"Apache-2.0"
] | permissive | LayeredInsight/layint_api_python | 3a6cf0bf62219f09010b828d7e02c2f3852a6f6f | a5c9a5b24098bd823c5102b7ab9e4745432f19b4 | refs/heads/develop | 2020-03-27T05:43:35.831400 | 2018-10-15T22:28:54 | 2018-10-15T22:28:54 | 146,044,385 | 0 | 0 | Apache-2.0 | 2018-10-15T22:28:55 | 2018-08-24T22:11:08 | Python | UTF-8 | Python | false | false | 2,729 | py | # coding: utf-8
"""
Layered Insight Assessment, Compliance, Witness & Control
LI Assessment & Compliance performs static vulnerability analysis, license and package compliance. LI Witness provides deep insight and analytics into containerized applications. Control provides dynamic runtime security and analytics for containerized applications. You can find out more about the Layered Insight Suite at [http://layeredinsight.com](http://layeredinsight.com).
OpenAPI spec version: 0.10
Contact: help@layeredinsight.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class UserGroups(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 = {
}
attribute_map = {
}
def __init__(self):
"""
UserGroups - a model defined in Swagger
"""
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, UserGroups):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
| [
"Scott Oberg"
] | Scott Oberg |
639a77b123efd4d955c07a5f637e1a9b416ce673 | 040fbf650a95564c92632189687bc2a924d0a327 | /gmn/src/d1_gmn/app/views/headers.py | 0c776cd55fcf1fd7dd1c1882b5766aa4a8455d0a | [
"Apache-2.0"
] | permissive | vchendrix/d1_python | 97b4e9671ae0642fdfa94054e270d44bcf1b6b6b | 0fa85c3a8de158d0225bd7428ddab3cf53a3d3e7 | refs/heads/master | 2020-03-20T22:25:55.987123 | 2018-06-15T18:33:06 | 2018-06-15T18:33:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,446 | py | # -*- coding: utf-8 -*-
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2016 DataONE
#
# 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.
"""Read and write HTTP Headers
"""
import datetime
import d1_gmn.app
import d1_gmn.app.auth
import d1_gmn.app.db_filter
import d1_gmn.app.did
import d1_gmn.app.event_log
import d1_gmn.app.models
import d1_gmn.app.psycopg_adapter
import d1_gmn.app.revision
import d1_gmn.app.sysmeta
import d1_gmn.app.util
import d1_gmn.app.views.slice
import d1_gmn.app.views.util
import d1_common.const
import d1_common.date_time
import d1_common.type_conversions
import d1_common.types
import d1_common.types.dataoneTypes
import d1_common.types.dataoneTypes_v1_1
import d1_common.types.dataoneTypes_v2_0
import d1_common.types.exceptions
import d1_common.url
import d1_common.xml
def add_sciobj_properties_headers_to_response(response, sciobj):
response['Content-Length'] = sciobj.size
response['Content-Type'] = d1_gmn.app.views.util.content_type_from_format(
sciobj.format.format
)
response['Last-Modified'] = d1_common.date_time.http_datetime_str_from_dt(
d1_common.date_time.normalize_datetime_to_utc(sciobj.modified_timestamp)
)
response['DataONE-GMN'] = d1_gmn.__version__
response['DataONE-FormatId'] = sciobj.format.format
response['DataONE-Checksum'] = '{},{}'.format(
sciobj.checksum_algorithm.checksum_algorithm, sciobj.checksum
)
response['DataONE-SerialVersion'] = sciobj.serial_version
add_http_date_header_to_response(response)
if d1_common.url.isHttpOrHttps(sciobj.url):
response['DataONE-Proxy'] = sciobj.url
if sciobj.obsoletes:
response['DataONE-Obsoletes'] = sciobj.obsoletes.did
if sciobj.obsoleted_by:
response['DataONE-ObsoletedBy'] = sciobj.obsoleted_by.did
sid = d1_gmn.app.revision.get_sid_by_pid(sciobj.pid.did)
if sid:
response['DataONE-SeriesId'] = sid
def add_http_date_header_to_response(response, date_time=None):
response['Date'] = d1_common.date_time.http_datetime_str_from_dt(
d1_common.date_time.normalize_datetime_to_utc(date_time)
if date_time else datetime.datetime.utcnow()
)
def add_cors_headers_to_response(response, method_list):
"""Add Cross-Origin Resource Sharing (CORS) headers to response
- {method_list} is a list of HTTP methods that are allowed for the endpoint
that was called. It should not include "OPTIONS", which is included
automatically since it's allowed for all endpoints.
"""
opt_method_list = ','.join(method_list + ['OPTIONS'])
response['Allow'] = opt_method_list
response['Access-Control-Allow-Methods'] = opt_method_list
response['Access-Control-Allow-Origin'] = '*'
response['Access-Control-Allow-Headers'] = 'Authorization'
response['Access-Control-Allow-Credentials'] = 'true'
| [
"git@dahlsys.com"
] | git@dahlsys.com |
df5d69817ac04c7ca1a7fd5955756c39b6775ff7 | 63ace5832d453e325681d02f6496a0999b72edcb | /examples/monero.py | a8fe6f2b129f8e624e70388c97b8227a4626792e | [
"MIT"
] | permissive | ebellocchia/bip_utils | c9ec04c687f4247e57434319e36b2abab78f0b32 | d15c75ddd74e4838c396a0d036ef6faf11b06a4b | refs/heads/master | 2023-09-01T13:38:55.567370 | 2023-08-16T17:04:14 | 2023-08-16T17:04:14 | 251,130,186 | 244 | 88 | MIT | 2023-08-23T13:46:19 | 2020-03-29T20:42:48 | Python | UTF-8 | Python | false | false | 1,284 | py | """Example of keys derivation for Monero (same addresses of official wallet)."""
import binascii
from bip_utils import Monero, MoneroMnemonicGenerator, MoneroSeedGenerator, MoneroWordsNum
# Generate random mnemonic
mnemonic = MoneroMnemonicGenerator().FromWordsNumber(MoneroWordsNum.WORDS_NUM_25)
print(f"Mnemonic string: {mnemonic}")
# Generate seed from mnemonic
seed_bytes = MoneroSeedGenerator(mnemonic).Generate()
# Construct from seed
monero = Monero.FromSeed(seed_bytes)
# Print keys
print(f"Monero private spend key: {monero.PrivateSpendKey().Raw().ToHex()}")
print(f"Monero private view key: {monero.PrivateViewKey().Raw().ToHex()}")
print(f"Monero public spend key: {monero.PublicSpendKey().RawCompressed().ToHex()}")
print(f"Monero public view key: {monero.PublicViewKey().RawCompressed().ToHex()}")
# Print primary address
print(f"Monero primary address: {monero.PrimaryAddress()}")
# Print integrated address
payment_id = binascii.unhexlify(b"d6f093554c0daa94")
print(f"Monero integrated address: {monero.IntegratedAddress(payment_id)}")
# Print the first 5 subaddresses for account 0 and 1
for acc_idx in range(2):
for subaddr_idx in range(5):
print(f"Subaddress (account: {acc_idx}, index: {subaddr_idx}): {monero.Subaddress(subaddr_idx, acc_idx)}")
| [
"54482000+ebellocchia@users.noreply.github.com"
] | 54482000+ebellocchia@users.noreply.github.com |
23205934f3e45edba56c28705da6439fac77b2a5 | f0d713996eb095bcdc701f3fab0a8110b8541cbb | /nn7JKRBfq8iDcX8ZB_15.py | f35f0f8e1dfbbfd7b790a500d47aa08cf05efda7 | [] | 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 | 452 | py | """
Write a function that returns a **lambda expression** , which transforms its
input by adding a particular `suffix` at the end.
### Examples
add_ly = add_suffix("ly")
add_ly("hopeless") ➞ "hopelessly"
add_ly("total") ➞ "totally"
add_less = add_suffix("less")
add_less("fear") ➞ "fearless"
add_less("ruth") ➞ "ruthless"
### Notes
N/A
"""
def add_suffix(suffix):
return lambda x: x + suffix
| [
"daniel.reich@danielreichs-MacBook-Pro.local"
] | daniel.reich@danielreichs-MacBook-Pro.local |
3d240c0fdda9cbe03630ab8703bc3fb487c7fd6d | 2296699c10d8e01da0b1ac079d67e87c8e4f766a | /code/objects.py | 5d4a81ccbfc9808f5a8f072b6bfeb0fcd08a3a82 | [
"Apache-2.0"
] | permissive | marcverhagen/semcor | 8d18060885b7a8a1aca1d7987577cbe0cf2cecc1 | d2ff7867880029800c1524444533843510cd78a6 | refs/heads/master | 2021-08-16T21:34:36.868125 | 2020-03-02T18:55:52 | 2020-03-02T18:55:52 | 162,839,926 | 1 | 2 | null | null | null | null | UTF-8 | Python | false | false | 4,998 | py | """
"""
from __future__ import print_function
import os
from ansi import BOLD, BLUE, GREEN, GREY, END
class SemcorObject(object):
def is_paragraph(self):
return False
def is_sentence(self):
return False
def is_word_form(self):
return False
def is_punctuation(self):
return False
class Paragraph(SemcorObject):
def __init__(self, pid):
self.pid = pid # <string>
self.sentences = []
def add_sentence(self, sent):
self.sentences.append(sent)
def is_paragraph(self):
return True
def collect_forms(self, forms):
"""Collect all instances of WordForm that have a sense."""
for s in self.sentences:
s.collect_forms(forms)
def pp(self):
print("<para %s>" % self.pid)
for s in self.sentences:
s.pp()
class Sentence(SemcorObject):
def __init__(self, semcor_file, para, sid):
self.fname = os.path.basename(semcor_file.fname)
self.para = para
self.pid = para.pid # <string>
self.sid = sid # <string>
self.elements = []
def __str__(self):
return "<Sentence %s:%s with %d wfs>" % (self.fname, self.sid, len(self.elements))
def is_sentence(self):
return True
def get_element(self, n):
"""Returns the WordForm or the Punctuation instance at position n of the list of
elements in the sentence, returns None if there is no such index."""
try:
return self.elements[n]
except IndexError:
return None
def add_element(self, element):
# note that an element will either be an instance of WordForm or an
# instance of Punctuation
self.elements.append(element)
def collect_forms(self, forms):
for wf in self.elements:
if wf.is_word_form() and wf.has_sense():
forms.append(wf)
def as_string(self):
return ' '.join([t.text for t in self.elements])
def pp(self, highlight=None):
print("%s%s%s-%s%s: " % (GREY, GREEN, self.fname, self.sid, END), end='')
for wf in self.elements:
if wf.is_word_form() and highlight == wf.position:
print(BOLD + BLUE + wf.text + END, end=' ')
#elif wf.has_sense():
# print(BLUE+wf.text+END, end=' ')
else:
print(wf.text, end=' ')
print()
class WordForm(SemcorObject):
"""Semcor word forms have a lemma, a part-of-speech, a wordnet sense and a
lexical sense (we are for now ignoring other attributes). Word forms are
initiated from a tag like the following.
<wf cmd=done pos=VB lemma=say wnsn=1 lexsn=2:32:00::>said</wf>
Note that these word forms can have multiple tokens and those are not just
for names, for example primary_election is a word form. Some word forms do
not have senses associated with them, for them we just have POS and the
text."""
def __init__(self, para, sent, position, tag):
self.para = para # instance of Paragraph
self.sent = sent # instance of Sentence
self.position = position # position in the sentence
self.pid = para.pid
self.sid = sent.sid
self.pos = tag.get('pos')
self.rdf = tag.get('rdf')
self.pn = tag.get('pn')
self.lemma = tag.get('lemma')
self.wnsn = tag.get('wnsn')
self.lexsn = tag.get('lexsn')
self.text = tag.getText()
self.synset = None
self.keys = tuple(tag.__dict__['attrs'].keys()) # for statistics
def __str__(self):
if self.wnsn is None:
return "<wf %s %s>" % (self.pos, self.text)
else:
return "<wf %s %s %s %s>" % (self.pos, self.lemma, self.wnsn, self.lexsn)
def sense(self):
return "%s%%%s" % (self.lemma, self.lexsn) if self.has_sense() else None
def is_word_form(self):
return True
def is_nominal(self):
return self.pos.startswith('NN')
def is_common_noun(self):
return self.pos in ('NN', 'NNS')
def has_sense(self):
return self.wnsn is not None and self.lexsn is not None
def kwic(self, context):
kw = self.sent.elements[self.position].text
left = self.sent.elements[:self.position]
right = self.sent.elements[self.position+1:]
left = ' '.join([t.text for t in left])
right = ' '.join([t.text for t in right])
left = left[-context:]
right = right[:context]
return (left, kw, right)
class Punctuation(SemcorObject):
def __init__(self, tag):
self.text = tag.getText()
self.keys = tuple()
def __str__(self):
return "<Punctuation %s>" % self.text
def is_punctuation(self):
return True
def has_sense(self):
return False
def sense(self):
return None
| [
"marc@cs.brandeis.edu"
] | marc@cs.brandeis.edu |
ef5e9a18a00128b006326db88a45a5ba9a3a18b8 | 487ce91881032c1de16e35ed8bc187d6034205f7 | /codes/CodeJamCrawler/16_1_1_neat/16_1_1_Lukasod_problem1.py | 26c9273e42e32c0821136127856ef4a61e00d5be | [] | no_license | DaHuO/Supergraph | 9cd26d8c5a081803015d93cf5f2674009e92ef7e | c88059dc66297af577ad2b8afa4e0ac0ad622915 | refs/heads/master | 2021-06-14T16:07:52.405091 | 2016-08-21T13:39:13 | 2016-08-21T13:39:13 | 49,829,508 | 2 | 0 | null | 2021-03-19T21:55:46 | 2016-01-17T18:23:00 | Python | UTF-8 | Python | false | false | 251 | py |
T = int(input().strip())
for i in range(T):
S = input().strip()
words = [S[0]]
for letter in S[1:]:
words = [letter + j for j in words] + [j + letter for j in words]
print("Case #" + str(i + 1) + ": " + sorted(words)[-1])
| [
"[dhuo@tcd.ie]"
] | [dhuo@tcd.ie] |
8bf29bb739823ba7eace53be017b716d5a54f108 | de24f83a5e3768a2638ebcf13cbe717e75740168 | /moodledata/vpl_data/152/usersdata/274/66550/submittedfiles/swamee.py | 5865cf6df59fa8f2d3a45f20a805d5a79ad2d0f9 | [] | no_license | rafaelperazzo/programacao-web | 95643423a35c44613b0f64bed05bd34780fe2436 | 170dd5440afb9ee68a973f3de13a99aa4c735d79 | refs/heads/master | 2021-01-12T14:06:25.773146 | 2017-12-22T16:05:45 | 2017-12-22T16:05:45 | 69,566,344 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 372 | py | # -*- coding: utf-8 -*-
import math
#COMECE SEU CÓDIGO AQUI
#ENTRADA
f = float(input("Valor de f: "))
L = float(input("Valor de L: "))
Q = float(input("Valor de Q: "))
DeltaH = float(input("Valor de delta H: "))
V = float(input("valor de V: "))
#PROCESSAMENTO
D = ((8*f*L*(Q**2))/((3.14159**2)*9.81*DeltaH))**(1/5)
Rey = (4*Q)/(3.14159*D*V)
K = (0.25)/math.log10(0.000000 | [
"rafael.mota@ufca.edu.br"
] | rafael.mota@ufca.edu.br |
6bc1d0251fa9f3b44c2b49da8e8613f888c65b93 | c1a3d3b60441125605bc8bc42ede890808344b53 | /utils.py | 70943c1f2252d425d6ea863d166f7d35b27cf49a | [
"MIT"
] | permissive | learningequality/sushi-chef-readwritethink | a5c4a0944e364aaa9a8d15e7dd29bbe83f928be4 | 261191fd35b81774cc60a19ae8c27f8fa04fc352 | refs/heads/master | 2021-05-03T11:56:40.036853 | 2019-02-22T21:52:49 | 2019-02-22T21:52:49 | 120,490,074 | 0 | 1 | MIT | 2019-02-22T21:52:50 | 2018-02-06T16:42:03 | Python | UTF-8 | Python | false | false | 3,079 | py | import json
import os
from pathlib import Path
import ntpath
from ricecooker.utils import downloader
import requests
from ricecooker.utils.caching import CacheForeverHeuristic, FileCache, CacheControlAdapter
#from le_utils.constants import licenses, content_kinds, file_formats
DATA_DIR = "chefdata"
BASE_URL = "http://www.readwritethink.org"
sess = requests.Session()
cache = FileCache('.webcache')
basic_adapter = CacheControlAdapter(cache=cache)
forever_adapter = CacheControlAdapter(heuristic=CacheForeverHeuristic(), cache=cache)
sess.mount('http://', basic_adapter)
sess.mount(BASE_URL, forever_adapter)
def save_thumbnail(url, save_as):
THUMB_DATA_DIR = build_path([DATA_DIR, 'thumbnail'])
filepath = os.path.join(THUMB_DATA_DIR, save_as)
try:
document = downloader.read(url, loadjs=False, session=sess)
except requests.exceptions.ConnectionError as e:
return None
else:
with open(filepath, 'wb') as f:
f.write(document)
return filepath
def if_file_exists(filepath):
file_ = Path(filepath)
return file_.is_file()
def if_dir_exists(filepath):
file_ = Path(filepath)
return file_.is_dir()
def get_name_from_url(url):
head, tail = ntpath.split(url)
params_index = tail.find("&")
if params_index != -1:
tail = tail[:params_index]
basename = ntpath.basename(url)
params_b_index = basename.find("&")
if params_b_index != -1:
basename = basename[:params_b_index]
return tail or basename
def get_name_from_url_no_ext(url):
path = get_name_from_url(url)
path_split = path.split(".")
if len(path_split) > 1:
name = ".".join(path_split[:-1])
else:
name = path_split[0]
return name
def build_path(levels):
path = os.path.join(*levels)
if not if_dir_exists(path):
os.makedirs(path)
return path
def remove_links(content):
if content is not None:
for link in content.find_all("a"):
link.replaceWithChildren()
def remove_iframes(content):
if content is not None:
for iframe in content.find_all("iframe"):
iframe.extract()
def check_shorter_url(url):
shorters_urls = set(["bitly.com", "goo.gl", "tinyurl.com", "ow.ly", "ls.gd",
"buff.ly", "adf.ly", "bit.do", "mcaf.ee"])
index_init = url.find("://")
index_end = url[index_init+3:].find("/")
if index_init != -1:
if index_end == -1:
index_end = len(url[index_init+3:])
domain = url[index_init+3:index_end+index_init+3]
check = len(domain) < 12 or domain in shorters_urls
return check
def get_level_map(tree, levels):
actual_node = levels[0]
r_levels = levels[1:]
for children in tree.get("children", []):
if children["source_id"] == actual_node:
if len(r_levels) >= 1:
return get_level_map(children, r_levels)
else:
return children
def load_tree(path):
with open(path, 'r') as f:
tree = json.load(f)
return tree
| [
"mara80@gmail.com"
] | mara80@gmail.com |
04e50d536e1fc6d75dbe209cfb08969375b7d392 | 453e245dcb67a75f671d5e6067af13c21acd4f97 | /3.3 Pipeline/3-Pipeline_train.py | b72d3e1f52e2289f6b821df35479cad4f159bdcf | [] | no_license | ahmedatef1610/scikit-learn-library-for-machine-learning | c828f7510cd9a7df41e7aece31c08ea00d69bb4f | f12be8c1702c413742328a75f60b9b1f78a3c2d3 | refs/heads/main | 2023-04-05T01:23:46.970931 | 2021-04-12T09:16:26 | 2021-04-12T09:16:26 | 356,732,567 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,514 | py | #imports
import pandas as pd
import math
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import Ridge
from sklearn.linear_model import Lasso
from sklearn.metrics import mean_squared_error
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
#----------------------------------------------------
#import training dataset
train_df = pd.read_csv('path/3.3 Pipeline/train.csv', index_col='ID')
#see the columns in our data
print(train_df.info())
# take a look at the head of the dataset
print(train_df.head())
#create our X and y
X = train_df.drop('medv', axis=1)
y = train_df['medv']
print("="*50)
#----------------------------------------------------
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42, test_size=0.3)
#----------------------------------------------------
lr_model = LinearRegression()
lr_model.fit(X_train, y_train)
print('Training score: {}'.format(lr_model.score(X_train, y_train)))
print('Test score: {}'.format(lr_model.score(X_test, y_test)))
y_pred = lr_model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
rmse = math.sqrt(mse)
print('RMSE: {}'.format(rmse))
print("="*50)
#----------------------------------------------------
steps = [
('scalar', StandardScaler()),
('poly', PolynomialFeatures(degree=2)),
('model', LinearRegression())
]
pipeline = Pipeline(steps)
pipeline.fit(X_train, y_train)
print('Training score: {}'.format(pipeline.score(X_train, y_train)))
print('Test score: {}'.format(pipeline.score(X_test, y_test)))
print("="*50)
#----------------------------------------------------
steps = [
('scalar', StandardScaler()),
('poly', PolynomialFeatures(degree=2)),
('model', Ridge(alpha=10, fit_intercept=True))
]
ridge_pipe = Pipeline(steps)
ridge_pipe.fit(X_train, y_train)
print('Training Score: {}'.format(ridge_pipe.score(X_train, y_train)))
print('Test Score: {}'.format(ridge_pipe.score(X_test, y_test)))
print("="*50)
#----------------------------------------------------
steps = [
('scalar', StandardScaler()),
('poly', PolynomialFeatures(degree=2)),
('model', Lasso(alpha=0.3, fit_intercept=True))
]
lasso_pipe = Pipeline(steps)
lasso_pipe.fit(X_train, y_train)
print('Training score: {}'.format(lasso_pipe.score(X_train, y_train)))
print('Test score: {}'.format(lasso_pipe.score(X_test, y_test)))
print("="*50)
| [
"ahmedatef1610@gmail.com"
] | ahmedatef1610@gmail.com |
b7fb19e89546027400e590c2391e345744d9ed9f | c5157ce2aa61f46c3cc9e028e347587e1fb1669c | /gui/python/resistor/resistor.py | ae31903c80ac9c0f122b5955445e86834fb5c12b | [] | no_license | ramalho/atelier-labs | 2617706121fe9d67b646037e24a01380fa2ed53a | 57986c9a7cd20046f58885a0b75cb12ce3b57f16 | refs/heads/master | 2018-12-29T07:02:24.517423 | 2012-05-21T15:00:06 | 2012-05-21T15:00:06 | 4,394,443 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,577 | py |
'''
Source for color table:
http://en.wikipedia.org/wiki/Electronic_color_code
'''
COLORS = 'black brown red orange yellow green blue violet gray white'.split()
TOLERANCE = {
'brown':1, 'red':2,
'green':0.5, 'blue':0.25, 'violet':0.1, 'gray':0.05,
'gold':5, 'silver':10} #, None:20}
def identify(bands):
digits = []
for band in bands[:-2]: # all bands except last 2
digit = COLORS.index(band)
digits.append(str(digit))
digits = int(''.join(digits))
multiplier = COLORS.index(bands[-2]) # the band before last
value = digits * (10 ** multiplier)
tolerance = TOLERANCE.get(bands[-1],'unknown color') # last band
return '%s Ohms, %s%% tolerance' % (value, tolerance)
def self_test():
'''
Source for examples:
http://www.arar93.dsl.pipex.com/mds975/Content/components01.html
'''
# 4 bands
print identify('brown black brown silver'.split())
print identify('yellow violet red gold'.split())
print identify('orange orange yellow silver'.split())
# 5 bands
print identify('brown black black black silver'.split())
print identify('yellow violet black brown gold'.split())
print identify('orange orange black orange silver'.split())
def main():
from sys import argv
colors = argv[1:] # skip script name (argv[0])
if len(colors) in [4,5]:
print identify(colors)
else:
print 'usage:'
print argv[0], 'color1 color2 color3 color4 [color5]'
if __name__=='__main__':
# self_test()
main()
| [
"luciano@ramalho.org"
] | luciano@ramalho.org |
586739cc93832f34ce8cea5c5d8da2b31592e79d | 4640123092be222413fa233f09aa167d470de46c | /backend/home/migrations/0002_customtext_homepage.py | 067d3cd154523bff76fbb9dfd2c02c758968fed6 | [] | no_license | crowdbotics-apps/teste-27867 | 8ca166788cbd5aa90844d1953f0ad9a24910492c | df35af7b664cb3e2053f7a36c8c49268c681fe8b | refs/heads/master | 2023-05-18T21:34:38.469264 | 2021-06-09T14:06:19 | 2021-06-09T14:06:19 | 375,248,524 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 805 | py | # Generated by Django 2.2.20 on 2021-06-09 14:06
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('home', '0001_load_initial_data'),
]
operations = [
migrations.CreateModel(
name='CustomText',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=150)),
],
),
migrations.CreateModel(
name='HomePage',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('body', models.TextField()),
],
),
]
| [
"team@crowdbotics.com"
] | team@crowdbotics.com |
af5df5ff93860818117097f576bf7e0bba351909 | 7da5ac719e4c9ca9cb3735d0ade3106183d96ffe | /Projeto/IoTcity_services/server/server/mainserver/migrations/0011_auto_20170326_1126.py | 4495c2e03d5bda1dd2675a88eac680e3756c4a3d | [] | no_license | shanexia1818/IoTCity | a405c0921b417e5bb0a61966f9ca03a1f87147a7 | 3fe14b6918275684291f969fd6c3f69a7ee14a4c | refs/heads/master | 2020-08-07T21:08:38.811470 | 2018-09-10T11:10:56 | 2018-09-10T11:10:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 691 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2017-03-26 11:26
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mainserver', '0010_auto_20170326_1121'),
]
operations = [
migrations.AlterField(
model_name='alarm',
name='daysOfWeek',
field=models.ManyToManyField(blank=True, null=True, to='mainserver.day_week'),
),
migrations.AlterField(
model_name='alarm',
name='daysOfYear',
field=models.ManyToManyField(blank=True, null=True, to='mainserver.day_year'),
),
]
| [
"diogodanielsoaresferreira@ua.pt"
] | diogodanielsoaresferreira@ua.pt |
07bb3c5808d3f623a80fedb01254af988f185238 | dc67e70a303f265ee6cb4c1a2d61fe811053fb3d | /selection/product.py | de869f2e3445ce58bb4a1a06dc228759fec30dc1 | [] | no_license | cry999/AtCoder | d39ce22d49dfce805cb7bab9d1ff0dd21825823a | 879d0e43e3fac0aadc4d772dc57374ae72571fe6 | refs/heads/master | 2020-04-23T13:55:00.018156 | 2019-12-11T05:23:03 | 2019-12-11T05:23:03 | 171,214,066 | 0 | 0 | null | 2019-05-13T15:17:02 | 2019-02-18T04:24:01 | Python | UTF-8 | Python | false | false | 208 | py | def product(a: int, b: int) -> str:
p = a * b
return 'Even' if (p & 1) == 0 else 'Odd'
if __name__ == "__main__":
a, b = [int(s) for s in input().split()]
ans = product(a, b)
print(ans)
| [
"when.the.cry999@gmail.com"
] | when.the.cry999@gmail.com |
832af04f8bc176b508217819c0cbdbd290cf40b8 | 53fab060fa262e5d5026e0807d93c75fb81e67b9 | /backup/user_211/ch18_2020_03_15_15_02_54_971317.py | 5eba77fe63b13d26a8ca9bcedc6e427e50869e23 | [] | 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 | 171 | py | def verifica_idade(x):
if x>=21:
return 'Liberado EUA e BRASI'
elif x>=18:
return 'Liberado BRASIL'
else:
return 'Não está liberado'
| [
"you@example.com"
] | you@example.com |
83575457e3e658ca944654ab7e19947978f37d5a | 48a1156c4226a22be2cf271149be263adf9e5aef | /deploy/conf/web/gunicorn.conf.py | 719128c5cfafd05900bb0b3f2a57be46021c2ac5 | [
"MIT"
] | permissive | yacoma/auth-boilerplate | 945edb1174ab6009780a50a51ec2389bc12845a3 | 26c86f3b12edc7074a2fd78322e6005fdb1029cb | refs/heads/master | 2021-01-12T01:18:33.584773 | 2020-05-07T15:00:01 | 2020-05-07T15:00:01 | 78,362,662 | 6 | 1 | null | 2017-01-30T20:46:05 | 2017-01-08T18:36:46 | JavaScript | UTF-8 | Python | false | false | 178 | py | import multiprocessing
bind = "unix:/tmp/proxy_auth-boilerplate.yacoma.it.sock"
workers = multiprocessing.cpu_count() * 2 + 1
forwarded_allow_ips = "127.0.0.1, 188.165.237.135"
| [
"henri.hulski@gazeta.pl"
] | henri.hulski@gazeta.pl |
83c9631bd86714b665acd2c59700bdd2514e6d14 | 3920ab5c8deeaee370e6d28793fd7f2a9ca51188 | /jarbas/core/migrations/0012_use_date_not_datetime.py | e34719f67393411d12ed109e7ad9ec4829ae7e95 | [
"MIT"
] | permissive | MSLacerda/serenata-de-amor | 1fe5309ef3ba76f6f9f7d16986730fe96c0f0991 | 789586d8dea3768502ac7f2d5e333cf0692642ac | refs/heads/master | 2020-03-15T17:57:39.301809 | 2018-10-08T11:50:07 | 2018-10-08T11:50:07 | 132,273,013 | 2 | 0 | MIT | 2018-10-08T11:50:08 | 2018-05-05T18:12:13 | Python | UTF-8 | Python | false | false | 498 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-11-25 15:10
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0011_subquota_description_length'),
]
operations = [
migrations.AlterField(
model_name='document',
name='issue_date',
field=models.DateField(blank=True, null=True, verbose_name='Issue date'),
),
]
| [
"cuducos@gmail.com"
] | cuducos@gmail.com |
bfce843a80276eacca751eb4fbf2dfd3f9d62c1c | b8e92c8c672ce620390dc09d782db73baa09c8b9 | /app/remote_code_execution_engine/schemas/evaluation.py | aa896051996ccc61c1a4d6eb3006438ca9997acd | [
"MIT"
] | permissive | GeorgianBadita/remote-code-execution-engine | 8bf590d697c4e808b933f3b7010b57e8ee1161de | 4ac3ca7567cd89cc1f979622add81efa9edfea8f | refs/heads/main | 2023-03-01T02:55:20.285861 | 2021-02-07T01:10:53 | 2021-02-07T01:10:53 | 332,325,012 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 249 | py | from typing import List
from pydantic import BaseModel
class EvaluationResult(BaseModel):
submission_id: str
has_error: bool
results: List[bool]
out_of_resources: bool
out_of_time: bool
exit_code: int
raw_output: str
| [
"geo.badita@gmail.com"
] | geo.badita@gmail.com |
c23dd238375963e81a15419ebcf305bca0ac0e7c | 531a1714bc78e215308978b9536437f8e3dab2be | /tests/test_imports.py | 3235582dfbc8e29a7ea292cbccbc9c175eb2c758 | [
"MIT"
] | permissive | samirelanduk/geometrica | 6194d67bb73974028398eca02d9983bac4a1d23c | 322cc2fd52dee21b8ac2b10e45d5cf0bf7034e64 | refs/heads/master | 2021-01-21T05:17:07.131581 | 2017-05-13T11:33:12 | 2017-05-13T11:33:12 | 83,167,131 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 701 | py | from unittest import TestCase
import geometrica
class TrigFunctionsImportTests(TestCase):
def test_sine_law_imported(self):
from geometrica.trig import sine_law
self.assertIs(sine_law, geometrica.sine_law)
def test_cosine_law_imported(self):
from geometrica.trig import cosine_law
self.assertIs(cosine_law, geometrica.cosine_law)
class TransformationImportTests(TestCase):
def test_translate_imported(self):
from geometrica.transform import translate
self.assertIs(translate, geometrica.translate)
def test_rotate_imported(self):
from geometrica.transform import rotate
self.assertIs(rotate, geometrica.rotate)
| [
"sam.ireland.uk@gmail.com"
] | sam.ireland.uk@gmail.com |
f042cae327b157b337ea7090e4c0f42a846d3a24 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p03425/s982174788.py | 01f4ca7a93c6a1d56f1486e0fe88f23e34b32345 | [] | 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 | 506 | py | import sys
input = sys.stdin.readline
def main():
N = int(input())
L = {'M':0, 'A':0, 'R':0, 'C':0, 'H':0}
for i in range(N):
S = input().rstrip()
if S[0] in L:
L[S[0]] += 1
CNT = 0
i = 0
S = [0]*5
for k, v in L.items():
S[i] = v
i += 1
ans = 0
for p in range(3):
for q in range(p+1,4):
for r in range(q+1,5):
ans += S[p]*S[q]*S[r]
print(ans)
if __name__ == '__main__':
main() | [
"66529651+Aastha2104@users.noreply.github.com"
] | 66529651+Aastha2104@users.noreply.github.com |
c0dc054906d0ea98a80d0b8cf0dc3c4d8801327b | 958685165bfeb4122cc3473659a6d0c89c5cae95 | /crea8s_rental/__init__.py | 0c3addd67685eee41e9ce6025111b000ef3dfdcc | [] | no_license | tringuyen17588/OpenERP-7.0 | 44efee7735af65d960c5adb4b03a1a329f5c4a57 | 2486261e4d351d4f444ec31e74c6b0e36ed2fb82 | refs/heads/master | 2021-01-10T02:45:24.320726 | 2016-02-19T06:05:21 | 2016-02-19T06:05:21 | 52,064,852 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,115 | py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
#----------------------------------------------------------
#
#----------------------------------------------------------
import rental | [
"tri@crea8s.com"
] | tri@crea8s.com |
ec4e081afdb3147dd063ec36ddbbe72f3b0b469f | c3432a248c8a7a43425c0fe1691557c0936ab380 | /이것이_코딩테스트다_Book/알고리즘_유형별_기출문제/그리디문제/문자열_뒤집기.py | 33667852daacb3ae2fbf746b9e3e46275f51762c | [] | no_license | Parkyunhwan/BaekJoon | 13cb3af1f45212d7c418ecc4b927f42615b14a74 | 9a882c568f991c9fed3df45277f091626fcc2c94 | refs/heads/master | 2022-12-24T21:47:47.052967 | 2022-12-20T16:16:59 | 2022-12-20T16:16:59 | 232,264,447 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 194 | py | arr = list(input())
arr = [int(i) for i in arr]
prev = arr[0]
count = [0]*2
for a in arr:
if prev != a:
count[prev] += 1
prev = a
count[prev] += 1
print(min(count[0], count[1])) | [
"pyh8618@gmail.com"
] | pyh8618@gmail.com |
e2a476e8cea308b2437c174320358f74693af7b0 | 91c5a1865717e6757bbfec825d411f96dcf2e2e5 | /python/11_test/11.1/test_name_function.py | 3ec1f8804cd2f5da58ac67995a1b91dee886c1cb | [] | no_license | ydPro-G/Python_file | 6f676d1b66e21548f5fad8a715a1767344c2b0c4 | c035e7c344c3c224d55e33efc16ee941bc3d6ff2 | refs/heads/master | 2023-06-19T06:12:44.550778 | 2021-07-14T09:15:15 | 2021-07-14T09:15:15 | 261,126,468 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,921 | py | # 11 测试函数
print("\n11.1.1")
# 11.1.1 单元测试和测试用例
# 标准库中的模块unittest提供了代码测试工具
# 单元测试用于核实函数的某个方面没有问题
# 测试用例是一组单元测试,这些单元测试一起核实函数在各种情况下的行为都符合要求
# 全覆盖测试包含一整套单元测试
print('\n11.1.2')
# 可通过测试
# 导入模块unittest以及要测试的函数
# 创建一个继承unittest。TestCase的类,编写方法对函数行为不同方面进行测试
# 检查函数get_formatted_name()在给定名和姓时能否正常工作
# 导入模块unittest
# import unittest
# # 导入要测试的函数 get_formatted_name()
# from name_function import get_formatted_name
# # 编写一个类,用于包含针对函数的单元测试,类必须继承unittest.TestCase类
# class NamesTestCase(unittest.TestCase):
# """测试name_function.py"""
# def test_first_last_name(self):
# """能够正确处理像Janis Joplin这样的姓名吗?"""
# formatted_name = get_formatted_name('janis','joplin') # 调用要测试的函数,将结果存储到变量中
# self.assertEqual(formatted_name,'Janis Jopiln') # 断言方法[断言:相等]:调用了断言方法,并向它传递变量与预期要实现的结果,对变量与结果进行比较,如果相等就ok,不相等就报异常
# unittest.main()
print('\n11.1.3')
# 11.1.3 不能通过的测试
# 会报一个traceback(回溯),指出get_formatted_name有问题,缺少一个必要的位置实参
print('\n11.1.4')
# 11.1.4 测试未通过怎么办
# 检查刚对函数做出的修改,找出导致函数行为不符合预期的修改
print('\n11.1.5')
# 11.1.5 新测试
# 用于测试包含中间名的名字
# 在NamesTestCase类中添加一个新方法
import unittest
# 导入要测试的函数 get_formatted_name()
from name_function import get_formatted_name
# 编写一个类,用于包含针对函数的单元测试,类必须继承unittest.TestCase类
class NamesTestCase(unittest.TestCase):
"""测试name_function.py"""
def test_first_last_name(self):
"""能够正确处理像Janis Joplin这样的姓名吗?"""
formatted_name = get_formatted_name('janis','joplin')
self.assertEqual(formatted_name,'Janis Joplin') # 断言
# 方法名必须以test打头,这样才会自动运行
def test_first_last_middle_name(self):
"""能够正确处理像Wolfgang Amadeus Mozart这样的名字吗?"""
formatted_name = get_formatted_name('one','two','three')
self.assertEqual(formatted_name,'One Three Two') # 断言方法[断言:相等]:调用了断言方法,并向它传递变量与预期要实现的结果,对变量与结果进行比较,如果相等就ok,不相等就报异常
unittest.main()
| [
"46178109+ydPro-G@users.noreply.github.com"
] | 46178109+ydPro-G@users.noreply.github.com |
b9588ccb4ffb0e1bce066b2d810835e06acca12a | c505575568bca9d5f171be004c028613dc540244 | /project_name/settings/production.py | 2b584939118024da657b053e84d36eccda35e62b | [] | no_license | alfredo/django-template-plus | e699769015e4a4b5c533f4be2d3ef40779c9d660 | 2d58c6dc8d9493b69031df51ec2e29b13e70e57c | refs/heads/master | 2021-01-20T10:13:03.422330 | 2013-07-04T13:43:15 | 2013-07-04T13:43:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 285 | py | # Production settings for {{ project_name }}
from {{ project_name }}.settings import *
SITE_URL = 'http://{{ heroku_app }}.herokuapp.com'
# Basic authentication for Heroku
BASIC_WWW_AUTHENTICATION_USERNAME = ""
BASIC_WWW_AUTHENTICATION_PASSWORD = ""
BASIC_WWW_AUTHENTICATION = False
| [
"alfredo@madewithbyt.es"
] | alfredo@madewithbyt.es |
da236f1d91d055f79cea963d136dafe2b5ff99e3 | 53e58c213232e02250e64f48b97403ca86cd02f9 | /16/mc/ExoDiBosonResonances/EDBRTreeMaker/test/crab3_analysisM3000_R_0-7.py | 67b6fed624f209f701f450282bbd0022b699f73f | [] | no_license | xdlyu/fullRunII_ntuple_102X | 32e79c3bbc704cfaa00c67ab5124d40627fdacaf | d420b83eb9626a8ff1c79af5d34779cb805d57d8 | refs/heads/master | 2020-12-23T15:39:35.938678 | 2020-05-01T14:41:38 | 2020-05-01T14:41:38 | 237,192,426 | 0 | 2 | null | null | null | null | UTF-8 | Python | false | false | 2,303 | py | from WMCore.Configuration import Configuration
name = 'WWW/sig'
steam_dir = 'xulyu'
config = Configuration()
config.section_("General")
config.General.requestName = 'M3000_R0-7_off'
config.General.transferLogs = True
config.section_("JobType")
config.JobType.pluginName = 'Analysis'
config.JobType.inputFiles = ['Summer16_07Aug2017_V11_MC_L1FastJet_AK4PFchs.txt','Summer16_07Aug2017_V11_MC_L2Relative_AK4PFchs.txt','Summer16_07Aug2017_V11_MC_L3Absolute_AK4PFchs.txt','Summer16_07Aug2017_V11_MC_L1FastJet_AK8PFchs.txt','Summer16_07Aug2017_V11_MC_L2Relative_AK8PFchs.txt','Summer16_07Aug2017_V11_MC_L3Absolute_AK8PFchs.txt','Summer16_07Aug2017_V11_MC_L1FastJet_AK8PFPuppi.txt','Summer16_07Aug2017_V11_MC_L2Relative_AK8PFPuppi.txt','Summer16_07Aug2017_V11_MC_L3Absolute_AK8PFPuppi.txt','Summer16_07Aug2017_V11_MC_L1FastJet_AK4PFPuppi.txt','Summer16_07Aug2017_V11_MC_L2Relative_AK4PFPuppi.txt','Summer16_07Aug2017_V11_MC_L3Absolute_AK4PFPuppi.txt']
#config.JobType.inputFiles = ['PHYS14_25_V2_All_L1FastJet_AK4PFchs.txt','PHYS14_25_V2_All_L2Relative_AK4PFchs.txt','PHYS14_25_V2_All_L3Absolute_AK4PFchs.txt','PHYS14_25_V2_All_L1FastJet_AK8PFchs.txt','PHYS14_25_V2_All_L2Relative_AK8PFchs.txt','PHYS14_25_V2_All_L3Absolute_AK8PFchs.txt']
# Name of the CMSSW configuration file
#config.JobType.psetName = 'bkg_ana.py'
config.JobType.psetName = 'analysis_sig.py'
#config.JobType.allowUndistributedCMSSW = True
config.JobType.allowUndistributedCMSSW = True
config.section_("Data")
#config.Data.inputDataset = '/WJetsToLNu_13TeV-madgraph-pythia8-tauola/Phys14DR-PU20bx25_PHYS14_25_V1-v1/MINIAODSIM'
config.Data.inputDataset = '/WkkToWRadionToWWW_M3000-R0-7-TuneCUETP8M1_13TeV-madgraph-pythia/RunIISummer16MiniAODv3-PUMoriond17_94X_mcRun2_asymptotic_v3-v1/MINIAODSIM'
#config.Data.inputDBS = 'global'
config.Data.inputDBS = 'global'
config.Data.splitting = 'FileBased'
config.Data.unitsPerJob =5
config.Data.totalUnits = -1
config.Data.publication = False
config.Data.outLFNDirBase = '/store/group/dpg_trigger/comm_trigger/TriggerStudiesGroup/STEAM/' + steam_dir + '/' + name + '/'
# This string is used to construct the output dataset name
config.Data.outputDatasetTag = 'M3000_R0-7_off'
config.section_("Site")
# Where the output files will be transmitted to
config.Site.storageSite = 'T2_CH_CERN'
| [
"XXX@cern.ch"
] | XXX@cern.ch |
cfdbd786e226fab3dd20e883df0c067fa999d9ae | 1ade02a8e0c6d7e442c9d9041f15518d22da3923 | /Homework/w1d2/inclass/information_extraction_exercise.py | 60b1b7ca589a5f9e1bee6cf00c9d84843e96cea4 | [] | no_license | fodisi/ByteAcademy-Bootcamp | 7980b80636a36db6da3e0fc0e529fbc6b8e097e0 | d53e3f4864f6cba1b85e806c29b01c48e3c2e81d | refs/heads/master | 2020-03-19T12:55:31.489638 | 2018-07-25T16:19:19 | 2018-07-25T16:19:19 | 136,550,128 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 615 | py | #!/usr/bin/env python3
import json
import requests
def get_price(ticker_symbol):
endpoint = 'http://dev.markitondemand.com/MODApis/Api/v2/Quote/json?symbol='+ticker_symbol
response = json.loads(requests.get(endpoint).text)['LastPrice']
return response
def get_symbol(company_name):
endpoint = 'http://dev.markitondemand.com/MODApis/Api/v2/Lookup/json?input='+company_name
response = json.loads(requests.get(endpoint).text)[0]['Symbol']
return response
if __name__ == '__main__':
#print(get_price('tsla'))
#print(get_symbol('tesla'))
print(get_price(get_symbol('apple')))
| [
"fodisi@users.noreply.github.com"
] | fodisi@users.noreply.github.com |
2b12246547b51b74307c0c0e914afc2c5ce1b294 | 4fde32723e04cbb9c929c54dad55f4333ba48d90 | /tests/exceptions/source/diagnose/keyword_argument.py | 915a4a8c8fe4dcb406b7587f72ee1d3714dffca8 | [
"MIT"
] | permissive | Delgan/loguru | 29f1b64a4944886559d76e22029fe1e5c88e7fec | 80bcf4e25da9f79617ef23ca0fb29b100caac8f2 | refs/heads/master | 2023-09-03T20:18:46.892038 | 2023-09-03T16:19:15 | 2023-09-03T16:19:15 | 100,401,612 | 15,902 | 775 | MIT | 2023-09-11T14:19:42 | 2017-08-15T17:22:32 | Python | UTF-8 | Python | false | false | 246 | py | import sys
from loguru import logger
logger.remove()
logger.add(sys.stderr, format="", colorize=True, backtrace=False, diagnose=True)
def f(x):
return 1 / x
y = 0
with logger.catch():
f(x=y)
x = 0
with logger.catch():
f(x=x)
| [
"delgan.py@gmail.com"
] | delgan.py@gmail.com |
955a3eb12f6890a23402b59ec8dfaebaaf36fc45 | 472c0ba1911619f8e2e1a68b4f956fad05be4e94 | /src/matlab2cpp/parser.py | 0ffd7711ae1689070e9362f1c37d0478a7bc10d8 | [
"BSD-3-Clause"
] | permissive | jonathf/matlab2cpp | f8b9541cf79507ec764b04b8211e73c47a20c131 | b6e2cbaedb36c909952911adfe44fe26252a36a1 | refs/heads/master | 2022-08-08T21:28:23.028072 | 2022-07-15T19:58:01 | 2022-07-15T19:58:01 | 31,599,354 | 197 | 68 | BSD-3-Clause | 2022-07-15T19:58:02 | 2015-03-03T13:20:32 | Python | UTF-8 | Python | false | false | 4,744 | py | """Create parser for m2cpp."""
import argparse
from textwrap import dedent
import glob
import matlab2cpp
HELP_DESCRIPTION = """\
*** Matlab2cpp ***
The toolbox frontend of the Matlab2cpp library. Use this to try to do automatic
and semi-automatic translation from Matlab source file to C++. The program
will create files with the same name as the input, but with various extra
extensions. Scripts will receive the extension `.cpp`, headers and modules
`.hpp`. A file containing data type and header information will be stored in
a `.py` file. Any errors will be stored in `.log`.
"""
def matlab_file_completer(prefix, **kws):
"""Complete files with matlab extensions."""
return glob.glob("{}*.m".format(prefix))
def create_parser():
"""Create argument parser."""
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description=dedent(HELP_DESCRIPTION))
parser.add_argument(
"filename", help="File containing valid Matlab code."
).completer = matlab_file_completer
parser.add_argument(
"-o", '--original', action="store_true", help=(
"Include original Matlab code line as comment before the "
"C++ translation of the code line"),
)
parser.add_argument(
"-c", '--comments', action="store_true", help=(
"Include Matlab comments in the generated C++ files."),
)
parser.add_argument(
"-s", '--suggest', action="store_true", help=(
"Automatically populate the `<filename>.py` file with datatype "
"with suggestions if possible."),
)
parser.add_argument(
"-S", '--matlab-suggest', action="store_true", help=(
"Creates a folder m2cpp_temp. In the folder the matlab file(s) to "
"be translated are also put. These matlab file(s) are slightly "
"modified so that they output data-type information of the "
"variables to file(s). This output can then be used to set the "
"datatypes for the translation."),
)
parser.add_argument(
"-r", '--reset', action="store_true", help=(
"Ignore the content of `<filename>.py` and make a fresh translation."),
)
parser.add_argument(
"-t", '--tree', action="store_true", help=(
"Print the underlying node tree. Each line in the output "
"represents a node and is formated as follows: \n\n"
"`<codeline> <position> <class> <backend> <datatype> <name> <translation>`\n\n"
"The indentation represents the tree structure."),
)
parser.add_argument(
"-T", "--tree-full", action="store_true", help=(
"Same as -t, but the full node tree, but include meta-nodes."),
)
parser.add_argument(
"-d", '--disp', action="store_true", help=(
"Print out the progress of the translation process."),
)
parser.add_argument(
"-p", "--paths_file", type=str, dest="paths_file", help=(
"Flag and paths_file (-p path_to_pathsfile). m2cpp will look for "
"matlab files in the location specified in the paths_file"),
)
parser.add_argument(
"-omp", '--enable-omp', action="store_true", help=(
"OpenMP code is inserted for Parfor and loops marked with the "
"pragma %%#PARFOR (in Matlab code) when this flag is set."),
)
parser.add_argument(
"-tbb", '--enable-tbb', action="store_true", help=(
"TBB code is inserted for Parfor and loops marked with the "
"pragma %%#PARFOR (in Matlab code) when this flag is set."),
)
parser.add_argument(
"-ref", '--reference', action="store_true", help=(
'For the generated C++ code, function input parameters are '
'"copied by value" as default. With this flag some input '
'parameters in the generated code can be const references. '
'There can be some performance advantage of using const '
'references instead of "copied by value". Note that Matlab '
'"copies by value". The Matlab code you try to translate to '
'C++ code could try read as well as write to this input variable. '
"The code generator doesn't perform an analysis to detect this "
'and then "copy by value" for this variable.'),
)
parser.add_argument(
"-l", '--line', type=int, dest="line", help=(
"Only display code related to code line number `<line>`."),
)
parser.add_argument(
"-n", '--nargin', action="store_true", help=(
"Don't remove if and switch branches which use nargin variable."),
)
return parser
| [
"jonathf@gmail.com"
] | jonathf@gmail.com |
26f6ff2a255625275d61146503b16f43f11f2c3a | 4e0ff785b993b6bae70745434e61f27ca82e88f0 | /113-Path-Sum-II/solution.py | 8f5f4558cd246ae961dcad453e72f3e13d869c38 | [] | no_license | NobodyWHU/Leetcode | 2ee557dd77c65c5fa8ca938efb6de3793b4de261 | d284fa3daab02531e5300867463b293d44737e32 | refs/heads/master | 2021-01-23T14:05:28.161062 | 2016-09-23T11:51:51 | 2016-09-23T11:51:51 | 58,898,114 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 883 | py | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""
if not root:
return []
ans = []
self.helper(sum-root.val, root, [root.val], ans)
return ans
def helper(self, leftvalue, root, temp, ans):
if leftvalue == 0 and root.left is None and root.right is None:
ans.append(temp)
return
if root.left:
self.helper(leftvalue-root.left.val, root.left, temp+[root.left.val], ans)
if root.right:
self.helper(leftvalue-root.right.val, root.right, temp+[root.right.val], ans)
| [
"haohaoranran@126.com"
] | haohaoranran@126.com |
2f90756cc1595c4a95effe25d37d4029f6377e25 | f335e561d30319cf4759199fc78ea429b0cdb052 | /lldb/test/API/commands/expression/import-std-module/list/TestListFromStdModule.py | 9382c800ec76e275bbaaab5d146be2028e6a7c06 | [
"NCSA",
"Apache-2.0",
"LLVM-exception"
] | permissive | lock3/meta | 9f7c721c890f34256bfac17d789e7078d3b9675a | 918b8a2affc4a3e280b2cd2400dc535e32129c2c | refs/heads/feature/reflect | 2023-06-16T23:15:42.059634 | 2020-11-05T23:33:12 | 2020-11-10T21:17:00 | 278,660,720 | 122 | 14 | null | 2023-04-07T15:19:30 | 2020-07-10T14:54:22 | C++ | UTF-8 | Python | false | false | 2,156 | py | """
Test basic std::list functionality.
"""
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class TestBasicList(TestBase):
mydir = TestBase.compute_mydir(__file__)
@add_test_categories(["libc++"])
@skipIf(compiler=no_match("clang"))
def test(self):
self.build()
lldbutil.run_to_source_breakpoint(self,
"// Set break point at this line.",
lldb.SBFileSpec("main.cpp"))
self.runCmd("settings set target.import-std-module true")
list_type = "std::list<int, std::allocator<int> >"
size_type = list_type + "::size_type"
value_type = list_type + "::value_type"
iteratorvalue = "std::__list_iterator<int, void *>::value_type"
riterator_value = "std::__list_iterator<int, void *>::value_type"
self.expect_expr("a",
result_type=list_type,
result_children=[
ValueCheck(value="3"),
ValueCheck(value="1"),
ValueCheck(value="2")
])
self.expect_expr("a.size()", result_type=size_type, result_value="3")
self.expect_expr("a.front()", result_type=value_type, result_value="3")
self.expect_expr("a.back()", result_type=value_type, result_value="2")
self.expect("expr a.sort()")
self.expect_expr("a.front()", result_type=value_type, result_value="1")
self.expect_expr("a.back()", result_type=value_type, result_value="3")
self.expect("expr std::reverse(a.begin(), a.end())")
self.expect_expr("a.front()", result_type=value_type, result_value="3")
self.expect_expr("a.back()", result_type=value_type, result_value="1")
self.expect_expr("*a.begin()",
result_type=iteratorvalue,
result_value="3")
self.expect_expr("*a.rbegin()",
result_type=riterator_value,
result_value="1")
| [
"teemperor@gmail.com"
] | teemperor@gmail.com |
29c1c4beba24f4ef72451a2ee5e945a97aca3955 | 45a153a8e27b552d82d137bd94f2d5d0aec3c889 | /GoogleCLoudwithTwilio/google-cloud-sdk/lib/surface/compute/instance_groups/managed/stop_autoscaling.py | 2b8c7bad314ab25f4c5235300b511b241bcd0ea4 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | Pooshan/App-using-Twilio | 84bc0be1f091c678528bdf161c9fbb0af617fc0e | a6eea3f40ef9f22a7ab47c1f63b90deaa2620049 | refs/heads/master | 2022-11-23T23:56:49.754209 | 2016-10-01T18:47:25 | 2016-10-01T18:47:25 | 69,719,320 | 0 | 1 | null | 2022-11-02T19:48:20 | 2016-10-01T04:26:37 | Python | UTF-8 | Python | false | false | 6,012 | py | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command for stopping autoscaling of a managed instance group."""
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute import instance_groups_utils
from googlecloudsdk.api_lib.compute import managed_instance_groups_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute import flags
def _AddArgs(parser, multizonal):
"""Adds args."""
parser.add_argument(
'name',
metavar='NAME',
completion_resource='compute.instanceGroupManagers',
help='Managed instance group which will no longer be autoscaled.')
if multizonal:
scope_parser = parser.add_mutually_exclusive_group()
flags.AddRegionFlag(
scope_parser,
resource_type='resources',
operation_type='delete',
explanation=flags.REGION_PROPERTY_EXPLANATION_NO_DEFAULT)
flags.AddZoneFlag(
scope_parser,
resource_type='resources',
operation_type='delete',
explanation=flags.ZONE_PROPERTY_EXPLANATION_NO_DEFAULT)
else:
flags.AddZoneFlag(
parser,
resource_type='resources',
operation_type='delete')
def _IsZonalGroup(ref):
"""Checks if reference to instance group is zonal."""
return ref.Collection() == 'compute.instanceGroupManagers'
@base.ReleaseTracks(base.ReleaseTrack.GA)
class StopAutoscaling(base_classes.BaseAsyncMutator):
"""Stop autoscaling a managed instance group."""
@property
def service(self):
return self.compute.autoscalers
@property
def resource_type(self):
return 'autoscalers'
@property
def method(self):
return 'Delete'
@staticmethod
def Args(parser):
_AddArgs(parser=parser, multizonal=False)
def CreateGroupReference(self, args):
return self.CreateZonalReference(
args.name, args.zone, resource_type='instanceGroupManagers')
def GetAutoscalerServiceForGroup(self, group_ref):
return self.compute.autoscalers
def GetAutoscalerResource(self, igm_ref, args):
autoscaler = managed_instance_groups_utils.AutoscalerForMig(
mig_name=args.name,
autoscalers=managed_instance_groups_utils.AutoscalersForLocations(
regions=None,
zones=[igm_ref.zone],
project=self.project,
compute=self.compute,
http=self.http,
batch_url=self.batch_url),
project=self.project,
scope_name=igm_ref.zone,
scope_type='zone')
if autoscaler is None:
raise managed_instance_groups_utils.ResourceNotFoundException(
'The managed instance group is not autoscaled.')
return autoscaler
def ScopeRequest(self, request, igm_ref):
request.zone = igm_ref.zone
def CreateRequests(self, args):
igm_ref = self.CreateGroupReference(args)
service = self.GetAutoscalerServiceForGroup(igm_ref)
# Assert that Instance Group Manager exists.
managed_instance_groups_utils.GetInstanceGroupManagerOrThrow(
igm_ref, self.project, self.compute, self.http, self.batch_url)
autoscaler = self.GetAutoscalerResource(igm_ref, args)
request = service.GetRequestType(self.method)(
project=self.project,
autoscaler=autoscaler.name)
self.ScopeRequest(request, igm_ref)
return [(service, self.method, request,)]
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.ALPHA)
class StopAutoscalingAlpha(StopAutoscaling):
"""Stop autoscaling a managed instance group."""
@staticmethod
def Args(parser):
_AddArgs(parser=parser, multizonal=True)
def CreateGroupReference(self, args):
return instance_groups_utils.CreateInstanceGroupReference(
scope_prompter=self, compute=self.compute, resources=self.resources,
name=args.name, region=args.region, zone=args.zone)
def GetAutoscalerServiceForGroup(self, group_ref):
if _IsZonalGroup(group_ref):
return self.compute.autoscalers
else:
return self.compute.regionAutoscalers
def GetAutoscalerResource(self, igm_ref, args):
if _IsZonalGroup(igm_ref):
scope_name = igm_ref.zone
scope_type = 'zone'
zones, regions = [scope_name], None
else:
scope_name = igm_ref.region
scope_type = 'region'
zones, regions = None, [scope_name]
autoscaler = managed_instance_groups_utils.AutoscalerForMig(
mig_name=args.name,
autoscalers=managed_instance_groups_utils.AutoscalersForLocations(
regions=regions,
zones=zones,
project=self.project,
compute=self.compute,
http=self.http,
batch_url=self.batch_url),
project=self.project,
scope_name=scope_name,
scope_type=scope_type)
if autoscaler is None:
raise managed_instance_groups_utils.ResourceNotFoundException(
'The managed instance group is not autoscaled.')
return autoscaler
def ScopeRequest(self, request, igm_ref):
if _IsZonalGroup(igm_ref):
request.zone = igm_ref.zone
else:
request.region = igm_ref.region
StopAutoscaling.detailed_help = {
'brief': 'Stop autoscaling a managed instance group',
'DESCRIPTION': """\
*{command}* stops autoscaling a managed instance group. If autoscaling
is not enabled for the managed instance group, this command does nothing and
will report an error.
""",
}
StopAutoscalingAlpha.detailed_help = StopAutoscaling.detailed_help
| [
"pooshan.vyas@gmail.com"
] | pooshan.vyas@gmail.com |
9846ac7ed6b055116e262bf86b8ee3ee14bd8f6e | edb88981aa1420af7e074068ed7818b9d904a3dd | /tags/release-0.4.2/minds/docarchive.py | 6236e76613b96b887b1e880dfc7f07115f3cece8 | [] | no_license | BackupTheBerlios/mindretrieve-svn | 101c0f1dfc25d20d5f828b6fd0d43301b773af4e | 463745fcf1c1d5b1f6c201c30bcc339c99b437ed | refs/heads/master | 2021-01-22T13:57:31.225772 | 2006-04-28T04:24:43 | 2006-04-28T04:24:43 | 40,801,743 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,822 | py | """Usage: docarchive [option] [id|filename]
-r read docid
-a add filename [not implemented]
"""
# todo: describe docarchive file format
# Note: id are generally added consecutively in chronical order.
# However, users are free to purge documents afterward. Therefore id
# does not necessary start from 0 nor are they necessary consecutive.
import logging
import os, os.path, sys
import re
import StringIO
import threading
import zipfile
from minds.config import cfg
from toollib import zipfile_single
log = logging.getLogger('docarc')
def parseId(id):
""" Return arc_path, filename represents by id.
e.g. id=123456789 -> $archive/123456.zip/789
Raises KeyError if malformed
"""
if not id.isdigit() or len(id) != 9:
raise KeyError, 'Invalid id: %s' % str(id)
apath = cfg.getPath('archive')
return os.path.join(apath, id[:6]+'.zip'), id[6:]
def get_document(id):
""" Return fp to the content of id.
KeyError if arc_path or filename not exist.
"""
arc_path, filename = parseId(id)
if not os.path.exists(arc_path):
raise KeyError, 'archive file does not exist %s' % arc_path
zfile = zipfile_single.ZipFile(file(arc_path,'rb'), 'r')
try:
return StringIO.StringIO(zfile.read(filename))
finally:
zfile.close()
class IdCounter(object):
def __init__(self):
self.currentIdLock = threading.Lock()
# archive status - _beginId:_endId
# None,None: uninitialized
# 0,0 : no document
# 0,1 : 1 document with id 0
# ...and so on...
self._beginId = None
self._endId = None
arc_pattern = re.compile('\d{6}.zip$')
filename_pattern = re.compile('\d{3}$')
def _findIdRange(self):
""" Scan the $archive directory for zip files for the begin and end id. """
apath = cfg.getPath('archive')
files = filter(self.arc_pattern.match, os.listdir(apath))
if not files:
self._beginId = 0
self._endId = 0
return
first_arc = min(files)
last_arc = max(files)
first = self._findId(os.path.join(apath, first_arc), min)
last = self._findId(os.path.join(apath, last_arc ), max)
self._beginId = int(first_arc[:6] + first) # would be a 9 digit id
self._endId = int(last_arc[:6] + last )+1 # would be a 9 digit id
def _findId(self, path, min_or_max):
""" return the min_or_max filename in path (as a 3 dight string) """
zfile = zipfile.ZipFile(path, 'r') # would throw BadZipfile if not a zip file
try:
files = zfile.namelist()
files = filter(self.filename_pattern.match, files) # filter invalid filename
if not files:
# This is an odd case when there is a zip but nothing inside
# (possibly some exception happened when adding to archive).
# The min and max id is arguably not correct.
return '000'
return min_or_max(files)
finally:
zfile.close()
def getNewId(self):
""" Return an unused new id. Id is in the format of 9 digit string. """
self.currentIdLock.acquire()
try:
if self._endId == None:
# This is going to be a long operation inside a
# synchronization block. Everybody is going to wait
# until the lazy initialization finish.
self._findIdRange()
log.info('Initial archive id range is %s:%s', self._beginId, self._endId)
id = '%09d' % self._endId
self._endId += 1
return id
finally:
self.currentIdLock.release()
idCounter = IdCounter()
class ArchiveHandler(object):
""" Optimize batch reading and writing by reusing opened zipfile if
possible. Must call close() at the end.
Parameter:
mode - 'r' for read and 'w' for write
Internally use 'a' instead or 'w' if zip file exist (see zipfile.ZipFile)
"""
def __init__(self, mode):
if mode not in ['r','w']:
raise ValueError, 'Invalid mode %s' % mode
self.arc_path = None
self.zfile = None
self.mode = mode
def _open(self, id):
""" Return opened zfile, filename represents id """
arc_path, filename = parseId(id)
if self.arc_path:
if self.arc_path == arc_path: # same arc_path
return self.zfile, filename # reuse opened zfile
else: # different arc_path,
self.close() # must close previously opened zfile
# It would be easier if ZipFile can use 'a' to create new archive.
# Instead do some checking first.
if self.mode == 'w' and os.path.exists(arc_path):
self.zfile = zipfile.ZipFile(arc_path, 'a', zipfile.ZIP_DEFLATED)
else:
self.zfile = zipfile.ZipFile(arc_path, self.mode, zipfile.ZIP_DEFLATED)
self.arc_path = arc_path
return self.zfile, filename
def close(self):
if self.zfile:
self.zfile.close()
self.zfile = None
self.arc_path = None
def add_document(self, id, fp):
zfile, filename = self._open(id)
try: # check if filename is in archive
zipinfo = self.zfile.getinfo(filename)
except KeyError: # good, filename not in arc
pass
else: # expect KeyError; otherwise an entry is already there
raise KeyError, 'Duplicated entry %s in %s' % (filename, self.arc_path)
self.zfile.writestr(filename, fp.read())
## cmdline testing #####################################################
def main(argv):
from minds import proxy
proxy.init(proxy.CONFIG_FILENAME)
if len(argv) <= 1:
print __doc__
idCounter._findIdRange()
print 'idRange [%s:%s]\n' % (idCounter._beginId, idCounter._endId)
if len(argv) <= 1:
sys.exit(-1)
option = argv[1]
if option == '-r':
id = argv[2]
id = ('000000000' + id)[-9:]
arc_path, filename = parseId(id)
print get_document(arc_path, filename).read()
elif option == '-a':
filename = argv[2]
print 'not implemented'
if __name__ == '__main__':
main(sys.argv) | [
"tungwaiyip@785ff9d5-dded-0310-b5f2-a5aff206d990"
] | tungwaiyip@785ff9d5-dded-0310-b5f2-a5aff206d990 |
b87b4b74514f77319ea93923b9b29886492b9b0f | b38247a5d84d8b52ce8363f8dd81629cfbe17f65 | /reagent/gym/types.py | 22a1343083ad5d4a45d47ada2cbedc2258ab611f | [
"BSD-3-Clause"
] | permissive | facebookresearch/ReAgent | 7f2b82eaaf7a19e58cc50aacc307d7b001231440 | c5f1a8371a677b4f8fb0882b600bf331eba5259d | refs/heads/main | 2023-09-05T15:56:49.175072 | 2023-08-29T21:48:40 | 2023-08-29T21:48:40 | 98,565,575 | 1,480 | 290 | BSD-3-Clause | 2023-09-12T23:09:30 | 2017-07-27T17:53:21 | Python | UTF-8 | Python | false | false | 4,660 | py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
# Please DO NOT import gym in here. We might have installation without gym depending on
# this module for typing
from abc import ABC, abstractmethod
from dataclasses import asdict, dataclass, field, fields
from typing import Any, Callable, Dict, List, Optional, Union
import numpy as np
import reagent.core.types as rlt
import torch
import torch.nn.functional as F
@dataclass
class Transition(rlt.BaseDataClass):
mdp_id: int
sequence_number: int
observation: Any
action: Any
reward: float
terminal: bool
log_prob: Optional[float] = None
possible_actions_mask: Optional[np.ndarray] = None
info: Optional[Dict] = None
# Same as asdict but filters out none values.
def asdict(self):
return {k: v for k, v in asdict(self).items() if v is not None}
def get_optional_fields(cls) -> List[str]:
"""return list of optional annotated fields"""
ret: List[str] = []
for f in fields(cls):
# Check if exactly two arguments exists and one of them are None type
if hasattr(f.type, "__args__") and type(None) in f.type.__args__:
ret.append(f.name)
return ret
@dataclass
class Trajectory(rlt.BaseDataClass):
transitions: List[Transition] = field(default_factory=list)
def __post_init__(self) -> None:
self.optional_field_exist: Dict[str, bool] = {
f: False for f in get_optional_fields(Transition)
}
def __len__(self) -> int:
return len(self.transitions)
def add_transition(self, transition: Transition) -> None:
if len(self) == 0:
# remember which optional fields should be filled
for f in self.optional_field_exist:
val = getattr(transition, f, None)
if val is not None:
self.optional_field_exist[f] = True
# check that later additions also fill the same optional fields
for f, should_exist in self.optional_field_exist.items():
val = getattr(transition, f, None)
if (val is not None) != should_exist:
raise ValueError(
f"Field {f} given val {val} whereas should_exist is {should_exist}."
)
self.transitions.append(transition)
def __getattr__(self, attr: str):
ret = []
for transition in self.transitions:
ret.append(getattr(transition, attr))
return ret
def calculate_cumulative_reward(self, gamma: float = 1.0):
"""Return (discounted) sum of rewards."""
num_transitions = len(self)
assert num_transitions > 0, "called on empty trajectory"
rewards = self.reward
discounts = [gamma**i for i in range(num_transitions)]
return sum(reward * discount for reward, discount in zip(rewards, discounts))
def to_dict(self):
d = {"action": F.one_hot(torch.from_numpy(np.stack(self.action)), 2)}
for f in [
"observation",
"reward",
"terminal",
"log_prob",
"possible_actions_mask",
]:
if self.optional_field_exist.get(f, True):
f_value = getattr(self, f)
if np.isscalar(f_value[0]):
# scalar values
d[f] = torch.tensor(f_value)
else:
# vector values, need to stack
d[f] = torch.from_numpy(np.stack(f_value)).float()
return d
class Sampler(ABC):
"""Given scores, select the action."""
@abstractmethod
def sample_action(self, scores: Any) -> rlt.ActorOutput:
raise NotImplementedError()
@abstractmethod
def log_prob(self, scores: Any, action: torch.Tensor) -> torch.Tensor:
raise NotImplementedError()
def update(self) -> None:
"""Call to update internal parameters (e.g. decay epsilon)"""
pass
# From preprocessed observation, produce scores for sampler to select action
DiscreteScorer = Callable[[Any, Optional[torch.Tensor]], Any]
ContinuousScorer = Callable[[Any], Any]
Scorer = Union[DiscreteScorer, ContinuousScorer]
# Transform ReplayBuffer's transition batch to trainer.train
TrainerPreprocessor = Callable[[Any], Any]
""" Called after env.step(action)
Args: (state, action, reward, terminal, log_prob)
"""
PostStep = Callable[[Transition], None]
""" Called after end of episode
"""
PostEpisode = Callable[[Trajectory, Dict], None]
@dataclass
class GaussianSamplerScore(rlt.BaseDataClass):
loc: torch.Tensor
scale_log: torch.Tensor
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
1118d813dbd043ad6b96b0b5ec0f378d73157bfc | 876672868996f0da96c5db39fe44dc1a13354bd8 | /557. Reverse Words in a String III.py | e700691d5be1d4761a2d617fac5ddd22f0e4ea00 | [] | no_license | eekstunt/leetcode | f9958cb18d537c149316370ec1acdfaefa20b4df | 3bff096b1cb6a8abc887c6de36beb92bd0ee4fc3 | refs/heads/master | 2022-04-20T17:08:33.413691 | 2020-04-18T17:58:56 | 2020-04-18T17:58:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 181 | py | # https://leetcode.com/problems/reverse-words-in-a-string-iii/
class Solution:
def reverseWords(self, s: str) -> str:
return ' '.join(word[::-1] for word in s.split())
| [
"you@example.com"
] | you@example.com |
7dd4464fdcffe881ff7e78bbd9d0185e32a1e30d | 574af23550bed50fdf9cfa205d7a063131f332a0 | /scripts/migrate_to_json_graph.py | 6d7d5b9a36c5ec3754c1069a6b7165ecd09eeb5d | [
"MIT",
"BSD-3-Clause"
] | permissive | setu4993/cf-scripts | db8015b499090dd0923dcf0192ee85ec29ee037f | 315187e2f25de4e3bc157ea1ac0f7f4d9b22a680 | refs/heads/master | 2020-09-25T13:34:47.659245 | 2019-12-11T17:04:48 | 2019-12-11T17:04:48 | 226,014,246 | 0 | 0 | NOASSERTION | 2019-12-05T04:13:44 | 2019-12-05T04:13:43 | null | UTF-8 | Python | false | false | 132 | py | import networkx as nx
from conda_forge_tick.utils import dump_graph
gx = nx.read_gpickle('graph.pkl')
dump_graph(gx, 'graph.json')
| [
"cjwright4242@gmail.com"
] | cjwright4242@gmail.com |
824b5ecadedca94aef264f6fdec1628f4f0cb0ae | 07570ec33eb49effd9ed6af73214bac1b607038f | /client/swagger_client/models/certificate_list.py | 2586693e77e82e23c1bdd2d6d8c8954090aea0de | [
"MIT"
] | permissive | kakwa/certascale | d9998a66ba6a239ba5b5e537f12dabdd5876996c | 0df8da0f518506500117152fd0e28ee3286949af | refs/heads/master | 2020-03-29T09:24:32.794060 | 2019-01-30T14:06:10 | 2019-01-30T14:06:10 | 149,756,729 | 0 | 2 | null | null | null | null | UTF-8 | Python | false | false | 3,618 | py | # coding: utf-8
"""
certascale API
Certascale API documentation # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from swagger_client.models.certificate import Certificate # noqa: F401,E501
class CertificateList(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 = {
'list': 'list[Certificate]',
'next_id': 'int'
}
attribute_map = {
'list': 'list',
'next_id': 'next_id'
}
def __init__(self, list=None, next_id=None): # noqa: E501
"""CertificateList - a model defined in Swagger""" # noqa: E501
self._list = None
self._next_id = None
self.discriminator = None
if list is not None:
self.list = list
if next_id is not None:
self.next_id = next_id
@property
def list(self):
"""Gets the list of this CertificateList. # noqa: E501
:return: The list of this CertificateList. # noqa: E501
:rtype: list[Certificate]
"""
return self._list
@list.setter
def list(self, list):
"""Sets the list of this CertificateList.
:param list: The list of this CertificateList. # noqa: E501
:type: list[Certificate]
"""
self._list = list
@property
def next_id(self):
"""Gets the next_id of this CertificateList. # noqa: E501
:return: The next_id of this CertificateList. # noqa: E501
:rtype: int
"""
return self._next_id
@next_id.setter
def next_id(self, next_id):
"""Sets the next_id of this CertificateList.
:param next_id: The next_id of this CertificateList. # noqa: E501
:type: int
"""
self._next_id = next_id
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.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 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, CertificateList):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| [
"carpentier.pf@gmail.com"
] | carpentier.pf@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.