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
1d71cdc28e7df4c73083aeda6d2500856049954c
1c17aaf0f96c2ba2e2eaf6b552017fb1393a5eaf
/week_1_5/05_3.py
b7fd80b0fad08bacb17e3d113e80b11a72308940
[]
no_license
ljwon0312/academy_python
b5372387ce317f487e7b498f5f875058661878d3
b87c3ba38616f3785a1ba587472a3407e113d57a
refs/heads/master
2020-06-17T03:33:29.989733
2019-07-10T07:53:31
2019-07-10T07:53:31
195,782,134
0
0
null
null
null
null
UTF-8
Python
false
false
1,705
py
codon_dict = {'TTT':'F', 'TTC':'F', 'TTA':'L', 'TTG':'L', 'TCT':'S', 'TCC':'S', 'TCA':'S', 'TCG':'S', 'TAT':'Y', 'TAC':'Y', 'TAA':'*', 'TAG':'*', 'TGT':'C', 'TGC':'C', 'TGA':'*', 'TGG':'W', 'CTT':'L', 'CTC':'L', 'CTA':'L', 'CTG':'L', 'CCT':'P', 'CCC':'P', 'CCA':'P', 'CCG':'P', 'CAT':'H', 'CAC':'H', 'CAA':'Q', 'CAG':'Q', 'CGT':'R', 'CGC':'R', 'CGA':'R', 'CGG':'R', 'ATT':'I', 'ATC':'I', 'ATA':'I', 'ATG':'M', 'ACT':'T', 'ACC':'T', 'ACA':'T', 'ACG':'T', 'AAT':'N', 'AAC':'N', 'AAA':'K', 'AAG':'K', 'AGT':'S', 'AGC':'S', 'AGA':'R', 'AGG':'R', 'GTT':'V', 'GTC':'V', 'GTA':'V', 'GTG':'V', 'GCT':'A', 'GCC':'A', 'GCA':'A', 'GCG':'A', 'GAT':'D', 'GAC':'D', 'GAA':'E', 'GAG':'E', 'GGT':'G', 'GGC':'G', 'GGA':'G', 'GGG':'G'} with open('sequence.nucleotide.fasta','r') as f: ll = f.read().split('\n')[1:] sequence = ''.join(ll) compl = sequence.replace("A","X") compl = compl.replace("T","A") compl = compl.replace("X","T") compl = compl.replace("G","X") compl = compl.replace("C","G") compl = compl.replace("X","C") f1 = ' '.join([codon_dict[sequence[n-3:n]] for n in range(3,2332) if n%3==0]) f2 = ' '.join([codon_dict[sequence[n-3:n]] for n in range(3,2332) if n%3==1]) f3 = ' '.join([codon_dict[sequence[n-3:n]] for n in range(3,2332) if n%3==2]) r1 = ' '.join([codon_dict[compl[::-1][n-3:n]] for n in range(3,2332) if n%3==0]) r2 = ' '.join([codon_dict[compl[::-1][n-3:n]] for n in range(3,2332) if n%3==1]) r3 = ' '.join([codon_dict[compl[::-1][n-3:n]] for n in range(3,2332) if n%3==2]) print(f1+'\n '+f2+'\n '+f3+'\n'+sequence+'\n'+compl+'\n'+ '%2331s\n%2330s\n%2329s' %(r1[::-1],r2[::-1],r3[::-1]))
[ "jjww-0312@naver.com" ]
jjww-0312@naver.com
004d960888711abd2459097ce1f9fb8af8aa03cc
c15899ee195d5e4ee978f271767b899bcfe6ea60
/plugins/nzbhydra/resources/nzbhydraUI/freenas/forms.py
811acb34f1fa212e7ff1bb245b9e07eae08afc28
[]
no_license
josh4trunks/freenas-plugins
d39159aa8454ea6be02923cf276348124c84033c
ff7a4276fe4d6584700d271b10d350b23f3c03c5
refs/heads/master
2020-12-01T13:04:10.856791
2018-10-16T13:50:30
2018-10-16T13:50:30
26,624,312
34
13
null
2017-08-02T10:38:23
2014-11-14T05:46:58
Python
UTF-8
Python
false
false
888
py
from subprocess import Popen, PIPE import hashlib import json import pwd import urllib from django.utils.translation import ugettext_lazy as _ from dojango import forms from nzbhydraUI.freenas import models, utils class NZBHydraForm(forms.ModelForm): class Meta: model = models.NZBHydra exclude = ( 'enable', ) def __init__(self, *args, **kwargs): self.jail_path = kwargs.pop('jail_path') super(NZBHydraForm, self).__init__(*args, **kwargs) def save(self, *args, **kwargs): obj = super(NZBHydraForm, self).save(*args, **kwargs) if obj.enable: Popen(["/usr/sbin/sysrc", "nzbhydra_enable=YES"], stdout=PIPE, stderr=PIPE) else: Popen(["/usr/sbin/sysrc", "nzbhydra_enable=NO"], stdout=PIPE, stderr=PIPE)
[ "joshruehlig@gmail.com" ]
joshruehlig@gmail.com
e8e4f0a3e63dd64e48c24cae5de0e03b153797e9
52b5773617a1b972a905de4d692540d26ff74926
/.history/permutations_20200723155624.py
1a43bb06b64892a0a05e131276152208c87546a0
[]
no_license
MaryanneNjeri/pythonModules
56f54bf098ae58ea069bf33f11ae94fa8eedcabc
f4e56b1e4dda2349267af634a46f6b9df6686020
refs/heads/master
2022-12-16T02:59:19.896129
2020-09-11T12:05:22
2020-09-11T12:05:22
null
0
0
null
null
null
null
UTF-8
Python
false
false
330
py
def perm(arr): # sort the array if len(arr) == 0: return 0 else: arr.sort() perm = set(arr) maxValue = max(arr) if len(perm) == maxValue: return 1 elif len(perm) == 1: return 0 print(perm([1,1,1]))
[ "mary.jereh@gmail.com" ]
mary.jereh@gmail.com
b1d37d62e22effe849327ad9efec359561e3190b
c413fce92172f3503fd4790b68ad6bbddbf4c919
/20170501/02_make_exception/02_mexception.py
b803391aede525e909f53d4899cb32a49b572b0d
[]
no_license
JohnHaan/cloudtechpython
9dbd80e71b7151e3ba1be416b798f086785a1f19
17b9b8224cdc29a4b51e592e86f8c9863309c5b1
refs/heads/master
2021-01-22T21:22:36.733331
2017-11-28T13:54:32
2017-11-28T13:54:32
85,414,710
0
1
null
2017-04-21T02:51:09
2017-03-18T16:15:17
Python
UTF-8
Python
false
false
299
py
class MyError(Exception): pass def say_nick(nickname): if nickname == 'dolbam': raise MyError() print(nickname) if __name__ == '__main__': for i in ['zeroxkim', 'dolbam']: try: say_nick(i) except MyError: print("wrong nickname")
[ "yongiman@gmail.com" ]
yongiman@gmail.com
4c4313dd1ac27c37e207f29bdec56e2ffde9a46a
a81c1492783e7cafcaf7da5f0402d2d283b7ce37
/google/ads/google_ads/v6/services/geographic_view_service_client_config.py
0bb6c499223798af61ddd383cefd941113c27d62
[ "Apache-2.0" ]
permissive
VincentFritzsche/google-ads-python
6650cf426b34392d1f58fb912cb3fc25b848e766
969eff5b6c3cec59d21191fa178cffb6270074c3
refs/heads/master
2023-03-19T17:23:26.959021
2021-03-18T18:18:38
2021-03-18T18:18:38
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,185
py
config = { "interfaces": { "google.ads.googleads.v6.services.GeographicViewService": { "retry_codes": { "retry_policy_1_codes": [ "UNAVAILABLE", "DEADLINE_EXCEEDED" ], "no_retry_codes": [] }, "retry_params": { "retry_policy_1_params": { "initial_retry_delay_millis": 5000, "retry_delay_multiplier": 1.3, "max_retry_delay_millis": 60000, "initial_rpc_timeout_millis": 3600000, "rpc_timeout_multiplier": 1.0, "max_rpc_timeout_millis": 3600000, "total_timeout_millis": 3600000 }, "no_retry_params": { "initial_retry_delay_millis": 0, "retry_delay_multiplier": 0.0, "max_retry_delay_millis": 0, "initial_rpc_timeout_millis": 0, "rpc_timeout_multiplier": 1.0, "max_rpc_timeout_millis": 0, "total_timeout_millis": 0 } }, "methods": { "GetGeographicView": { "timeout_millis": 60000, "retry_codes_name": "retry_policy_1_codes", "retry_params_name": "retry_policy_1_params" } } } } }
[ "noreply@github.com" ]
VincentFritzsche.noreply@github.com
873fa6fdc46a377613d15a63e3fa52a0075972ea
4e5141121d8b4015db233cbc71946ec3cfbe5fe6
/samples/basic/executor/models/cisco-ios-xr/Cisco-IOS-XR-snmp-test-trap-act/nc-execute-xr-snmp-test-trap-act-210-ydk.py
1eab0af3fe816529cbffcdfeb619368a0a50f197
[ "Apache-2.0" ]
permissive
itbj/ydk-py-samples
898c6c9bad9d6f8072892300d42633d82ec38368
c5834091da0ebedbb11af7bbf780f268aad7040b
refs/heads/master
2022-11-20T17:44:58.844428
2020-07-25T06:18:02
2020-07-25T06:18:02
282,382,442
1
0
null
2020-07-25T06:04:51
2020-07-25T06:04:50
null
UTF-8
Python
false
false
2,657
py
#!/usr/bin/env python # # Copyright 2016 Cisco Systems, Inc. # # 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. # """ Execute RPC for model Cisco-IOS-XR-snmp-test-trap-act. usage: nc-execute-xr-snmp-test-trap-act-210-ydk.py [-h] [-v] device positional arguments: device NETCONF device (ssh://user:password@host:port) optional arguments: -h, --help show this help message and exit -v, --verbose print debugging messages """ from argparse import ArgumentParser from urlparse import urlparse from ydk.services import ExecutorService from ydk.providers import NetconfServiceProvider from ydk.models.cisco_ios_xr import Cisco_IOS_XR_snmp_test_trap_act \ as xr_snmp_test_trap_act import logging if __name__ == "__main__": """Execute main program.""" parser = ArgumentParser() parser.add_argument("-v", "--verbose", help="print debugging messages", action="store_true") parser.add_argument("device", help="NETCONF device (ssh://user:password@host:port)") args = parser.parse_args() device = urlparse(args.device) # log debug messages if verbose argument specified if args.verbose: logger = logging.getLogger("ydk") logger.setLevel(logging.INFO) handler = logging.StreamHandler() formatter = logging.Formatter(("%(asctime)s - %(name)s - " "%(levelname)s - %(message)s")) handler.setFormatter(formatter) logger.addHandler(handler) # create NETCONF provider provider = NetconfServiceProvider(address=device.hostname, port=device.port, username=device.username, password=device.password, protocol=device.scheme) # create executor service executor = ExecutorService() infra_syslog_message_generated = xr_snmp_test_trap_act.InfraSyslogMessageGenerated() # create object # execute RPC on NETCONF device executor.execute_rpc(provider, infra_syslog_message_generated) exit() # End of script
[ "saalvare@cisco.com" ]
saalvare@cisco.com
77f4f391c4a589f687c1673464cd42ba2b0ce694
4855a73f552c79f9123990a66b4fd29f829cd07d
/JZOffer/JZOffer14_2.py
c55d60a02a04ffcc0d79604611fbc389a45350b9
[]
no_license
EmlynQuan/Programming-Python
e2d47de71c4d5981b79bba3b4bf9ac9cf7115484
11bbc8aa58b5f16d7cfadd30c7eea241e6dd7bdd
refs/heads/master
2023-06-24T06:50:27.255834
2021-07-29T15:47:50
2021-07-29T15:47:50
362,500,150
0
0
null
null
null
null
UTF-8
Python
false
false
344
py
# coding=utf-8 def cuttingRope_dp(n): """ :type n: int :rtype: int """ if n <= 3: return n-1 dp = [0 for i in range(n+1)] dp[1] = 1 dp[2] = 1 dp[3] = 2 for i in range(3, n+1): for j in range(1, i/2+1): dp[i] = max(dp[i], j*max(dp[i-j], i-j)) return dp[n] % 1000000007
[ "2569627904@qq.com" ]
2569627904@qq.com
ba9eb14de7b40eaeee426d39736d20fa3a6fb304
971e0efcc68b8f7cfb1040c38008426f7bcf9d2e
/tests/model_control/detailed/transf_Quantization/model_control_one_enabled_Quantization_MovingAverage_Seasonal_DayOfMonth_MLP.py
72d984f241059cea41ee8f1d543e8cd2d2152544
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
antoinecarme/pyaf
a105d172c2e7544f8d580d75f28b751351dd83b6
b12db77cb3fa9292e774b2b33db8ce732647c35e
refs/heads/master
2023-09-01T09:30:59.967219
2023-07-28T20:15:53
2023-07-28T20:15:53
70,790,978
457
77
BSD-3-Clause
2023-03-08T21:45:40
2016-10-13T09:30:30
Python
UTF-8
Python
false
false
169
py
import tests.model_control.test_ozone_custom_models_enabled as testmod testmod.build_model( ['Quantization'] , ['MovingAverage'] , ['Seasonal_DayOfMonth'] , ['MLP'] );
[ "antoine.carme@laposte.net" ]
antoine.carme@laposte.net
bba9ea3018221f89eb8650ff3f46c4a24e7e06a1
4ede275efc8bc9f9ef121dc37215d2f0d8453e36
/14pl.py
c9485786e19ce057f3e6bd2acf6e59c83c2fbfd7
[]
no_license
shanthivimalanataraajan01/code
bfa8a441b0c360aebd02248ad4433cc21889c3d2
ea467ae1eefd68a5dceaa53aab7149d31bd5faf6
refs/heads/master
2020-04-15T05:01:03.625422
2019-05-17T09:35:45
2019-05-17T09:35:45
164,405,963
0
2
null
null
null
null
UTF-8
Python
false
false
189
py
n=int(input()) s=input() r=["a","e","i","o","u","A","E","I","O","U"] l=[] for i in range(len(s)): if s[i] not in r: l.append(s[i]) for i in reversed(l): print(i,end="")
[ "noreply@github.com" ]
shanthivimalanataraajan01.noreply@github.com
20d292d62891bea770e215fc0d6057a5f8d0e71c
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03013/s862770643.py
7ccbf8573c48d9c4b4925c320990f7e34dc43586
[]
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
750
py
#import math #import itertools #import numpy as np #from collections import deque # sys.setrecursionlimit(10 ** 6) MOD = 10 ** 9 + 7 #INF = 10 ** 9 #PI = 3.14159265358979323846 INT = lambda: int(input()) INTM = lambda: map(int,input().split()) STRM = lambda: map(str,input().split()) STR = lambda: str(input()) LIST = lambda: list(map(int,input().split())) LISTS = lambda: list(map(str,input().split())) def do(): n,m=INTM() b_sts=[False]*n for i in range(m): b=INT() b-=1 b_sts[b]=True step=[0]*(n+2) step[1]=1 for i in range(n): if b_sts[i]: continue else: step[i+2]=(step[i+1]+step[i])%MOD print(step[-1]%MOD) if __name__=='__main__': do()
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
1ceccd56e6f916af518465d5e03cdc7d5860afd4
c26b3a7d446fbfd71ce11e04129358c17dd6239a
/tAPP/3/P4.py
e0a55f3cd27e899abf582eb63103c2b47d192dfc
[ "MIT" ]
permissive
ArvinZJC/UofG_PGT_PSD_Python
4c4c2430cb95309a37086503e7ee638a45d571ab
d90e9bb0b53b14c6b1d7e657c3c61e2792e0d9c4
refs/heads/main
2023-05-09T21:18:07.847277
2021-06-14T17:26:38
2021-06-14T17:26:38
329,307,728
0
0
null
null
null
null
UTF-8
Python
false
false
1,419
py
''' Description: Problem 4 (complete the code) Version: 1.0.1.20210117 Author: Arvin Zhao Date: 2021-01-16 00:19:34 Last Editors: Arvin Zhao LastEditTime: 2021-01-17 12:13:41 ''' from tkinter import Tk, Label, Entry, Button from tkinter.constants import END def convert_to_km(): miles = textbox1.get() message = float(miles) / 1.6093 textbox2.delete(0, END) textbox2.insert(END, message) textbox2.insert(END, ' km') def convert_to_miles(): km = textbox1.get() km = int(km) message = km * 0.6214 textbox2.delete(0, END) textbox2.insert(END, message) textbox2.insert(END, ' miles') if __name__ == '__main__': window = Tk() window.title('Distance') window.geometry('260x200') label1 = Label(text = 'Enter the value you want to convert: ') label1.place(x = 30, y = 20) textbox1 = Entry(text = '') textbox1.place(x = 30, y = 50, width = 200, height = 25) textbox1['justify'] = 'center' textbox1.focus() convert1 = Button(text = 'Convert mile to km', command = convert_to_km) convert1.place(x = 30, y = 80, width = 200, height = 25) convert2 = Button(text = 'Convert km to mile', command = convert_to_miles) convert2.place(x = 30, y = 110, width = 200, height = 25) textbox2 = Entry(text = '') textbox2.place(x = 30, y = 140, width = 200, height = 25) textbox2['justify'] = 'center' window.mainloop()
[ "tomzjc@qq.com" ]
tomzjc@qq.com
11384963eb0c43c775c81061bdd8d70f1ecc25fe
4ad14e547695daaf4637c0790c21245a99fb6114
/Fmfiles/Fmfiles/pipelines.py
be1185d41ce5ce649a20c8f991da0de3c39a83d3
[]
no_license
gxl2632537/pachong
b8e1c26ef0e13504dc084b8e12975823126dac41
1ec30451e83a66768b4616ed9d736af8ee53deba
refs/heads/master
2022-11-07T02:16:42.549654
2020-06-30T09:47:34
2020-06-30T09:47:34
272,400,120
1
0
null
null
null
null
UTF-8
Python
false
false
1,596
py
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html import scrapy import os from scrapy.pipelines.files import FilesPipeline from Fmfiles.settings import FILES_STORE from scrapy.exceptions import DropItem class FmfilesPipeline(FilesPipeline): # 动态获取资源文件默认父目录“full”,并保存为属性 __file_dir = None # def process_item(self, item, spider): # return item def get_media_requests(self, item, info): file_url = item['file_url'] yield scrapy.Request(file_url) def item_completed(self, results, item, info): # file_paths系统自带的 file_paths = [x['path'] for ok, x in results if ok] if not self.__file_dir: self.__file_dir = file_paths[0].split('/')[0] if not file_paths: raise DropItem("Item contains no files") # os.rename(src,dst) 方法用于重命名文件或目录 src -- 要修改的目录名 dst -- 修改后的目录名 os.rename(FILES_STORE + file_paths[0], FILES_STORE + item['file_album'] + '/' + item['file_name']) return item def close_spider(self, spider): if self.__file_dir is None: return None ori_filepath = FILES_STORE + self.__file_dir if os.path.exists(ori_filepath): # os.rmdir() 方法用于删除指定路径的目录 如果文件已经存在则删除文件 os.rmdir(ori_filepath)
[ "l" ]
l
dc78ca14f957482b684aac9c5650a6871a3f4025
c7329046b8c19cb55e41e2275993b32fbec7b7eb
/test/test_mirage/test_model/test_impl/test_singular_isothermal_sphere.py
300b755948572277d34cde53d13dde974e235466
[ "MIT" ]
permissive
JordanKoeller/Mirage
72af9b7e6e71f97574e67eff400eb20dfa0a340e
5ed8dcf8934495bd18e534e54784e053475eb49e
refs/heads/main
2023-08-09T06:57:40.111101
2023-08-05T21:21:08
2023-08-05T21:21:08
147,987,257
0
1
null
null
null
null
UTF-8
Python
false
false
897
py
from unittest import TestCase from astropy import units as u from mirage.model.impl import SingularIsothermalSphereLens from mirage.model import Quasar from mirage.util import Vec2D, PolarVec class TestPointLens(TestCase): def get_lens(self): return SingularIsothermalSphereLens( quasar=Quasar(1.2, mass=u.Quantity(1e9, "solMass")), redshift=0.7, velocity_dispersion=u.Quantity(300, "km/s"), star_fraction=0.8, shear=PolarVec(u.Quantity(0.1, "rad"), u.Quantity(0.2, "rad")), ellipticity=PolarVec(u.Quantity(0.1, "rad"), u.Quantity(0.3, "rad")), ) def testEinsteinRadius_success(self): lens = self.get_lens() er = lens.einstein_radius self.assertEqual(er.unit, u.arcsec) def testMicrotracingParameters_success(self): lens = self.get_lens() tracing_params = lens.microtracing_parameters(Vec2D(2, 3, "arcsec"))
[ "jkoeller12@gmail.com" ]
jkoeller12@gmail.com
65d5a881a175b2753d0e88f4d19f3cd42c2452b9
4148260054c2cf4605dacb8bdef3605c82eca470
/temboo/Library/SendGrid/NewsletterAPI/ListsEmail/AddEmailToList.py
5d18334ef39a88208f7a4b7f40dc69496a4969ba
[]
no_license
wimsy/actuarize-web
0f23d5f00afe3d36d430621cdb497d2e64998416
5f43af3019da6fb08cafeec9ff0a89df5196b864
refs/heads/master
2021-03-12T19:38:21.887681
2012-12-19T01:13:50
2012-12-19T01:13:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,649
py
# -*- coding: utf-8 -*- ############################################################################### # # AddEmailToList # Add an email to an existing Recipient List. # # Python version 2.6 # ############################################################################### from temboo.core.choreography import Choreography from temboo.core.choreography import InputSet from temboo.core.choreography import ResultSet from temboo.core.choreography import ChoreographyExecution class AddEmailToList(Choreography): """ Create a new instance of the AddEmailToList Choreography. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. """ def __init__(self, temboo_session): Choreography.__init__(self, temboo_session, '/Library/SendGrid/NewsletterAPI/ListsEmail/AddEmailToList') def new_input_set(self): return AddEmailToListInputSet() def _make_result_set(self, result, path): return AddEmailToListResultSet(result, path) def _make_execution(self, session, exec_id, path): return AddEmailToListChoreographyExecution(session, exec_id, path) """ An InputSet with methods appropriate for specifying the inputs to the AddEmailToList choreography. The InputSet object is used to specify input parameters when executing this choreo. """ class AddEmailToListInputSet(InputSet): """ Set the value of the APIKey input for this choreography. ((required, string) The API Key obtained from SendGrid.) """ def set_APIKey(self, value): InputSet._set_input(self, 'APIKey', value) """ Set the value of the APIUser input for this choreography. ((required, string) The username registered with SendGrid.) """ def set_APIUser(self, value): InputSet._set_input(self, 'APIUser', value) """ Set the value of the Data input for this choreography. ((required, string) The JSON string containing the name, email and additional fields to be added to the specified recipient lists. Example: {"email":"address@example.com","name":"name","other_field":"value"}) """ def set_Data(self, value): InputSet._set_input(self, 'Data', value) """ Set the value of the List input for this choreography. ((required, string) The recipient list to which emaill addresses are being added. The list must be already existing.) """ def set_List(self, value): InputSet._set_input(self, 'List', value) """ Set the value of the ResponseFormat input for this choreography. ((optional, string) The format of the response from SendGrid, in either json, or xml. Default is set to json.) """ def set_ResponseFormat(self, value): InputSet._set_input(self, 'ResponseFormat', value) """ Set the value of the VaultFile input for this choreography. () """ """ A ResultSet with methods tailored to the values returned by the AddEmailToList choreography. The ResultSet object is used to retrieve the results of a choreography execution. """ class AddEmailToListResultSet(ResultSet): """ Retrieve the value for the "Response" output from this choreography execution. (The response from SendGrid. The format corresponds to the ResponseFormat input. Default is json.) """ def get_Response(self): return self._output.get('Response', None) class AddEmailToListChoreographyExecution(ChoreographyExecution): def _make_result_set(self, response, path): return AddEmailToListResultSet(response, path)
[ "mike.wimsatt@gmail.com" ]
mike.wimsatt@gmail.com
076599354848efd0d14fdc3c76a3c7360e7ed706
70b339d0b2638a7914d0d56c5edf8a2637c9f4b0
/thousandSeparator.py
999ebd880f493406a097ca8fd4036f33990e4133
[]
no_license
pflun/advancedAlgorithms
9991da7514024e18ba08de8688966b9220e12571
5520dbcd26999b98e1229bf03c2f62dd690a2ddc
refs/heads/master
2023-02-19T12:05:26.902535
2023-02-14T06:08:54
2023-02-14T06:08:54
189,055,701
4
0
null
null
null
null
UTF-8
Python
false
false
469
py
class Solution(object): def thousandSeparator(self, n): """ :type n: int :rtype: str """ res = [] while n / 1000 > 0: remain = str(n % 1000) if len(remain) == 1: remain = '00' + remain elif len(remain) == 2: remain = '0' + remain res = [remain] + res n /= 1000 res = [str(n % 1000)] + res return '.'.join(res)
[ "tango7down@icloud.com" ]
tango7down@icloud.com
4964d2f9abf377ed066bd2037665447f341785e3
8d54e547467ee9f91311dab51b6dd104e814f7d5
/text_txt_lmfit.py
dbab90c88c6528b1b9d01fa2e077bdbb7052b923
[]
no_license
alictg81/pyspeckit-tests
9dca6e41b8b783ef72d05f7135652efe6eddef1e
62153cb2dbff2cffda1a9c8f626ac4e1549f8532
refs/heads/master
2021-01-22T06:49:11.600689
2015-04-07T16:22:17
2015-04-07T16:22:17
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,784
py
from pyspeckit import spectrum if not 'interactive' in globals(): interactive=False if not 'savedir' in globals(): savedir = '' sp = spectrum.Spectrum('simple_txt.txt') print "Does it have an axis? ",sp.plotter.axis sp.plotter() print "How about now? ",sp.plotter.axis print "FITTING GAUSSIAN" sp.specfit(quiet=False) sp.specfit.annotate(loc='lower right') sp.plotter.figure.savefig(savedir+'txt_gaussfit.png') print "Guesses: ", sp.specfit.guesses print "Best fit: ", sp.specfit.modelpars print "Datamax: ",sp.data.max() if interactive: raw_input("Wait here a moment") # Fit a baseline, excluding the velocities with data, and don't subtract it print "FITTING BASELINE" sp.baseline(exclude=[2.111,2.129],subtract=False) # DEBUG added 1/16/2012 sp.baseline.highlight_fitregion() sp.plotter.figure.savefig(savedir+'txt_baseline.png') print "Baseline: ",sp.baseline.baselinepars #print "Excludepix: ",sp.baseline.excludepix #print "Excludevelo: ",sp.baseline.excludevelo print "EQW: ",sp.specfit.EQW() print "Datamax: ",sp.data.max() print "NOK: ",sp.baseline.OKmask.sum() print sp.data[sp.baseline.includemask] print sp.baseline.basespec if interactive: raw_input("Wait here a moment") print "REFITTING GAUSSIAN" sp.specfit(quiet=False) sp.specfit.annotate(loc='lower right') print "Guesses: ", sp.specfit.guesses print "Best fit: ", sp.specfit.modelpars print "Datamax: ",sp.data.max() sp.plotter.figure.savefig(savedir+'txt_baseline_gaussfit.png') if interactive: raw_input("Wait here a moment") print "EQW: ",sp.specfit.EQW(plot=True,annotate=True) sp.plotter.refresh() sp.plotter.figure.savefig(savedir+'txt_EQW.png') sp.specfit.add_sliders() if interactive: raw_input('Press enter to print guesses and best fit and end code') #from matplotlib import pyplot
[ "keflavich@gmail.com" ]
keflavich@gmail.com
225d064d759e8103f09dc0d0d525433e922a6c19
f8ece22d9e9e12e2cbca56d72a6b2728ba9a275a
/setup.py
28b7dbcd103df90c11e4c7e2ecd33447d0f296a8
[ "MIT" ]
permissive
pparan/polyaxon
8c8912f9ba724e007357efcaefeab86fec2d5630
423199721e90431209b00c0f76caa6b4f9aa4b24
refs/heads/master
2021-04-15T07:15:19.701268
2018-03-21T11:59:12
2018-03-21T11:59:12
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,047
py
#!/usr/bin/env python import sys from setuptools import find_packages, setup from setuptools.command.test import test as TestCommand class PyTest(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): import pytest errcode = pytest.main(self.test_args) sys.exit(errcode) setup(name='polyaxon', version='0.0.6', description='Deep Learning library for TensorFlow for ' 'building end to end models and experiments.', maintainer='Mourad Mourafiq', maintainer_email='mouradmourafiq@gmail.com', author='Mourad Mourafiq', author_email='mouradmourafiq@gmail.com', url='https://github.com/polyaxon/polyaxon', license='MIT', platforms='any', packages=find_packages(), keywords=[ 'polyaxon', 'tensorFlow', 'deep-learning', 'machine-learning', 'data-science', 'neural-networks', 'artificial-intelligence', 'ai', 'reinforcement-learning' ], install_requires=[ "celery==4.1.0", "Django==1.11.7", "django-cors-headers==2.1.0", "djangorestframework==3.7.0", "djangorestframework-camel-case==0.2.0", "docker==2.6.1", "GitPython==2.1.7", "Jinja2==2.9.6", "pika==0.11.0", "psycopg2==2.7.3.1", "redis==2.10.6", "sanic==0.6.0", "six==1.11.0", "Unipath==1.1", "uWSGI==2.0.15", "websockets==3.4", ], classifiers=[ 'Programming Language :: Python', 'Operating System :: OS Independent', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'Topic :: Scientific/Engineering :: Artificial Intelligence' ], tests_require=['pytest'], cmdclass={'test': PyTest})
[ "mouradmourafiq@gmail.com" ]
mouradmourafiq@gmail.com
caf878602d26dd8f569da3d2ddf5ec00fd85e19f
3c59fe3748fe0461d1327b9b751d8dc7c9405367
/teus_back/users/migrations/0014_auto_20210505_0038.py
47010d11a0dca65fd47a52b7741afa4401f6e016
[]
no_license
RympeR/teus-django-vue
8c69b5aaf38af091597065ab1306e33283846d16
b6be2bace144a0f3102339295eae05579657205e
refs/heads/main
2023-05-13T16:30:29.425392
2021-06-03T07:13:34
2021-06-03T07:13:34
342,588,668
0
0
null
null
null
null
UTF-8
Python
false
false
465
py
# Generated by Django 3.1.7 on 2021-05-04 21:38 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0013_auto_20210430_0435'), ] operations = [ migrations.AlterField( model_name='phone', name='expires_at', field=models.DateTimeField(default=datetime.datetime(2021, 5, 5, 0, 20), verbose_name='Expires at'), ), ]
[ "georg.rashkov@gmail.com" ]
georg.rashkov@gmail.com
931b73a7d655f1fb2521e8aeced917c19b27cb99
13eb4610eb9316c246768c7dffe94e24eb5ce3ed
/docs/conf.py
b320008b6bfca53accb03b2174ac8109ac31137d
[ "Apache-2.0" ]
permissive
webclinic017/pyEX-zipline
e5141b70424b0c04f7ad59a34ab9bcd26b817ec5
3d0636af2686861cd08054447bcc60190d48aedd
refs/heads/master
2022-07-22T08:38:08.060746
2020-05-19T19:32:16
2020-05-19T19:32:16
null
0
0
null
null
null
null
UTF-8
Python
false
false
7,420
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # pyEX.zipline documentation build configuration file, created by # sphinx-quickstart on Fri Jan 12 22:07:11 2018. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import sys import os import os.path import subprocess import sphinx_rtd_theme from recommonmark.transform import AutoStructify sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = ['sphinx.ext.coverage', 'sphinx.ext.viewcode', 'sphinx.ext.autodoc', 'sphinx.ext.napoleon', 'recommonmark'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = ['.rst', '.md'] # The master toctree document. master_doc = 'index' # General information about the project. project = 'pyEX.zipline' copyright = '2020, Tim Paine' author = 'Tim Paine' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # _version_py = os.path.join('..', 'pyEX', 'zipline', '_version.py') version_ns = {} with open(_version_py, mode='r') as version_file: exec(version_file.read(), version_ns) # The short X.Y version. version = '%i.%i' % version_ns['version_info'][:2] # The full version, including alpha/beta/rc tags. release = version_ns['__version__'] # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # # html_theme = 'alabaster' html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Custom sidebar templates, must be a dictionary that maps document names # to template names. # # This is required for the alabaster theme # refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars html_sidebars = { '**': [ 'relations.html', # needs 'show_related': True theme option to display 'searchbox.html', ] } # -- Options for HTMLHelp output ------------------------------------------ # Output file base name for HTML help builder. htmlhelp_basename = 'pyEXziplinedoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'pyEX.zipline.tex', 'pyEX.zipline Documentation', 'Tim Paine', 'manual'), ] # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'pyEX.zipline', 'pyEX.zipline Documentation', [author], 1) ] # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'pyEX.zipline', 'pyEX.zipline Documentation', author, 'pyEX.zipline', 'One line description of project.', 'Miscellaneous'), ] def run_copyreadme(_): out = os.path.abspath(os.path.join(os.path.dirname(__file__), 'index.md')) readme = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'README.md')) api = os.path.abspath(os.path.join(os.path.dirname(__file__), 'api.md')) with open(out, 'w') as fp1: with open(readme, 'r') as fp2: for line in fp2: if 'src=' in line: # <img> fp1.write(line.replace("docs/", "")) elif "](docs/" in line: # md fp1.write(line.replace("](docs/", "](")) else: fp1.write(line) fp1.write("# API Documentation\n\n") with open(api, 'r') as fp2: fp1.write(fp2.read()) def run_apidoc(_): out_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), 'api')) pyEX_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'pyEX')) cmd_path = 'sphinx-apidoc' if hasattr(sys, 'real_prefix'): # Check to see if we are in a virtualenv # If we are, assemble the path manually cmd_path = os.path.abspath(os.path.join(sys.prefix, 'bin', 'sphinx-apidoc')) subprocess.check_call([cmd_path, '-E', '-M', '-o', out_dir, pyEX_dir, '--force']) def setup(app): app.add_config_value('recommonmark_config', { 'auto_toc_tree_section': 'Contents', }, True) app.add_transform(AutoStructify) app.connect('builder-inited', run_copyreadme) app.connect('builder-inited', run_apidoc)
[ "t.paine154@gmail.com" ]
t.paine154@gmail.com
c1918f6020987d4268163b9fcd8cd562a0d239d6
cb30200e8af3a27f3d4faf7e0ca31bdb96f2f85a
/neutron/db/uos_db.py
97a8667d885eac45f0cd4a4a096228b44fc247b2
[ "Apache-2.0" ]
permissive
CingHu/neutron-ustack
ee7bf5a373dfc400c1ed86dedc7414c27185de4d
a1da17d0d63b3342a48c35da37984d6386ee1016
refs/heads/master
2016-08-13T02:02:48.179378
2015-11-27T02:46:46
2015-11-27T02:46:46
46,955,615
0
0
null
null
null
null
UTF-8
Python
false
false
2,291
py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2014 UnitedStack 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. # @author: Yong Sheng Gong, UnitedStack, inc. from neutron.api.v2 import attributes from neutron.db import db_base_plugin_v2 from neutron.extensions import l3 from neutron.openstack.common import timeutils def _uos_extend_timestamp(res, db): res['created_at'] = timeutils.strtime(db['created_at']) def _uos_extend_floatingip_dict_binding(core_plugin, res, db): _uos_extend_timestamp(res, db) def _uos_extend_router_dict_binding(core_plugin, res, db): _uos_extend_timestamp(res, db) def _uos_extend_network_dict_binding(core_plugin, res, db): _uos_extend_timestamp(res, db) def _uos_extend_port_dict_binding(core_plugin, res, db): _uos_extend_timestamp(res, db) def _uos_extend_subnet_dict_binding(core_plugin, res, db): _uos_extend_timestamp(res, db) def _uos_extend_sg_dict_binding(core_plugin, res, db): _uos_extend_timestamp(res, db) db_base_plugin_v2.NeutronDbPluginV2.register_dict_extend_funcs( l3.FLOATINGIPS, [_uos_extend_floatingip_dict_binding]) db_base_plugin_v2.NeutronDbPluginV2.register_dict_extend_funcs( l3.ROUTERS, [_uos_extend_router_dict_binding]) db_base_plugin_v2.NeutronDbPluginV2.register_dict_extend_funcs( attributes.NETWORKS, [_uos_extend_network_dict_binding]) db_base_plugin_v2.NeutronDbPluginV2.register_dict_extend_funcs( attributes.PORTS, [_uos_extend_port_dict_binding]) db_base_plugin_v2.NeutronDbPluginV2.register_dict_extend_funcs( attributes.SUBNETS, [_uos_extend_subnet_dict_binding]) db_base_plugin_v2.NeutronDbPluginV2.register_dict_extend_funcs( 'security_groups', [_uos_extend_sg_dict_binding])
[ "xining@unitedstack.com" ]
xining@unitedstack.com
2eb41a9f7840f3f1afa3331c5e071c1d40c62578
d3c21f0051e5ca2f45d98381b0372b4cd916b213
/cgi-bin/module/plugins/hoster/RarefileNet.py
8339d40eb79d560f8e907c754e90918bee1bd306
[]
no_license
f3l/shareacc
ca165272f4265180d9178b6a066c69a0b368f8dd
615c71216317f7ac46b5217f5672cad0c71a1e49
refs/heads/master
2020-04-06T06:41:11.278718
2013-02-05T15:15:15
2013-02-05T15:15:15
4,640,503
0
1
null
null
null
null
UTF-8
Python
false
false
1,095
py
# -*- coding: utf-8 -*- import re from module.plugins.hoster.XFileSharingPro import XFileSharingPro, create_getInfo from module.utils import html_unescape class RarefileNet(XFileSharingPro): __name__ = "RarefileNet" __type__ = "hoster" __pattern__ = r"http://(?:\w*\.)*rarefile.net/\w{12}" __version__ = "0.01" __description__ = """Rarefile.net hoster plugin""" __author_name__ = ("zoidberg") __author_mail__ = ("zoidberg@mujmail.cz") FILE_NAME_PATTERN = r'<td><font color="red">(?P<N>.*?)</font></td>' FILE_SIZE_PATTERN = r'<td>Size : (?P<S>.+?)&nbsp;' def handleCaptcha(self, inputs): captcha_div = re.search(r'<b>Enter code.*?<div.*?>(.*?)</div>', self.html, re.S).group(1) self.logDebug(captcha_div) numerals = re.findall('<span.*?padding-left\s*:\s*(\d+).*?>(\d)</span>', html_unescape(captcha_div)) inputs['code'] = "".join([a[1] for a in sorted(numerals, key = lambda num: int(num[0]))]) self.logDebug("CAPTCHA", inputs['code'], numerals) return 3 getInfo = create_getInfo(RarefileNet)
[ "root@server3.kruton.de" ]
root@server3.kruton.de
284d78f1fcbbd919d674c1a864e74677d41bcf25
8a8438419c211d1c3f3333d9215d501ee5aa745a
/annotation/annot_express.py
58959152c5c2b2d83da9965f1eaa45af7241adbb
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
WhiteLab/RNAseq
fb6478f0c8df3ee816d13b7e8998e4440a0ce7a3
ea34f2d0b886076007fa382a87d37cd41e8417bb
refs/heads/master
2021-01-25T15:56:56.386057
2018-04-19T17:03:40
2018-04-19T17:03:40
33,335,010
1
2
null
null
null
null
UTF-8
Python
false
false
1,728
py
#!/usr/bin/env python3 import sys def make_index(index_ref): ind = {} index = open(index_ref, 'r') next(index) for line in index: ann = line.rstrip('\n').split('\t') ind[ann[0]] = {} ind[ann[0]]['name'] = ann[1] ind[ann[0]]['type'] = ann[2] index.close() return ind def annot_express(index_ref, sample): ind = make_index(index_ref) table = open(sample + '.express_quantification.txt', 'r') head = next(table) out_fn = sample + '.express_quantification_annotated.txt' out_fh = open(out_fn, 'w') out_fh.write('name\ttype\t' + head) for line in table: info = line.split('\t') if float(info[3]) > 0: out_fh.write(ind[info[1]]['name'] + '\t ' + ind[info[1]]['type'] + '\t' + line) # skipping this part, ends up being a fat log generator # else: # sys.stderr.write('Skipped ' + ind[info[1]]['name'] + ' ' + ind[info[1]]['type'] + ' ' + info[1] # + ' no reads!\n') table.close() return 0 if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description='Quantify transcripts using STAR output bam') parser.add_argument('-i', '--index', action='store', dest='index', help='Reference file with RNA gene names,' ' type and trasncript ids') parser.add_argument('-sa', '--sample', action='store', dest='sample', help='Sample name prefix') if len(sys.argv) == 1: parser.print_help() sys.exit(1) inputs = parser.parse_args() index = inputs.index sample = inputs.sample annot_express(index, sample)
[ "miguel.a.brown@gmail.com" ]
miguel.a.brown@gmail.com
c70cf1d502370239756e3024f3a99e04f5a385ee
b5cba88ce8c86740c8c3453134610fd5bafbb8c4
/Leetcode/1295. Find Numbers with Even Number of Digits/solution.py
49f4d0d266abbbea8614c1133f3ae970bf4a6cf3
[]
no_license
EduardoSantos7/Algorithms4fun
55fcf9d515ea3b70b93298ac96a58d2ae68dee11
6ff182ed596b6322322b087f29e6ad98baec3f97
refs/heads/master
2023-07-23T01:38:08.216313
2023-07-23T01:35:58
2023-07-23T01:35:58
227,448,848
1
1
null
null
null
null
UTF-8
Python
false
false
465
py
class Solution: def findNumbers(self, nums: List[int]) -> int: result = 0 seen = {} for num in nums: if num in seen: if not seen[num] % 2: result += 1 continue count = 0 while num > 0: num //= 10 count += 1 seen[num] = count if not count % 2: result += 1 return result
[ "eduardoluissd@gmail.com" ]
eduardoluissd@gmail.com
b32a32aa16e78d200314b7da8479cb85659f5783
d74913eda69ee1799c887a645c574fa5a4da8fba
/code/download/download_soils.py
225e8cea96a34dccc9d990085c4111021268eeee
[ "Apache-2.0" ]
permissive
Fweek/pyMETRIC
efd6fe8c6ea74f5c87d19ecbb6653549fb3ba943
0e7eec57fedd33b81e6e7efe58290f50ebbebfab
refs/heads/master
2021-05-03T10:23:15.066106
2018-02-06T19:32:36
2018-02-06T19:32:36
120,534,046
1
0
null
2018-02-06T23:00:49
2018-02-06T23:00:48
null
UTF-8
Python
false
false
2,953
py
#-------------------------------- # Name: download_soils.py # Purpose: Download soil AWC raster # Python: 2.7, 3.5, 3.6 #-------------------------------- import argparse import datetime as dt import logging import os import sys import zipfile from python_common import url_download def main(output_folder, overwrite_flag=False): """Download soil Available Water Capacity (AWC) raster Args: output_folder (str): folder path where files will be saved overwrite_flag (bool): If True, overwrite existing files Returns: None """ # Composite SSURGO/STATSGO download_url = 'https://storage.googleapis.com/openet/ssurgo/AWC_WTA_0to10cm_composite.tif' # STATSGO Only # download_url = 'https://storage.googleapis.com/openet/statsgo/AWC_WTA_0to10cm_statsgo.tif' output_name = download_url.split('/')[-1] output_path = os.path.join(output_folder, output_name) if not os.path.isdir(output_folder): os.makedirs(output_folder) if not os.path.isfile(output_path) or overwrite_flag: logging.info('\nDownloading AWC') logging.info(' {}'.format(download_url)) logging.info(' {}'.format(output_path)) url_download(download_url, output_path) else: logging.debug('\nAWC raster already downloaded') def arg_parse(): """Base all default folders from script location scripts: ./pyMETRIC/code/download code: ./pyMETRIC/code output: ./pyMETRIC/soils """ script_folder = sys.path[0] code_folder = os.path.dirname(script_folder) project_folder = os.path.dirname(code_folder) output_folder = os.path.join(project_folder, 'soils') parser = argparse.ArgumentParser( description='Download Soil Available Water Capcity (AWC)', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( '--output', help='Output folder', metavar='FOLDER', default=os.path.join(project_folder, 'soils')) parser.add_argument( '-o', '--overwrite', default=None, action="store_true", help='Force overwrite of existing files') parser.add_argument( '-d', '--debug', default=logging.INFO, const=logging.DEBUG, help='Debug level logging', action="store_const", dest="loglevel") args = parser.parse_args() # Convert output folder to an absolute path if args.output and os.path.isdir(os.path.abspath(args.output)): args.output = os.path.abspath(args.output) return args if __name__ == '__main__': args = arg_parse() logging.basicConfig(level=args.loglevel, format='%(message)s') logging.info('\n{}'.format('#' * 80)) log_f = '{:<20s} {}' logging.info(log_f.format('Run Time Stamp:', dt.datetime.now().isoformat(' '))) logging.info(log_f.format('Script:', os.path.basename(sys.argv[0]))) main(output_folder=args.output, overwrite_flag=args.overwrite)
[ "dgketchum@gmail.com" ]
dgketchum@gmail.com
9bb59c34c03b8d36943b1d47bfe4981e476e6a7a
dc19e59cac871b172eb357499159b92fca81e5ca
/docs/toHTML.py
2fa74dd72b05a9428d6b26b2a2bd5657a4b5a5b1
[ "MIT" ]
permissive
numython-rd/moro
ed3fe76b35ce190244503c40a445fbbd42143278
8d6e15ba21a0de7ec354ccbc23c38123a570904a
refs/heads/master
2023-03-26T18:48:07.588409
2021-03-18T01:50:14
2021-03-18T01:50:14
300,115,200
0
0
null
null
null
null
UTF-8
Python
false
false
166
py
# -*- coding: utf-8 -*- import os source = "source" build = "." instr = "sphinx-build -b html "+source+" "+build os.system(instr) os.startfile(build+r"\index.html")
[ "delossantosmfq@gmail.com" ]
delossantosmfq@gmail.com
9b69bc22bdfcfa2d1afe985f945375682c176ad1
57fab09b925d5ad305c7d3768c06e82e0b867d47
/bag/reorder_po.py
e821d44e2e5d57009c4748129ada5ee0dee22408
[ "MIT" ]
permissive
nandoflorestan/bag
f6b042341cdf96812ae34320879a6b67fb6884c9
63f6fbd3e768bf55d79ac96964aa3bf7702f3f9a
refs/heads/master
2023-08-04T23:43:27.961604
2023-07-31T15:12:44
2023-07-31T15:12:44
9,621,828
24
6
null
2015-07-17T05:10:23
2013-04-23T11:46:23
Python
UTF-8
Python
false
false
1,266
py
"""Reorder the translations inside a .po file. This script was written because transifex is messy and when you pull translations from transifex, the order of the strings completely changes and when you do a ``git diff`` you cannot make sense of the alterations. It is even hard to see whether any translations have been lost. But if you always reorder the .po after pulling from transifex, then the diff will be readable and the version history will make sense. """ from argh import ArghParser, arg from pathlib import Path from polib import pofile @arg("path", help=".po file to be sorted, or a directory containing .po files") @arg("-e", "--encoding", default="utf-8", help=".po file encoding") def reorder_po(path, encoding="utf-8"): p = Path(path) if p.is_dir(): for path in p.glob("**.po"): _reorder_one(str(path), encoding=encoding) else: _reorder_one(str(path), encoding=encoding) def _reorder_one(path, encoding="utf-8"): po = pofile(path, encoding=encoding) po.sort() po.save(path) def _command(): # http://argh.readthedocs.org/en/latest/ parser = ArghParser(description=__doc__) parser.set_default_command(reorder_po) parser.dispatch() if __name__ == "__main__": _command()
[ "nandoflorestan@gmail.com" ]
nandoflorestan@gmail.com
7aa043d24cb175a85f93b7c12cd0cba2de709b61
5da2c116d3d0dc4f3811cec144c9f8b5a74afede
/lncrawl/sources/fanfiction.py
c29ccaba499a13167460d62aad29c76ad932190c
[ "Apache-2.0" ]
permissive
NNTin/lightnovel-crawler
a08bd252f2e72f41f931f0b2165f906b64d33692
451e816ab03c8466be90f6f0b3eaa52d799140ce
refs/heads/master
2021-06-23T12:07:43.668329
2021-04-25T01:51:26
2021-04-25T01:51:26
361,695,538
2
0
Apache-2.0
2021-04-26T16:48:21
2021-04-26T09:40:46
null
UTF-8
Python
false
false
3,425
py
# -*- coding: utf-8 -*- import json import logging import re from urllib.parse import urlparse from ..utils.crawler import Crawler logger = logging.getLogger(__name__) chapter_url = 'https://www.fanfiction.net/s/%s/%s' search_url = 'https://www.fanfiction.net/search/?keywords=%s&type=story&match=title&ready=1&categoryid=202' class FanFictionCrawler(Crawler): base_url = 'https://www.fanfiction.net/' def search_novel(self, query): query = query.lower().replace(' ', '+') soup = self.get_soup(search_url % query) results = [] for div in soup.select('#content_wrapper .z-list')[:25]: a = div.select_one('a.stitle') a.select_one('img').decompose() info = div.select_one('.xgray').text.strip() chapters = re.findall(r'Chapters: \d+', info)[0] origin_book = re.findall(r'^.+Rated:', info)[0][:-9] writer = div.select_one('a[href*="/u/"]').text.strip() results.append({ 'title': a.text.strip(), 'url': self.absolute_url(a['href']), 'info': '%s | %s | By, %s' % (origin_book, chapters, writer) }) # end for return results # end def def read_novel_info(self): '''Get novel title, autor, cover etc''' logger.debug('Visiting %s', self.novel_url) soup = self.get_soup(self.novel_url) self.novel_title = soup.select_one( '#profile_top b.xcontrast_txt, #content b').text.strip() logger.info('Novel title: %s', self.novel_title) possible_image = soup.select_one('#profile_top img.cimage') if possible_image: self.novel_cover = self.absolute_url(possible_image['src']) # end if logger.info('Novel cover: %s', self.novel_cover) self.novel_author = soup.select_one( '#profile_top, #content').select_one('a[href*="/u/"]').text.strip() logger.info('Novel author: %s', self.novel_author) self.novel_id = urlparse(self.novel_url).path.split('/')[2] logger.info('Novel id: %s', self.novel_id) if soup.select_one('#pre_story_links'): origin_book = soup.select('#pre_story_links a')[-1] self.volumes.append({ 'id': 1, 'title': origin_book.text.strip(), }) else: self.volumes.append({'id': 1}) # end if chapter_select = soup.select_one('#chap_select, select#jump') if chapter_select: for option in chapter_select.select('option'): self.chapters.append({ 'volume': 1, 'id': int(option['value']), 'title': option.text.strip(), 'url': chapter_url % (self.novel_id, option['value']), }) # end for else: self.chapters.append({ 'id': 1, 'volume': 1, 'url': self.novel_url, }) # end if # end def def download_chapter_body(self, chapter): '''Download body of a single chapter and return as clean html format.''' logger.info('Downloading %s', chapter['url']) soup = self.get_soup(chapter['url']) contents = soup.select_one('#storytext, #storycontent') return str(contents) # end def # end class
[ "dipu.sudipta@gmail.com" ]
dipu.sudipta@gmail.com
02f21d9e9666ff708866722614bcd616ca5d00fc
9ecb6a1d3a71e7f87f3784af6b808f23a2abe348
/spinningup/spinup/algos/td3/core.py
b9e2b6ad2e3dcfd388dc765ca58d71b8d7a6a6b4
[ "MIT" ]
permissive
HumanCompatibleAI/interactive-behaviour-design
13ae305b39d29595e8fd5907f8d9e9fa6c2efc16
226db7a55d64ce15edfb8d7b3352c7bf7b81b533
refs/heads/master
2020-05-02T16:54:02.232639
2019-08-08T14:29:11
2019-08-08T14:29:11
178,082,205
0
1
null
null
null
null
UTF-8
Python
false
false
1,565
py
import numpy as np import tensorflow as tf def placeholder(dim=None): return tf.placeholder(dtype=tf.float32, shape=(None,dim) if dim else (None,)) def placeholders(*args): return [placeholder(dim) for dim in args] def mlp(x, hidden_sizes=(32,), activation=tf.tanh, output_activation=None): for h in hidden_sizes[:-1]: x = tf.layers.dense(x, units=h, activation=activation) return tf.layers.dense(x, units=hidden_sizes[-1], activation=output_activation, kernel_initializer=tf.initializers.orthogonal(gain=0.01)) def get_vars(scope): return [x for x in tf.global_variables() if scope in x.name] def count_vars(scope): v = get_vars(scope) return sum([np.prod(var.shape.as_list()) for var in v]) """ Actor-Critics """ def mlp_actor_critic(x, a, hidden_sizes=(400,300), activation=tf.nn.relu, output_activation=tf.tanh, action_space=None): act_dim = a.shape.as_list()[-1] act_limit = action_space.high[0] with tf.variable_scope('pi'): pi = act_limit * mlp(x, list(hidden_sizes)+[act_dim], activation, output_activation) with tf.variable_scope('q1'): q1 = tf.squeeze(mlp(tf.concat([x,a], axis=-1), list(hidden_sizes)+[1], activation, None), axis=1) with tf.variable_scope('q2'): q2 = tf.squeeze(mlp(tf.concat([x,a], axis=-1), list(hidden_sizes)+[1], activation, None), axis=1) with tf.variable_scope('q1', reuse=True): q1_pi = tf.squeeze(mlp(tf.concat([x,pi], axis=-1), list(hidden_sizes)+[1], activation, None), axis=1) return pi, q1, q2, q1_pi
[ "matthew.rahtz@gmail.com" ]
matthew.rahtz@gmail.com
f29c1c8d352d400edd2c54e09c41c0ff74480335
2761a7b1b89c3bc250d5848c0fb2bde23a46989c
/costom_tfp_model_/bayesian/train.py
732910532341d2d516189d906694cc89e4632fb7
[]
no_license
mahdisharifloo/tensorflow_lite_projects
9daa051297395903f788ed2841c7b7d3406c284e
0f178b484ed667581e5edc882339c4699a5d0378
refs/heads/master
2022-11-29T05:34:29.525744
2020-08-12T20:26:40
2020-08-12T20:26:40
284,647,945
3
0
null
null
null
null
UTF-8
Python
false
false
3,877
py
# -*- coding: utf-8 -*- import pandas as pd import numpy as np import itertools import tensorflow_probability as tfp import tensorflow as tf import tensorflow.keras as keras from sklearn import metrics from sklearn.metrics import confusion_matrix from tensorflow.keras.preprocessing.image import ImageDataGenerator, img_to_array, load_img from tensorflow.keras.models import Sequential from tensorflow.keras import optimizers from tensorflow.keras.preprocessing import image from tensorflow.keras.layers import Dropout, Flatten, Dense from tensorflow.keras import applications from tensorflow.keras.utils import to_categorical import matplotlib.pyplot as plt import matplotlib.image as mpimg import math import datetime import time # load the bottleneck features saved earlier train_data = np.load('bottleneck_features_train.npy') test_data = np.load('bottleneck_features_test.npy') # get the class labels for the training data, in the original order train_labels = generator_top.classes test_labels = val_generator_top.classes # convert the training labels to categorical vectors train_labels = to_categorical(train_labels, num_classes=num_classes) test_labels = to_categorical(test_labels, num_classes=num_classes) start = datetime.datetime.now() kernel_divergence_fn=lambda q, p, _: tfp.distributions.kl_divergence(q, p) / (train_data.shape[0] *1.0) model_vi = Sequential() # model_vi.add(Flatten(input_shape=train_data.shape[1:])) model_vi.add(tf.keras.layers.InputLayer(input_shape=train_data.shape[1:], name="input")) model_vi.add(tfp.layers.Convolution2DFlipout(8,kernel_size=(3,3),padding="same", activation = 'relu', kernel_divergence_fn=kernel_divergence_fn,input_shape=(32,32,3))) model_vi.add(tfp.layers.Convolution2DFlipout(8,kernel_size=(3,3),padding="same", activation = 'relu', kernel_divergence_fn=kernel_divergence_fn)) model_vi.add(tf.keras.layers.MaxPooling2D((2,2))) model_vi.add(tfp.layers.Convolution2DFlipout(16,kernel_size=(3,3),padding="same", activation = 'relu', kernel_divergence_fn=kernel_divergence_fn)) model_vi.add(tfp.layers.Convolution2DFlipout(16,kernel_size=(3,3),padding="same", activation = 'relu', kernel_divergence_fn=kernel_divergence_fn)) model_vi.add(tf.keras.layers.MaxPooling2D((2,2))) model_vi.add(tf.keras.layers.Flatten()) model_vi.add(tfp.layers.DenseFlipout(100, activation = 'relu', kernel_divergence_fn=kernel_divergence_fn)) model_vi.add(tfp.layers.DenseFlipout(100, activation = 'relu', kernel_divergence_fn=kernel_divergence_fn)) model_vi.add(tfp.layers.DenseFlipout(num_classes, activation = 'softmax', kernel_divergence_fn=kernel_divergence_fn)) model_vi.compile(loss='categorical_crossentropy', optimizer=optimizers.RMSprop(lr=1e-4), metrics=['accuracy']) model_vi.summary() history = model_vi.fit(train_data, train_labels, epochs=epochs, batch_size=batch_size, validation_data=(test_data, test_labels)) (eval_loss, eval_accuracy) = model_vi.evaluate( test_data, test_labels, batch_size=batch_size,verbose=1) print("[INFO] accuracy: {:.2f}%".format(eval_accuracy * 100)) print("[INFO] Loss: {}".format(eval_loss)) end= datetime.datetime.now() elapsed= end-start print ("Time: ", elapsed) model_vi.save_weights(top_model_weights_path) #Graphing our training and validation acc = history.history['accuracy'] val_acc = history.history['val_accuracy'] loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(len(acc)) plt.plot(epochs, acc, 'r', label='Training acc') plt.plot(epochs, val_acc, 'b', label='Validation acc') plt.title('Training and validation accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend() plt.figure() plt.plot(epochs, loss, 'r', label='Training loss') plt.plot(epochs, val_loss, 'b', label='Validation loss') plt.title('Training and validation loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend() plt.show()
[ "0059sharifloo@gmail.com" ]
0059sharifloo@gmail.com
f7060334136865396f4d86572f5cd846a5112c05
6a33cb94d4af1d8a7329ddc6c9d42f870c35bb2f
/python/euler29.py
d9b80faeb8ae6bc4abadea9e824c11439db0308a
[]
no_license
vochong/project-euler
836321cc8e7d2e7cdf22b3b136d44dcba74a8701
6a0c7103861ff825bf84800b6e2e62819a41e36d
refs/heads/master
2020-04-29T10:41:48.487159
2018-09-19T00:13:34
2018-09-19T00:13:34
null
0
0
null
null
null
null
UTF-8
Python
false
false
665
py
def euler29(): """ Consider all integer combinations of ab for 2 <= a <= 5 and 2 <= b <= 5: 22=4, 23=8, 24=16, 25=32 32=9, 33=27, 34=81, 35=243 42=16, 43=64, 44=256, 45=1024 52=25, 53=125, 54=625, 55=3125 If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms: 4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125 How many distinct terms are in the sequence generated by ab for 2 <= a <= 100 and 2 <= b <= 100? """ pows = [] for a in range(2, 101): for b in range(2, 101): pows.append(a**b) return len(set(pows)) if __name__ == "__main__": print euler29()
[ "kueltz.anton@gmail.com" ]
kueltz.anton@gmail.com
21ac3eeda637128a5f315d8c4bcc6ebe54e963fd
b06b6ac432961322f5a55a4cf8ad9bba27622042
/pages/migrations/0002_auto__add_field_page_header_image.py
6e136301447e3fe351716caa165da6d8bfacd5d2
[ "BSD-2-Clause" ]
permissive
jpic/pescator
97a4e2ba62485d3fa537c060876b7fd04d3286e4
0d3140ac4c8b07940c2f4753c6f8cb5ac95d8292
refs/heads/master
2021-01-01T15:45:16.610383
2013-11-29T19:03:20
2013-11-29T19:03:20
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,847
py
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Page.header_image' db.add_column(u'pages_page', 'header_image', self.gf('django.db.models.fields.files.ImageField')(max_length=100, null=True, blank=True), keep_default=False) def backwards(self, orm): # Deleting field 'Page.header_image' db.delete_column(u'pages_page', 'header_image') models = { u'pages.block': { 'Meta': {'ordering': "(u'name',)", 'object_name': 'Block'}, 'body': ('redactor.fields.RedactorField', [], {}), 'body_en': ('redactor.fields.RedactorField', [], {'null': 'True', 'blank': 'True'}), 'body_fr': ('redactor.fields.RedactorField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'name_en': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'name_fr': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'template': ('django.db.models.fields.CharField', [], {'default': "u'pages/block.html'", 'max_length': '50'}) }, u'pages.page': { 'Meta': {'ordering': "(u'name',)", 'object_name': 'Page'}, 'blocks': ('sortedm2m.fields.SortedManyToManyField', [], {'to': u"orm['pages.Block']", 'symmetrical': 'False', 'blank': 'True'}), 'body': ('redactor.fields.RedactorField', [], {}), 'body_en': ('redactor.fields.RedactorField', [], {'null': 'True', 'blank': 'True'}), 'body_fr': ('redactor.fields.RedactorField', [], {'null': 'True', 'blank': 'True'}), 'header_image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'name_en': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'name_fr': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'photos': ('sortedm2m.fields.SortedManyToManyField', [], {'to': u"orm['pages.Photo']", 'symmetrical': 'False', 'blank': 'True'}), 'slug': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'slug_en': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'slug_fr': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'template': ('django.db.models.fields.CharField', [], {'default': "u'pages/page_detail.html'", 'max_length': '50'}) }, u'pages.photo': { 'Meta': {'ordering': "(u'name',)", 'object_name': 'Photo'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'name_en': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'name_fr': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}) } } complete_apps = ['pages']
[ "jamespic@gmail.com" ]
jamespic@gmail.com
98d31e2bc1edb6dbcb1566b0a6c71cd60d65e3f1
922227eabe29f0a6779bd28ae037a46acbe06d6a
/apps/fsq/views.py
d44303731e3604fb369584f6849601bcbcb8116d
[]
no_license
rootart/geojam
2acf6f0289c372e482998732faa31bee222b065a
1ac99f5428ddae5c5e7f10c685075cf8a52843c8
refs/heads/master
2020-05-18T07:44:06.126567
2011-08-19T19:49:16
2011-08-19T19:49:16
2,235,935
0
0
null
null
null
null
UTF-8
Python
false
false
3,223
py
from django.http import ( HttpResponseRedirect, HttpResponse, HttpResponseForbidden ) from django.conf import settings from django.contrib.auth import login, authenticate, logout from django.core.urlresolvers import reverse from django.contrib.gis.geos import * import oauth2 as oauth import urllib try: import simplejson as json except ImportError: import json from core.models import Checkin SERVER = getattr(settings, 'OAUTH_SERVER', 'foursquare.com') AUTHENTICATE_URL = getattr(settings, 'OAUTH_REQUEST_TOKEN_URL', 'http://%s/oauth2/authenticate' % SERVER) ACCESS_TOKEN_URL = getattr(settings, 'OAUTH_ACCESS_TOKEN_URL', 'http://%s/oauth2/access_token' % SERVER) API_URL= "https://api.foursquare.com/v2/" FOURSQUARE_CONSUMER_KEY = getattr(settings, 'FOURSQUARE_CONSUMER_KEY', 'YOUR_KEY') FOURSQUARE_CONSUMER_SECRET = getattr(settings, 'FOURSQUARE_CONSUMER_SECRET', 'YOUR_SECRET') def auth(request): params = { 'response_type': 'code', 'client_id': FOURSQUARE_CONSUMER_KEY, 'redirect_uri': 'http://geojam.djangostars.com/auth/return/' } url = AUTHENTICATE_URL + "?" + urllib.urlencode(params) return HttpResponseRedirect(url) def logout_(request): request.session.clear() logout(request) return HttpResponseRedirect(reverse('dashboard')) def fetch_data(api, token): link = API_URL + api + "?oauth_token=" + token try: f = urllib.urlopen(link) except: pass else: return json.loads(f.read()) def fetch_checkins(token): api = 'users/self/checkins' link = API_URL + api + "?oauth_token=" + token try: f = urllib.urlopen(link) except: pass data = json.loads(f.read()) for item in data['response']['checkins']['items']: geodata = Point( item['venue']['location']['lng'], item['venue']['location']['lat']) # import pdb # pdb.set_trace() checkin = Checkin( type = 2, title = item['venue']['name'], geodata = geodata ) checkin.save() def return_(request): code = request.GET.get('code', None) if code: params = { 'client_id': FOURSQUARE_CONSUMER_KEY, 'client_secret': FOURSQUARE_CONSUMER_SECRET, 'grant_type': 'authorization_code', 'redirect_uri': 'http://geojam.djangostars.com/auth/return/', 'code': code, } params = urllib.urlencode(params) f = urllib.urlopen(ACCESS_TOKEN_URL+"?"+params) token = f.read() token = json.loads(token)['access_token'] # Get user information using api request data = fetch_data('users/self', token) foursquare_user_data = data['response']['user'] user = authenticate(foursquare_user_data=foursquare_user_data, access_token=token) login(request, user) request.session['token_%s' % user.username] = token # Fetch last 100 checkins from foursquare fetch_checkins(token) return HttpResponseRedirect(reverse('dashboard')) else: return HttpResponseForbidden("Hei, Go away!")
[ "dijakroot@gmail.com" ]
dijakroot@gmail.com
8b5625755b9e41df88d4a4fa0ad12b81868a1b34
35a6f993b84afdd2c0ade094e0312b3aaa53294f
/src/tag_server/mit-cf/tag/views.py
c82f2d03e392253686f1b08a315d5390d5336484
[]
no_license
MIT-repository/tag_server
3266875ac8efee255b324eead419a62a0320f511
488b0582b1341d0a1d372681d57aa456b7d5c9d6
refs/heads/master
2022-12-09T00:21:41.601852
2020-08-19T12:24:01
2020-08-19T12:24:01
288,722,644
0
1
null
null
null
null
UTF-8
Python
false
false
1,410
py
from django.http import HttpResponse, JsonResponse from django.shortcuts import render import os, boto3 from .models import Song from .DeepAudioClassification.main import predict # Create your views here. service_name = os.environ.get('service_name') endpoint_url = os.environ.get('s3_url') region_name = os.environ.get('reg') access_key = os.environ.get('s3_key') secret_key = os.environ.get('secret_key') s3 = boto3.client(service_name, endpoint_url=endpoint_url, aws_access_key_id=access_key, aws_secret_access_key=secret_key) base = os.path.dirname( os.path.abspath( __file__ ) ) master_path = base+'/DeepAudioClassification/Prediction/' #master_path = '/' def tag(requests, bucket,folder, name): down_name = folder+'/'+name local_file_path = master_path + 'Raw/{}'.format(name) # try: # song = Song.objects.get(name=name,bucket=bucket) print("download :", local_file_path) #except Exception as err: #print(err) s3.download_file(bucket, down_name, local_file_path) #song = Song.objects.create(name=name, bucket=bucket, genre='test') genre = predict() os.remove(local_file_path) os.remove(master_path+'Slices/predict/*') return JsonResponse( { "bucket": bucket, "name": name, "genre": genre }, safe=False, json_dumps_params={'ensure_ascii': False} )
[ "l4538@naver.com" ]
l4538@naver.com
392292d26e820beee08966256dc3b7e7deabcff6
13b46582bb6bbfe08a2e24127198ded24e6c0ad3
/server/security/migrations/0002_auto_20210103_2232.py
6e941810356d692616f510085d017f85a27449ad
[]
no_license
dmetrosoft/seo-audits-toolkit
9b12735d8345ef5075e87e6ea09440e01e32746f
c3e95fc4bf51d72e61c0507c14bd384d2368f475
refs/heads/master
2023-08-25T06:11:54.055464
2021-04-08T15:51:23
2021-04-08T15:51:23
null
0
0
null
null
null
null
UTF-8
Python
false
false
706
py
# Generated by Django 3.1.4 on 2021-01-03 22:32 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('security', '0001_initial'), ] operations = [ migrations.RenameField( model_name='security_result', old_name='pwa_score', new_name='result', ), migrations.AddField( model_name='security', name='score', field=models.CharField(max_length=20, null=True), ), migrations.AddField( model_name='security_result', name='score', field=models.CharField(max_length=20, null=True), ), ]
[ "stan@primates.dev" ]
stan@primates.dev
0254a942224af44e67171f739c52b55757946efb
84688ba401bb0d82f5345d7b2c1c91c1b82b8c41
/notifications/migrations/0002_auto_20190726_2030.py
88f0133b4bf298f0baf1018c1867724b1a9f4611
[]
no_license
AbrahamMayowa/edupam
14878df433f356b60c0bda700457123c6db8c734
97908dc56913d0a06fa0340c5985496935b9a097
refs/heads/master
2023-05-10T23:42:37.043219
2022-10-11T09:19:58
2022-10-11T09:19:58
167,404,444
0
0
null
2023-04-30T07:46:03
2019-01-24T17:02:44
JavaScript
UTF-8
Python
false
false
1,124
py
# Generated by Django 2.1.3 on 2019-07-26 20:30 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('notifications', '0001_initial'), ] operations = [ migrations.AddField( model_name='thumpednotification', name='is_comment_thump', field=models.BooleanField(default=False), ), migrations.AlterField( model_name='thumpednotification', name='created', field=models.DateTimeField(auto_now_add=True, db_index=True), ), migrations.AlterField( model_name='thumpednotification', name='target_id', field=models.PositiveIntegerField(blank=True, db_index=True, null=True), ), migrations.AlterField( model_name='thumpednotification', name='thumped_target', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='thumped_up_target', to='contenttypes.ContentType'), ), ]
[ "root@ubuntu.ubuntu-domain" ]
root@ubuntu.ubuntu-domain
2c6f7329cf5f3fe94f8c1b248451d1d8a25c4bf2
5d8fbd0ae055a830be62de0191113f6e03f91046
/practice4v.py
9c6f45f76ba2a4b62ff72c2bb4abf339ca89b233
[]
no_license
harmansehmbi/Project4
ba892d921c6b1a9b595a0aa1781afcd79fee5269
baf7e75199d99b60431ba191fbb53fbcd25116cb
refs/heads/master
2020-06-01T16:02:57.311321
2019-06-08T04:01:07
2019-06-08T04:01:07
190,843,134
0
0
null
null
null
null
UTF-8
Python
false
false
261
py
dishes = {"dish1":100, "dish2":200, "dish3":300, "dish4":150} print() keys = list(dishes.keys()) values = list(dishes.values()) print(keys, type(keys)) print() print(values, type(values)) print() print(max(dishes.keys())) print() print(max(dishes.values()))
[ "51370954+harmansehmbi@users.noreply.github.com" ]
51370954+harmansehmbi@users.noreply.github.com
1e3e7d87108b4bf2008a6bcf63f8e833328da5e4
73b73f15adefd4c8d1fc2888406fc7f6b567c9f0
/blogapp/urls.py
2a66e3ab5b4a63a0add5b35819cd5fcf89b51d67
[]
no_license
codenotespy/www.codenotes.site_dj
ed4b736814b783b32d41ee1add70bda4eb9522dc
e1cd0dcb2e6fbdfec4b7ebdf7b19e2338a297e48
refs/heads/main
2023-06-09T22:51:46.291207
2021-06-29T03:56:14
2021-06-29T03:56:14
381,232,611
0
0
null
null
null
null
UTF-8
Python
false
false
1,505
py
from django.urls import path from . import views urlpatterns = [ path('', views.blog_menu, name='blog_menu'), path('contact', views.contact, name='contact'), path('upload_blog', views.upload_blog, name='upload_blog'), path('blog/<int:id>/', views.blog, name='blog'), path('blog_like/<int:id>/', views.blog_like, name='blog_like'), path('blog_up/<int:id>/', views.blog_up, name='blog_up'), path('blog_down/<int:id>/', views.blog_down, name='blog_down'), path('priorityform/<int:id>/', views.priorityform, name='priorityform'), path('delete_blog/<int:pk>/', views.delete_blog, name='delete_blog'), path('update_blog/<int:id>/', views.update_blog, name='update_blog'), path('update_blog_cover/<int:pk>/', views.update_blog_cover, name='update_blog_cover'), path('bio_update', views.bio_update, name='bio_update'), path('mybio', views.mybio, name='mybio'), path('tags/<slug:tag_slug>/', views.TagIndexBlog, name='posts_by_tag'), path('blogsforuser/<int:id>/', views.blogsforuser, name='blogsforuser'), path('bioforuser/<int:id>/', views.bioforuser, name='bioforuser'), path('about_update', views.about_update, name='about_update'), path('site_about', views.site_about, name='site_about'), path('authormenu', views.authormenu, name='authormenu'), ] from django.conf import settings from django.conf.urls.static import static if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
[ "aydinugur8@hotmail.com" ]
aydinugur8@hotmail.com
dbe56d846912e13b4c72c12ef311a8562813ec85
ab5cdf8f2de94c327e4679da84f941b1f3c04db4
/kubernetes/test/test_v1_glusterfs_volume_source.py
39a802f1d91d71050744ebdb7a46060e9740cc45
[ "Apache-2.0" ]
permissive
diannaowa/client-python
a4a92a125178db26004eaef5062f9b1b581b49a8
5e268fb0b6f21a535a14a7f968b84ed4486f6774
refs/heads/master
2020-12-02T22:06:03.687696
2017-06-30T21:42:50
2017-06-30T21:42:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
925
py
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.7.0 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys import unittest import kubernetes.client from kubernetes.client.rest import ApiException from kubernetes.client.models.v1_glusterfs_volume_source import V1GlusterfsVolumeSource class TestV1GlusterfsVolumeSource(unittest.TestCase): """ V1GlusterfsVolumeSource unit test stubs """ def setUp(self): pass def tearDown(self): pass def testV1GlusterfsVolumeSource(self): """ Test V1GlusterfsVolumeSource """ model = kubernetes.client.models.v1_glusterfs_volume_source.V1GlusterfsVolumeSource() if __name__ == '__main__': unittest.main()
[ "mehdy@google.com" ]
mehdy@google.com
c1895e6e58c9a7846f94b1a64c77145bf2a32ad3
3f69ffa4e42526c50100dc0f7e7ad88502a664e1
/pyforms_gui/controls/control_event_timeline/events/pointer.py
18b837dbd20aa023d08cb86c2a9135e181aa04f9
[]
no_license
UmSenhorQualquer/pyforms-gui
d09854839ff20d26703034e596658e28730362ec
a25bcfe3229e9eaab94fdd84dd749c5de071d836
refs/heads/v4
2022-05-05T11:20:38.432276
2021-06-03T16:13:59
2021-06-03T16:13:59
134,008,541
121
25
null
2022-03-24T16:23:47
2018-05-18T22:09:20
Python
UTF-8
Python
false
false
2,379
py
# !/usr/bin/python # -*- coding: utf-8 -*- from AnyQt.QtGui import QColor from AnyQt import QtCore class Pointer(object): def __init__(self, position, parent): """ :param position: :param parent: """ self._position = position self._parent = parent def draw(self, painter, showvalues=False, highlight=False): """ :param painter: :param showvalues: :return: """ if highlight: painter.setPen(QColor(0, 150, 150)) painter.setBrush(QColor(0, 150, 150)) else: painter.setPen(QColor(0, 255, 0)) painter.setBrush(QColor(0, 255, 0)) painter.drawLine( self.xposition, 8, self.xposition, self._parent.height()) painter.drawEllipse(QtCore.QPoint(self.xposition, 8), 5, 5) painter.drawText(self.xposition + 8, 8 + 4, str(self._position)) ########################################################################## #### HELPERS/FUNCTIONS ################################################### ########################################################################## def moveEvent(self): """ :return: """ pass def collide(self, x, y): """ :param x: :param y: :return: """ return self.begin <= x <= self.end and 0 <= y <= self._parent.TOPTRACK_HEIGHT def can_slide_begin(self, x, y): """ :param x: :param y: :return: """ return False def can_slide_end(self, x, y): """ :param x: :param y: :return: """ return False def move(self, x, y): """ :param x: :param y: :return: """ x = int(round(x / self._parent._scale)) if (self._position - x) >= 0 and (self._position - x) <= (self._parent.width() / self._parent._scale): self._position += x self.moveEvent() ########################################################################## #### PROPERTIES ########################################################## ########################################################################## @property def xposition(self): return self._parent.frame2x(self.position) @property def position(self): return self._position @position.setter def position(self, value): self._position = value self.moveEvent() @property def frame(self): return self._position @property def begin(self): return self._position * self._parent.scale - 5 @property def end(self): return self._position * self._parent.scale + 5
[ "ricardojvr@gmail.com" ]
ricardojvr@gmail.com
5c875bc14088390b5c80f58390c190466aa572b3
31b9c04fd1edc1401721e9010a171cdb0da8e77f
/mysite/main/migrations/0002_post_mainphoto.py
c2907525a31e84b2a70cdab6c5c5c4b1a5a153c0
[]
no_license
ChoiKangM/replyWithDjango
2b0685bf1f9934d0dcb48ac7525e8a6f41c46d2d
2bdafabddfaca48b1b5b91cb09a3b7404e4472e7
refs/heads/master
2023-08-08T03:32:46.305187
2019-05-14T21:08:39
2019-05-14T21:08:39
null
0
0
null
null
null
null
UTF-8
Python
false
false
394
py
# Generated by Django 2.1.8 on 2019-05-07 01:41 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0001_initial'), ] operations = [ migrations.AddField( model_name='post', name='mainphoto', field=models.ImageField(blank=True, null=True, upload_to=''), ), ]
[ "choikm3847@gmail.com" ]
choikm3847@gmail.com
f7ffd0f4812bee9b9bd47aa0f720b0e299eb38f3
14483184f0eabafab14f75a052a69e363f973f99
/101.symmetric-tree.py
80f9454d04af06824f3e4018d4db3b084a9ef349
[]
no_license
DizzyYunxuan/Leetcode_answers
d38679935214597bae973a1fef03334005802819
9605165b684bc5a1299a418bb274dc0d3be117a6
refs/heads/master
2021-06-19T15:01:34.991783
2021-03-31T12:10:52
2021-03-31T12:10:52
196,497,506
1
0
null
null
null
null
UTF-8
Python
false
false
903
py
# # @lc app=leetcode id=101 lang=python3 # # [101] Symmetric Tree # # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isSymmetric(self, root: TreeNode) -> bool: return self.isSameTree(root.left, root.right) if root else True def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: if not p and not q: return True if (not p or not q): return False elif p.val != q.val: return False left = self.isSameTree(p.left, q.right) right = self.isSameTree(p.right, q.left) return left and right ✔ Accepted ✔ 195/195 cases passed (44 ms) ✔ Your runtime beats 40.99 % of python3 submissions ✔ Your memory usage beats 5.17 % of python3 submissions (14 MB)
[ "516488199@qq.com" ]
516488199@qq.com
00f589526d0fa2d4c1641fdcd926f14682be16c1
24a9c8f2fac4e2b20f731387336ec4e22d5fd2c7
/司法题1/词云.py
d4b2be329075aba70d6f82c1eede21a6a482937d
[]
no_license
yunli45/pycharmProjectHome
94833822e3036bf2baf8700c4493132e63177d4c
9a382c060963eb801a3da07423e84a4132257b02
refs/heads/master
2020-05-23T23:35:20.476973
2019-05-16T09:45:58
2019-05-16T09:49:16
186,986,803
0
0
null
null
null
null
UTF-8
Python
false
false
1,770
py
# -*- coding: utf-8 -*- """ # code is far away from bugs with the god animal protecting     I love animals. They taste delicious.               ┏┓      ┏┓             ┏┛┻━━━┛┻┓             ┃      ☃      ┃             ┃  ┳┛  ┗┳  ┃             ┃      ┻      ┃             ┗━┓      ┏━┛                 ┃      ┗━━━┓                 ┃  神兽保佑    ┣┓                 ┃ 永无BUG!   ┏┛                 ┗┓┓┏━┳┓┏┛                   ┃┫┫  ┃┫┫                   ┗┻┛  ┗┻┛ """ """ Minimal Example =============== 使用默认参数生成方形的词云 """ from wordcloud import WordCloud from os import path d = path.dirname(__file__) # 读取整个文本 text = open(path.join(d, "Alice.txt")).read() # 生成词云图像 # wordcloud = WordCloud.generate(text) # matplotlib的方式展示生成的词云图像 import matplotlib.pyplot as plt # plt.imshow(wordcloud, interpolation="bilinear") # 展示 # plt.axis("off") #max_font_size设定生成词云中的文字最大大小 #width,height,margin可以设置图片属性 # generate 可以对全部文本进行自动分词,但是他对中文支持不好 wordcloud = WordCloud(max_font_size=66).generate(text) plt.figure() plt.imshow(wordcloud, interpolation="bilinear") plt.axis("off") plt.show() #保存到本地 wordcloud.to_file(path.join(d, "alice.png")) # pil方式展示生成的词云图像(如果你没有matplotlib) # image = wordcloud.to_image() # image.show()
[ "yunli_45@163.com" ]
yunli_45@163.com
4396e7581798f07422042200815e7f3b1af1ea69
b32300bf27d391fd9441cfbd9c86cd2943617e42
/py_osm_cluster/util/coords.py
8fedcd390dc44d775b94e294fe802641438b7c96
[]
no_license
jakubwida/py_osm_cluster_bachelors
71668552e5895ea7e0622d9fa54eb13ad264c31c
ea151268b184a38a6371c8df919fec7ef10cffaa
refs/heads/master
2021-01-25T07:49:09.313509
2017-07-04T09:40:24
2017-07-04T09:40:24
93,666,761
0
0
null
null
null
null
UTF-8
Python
false
false
2,144
py
class Coords: def __init__(self): self.labels = [] self.coords = [] self.c_number = 0 self.c_positions = [] def assimilate(self,other_coords): self.coords = self.coords+other_coords.coords self.c_number = self.c_number+other_coords.c_number self.c_positions = self.c_positions+other_coords.c_positions max_label = max(self.labels) self.labels = self.labels + [x+max_label for x in other_coords.labels] def write_file(self,filename): f = open(filename,'w') f.write(str(self)) """ f.write('coords\n') for element in self.coords: f.write(str(element[0])+' '+str(element[1])+'\n') f.write('labels\n') for element in self.labels: f.write(str(element)+'\n') f.write('c_number\n') f.write(str(self.c_number)+'\n') f.write('c_positions\n') for element in self.c_positions: f.write(str(element[0])+' '+str(element[1])+'\n') """ def read_file(self,filename): f = open(filename,'r') modes =["coords","labels","c_number","c_positions"] mode = None for line in f: line = line.strip("\n") #print(repr(line)) if line in modes: mode = line else: line = [float(x) for x in line.split(" ")] if mode == "coords": self.coords.append(line) elif mode == "c_positions": self.c_positions.append(line) elif mode == "c_number": self.c_number = int(line[0]) elif mode == "labels": self.labels.append(int(line[0])) def __str__(self): out ="" out = out + 'coords\n' for element in self.coords: out = out + str(element[0])+' '+str(element[1])+'\n' out = out + 'labels\n' for element in self.labels: out = out + str(element)+'\n' out = out + 'c_number\n' out = out + str(self.c_number)+'\n' out = out + 'c_positions\n' for element in self.c_positions: out = out + str(element[0])+' '+str(element[1])+'\n' return out """ returns a dictionary where keys = label values, values = lists of coords under these labels""" def clusters_into_lists_dict(self): out = {} for num,i in enumerate(self.coords): label = self.labels[num] if label in out: out[label].append(i) else: out[label] = [i] return out
[ "jakub.wida@outlook.com" ]
jakub.wida@outlook.com
cc0502e3cab1bd6a7d5f807163d274ebcf5b5a7d
a6e4a6f0a73d24a6ba957277899adbd9b84bd594
/sdk/python/pulumi_azure_native/storsimple/get_manager_extended_info.py
f1ef7dd5ffdca94ce009fca602b31b92407d3c83
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
MisinformedDNA/pulumi-azure-native
9cbd75306e9c8f92abc25be3f73c113cb93865e9
de974fd984f7e98649951dbe80b4fc0603d03356
refs/heads/master
2023-03-24T22:02:03.842935
2021-03-08T21:16:19
2021-03-08T21:16:19
null
0
0
null
null
null
null
UTF-8
Python
false
false
7,305
py
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from .. import _utilities, _tables __all__ = [ 'GetManagerExtendedInfoResult', 'AwaitableGetManagerExtendedInfoResult', 'get_manager_extended_info', ] @pulumi.output_type class GetManagerExtendedInfoResult: """ The extended info of the manager. """ def __init__(__self__, algorithm=None, encryption_key=None, encryption_key_thumbprint=None, etag=None, id=None, integrity_key=None, kind=None, name=None, portal_certificate_thumbprint=None, type=None, version=None): if algorithm and not isinstance(algorithm, str): raise TypeError("Expected argument 'algorithm' to be a str") pulumi.set(__self__, "algorithm", algorithm) if encryption_key and not isinstance(encryption_key, str): raise TypeError("Expected argument 'encryption_key' to be a str") pulumi.set(__self__, "encryption_key", encryption_key) if encryption_key_thumbprint and not isinstance(encryption_key_thumbprint, str): raise TypeError("Expected argument 'encryption_key_thumbprint' to be a str") pulumi.set(__self__, "encryption_key_thumbprint", encryption_key_thumbprint) if etag and not isinstance(etag, str): raise TypeError("Expected argument 'etag' to be a str") pulumi.set(__self__, "etag", etag) if id and not isinstance(id, str): raise TypeError("Expected argument 'id' to be a str") pulumi.set(__self__, "id", id) if integrity_key and not isinstance(integrity_key, str): raise TypeError("Expected argument 'integrity_key' to be a str") pulumi.set(__self__, "integrity_key", integrity_key) if kind and not isinstance(kind, str): raise TypeError("Expected argument 'kind' to be a str") pulumi.set(__self__, "kind", kind) if name and not isinstance(name, str): raise TypeError("Expected argument 'name' to be a str") pulumi.set(__self__, "name", name) if portal_certificate_thumbprint and not isinstance(portal_certificate_thumbprint, str): raise TypeError("Expected argument 'portal_certificate_thumbprint' to be a str") pulumi.set(__self__, "portal_certificate_thumbprint", portal_certificate_thumbprint) if type and not isinstance(type, str): raise TypeError("Expected argument 'type' to be a str") pulumi.set(__self__, "type", type) if version and not isinstance(version, str): raise TypeError("Expected argument 'version' to be a str") pulumi.set(__self__, "version", version) @property @pulumi.getter def algorithm(self) -> str: """ Represents the encryption algorithm used to encrypt the keys. None - if Key is saved in plain text format. Algorithm name - if key is encrypted """ return pulumi.get(self, "algorithm") @property @pulumi.getter(name="encryptionKey") def encryption_key(self) -> Optional[str]: """ Represents the CEK of the resource. """ return pulumi.get(self, "encryption_key") @property @pulumi.getter(name="encryptionKeyThumbprint") def encryption_key_thumbprint(self) -> Optional[str]: """ Represents the Cert thumbprint that was used to encrypt the CEK. """ return pulumi.get(self, "encryption_key_thumbprint") @property @pulumi.getter def etag(self) -> Optional[str]: """ The etag of the resource. """ return pulumi.get(self, "etag") @property @pulumi.getter def id(self) -> str: """ The path ID that uniquely identifies the object. """ return pulumi.get(self, "id") @property @pulumi.getter(name="integrityKey") def integrity_key(self) -> str: """ Represents the CIK of the resource. """ return pulumi.get(self, "integrity_key") @property @pulumi.getter def kind(self) -> Optional[str]: """ The Kind of the object. Currently only Series8000 is supported """ return pulumi.get(self, "kind") @property @pulumi.getter def name(self) -> str: """ The name of the object. """ return pulumi.get(self, "name") @property @pulumi.getter(name="portalCertificateThumbprint") def portal_certificate_thumbprint(self) -> Optional[str]: """ Represents the portal thumbprint which can be used optionally to encrypt the entire data before storing it. """ return pulumi.get(self, "portal_certificate_thumbprint") @property @pulumi.getter def type(self) -> str: """ The hierarchical type of the object. """ return pulumi.get(self, "type") @property @pulumi.getter def version(self) -> Optional[str]: """ The version of the extended info being persisted. """ return pulumi.get(self, "version") class AwaitableGetManagerExtendedInfoResult(GetManagerExtendedInfoResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return GetManagerExtendedInfoResult( algorithm=self.algorithm, encryption_key=self.encryption_key, encryption_key_thumbprint=self.encryption_key_thumbprint, etag=self.etag, id=self.id, integrity_key=self.integrity_key, kind=self.kind, name=self.name, portal_certificate_thumbprint=self.portal_certificate_thumbprint, type=self.type, version=self.version) def get_manager_extended_info(manager_name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetManagerExtendedInfoResult: """ The extended info of the manager. API Version: 2017-06-01. :param str manager_name: The manager name :param str resource_group_name: The resource group name """ __args__ = dict() __args__['managerName'] = manager_name __args__['resourceGroupName'] = resource_group_name if opts is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('azure-native:storsimple:getManagerExtendedInfo', __args__, opts=opts, typ=GetManagerExtendedInfoResult).value return AwaitableGetManagerExtendedInfoResult( algorithm=__ret__.algorithm, encryption_key=__ret__.encryption_key, encryption_key_thumbprint=__ret__.encryption_key_thumbprint, etag=__ret__.etag, id=__ret__.id, integrity_key=__ret__.integrity_key, kind=__ret__.kind, name=__ret__.name, portal_certificate_thumbprint=__ret__.portal_certificate_thumbprint, type=__ret__.type, version=__ret__.version)
[ "noreply@github.com" ]
MisinformedDNA.noreply@github.com
2429afb1390e940a0538dd6d4cebf7258e4c4ab6
f0181afd2eea9b086ce9487fb8d7fd949282140a
/perl/alignment/local_alignment.py
db92f56beb54b2cb64580db945895b78d465058e
[ "MIT" ]
permissive
linsalrob/EdwardsLab
4a571676859c8b7238e733a0d3ad98ceb2e83c63
3c466acc07f1a56b575860ad26c92f900b272a53
refs/heads/master
2023-08-20T17:13:35.466103
2023-08-17T09:17:36
2023-08-17T09:17:36
25,702,093
36
25
MIT
2020-09-23T12:44:44
2014-10-24T18:27:16
Python
UTF-8
Python
false
false
2,920
py
__author__ = 'redwards' import os from array import array from matrices import blosum62 def score(a, b): blosum = blosum62() if a in blosum and b in blosum[a]: return blosum[a][b] elif b in blosum and a in blosum[b]: return blosum[b][a] else: sys.stderr.write("Can not score amino acids " + a + " and " + b + "\n") return -8 def local_alignment(seq1, seq2, gap_open=11, gap_extn=1): """ Perform a ungapped local alignment. This approach uses 6 matrices. :param seq1: The first sequence :param seq2: The second sequence :param gap_open: The gap opening penalty (default = 11) :param gap_extn: The gap extention penalty (default = 1) :return: The score, and the two sequences with gaps in them """ ################################################ # Create Score Matrix and Helper Matrices ################################################ scorematrix = [array('i', [0 for x in xrange(0, len(seq1) + 1)]) for t in xrange(0, len(seq2) + 1)] maxhigheri = [array('i', [0 for x in xrange(0, len(seq1) + 1)]) for t in xrange(0, len(seq2) + 1)] maxhigherj = [array('i', [0 for x in xrange(0, len(seq1) + 1)]) for t in xrange(0, len(seq2) + 1)] helpermatrix = [array('i', [0 for x in xrange(0, len(seq1) + 1)]) for t in xrange(0, len(seq2) + 1)] endi = 0 endj = 0 bestscore = -1 for i in xrange(0, len(seq2)): for j in xrange(0, len(seq1)): match = scorematrix[i][j] + score(seq2[i],seq1[j]) maxhigheri[i+1][j+1] = max([maxhigheri[i+1][j] - gap_extn, scorematrix[i+1][j] - gap_open]) maxhigherj[i+1][j+1] = max([maxhigherj[i][j+1] - gap_extn, scorematrix[i][j+1] - gap_open]) maxv = max([match,maxhigheri[i+1][j+1],maxhigherj[i+1][j+1],0]) scorematrix[i+1][j+1] = maxv # how did we get here? if maxv <= 0: helpermatrix[i+1][j+1] = 4 elif maxv == match: helpermatrix[i+1][j+1] = 1 elif maxv == maxhigherj[i+1][j+1]: helpermatrix[i+1][j+1] = 2 elif maxv == maxhigheri[i+1][j+1]: helpermatrix[i+1][j+1] = 3 else: helpermatrix[i+1][j+1] = 4 newscore = scorematrix[i+1][j+1] if newscore > bestscore: bestscore = newscore endi = i+1 endj = j+1 i = endi j = endj hm = helpermatrix[i][j] while i * j != 0 and hm != 4: if hm == 1: i = i - 1 j = j - 1 elif hm == 2: i = i - 1 elif hm == 3: j = j - 1 hm = helpermatrix[i][j] print(bestscore) print(seq1[j:endj]) print(seq2[i:endi]) if __name__ == "__main__": s1 = 'ATGLVRRLGSFLVEDFSRYKLL' s2 = 'GLMRRSGSPLVESRYKLL' local_alignment(s1, s2)
[ "raedwards@gmail.com" ]
raedwards@gmail.com
9222dbde7d346213b91034145a348a5cff4cbbf6
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03161/s980102866.py
deba467f47fe65240ad40d992abb931cd5df9b26
[]
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
319
py
if __name__ == '__main__': n,k = map(int,input().split()) h = list(map(int,input().split())) #TLE pypy INF = 10**9 dp = [INF] * (n+1) dp[0] = 0 k = min(k,n) for i in range(1,n): for j in range(1,k+1): dp[i] = min(dp[i],dp[i-j]+abs(h[i]-h[i-j])) print(dp[n-1])
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
b0458242d96796db2944d822cfd3c245a1bd89f5
48616fb53c96dafed001ab264f819bad38769371
/pydesica/src/plot_hist_death.py
095c91df24e3a2541de58093361d3756ab945c71
[]
no_license
mdekauwe/SE_AUS_drought_risk_paper
1ee650ba9ef553dc062223c77277f66b5cb8721b
a908e82844ea5ecf927c1039dd0059a50027be9f
refs/heads/master
2020-09-17T08:57:07.200626
2020-06-01T23:51:35
2020-06-01T23:51:35
224,061,720
0
2
null
null
null
null
UTF-8
Python
false
false
5,100
py
#!/usr/bin/env python # coding: utf-8 """ Plot the pixel output That's all folks. """ __author__ = "Martin De Kauwe" __version__ = "1.0 (12.03.2018)" __email__ = "mdekauwe@gmail.com" import pandas as pd import sys import numpy as np import matplotlib.pyplot as plt import os import seaborn as sns rf = pd.read_csv("outputs/rf_trait_sensitivity_all.csv") wsf = pd.read_csv("outputs/wsf_trait_sensitivity_all.csv") dsf = pd.read_csv("outputs/dsf_trait_sensitivity_all.csv") grw = pd.read_csv("outputs/grw_trait_sensitivity_all.csv") saw = pd.read_csv("outputs/saw_trait_sensitivity_all.csv") #rf = pd.read_csv("outputs/rf_trait_sens_OAT.csv") #wsf = pd.read_csv("outputs/wsf_trait_sens_OAT.csv") #dsf = pd.read_csv("outputs/dsf_trait_sens_OAT.csv") #grw = pd.read_csv("outputs/grw_trait_sens_OAT.csv") #saw = pd.read_csv("outputs/saw_trait_sens_OAT.csv") rf = rf[rf.day_of_death > 0] wsf = wsf[wsf.day_of_death > 0] dsf = dsf[dsf.day_of_death > 0] grw = grw[grw.day_of_death > 0] saw = saw[saw.day_of_death > 0] width = 9 height = 6 fig = plt.figure(figsize=(width, height)) fig.subplots_adjust(hspace=0.13) fig.subplots_adjust(wspace=0.13) plt.rcParams['text.usetex'] = False plt.rcParams['font.family'] = "sans-serif" plt.rcParams['font.sans-serif'] = "Helvetica" plt.rcParams['axes.labelsize'] = 16 plt.rcParams['font.size'] = 16 plt.rcParams['legend.fontsize'] = 12 plt.rcParams['xtick.labelsize'] = 16 plt.rcParams['ytick.labelsize'] = 16 colours = sns.color_palette("Set2", 8) ax = fig.add_subplot(111) sns.distplot(rf.day_of_death, ax=ax, rug=False, norm_hist=True, kde_kws={"label": "RF"}, kde=True, color=colours[0]) sns.distplot(wsf.day_of_death, ax=ax, rug=False, norm_hist=True, kde_kws={"label": "WSF"}, kde=True, color=colours[1]) sns.distplot(dsf.day_of_death, ax=ax, rug=False, norm_hist=True, kde_kws={"label": "DSF"}, kde=True, color=colours[2]) ax.tick_params(direction='in', length=4) ax.set_xlabel("Day of death") ax.set_ylabel("Probability density") ax.legend(numpoints=1, ncol=1, loc="best", frameon=False) ofdir = "/Users/mdekauwe/Desktop" ofname = "day_of_death_RF_WSF_DSF.png" fig.savefig(os.path.join(ofdir, ofname), bbox_inches='tight', pad_inches=0.1, dpi=300) width = 9 height = 6 fig = plt.figure(figsize=(width, height)) fig.subplots_adjust(hspace=0.13) fig.subplots_adjust(wspace=0.13) plt.rcParams['text.usetex'] = False plt.rcParams['font.family'] = "sans-serif" plt.rcParams['font.sans-serif'] = "Helvetica" plt.rcParams['axes.labelsize'] = 16 plt.rcParams['font.size'] = 16 plt.rcParams['legend.fontsize'] = 12 plt.rcParams['xtick.labelsize'] = 16 plt.rcParams['ytick.labelsize'] = 16 colours = sns.color_palette("Set2", 8) ax = fig.add_subplot(111) sns.distplot(grw.day_of_death, ax=ax, rug=False, norm_hist=True, kde_kws={"label": "GRW"}, kde=True, color=colours[3]) sns.distplot(saw.day_of_death, ax=ax, rug=False, norm_hist=True, kde_kws={"label": "SAW"}, kde=True, color=colours[4]) ax.set_xlim(0, 600) ax.tick_params(direction='in', length=4) ax.set_xlabel("Day of death") ax.set_ylabel("Probability density") ax.legend(numpoints=1, ncol=1, loc="best", frameon=False) ofdir = "/Users/mdekauwe/Desktop" ofname = "day_of_death_GRW_SAW.png" fig.savefig(os.path.join(ofdir, ofname), bbox_inches='tight', pad_inches=0.1, dpi=300) width = 9 height = 6 fig = plt.figure(figsize=(width, height)) fig.subplots_adjust(hspace=0.13) fig.subplots_adjust(wspace=0.13) plt.rcParams['text.usetex'] = False plt.rcParams['font.family'] = "sans-serif" plt.rcParams['font.sans-serif'] = "Helvetica" plt.rcParams['axes.labelsize'] = 16 plt.rcParams['font.size'] = 16 plt.rcParams['legend.fontsize'] = 12 plt.rcParams['xtick.labelsize'] = 16 plt.rcParams['ytick.labelsize'] = 16 colours = sns.color_palette("Set2", 8) ax = fig.add_subplot(111) sns.distplot(rf.day_of_death, ax=ax, rug=False, norm_hist=True, kde_kws={"label": "RF"}, kde=True, color=colours[0]) sns.distplot(wsf.day_of_death, ax=ax, rug=False, norm_hist=True, kde_kws={"label": "WSF"}, kde=True, color=colours[1]) sns.distplot(dsf.day_of_death, ax=ax, rug=False, norm_hist=True, kde_kws={"label": "DSF"}, kde=True, color=colours[2]) sns.distplot(grw.day_of_death, ax=ax, rug=False, norm_hist=True, kde_kws={"label": "GRW"}, kde=True, color=colours[3]) sns.distplot(saw.day_of_death, ax=ax, rug=False, norm_hist=True, kde_kws={"label": "SAW"}, kde=True, color=colours[4]) #ax.set_xlim(100, 600) #ax.set_ylim(0.0, 0.005) #plt.xticks([], []) #splt.setp(ax.get_xticklabels(), visible=False) ax.tick_params(direction='in', length=4) ax.set_xlabel("Day of hydraulic failure ($\Psi$$_{\mathrm{crit}}$)", labelpad=10) ax.set_ylabel("Probability density") ax.legend(numpoints=1, ncol=1, loc="best", frameon=False) #ofdir = "/Users/mdekauwe/Desktop" ofdir = "/Users/mdekauwe/Dropbox/Drought_risk_paper/figures/figs" ofname = "day_of_death_all.pdf" fig.savefig(os.path.join(ofdir, ofname), bbox_inches='tight', pad_inches=0.1)
[ "mdekauwe@gmail.com" ]
mdekauwe@gmail.com
0ab75df4472e4622b1a049811be92712ca4fc93a
d3170930a453d7f4ab62c4637f21e8e1d74ac971
/axf/urls_order_apis.py
9833c9dbe2456599f9cc0cf30e0d0f25e7c0eb66
[]
no_license
whoareyou0401/1901axf_vue
97fd03439ef919024832348f61ea3c1f5cf2469c
4bb0fcf2000a624be294bbcfdbfc52895fedd36e
refs/heads/master
2020-05-29T19:45:36.536110
2019-05-31T02:47:41
2019-05-31T02:47:41
189,338,601
1
0
null
null
null
null
UTF-8
Python
false
false
187
py
from django.conf.urls import url from .order_apis import * urlpatterns = [ url(r"^order$", OrderAPI.as_view()), url(r"^confirm$", ConfirmOrder.as_view({"post":"confirm"})), ]
[ "1625211623@qq.com" ]
1625211623@qq.com
3fc13f2b5432026514c79268d90a33390a6b94bb
f949cf76d051abb911be3e3adbfe777aa6f9fc95
/code1/analysis/loadFactor_vs_collision_test_speed.py
2764cb51d46d32ff4500dd5c9ad782dc7db8ac44
[]
no_license
xeniaqian94/11711-Algorithm-for-NLP
ae8137849654ccdd77b2da059a955eeecc71e76f
f63743ecb937231835ea394a8ad64d876346f802
refs/heads/master
2021-01-23T23:12:21.073989
2017-11-12T21:31:17
2017-11-12T21:31:17
102,955,520
1
0
null
null
null
null
UTF-8
Python
false
false
2,259
py
import sys import re import matplotlib.pyplot as plt # python loadFactor_vs_collision_test_speed.py ../loadFactor_log ../plot/loadFactor_vs_collision_test_speed f=open(sys.argv[1],"r") loadFactor=[] testTime=[] ratio_bigram=[] ratio_trigram=[] prev_line="" for line in f.readlines(): if (re.match(r"^load factor ([\.0-9]+)",line)): loadFactor+=[float(re.match(r"^load factor ([\.0-9]+)",line).group(1))] if (re.match(r"^Decoding took ([\.0-9]+)s",line)): # Building took 160.537s testTime+=[float(re.match(r"^Decoding took ([\.0-9]+)s",line).group(1))] # class edu.berkeley.nlp.assignments.assign1.student.longIntOpenHashMapBigram num_collision 266264368 num_access 332076077 ratio 0.8018173739145925 if (re.match(r".*longIntOpenHashMapBigram .*ratio ([\.0-9]+)",line)): ratio_bigram+=[float(re.match(r".*longIntOpenHashMapBigram.*ratio ([\.0-9]+)",line).group(1))] if (re.match(r".*longIntOpenHashMap .*ratio ([\.0-9]+)",line)): ratio_trigram+=[float(re.match(r".*longIntOpenHashMap .*ratio ([\.0-9]+)",line).group(1))] print len(loadFactor),len(testTime),len(ratio_bigram),len(ratio_trigram) assert len(loadFactor)==len(testTime)==len(ratio_bigram)==len(ratio_trigram) testTime=[x for _,x in sorted(zip(loadFactor,testTime))] ratio_bigram=[x for _,x in sorted(zip(loadFactor,ratio_bigram))] ratio_trigram=[x for _,x in sorted(zip(loadFactor,ratio_trigram))] fig, ax1 = plt.subplots() ax1.plot(loadFactor, testTime, 'b.-') ax1.set_xlabel('Load Factor') # Make the y-axis label, ticks and tick labels match the line color. ax1.set_ylabel('LM Decode Time (s)',color='b') ax1.tick_params('y', colors='b') ax2 = ax1.twinx() ax2.plot(loadFactor,ratio_bigram, 'r^--',label="Bigram") ax2.plot(loadFactor,ratio_trigram,'m*-',label="Trigram") ax2.plot(loadFactor,loadFactor,"g-") ax2.set_ylabel('Ratio = # collision / # access',color='r') ax2.tick_params('y', colors='r') ax1.grid() ax2.grid() handles, labels = ax2.get_legend_handles_labels() ax2.legend(handles, labels) fig.tight_layout() plt.savefig(sys.argv[2]) plt.show() # fig=plt.figure() # ax=fig.add_subplot(111) # ax.set_xlabel("training size") # ax.set_ylabel("perplexity") # ax.grid() # ax.plot(training_size,perplexity,"b.-") # plt.savefig(sys.argv[2]) # plt.show()
[ "xeniaqian94@gmail.com" ]
xeniaqian94@gmail.com
aacab90637ea6957ea3d6e2c1ea9b511bf075c02
15f321878face2af9317363c5f6de1e5ddd9b749
/solutions_python/Problem_116/2510.py
337278eb13b6bb47614cb3a25617d675dc147176
[]
no_license
dr-dos-ok/Code_Jam_Webscraper
c06fd59870842664cd79c41eb460a09553e1c80a
26a35bf114a3aa30fc4c677ef069d95f41665cc0
refs/heads/master
2020-04-06T08:17:40.938460
2018-10-14T10:12:47
2018-10-14T10:12:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,910
py
class TicTac(): blen=range(4) def __init__(self,inBoardStr): self.board=[] for (crow,cline) in zip(self.blen,inBoardStr.split('\n')): cbline=[clet.upper() for (ccol,clet) in zip(self.blen,cline)] self.board+=[cbline] def checkwin(self): if self.checkvic('X'): return 'X won' if self.checkvic('O'): return 'O won' if self.notfinished(): return 'Game has not completed' else: return 'Draw' def notfinished(self): isEmpty=lambda x: x=='.' return any(map(lambda cline: any(map(isEmpty,cline)),self.board)) def checkvic(self,val): if any(map(lambda i: self.checkvicr(val,i),self.blen)): return True if any(map(lambda i: self.checkvicc(val,i),self.blen)): return True if any(self.checkvicd(val)): return True return False def checkvicr(self,val,i): isFull=lambda x: (x==val) | (x=='T') oVals=map(isFull,self.board[i]) print ('r',val,i,oVals) return all(oVals) def checkvicc(self,val,i): isFull=lambda x: (x==val) | (x=='T') oVals=map(lambda cline: isFull(cline[i]),self.board) print ('c',val,i,oVals) return all(oVals) def checkvicd(self,val): isFull=lambda x: (x==val) | (x=='T') diagA=zip(self.blen,self.blen) diagB=zip(self.blen[::-1],self.blen) checkVals=lambda diag: all(map(lambda cc: isFull(self.board[cc[0]][cc[1]]),diag)) oVals=map(checkVals,[diagA,diagB]) print (val,oVals) return oVals def __str__(self): return str(self.board) f=open('/mnt/sdcard/Download/A-large.in','r') bds=int(f.readline()) oList=[] for i in range(bds): cboard=map(lambda x: f.readline(),range(4)) f.readline() oList+=[TicTac(''.join(cboard))] f.close() winList=map(lambda x: x.checkwin(),oList) f=open('/mnt/sdcard/Download/tictacout5.txt','w') for (caseN,status) in enumerate(winList): f.write('Case #%i: %s\n' % (caseN+1,status)) f.close() #b=TicTac('..XO\nX.TX\n.O.T\nOXXO') #print b.checkwin()
[ "miliar1732@gmail.com" ]
miliar1732@gmail.com
35fa7fe8cb27b270e1efe832507fc58db96eee12
29dcd6c3475acde11bfc8dd7b6826ffddb40e1ab
/Week7Python/Week7/randomAverageSumMaxMin.py
8c0c8ac3b260f0158a0d860e0aaeec63863337ca
[]
no_license
quangdbui9999/CS-171
24ca7f7f27847c7b729d74b2c85abc0464cd8c1a
963b2e83e6939703ca2b7617941e5fc04d374570
refs/heads/master
2022-09-18T13:11:38.619101
2020-06-07T22:51:51
2020-06-07T22:51:51
270,453,427
0
0
null
null
null
null
UTF-8
Python
false
false
602
py
def main(): fileName = "randomNumber.txt" file = open(fileName, "r") getSum = 0 average = 0 maxNumber = -1 minNumber = 1000 for i in range(0, 1000): line = file.readline() number = int(line) getSum += number if(number < minNumber): minNumber = number if(number > maxNumber): maxNumber = number average = float(getSum / 1000) print("Average is: " + str(average)) print("Max number is : " + str(maxNumber)) print("Min number is : " + str(minNumber)) file.close() main()
[ "noreply@github.com" ]
quangdbui9999.noreply@github.com
dab23a2f681f7e8d2b14073564382513078fd1e1
4577d8169613b1620d70e3c2f50b6f36e6c46993
/students/1808084/homework01/program02.py
649e76a862e1916832e6b105fcdaf485735f8fd4
[]
no_license
Fondamenti18/fondamenti-di-programmazione
cbaf31810a17b5bd2afaa430c4bf85d05b597bf0
031ec9761acb1a425fcc4a18b07884b45154516b
refs/heads/master
2020-03-24T03:25:58.222060
2018-08-01T17:52:06
2018-08-01T17:52:06
142,419,241
0
0
null
null
null
null
UTF-8
Python
false
false
2,843
py
# -*- coding: utf-8 -*- """ Created on Thu Oct 19 17:55:21 2017 @author: Lorenzo """ ''' In determinate occasioni ci capita di dover scrivere i numeri in lettere, ad esempio quando dobbiamo compilare un assegno. Puo' capitare che alcuni numeri facciano sorgere in noi qualche dubbio. Le perplessita' nascono soprattutto nella scrittura dei numeri composti con 1 e 8. Tutti i numeri come venti, trenta, quaranta, cinquanta, ecc... elidono la vocale finale (la "i" per 20, la "a" per tutti gli altri) fondendola con la vocale iniziale del numero successivo; scriveremo quindi ventuno, ventotto, trentotto, cinquantuno ecc... Il numero cento, nella formazione dei numeri composti con uno e otto, non si comporta cosi'; il numero "cento" e tutte le centinaia (duecento, trecento, ecc...), infatti, non elidono la vocale finale. Dunque non scriveremo centuno, trecentotto ma centouno, trecentootto, ecc... I numeri composti dalle centinaia e dalla decina "ottanta" invece tornano ad elidere la vocale finale; scriveremo quindi centottanta, duecentottanta, ecc..., non centoottanta, duecentoottanta, ... Il numero "mille" non elide in nessun numero composto la vocale finale; scriveremo quindi milleuno, milleotto, milleottanta, ecc... Altri esempi sono elencati nel file grade02.txt Scrivere una funzione conv(n) che prende in input un intero n, con 0<n<1000000000000, e restituisce in output una stringa con il numero espresso in lettere ATTENZIONE: NON USATE LETTERE ACCENTATE. ATTENZIONE: Se il grader non termina entro 30 secondi il punteggio dell'esercizio e' zero. ''' def conv(j): if j==0: return '' elif j<=19: return ('uno', 'due', 'tre', 'quattro', 'cinque', 'sei', 'sette', 'otto', 'nove', 'dieci', 'undici', 'dodici', 'tredici', 'quattordici', 'quindici', 'sedici', 'diciassette', 'diciotto', 'diciannove')[j-1] elif j<=99: decine=('venti', 'trenta','quaranta','cinquanta','sessanta','settanta','ottanta','novanta') letter=decine[int(j/10)-2] z=j%10 if z==1 or z==8: letter=letter[:-1] return letter + conv(j%10) elif j<=199: return 'cento'+conv(j%100) elif j<=999: m=j%100 m=int(m/10) letter='cent' if m!=8: letter=letter+'o' return conv(int(j/100))+ letter+ conv(j%100) elif j<=1999: return 'mille'+conv(j%1000) elif j<=999999: return conv(int(j/1000))+'mila'+conv(j%1000) elif j<=1999999: return 'unmilione'+conv(int(j%1000000)) elif j<=999999999: return conv(int(j/1000000))+'milioni'+conv(j%1000000) elif j<=1999999999: return 'unmiliardo'+ conv(j%1000000000) else: return conv(int(j/1000000000))+'miliardi'+conv(j%1000000000)
[ "a.sterbini@gmail.com" ]
a.sterbini@gmail.com
67c4fcf63b42d176656a5364095de76ee9f01326
69bcc45028038351a7f891025df1f8e7d4b855f1
/pipeline/0x02-databases/33-schools_by_topic.py
17fb419f2a03fb8de363b332cb2bff9883340c20
[]
no_license
linkjavier/holbertonschool-machine_learning
6db799844821d450fed2a33a8819cb8df0fef911
c7b6ea4c37b7c5dc41e63cdb8142b3cdfb3e1d23
refs/heads/main
2023-08-17T21:00:24.182003
2021-09-09T05:47:06
2021-09-09T05:47:06
304,503,773
0
0
null
null
null
null
UTF-8
Python
false
false
254
py
#!/usr/bin/env python3 """ Where can I learn Python? """ def schools_by_topic(mongo_collection, topic): """ Function that returns the list of school having a specific topic """ return list(mongo_collection.find({"topics": {"$all": [topic]}}))
[ "linkjavier@hotmail.com" ]
linkjavier@hotmail.com
17c40c0786dd78ceab94a787c68a02c570d12f07
3d19e1a316de4d6d96471c64332fff7acfaf1308
/Users/E/elie222/fantasy_football_-_premierleaguecom_cleaner_versio.py
7f72eb5eacdfb0f99c528de816d9ca166b44d636
[]
no_license
BerilBBJ/scraperwiki-scraper-vault
4e98837ac3b1cc3a3edb01b8954ed00f341c8fcc
65ea6a943cc348a9caf3782b900b36446f7e137d
refs/heads/master
2021-12-02T23:55:58.481210
2013-09-30T17:02:59
2013-09-30T17:02:59
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,216
py
import scraperwiki import json from datetime import date for i in range(1,1000): try: jsonPage = scraperwiki.scrape('http://fantasy.premierleague.com/web/api/elements/%d/'%(i)) playerObj = json.loads(jsonPage) data = {} data["code"] = playerObj["code"] data["transfers_balance"] = playerObj["transfers_balance"] data["news_updated"] = playerObj["news_updated"] data["news_added"] = playerObj["news_added"] data["web_name"] = playerObj["web_name"] data["in_dreamteam"] = playerObj["in_dreamteam"] data["id"] = playerObj["id"] data["first_name"] = playerObj["first_name"] data["transfers_out_event"] = playerObj["transfers_out_event"] data["selected"] = playerObj["selected"] data["total_points"] = playerObj["total_points"] data["type_name"] = playerObj["type_name"] data["team_name"] = playerObj["team_name"] data["status"] = playerObj["status"] data["added"] = playerObj["added"] data["now_cost"] = playerObj["now_cost"] data["transfers_in"] = playerObj["transfers_in"] data["news"] = playerObj["news"] data["news_return"] = playerObj["news_return"] data["transfers_in_event"] = playerObj["transfers_in_event"] data["selected_by"] = playerObj["selected_by"] data["second_name"] = playerObj["second_name"] data["date_downloaded"] = date.today() scraperwiki.sqlite.save(unique_keys=["id", "date_downloaded"], data=data) except: print 'Stopped at %d'%(i) breakimport scraperwiki import json from datetime import date for i in range(1,1000): try: jsonPage = scraperwiki.scrape('http://fantasy.premierleague.com/web/api/elements/%d/'%(i)) playerObj = json.loads(jsonPage) data = {} data["code"] = playerObj["code"] data["transfers_balance"] = playerObj["transfers_balance"] data["news_updated"] = playerObj["news_updated"] data["news_added"] = playerObj["news_added"] data["web_name"] = playerObj["web_name"] data["in_dreamteam"] = playerObj["in_dreamteam"] data["id"] = playerObj["id"] data["first_name"] = playerObj["first_name"] data["transfers_out_event"] = playerObj["transfers_out_event"] data["selected"] = playerObj["selected"] data["total_points"] = playerObj["total_points"] data["type_name"] = playerObj["type_name"] data["team_name"] = playerObj["team_name"] data["status"] = playerObj["status"] data["added"] = playerObj["added"] data["now_cost"] = playerObj["now_cost"] data["transfers_in"] = playerObj["transfers_in"] data["news"] = playerObj["news"] data["news_return"] = playerObj["news_return"] data["transfers_in_event"] = playerObj["transfers_in_event"] data["selected_by"] = playerObj["selected_by"] data["second_name"] = playerObj["second_name"] data["date_downloaded"] = date.today() scraperwiki.sqlite.save(unique_keys=["id", "date_downloaded"], data=data) except: print 'Stopped at %d'%(i) break
[ "pallih@kaninka.net" ]
pallih@kaninka.net
a49f0908a19d55d7b3eee998f7ebec8be51c1ee0
37a92a9c4b03c9a8d485413ea0ca804c3860e4b2
/multi-label-cls/util.py
44259f234cdee61a0f420ee0d9681720d64aa6d2
[ "Apache-2.0" ]
permissive
JulianYu123456/icnn
0502950f281fdf6fdee3ed430bbbcf6250bc299c
0aaf4b5cd13d71d98b0d05f367e1f71657ea6eb8
refs/heads/master
2021-04-17T08:39:18.704713
2020-04-05T08:45:59
2020-04-05T08:45:59
249,430,014
0
0
Apache-2.0
2020-03-23T12:52:24
2020-03-23T12:52:24
null
UTF-8
Python
false
false
441
py
import numpy as np import sklearn from sklearn.metrics import f1_score def macroF1(trueY, predY): # trueY and predY should be (nExamples, nLabels) predY_bin = (predY >= 0.5).astype(np.int) trueY_bin = trueY.astype(np.int) # The transpose is here because sklearn's f1_score expects multi-label # data to be formatted as (nLabels, nExamples). return f1_score(trueY_bin.T, predY_bin.T, average='macro', pos_label=None)
[ "bamos@cs.cmu.edu" ]
bamos@cs.cmu.edu
53c0b78d84a3165bf0d2d3d584bc9787c6f5e5f8
ad4c2aa0398406ccb7e70562560e75fa283ffa1a
/inorder-successor-in-bst/inorder-successor-in-bst.py
c32fe6518bfadb60f56d65c472aab78b0a7dea4b
[ "Apache-2.0" ]
permissive
kmgowda/kmg-leetcode-python
427d58f1750735618dfd51936d33240df5ba9ace
4d32e110ac33563a8bde3fd3200d5804db354d95
refs/heads/main
2023-08-22T06:59:43.141131
2021-10-16T14:04:32
2021-10-16T14:04:32
417,841,590
0
1
null
null
null
null
UTF-8
Python
false
false
944
py
// https://leetcode.com/problems/inorder-successor-in-bst # 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 inorder_successor(self, root, p , found): node = None if root: found, node = self.inorder_successor(root.left, p, found) if node: return True, node if found: return True, root elif root == p: found = True found, node = self.inorder_successor(root.right, p, found) return found, node def inorderSuccessor(self, root, p): """ :type root: TreeNode :type p: TreeNode :rtype: TreeNode """ found, node = self.inorder_successor(root, p, False) return node
[ "keshava.gowda@gmail.com" ]
keshava.gowda@gmail.com
40b04c99c8cc4e9c2cac9d79520874d3404d15ea
9743d5fd24822f79c156ad112229e25adb9ed6f6
/xai/brain/wordbase/otherforms/_blarneying.py
d66e3c6b974c393c850ae6c85b2b91e1dacb8a8a
[ "MIT" ]
permissive
cash2one/xai
de7adad1758f50dd6786bf0111e71a903f039b64
e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6
refs/heads/master
2021-01-19T12:33:54.964379
2017-01-28T02:00:50
2017-01-28T02:00:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
230
py
#calss header class _BLARNEYING(): def __init__(self,): self.name = "BLARNEYING" self.definitions = blarney self.parents = [] self.childen = [] self.properties = [] self.jsondata = {} self.basic = ['blarney']
[ "xingwang1991@gmail.com" ]
xingwang1991@gmail.com
92578a4d2ea658a02029df6288200900ba1d402a
dacf092e82b5cc841554178e5117c38fd0b28827
/day6/session_6.1.py
dacdb0f52bdb94e716e19f74900a9dfb4b077b57
[]
no_license
RainMoun/python_programming_camp
f9bbee707e7468a7b5d6633c2364f5dd75abc8a4
f8e06cdd2e6174bd6986d1097cb580a6a3b7201f
refs/heads/master
2020-04-15T11:27:09.680587
2019-04-06T02:21:14
2019-04-06T02:21:14
164,630,838
4
1
null
null
null
null
UTF-8
Python
false
false
2,151
py
menu_university = { '浙江': { '杭州': { '下沙区': { '杭州电子科技大学': {}, '浙江工商大学': {}, '浙江理工大学': {} }, '西湖区': { '浙江大学': {}, }, }, '宁波': { '江北区': { '宁波大学': {} }, '鄞州区': { "宁波诺丁汉大学": {} } } } } sign_exit = False while not sign_exit: menu = menu_university for key in menu.keys(): print(key) choose_first = input("第一层:").strip() if choose_first == 'b': break elif choose_first == 'exit': sign_exit = True break elif choose_first in menu: pass else: continue while not sign_exit: menu_2 = menu[choose_first] for key in menu_2.keys(): print(key) choose_second = input("第二层:").strip() if choose_second == 'b': break elif choose_second == 'exit': sign_exit = True break elif choose_second in menu_2: pass else: continue while not sign_exit: menu_3 = menu_2[choose_second] for key in menu_3.keys(): print(key) choose_third = input("第三层:").strip() if choose_third == 'b': break elif choose_third == 'exit': sign_exit = True break elif choose_third in menu_3: pass else: continue while not sign_exit: menu_4 = menu_3[choose_third] for key in menu_4.keys(): print(key) choose_forth = input("第四层:").strip() if choose_forth == 'b': break elif choose_forth == 'exit': sign_exit = True break else: pass
[ "775653143@qq.com" ]
775653143@qq.com
479041b670289ff52f5224e1e10b9ca4dbdbae7f
c22a4957e6874b23f771d8174794ee4e31c5c792
/2_Tuples_and_sets/11. Longest Intersection.py
9f484292a01107c26761fd1b903ef54d82b3896a
[]
no_license
GalyaBorislavova/SoftUni_Python_Advanced_May_2021
d57ff7f6480c9011190bb52880bb1fe48298fcdb
67ad5acd43acc90042b3ac0fd5a8f4fe81bc0f53
refs/heads/main
2023-06-14T22:00:21.904387
2021-07-07T06:15:08
2021-07-07T06:15:08
381,794,137
0
0
null
null
null
null
UTF-8
Python
false
false
1,098
py
def input_to_list(count): lines = [] for _ in range(count): line = input() if " " in line: data = line.split() for el in data: lines.append(el) else: lines.append(line) return lines n = int(input()) input_sequences = input_to_list(n) longest_intersection = set() max_len_intersection = 0 for i in input_sequences: range_first_set, range_second_set = i.split("-") start_first_set, end_first_set = range_first_set.split(",") start_second_set, end_second_set = range_second_set.split(",") current_first_set = set(num for num in range(int(start_first_set), int(end_first_set) + 1)) current_second_set = set(num for num in range(int(start_second_set), int(end_second_set) + 1)) intersection = current_first_set.intersection(current_second_set) if len(intersection) > max_len_intersection: longest_intersection = intersection max_len_intersection = len(intersection) print(f"Longest intersection is {[*longest_intersection]} with length {max_len_intersection}")
[ "galyaborislavova888@gmail.com" ]
galyaborislavova888@gmail.com
54ab222cfbc270bfb8f73f764064bcca188236eb
1f6cdaead83b425ba2fda2b8b4f9eb1d03d97426
/app/models/skill.py
12d070e18395fda9465c6eb7791077266148341f
[]
no_license
simpuid/cvbuilder
3291f18a52bc5cdceb81d000e418c8c74ba3680d
c27cb0cfec0b8fc19245deb957b577a1e789db64
refs/heads/master
2023-01-01T08:13:55.755812
2020-10-30T21:55:37
2020-10-30T21:55:37
306,163,829
0
2
null
2020-10-28T18:20:31
2020-10-21T22:36:52
Python
UTF-8
Python
false
false
1,109
py
from db import execute, fetch class Skill: def __init__(self, uid: int, skill_list: list): self.id = uid self.skill_list = skill_list def update(self, index, skill_name): if skill_name != self.skill_list[index]: self.delete(index) self.add(skill_name) def delete(self, index): execute('DELETE FROM skill_table WHERE student_id = %s AND skill_name = %s', (self.id, self.skill_list[index])) def add(self, skill_name): execute("""INSERT INTO skill_table VALUES (%s, %s) ON DUPLICATE KEY UPDATE student_id = VALUES(student_id), skill_name = VALUES(skill_name)""", (self.id, skill_name)) @staticmethod def load(uid: int): execute('SELECT * FROM skill_table WHERE student_id = %s', (uid,)) data = fetch() if len(data) == 0: return Skill(uid, []) skill_list = [entry['skill_name'] for entry in data] return Skill(uid, skill_list)
[ "prathameshkatkar11@gmail.com" ]
prathameshkatkar11@gmail.com
655329fb24105ab3d49e79b703e9372d94130f5d
73a5eca1ddee1d74a3c2be9ca4e5e67ebe3d16f7
/src/util/main.py
268fafaef1f85aa7a5b43a86fbd49cf82644a789
[ "MIT" ]
permissive
ychnlgy/Chebyshev-Lagrange
34346692a2925cde620377e8fbcb8d588623fac7
74292e72b83f992d6c42a2f2db04dfdce5a52aea
refs/heads/master
2020-05-23T06:20:10.831035
2020-02-12T16:31:38
2020-02-12T16:31:38
186,661,893
2
1
null
null
null
null
UTF-8
Python
false
false
391
py
MAIN = "__main__" def main(name=None): def main_wrapper(prog): if name == MAIN: import sys args = dict([d.split("=") for d in sys.argv[1:]]) prog(**args) return prog if callable(name): prog = name name = MAIN return main_wrapper(prog) else: return main_wrapper
[ "ychnlgy@gmail.com" ]
ychnlgy@gmail.com
fbd858342f10655883bdb5247be8b585be37030b
9405aa570ede31a9b11ce07c0da69a2c73ab0570
/aliyun-python-sdk-emr/aliyunsdkemr/request/v20160408/GetAuditLogsRequest.py
6103a63b5d1ff06daa042f0bb7494e9c42ca2bce
[ "Apache-2.0" ]
permissive
liumihust/aliyun-openapi-python-sdk
7fa3f5b7ea5177a9dbffc99e73cf9f00e640b72b
c7b5dd4befae4b9c59181654289f9272531207ef
refs/heads/master
2020-09-25T12:10:14.245354
2019-12-04T14:43:27
2019-12-04T14:43:27
226,002,339
1
0
NOASSERTION
2019-12-05T02:50:35
2019-12-05T02:50:34
null
UTF-8
Python
false
false
2,948
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 aliyunsdkcore.request import RpcRequest from aliyunsdkemr.endpoint import endpoint_data class GetAuditLogsRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Emr', '2016-04-08', 'GetAuditLogs','emr') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_ResourceOwnerId(self): return self.get_query_params().get('ResourceOwnerId') def set_ResourceOwnerId(self,ResourceOwnerId): self.add_query_param('ResourceOwnerId',ResourceOwnerId) def get_PageCount(self): return self.get_query_params().get('PageCount') def set_PageCount(self,PageCount): self.add_query_param('PageCount',PageCount) def get_OrderMode(self): return self.get_query_params().get('OrderMode') def set_OrderMode(self,OrderMode): self.add_query_param('OrderMode',OrderMode) def get_EntityId(self): return self.get_query_params().get('EntityId') def set_EntityId(self,EntityId): self.add_query_param('EntityId',EntityId) def get_PageNumber(self): return self.get_query_params().get('PageNumber') def set_PageNumber(self,PageNumber): self.add_query_param('PageNumber',PageNumber) def get_Limit(self): return self.get_query_params().get('Limit') def set_Limit(self,Limit): self.add_query_param('Limit',Limit) def get_PageSize(self): return self.get_query_params().get('PageSize') def set_PageSize(self,PageSize): self.add_query_param('PageSize',PageSize) def get_CurrentSize(self): return self.get_query_params().get('CurrentSize') def set_CurrentSize(self,CurrentSize): self.add_query_param('CurrentSize',CurrentSize) def get_OrderField(self): return self.get_query_params().get('OrderField') def set_OrderField(self,OrderField): self.add_query_param('OrderField',OrderField) def get_Operation(self): return self.get_query_params().get('Operation') def set_Operation(self,Operation): self.add_query_param('Operation',Operation)
[ "sdk-team@alibabacloud.com" ]
sdk-team@alibabacloud.com
212d8d6048601c474ec7d30cb6db83bb7e054684
c6a4069e265325e836e4ee79fae0f5490f1a1c47
/tests/test_fight.py
e8c2d1ee8f3ae4f2bede2c65675418e6c0ac5f38
[]
no_license
astoeff/clean-code-course-project
b2ca1d10b226ea95b602d2535810c9af5aadb244
2b64956ea1b33cba405ccd500bf1a5472a65e9c4
refs/heads/master
2022-11-19T05:04:20.992189
2020-07-17T17:12:59
2020-07-17T17:12:59
274,676,681
0
0
null
2020-07-17T17:13:00
2020-06-24T13:32:49
Python
UTF-8
Python
false
false
6,529
py
import unittest from main.models.hero import Hero from main.models.enemy import Enemy from main.fight import Fight from main.treasures.weapon import Weapon from main.constants import (FIGHT_INITIAL_INFORMATION_PART, FIGHT_HERO_CANNOT_ATTACK_INFORMATION_PART, FIGHT_HERO_ATTACK_INFORMATION_PART, DEFAULT_WEAPON_NAME, DEFAULT_WEAPON_DAMAGE, FIGHT_ENEMY_CANNOT_ATTACK_INFORMATION_PART, FIGHT_ENEMY_ATTACK_INFORMATION_PART) class TestFight(unittest.TestCase): #__init__() def test_with_given_correct_arguments_should_initialise_correctly(self): hero = Hero('hero', 'bravest', 100, 100, 2) enemy = Enemy() fight = Fight(hero, enemy) expected_hero = hero expected_enemy = enemy expected_distance = 0 expected_direction = 0 expected_information_parts = [FIGHT_INITIAL_INFORMATION_PART + str(enemy)] self.assertEqual(expected_hero, fight.hero) self.assertEqual(expected_enemy, fight.enemy) self.assertEqual(expected_distance, fight.distance) self.assertEqual(expected_direction, fight.direction) self.assertEqual(expected_information_parts, fight.information_parts) #hero_attack() def test_when_hero_can_not_attack_should_set_correct_information_part_and_enemy_takes_zero_damage(self): hero = Hero('hero', 'bravest', 100, 100, 2) enemy = Enemy() enemy_health_before_attack = enemy.health fight = Fight(hero, enemy) fight.hero_attack() result_information_parts = fight.information_parts expected_information_parts = [FIGHT_INITIAL_INFORMATION_PART + str(enemy), FIGHT_HERO_CANNOT_ATTACK_INFORMATION_PART] self.assertEqual(enemy_health_before_attack, enemy.health) self.assertEqual(expected_information_parts, result_information_parts) def test_when_hero_can_attack_should_set_correct_information_part_and_enemy_takes_damage_from_attack(self): hero = Hero('hero', 'bravest', 100, 100, 2) default_weapon = Weapon(name=DEFAULT_WEAPON_NAME, damage=DEFAULT_WEAPON_DAMAGE) hero.equip(default_weapon) enemy = Enemy() initial_enemy_as_string = str(enemy) enemy_health_before_attack = enemy.health fight = Fight(hero, enemy) fight.hero_attack() result_enemy_health = fight.enemy.health expected_enemy_health = enemy_health_before_attack - default_weapon.damage result_information_parts = fight.information_parts expected_information_parts = [FIGHT_INITIAL_INFORMATION_PART + initial_enemy_as_string, FIGHT_HERO_ATTACK_INFORMATION_PART + str(default_weapon.damage)] self.assertEqual(expected_enemy_health, result_enemy_health) self.assertEqual(expected_information_parts, result_information_parts) #enemy_attack() def test_when_enemy_can_not_attack_should_set_correct_information_part_and_hero_takes_zero_damage(self): hero = Hero('hero', 'bravest', 100, 100, 2) enemy = Enemy() enemy.damage = 0 fight = Fight(hero, enemy) hero_health_before_attack = hero.health fight.enemy_attack() result_information_parts = fight.information_parts expected_information_parts = [FIGHT_INITIAL_INFORMATION_PART + str(enemy), FIGHT_ENEMY_CANNOT_ATTACK_INFORMATION_PART] self.assertEqual(hero_health_before_attack, hero.health) self.assertEqual(expected_information_parts, result_information_parts) def test_when_enemy_can_attack_should_set_correct_information_part_and_hero_takes_damage_from_attack(self): hero = Hero('hero', 'bravest', 100, 100, 2) enemy = Enemy() fight = Fight(hero, enemy) hero_health_before_attack = hero.health fight.enemy_attack() result_hero_health = fight.hero.health expected_hero_health = hero_health_before_attack - enemy.damage result_information_parts = fight.information_parts expected_information_parts = [FIGHT_INITIAL_INFORMATION_PART + str(enemy), FIGHT_ENEMY_ATTACK_INFORMATION_PART + str(enemy.damage)] self.assertEqual(expected_hero_health, result_hero_health) self.assertEqual(expected_information_parts, result_information_parts) #execute() def test_with_hero_that_can_not_attack_should_stop_when_hero_is_dead(self): hero = Hero('hero', 'bravest', 100, 100, 2) enemy = Enemy() enemy.damage = hero.health fight = Fight(hero, enemy) fight.execute() result_hero_alive_status = hero.is_alive() expected_hero_alive_status = False result_enemy_alive_status = enemy.is_alive() expected_enemy_alive_status = True result_information_parts = fight.information_parts expected_information_parts = [FIGHT_INITIAL_INFORMATION_PART + str(enemy), FIGHT_HERO_CANNOT_ATTACK_INFORMATION_PART, FIGHT_ENEMY_ATTACK_INFORMATION_PART + str(enemy.damage)] self.assertEqual(expected_hero_alive_status, result_hero_alive_status) self.assertEqual(expected_enemy_alive_status, result_enemy_alive_status) self.assertEqual(expected_information_parts, result_information_parts) def test_with_hero_that_can_attack_and_enemy_that_can_not_should_stop_when_enemy_is_dead(self): hero = Hero('hero', 'bravest', 100, 100, 2) enemy = Enemy() weapon = Weapon(name=DEFAULT_WEAPON_NAME, damage=enemy.health) hero.equip(weapon) fight = Fight(hero, enemy) initial_enemy_as_string = str(enemy) fight.execute() result_hero_alive_status = hero.is_alive() expected_hero_alive_status = True result_enemy_alive_status = enemy.is_alive() expected_enemy_alive_status = False result_information_parts = fight.information_parts expected_information_parts = [FIGHT_INITIAL_INFORMATION_PART + initial_enemy_as_string, FIGHT_HERO_ATTACK_INFORMATION_PART + str(weapon.damage)] self.assertEqual(expected_hero_alive_status, result_hero_alive_status) self.assertEqual(expected_enemy_alive_status, result_enemy_alive_status) self.assertEqual(expected_information_parts, result_information_parts)
[ "antoni.1998@abv.bg" ]
antoni.1998@abv.bg
bec6065716cd4195abdc899d00334578c3a51678
c81ea73e93df307d35191ab184a85d6c67c57112
/dockers/mvcnn2/Model.py
33a386975482c00e07a61ec744468d7c35b5098f
[]
no_license
BlenderCN-Org/diplomka
8d0503fc5902dfede8317aed84f5a17f691f687f
575fe3f2436b9c511496c1dc019d9cc3423ba5f0
refs/heads/master
2020-05-22T15:42:00.143738
2019-05-07T07:37:46
2019-05-07T07:37:46
null
0
0
null
null
null
null
UTF-8
Python
false
false
561
py
import torch import torch.nn as nn import os import glob class Model(nn.Module): def __init__(self, name): super(Model, self).__init__() self.name = name def save(self, file): torch.save(self.state_dict(), file) def save_results(self, path, data): raise NotImplementedError("Model subclass must implement this method.") def load(self, file): if not os.path.exists(file): raise IOError("File {} does not exist!".format(file)) self.load_state_dict(torch.load(file))
[ "miroslavkrabec@seznam.cz" ]
miroslavkrabec@seznam.cz
d0c3a1f5eb693cf578a1067dd019d36cfe2056e1
b7b243902150a1aa5b774523ac01d7016de13477
/cyc/math/628.py
aff725b4b44ac4e418c1fa95533e1c5c2ce2506c
[]
no_license
Veraph/LeetCode_Practice
7e97a93464911a1f33b3133043d96c88cd54016a
eafadd711f6ec1b60d78442280f1c44b6296209d
refs/heads/master
2023-03-23T11:49:19.046474
2021-03-18T02:22:50
2021-03-18T02:22:50
273,317,388
0
0
null
null
null
null
UTF-8
Python
false
false
451
py
# 628.py -- Maximum Product of Three Numbers ''' Given an integer array, find three numbers whose product is maximum and output the maximum product. ''' def maximumProduct(nums): ''' read the description carefully. be careful about the negative nums. ''' nums.sort(reverse=True) # two situations, find the bigger one ans1 = nums[0] * nums[1] * nums[2] ans2 = nums[0] * nums[-1] * nums[-2] return max(ans1, ans2)
[ "jmw3531@live.com" ]
jmw3531@live.com
e63722dcf8d043c89d4fba02b0bbade77d3104dd
b6f377fce8b8d63bd00b5c10485439ddba7f0717
/server/__init__.py
de758ecbe3217f05fdf7f2e0f9d10f567b7f74a0
[ "MIT" ]
permissive
HackCameroon/Coronalert
9635d041e92f59fccaaac1e71f01c0f9cf347c2e
df7d66bec147ea1f47105102582bc25469e4bee2
refs/heads/master
2022-04-12T08:52:30.442765
2020-04-08T19:21:54
2020-04-08T19:21:54
262,270,364
1
0
MIT
2020-05-08T08:37:15
2020-05-08T08:37:14
null
UTF-8
Python
false
false
2,879
py
from flask import Flask, render_template # from flask_jwt_extended import JWTManager from flask_sqlalchemy import SQLAlchemy from twilio.rest import Client from flask_migrate import Migrate import os STATIC_FOLDER = "../client/build/static" TEMPLATE_FOLDER = "../client/build" CONFIG_FILE = "./config.py" CONFIG_EXAMPLE = "server/config.example" def load_from_env(app, *args): for a in args: app.config[a] = os.environ[a] def load_models(): """ Load all database models and create tables """ from server.models import User # noqa from server.models import Location # noqa db.create_all() def load_blueprints(): """ Load all blueprints for app """ from server.user.views import user_bp from server.location.views import location_bp from server.datapull.views import datapull_bp from server.sms.views import sms_bp app.register_blueprint(user_bp, url_prefix="/api/user") app.register_blueprint(location_bp, url_prefix="/api/location") app.register_blueprint(datapull_bp, url_prefix="/api/datapull") app.register_blueprint(sms_bp, url_prefix="/api/sms") def setup_default_routes(): """ Set up default routes for app """ @app.errorhandler(404) def default(error): return render_template("index.html") def setup_debug(): """ Set up debug settings """ from flask_cors import CORS app.config["JWT_COOKIE_CSRF_PROTECT"] = False CORS(app, origins=[app.config["FRONTEND_URL"]], supports_credentials=True) def setup_jwt(): """ Set up JWT for app """ app.config["JWT_TOKEN_LOCATION"] = ["cookies"] app.config["JWT_REFRESH_COOKIE_PATH"] = "/api/auth/token/refresh" def create_app(): """ Creates flask app, setting up database and blueprints """ global app global db global jwt global twilio_client global migrate # Set up and configure app app = Flask(__name__, static_folder=STATIC_FOLDER, template_folder=TEMPLATE_FOLDER) try: app.config.from_pyfile(CONFIG_FILE) print("Loading secret configs from file") except FileNotFoundError as e: env_vars = [line.split("=")[0] for line in open(CONFIG_EXAMPLE, "r")] load_from_env(app, *env_vars) print("Loading secret configs from env") if app.config["DEBUG"]: setup_debug() # Set up database db = SQLAlchemy(app) load_models() # Set up Flask Migrations migrate = Migrate(app, db) # Set up Twilio twilio_client = Client(app.config["TWILIO_SID"], app.config["TWILIO_AUTH_TOKEN"]) # Setup routes and bps setup_default_routes() load_blueprints() # Set up JWT for app # setup_jwt() # jwt = JWTManager(app) return app """ TODO: - Self-reporting feature for sms - Domain name - Manifest stuff """
[ "justinyu1618@gmail.com" ]
justinyu1618@gmail.com
48b71cb3fb8bc7bb76a91b40b2ce5b27e47ffabb
bc441bb06b8948288f110af63feda4e798f30225
/cmdb_extend_sdk/api/instance/get_instances_pb2.pyi
171bdfbd8163b6e22ba892a60c71cc8a169b7012
[ "Apache-2.0" ]
permissive
easyopsapis/easyops-api-python
23204f8846a332c30f5f3ff627bf220940137b6b
adf6e3bad33fa6266b5fa0a449dd4ac42f8447d0
refs/heads/master
2020-06-26T23:38:27.308803
2020-06-16T07:25:41
2020-06-16T07:25:41
199,773,131
5
0
null
null
null
null
UTF-8
Python
false
false
5,195
pyi
# @generated by generate_proto_mypy_stubs.py. Do not edit! import sys from google.protobuf.descriptor import ( Descriptor as google___protobuf___descriptor___Descriptor, ) from google.protobuf.internal.containers import ( RepeatedCompositeFieldContainer as google___protobuf___internal___containers___RepeatedCompositeFieldContainer, ) from google.protobuf.message import ( Message as google___protobuf___message___Message, ) from google.protobuf.struct_pb2 import ( Struct as google___protobuf___struct_pb2___Struct, ) from typing import ( Iterable as typing___Iterable, Optional as typing___Optional, Text as typing___Text, Union as typing___Union, ) from typing_extensions import ( Literal as typing_extensions___Literal, ) builtin___bool = bool builtin___bytes = bytes builtin___float = float builtin___int = int if sys.version_info < (3,): builtin___buffer = buffer builtin___unicode = unicode class GetInstancesRequest(google___protobuf___message___Message): DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... objectId = ... # type: typing___Text instanceIds = ... # type: typing___Text page = ... # type: builtin___int pageSize = ... # type: builtin___int @property def query(self) -> google___protobuf___struct_pb2___Struct: ... def __init__(self, *, objectId : typing___Optional[typing___Text] = None, instanceIds : typing___Optional[typing___Text] = None, page : typing___Optional[builtin___int] = None, pageSize : typing___Optional[builtin___int] = None, query : typing___Optional[google___protobuf___struct_pb2___Struct] = None, ) -> None: ... if sys.version_info >= (3,): @classmethod def FromString(cls, s: builtin___bytes) -> GetInstancesRequest: ... else: @classmethod def FromString(cls, s: typing___Union[builtin___bytes, builtin___buffer, builtin___unicode]) -> GetInstancesRequest: ... def MergeFrom(self, other_msg: google___protobuf___message___Message) -> None: ... def CopyFrom(self, other_msg: google___protobuf___message___Message) -> None: ... def HasField(self, field_name: typing_extensions___Literal[u"query",b"query"]) -> builtin___bool: ... def ClearField(self, field_name: typing_extensions___Literal[u"instanceIds",b"instanceIds",u"objectId",b"objectId",u"page",b"page",u"pageSize",b"pageSize",u"query",b"query"]) -> None: ... class GetInstancesResponse(google___protobuf___message___Message): DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... page = ... # type: builtin___int pageSize = ... # type: builtin___int total = ... # type: builtin___int @property def list(self) -> google___protobuf___internal___containers___RepeatedCompositeFieldContainer[google___protobuf___struct_pb2___Struct]: ... def __init__(self, *, page : typing___Optional[builtin___int] = None, pageSize : typing___Optional[builtin___int] = None, total : typing___Optional[builtin___int] = None, list : typing___Optional[typing___Iterable[google___protobuf___struct_pb2___Struct]] = None, ) -> None: ... if sys.version_info >= (3,): @classmethod def FromString(cls, s: builtin___bytes) -> GetInstancesResponse: ... else: @classmethod def FromString(cls, s: typing___Union[builtin___bytes, builtin___buffer, builtin___unicode]) -> GetInstancesResponse: ... def MergeFrom(self, other_msg: google___protobuf___message___Message) -> None: ... def CopyFrom(self, other_msg: google___protobuf___message___Message) -> None: ... def ClearField(self, field_name: typing_extensions___Literal[u"list",b"list",u"page",b"page",u"pageSize",b"pageSize",u"total",b"total"]) -> None: ... class GetInstancesResponseWrapper(google___protobuf___message___Message): DESCRIPTOR: google___protobuf___descriptor___Descriptor = ... code = ... # type: builtin___int codeExplain = ... # type: typing___Text error = ... # type: typing___Text @property def data(self) -> GetInstancesResponse: ... def __init__(self, *, code : typing___Optional[builtin___int] = None, codeExplain : typing___Optional[typing___Text] = None, error : typing___Optional[typing___Text] = None, data : typing___Optional[GetInstancesResponse] = None, ) -> None: ... if sys.version_info >= (3,): @classmethod def FromString(cls, s: builtin___bytes) -> GetInstancesResponseWrapper: ... else: @classmethod def FromString(cls, s: typing___Union[builtin___bytes, builtin___buffer, builtin___unicode]) -> GetInstancesResponseWrapper: ... def MergeFrom(self, other_msg: google___protobuf___message___Message) -> None: ... def CopyFrom(self, other_msg: google___protobuf___message___Message) -> None: ... def HasField(self, field_name: typing_extensions___Literal[u"data",b"data"]) -> builtin___bool: ... def ClearField(self, field_name: typing_extensions___Literal[u"code",b"code",u"codeExplain",b"codeExplain",u"data",b"data",u"error",b"error"]) -> None: ...
[ "service@easyops.cn" ]
service@easyops.cn
bb7bb7ba73a4dbedb7c358b976265b17ddd63cf5
249ae31366937f62e048f0fb858028432a2ec769
/apple-and-orange.py
8840c4437d9f1690530d6de43c8ebc2fb7893f58
[]
no_license
Mayurg6832/HackerRank-Problem-solving
198dccade1c79a5573362f8d656d447910ff1053
c8f2719f2728ed227e4f6ffea00163ddd8e17163
refs/heads/master
2022-10-12T22:36:29.500145
2020-06-10T09:18:49
2020-06-10T09:18:49
244,108,966
0
0
null
null
null
null
UTF-8
Python
false
false
401
py
s,t=map(int,input().split()) a,b=map(int,input().split()) m,n=map(int,input().split()) apple=list(map(int,input().split())) orange=list(map(int,input().split())) countA=0 countO=0 for i in range(len(apple)): temp=a+apple[i] if temp in range(s,t+1): countA+=1 for i in range(len(orange)): temp=b+orange[i] if temp in range(s,t+1): countO+=1 print(countA) print(countO)
[ "noreply@github.com" ]
Mayurg6832.noreply@github.com
d32de0ad23b35433aeaaee25ab27bdb519c0dfdb
ebbe9b78464976119e619d683aa1f6b370508ba7
/testdrf/tdrf/wsgi.py
824146f6d0f901ec80ed48a580c2fb5e85a9162e
[]
no_license
taojy123/openapi_speech
bc98dda45ba913b3408b5649a5c574b5badd21f0
751dde6b952c08d09bb6c7cbc0e65040fa2498e7
refs/heads/master
2022-11-07T14:03:32.104921
2020-06-27T15:19:19
2020-06-27T15:19:19
271,430,093
0
0
null
null
null
null
UTF-8
Python
false
false
385
py
""" WSGI config for tdrf 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.0/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tdrf.settings') application = get_wsgi_application()
[ "taojy123@163.com" ]
taojy123@163.com
52cc571ad9fd0579f0fdcb429ce18b6da15f9104
de24f83a5e3768a2638ebcf13cbe717e75740168
/moodledata/vpl_data/85/usersdata/174/55054/submittedfiles/funcoes1.py
4d3c33384d44b3a8fcf1a02d2bb63d5e462d030d
[]
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
1,633
py
# -*- coding: utf-8 -*- def crescente (lista): #código da função crescente for i in range(0,len(lista)-1,1): contd=0 if lista[i]>lista[i+1]: contd=contd+1 if (contd)!=len(lista)-1: return True else: return False def decrescente (lista): #código da função decrescente for i in range(0,len(lista)-1,1): contc=0 if lista[i]<lista[i+1]: contc=contc+1 if contc==len(lista)-1: return True else: return False def consecutivos (lista): #código da função de elementos consecutivos for i in range(0,len(lista)-1,1): cont = 0 if lista[i]==lista[i+1]: cont=cont+1 if cont!=1: return True else: return False #escreva as demais funções # Pedir a quantidade de elementos das listas n = int(input('Quantidade de elementos: ')) # Criar as listas vázias a=[] b=[] c=[] # Inserir elementos à lista for i in range(1,n+1,1): a.append(input('Lista A - %dº Valor: '%i)) for i in range(1,n+1,1): a.append(input('Lista B - %dº Valor: '%i)) for i in range(1,n+1,1): a.append(input('Lista C - %dº Valor: '%i)) #escreva o programa principal def testar(lista): # código da função para fazer os 3 testes if crescente(lista): print ('S') else: print ('N') if decrescente(lista): print ('S') else: print ('N') if consecutivos(lista): print ('S') else: print ('N') # Imprimir os resultados print (testar(a)) print (testar(b)) print (testar(c))
[ "rafael.mota@ufca.edu.br" ]
rafael.mota@ufca.edu.br
4c12c2b031f013b218218fdfe3a52bacb9141085
d2ea8079864f6f0b99937645c2d4cab8817e75f8
/05_lekcja6OperacjeNaPlikach/Zad6Karty.py
ae96e5509ce0b2438c098833c86ccf03a29cb229
[]
no_license
FlyingMedusa/PythonCourse
ea960ab20415180d6e164abf4af5619ad9d256fb
4be6ffd1054b25285205d19987fb0fade0f72c14
refs/heads/master
2022-04-09T15:59:38.742786
2020-02-12T17:49:56
2020-02-12T17:49:56
213,706,789
0
0
null
null
null
null
UTF-8
Python
false
false
1,580
py
def is_visa(is_card, number): if is_card == False: return False if len(number) == 16 or len(number) == 13: if card_number[0] == '4': return True def is_mastercard(is_card, number): if is_card == False: return False if len(number) == 16: if int(number[0:2]) in range(51, 56) or int(number[0:4]) in range(2221, 2721): return True def is_AmE(is_card, number): if is_card == False: return False if len(number) == 15: if int(number[0:2]) in (34, 37): return True filename = 'cardsnumbers.txt' with open(filename) as fopen: cards = fopen.read() cards = cards.split() i = 1 for card_number in cards: can_be_card_number = False print(i) if 13 > len(card_number) or 16 < len(card_number): print("\tWrong number") else: if card_number.isdecimal(): print("\tCan be a card number") can_be_card_number = True else: print("\tNot a number") if is_visa(can_be_card_number, card_number): print("\tI'm a Visa") with open('visa.txt', 'a') as f: f.write(card_number) elif is_mastercard(can_be_card_number, card_number): print("\tI'm a Mastercard") with open('mastercard.txt', 'a') as f: f.write(card_number) elif is_AmE(can_be_card_number, card_number): print("\tI'm an American Express") with open('American.txt', 'a') as f: f.write(card_number) else: print("\tNot known card type") i += 1
[ "sleboda.m98@gmail.com" ]
sleboda.m98@gmail.com
5a1775df5cda2474ee302d546f93b09146350649
ab8a34e5b821dde7b09abe37c838de046846484e
/twilio/sample-code-master/taskrouter/v1/task_queues_statistics/read-default/read-default.6.x.py
e63be41889aa29f493efff5404bcbd35336aaf55
[]
no_license
sekharfly/twilio
492b599fff62618437c87e05a6c201d6de94527a
a2847e4c79f9fbf5c53f25c8224deb11048fe94b
refs/heads/master
2020-03-29T08:39:00.079997
2018-09-21T07:20:24
2018-09-21T07:20:24
149,721,431
0
1
null
null
null
null
UTF-8
Python
false
false
547
py
# Download the helper library from https://www.twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/console account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' auth_token = 'your_auth_token' client = Client(account_sid, auth_token) statistics = client.taskrouter \ .workspaces('WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \ .task_queues \ .statistics \ .list() for record in statistics: print(record.cumulative)
[ "sekharfly@gmail.com" ]
sekharfly@gmail.com
376231c1647b7584c2972dbc259b12d4122f151e
2761d1c5563950f919953240e569dd7397ad2a28
/clip/ViT-B-32-cpu/code/__torch__/torch/nn/modules/linear/___torch_mangle_9547.py
2f0fb6831db918b275671b098939d68f5e4e1cbe
[ "MIT" ]
permissive
shawwn/CLIP
c8e65523481d4f48852600eda1909a853f46bc05
ba33b4eb956e6f507b4b39468b3b7336ac2260a1
refs/heads/main
2023-02-21T13:03:51.522948
2021-01-16T03:45:59
2021-01-16T03:45:59
327,780,194
6
2
null
2021-01-08T02:41:08
2021-01-08T02:41:08
null
UTF-8
Python
false
false
646
py
class Linear(Module): __parameters__ = ["weight", "bias", ] __buffers__ = [] weight : Tensor bias : Tensor training : bool def forward(self: __torch__.torch.nn.modules.linear.___torch_mangle_9547.Linear, argument_1: Tensor) -> Tensor: _0 = self.bias output = torch.matmul(argument_1.float(), torch.t(self.weight.float())) return torch.add_(output, _0, alpha=1) def forward1(self: __torch__.torch.nn.modules.linear.___torch_mangle_9547.Linear, argument_1: Tensor) -> Tensor: _1 = self.bias output = torch.matmul(argument_1.float(), torch.t(self.weight.float())) return torch.add_(output, _1, alpha=1)
[ "shawnpresser@gmail.com" ]
shawnpresser@gmail.com
d2f0dd4e289f55fd0a8ef460b27fab5cd1d64156
e7005d4b461c7dfc9f660dff642892cbb7b66948
/docker/server/project/app/controller/monitoring/views.py
fbef82c64d0eb24efffc86b35f83c41891006ae4
[]
no_license
ardikabs/fipro-core
963ca6e73dc9a961e94be7681fa919058acc414a
123ecad130fbf103b69604343fff96486419998c
refs/heads/master
2022-12-13T14:00:34.463893
2019-07-05T07:42:01
2019-07-05T07:42:01
130,592,675
5
0
null
2022-12-08T02:33:05
2018-04-22T17:50:06
CSS
UTF-8
Python
false
false
6,857
py
import datetime import pytz import json from bson import json_util from flask import ( current_app, jsonify, render_template, request, redirect, url_for, flash, make_response ) from flask_login import ( current_user, login_required ) from . import monitoring from app.utils import get_datetime, current_datetime from app.commons.MongoInterface import MongoInterface as MoI from app.models import Agents, OldAgents @monitoring.route('/') @login_required def index(): return redirect(url_for('main.index')) @monitoring.route('/top-attacks/') @login_required def top_attacks(): title = "Top Attacks" moi = MoI() if moi.check_conn() is False: return render_template('monitoring/top_attacks.html', title=title, db_info=False) return render_template('monitoring/top_attacks.html', title=title, db_info=True) @monitoring.route('/event-statistics/') @login_required def event_statistics(): import time start = time.time() title = "Event Statistics" moi = MoI() if moi.check_conn() is False: return render_template('monitoring/event_statistics.html', title=title, db_info=False) events = moi.logs.events_histogram(identifier= current_user.identifier, limit=10) print ("1. {}".format(time.time() - start)) countries = moi.logs.countries_histogram(identifier= current_user.identifier, limit=10) print ("2. {}".format(time.time() - start)) ports = moi.logs.ports_histogram(identifier= current_user.identifier, limit=11) print ("3. {}".format(time.time() - start)) sensor_events_histogram = json.dumps(events, default=json_util.default) countries_event_histogram = json.dumps(countries, default=json_util.default) ports_event_histogram = json.dumps(ports, default=json_util.default) sensor_events = moi.logs.events_count(identifier= current_user.identifier) print ("4. {}".format(time.time() - start)) ports_events = moi.logs.ports_events_count(identifier= current_user.identifier, limit=15) print ("5. {}".format(time.time() - start)) countries_ports_events = moi.logs.top_countries_port(identifier= current_user.identifier, limit=6) print ("6. {}".format(time.time() - start)) return render_template( 'monitoring/event_statistics.html', title=title, db_info=True, sensor_event_histogram=sensor_events_histogram, countries_event_histogram=countries_event_histogram, ports_event_histogram=ports_event_histogram, sensor_events=sensor_events, ports_events=ports_events, countries_ports_events=countries_ports_events ) @monitoring.route('/event-hourly-statistics/') @login_required def event_hourly_statistics(): title = "Event Hourly Statistics" moi = MoI() if moi.check_conn() is False: return render_template('monitoring/event_hourly.html', title=title, db_info=False) current = current_datetime() date = current.strftime("%Y-%m-%d") ts = datetime.datetime.strptime(date, "%Y-%m-%d") sensor_event = moi.logs.sensor_event_statistics(identifier= current_user.identifier, date=ts) agent_event = moi.logs.agents_event_statistics(identifier= current_user.identifier, date=ts) ports_event = moi.logs.ports_event_statistics(identifier= current_user.identifier, date=ts, limit=10) countries_event = moi.logs.countries_event_statistics(identifier= current_user.identifier, date=ts, limit=10) for agent in agent_event: ag = Agents.query.filter_by(ipaddr=agent.get('label')).first() agent['agent_ip'] = agent['label'] agent['label'] = ag.show_info() return render_template( 'monitoring/event_hourly.html', title=title, db_info=True, sensor_event = sensor_event, agent_event = agent_event, ports_event = ports_event, countries_event = countries_event ) # AJAX ENDPOINT @monitoring.route('/top-attacks/ajax/', methods=['GET','POST']) @login_required def top_attacks_ajax(): moi = MoI() if moi.check_conn() is False: return make_response(jsonify([]), 500) res = None type = request.args.get('type', None) limit = request.args.get('limit', 10) identifier = current_user.identifier options = {'limit': limit} if identifier is None: return make_response(jsonify({'message': 'Identifier required'}), 403) if type == 'top_srcip_port': res = moi.logs.top_sourceip_port(identifier = identifier) elif type == 'top_asn': res = moi.logs.top_asn(identifier = identifier, options=options) elif type == 'top_countries': res = moi.logs.top_countries(identifier = identifier, options=options) elif type == 'top_src_ip': res = moi.logs.top_sourceip(identifier = identifier, options=options) elif type == 'top_unknown': res = moi.logs.top_unknown_sourceip(identifier = identifier, options=options) if res: return make_response(jsonify(res), 200) else: if res is not None: res = {'message': 'No data available', 'status':False} return make_response(jsonify(res), 503) return make_response(jsonify({"message":"Type is not recognized", "status": False}), 404) @monitoring.route('/event-hourly-statistics/ajax/') @login_required def event_hourly_ajax(): moi = MoI() if moi.check_conn() is False: return make_response(jsonify([]), 500) type = request.args.get('type') date = request.args.get('date') identifier = current_user.identifier if identifier is None: return make_response(jsonify({'message': 'Identifier required'}), 403) if date is None: return make_response(jsonify({'message': 'Date param is not initialized'}), 404) ts = datetime.datetime.strptime(date, "%Y-%m-%d").replace(tzinfo=pytz.utc) if type == 'sensor-event': data = moi.logs.sensor_event_statistics(identifier= identifier, date=ts) elif type == 'agents-event': data = moi.logs.agents_event_statistics(identifier= identifier, date=ts) for agent in data: ag = Agents.query.filter_by(ipaddr=agent.get('label')).first() if ag is None: ag = OldAgents.query.filter_by(ipaddr=agent.get('label')).first() agent['agent_ip'] = agent['label'] agent['label'] = ag.show_info() elif type == 'ports-event': data = moi.logs.ports_event_statistics(identifier= identifier, date=ts, limit=10) elif type == 'countries-event': data = moi.logs.countries_event_statistics(identifier= identifier, date=ts, limit=10) if data: return make_response(jsonify(data), 200) else: return make_response(jsonify([]), 404)
[ "ardikabs@gmail.com" ]
ardikabs@gmail.com
9e4b180c96b1b6d9c029b8758dfdd177d8f91d11
a54d5a5ae5ba352963f1166a29e1bb6c867157ab
/python/test/test_cumulative_list_sum.py
2dd93e2dfe24d60ecabdb6d3b8f14108116ddf67
[]
no_license
alephist/edabit-coding-challenges
06f573e90ffbd13bc54ecbdaa8e6a225aa44f5d8
35f1fc84848fc44e184aae1ae231a36319c1c81e
refs/heads/main
2023-07-30T22:39:37.468756
2021-09-18T07:47:02
2021-09-18T07:47:02
341,467,751
0
0
null
null
null
null
UTF-8
Python
false
false
733
py
import unittest from typing import List, Tuple from cumulative_list_sum import cumulative_sum test_values: Tuple[Tuple[List[int], List[int]]] = ( ([], []), ([1], [1]), ([1, 2, 3], [1, 3, 6]), ([-1, -2, -3], [-1, -3, -6]), ([1, -2, 3], [1, -1, 2]), ([3, 3, -2, 408, 3, 3, 0, 66, 2, -2, 2, 3, 4, 2, -47, 3, 3, 2], [3, 6, 4, 412, 415, 418, 418, 484, 486, 484, 486, 489, 493, 495, 448, 451, 454, 456]), ) class CumulativeListSumTestCase(unittest.TestCase): def test_return_list_of_cumulative_sum(self): for lst, expected_lst in test_values: with self.subTest(): self.assertEqual(cumulative_sum(lst), expected_lst) if __name__ == '__main__': unittest.main()
[ "justin.necesito@gmail.com" ]
justin.necesito@gmail.com
8988b99c5aee861a7932799ddd6ef9b5e4ae0eb2
669f4fd966fd6068c9658a87fea3545e96df2285
/mask_tools.py
0d8c1711e31e27d14cb53d3e6511168301a80bae
[ "LicenseRef-scancode-public-domain" ]
permissive
wtfuzz/kaggle-dsbowl-2018-dataset-fixes
23927bad32b20beb6567e0f27c0af452bd3c4cf2
72b505fa661cde4e4b1a16198e71f16f1dd94fd1
refs/heads/master
2021-09-09T21:19:42.181400
2018-03-19T19:16:11
2018-03-19T19:16:11
125,908,151
0
0
null
2018-03-19T19:14:26
2018-03-19T19:14:26
null
UTF-8
Python
false
false
2,181
py
#!/usr/bin/env python3 import argparse from pathlib import Path import numpy as np from PIL import Image def create_masks(): """ Create masks from red color above original image. """ parser = argparse.ArgumentParser() parser.add_argument('root') args = parser.parse_args() root = Path(args.root) images_root = root / 'images' masks_root = root / 'masks' assert images_root.is_dir() and masks_root.is_dir() for mask_path in list(images_root.glob('mask*.png')): a = np.array(Image.open(mask_path)) # filter only red color mask = (a[:, :, 0] > 127) & (np.max(a[:, :, 1:3], axis=2) < 80) out_path = masks_root / mask_path.name _save_mask(mask, out_path) mask_path.unlink() print(f'{mask_path} -> {out_path}') def ensure_mask(): """ Ensure that a given (edited) mask shows what is it (clip to 0 or 255). """ parser = argparse.ArgumentParser() parser.add_argument('mask_paths', nargs='+') args = parser.parse_args() mask_paths = [] for mask_path in map(Path, args.mask_paths): if mask_path.is_dir(): mask_paths.extend((mask_path / 'masks').glob('*.png')) else: mask_path.append(mask_path) for mask_path in mask_paths: a = np.array(Image.open(mask_path)) needs_fixing = False if len(a.shape) == 3: needs_fixing = True print(f'fixing shape (was {a.shape}) for {mask_path}') a = a[:, :, :3].max(axis=2) if a.dtype != np.uint8: print(f'fixing dtype (was {a.dtype}) for {mask_path}') needs_fixing = True assert a.dtype == np.bool a = a.astype(np.uint8) * 255 assert len(a.shape) == 2 to_fix = np.sum((a > 0) & (a < 255)) if to_fix: needs_fixing = True print(f'fixed {to_fix} pixels for {mask_path}') if needs_fixing: _save_mask(a > 80, mask_path) def _save_mask(mask: np.ndarray, path: Path): assert mask.dtype == np.bool Image.fromarray(mask.astype(np.uint8) * 255).save(path) if __name__ == '__main__': ensure_mask()
[ "kostia.lopuhin@gmail.com" ]
kostia.lopuhin@gmail.com
e188fbadc4084e203a34f001c1a6c864b6c16e49
33518b9521d8e633010b0b9d1ea0f7a937437200
/Python/rotate_list/rotate_list.py
3ecf8c4f8d6e4e343598e87bf7f9176d4bd68aa5
[]
no_license
lqs4188980/CodingPractice
977ddb69306c92a5e3df88f26572200622fad82a
c17653832269ab1bb3e411f7d74bef4c8e9985b3
refs/heads/master
2021-01-22T05:10:40.885490
2016-02-05T09:06:51
2016-02-05T09:06:51
25,272,652
0
1
null
2016-01-06T07:50:29
2014-10-15T20:40:34
Java
UTF-8
Python
false
false
551
py
class Solution(object): def rotateRight(self, head, k): if head is None: return head l = 0 p = head while p: l += 1 p = p.next k %= l if k == 0: return head i, p = l-k, head while i: i -= 1 p = p.next q = p while q.next: q = q.next q.next = head i = l-k-1 while i > 0: i -= 1 head = head.next head.next = None return p
[ "xiaoqin.zhu.4@gmail.com" ]
xiaoqin.zhu.4@gmail.com
7ca4eecfe2397f0d485aeda40315a32a0818623e
8a9dbfd7c2213652265269838ca9c15aad66a66f
/class-20161005/report/정동휘_식품생명공학과/grade_calculator.py
9b0a53ccdbdcbbbbfb0588a42552fc3dd5fb7f8c
[]
no_license
askdjango/snu-web-2016-09
48ba3b0301be1e0f05f1e630dcfecac51827e779
eaf703cc3ff7ddf3795a636ad1631624a87a9b70
refs/heads/master
2020-02-26T14:23:00.495594
2016-12-19T11:51:45
2016-12-19T11:51:45
68,677,254
6
2
null
null
null
null
UTF-8
Python
false
false
1,370
py
result = {} for i in range(1, 4): name = input('{} 번째 학생 이름은? '.format(i)) ko_score = int(input('{}님의 국어 시험 점수는? '.format(name))) en_score = int(input('{}님의 영어 시험 점수는? '.format(name))) math_score = int(input('{}님의 수학 시험 점수는? '.format(name))) result[name] = { 'ko_score': ko_score, 'en_score': en_score, 'math_score': math_score, } print('개별 평균점수') for name in result: total = result[name]['ko_score'] + result[name]['en_score'] + result[name]['math_score'] average = total / 3 print('[{}] 국어: {}, 영어: {}, 수학: {}, 평균: {}'.format( name, result[name]['ko_score'], result[name]['en_score'], result[name]['math_score'], average, )) print('전체 국어 평균점수는?') ko_total = 0 for name in result: ko_total += result[name]['ko_score'] ko_average = ko_total / len(result) print(ko_average) print('전체 영어 평균점수는?') en_total = 0 for name in result: en_total += result[name]['en_score'] en_average = en_total / len(result) print(en_average) print('전체 수학 평균점수는?') math_total = 0 for name in result: math_total += result[name]['math_score'] math_average = math_total / len(result) print(math_average)
[ "allieuslee@gmail.com" ]
allieuslee@gmail.com
a718fb9f186e8c294058abca07778ec93045f6d0
af9268e1ead8cdb491868c14a2240d9e44fb3b56
/last-minute-env/lib/python2.7/site-packages/django/db/migrations/utils.py
7ce4ca8663c3ddcf8da046cd7f1629f47a953275
[]
no_license
frosqh/Cousinade2017
d5154c24c93ca8089eeba26b53c594e92cb6bd82
c34d5707af02402bf2bb7405eddc91297da399ff
refs/heads/master
2021-01-20T07:57:34.586476
2017-10-22T18:42:45
2017-10-22T18:42:45
90,074,802
1
0
null
null
null
null
UTF-8
Python
false
false
413
py
import datetime import re COMPILED_REGEX_TYPE = type(re.compile('')) class RegexObject(object): def __init__(self, obj): self.pattern = obj.pattern self.flags = obj.flags def __eq__(self, other): return self.pattern == other.pattern and self.flags == other.flags def get_migration_name_timestamp(): return datetime.datetime.now().strftime("%Y%m%d_%H%M")
[ "frosqh@gmail.com" ]
frosqh@gmail.com
f3259a87df330e939839e295315c2a730bbcd3a1
221cada2354556fbb969f25ddd3079542904ef5d
/Leetcode/53.py
542846f48674eb52b129579efcd4ee597d7cdaf6
[]
no_license
syzdemonhunter/Coding_Exercises
4b09e1a7dad7d1e3d4d4ae27e6e006732ffdcb1d
ca71572677d2b2a2aed94bb60d6ec88cc486a7f3
refs/heads/master
2020-05-24T11:19:35.019543
2019-11-22T20:08:32
2019-11-22T20:08:32
187,245,394
1
0
null
null
null
null
UTF-8
Python
false
false
765
py
# https://leetcode.com/problems/maximum-subarray/ ''' # T: O(n) # S: O(n) class Solution: def maxSubArray(self, nums: List[int]) -> int: dp = [0]*len(nums) dp[0] = nums[0] result = dp[0] for i in range(1, len(nums)): if dp[i - 1] < 0: dp[i] = nums[i] else: dp[i] = nums[i] + dp[i - 1] result = max(result, dp[i]) return result ''' # T: O(n) # S: O(1) class Solution: def maxSubArray(self, nums: List[int]) -> int: result = nums[0] max_end = nums[0] for num in nums[1:]: max_end = max(num, max_end + num) result = max(result, max_end) return result
[ "syzuser60@gmail.com" ]
syzuser60@gmail.com
425c558f56bc92363d78905ea0157a314eb024a5
07539ecbcee0488ce4a0eb779583da3149cfac7b
/amonone/mail/models.py
0c56dda41c125c637c4a429143771a2b70ceaf09
[ "MIT" ]
permissive
outbounder/amonone
e151584ac38222b40c314d586ebadc4e0f43fce1
985fa147c1d98a4f57ff33ebd37ca0d938fe674d
refs/heads/master
2020-12-25T13:33:46.425826
2013-07-11T08:54:32
2013-07-11T08:54:32
11,389,227
1
0
null
null
null
null
UTF-8
Python
false
false
624
py
from amonone.web.apps.core.basemodel import BaseModel class EmailModel(BaseModel): def __init__(self): super(EmailModel, self).__init__() self.collection = self.mongo.get_collection('email_settings') def save_email_details(self, data=None): self.collection.remove() self.collection.insert(data) def get_email_details(self): return self.collection.find_one() class EmailRecepientModel(BaseModel): def __init__(self): super(EmailRecepientModel, self).__init__() self.collection = self.mongo.get_collection('email_recepients') email_model = EmailModel() email_recepient_model = EmailRecepientModel()
[ "martinrusev@zoho.com" ]
martinrusev@zoho.com
1ee375c9ad6c64d94fa46b81938f9ace48c32246
83277e8b959de61b655f614b7e072394a99d77ae
/venv/lib/python3.7/site-packages/graphql/validation/rules/__init__.py
056a530de90b0f265b8512ca66debc4458dbc8f6
[ "MIT" ]
permissive
hskang9/scalable-django
b3ed144670c3d5b244168fdd38f33e1f596253c0
162e0f4a3d49f164af1d33298fa9a47b66508cbf
refs/heads/master
2023-04-29T05:33:23.460640
2020-03-27T00:55:28
2020-03-27T00:55:28
247,036,359
2
1
MIT
2023-04-21T20:53:08
2020-03-13T09:40:37
Python
UTF-8
Python
false
false
2,910
py
from .arguments_of_correct_type import ArgumentsOfCorrectType from .default_values_of_correct_type import DefaultValuesOfCorrectType from .fields_on_correct_type import FieldsOnCorrectType from .fragments_on_composite_types import FragmentsOnCompositeTypes from .known_argument_names import KnownArgumentNames from .known_directives import KnownDirectives from .known_fragment_names import KnownFragmentNames from .known_type_names import KnownTypeNames from .lone_anonymous_operation import LoneAnonymousOperation from .no_fragment_cycles import NoFragmentCycles from .no_undefined_variables import NoUndefinedVariables from .no_unused_fragments import NoUnusedFragments from .no_unused_variables import NoUnusedVariables from .overlapping_fields_can_be_merged import OverlappingFieldsCanBeMerged from .possible_fragment_spreads import PossibleFragmentSpreads from .provided_non_null_arguments import ProvidedNonNullArguments from .scalar_leafs import ScalarLeafs from .unique_argument_names import UniqueArgumentNames from .unique_fragment_names import UniqueFragmentNames from .unique_input_field_names import UniqueInputFieldNames from .unique_operation_names import UniqueOperationNames from .unique_variable_names import UniqueVariableNames from .variables_are_input_types import VariablesAreInputTypes from .variables_in_allowed_position import VariablesInAllowedPosition # Necessary for static type checking if False: # flake8: noqa from typing import List, Type from .base import ValidationRule specified_rules = [ UniqueOperationNames, LoneAnonymousOperation, KnownTypeNames, FragmentsOnCompositeTypes, VariablesAreInputTypes, ScalarLeafs, FieldsOnCorrectType, UniqueFragmentNames, KnownFragmentNames, NoUnusedFragments, PossibleFragmentSpreads, NoFragmentCycles, NoUndefinedVariables, NoUnusedVariables, KnownDirectives, KnownArgumentNames, UniqueArgumentNames, ArgumentsOfCorrectType, ProvidedNonNullArguments, DefaultValuesOfCorrectType, VariablesInAllowedPosition, OverlappingFieldsCanBeMerged, UniqueInputFieldNames, UniqueVariableNames, ] # type: List[Type[ValidationRule]] __all__ = [ "ArgumentsOfCorrectType", "DefaultValuesOfCorrectType", "FieldsOnCorrectType", "FragmentsOnCompositeTypes", "KnownArgumentNames", "KnownDirectives", "KnownFragmentNames", "KnownTypeNames", "LoneAnonymousOperation", "NoFragmentCycles", "UniqueVariableNames", "NoUndefinedVariables", "NoUnusedFragments", "NoUnusedVariables", "OverlappingFieldsCanBeMerged", "PossibleFragmentSpreads", "ProvidedNonNullArguments", "ScalarLeafs", "UniqueArgumentNames", "UniqueFragmentNames", "UniqueInputFieldNames", "UniqueOperationNames", "VariablesAreInputTypes", "VariablesInAllowedPosition", "specified_rules", ]
[ "hyungsukkang@Hyungsuks-Mac-mini.local" ]
hyungsukkang@Hyungsuks-Mac-mini.local
00b09bb07ee546d00b56dca37a774c559f81dda9
6982c3c54ee9199d93fb89c61cfdcba15b9b7012
/exercise/git_exercises/visitors_book/visitors_book/wsgi.py
20d31dac8eebd8eb05a5e3d496a59265370e9973
[]
no_license
gzgdouru/python_study
a640e1097ebc27d12049ded53fb1af3ba9729bac
e24b39e82e39ee5a5e54566781457e18c90a122a
refs/heads/master
2020-03-29T11:33:13.150869
2019-03-08T09:24:29
2019-03-08T09:24:29
149,858,658
0
1
null
null
null
null
UTF-8
Python
false
false
404
py
""" WSGI config for visitors_book 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/1.11/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "visitors_book.settings") application = get_wsgi_application()
[ "18719091650@163.com" ]
18719091650@163.com
8fd124b553f30e34b2daea187d61f7717b22fa81
3c000380cbb7e8deb6abf9c6f3e29e8e89784830
/venv/Lib/site-packages/cobra/modelimpl/vns/range.py
ebba918f860a70b9f9534be38894aba409af3ada
[]
no_license
bkhoward/aciDOM
91b0406f00da7aac413a81c8db2129b4bfc5497b
f2674456ecb19cf7299ef0c5a0887560b8b315d0
refs/heads/master
2023-03-27T23:37:02.836904
2021-03-26T22:07:54
2021-03-26T22:07:54
351,855,399
0
0
null
null
null
null
UTF-8
Python
false
false
5,551
py
# coding=UTF-8 # ********************************************************************** # Copyright (c) 2013-2020 Cisco Systems, Inc. All rights reserved # written by zen warriors, do not modify! # ********************************************************************** from cobra.mit.meta import ClassMeta from cobra.mit.meta import StatsClassMeta from cobra.mit.meta import CounterMeta from cobra.mit.meta import PropMeta from cobra.mit.meta import Category from cobra.mit.meta import SourceRelationMeta from cobra.mit.meta import NamedSourceRelationMeta from cobra.mit.meta import TargetRelationMeta from cobra.mit.meta import DeploymentPathMeta, DeploymentCategory from cobra.model.category import MoCategory, PropCategory, CounterCategory from cobra.mit.mo import Mo # ################################################## class Range(Mo): """ A range assertion. """ meta = ClassMeta("cobra.model.vns.Range") meta.moClassName = "vnsRange" meta.rnFormat = "range-%(name)s" meta.category = MoCategory.REGULAR meta.label = "Range Assertion" meta.writeAccessMask = 0x1 meta.readAccessMask = 0x1 meta.isDomainable = False meta.isReadOnly = True meta.isConfigurable = False meta.isDeletable = False meta.isContextRoot = False meta.parentClasses.add("cobra.model.vns.MDev") meta.parentClasses.add("cobra.model.vns.MParam") meta.parentClasses.add("cobra.model.vns.MFolder") meta.parentClasses.add("cobra.model.vns.Composite") meta.parentClasses.add("cobra.model.vns.MFunc") meta.superClasses.add("cobra.model.naming.NamedObject") meta.superClasses.add("cobra.model.vns.Assertion") meta.rnPrefixes = [ ('range-', True), ] prop = PropMeta("str", "childAction", "childAction", 4, PropCategory.CHILD_ACTION) prop.label = "None" prop.isImplicit = True prop.isAdmin = True prop._addConstant("deleteAll", "deleteall", 16384) prop._addConstant("deleteNonPresent", "deletenonpresent", 8192) prop._addConstant("ignore", "ignore", 4096) meta.props.add("childAction", prop) prop = PropMeta("str", "dn", "dn", 1, PropCategory.DN) prop.label = "None" prop.isDn = True prop.isImplicit = True prop.isAdmin = True prop.isCreateOnly = True meta.props.add("dn", prop) prop = PropMeta("str", "lcOwn", "lcOwn", 9, PropCategory.REGULAR) prop.label = "None" prop.isImplicit = True prop.isAdmin = True prop.defaultValue = 0 prop.defaultValueStr = "local" prop._addConstant("implicit", "implicit", 4) prop._addConstant("local", "local", 0) prop._addConstant("policy", "policy", 1) prop._addConstant("replica", "replica", 2) prop._addConstant("resolveOnBehalf", "resolvedonbehalf", 3) meta.props.add("lcOwn", prop) prop = PropMeta("str", "modTs", "modTs", 7, PropCategory.REGULAR) prop.label = "None" prop.isImplicit = True prop.isAdmin = True prop.defaultValue = 0 prop.defaultValueStr = "never" prop._addConstant("never", "never", 0) meta.props.add("modTs", prop) prop = PropMeta("str", "name", "name", 7373, PropCategory.REGULAR) prop.label = "Name" prop.isConfig = True prop.isAdmin = True prop.isCreateOnly = True prop.isNaming = True prop.range = [(1, 16)] prop.regex = ['[a-zA-Z0-9_.:-]+'] prop.defaultValue = "schema" prop.defaultValueStr = "schema" meta.props.add("name", prop) prop = PropMeta("str", "nameAlias", "nameAlias", 28417, PropCategory.REGULAR) prop.label = "Name alias" prop.isConfig = True prop.isAdmin = True prop.range = [(0, 63)] prop.regex = ['[a-zA-Z0-9_.-]+'] meta.props.add("nameAlias", prop) prop = PropMeta("str", "not", "not", 5085, PropCategory.REGULAR) prop.label = "None" prop.isImplicit = True prop.isAdmin = True prop.defaultValue = False prop.defaultValueStr = "no" prop._addConstant("no", None, False) prop._addConstant("yes", None, True) meta.props.add("not", prop) prop = PropMeta("str", "rn", "rn", 2, PropCategory.RN) prop.label = "None" prop.isRn = True prop.isImplicit = True prop.isAdmin = True prop.isCreateOnly = True meta.props.add("rn", prop) prop = PropMeta("str", "status", "status", 3, PropCategory.STATUS) prop.label = "None" prop.isImplicit = True prop.isAdmin = True prop._addConstant("created", "created", 2) prop._addConstant("deleted", "deleted", 8) prop._addConstant("modified", "modified", 4) meta.props.add("status", prop) prop = PropMeta("str", "value1", "value1", 5088, PropCategory.REGULAR) prop.label = "None" prop.isImplicit = True prop.isAdmin = True prop.range = [(0, 512)] meta.props.add("value1", prop) prop = PropMeta("str", "value2", "value2", 5089, PropCategory.REGULAR) prop.label = "None" prop.isImplicit = True prop.isAdmin = True prop.range = [(0, 512)] meta.props.add("value2", prop) meta.namingProps.append(getattr(meta.props, "name")) # Deployment Meta meta.deploymentQuery = True meta.deploymentType = "Ancestor" meta.deploymentQueryPaths.append(DeploymentPathMeta("MDevToGraphInst", "Graph Instances", "cobra.model.vns.GraphInst")) def __init__(self, parentMoOrDn, name, markDirty=True, **creationProps): namingVals = [name] Mo.__init__(self, parentMoOrDn, markDirty, *namingVals, **creationProps) # End of package file # ##################################################
[ "bkhoward@live.com" ]
bkhoward@live.com
7a585e2db5523b1ba1a9cca50833de40373101ac
cdbd54f19b28c651e1945f4514a2a2a5431d4753
/myspider/myspider/settings.py
fe55396cdd58a2b20c9a62c340c9ed8b6be7bf33
[]
no_license
Knowledgeofitselfisriches/spider
8ccc7e928da00dc7b53159fb53d6f38b16316ee9
797736b6ac850532efe42d9e60524d612d99ad02
refs/heads/master
2020-03-27T08:41:06.005591
2018-09-11T05:48:10
2018-09-11T05:48:10
146,277,449
0
0
null
null
null
null
UTF-8
Python
false
false
3,380
py
# -*- coding: utf-8 -*- # Scrapy settings for myspider project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # https://doc.scrapy.org/en/latest/topics/settings.html # https://doc.scrapy.org/en/latest/topics/downloader-middleware.html # https://doc.scrapy.org/en/latest/topics/spider-middleware.html import os BOT_NAME = 'myspider' SPIDER_MODULES = ['myspider.spiders'] NEWSPIDER_MODULE = 'myspider.spiders' # Crawl responsibly by identifying yourself (and your website) on the user-agent # USER_AGENT = 'myspider (+http://www.yourdomain.com)' # Obey robots.txt rules ROBOTSTXT_OBEY = False # Configure maximum concurrent requests performed by Scrapy (default: 16) # CONCURRENT_REQUESTS = 32 # Configure a delay for requests for the same website (default: 0) # See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay # See also autothrottle settings and docs # DOWNLOAD_DELAY = 3 # The download delay setting will honor only one of: # CONCURRENT_REQUESTS_PER_DOMAIN = 16 # CONCURRENT_REQUESTS_PER_IP = 16 # Disable cookies (enabled by default) # COOKIES_ENABLED = False # Disable Telnet Console (enabled by default) # TELNETCONSOLE_ENABLED = False # Override the default request headers: DEFAULT_REQUEST_HEADERS = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'en', 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36' } # Enable or disable spider middlewares # See https://doc.scrapy.org/en/latest/topics/spider-middleware.html # SPIDER_MIDDLEWARES = { # 'myspider.middlewares.MyspiderSpiderMiddleware': 543, # } # Enable or disable downloader middlewares # See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html # DOWNLOADER_MIDDLEWARES = { # 'myspider.middlewares.MyspiderDownloaderMiddleware': 543, # } # Enable or disable extensions # See https://doc.scrapy.org/en/latest/topics/extensions.html # EXTENSIONS = { # 'scrapy.extensions.telnet.TelnetConsole': None, # } # Configure item pipelines # See https://doc.scrapy.org/en/latest/topics/item-pipeline.html ITEM_PIPELINES = { 'myspider.pipelines.MyspiderPipeline': 301, 'myspider.pipelines.ShangGuiGuImagePipelines': 300, } # Enable and configure the AutoThrottle extension (disabled by default) # See https://doc.scrapy.org/en/latest/topics/autothrottle.html # AUTOTHROTTLE_ENABLED = True # The initial download delay # AUTOTHROTTLE_START_DELAY = 5 # The maximum download delay to be set in case of high latencies # AUTOTHROTTLE_MAX_DELAY = 60 # The average number of requests Scrapy should be sending in parallel to # each remote server # AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0 # Enable showing throttling stats for every response received: # AUTOTHROTTLE_DEBUG = False # Enable and configure HTTP caching (disabled by default) # See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings # HTTPCACHE_ENABLED = True # HTTPCACHE_EXPIRATION_SECS = 0 # HTTPCACHE_DIR = 'httpcache' # HTTPCACHE_IGNORE_HTTP_CODES = [] # HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage' IMAGES_STORE = os.path.dirname(os.path.realpath("__file__")) + "/images/"
[ "283658013@qq.com" ]
283658013@qq.com
5f36f7b5a2f455751488b2ddc7cfe19638b20074
7913bf8dee268d0ed0a96b6ef359abac24f4e613
/code/backend/billing/migrations/0002_auto_20200512_1158.py
34b08f9bf77070850a866489ba0306dbd6f8e330
[ "MIT" ]
permissive
dorinapall/noe
724236813fc130be550b80bb1701293c4d2775eb
6d5682ab00a2cdc5cb419ecab57804c9f70d7b3a
refs/heads/master
2022-11-11T17:29:22.365369
2020-06-18T09:12:58
2020-06-18T09:12:58
273,198,257
1
0
MIT
2020-06-18T09:35:22
2020-06-18T09:35:21
null
UTF-8
Python
false
false
567
py
# Generated by Django 3.0.5 on 2020-05-12 09:58 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('appointments', '0003_seat_doctor_name'), ('billing', '0001_initial'), ] operations = [ migrations.AlterField( model_name='billingdetail', name='appointment', field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='billing_detail', to='appointments.Appointment'), ), ]
[ "kissgyorgy@me.com" ]
kissgyorgy@me.com
1f3a93ff2a1c44f7c16ced6b39a02975fae54761
3ba2d4091332b9d0a2b053f15a4d4ce4ae1c1ef0
/中等148. 排序链表.py
91439c6553ea5b008723b9dca4e9aafa03ea40cd
[]
no_license
ganhan999/ForLeetcode
126272d34250035abda6c2d67222c2c186a3f80b
9980a9e4bf448b2cf3fed98891a54b6d202a64db
refs/heads/master
2023-05-01T14:21:49.883692
2021-05-12T08:59:51
2021-05-12T08:59:51
348,708,572
0
0
null
null
null
null
UTF-8
Python
false
false
3,684
py
""" 给你链表的头结点head,请将其按 升序 排列并返回 排序后的链表 。 进阶: 你可以在O(nlogn) 时间复杂度和常数级空间复杂度下,对链表进行排序吗? 示例 1: 输入:head = [4,2,1,3] 输出:[1,2,3,4] 示例 2: 输入:head = [-1,5,3,4,0] 输出:[-1,0,3,4,5] 示例 3: 输入:head = [] 输出:[] """ """ 合并排序,利用递归,自上而下 """ #大神做法1 class Solution: def sortList(self, head: ListNode) -> ListNode: def sortFunc(head: ListNode, tail: ListNode) -> ListNode:#用快慢指针找到中点,分成两个链表 if not head: return head if head.next == tail: head.next = None return head slow = fast = head while fast != tail: slow = slow.next fast = fast.next if fast != tail: fast = fast.next mid = slow return merge(sortFunc(head, mid), sortFunc(mid, tail)) def merge(head1: ListNode, head2: ListNode) -> ListNode: dummyHead = ListNode(0) temp, temp1, temp2 = dummyHead, head1, head2 while temp1 and temp2: if temp1.val <= temp2.val: temp.next = temp1 temp1 = temp1.next else: temp.next = temp2 temp2 = temp2.next temp = temp.next if temp1: temp.next = temp1 elif temp2: temp.next = temp2 return dummyHead.next return sortFunc(head, None)#一开始是以None作为fast的最后一个节点的判断条件 """ 合并排序,自底向上,先1后2再4以此类推 """ #大神做法1 class Solution: def sortList(self, head: ListNode) -> ListNode: def merge(head1: ListNode, head2: ListNode) -> ListNode: dummyHead = ListNode(0) temp, temp1, temp2 = dummyHead, head1, head2 while temp1 and temp2: if temp1.val <= temp2.val: temp.next = temp1 temp1 = temp1.next else: temp.next = temp2 temp2 = temp2.next temp = temp.next if temp1: temp.next = temp1 elif temp2: temp.next = temp2 return dummyHead.next if not head: return head length = 0 node = head while node: length += 1 node = node.next dummyHead = ListNode(0, head) subLength = 1 while subLength < length: prev, curr = dummyHead, dummyHead.next while curr: head1 = curr for i in range(1, subLength): if curr.next: curr = curr.next else: break head2 = curr.next curr.next = None curr = head2 for i in range(1, subLength): if curr and curr.next: curr = curr.next else: break succ = None if curr: succ = curr.next curr.next = None merged = merge(head1, head2) prev.next = merged while prev.next: prev = prev.next curr = succ subLength <<= 1 return dummyHead.next
[ "940320304@qq.com" ]
940320304@qq.com
053856ce397586ba9db58c2ae9a1b73ace95139a
82a42645c35b43542c63afb28d3dd0f891d71982
/Stack_and_Queue/RedundantBraces.py
ec0bbb178edbfe11e9042351476d23c7e96b773f
[]
no_license
nehatomar12/Data-structures-and-Algorithms
54e48ecd3cd360ff4ea0196243e4a8b4cdf6181f
b9566764de4faa0e95a4dfe90fe46f843ade4a8c
refs/heads/master
2023-03-01T01:28:55.581679
2021-02-09T08:07:47
2021-02-09T08:07:47
292,843,092
0
0
null
null
null
null
UTF-8
Python
false
false
1,094
py
""" Given a string A denoting an expression. It contains the following operators ’+’, ‘-‘, ‘*’, ‘/’. Chech whether A has redundant braces or not. Return 1 if A has redundant braces, else return 0. Note: A will be always a valid expression. Input 1: A = "((a + b))" Output 1: 1 Explanation 1: ((a + b)) has redundant braces so answer will be 1. Input 2: A = "(a + (a + b))" Output 2: 0 """ A = "((a + b))" A = "(a + (a + b))" #A = "(a)" #A = " ((a+b-c)*c)" def braces(): res = True s = [] top = -1 temp = "" for i in A: if i != " ": s.append(i) top += 1 if top != -1 and s[top] == ')': s.pop() top -= 1 while top != -1 : if s[top] == "(": break temp += s.pop() top -= 1 s.pop() top -= 1 if temp and len(temp) > 1: temp ="" else: res = False if res: return 0 return 1 print((braces()))
[ "neha.tomar@M305393FCHTDF.community.veritas.com" ]
neha.tomar@M305393FCHTDF.community.veritas.com
7e1cef525621e6e50f5dd544e860b0e514055996
be1619e4ef51753443fbc82dedcd9bb5c32749ab
/migrations/tests/loader_files/app2/0001_initial.migration.py
945e1b041c80a3593d661466e63eee2da73c15f9
[]
no_license
PeterUSA123/migrations
5264ea0deed4dc8670f54a6abdf5000439e10cb4
7e5dfb7c32970d9f2163d779a2e225feb123c740
refs/heads/master
2020-09-10T07:39:25.911462
2012-09-04T18:51:15
2012-09-04T18:51:15
null
0
0
null
null
null
null
UTF-8
Python
false
false
383
py
from migrations.api import * class Migration(BaseMigration): actions = [ CreateModel( name = "Book", fields = [ ("title", Field("django.db.models.fields.CharField", [], {"max_length": "100"})), ("author", Field("django.db.models.fields.related.ForeignKey", ["app1.Author"], {})), ], ), ]
[ "andrew@aeracode.org" ]
andrew@aeracode.org
f0d8898bd3cd604ac6df4be28d7ffbec78e9e395
20d9130fdc21756c4f8fe255583922352f5c5762
/src/DIRAC/Interfaces/scripts/dirac-framework-ping-service.py
651aab2405ce29d834f1054882fa688175e87666
[]
no_license
bopopescu/bes3-jinr
095314e43f41f08bd48b248fe3ca627a5c009f58
fdfd852c92a56192b8ee9970b66f0136e6e0afff
refs/heads/master
2022-11-26T06:01:36.718508
2014-03-17T06:03:50
2014-03-17T06:03:50
282,113,617
0
0
null
2020-07-24T03:30:10
2020-07-24T03:30:09
null
UTF-8
Python
false
false
1,430
py
#!/usr/bin/env python ######################################################################## # $HeadURL$ # File : dirac-framework-ping-service # Author : Stuart Paterson ######################################################################## """ Ping the given DIRAC Service """ __RCSID__ = "55b8255 (2010-12-14 18:54:06 +0000) Ricardo Graciani <graciani@ecm.ub.es>" import DIRAC from DIRAC.Core.Base import Script Script.setUsageMessage( '\n'.join( [ __doc__.split( '\n' )[1], 'Usage:', ' %s [option|cfgfile] ... System Service|System/Agent' % Script.scriptName, 'Arguments:', ' System: Name of the DIRAC system (ie: WorkloadManagement)', ' Service: Name of the DIRAC service (ie: Matcher)'] ) ) Script.parseCommandLine( ignoreErrors = True ) args = Script.getPositionalArgs() if len( args ) == 1: args = args[0].split( '/' ) if len( args ) < 2: Script.showHelp() from DIRAC.Interfaces.API.Dirac import Dirac dirac = Dirac() exitCode = 0 system = args[0] service = args[1] result = dirac.ping( system, service, printOutput = True ) if not result: print 'ERROR: Null result from ping()' exitCode = 2 elif not result['OK']: print 'ERROR: ', result['Message'] exitCode = 2 DIRAC.exit( exitCode )
[ "gavelock@gmail.com" ]
gavelock@gmail.com
531256a3754c73218f5f4197dfd5e7e094ed1479
d1032c2b568daf02de5cf2e7aaa33a608ffd20e1
/Basic/1097_16694268(AC).py
3e843332f77134831cb1f74c8ffc85ec0998a1ce
[]
no_license
Junhyeok1015/Codeup
267edef68113951019d28d311d38aa91d6677bde
ee5207528fd22689311c2941b94d7ac2480fe0cc
refs/heads/master
2023-02-12T17:10:06.481196
2021-01-17T02:34:23
2021-01-17T02:34:23
326,317,725
0
0
null
null
null
null
UTF-8
Python
false
false
602
py
list_ = [] for _ in range(19): a = list(map(int, input().strip().split(" "))) list_.append(a) n = int(input()) for i in range(n): a, b = list(map(int, input().strip().split(" "))) for i in range(19): if list_[a-1][i] == 0: list_[a-1][i] = 1 else: list_[a-1][i] = 0 for i in range(19): if list_[i][b-1] == 0: list_[i][b-1] = 1 else: list_[i][b-1] = 0 for i in range(19): line = "" for j in range(19): k = str(list_[i][j]) line += k + " " print(line)
[ "mo223772@naver.com" ]
mo223772@naver.com
285ca8ee864c495bce6ae6df87254098f6f3ae2e
4f875744ccae8fa9225318ce16fc483b7bf2735e
/facebook/phoneScreen/romanToInteger.py
b8b2400a7a9d68417e8d3c8bc1fe8508c27053a0
[]
no_license
nguyenngochuy91/companyQuestions
62c0821174bb3cb33c7af2c5a1e83a60e4a29977
c937fe19be665ba7ac345e1729ff531f370f30e8
refs/heads/master
2020-07-27T05:58:36.794033
2020-04-10T20:57:15
2020-04-10T20:57:15
208,893,527
1
0
null
null
null
null
UTF-8
Python
false
false
458
py
# -*- coding: utf-8 -*- """ Created on Wed Oct 9 16:49:16 2019 @author: huyn """ def romanToInt(s: str) -> int: d= {"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000} if not s: return 0 current = d[s[0]] accumulate = d[s[0]] for i in range(len(s)-1): v = d[s[i+1]] if v>current: accumulate= accumulate-current+v-current else: accumulate+=v current=v return accumulate
[ "huyn@cvm6h4zv52.cvm.iastate.edu" ]
huyn@cvm6h4zv52.cvm.iastate.edu
19a398780eab3ca00a2386b563a810fa549b5d18
eadd15064aa74811e7a3718b617636627ef4fd47
/web/migrations/0013_image_name.py
197a63613795ccaf8996f8c4be245d15c0425935
[]
no_license
topsai/plasrefine_backstage
262f7bb032daa4d018aac1519e1139cb060c3f91
1eb34dd0b13ebdc2a42dd6ed1aaa2d08c18ab5fb
refs/heads/master
2023-04-12T13:24:22.710108
2021-05-08T14:16:41
2021-05-08T14:16:41
361,993,024
0
0
null
null
null
null
UTF-8
Python
false
false
420
py
# Generated by Django 3.2 on 2021-04-30 14:53 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('web', '0012_websetting_about'), ] operations = [ migrations.AddField( model_name='image', name='name', field=models.CharField(default=1, max_length=30), preserve_default=False, ), ]
[ "hurte@foxmail.com" ]
hurte@foxmail.com
57b116ce2d853c1a87b2103a9ab456fb8fb82aa5
97d8d8f303545583e04356279b58c59e41bcb0e7
/TransitAdScreen/settings/base.py
bf8535f899ce787bb222211c9c15aefdd5549c83
[ "Apache-2.0" ]
permissive
8secz-johndpope/transit-advertising-screen-cms
2493c270022ac03b17e4b4b1e9b426f568d01ed5
9c27d4d7ed9fe598c1c48ca96ee5d10f619c8683
refs/heads/master
2022-09-24T13:44:07.056409
2019-10-17T16:40:21
2019-10-17T16:40:21
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,983
py
""" Django settings for TransitAdScreen project. Generated by 'django-admin startproject' using Django 2.2. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'screens.apps.ScreensConfig', 'constance', 'constance.backends.database', 'import_export', 'mathfilters', ] 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 = 'TransitAdScreen.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_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', ], }, }, ] WSGI_APPLICATION = 'TransitAdScreen.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': {} } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/' # Constance CONSTANCE_BACKEND = 'constance.backends.database.DatabaseBackend' CONSTANCE_CONFIG = { 'IMAGE_SERVER_URL': ('https://images.servername.com/', 'Image server URL', str), }
[ "raulsergio9@gmail.com" ]
raulsergio9@gmail.com
3114d5b038163034c2754987fa9932c9df3025f7
07c4f43677af3c8384fd7dd2bd3498f80215625c
/async_worker/__init__.py
ee5e06e732c1aa9689d666bbde5e46a9066211be
[ "Apache-2.0" ]
permissive
cxy19941228/DeepRL
4d898deede02047b4df0d48f40cb0e313137474a
41627588fb2e37869a314ae1af0d272f3f302285
refs/heads/master
2021-08-08T07:56:04.830382
2017-11-09T23:38:42
2017-11-09T23:38:42
null
0
0
null
null
null
null
UTF-8
Python
false
false
165
py
from .actor_critic import * from .continuous_actor_critic import * from .n_step_q import * from .one_step_sarsa import * from .one_step_q import * from .ppo import *
[ "zhangshangtong.cpp@icloud.com" ]
zhangshangtong.cpp@icloud.com
93de096df8ef3defb9087ea670888bea064f46de
fa82dad9e83206d4630a55141bf44f50cbf0c3a8
/day1_python/01_python200_src/093.py
d62211e665cf90be84d1cdc4d581519076449edf
[]
no_license
jsh2333/pyml
8f8c53a43af23b8490b25f35f28d85f1087df28d
157dfa7cc2f1458f12e451691a994ac6ef138cab
refs/heads/master
2021-03-27T22:26:38.254206
2020-04-26T06:35:11
2020-04-26T06:35:11
249,114,580
3
1
null
null
null
null
UTF-8
Python
false
false
236
py
url = 'http://www.naver.com/news/today=20160831' log = 'name:홍길동 age:17 sex:남자 nation:조선' ret1 = url.split('/') print(ret1) ret2 = log.split() for data in ret2: d1, d2 = data.split(':') print('%s -> %s' %(d1, d2))
[ "jsh2333@gmail.com" ]
jsh2333@gmail.com
dbd174bfddafd6ac8f11846488ad2bd44d95b29e
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p04044/s849053305.py
0b1342b80952e0cfcb0dc7796192d0f3752b6f68
[]
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
374
py
# row = [int(x) for x in input().rstrip().split(" ")] # n = int(input().rstrip()) # s = input().rstrip() def resolve(): import sys input = sys.stdin.readline n, l = [int(x) for x in input().rstrip().split(" ")] s_list = [input().rstrip() for _ in range(n)] s_list = sorted(s_list) print("".join(s_list)) if __name__ == "__main__": resolve()
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
6ccf0ca23a683d99e9f431477837de49ec028d4f
9222114c0b39007eb1af715cf18fc95ff282b38c
/problems/415. Add Strings/1 - Backtracking.py
a96022d06c9d0b76ef3f2cbc3458d4236d83b04c
[]
no_license
Vasilic-Maxim/LeetCode-Problems
1a2a09edca6489a349e5d69d087279630cff157d
359f3b78da90c41c7e42e5c9e13d49b4fc67fe41
refs/heads/master
2021-07-10T22:03:29.327658
2021-06-07T12:42:52
2021-06-07T12:42:52
246,826,450
0
0
null
null
null
null
UTF-8
Python
false
false
472
py
from itertools import zip_longest class Solution: def addStrings(self, num1: str, num2: str) -> str: zero = ord("0") carry = 0 result = [] for n1, n2 in zip_longest(reversed(num1), reversed(num2)): n1 = 0 if n1 is None else ord(n1) - zero n2 = 0 if n2 is None else ord(n2) - zero carry, mod = divmod(n1 + n2 + carry, 10) result.append(str(mod)) return "".join(result).reverse()
[ "lmantenl@gmail.com" ]
lmantenl@gmail.com
ee91dee71252520a9168a9f851ead2970876ff66
45bbb2d050c5e6acf85a2180f5c27d415a994185
/KerasCode/mlp.py
a0e6547bf19f7e6756d192aad9932e15d4cf696d
[]
no_license
afcarl/dl_code
e25f07e9e7eba59d83ea0ddb90637bce605b35c9
2b0423673faba67f6ad653c04b6cd045a66f5e80
refs/heads/master
2020-03-22T09:59:01.003729
2017-05-17T02:34:20
2017-05-17T02:34:20
139,873,303
1
0
null
2018-07-05T16:11:15
2018-07-05T16:11:14
null
UTF-8
Python
false
false
764
py
from keras.models import Sequential from keras.layers import Dense import numpy import os import TheanoCode # theano.config.device = 'gpu' seed = 7 numpy.random.seed(seed) data_path = "/".join([os.getcwd(), "../Data/pima-indians-diabetes.data.txt"]) dataset = numpy.loadtxt(data_path, delimiter=",") X = dataset[:,0:8] Y = dataset[:,8] model = Sequential() model.add(Dense(12, input_dim=8, init='uniform', activation='relu')) model.add(Dense(8, init='uniform', activation='relu')) model.add(Dense(1, init='uniform', activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) model.fit(X, Y, nb_epoch=150, batch_size=10) scores = model.evaluate(X, Y) print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
[ "zhaosanqiang916@gmail.com" ]
zhaosanqiang916@gmail.com
80e000c9d12a4180c7aa61e175235c04a2c00eb6
a1a43879a2da109d9fe8d9a75f4fda73f0d7166b
/api/tests_v2/zeros_like.py
52f67cbec0a4d72971c03445e047433928e0e79a
[]
no_license
PaddlePaddle/benchmark
a3ed62841598d079529c7440367385fc883835aa
f0e0a303e9af29abb2e86e8918c102b152a37883
refs/heads/master
2023-09-01T13:11:09.892877
2023-08-21T09:32:49
2023-08-21T09:32:49
173,032,424
78
352
null
2023-09-14T05:13:08
2019-02-28T03:14:16
Python
UTF-8
Python
false
false
1,332
py
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from common_import import * class PDZerosLike(PaddleAPIBenchmarkBase): def build_program(self, config): data = self.variable( name='data', shape=config.x_shape, dtype=config.x_dtype) result = paddle.zeros_like(x=data) self.feed_vars = [data] self.fetch_vars = [result] class TFZerosLike(TensorflowAPIBenchmarkBase): def build_graph(self, config): data = self.variable( name='data', shape=config.x_shape, dtype=config.x_dtype) result = tf.zeros_like(input=data) self.feed_list = [data] self.fetch_list = [result] if __name__ == '__main__': test_main(PDZerosLike(), TFZerosLike(), config=APIConfig("zeros_like"))
[ "noreply@github.com" ]
PaddlePaddle.noreply@github.com