blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 281 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 6 116 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 313 values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 18.2k 668M ⌀ | star_events_count int64 0 102k | fork_events_count int64 0 38.2k | gha_license_id stringclasses 17 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 107 values | src_encoding stringclasses 20 values | language stringclasses 1 value | is_vendor bool 2 classes | is_generated bool 2 classes | length_bytes int64 4 6.02M | extension stringclasses 78 values | content stringlengths 2 6.02M | authors listlengths 1 1 | author stringlengths 0 175 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
18a0d9873f18f71f270141f43088cee487f49f14 | 73ccbb899ab326bfa8c244cd81537fb584cafeca | /beetlebag.py | fc6e7fe223cdafaffe8c179f131f1b4de1ce4f93 | [] | no_license | nebulaf91/ieeextreme-11.0-codes | 725dc3df477364ba4c83515b1b825872a6eb2d17 | 559611b7278d406e892887934bdc09145032a306 | refs/heads/master | 2021-07-16T02:38:11.380849 | 2017-10-15T15:03:27 | 2017-10-15T15:03:27 | 107,022,137 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 581 | py | # not enough time. use simple greedy to try luck
import numpy as np
t = int(input())
for tt in range(t):
out = 0
c, n = map(int, input().split())
weights = np.zeros(n, dtype=int)
power = np.zeros(n, dtype=int)
for i in range(n):
weights[i], power[i] = map(int, input().split())
# print(power)
while(power.sum() != 0):
p = np.argmax(power)
# print(power)
# print("p")
# print(p)
# print(weights[p])
if(weights[p] <= c):
# print("c")
# print(c)
c = c - weights[p]
out += power[p]
power[p] = 0
print(out)
| [
"stopf91@163.com"
] | stopf91@163.com |
e8e2543ebf127df609e14150e7d324f892000270 | 899d52ea074189f5b55c0085a614217692c5d1ba | /Hand-Drawing-Classification-on-Google-Quick-Draw--master/resnet.py | d058be242ff22f73ff39c977d1be6826c3bbcacb | [] | no_license | robert-huang/stat441-project-quickdraw-classification | 7191b48e5250b15a451475e732e0cd3d2debd6d3 | ee80926f55e7904ab1a1390bec9db9308cc86cfe | refs/heads/master | 2022-12-02T04:41:37.454068 | 2020-08-15T06:35:44 | 2020-08-15T06:35:44 | 287,683,357 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,627 | py | import torch
from torch import nn
from torch import autograd
class ResNet(nn.Module):
def __init__(self, num_stages=4, blocks_per_stage=4, block_size=2,
fc_size=512, init_num_filters=32, img_dim=28, num_classes=10):
super().__init__()
kernel_sizes = [11, 5, 3]
def consume_kernel_size():
nonlocal kernel_sizes
kernel_size = kernel_sizes[0]
if len(kernel_sizes) > 1:
del kernel_sizes[0]
return kernel_size
paddings = [5, 2, 1]
def consume_padding():
nonlocal paddings
padding = paddings[0]
if len(paddings) > 1:
del paddings[0]
return padding
curr_num_filters = init_num_filters
self.initial = nn.ModuleList()
self.initial.append(nn.Conv2d(
in_channels = 1,
out_channels = curr_num_filters,
kernel_size = consume_kernel_size(),
padding = consume_padding()))
prev_num_filters = curr_num_filters
curr_filter_size = img_dim
self.blocks = nn.ModuleList()
self.relu = nn.ReLU()
self.maxpool = nn.MaxPool2d(2)
self.projections = nn.ModuleList()
for _ in range(num_stages):
for _ in range(blocks_per_stage):
block_modules = []
for _ in range(block_size):
if curr_num_filters == prev_num_filters:
stride = 1
else:
stride = 2
curr_filter_size = (curr_filter_size+1) // 2
block_modules.append(nn.Conv2d(
in_channels = prev_num_filters,
out_channels = curr_num_filters,
kernel_size = consume_kernel_size(),
padding = consume_padding(),
stride = stride))
block_modules.append(nn.BatchNorm2d(curr_num_filters))
prev_num_filters = curr_num_filters
self.blocks.append(nn.Sequential(*block_modules))
curr_num_filters = curr_num_filters * 2
next_filter_size = (curr_filter_size+1) // 2
self.projections.append(nn.Linear(
prev_num_filters * curr_filter_size * curr_filter_size,
curr_num_filters * next_filter_size * next_filter_size))
self.avg_pool = nn.AvgPool2d(kernel_size = curr_filter_size)
self.fc = nn.ModuleList()
self.fc.append(nn.Linear(prev_num_filters, fc_size))
self.fc.append(nn.ReLU())
self.fc.append(nn.Linear(fc_size, num_classes))
def forward(self, X):
batch_size = len(X)
curr = X
for m in self.initial:
curr = m(curr)
past_input = curr
curr_proj = 0
for m in self.blocks:
curr = m(curr)
past_channels = past_input.shape[1]
if curr.shape[1] == past_channels:
curr += past_input
else:
past_input = past_input.view(batch_size, -1)
past_input = self.projections[curr_proj](past_input)
past_input = past_input.view(curr.shape)
curr += past_input
curr_proj += 1
curr = self.relu(curr)
past_input = curr
curr = self.avg_pool(curr)
curr = curr.view(batch_size, -1) # remove 1x1 filter size
for m in self.fc:
curr = m(curr)
return curr
| [
"robert054321@hotmail.com"
] | robert054321@hotmail.com |
c89f26e98a6adf9060a8e28bdaa0c0c2e2e8c5a2 | dcc386509491b843c7ca264b96cdb08ec91d1f93 | /3_variables_and_memory/garbage_collection.py | a5ae5388057eb480e35d13b2361f8f826c8bab9c | [] | no_license | RuddleTime/python3_deep_dive1_udemy | 669d876b1da60a905cdea1d369979c3899e46c0f | 8acff41dfbc2dc334892e62084509dda79a7b17b | refs/heads/master | 2020-06-18T10:54:11.831239 | 2019-07-26T22:32:03 | 2019-07-26T22:32:03 | 196,278,052 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,930 | py | import ctypes
import gc # garbage collection module
def ref_count(address):
return ctypes.c_long.from_address(address).value
def object_by_id(object_id):
# Go through every object in the garbage collector
for obj in gc.get_objects():
if id(obj) == object_id:
return "Object exists in gc"
return "Not found"
a = [1, 2, 3]
z = 'random'
ref_count(id(a))
print(object_by_id(id(a)))
print(object_by_id(id(z)))
# Creating two classes to create a circular reference
class A:
def __init__(self):
self.b = B(self)
# When the class instantiates itself, the memory
# addresses of the instance of A and instance of B
print('A: self: {0}, b: {1}'.format(
hex(id(self)), hex(id(self.b)))
)
class B:
def __init__(self, a):
self.a = a
# Printing internal variable a below
print('B: self: {0}, a: {1}'.format(
hex(id(self)), hex(id(self.a)))
)
# XXX disabling garbage collector
gc.disable()
my_var = A()
print('Memory address of \'my_var\'.b: {0}'.format(hex(id(my_var.b))))
print('Memory address of \'my_var\'.b.a: {0}'.format(hex(id(my_var.b.a))))
a_id = id(my_var)
b_id = id(my_var.b)
print("Ref count for a_id: {0}".format(ref_count(a_id)))
print("Ref count for b_id: {0}".format(ref_count(b_id)))
print(object_by_id(a_id))
print(object_by_id(b_id))
my_var = None
print("*****************Setting \'a\' to None*****************")
print("Ref count for a_id: {0}".format(ref_count(a_id)))
print("Ref count for b_id: {0}".format(ref_count(b_id)))
print(object_by_id(a_id))
print(object_by_id(b_id))
# Running garbage collector manually
gc.collect()
print("*****************Running gc manually *****************")
print("Ref count for a_id: {0}".format(ref_count(a_id)))
print("Ref count for b_id: {0}".format(ref_count(b_id)))
print(object_by_id(a_id))
print(object_by_id(b_id))
| [
"ruddlec@tcd.ie"
] | ruddlec@tcd.ie |
18a2999613176a92592cf6e5e50bea83d2cfe61a | 8caee92caccb21668129b3dd7545d7f6db5da383 | /exploring/find_ms_id_by_label.py | ef0a8e19e53dcf60744adb5060e07db649818b37 | [] | no_license | OlivierValette/fibot | c097974bf42df01ee1ccb5f8d4c1bf0cadbcefb0 | 501306ddc8acb8a59a0f70a58267456515c52a14 | refs/heads/master | 2020-04-21T13:26:06.808314 | 2019-06-04T14:03:18 | 2019-06-04T14:03:18 | 169,598,212 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,163 | py | import requests
from bs4 import BeautifulSoup
# TODO: parameter to be stored in the database
MS_SEARCH_URL = "http://www.morningstar.fr/fr/funds/SecuritySearchResults.aspx?search="
# Search for an asset's Morningstar ID
def find_ms_id_by_label(label):
target = MS_SEARCH_URL + label
# fetch url
pageresponse = requests.get(target, timeout=5)
if pageresponse.status_code == 200:
pagecontent = BeautifulSoup(pageresponse.content, "html.parser")
# seek for <a href="/fr/funds/snapshot/snapshot.aspx?id=F00000MNJW">Comgest Monde I</a>
# under a <td class="msDataText searchLink">
results = []
for link in pagecontent.find_all("td", "searchLink"):
results.append(link.children.__next__().get('href')[-10:])
results.append(link.children.__next__().get_text())
for link in pagecontent.find_all("td", "searchIsin"):
results.append(link.children.__next__().get_text())
return results
else:
print("Le code saisi ne correspond à aucun fonds référencé par Morningstar")
return -1
msid = find_ms_id_by_label("Comgest Monde")
print(msid)
| [
"olivier.valette@spi10.com"
] | olivier.valette@spi10.com |
d0e654a18ca12052dea42d78b42a73852453c9ec | 07cf39100198fbd18a78afa99054f1bf6b19ad47 | /signac/synced_collections/validators.py | 910c2474040f70c566527948a75f58541f2cfbf5 | [
"BSD-3-Clause"
] | permissive | jennyfothergill/signac | 3e603526722611ccf31bda48dcd963e4c923ea90 | f506f720095aac6f91cc9086c1adde5d8acbdacc | refs/heads/master | 2023-03-06T17:58:25.594670 | 2021-06-14T11:21:40 | 2021-06-14T11:21:40 | 214,242,631 | 0 | 0 | BSD-3-Clause | 2023-03-01T00:57:30 | 2019-10-10T17:18:48 | Python | UTF-8 | Python | false | false | 4,676 | py | # Copyright (c) 2020 The Regents of the University of Michigan
# All rights reserved.
# This software is licensed under the BSD 3-Clause License.
"""Validators for SyncedCollection API.
A validator is any callable that raises Exceptions when called with invalid data.
Validators should act recursively for nested data structures and should not
return any values, only raise errors. This module implements built-in validators,
but client code is free to implement and add additioal validators to collection
types as needed.
"""
from collections.abc import Mapping, Sequence
from .errors import InvalidKeyError, KeyTypeError
from .numpy_utils import (
_is_atleast_1d_numpy_array,
_is_complex,
_is_numpy_scalar,
_numpy_cache_blocklist,
)
from .utils import AbstractTypeResolver
_no_dot_in_key_type_resolver = AbstractTypeResolver(
{
"MAPPING": lambda obj: isinstance(obj, Mapping),
"SEQUENCE": lambda obj: isinstance(obj, Sequence) and not isinstance(obj, str),
}
)
def no_dot_in_key(data):
"""Raise an exception if there is a dot (``.``) in a mapping's key.
Parameters
----------
data
Data to validate.
Raises
------
KeyTypeError
If key data type is not supported.
InvalidKeyError
If the key contains invalid characters or is otherwise malformed.
"""
VALID_KEY_TYPES = (str, int, bool, type(None))
switch_type = _no_dot_in_key_type_resolver.get_type(data)
if switch_type == "MAPPING":
for key, value in data.items():
if isinstance(key, str):
if "." in key:
raise InvalidKeyError(
f"Mapping keys may not contain dots ('.'): {key}"
)
# TODO: Make it an error to have a non-str key here in signac 2.0.
elif not isinstance(key, VALID_KEY_TYPES):
raise KeyTypeError(
f"Mapping keys must be str, int, bool or None, not {type(key).__name__}"
)
no_dot_in_key(value)
elif switch_type == "SEQUENCE":
for value in data:
no_dot_in_key(value)
def require_string_key(data):
"""Raise an exception if key in a mapping is not a string.
Almost all supported backends require string keys.
Parameters
----------
data
Data to validate.
Raises
------
KeyTypeError
If key type is not a string.
"""
# Reuse the type resolver here since it has the same groupings.
switch_type = _no_dot_in_key_type_resolver.get_type(data)
if switch_type == "MAPPING":
for key, value in data.items():
if not isinstance(key, str):
raise KeyTypeError(
f"Mapping keys must be str, not {type(key).__name__}"
)
require_string_key(value)
elif switch_type == "NON_STR_SEQUENCE":
for value in data:
require_string_key(value)
_json_format_validator_type_resolver = AbstractTypeResolver(
{
# We identify >0d numpy arrays as sequences for validation purposes.
"SEQUENCE": lambda obj: (isinstance(obj, Sequence) and not isinstance(obj, str))
or _is_atleast_1d_numpy_array(obj),
"NUMPY": lambda obj: _is_numpy_scalar(obj),
"BASE": lambda obj: isinstance(obj, (str, int, float, bool, type(None))),
"MAPPING": lambda obj: isinstance(obj, Mapping),
},
cache_blocklist=_numpy_cache_blocklist,
)
def json_format_validator(data):
"""Validate input data can be serialized to JSON.
Parameters
----------
data
Data to validate.
Raises
------
KeyTypeError
If key data type is not supported.
TypeError
If the data type of ``data`` is not supported.
"""
switch_type = _json_format_validator_type_resolver.get_type(data)
if switch_type == "BASE":
return
elif switch_type == "MAPPING":
for key, value in data.items():
if not isinstance(key, str):
raise KeyTypeError(f"Keys must be str, not {type(key).__name__}")
json_format_validator(value)
elif switch_type == "SEQUENCE":
for value in data:
json_format_validator(value)
elif switch_type == "NUMPY":
if _is_numpy_scalar(data.item()):
raise TypeError("NumPy extended precision types are not JSON serializable.")
elif _is_complex(data):
raise TypeError("Complex numbers are not JSON serializable.")
else:
raise TypeError(
f"Object of type {type(data).__name__} is not JSON serializable"
)
| [
"noreply@github.com"
] | noreply@github.com |
f7b7f9b07e860a94ff88ebb5c890928fd62d151a | fe7edf8a87c51d15f9b13e9a3a2bf165daa1de33 | /cacert.py | ad29a5d683894bf2870ca903dbddfc8ce0966cbc | [] | no_license | artizzle/pimail | f404cc0906d198d31ebef617336b2a9d3dde6bbe | 5957870a6e1a17a5218181d54d7421f1f3d27b38 | refs/heads/master | 2021-06-10T18:26:50.985165 | 2016-11-10T23:36:06 | 2016-11-10T23:36:06 | 73,429,215 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 9,297 | py | import subprocess
import fileinput
def cacert():
"""Get a new certificate from CAcert.org."""
name = input("What's your name?\n")
#Generate a private key.
wait = input("Generate a private key. Press enter.")
subprocess.call(['openssl', 'genrsa', '-out', name+'private.key', '4096'])
#Generate a certificate signing request.
print("""
####################################################################################################################
On the next Screen answer the required fields.
Here is the information you will be asked for:
Country Name (use a two letter code e.g. CA)
State or Province Name (e.g. Alberta)
Locality Name (e.g. Calgary)
Organisational Name (e.g. Arta's Personal Website)
Organisational Unit Name (e.g. Website)
Common Name (your domain name - see note below - e.g. *.arta.space)
Email Address (the contact address for your administrator e.g. webmaster@arta.space)
Don't set a password - leave it blank when asked.
We will keep the key file private by setting appropriate permissions.
The common name is important here: most websites rewrite https:// to https://www. or vice versa.
If your website is available at https://yourdomain.com then you should use yourdomain.com as the common name;
if your website is at https://www.yourdomain.com then your common name should be www.yourdomain.com or *.yourdomain.com
(the wildcard will match any subdomain, meaning you can use the same cert for https://mail.yourdomain.com
and https://www.yourdomain.com, which is handy).
#########################################################################################################################
""")
wait = input("Generate a new certificate signing request (CSR) from your private key. Press enter.")
#Generate a new certificate signing request (CSR) from your private key.
subprocess.call(['openssl', 'req', '-new', '-key', name+'private.key', '-out', name+'CSR.csr'])
print("""
###############################################################
Open a new terminal on your machine and type the following to
install the CAcert root certificate.
cd ~
wget http://www.cacert.org/certs/root.txt
sudo cp root.txt /etc/ssl/certs/cacert-root.crt
c_rehash /etc/ssl/certs
################################################################
""")
wait = input("When ready hit enter")
#Add these aliases to recieve CAcert verification through email
with open("/etc/aliases", "w") as f:
f.write("# See man 5 aliases for format.")
f.write("\npostmaster: "+name)
f.write("\nwebmaster: "+name)
f.write("\nroot: "+name)
#Load the new aliases.
subprocess.call(['newaliases'])
#Reload Postfix.
subprocess.call(['service', 'postfix', 'reload'])
print("""
##########################################################################
After you have created your account on CAcert.org and logged in,
first navigate to Domains --> Add and add your new domain (eg arta.space)
and then after you have verified the ownership of your domain via email
navigate to "server certificates --> new".
Copy & paste the following Certificate Signing Request (CSR) into the box
and click submit.
##########################################################################
""")
wait = input("When ready hit enter.\n")
#Copy the content of the CSR
subprocess.call(['cat', name+'CSR.csr'])
wait = input("\nWhenever you have aquired your certificate content hit enter.\n")
#Copy the result to a CRT file
print("""
#############################################################################################
The result will be displayed on screen, and you will also be emailed the certificate.
Note: the BEGIN CERTIFICATE and END CERTIFICATE lines are part of the cert, so copy those too!
Copy the certificate content and paste them when presented with an open file. After pasting
use CTRL+X to save and exit.
##############################################################################################
""")
wait = input("When ready hit enter.")
#Save the crt to a file
subprocess.call(['nano', name+'CRT.crt')
#Move the files to the proper locations.
subprocess.call(['mv', name+'private.key', '/etc/ssl/private/{keyfile}private.key'.format(keyfile=name)])
subprocess.call(['mv', name+'CRT.crt', '/etc/ssl/certs/{crtfile}CRT.crt'.format(crtfile=name)])
#Set keyfile to be owned by root.
subprocess.call(['chown', 'root:root', '/etc/ssl/private/{keyfile}private.key'.format(keyfile=name)])
#Only the root user can read and modify the keyfile.
subprocess.call(['chmod', '600', '/etc/ssl/private/{keyfile}private.key'.format(keyfile=name)])
#Set crtfile to be owned by root.
subprocess.call(['chown', 'root:root', '/etc/ssl/certs/{crtfile}CRT.crt'.format(crtfile=name)])
#Set it to be readable by everyone, but only modified by root.
subprocess.call(['chmod', '644', '/etc/ssl/certs/{crtfile}CRT.crt'.format(crtfile=name)])
#Put the files in apache default-ssl
with open("/etc/apache2/sites-available/default-ssl.conf", "w") as f:
f.write("""
<IfModule mod_ssl.c>
NameVirtualHost *:443
#=============================== ANTI SPAM ================================
<VirtualHost *:443>
ServerName default.only
<Location />
Order allow,deny
Deny from all
</Location>
SSLEngine on
SSLCertificateFile /etc/ssl/certs/certfile.crt
SSLCertificateKeyFile /etc/ssl/private/keyfile.key
</VirtualHost>
#================================ WEBSITE ===================================
<VirtualHost *:443>
ServerAdmin webmaster@rajabi.ca
ServerName www.rajabi.ca
ServerAlias rajabi.ca
DocumentRoot /var/www/html/
<Directory /var/www/html/>
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order allow,deny
allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/ssl_access.log combined
SSLEngine on
SSLCertificateFile /etc/ssl/certs/certfile.crt
SSLCertificateKeyFile /etc/ssl/private/keyfile.key
<FilesMatch "\.(cgi|shtml|phtml|php)$">
SSLOptions +StdEnvVars
</FilesMatch>
<Directory /usr/lib/cgi-bin>
SSLOptions +StdEnvVars
</Directory>
BrowserMatch "MSIE [2-6]" \
nokeepalive ssl-unclean-shutdown \
downgrade-1.0 force-response-1.0
# MSIE 7 and newer should be able to use keepalive
BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown
</VirtualHost>
#============================= SECOND WEBSITE ================================
""")
#Replace certfile and keyfile in apache's default-ssl with the correct files.
with fileinput.FileInput('/etc/apache2/sites-available/default-ssl.conf', inplace=True, backup='.backup') as f:
for line in f:
print(line.replace('certfile.crt', name+'CRT.crt'), end='')
with fileinput.FileInput('/etc/apache2/sites-available/default-ssl.conf', inplace=True, backup='.backup') as f:
for line in f:
print(line.replace('keyfile.key', name+'private.key'), end='')
#Replace certfile and keyfile in Postfix's main.cf with the correct files.
with fileinput.FileInput('/etc/postfix/main.cf', inplace=True) as f:
for line in f:
print(line.replace('ssl-cert-snakeoil.pem', name+'CRT.crt'), end='')
with fileinput.FileInput('/etc/postfix/main.cf', inplace=True) as f:
for line in f:
print(line.replace('ssl-cert-snakeoil.key', name+'private.key'), end='')
#Replace certfile and keyfile in Dovecot's 10-ssl.conf with the correct files.
with fileinput.FileInput('/etc/dovecot/conf.d/10-ssl.conf', inplace=True) as f:
for line in f:
print(line.replace('/etc/dovecot/dovecot.pem', '/etc/ssl/certs/'+name+'CRT.crt'), end='')
with fileinput.FileInput('/etc/dovecot/conf.d/10-ssl.conf', inplace=True) as f:
for line in f:
print(line.replace('/etc/dovecot/private/dovecot.pem', '/etc/ssl/private/'+name+'private.key'), end='')
#Replace certfile and keyfile in Squirrelmail apache.conf with the correct files.
with fileinput.FileInput('/etc/squirrelmail/apache.conf', inplace=True) as f:
for line in f:
print(line.replace('ssl-cert-snakeoil.pem', name+'CRT.crt'), end='')
with fileinput.FileInput('/etc/squirrelmail/apache.conf', inplace=True) as f:
for line in f:
print(line.replace('ssl-cert-snakeoil.key', name+'private.key'), end='')
subprocess.call(['service', 'postfix', 'reload'])
subprocess.call(['service', 'dovecot', 'reload'])
subprocess.call(['service', 'apache2', 'reload'])
cacert()
| [
"noreply@github.com"
] | noreply@github.com |
6f9cd1e5b7498d442628bca6592c84f90f1d02c0 | 82f993631da2871933edf83f7648deb6c59fd7e4 | /w1/L1/12.py | 4e40656a6ec9bba93b7855da255ff4c9ddd100ee | [] | no_license | bobur554396/PPII2021Summer | 298f26ea0e74c199af7b57a5d40f65e20049ecdd | 7ef38fb4ad4f606940d2ba3daaa47cbd9ca8bcd2 | refs/heads/master | 2023-06-26T05:42:08.523345 | 2021-07-24T12:40:05 | 2021-07-24T12:40:05 | 380,511,125 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 369 | py | # line = input()
# print(len(line))
'''
4
4 10 -1 100
'''
n = int(input())
# [<returning iter val> for <iter> in <list> condition ]
numbers = [int(n) for n in input().split()]
print(numbers)
# nums = []
# for n in numbers:
# nums.append(int(n))
# print(nums)
s = 0
for i in numbers:
if i > 0:
s += i
# print(s)
print(sum([n for n in numbers if n > 0])) | [
"bobur.muhsimbaev@gmail.com"
] | bobur.muhsimbaev@gmail.com |
3902901ad6c2c5b863e4a15e058503566e01aac6 | 4a82bea4e903b35be80f8a8a9196a0193ee5769e | /test_arduino_serial.py | 745f7a16815ea20cb26cd64d36a6de7da0da94da | [] | no_license | yunzhongxicao/mmwave_radar | a3e56376678de6e4c6ee20c8f461f97c1bd2bd4b | 67f69bc6b1d860537f4a91b7f204abd52ef1a241 | refs/heads/master | 2023-04-03T10:56:56.955040 | 2021-03-29T02:13:17 | 2021-03-29T02:13:17 | 336,739,823 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 482 | py | """
@File :test_arduino_serial.py
@Author:dfc
@Date :2021/3/1220:25
@Desc :这里只是测试利用python进行串口通信可行性
"""
import serial
# 打开串口
serialPort = "COM6"
baudRate = 9600
ser = serial.Serial(serialPort, baudRate, timeout=0.5)
demo1 = b'0'
demo2 = b'1'
demo3 = b'2'
while 1:
c = input('请输入指令:')
c = int(c)
if c == 0:
ser.write(demo1)
if c == 1:
ser.write(demo2)
if c == 2:
ser.write(demo3)
| [
"yunzhongxicao@sjtu.edu.cn"
] | yunzhongxicao@sjtu.edu.cn |
a8f04dab50ef5c54b203ebdac62eb2fe2957caa3 | b9922a20ba706bbd1e74e99f76822e365fc4398a | /estrutura_de_repeticao/numero_impar.py | 0b3415a5657fb93d303143f09a2fb21e55d04b60 | [] | no_license | adelyalbuquerque/projetos_adely | 6a95a0064705fe7530616cd8833d17286ab82797 | d0d7bd23b5fac90165f6a12c1acb11263b7021fb | refs/heads/master | 2021-01-19T04:10:32.541863 | 2016-07-22T19:28:51 | 2016-07-22T19:28:51 | 63,546,926 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 181 | py | numero = input("Digite um numero inteiro: ")
while numero != 0:
if (numero % 1) != 0 and (numero % numero) != 0:
print("Primo")
else:
print("Nao eh primo")
| [
"adely.albuquerque@gmail.com"
] | adely.albuquerque@gmail.com |
198db17b001f33aab6e03aa2f14284c01d52a729 | 046b40b6b5640b1779f8d42d84531e0b92433242 | /user.py | cc3c572c1170b0295827af795020dbefa92940b4 | [] | no_license | hawksuperguru/python-waitercaller | 3ea5303e1f8b7b768a8efbcc068a0077166707ce | 976eac7818978b16124b7875e8b13be9264d88d2 | refs/heads/master | 2021-05-07T16:19:48.873640 | 2017-10-30T10:44:18 | 2017-10-30T10:44:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 275 | py | class User:
def __init__(self, email):
self.email = email
def get_id(self):
return self.email
def is_active(self):
return True
def is_anonymous(self):
return False
def is_authenticated(self):
return True | [
"falcon.laravguru@yandex.com"
] | falcon.laravguru@yandex.com |
baef0557dc2c63efaa59504149f8588fef1e4309 | fd174bf1ef86d5cbf33ed7ce174a55274b0e327b | /Rescue/recieve.py | 96ab418df43fbe8af6a8c70b8399e60237638a55 | [] | no_license | pachicourse/IidaLab2017 | 470fc7b011906d7e316c51d5bedce6fd5e512263 | e18fd495d4165a08a7de9af400cb2db9dba2d142 | refs/heads/master | 2021-01-25T06:44:33.982408 | 2018-01-24T08:47:45 | 2018-01-24T08:47:45 | 93,598,137 | 0 | 0 | null | 2018-01-21T11:44:48 | 2017-06-07T06:00:11 | HTML | UTF-8 | Python | false | false | 1,700 | py | # WANと接続されている端末用プログラム
from flask import Flask, render_template, request
from email.mime.text import MIMEText
import os
import requests
import json
import smtplib
import datetime
GMAIL_ADDRESS = os.environ.get('GMAIL_ADDRESS')
GMAIL_PASS = os.environ.get('GMAIL_PASS')
app = Flask(__name__)
@app.route('/rescue', methods=['POST'])
def posted_json():
if request.headers['Content-Type'] != 'application/json':
print(request.headers['Content-Type'])
return 'It is not json data.'
# print(request.json)
send_email_self(request.json, GMAIL_ADDRESS, GMAIL_PASS)
return 'OK'
def send_email_self(json, address, password):
jp='iso-2022-jp'
raw_msg = ''
for key in json:
raw_msg = raw_msg + '・' + key + '\n' + json[key] + '\n\n'
msg = MIMEText(raw_msg, 'plain', jp,)
fromaddr = address
toaddr = address
# Subject指定の時に使う
d = datetime.datetime.now()
date = d.strftime("%Y-%m-%d %H:%M")
msg['Subject'] = date + ' 救援要請'
msg['From'] = fromaddr
msg['To'] = toaddr
try:
# gmailを利用して送信
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login(address, password)
server.send_message(msg)
print('Successfully sent email')
server.close()
return 'Successfully sent email'
except Exception:
print('Error: unable to send email')
import traceback
traceback.print_exc()
return 'Error: unable to send email'
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=False, threaded=True)
| [
"ddds78199500825@gmail.com"
] | ddds78199500825@gmail.com |
a921eb511127c4a8abd19099fdc2c956713a1868 | bc62493ec74497a3ed4d3f20a2f284ed7c5c310e | /bot.py | 6dc1de2556ade9f6d2ef611cc05b7593e48e4e3e | [] | no_license | tnwaps/youtube_tg_bot | 34a2a4f8411f061f8ef694437a91e89d0a0b97ce | 68bce5a9988821c123f473b96a6799262fe5218a | refs/heads/master | 2022-11-08T02:30:31.387231 | 2020-06-13T08:37:52 | 2020-06-13T08:37:52 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,318 | py | from telegram import Update
from telegram.ext import CallbackContext
from telegram.ext import Updater
from selenium import webdriver
from telegram.ext import Filters
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from telegram.ext import MessageHandler
import time
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.action_chains import ActionChains
import requests
token = 'lololo'
driver = webdriver.Chrome()
def message_handler(update: Update, context: CallbackContext):
text = update.message.text
if 'youtube' in text or 'youtu.be' in text:
driver.get(text)
browser.switch_to.frame(browser.find_element_by_xpath('//iframe[starts-with(@src, "https://www.youtube.com/embed")]'))
WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.XPATH, '//button[@aria-label="Play"]'))).click()
if(text=='!'):
driver.get()
def main():
updater = Updater(
token = token,
use_context=True
)
updater.dispatcher.add_handler(MessageHandler(filters=Filters.all,callback=message_handler))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
| [
"abusaid.manap@gmail.com"
] | abusaid.manap@gmail.com |
f0fd806301f11b38e6d5b561fd94db8760f5f48a | 051ab476fe9e5076c999ec18b452248d30ae13dd | /conftest.py | fe2c0e9459c0e3a504f437ab19adf755897252a7 | [] | no_license | art161qa/final_project_stepic_QA | 075028d48a5e5954d8161da586c6ee5676e63ffa | f3e561cb548ccc00a337042ffea08af6633cf3b6 | refs/heads/master | 2022-12-21T01:50:01.251411 | 2020-09-25T15:47:34 | 2020-09-25T15:47:34 | 294,165,132 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,162 | py | import pytest
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
def pytest_addoption(parser):
parser.addoption('--browser_name', action='store', default='chrome', help='Choose browser')
parser.addoption('--language', action='store', default='en', help='Choose language')
@pytest.fixture(scope="function")
def browser(request):
browser_name = request.config.getoption("browser_name")
user_language = request.config.getoption("language")
if browser_name == 'chrome':
print("\nstart chrome browser")
options = Options()
options.add_experimental_option('prefs', {'intl.accept_languages': user_language})
browser = webdriver.Chrome(options=options)
browser.maximize_window()
elif browser_name == 'firefox':
print("\nstart firefox browser")
fp = webdriver.FirefoxProfile()
fp.set_preference("intl.accept_languages", user_language)
browser = webdriver.Firefox(firefox_profile=fp)
else:
raise pytest.UsageError("--browser_name should be chrome or firefox")
yield browser
print("\nquit browser..")
browser.quit()
| [
"massiveframe@gmail.com"
] | massiveframe@gmail.com |
cad96b87c39da0d07e675e341783273ea03f36a4 | 633e2347ae46bbbb3bb68533407a32777017596f | /hook/zmes_hook_helpers/__init__.py | 8025431701ffdb4bc25244ba1da39133aa836ae9 | [
"MIT"
] | permissive | nmeylan/zmeventnotification | 1366c9120b2c0050219f4dedf19cc98a7338a195 | 1ec30a342745f5221a49f05ba8da7d4eed5bce20 | refs/heads/master | 2022-11-29T16:39:25.235847 | 2020-07-24T13:18:54 | 2020-07-28T15:24:18 | 282,207,149 | 0 | 0 | null | 2020-07-24T11:52:44 | 2020-07-24T11:52:44 | null | UTF-8 | Python | false | false | 43 | py | __version__ = "5.15.7"
VERSION=__version__
| [
"pliablepixels@gmail.com"
] | pliablepixels@gmail.com |
39622383718672dada6c3f167d95412716c9fdcf | 0e9bb62e0d964fd9019b5e03d624a0990901d554 | /misc/Final_Merge/merge_method.py | 99413132862c38c4ff1519e56ec6d8c73b2d822a | [] | no_license | faramarzmunshi/app_classification | d99c4d85b25870d966fccd6e837a45baa14111fc | 81161bf808ff505a9ef2d8221d05f6fff6b8e15f | refs/heads/master | 2021-08-28T08:21:27.277145 | 2017-12-11T17:40:25 | 2017-12-11T17:40:25 | 113,754,780 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 21,830 | py | # ************************************************ Import Libraries ****************************************************
import numpy as np
import random
np.random.seed(813306)
from pprint import pprint
from keras.models import Model
from keras.layers import Input, Dense, Dropout
from keras.utils import np_utils
import numpy as np
import pickle
import keras
from keras import backend as K
from keras.callbacks import ReduceLROnPlateau
from sklearn.decomposition import PCA
import pandas as pd
NUM_EPOCHS = 1000
# **************************************************** Functions *******************************************************
def precision(y_true, y_pred):
"""Precision metric.
-
- Only computes a batch-wise average of precision.
-
- Computes the precision, a metric for multi-label classification of
- how many selected items are relevant.
- """
true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))
precision = true_positives / (predicted_positives + K.epsilon())
return precision
def recall(y_true, y_pred):
"""Recall metric.
-
- Only computes a batch-wise average of recall.
-
- Computes the recall, a metric for multi-label classification of
- how many relevant items are selected.
- """
true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))
recall = true_positives / (possible_positives + K.epsilon())
return recall
def fbeta_score(y_true, y_pred, beta=1):
"""Computes the F score.
-
- The F score is the weighted harmonic mean of precision and recall.
- Here it is only computed as a batch-wise average, not globally.
-
- This is useful for multi-label classification, where input samples can be
- classified as sets of labels. By only using accuracy (precision) a model
- would achieve a perfect score by simply assigning every class to every
- input. In order to avoid this, a metric should penalize incorrect class
- assignments as well (recall). The F-beta score (ranged from 0.0 to 1.0)
- computes this, as a weighted mean of the proportion of correct class
- assignments vs. the proportion of incorrect class assignments.
-
- With beta = 1, this is equivalent to a F-measure. With beta < 1, assigning
- correct classes becomes more important, and with beta > 1 the metric is
- instead weighted towards penalizing incorrect class assignments.
- """
if beta < 0:
raise ValueError('The lowest choosable beta is zero (only precision).')
# If there are no true positives, fix the F score at 0 like sklearn.
if K.sum(K.round(K.clip(y_true, 0, 1))) == 0:
return 0
p = precision(y_true, y_pred)
r = recall(y_true, y_pred)
bb = beta ** 2
fbeta_score = (1 + bb) * (p * r) / (bb * p + r + K.epsilon())
return fbeta_score
def _one_hot_encode(label_vector, total_num_labels):
"""
One hot encode a label vector.
:param label_vector: a vector of labels for each time series
:param total_num_labels: total number of labels
:return: one hot encoded version of labels of all time series
"""
out = np.zeros(shape=(len(label_vector), total_num_labels))
for i in range(len(label_vector)):
out[i, int(label_vector[i])] = 1
return out
def _optimization(dataset1, dataset2, nb_epochs=3000):
"""
First trains a model on dataset1, then predicts the labels for vectors in dataset2 using labels of dataset1
:param dataset1: A dictionary of certain format
:param dataset2: A dictionary of certain format
:return: Predicted labels for dataset2 using labels of dataset1
"""
x1_mean = dataset1['train'].mean()
x1_std = dataset1['train'].std()
x_train1 = (dataset1['train'] - x1_mean) / (x1_std)
y_train1 = dataset1['labels']['train']
Y_train1 = dataset1['hot_labels']['train']
x1_mean = dataset1['test'].mean()
x1_std = dataset1['test'].std()
x_test1 = (dataset1['test'] - x1_mean) / (x1_std)
y_test1 = dataset1['labels']['test']
Y_test1 = dataset1['hot_labels']['test']
x2_mean = dataset2['train'].mean()
x2_std = dataset2['train'].std()
x_train2 = (dataset2['train'] - x2_mean) / (x2_std)
x2_mean = dataset2['test'].mean()
x2_std = dataset2['test'].std()
x_test2 = (dataset2['test'] - x2_mean) / (x2_std)
x_model1 = Input(x_train1.shape[1:])
y_model1 = Dropout(0.1)(x_model1)
y_model1 = Dense(50, activation='relu')(x_model1)
y_model1 = Dropout(0.2)(y_model1)
y_model1 = Dense(50, activation='relu')(y_model1)
out_model1 = Dense(len(np.unique(y_train1)), activation='softmax')(y_model1)
model1 = Model(input=x_model1, output=out_model1)
optimizer = keras.optimizers.Adadelta()
model1.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy'])
reduce_lr = ReduceLROnPlateau(monitor='loss', factor=0.5, patience=200, min_lr=0.1)
hist = model1.fit(x_train1, Y_train1, batch_size=x_train1.shape[0], nb_epoch=nb_epochs, verbose=1,
validation_data=(x_test1, Y_test1), shuffle=True, callbacks=[reduce_lr])
dataset2_new_labels_train = []
for i in range(x_train2.shape[0]):
xTrain = x_train2[i,:].reshape((1,x_train2.shape[1]))
dataset2_new_labels_train.append(np.argmax(model1.predict(xTrain, batch_size=1)))
dataset2_new_labels_test = []
for i in range(x_test2.shape[0]):
xTest = x_test2[i,:].reshape((1,x_test2.shape[1]))
dataset2_new_labels_test.append(np.argmax(model1.predict(xTest, batch_size=1)))
# Print the testing results which has the l in range(x_train.shape[0]):
# for i in range(len(x_test1)):
# xTest = x_test1[i,:].reshape((1,2048))
# print((np.argmax(model.predict(xTest, batch_size=1)), y_test1[i]))
# log = pd.DataFrame(hist.history)
# print("saving results for 100 nodes" + _MODE + fname)
# log.to_json('accuracies/accuracy_100_' + _MODE + fname + '.json')
# with open('Text_Files/' + fname + '_results.txt', 'w') as text_file:
# text_file.write(fname + '<<<=====>>>' + str(max(log.val_acc.values)))
# assert 2==1
x_model1 = []
y_model1 = []
out_model1 = []
model1 = []
return dataset2_new_labels_train, dataset2_new_labels_test
def _load_obj(filename):
with open(filename) as f:
return pickle.load(f)
def _readucr(filename):
try:
data = np.loadtxt(filename, delimiter = ',')
Y = data[:,0]
X = data[:,1:]
except:
data = _load_obj(filename)
data = np.array([[d[0]]+d[1] for d in data])
Y = data[:,0]
X = data[:,1:]
return X, Y
def _ucr_to_dictionary(fname):
x_train, y_train = _readucr('/home/ubuntu/big_disk/GADF_images/' + fname + '_GADF_CNNOUT_' + 'TRAIN')
x_test, y_test = _readucr('/home/ubuntu/big_disk/GADF_images/' + fname + '_GADF_CNNOUT_' + 'TEST')
# x_train, y_train = _readucr(fname + '_GADF_CNNOUT_' + 'TRAIN')
# x_test, y_test = _readucr(fname + '_GADF_CNNOUT_' + 'TEST')
nb_classes = len(np.unique(y_test))
y_train = (y_train - y_train.min()) / (y_train.max() - y_train.min()) * (nb_classes - 1)
y_test = (y_test - y_test.min()) / (y_test.max() - y_test.min()) * (nb_classes - 1)
Y_train = np_utils.to_categorical(y_train, nb_classes)
Y_test = np_utils.to_categorical(y_test, nb_classes)
dictionary = {'labels':{}, 'hot_labels':{}}
dictionary['train'] = x_train
dictionary['test'] = x_test
dictionary['labels']['train'] = y_train
dictionary['labels']['test'] = y_test
dictionary['hot_labels']['train'] = Y_train
dictionary['hot_labels']['test'] = Y_test
return dictionary
def _merge_datasets(dataset1, dataset2):
"""
Merge two datasets to unify their labels
:param dataset1: A dataset of certain format @vtype: A dictionary
:param dataset2: A dataset of certain format @vtype: A dictionary
:return: A merged dataset with unified labels of the same format as inputs @vtype: A dictionary
"""
# Number of labels in dataset 1
_NUM_LABELS_D1 = len(np.unique(dataset1['labels']['train']))
# Number of labels in dataset 2
_NUM_LABELS_D2 = len(np.unique(dataset2['labels']['train']))
# Call the optimization function to train on the first dataset and predict on the second dataset
ds2_labels_using_ds1_train, ds2_labels_using_ds1_test = _optimization(dataset1, dataset2, nb_epochs=NUM_EPOCHS)
# Initialize the label counting matrix
label_counter = np.zeros(shape=(_NUM_LABELS_D2, _NUM_LABELS_D1))
# Fill the label counting matrix accordingly
for i in range(len(ds2_labels_using_ds1_train)):
label_counter[int(dataset2['labels']['train'][i]), int(ds2_labels_using_ds1_train[i])] += 1
for i in range(len(ds2_labels_using_ds1_test)):
label_counter[int(dataset2['labels']['test'][i]), int(ds2_labels_using_ds1_test[i])] += 1
Matrix1 = np.matrix.copy(label_counter)
# Initialize the new set of labels for dataset 2
ds2_new_labels_train = np.zeros(shape=(len(ds2_labels_using_ds1_train), 2))
ds2_new_labels_test = np.zeros(shape=(len(ds2_labels_using_ds1_test), 2))
# Determine the new labels for dataset 2
for i in range(len(ds2_labels_using_ds1_train)):
if dataset2['labels']['train'][i] == np.argmax(label_counter[:, int(ds2_labels_using_ds1_train[i])]):
ds2_new_labels_train[i, :] = np.array([ds2_labels_using_ds1_train[i], dataset2['labels']['train'][i]])
else:
ds2_new_labels_train[i, :] = np.array([ds2_labels_using_ds1_train[i], -1])
# Determine the new labels for dataset 2
for i in range(len(ds2_labels_using_ds1_test)):
if dataset2['labels']['test'][i] == np.argmax(label_counter[:, int(ds2_labels_using_ds1_test[i])]):
ds2_new_labels_test[i, :] = np.array([ds2_labels_using_ds1_test[i], dataset2['labels']['test'][i]])
else:
ds2_new_labels_test[i, :] = np.array([ds2_labels_using_ds1_test[i], -1])
# Call the optimization function to train on the second dataset and predict on the first dataset
ds1_labels_using_ds2_train, ds1_labels_using_ds2_test = _optimization(dataset2, dataset1, nb_epochs=NUM_EPOCHS)
# Initialize the label counting matrix
label_counter = np.zeros(shape=(_NUM_LABELS_D1, _NUM_LABELS_D2))
# Fill the label counting matrix accordingly
for i in range(len(ds1_labels_using_ds2_train)):
label_counter[int(dataset1['labels']['train'][i]), int(ds1_labels_using_ds2_train[i])] += 1
for i in range(len(ds1_labels_using_ds2_test)):
label_counter[int(dataset1['labels']['test'][i]), int(ds1_labels_using_ds2_test[i])] += 1
Matrix2 = np.matrix.copy(label_counter.T)
# Initialize the new set of labels for dataset 1
ds1_new_labels_train = np.zeros(shape=(len(ds1_labels_using_ds2_train), 2))
ds1_new_labels_test = np.zeros(shape=(len(ds1_labels_using_ds2_test), 2))
# Determine the new labels for dataset 1
for i in range(len(ds1_labels_using_ds2_train)):
if ds1_labels_using_ds2_train[i] == np.argmax(label_counter[int(dataset1['labels']['train'][i]), :]):
ds1_new_labels_train[i, :] = np.array([dataset1['labels']['train'][i], ds1_labels_using_ds2_train[i]])
else:
ds1_new_labels_train[i, :] = np.array([dataset1['labels']['train'][i], -1])
# Determine the new labels for dataset 1
for i in range(len(ds1_labels_using_ds2_test)):
if ds1_labels_using_ds2_test[i] == np.argmax(label_counter[int(dataset1['labels']['test'][i]), :]):
ds1_new_labels_test[i, :] = np.array([dataset1['labels']['test'][i], ds1_labels_using_ds2_test[i]])
else:
ds1_new_labels_test[i, :] = np.array([dataset1['labels']['test'][i], -1])
# Concatenate all labels from both datasets
all_labels = np.concatenate((ds1_new_labels_train, ds2_new_labels_train,
ds1_new_labels_test, ds2_new_labels_test), axis=0)
# Transform the tuple labels to scalar labels
already_explored_rows = []
label = 0
vector_label = np.zeros(shape=(all_labels.shape[0], 1))
for i in range(all_labels.shape[0]):
if np.where((all_labels == all_labels[i, :]).all(axis=1))[0][0] not in already_explored_rows:
rows = np.where((all_labels == all_labels[i, :]).all(axis=1))[0]
vector_label[rows] = label
label += 1
print all_labels[i,:]
print 'label = {0}'.format(label)
for j in range(len(rows)):
already_explored_rows.append(rows[j])
vector_label = np.squeeze(vector_label)
# One hot encoded version of the labels
hot_labels = _one_hot_encode(vector_label, len(set(vector_label)))
vector_label_train = vector_label[0:(ds1_new_labels_train.shape[0] + ds2_new_labels_train.shape[0])]
vector_label_test = vector_label[(ds1_new_labels_train.shape[0] + ds2_new_labels_train.shape[0]):]
hot_labels_train = hot_labels[0:(ds1_new_labels_train.shape[0] + ds2_new_labels_train.shape[0]),:]
hot_labels_test = hot_labels[(ds1_new_labels_train.shape[0] + ds2_new_labels_train.shape[0]):,:]
# # Concatenate all labels from both datasets
# all_labels_train = np.concatenate((ds1_new_labels_train, ds2_new_labels_train), axis=0)
#
# # Transform the tuple labels to scalar labels
# already_explored_rows = []
#
# label = 0
#
# vector_label_train = np.zeros(shape=(all_labels_train.shape[0], 1))
#
# for i in range(all_labels_train.shape[0]):
# if np.where((all_labels_train == all_labels_train[i, :]).all(axis=1))[0][0] not in already_explored_rows:
# rows = np.where((all_labels_train == all_labels_train[i, :]).all(axis=1))[0]
# vector_label_train[rows] = label
# label += 1
# for j in range(len(rows)):
# already_explored_rows.append(rows[j])
#
# vector_label_train = np.squeeze(vector_label_train)
#
# # One hot encoded version of the labels
# hot_labels_train = _one_hot_encode(vector_label_train, len(set(vector_label_train)))
#
# # Concatenate all labels from both datasets
# all_labels_test = np.concatenate((ds1_new_labels_test, ds2_new_labels_test), axis=0)
#
# # Transform the tuple labels to scalar labels
# already_explored_rows = []
#
# label = 0
#
# vector_label_test = np.zeros(shape=(all_labels_test.shape[0], 1))
#
# for i in range(all_labels_test.shape[0]):
# if np.where((all_labels_test == all_labels_test[i, :]).all(axis=1))[0][0] not in already_explored_rows:
# rows = np.where((all_labels_test == all_labels_test[i, :]).all(axis=1))[0]
# vector_label_test[rows] = label
# label += 1
# for j in range(len(rows)):
# already_explored_rows.append(rows[j])
#
# vector_label_test = np.squeeze(vector_label_test)
#
# # One hot encoded version of the labels
# hot_labels_test = _one_hot_encode(vector_label_test, len(set(vector_label_test)))
# Initialize the concatenated dataset
new_dataset = {'labels': {'train': vector_label_train, 'test': vector_label_test},
'hot_labels': {'train': hot_labels_train, 'test': hot_labels_test}}
# Fill the corresponding keys for the concatenated dataset
for key in dataset1.keys():
if (key != 'labels') and (key != 'hot_labels'):
new_dataset[key] = np.concatenate((dataset1[key], dataset2[key]), axis=0)
# Return the merged dataset as a dictionary
return new_dataset, Matrix1, Matrix2
# ************************************************* Merge two Datasets *************************************************
# dataset_list = ['Adiac', 'Beef', 'CBF', 'ChlorineConcentration', 'CinC_ECG_torso', 'Coffee', 'Cricket_X', 'Cricket_Y',
# 'Cricket_Z', 'DiatomSizeReduction', 'ECGFiveDays', 'FaceAll', 'FaceFour', 'FacesUCR', '50words', 'FISH',
# 'Gun_Point', 'Haptics', 'InlineSkate', 'ItalyPowerDemand', 'Lighting2', 'Lighting7', 'MALLAT',
# 'MedicalImages','MoteStrain', 'NonInvasiveFatalECG_Thorax1', 'NonInvasiveFatalECG_Thorax2', 'OliveOil',
# 'OSULeaf','SonyAIBORobotSurface', 'SonyAIBORobotSurfaceII', 'StarLightCurves', 'SwedishLeaf', 'Symbols',
# 'synthetic_control', 'Trace', 'TwoLeadECG', 'Two_Patterns', 'uWaveGestureLibrary_X',
# 'uWaveGestureLibrary_Y','uWaveGestureLibrary_Z', 'wafer', 'WordsSynonyms', 'yoga']
# flist = ['Cricket_X', 'Cricket_Y', 'Cricket_Z']
flist = ['SonyAIBORobotSurface', 'SonyAIBORobotSurfaceII']
# flist = ['SonyAIBORobotSurface', 'Cricket_X', 'Lighting7']
# flist = ['Lighting2','Lighting7']
# flist = ['FISH', 'Haptics', 'InlineSkate']
dataset = _ucr_to_dictionary(flist[0])
for num_fname in range(1,len(flist)):
dataset1 = _ucr_to_dictionary(flist[num_fname])
dataset, matrix1, matrix2 = _merge_datasets(dataset,dataset1)
x_train = dataset['train']
x_test = dataset['test']
y_train = dataset['labels']['train']
y_test = dataset['labels']['test']
Y_train = dataset['hot_labels']['train']
Y_test = dataset['hot_labels']['test']
# Number of time series with specific label for training data
label_index_train = {}
for i in range(len(np.unique(y_train))):
label_index_train[i] = np.sum(y_train == i)
# Number of time series with specific label for test data
label_index_test = {}
for i in range(len(np.unique(y_test))):
label_index_test[i] = np.sum(y_test == i)
print 'Number of time series per label in training data is = {0}'.format(label_index_train)
print 'Number of time series per label in test data is = {0}'.format(label_index_test)
print 'Number of time series in training data is = {0}'.format(x_train.shape[0])
print 'Number of time series in test data is = {0}'.format(x_test.shape[0])
print 'Number of labels before removal = {0}'.format(int(max(max(y_train),max(y_test))+1))
labels_to_remove = [1, 2]
remaining_rows_train = []
remaining_rows_test = []
for row in range(x_train.shape[0]):
if y_train[row] not in labels_to_remove:
remaining_rows_train.append(row)
x_train = x_train[remaining_rows_train,:]
y_train = y_train[remaining_rows_train]
for row in range(x_test.shape[0]):
if y_test[row] not in labels_to_remove:
remaining_rows_test.append(row)
x_test = x_test[remaining_rows_test,:]
y_test = y_test[remaining_rows_test]
y_train_copy = np.matrix.copy(y_train)
y_test_copy = np.matrix.copy(y_test)
for lbl in labels_to_remove:
for i in range(len(y_train)):
if y_train_copy[i] > lbl:
y_train[i] -= 1
for i in range(len(y_test)):
if y_test_copy[i] > lbl:
y_test[i] -= 1
num_labels = int(max(max(y_train),max(y_test))+1)
Y_train = _one_hot_encode(y_train, num_labels)
Y_test = _one_hot_encode(y_test, num_labels)
x_mean = x_train.mean()
x_std = x_train.std()
x_train = (x_train - x_mean) / (x_std)
x_mean = x_test.mean()
x_std = x_test.std()
x_test = (x_test - x_mean) / (x_std)
# ind = range(len(remaining_rows))
#
# random.shuffle(ind)
#
# NUM_TEST = int(x.shape[0]/7)
# x_test = x[ind[0:NUM_TEST],:]
# y_test = y[ind[0:NUM_TEST]]
# Y_test = Y[ind[0:NUM_TEST],:]
#
# x_train = x[ind[NUM_TEST:],:]
# y_train = y[ind[NUM_TEST:]]
# Y_train = Y[ind[NUM_TEST:],:]
print 'number of labels: ', num_labels
x_model = Input(x_train.shape[1:])
y_model = Dropout(0.1)(x_model)
y_model = Dense(50, activation='relu')(x_model)
y_model = Dropout(0.2)(y_model)
y_model = Dense(50, activation='relu')(y_model)
out_model = Dense(num_labels, activation='softmax')(y_model)
model = Model(input=x_model, output=out_model)
optimizer = keras.optimizers.Adadelta()
model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy'])
reduce_lr = ReduceLROnPlateau(monitor='loss', factor=0.5, patience=200, min_lr=0.1)
hist = model.fit(x_train, Y_train, batch_size=len(remaining_rows_train), nb_epoch=NUM_EPOCHS+1000, verbose=1,
validation_data=(x_test,Y_test), shuffle=True, callbacks=[reduce_lr])
print 'Matrix1 = {0}'.format(matrix1)
print 'Matrix2 = {0}'.format(matrix2)
print 'Number of time series after removing unnecessary labels in training data is = {0}'.format(x_train.shape[0])
print 'Number of time series after removing unnecessary labels in test data is = {0}'.format(x_test.shape[0])
print 'Number of labels is = {0}'.format(num_labels)
print 'Predicted labels vs True labels'
y_pred = []
for i in range(x_test.shape[0]):
xTest = x_test[i,:].reshape((1,2048))
print((np.argmax(model.predict(xTest, batch_size=1)),y_test[i]))
y_pred.append(int(np.argmax(model.predict(xTest, batch_size=1))))
accuracy_per_label = {}
y_pred = np.array(y_pred)
y_test = np.array(y_test)
for i in range(num_labels):
pred_label_loc = np.where(y_pred==i)[0]
actual_label_loc = np.where(y_test==i)[0]
accuracy_per_label[i] = 0
for j in pred_label_loc:
if j in actual_label_loc:
accuracy_per_label[i] += 1
if actual_label_loc.tolist():
accuracy_per_label[i] = (accuracy_per_label[i]*100.0/len(actual_label_loc), len(actual_label_loc))
if num_labels == 2:
y_test = y_test.tolist()
print 'Precision was {0}.'.format(precision(y_test,y_pred))
print 'Recall was {0}.'.format(recall(y_test,y_pred))
print 'F1 was {0}.'.format(fbeta_score(y_test,y_pred))
print 'Accuracy per label:'
pprint(accuracy_per_label)
print 'Flist = {0}'.format(flist)
| [
"faramarzmunshi@gmail.com"
] | faramarzmunshi@gmail.com |
e9ac73578b1341f9b3e00b0301d3a37672230a11 | ac7cab5a22fe8b73c03fb155028d19085d4b0f26 | /rango/models.py | 5bca5a21cdaeade75a0a20bb24baeffa8c2e6471 | [] | no_license | FullStackPeterPAN/tango_with_django_project | c0d5838b61cdf91489a7f5af0d504130ccf90212 | a7ac005bb7b9e01440770e68bc478b4f3559539b | refs/heads/master | 2022-11-01T21:34:18.128669 | 2018-03-18T10:13:09 | 2018-03-19T16:46:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,311 | py | from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.template.defaultfilters import slugify
from django.contrib.auth.models import User
import datetime
from django.db import models
from django.utils import timezone
class Category(models.Model):
name = models.CharField(max_length=128, unique=True)
views = models.IntegerField(default=0)
likes = models.IntegerField(default=0)
slug = models.SlugField(blank=True, unique=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Category, self).save(*args, **kwargs)
class Meta:
verbose_name_plural = 'Categories'
def __str__(self): # For Python 2, use __unicode__ too
return self.name
class Page(models.Model):
category = models.ForeignKey(Category)
title = models.CharField(max_length=128)
url = models.URLField()
views = models.IntegerField(default=0)
def __str__(self): # For Python 2, use __unicode__ too
return self.title
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date <= now
was_published_recently.admin_order_field = 'pub_date'
was_published_recently.boolean = True
was_published_recently.short_description = 'Published recently?'
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
class UserProfile(models.Model):
# This line is required. Links UserProfile to a User model instance.
user = models.OneToOneField(User)
# The additional attributes we wish to include.
website = models.URLField(blank=True)
picture = models.ImageField(upload_to='profile_images', blank=True)
# Override the __unicode__() method to return out something meaningful!
# Remember if you use Python 2.7.x, define __unicode__ too!
def __str__(self):
return self.user.username
| [
"2294163p@student.gla.ac.uk"
] | 2294163p@student.gla.ac.uk |
3cb9259d4f4214fc9346777f14b80e8f08b66957 | e34dfe70b30e584d8b1992377b1b4f8a08235824 | /cloudmesh/common/console.py | 7042af40082ed1d6fcf2d07ae6ca9ec0509d795b | [
"Python-2.0",
"Apache-2.0"
] | permissive | juaco77/cloudmesh-common | 09efd91310f1d6fc5d34f60f4c34e63e8c6fc9ae | 0bb330da363b8edb9e509a8138a3054978a8a390 | refs/heads/master | 2020-06-08T05:04:18.070674 | 2019-05-17T10:33:13 | 2019-05-17T10:33:13 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,233 | py | """
Printing messages in a console
"""
from __future__ import print_function
import textwrap
import traceback
import colorama
from colorama import Fore, Back, Style
colorama.init()
def indent(text, indent=2, width=128):
"""
indents the given text by the indent specified and wrapping to the given width
:param text: the text to print
:param indent: indent characters
:param width: the width of the text
:return:
"""
return "\n".join(
textwrap.wrap(text,
width=width,
initial_indent=" " * indent,
subsequent_indent=" " * indent))
class Console(object):
"""
A simple way to print in a console terminal in color. Instead of using
simply the print statement you can use special methods to indicate
warnings, errors, ok and regular messages.
Example Usage::
Console.warning("Warning")
Console.error("Error")
Console.info("Info")
Console.msg("msg")
Console.ok("Success")
One can switch the color mode off with::
Console.color = False
Console.error("Error")
The color will be switched on by default.
"""
color = True
debug = True
theme_color = {
'HEADER': Fore.MAGENTA,
'BLACK': Fore.BLACK,
'CYAN': Fore.CYAN,
'WHITE': Fore.WHITE,
'BLUE': Fore.BLUE,
'OKBLUE': Fore.BLUE,
'OKGREEN': Fore.GREEN,
'GREEN': Fore.GREEN,
'FAIL': Fore.RED,
'WARNING': Fore.MAGENTA,
'RED': Fore.RED,
'ENDC': '\033[0m',
'BOLD': "\033[1m",
}
theme_bw = {
'HEADER': '',
'BLACK': '',
'CYAN': '',
'WHITE': '',
'BLUE': '',
'OKBLUE': '',
'OKGREEN': '',
'GREEN': '',
'FAIL': '',
'WARNING': '',
'RED': '',
'ENDC': '',
'BOLD': "",
}
theme = theme_color
@classmethod
def set_debug(cls, on=True):
"""
sets debugging on or of
:param on: if on debugging is set
:return:
"""
cls.debug = on
@staticmethod
def set_theme(color=True):
"""
defines if the console messages are printed in color
:param color: if True its printed in color
:return:
"""
if color:
Console.theme = Console.theme_color
else:
Console.theme = Console.theme_bw
Console.color = color
@staticmethod
def get(name):
"""
returns the default theme for printing console messages
:param name: the name of the theme
:return:
"""
if name in Console.theme:
return Console.theme[name]
else:
return Console.theme['BLACK']
@staticmethod
def txt_msg(message, width=79):
"""
prints a message to the screen
:param message: the message to print
:param width: teh width of the line
:return:
"""
return textwrap.fill(message, width=width)
@staticmethod
def msg(*message):
"""
prints a message
:param message: the message to print
:return:
"""
str = " ".join(message)
print(str)
@classmethod
def error(cls, message, prefix=True, traceflag=False):
"""
prints an error message
:param message: the message
:param prefix: a prefix for the message
:param traceflag: if true the stack trace is retrieved and printed
:return:
"""
# print (message, prefix)
message = message or ""
if prefix:
text = "ERROR: "
else:
text = ""
if cls.color:
cls.cprint('FAIL', text, str(message))
else:
print(cls.txt_msg(text + str(message)))
if traceflag and cls.debug:
trace = traceback.format_exc().strip()
if trace:
print()
print("Trace:")
print("\n ".join(str(trace).splitlines()))
print()
@staticmethod
def TODO(message, prefix=True, traceflag=True):
"""
prints an TODO message
:param message: the message
:param prefix: if set to true it prints TODO: as prefix
:param traceflag: if true the stack trace is retrieved and printed
:return:
"""
message = message or ""
if prefix:
text = "TODO: "
else:
text = ""
if Console.color:
Console.cprint('FAIL', text, str(message))
else:
print(Console.msg(text + str(message)))
trace = traceback.format_exc().strip()
if traceflag and trace != "None":
print()
print("\n".join(str(trace).splitlines()))
print()
@staticmethod
def debug_msg(message):
"""
print a debug message
:param message: the message
:return:
"""
message = message or ""
if Console.color:
Console.cprint('RED', 'DEBUG: ', message)
else:
print(Console.msg('DEBUG: ' + message))
@staticmethod
def info(message):
"""
prints an informational message
:param message: the message
:return:
"""
message = message or ""
if Console.color:
Console.cprint('OKBLUE', "INFO: ", message)
else:
print(Console.msg("INFO: " + message))
@staticmethod
def warning(message):
"""
prints a warning
:param message: the message
:return:
"""
message = message or ""
if Console.color:
Console.cprint('WARNING', "WARNING: ", message)
else:
print(Console.msg("WARNING: " + message))
@staticmethod
def ok(message):
"""
prints an ok message
:param message: the message<
:return:
"""
message = message or ""
if Console.color:
Console.cprint('OKGREEN', "", message)
else:
print(Console.msg(message))
@staticmethod
def cprint(color, prefix, message):
"""
prints a message in a given color
:param color: the color as defined in the theme
:param prefix: the prefix (a string)
:param message: the message
:return:
"""
message = message or ""
prefix = prefix or ""
print((Console.theme[color] +
prefix +
message +
Console.theme['ENDC']))
#
# Example
#
if __name__ == "__main__":
print(Console.color)
print(Console.theme)
Console.warning("Warning")
Console.error("Error")
Console.info("Info")
Console.msg("msg")
Console.ok("Ok")
Console.color = False
print(Console.color)
Console.error("Error")
print(Fore.RED + 'some red text')
print(Back.GREEN + 'and with a green background')
print(Style.DIM + 'and in dim text')
print(Fore.RESET + Back.RESET + Style.RESET_ALL)
print('back to normal now')
| [
"laszewski@gmail.com"
] | laszewski@gmail.com |
26cadb013cdd14f5324e9d6d73ca1a8a0f3d8c8f | 4e008e556495839a15100262c39f35cbdbd25e65 | /v12 Condicionales III/practica_condicionales.py | f8d213b430199cb77c5b8ec395169b4d0a952d09 | [] | no_license | cmolinagithub/cursoPython | c2300c76570d653153e543cb02cc848be5ceb0fd | 3e47d787dd2be151281c22f5d8d4bdb04a11d76a | refs/heads/master | 2020-05-16T19:27:45.110116 | 2019-07-23T21:32:07 | 2019-07-23T21:32:07 | 183,261,813 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 221 | py | '''edad=7
if edad <100:
print("Edad es correcta")
else:
print("Edad incorrecta")
'''
##concatenacion de condiciones
#edad=-7
edad=145
if 0<edad<100:
print("edad es correta")
else:
print("edad incorrecta") | [
"cmolinabastidas@gmail.com"
] | cmolinabastidas@gmail.com |
275c145e3d67fab7b8eaa04044d410a9e813dbdd | a77f57098198d816b2fcc18fe12ade248d794a00 | /sim/simpheno.py | 264a3c30fa47de60585de9c2022ff3a809105ee6 | [] | no_license | huwenboshi/blabbertools | 60efea77fe9e46af993ca060cd25ea759db87fb6 | bef8187b3e8811e3d25d4b4ba4b7686f448b2a1d | refs/heads/master | 2020-12-07T13:31:46.292849 | 2014-10-08T02:36:16 | 2014-10-08T02:36:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,521 | py | #!/usr/bin/python
"""
python script to simulate phenotypes
input data: haplotypes, legend
output data: simulated phenotypes
author: huwenbo shi
"""
from optparse import OptionParser
import sys
import math
import os
import random
import numpy as np
# get command line
parser = OptionParser(add_help_option=False)
parser.add_option("-h", "--hap", dest="hapfile")
parser.add_option("-m", "--marker", dest="markerfile")
parser.add_option("-f", "--freqth", dest="freqth_str")
parser.add_option("-n", "--nsnps", dest="nsnps_str")
parser.add_option("-p", "--pint", dest="pint_str")
parser.add_option("-q", "--ncau", dest="ncau_str")
parser.add_option("-o", "--outprefix")
(options, args) = parser.parse_args()
hapfile_nm = options.hapfile
markerfile_nm = options.markerfile
freqth_str = options.freqth_str
nsnps_str = options.nsnps_str
pint_str = options.pint_str
ncau_str = options.ncau_str
outprefix = options.outprefix
# check command line
if(hapfile_nm == None or markerfile_nm == None or
freqth_str == None or nsnps_str == None or
pint_str == None or outprefix == None or
ncau_str == None):
sys.stderr.write("Usage:\n")
sys.stderr.write("\tUse -h to specify hap file\n")
sys.stderr.write("\tUse -m to specify marker file\n")
sys.stderr.write("\tUse -f to specify MAF threshold\n")
sys.stderr.write("\tUse -n to specify the number of SNPs\n")
sys.stderr.write("\tUse -p to specify the number of interactions\n")
sys.stderr.write("\tUse -o to specify output prefix\n")
sys.stderr.write("\tUse -q to specify number of causal SNPs\n")
sys.exit()
print '#################################\n'
print '** simulation started **'
print '\n#################################\n'
# parse numeric values
freqth = float(freqth_str)
nsnps = int(nsnps_str)
pint = int(pint_str)
ncau = int(ncau_str)
# constants - heritability
h2 = 0.2
h2_int = 0.02
korder = 2
# read in legend file
markers = []
flr = False
markerfile = open(markerfile_nm, 'r')
for line in markerfile:
if(flr == False):
flr = True
continue
line = line.strip()
markers.append(line)
markerfile.close()
# read in haplotype file
# each col of haps stores a haplotype
haps = []
hapfile = open(hapfile_nm, 'r')
for line in hapfile:
line = line.strip()
cols = line.split()
for i in xrange(len(cols)):
cols[i] = int(cols[i])
haps.append(cols)
hapfile.close()
haps = np.matrix(haps)
# convert haps to gens
nrow = haps.shape[0]
ncol = haps.shape[1]
gens = np.zeros((nrow, ncol/2))
for i in xrange(nrow):
for j in xrange(0, ncol, 2):
gens[i,j/2] = haps[i,j]+haps[i,j+1]
# obtain allele frequency
# filter out snps with maf less than freqth
sim_snps = []
sim_snps_idx = []
freqs = gens.mean(1)/2
nrow = freqs.shape[0]
for i in xrange(nrow):
if(len(sim_snps) >= nsnps):
break
if(freqs[i] > freqth and freqs[i] < 1-freqth):
sim_snps.append(markers[i])
sim_snps_idx.append(i)
# select the snps, haps, and freqs indexed in sim_snps_idx
# normalize snps
gens_norm = gens[sim_snps_idx,:]
gens = gens[sim_snps_idx,:]
haps = haps[sim_snps_idx,:]
freqs = freqs[sim_snps_idx]
nrow = gens_norm.shape[0]
ncol = gens_norm.shape[1]
for i in xrange(nrow):
for j in xrange(ncol):
var = 2*freqs[i]*(1-freqs[i])
gens_norm[i,j] = (gens_norm[i,j]-2*freqs[i])/math.sqrt(var)
print '** normalized all snps **'
print '-- mean of gi'
print gens_norm.mean(1)
print '-- var of gi'
print np.var(gens_norm)
print '\n#################################\n'
# draw single snps
pool_size = gens_norm.shape[0]
idx_pool = range(pool_size)
cau_idx = []
for i in xrange(ncau):
random.shuffle(idx_pool)
cau_idx.append(idx_pool[0])
del idx_pool[0]
print '** selected %d causal snps, %d interactions **' % (ncau, pint)
print '\n#################################\n'
# draw interaction snps
snp_idx_pairs = []
for i in xrange(pint):
idx_pair = [-1]*korder
for j in xrange(korder):
random.shuffle(idx_pool)
idx_pair[j] = idx_pool[0]
del idx_pool[0]
snp_idx_pairs.append(idx_pair)
# create interaction genotypes
nsnp = gens_norm.shape[0]
nind = gens_norm.shape[1]
nint = len(snp_idx_pairs)
gens_int = np.ones((nint, nind))
for i in xrange(nint):
for j in xrange(nind):
for k in xrange(korder):
gens_int[i,j] = gens_int[i,j]*gens[snp_idx_pairs[i][k],j]
# normalize interaction genotypes
gens_int_norm = gens_int
for i in xrange(nint):
idx0 = snp_idx_pairs[i][0]
idx1 = snp_idx_pairs[i][1]
gens0 = gens[idx0,:]
gens1 = gens[idx1,:]
mu0 = gens0.mean(0)
mu1 = gens1.mean(0)
cov01 = np.cov(gens0, gens1)[0,1]
gens0_sq = np.square(gens0)
gens1_sq = np.square(gens1)
mu0_sq = gens0_sq.mean(0)
mu1_sq = gens1_sq.mean(0)
cov01_sq = np.cov(gens0_sq, gens1_sq)[0,1]
mu = mu0*mu1+cov01
var = mu0_sq*mu1_sq+cov01_sq-mu*mu
for j in xrange(nind):
gens_int_norm[i,j] = (gens_int_norm[i,j]-mu)/math.sqrt(var)
print '** normalized all interactions **'
print '-- mean of gi*gj'
print gens_int_norm.mean(1)
print '-- var of gi*gj'
print np.var(gens_int_norm)
print '\n#################################\n'
# simulate phenotypes
# initialization
pheno = np.zeros((nind, 1))
if(ncau > 0):
betas = np.random.normal(0.0, math.sqrt(h2/ncau), ncau)
betas_int = np.random.normal(0.0, math.sqrt(h2_int/nint), nint)
# add single snp effect
gens_norm_cau = gens_norm[cau_idx,:]
for i in xrange(nind):
for j in xrange(ncau):
gen = gens_norm_cau[j,i]
b = betas[j]
pheno[i] = pheno[i]+b*gen
# add snp interaction effect
for i in xrange(nind):
for j in xrange(nint):
gen_int = gens_int_norm[j,i]
b_int = betas_int[j]
pheno[i] = pheno[i]+b_int*gen_int
# add environment effect
env_effect = np.random.normal(0.0, math.sqrt(1-h2-h2_int), (nind,1))
pheno = pheno+env_effect
print '** simulation ended **'
print '\n#################################\n'
# write out result
hapfile = open(outprefix+'.sim.hap', 'w')
nrow = haps.shape[0]
ncol = haps.shape[1]
for i in xrange(nrow):
line = ''
for j in xrange(ncol):
line += str(haps[i,j])+' '
hapfile.write(line+'\n')
hapfile.close()
snpfile = open(outprefix+'.sim.snp', 'w')
snpfile.write('snp_id pos x0 x1\n')
for m in markers:
snpfile.write(m+'\n')
snpfile.close()
phefile = open(outprefix+'.sim.phe', 'w')
nind = pheno.shape[0]
for i in xrange(nind):
phefile.write(str(pheno[i,0])+'\n')
phefile.close()
| [
"shihuwenboinus@gmail.com"
] | shihuwenboinus@gmail.com |
563dfccd2fd271a2ae0edc1613952e7947965a62 | 58afefdde86346760bea40690b1675c6639c8b84 | /leetcode/global-and-local-inversions/288943653.py | 0f1c892c5fa61990ec2ad92c40c0f4af8ae7abd2 | [] | no_license | ausaki/data_structures_and_algorithms | aaa563f713cbab3c34a9465039d52b853f95548e | 4f5f5124534bd4423356a5f5572b8a39b7828d80 | refs/heads/master | 2021-06-21T10:44:44.549601 | 2021-04-06T11:30:21 | 2021-04-06T11:30:21 | 201,942,771 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 712 | py | # title: global-and-local-inversions
# detail: https://leetcode.com/submissions/detail/288943653/
# datetime: Fri Dec 27 19:09:22 2019
# runtime: 388 ms
# memory: 13.4 MB
class Solution:
def isIdealPermutation(self, A: List[int]) -> bool:
N = len(A)
k = -1
i = 0
while i < N:
j = i + 1
while j < N and A[j] > A[j - 1]:
k = A[j - 1]
j += 1
if j == N:
break
i = j
if A[i] < k:
return False
if i + 1 < N and (A[i] > A[i + 1] or A[i + 1] < A[i - 1]):
return False
k = A[i - 1]
i += 1
return True | [
"ljm51689@gmail.com"
] | ljm51689@gmail.com |
037cd1bbb07e278e8e22db1424ee0da288599866 | b6d3a2cd9ced1e411f4d9a7815492c0070bf5691 | /Code/tunneler/PubSubAgent/Main.py | 62430f0a978c8896a1abb201aecb62e9b5d3215a | [] | no_license | FIU-SCIS-Senior-Projects/Addigy4 | b9241c90107da3a0f1cdf70ec83809183b2a09d6 | fc4f87f0097047d872cd9f775d98765b50c17257 | refs/heads/master | 2020-04-10T16:28:20.132129 | 2015-12-18T19:26:06 | 2015-12-18T19:26:09 | 41,682,638 | 2 | 1 | null | 2015-11-02T06:18:48 | 2015-08-31T15:12:40 | JavaScript | UTF-8 | Python | false | false | 8,454 | py | import shlex
import getpass
from threading import Thread
import webbrowser
__author__ = 'cruiz1391'
import json
import os, sys, traceback, subprocess
import pubsub
ChannelName = "DemoTest"
ServerAdd = 'addigy-dev.cis.fiu.edu'
ServerPort = 5672
PubSubId = "0c86c7ef-f579-4115-8137-289b8a257803"
connected = True
message = ""
usrnANDpassw = "test5"
queueName = "test5_mailbox"
routingKey = "testcorp"
client_running = None
tunnel_running = None
threads_running = []
###########################################################################################################
def terminateThreads():
global threads_running
while(threads_running.__len__() != 0):
thread = threads_running.pop()
thread._stop()
###########################################################################################################
def setClientRunning(_running_client):
global client_running
client_running = _running_client
###########################################################################################################
def setTunnelRunning(_running_tunnel):
global tunnel_running
tunnel_running = _running_tunnel
###########################################################################################################
def addThreadsRunning(_running_Thread):
global threads_running
threads_running.append(_running_Thread)
###########################################################################################################
def failedAction():
return False
###########################################################################################################
def startSSH(command):
os.system("gnome-terminal -e 'bash -c \"%s; exec bash\"'" % command)
###########################################################################################################
def startWEB(url):
webbrowser.open_new(url)
###########################################################################################################
def startVNC(port):
os.system("vncviewer localhost:"+port)
###########################################################################################################
def successAction(request):
target = request['target']
if target == 'client':
terminate = request['disconnect']
if(terminate == "true"):
terminateThreads()
return
connection = request['connection_type']
if(connection == "ssh"):
print("opening terminal!")
command = "ssh -v "+getpass.getuser()+"@localhost -p "+request['local_port']
tunnels_on_select = Thread(target=startSSH, args=[command])
tunnels_on_select.daemon = True
tunnels_on_select.start()
addThreadsRunning(tunnels_on_select)
elif(connection == "web"):
print("opening browser!")
url = "http://localhost:3000"
tunnels_on_select = Thread(target=startWEB, args=[url])
tunnels_on_select.daemon = True
tunnels_on_select.start()
addThreadsRunning(tunnels_on_select)
elif(connection == "vnc"):
print("opening vnc!")
port = request['local_port']
tunnels_on_select = Thread(target=startVNC, args=[port])
tunnels_on_select.daemon = True
tunnels_on_select.start()
addThreadsRunning(tunnels_on_select)
elif target == 'tunneler':
successResponse = request['messageToClient']
pubSubClient.publish(routing_key=routingKey, body=bytes(json.dumps(successResponse), 'utf-8'))
###########################################################################################################
def receiveMessages(channel, method_frame, header_frame, body):
try:
jsonMssg = json.loads(body.decode("utf-8") )
if(PubSubId in jsonMssg):
request = jsonMssg[PubSubId]
print("\nrequest received: " + str(request)+"\n")
if(executeCommand(request)):
print("success")
successAction(request)
else:
print("failed")
except ValueError as e:
# Sring is not a valid json format text
sys.stderr.write("Message not a valid Json: " + body.decode("utf-8")+"\n")
###########################################################################################################
def subscribeToChannel():
global pubSubClient
pubSubClient = pubsub.PubSub(addr=ServerAdd, username=usrnANDpassw, password=usrnANDpassw, organization=routingKey)
pubSubClient.create_queue(queue_name=queueName, auto_delete=True)
pubSubClient.subscribe(receiveMessages, queueName, no_ack=True)
###########################################################################################################
def startTunneler(tunnelId, path):
print("starting tunneler!")
command_line = "python " + path + " " + tunnelId
args = shlex.split(command_line)
if(not os.path.exists(path)):
message = "Tunnel path doesn't exist!"
return False
p = subprocess.Popen(args, stdout=subprocess.PIPE)
success = False
while True:
output = p.stdout.readline()
if output == '' and p.poll() is not None:
break
if output:
outputString = output.decode("utf-8")
if(outputString == "Tunnel created: "+tunnelId+"\n" or outputString == "Tunnel exist: " + tunnelId+"\n"):
success = True
print (outputString)
message = outputString
if success:
break
if(success):
setTunnelRunning(p)
return True
else:
return False
###########################################################################################################
def startClient(targetTunnel, localPort, destPort, path):
print("starting client")
command_line = "python " + path + " " + str(targetTunnel) + " " + str(localPort) + " " + str(destPort)
args = shlex.split(command_line)
if(not os.path.exists(path)):
message = "Client path doesn't exist!"
return False
p = subprocess.Popen(args, stdout=subprocess.PIPE)
success = False
while True:
output = p.stdout.readline()
if output == '' and p.poll() is not None:
break
if output:
outputString = output.decode("utf-8")
if(outputString == "Client created: "+targetTunnel+"\n" or outputString == "Client exist: " + targetTunnel+"\n"):
success = True
print (outputString)
message = outputString
if success:
break
if(success):
setClientRunning(p)
return True
else:
return False
###########################################################################################################
def executeTermination(target):
global client_running, tunnel_running
if(target == "client"):
if not client_running == None:
print("Terminating client")
client_running.terminate()
else:
if not tunnel_running == None:
print("Terminating tunneler")
tunnel_running.terminate()
###########################################################################################################
def executeCommand(request):
PATH = "/var/opt/"
target = request['target']
try:
if target == 'client':
terminate = request['disconnect']
if(terminate == "true"):
executeTermination("client")
return True
targetTunnel = request['tunnel_id']
local_port = int(request['local_port'])
tunnelport = request['tunnel_port']
return startClient(targetTunnel, local_port, tunnelport, PATH+"client/Main.py")
elif target == 'tunneler':
terminate = request['disconnect']
if(terminate == "true"):
executeTermination("tunneler")
return True
tunnelId = request['tunnel_id']
return startTunneler(tunnelId, PATH+"tunneler/Main.py")
except FileNotFoundError as error:
sys.stderr.write(str(error))
traceback.print_exc()
return False
###########################################################################################################
if __name__ == '__main__':
subscribeToChannel()
| [
"cruiz1391@gmail.com"
] | cruiz1391@gmail.com |
6be597b3f45df0dfaa61db71a171b3239f97b0a9 | cb309ee241803ff4b87a05c579060027d953d71c | /collector/models.py | 7ac275247bcbec5f3bba88f4c245910d46af74fb | [] | no_license | bio-it/ImpedanceServer | 7c549cd946e8afa96b007c4e2e17d8db8ca2ac65 | a165c1dedaf93d3ce9883afd8123faf28491ea95 | refs/heads/master | 2021-02-09T17:35:45.517861 | 2020-03-03T06:27:31 | 2020-03-03T06:27:31 | 244,308,076 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,122 | py | from __future__ import unicode_literals
from django.db import models
# Model for dwf
class DwfResultData(models.Model):
dataCounter = models.IntegerField(primary_key=True, default=0)
startTime = models.DateTimeField(blank=True, null=True)
targetTime = models.DateTimeField(blank=True, null=True)
period = models.IntegerField(null=False, default=1)
freqs = models.TextField(null=False, default='')
channels = models.TextField(null=False, default='')
class DwfMeasureData(models.Model):
id = models.AutoField(primary_key=True)
dataCounter = models.IntegerField(null=False, default=0)
Z = models.FloatField(null=False, default=0.0)
R = models.FloatField(null=False, default=0.0)
C = models.FloatField(null=False, default=0.0)
freq = models.IntegerField(null=False, default=0)
channel = models.IntegerField(null=False, default='')
time = models.DateTimeField(blank=True, null=True)
timeMin = models.IntegerField(null=False, default=0)
class Parameter(models.Model):
id = models.AutoField(primary_key=True)
key = models.TextField(null=False, default="")
value = models.TextField(null=False, default="")
| [
"mauver@naver.com"
] | mauver@naver.com |
d0b687546ac4f7f9e863239bf7175a5f4728cf41 | ed2524c630a6991e6e8fa000216fbbd1d86a9aeb | /sum/urls.py | d9be7e088defea6f539a0cf3e91dc15d08cc50ed | [] | no_license | Subhramohanty/postman | e1435c6ed7c2034bccfbd93e1a4212f7cf148596 | 5bbb927222964960698c140f30d837e0fd06db47 | refs/heads/main | 2023-02-07T02:47:11.826908 | 2020-12-29T12:15:34 | 2020-12-29T12:15:34 | 325,278,052 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,002 | py | """sum URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from sumapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('api/',views.UserList.as_view()),
path('order/',views.OrderList.as_view(),name='order'),
path('category/',views.OrderList.as_view(),name='category'),
path('product/',views.ProductList.as_view(),name='product'),
]
| [
"subhramohanty008@gmail.com"
] | subhramohanty008@gmail.com |
bc588af7165c518b2b39df077d944a19465b635e | b2a312acad1062ed7e35eaedc90eede1b6aee7f0 | /pyramid_admin2/views/model_view.py | 731b9b440c694a46da5d0d338b2df519f9526883 | [] | no_license | tarzanjw/pyramid_admin2 | 93060ca0697359c956a525ea12f1951d1e94e849 | 479d0df566bd0577c485695c6940415d644f3ee2 | refs/heads/master | 2016-08-04T18:49:52.497474 | 2014-10-14T05:02:43 | 2014-10-14T05:02:43 | 24,974,500 | 1 | 0 | null | 2014-10-14T04:59:52 | 2014-10-09T05:08:57 | Python | UTF-8 | Python | false | false | 8,012 | py | __author__ = 'tarzan'
import six
if six.PY2:
from urllib import urlencode
else:
from urllib.parse import urlencode
import inspect
import deform
from pyramid.httpexceptions import HTTPFound
from pyramid.view import view_config
from ..helpers import cell_datatype
from .. import resources as _rsr, admin_manager
import colander
from pyramid.traversal import lineage
def _none_to_colander_null(data):
return {k: v if v is not None else colander.null for k, v in data.items()}
def _colander_null_to_none(data):
return {k: v if v is not colander.null else None for k, v in data.items()}
class InvalidSchemaClassError(RuntimeError):
def __init__(self, admin_mgr):
"""
:type admin_mgr: pyramid_admin2.admin_manager.AdminManager
"""
self.admin_mgr = admin_mgr
super(InvalidSchemaClassError, self).__init__('%s is not class for %s\'s schema'
% (self.admin_mgr.schema_cls,
self.admin_mgr.model))
@view_config(context=InvalidSchemaClassError, renderer='pyramid_admin2:templates/no_schema.mak')
def on_invalid_schema_class(context, request):
return {
'error': context,
}
class ModelView(object):
def __init__(self, context, request):
"""
:type context: pyramid_admin2.resources.ModelResource
:type request: pyramid.request.Request
"""
self.context = context
self.request = request
@property
def model(self):
return self.context.model
@property
def criteria(self):
"""
:rtype: pyramid_admin2.admin_manager.BrowseCriteria
"""
return self.admin_mgr.create_criteria(self.request)
@property
def is_current_context_object(self):
"""
:rtype : bool
"""
return isinstance(self.context, _rsr.ObjectResource)
@property
def admin_mgr(self):
"""
:rtype : pyramid_admin2.admin_manager.AdminManager
"""
return admin_manager.get_manager(self.model)
@property
def model_schema_cls(self):
if not inspect.isclass(self.admin_mgr.schema_cls):
raise InvalidSchemaClassError(self.admin_mgr)
# assert inspect.isclass(self.backend_mgr.schema_cls), \
# '%s.__backend_schema_cls__ (%s) is not a class' % \
# (self.model.__name__, self.backend_mgr.schema_cls)
return self.admin_mgr.schema_cls
def cell_datatype(self, val):
return cell_datatype(val)
@property
def toolbar_actions(self):
actions = self.model_actions
if isinstance(self.context, self.admin_mgr.ObjectResource):
actions += self.object_actions(self.context.object)
return actions
@property
def model_actions(self):
actions = []
for aconf in self.admin_mgr.actions:
if aconf.is_model_action:
actions.append({
'url': _rsr.model_url(self.request, self.model, aconf.conf['name']),
'label': aconf.get_label(None),
'icon': aconf.icon,
})
return actions
def object_actions(self, obj):
actions = []
for aconf in self.admin_mgr.actions:
if aconf.is_object_action:
label = aconf.label
label = label % {
'obj': obj,
'mgr': self.admin_mgr,
}
actions.append({
'url': _rsr.object_url(self.request, obj, aconf.conf['name']),
'label': aconf.get_label(obj),
'icon': aconf.icon,
'onclick': aconf.get_onclick(obj),
})
return actions
@property
def breadcrumbs(self):
cxt = self.context
cxts = list(reversed(list(lineage(cxt))))
r = self.request
if not r.view_name:
if self.is_current_context_object:
cmd_name = 'detail'
else:
cmd_name = 'list'
# cxts = cxts[:-1]
else:
cmd_name = r.view_name
_label = '@' + cmd_name
for aconf in self.admin_mgr.actions:
if cmd_name == aconf.name:
if self.is_current_context_object:
_label = aconf.get_label(cxt.object)
else:
_label = aconf.get_label()
break
return [{
'url': r.resource_url(c),
'label': u'%s' % c,
} for c in cxts] + [_label, ]
def list_page_url(self, page, partial=False):
params = self.request.GET.copy()
params["_page"] = page
if partial:
params["partial"] = "1"
qs = urlencode(params, True)
return "%s?%s" % (self.request.path, qs)
def action_list(self):
search_schema_cls = self.admin_mgr.search_schema_cls
if search_schema_cls is None:
search_form = None
else:
search_schema = search_schema_cls().bind()
search_form = deform.Form(search_schema,
method='GET',
appstruct=self.request.GET.mixed(),
buttons=(deform.Button(title='Search'), )
)
return {
'view': self,
'admin_mgr': self.admin_mgr,
'criteria': self.criteria,
'search_form': search_form,
}
def action_create(self):
schema = self.model_schema_cls().bind()
form = deform.Form(schema,
buttons=(deform.Button(title='Create'),
deform.Button(title='Cancel', type='reset', name='cancel')))
if 'submit' in self.request.POST:
try:
data = form.validate(self.request.POST.items())
data = _colander_null_to_none(data)
obj = self.admin_mgr.create(data)
self.request.session.flash(u'"%s" was created successful.' % obj, queue='pyramid_admin')
return HTTPFound(_rsr.object_url(self.request, obj))
except deform.ValidationFailure as e:
pass
return {
'view': self,
"form": form,
'admin_mgr': self.admin_mgr,
}
def action_update(self):
obj = self.context.object
schema = self.model_schema_cls().bind(obj=obj)
""":type schema: colander.Schema"""
appstruct = _none_to_colander_null({k: obj.__getattribute__(k)
for k in self.admin_mgr.column_names})
form = deform.Form(schema,
appstruct=appstruct,
buttons=(deform.Button(title='Update'),
deform.Button(title='Cancel', type='reset', name='cancel')))
if 'submit' in self.request.POST:
try:
data = form.validate(self.request.POST.items())
data = _colander_null_to_none(data)
obj = self.admin_mgr.update(obj, data)
self.request.session.flash(u'"%s" was updated successful.' % obj, queue='pyramid_admin')
return HTTPFound(_rsr.object_url(self.request, obj))
except deform.ValidationFailure as e:
pass
return {
'view': self,
'obj': obj,
"form": form,
'admin_mgr': self.admin_mgr,
}
def action_detail(self):
return {
'view': self,
'obj': self.context.object,
'admin_mgr': self.admin_mgr,
}
def action_delete(self):
obj = self.context.object
self.admin_mgr.delete(obj)
self.request.session.flash(u'%s#%s was history!' % (self.admin_mgr.display_name, obj))
return HTTPFound(_rsr.model_url(self.request, self.model))
| [
"hoc3010@gmail.com"
] | hoc3010@gmail.com |
33d0c570a0b5580573dfbdaff8adf62a2607badd | eb743ef136f3ad28ba6c9c90df436720a8d59d09 | /main/extractorchong.py | 4b5bebae2f55575b614036c004b31b67d8096358 | [] | no_license | Cindie00/P2_1A_5 | 438dad0b3ad9c0baf9e31fa44616bcf2e7a6e788 | b49fbf039c392cd4b73261cbe9abc195fe987fb2 | refs/heads/main | 2023-04-23T01:26:27.832109 | 2021-05-10T10:44:30 | 2021-05-10T10:44:30 | 351,902,542 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,300 | py | #############################
#
# Extracteur de donnés de Chong de l'exercice 2. ce qui équivaut à la Question 4 sur le site
#
#########################################################################################################@
import sqlite3
conn = sqlite3.connect('Base.sqlite')
cursor= conn.cursor()
data=list(cursor.execute("SELECT mere_id, date FROM velages"))
def Velage():
'''
pre:/
post: renvoie un dictionnaire avec le nombre de velages par année
'''
dico={}
annee={}
for x in data: # on crée 2 dictionnaires avec le nombre de velages par années
if dico.get(x[0],None) == None:
dico[x[0]]=1
else:
dico[x[0]]+=1
if annee.get(x[1][-4:],None) == None:
annee[x[1][-4:]]={dico[x[0]]:1}
else:
if annee[x[1][-4:]].get(dico[x[0]],None) == None:
annee[x[1][-4:]][dico[x[0]]]=1
else:
annee[x[1][-4:]][dico[x[0]]]+=1
for a in annee: #on récupère les donnés pour chaque année
for i in range(1,8):
if annee[a].get(i,None) == None:
annee[a][i]=0
return annee #on renvoie le dictionnaire avec les données du nombre de velages par an
conn.commit()
| [
"noreply@github.com"
] | noreply@github.com |
c9f4b189afc4ddbb247738162482210f8d229886 | 05e905fa3ca30fba051a8e8cce47895075ac03e3 | /ex47/game.py | b985c7183f885568b89b4f33a2b67b9fbbcf1a7c | [] | no_license | gitrobike/ex47 | b5396e35c75b5fad7d1cf135c80f76e9200c98f9 | 5d5c287e8ea6a5508868e5a5128cebe65421acde | refs/heads/master | 2021-01-10T10:47:08.076449 | 2016-01-19T07:19:15 | 2016-01-19T07:19:15 | 49,685,815 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 538 | py | # -*- coding: utf-8 -*-
class Room(object):
def __init__(self, name, description):
self.name = name
self.description = description
self.paths = {}
def go(self, direction):
#传入房间名,进入房间,获取value值。
return self.paths.get(direction)
# return self.paths.get(direction, None)#默认值是None,应该可以不写
def add_paths(self, paths):
#在paths字典中增加一组键值对
self.paths.update(paths)
#
# def ss(s):
# print(s) | [
"497125399@qq.com"
] | 497125399@qq.com |
9304946f7f5ed9562d7a3dbb6c52486fd296a7a1 | 9ef502b92bd218e919c65513e835c15c32667e8f | /samsung_load_0113.py | 75e8319216cf77777569806bc31afb952c0b80c3 | [] | no_license | YoungriKIM/samsung_stock | 034bc586440ab04531bb8d0b951747377c340966 | f15b6a3ebc3db76f960fc8f138dba7e43e345ef4 | refs/heads/main | 2023-04-14T03:20:51.169497 | 2021-03-25T08:35:48 | 2021-03-25T08:35:48 | 351,362,762 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 794 | py | import numpy as np
x_train = np.load('../data/npy/samsung_x_train.npy')
y_train = np.load('../data/npy/samsung_y_train.npy')
x_val = np.load('../data/npy/samsung_x_val.npy')
y_val = np.load('../data/npy/samsung_y_val.npy')
x_test = np.load('../data/npy/samsung_x_test.npy')
y_test = np.load('../data/npy/samsung_y_test.npy')
x_pred = np.load('../data/npy/samsung_x_pred.npy')
from tensorflow.keras.models import load_model
model = load_model('../data/modelcheckpoint/samsung_14-891193.4375.hdf5')
#4. 평가, 예측
result = model.evaluate(x_test, y_test, batch_size=1)
print('mse: ', result[0])
print('mae: ', result[1])
y_pred = model.predict(x_pred)
print('1/14일 삼성주식 종가: ', y_pred)
# mse: 1286656.875
# mae: 825.32763671875
# 1/14일 삼성주식 종가: [[90572.59]] | [
"lemontleo0311@gmail.com"
] | lemontleo0311@gmail.com |
e6ba2e66f4df8af86c5e31215b5c3d8973ecf055 | 81302ee42c1b3c25ce1566d70a782ab5525c7892 | /nr/nr_band_matching/autocorrelation_full_chain.py | aba89bd8971c7b2b106fb1a5a0ea7d38951568ae | [] | no_license | mdanthony17/neriX | 5dd8ce673cd340888d3d5e4d992f7296702c6407 | 2c4ddbb0b64e7ca54f30333ba4fb8f601bbcc32e | refs/heads/master | 2020-04-04T06:01:25.200835 | 2018-06-05T00:37:08 | 2018-06-05T00:46:11 | 49,095,961 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,812 | py | #!/usr/bin/python
import sys, array, os
#sys.path.insert(0, '..')
import ROOT as root
from rootpy.plotting import Hist, Hist2D, Canvas, Legend
import nr_band_config
import numpy as np
import corner
import cPickle as pickle
import time, emcee
if len(sys.argv) != 5:
print 'Use is python perform_full_matching.py <filename> <anode setting> <cathode setting> <num walkers> [<deviation_from_nest(efficiency fit only!!!)>]'
sys.exit()
filename = sys.argv[1]
anode_setting = float(sys.argv[2])
cathode_setting = float(sys.argv[3])
num_walkers = int(sys.argv[4])
nameOfResultsDirectory = nr_band_config.results_directory_name
l_plots = ['plots', filename]
dir_specifier_name = '%.3fkV_%.1fkV' % (cathode_setting, anode_setting)
nameOfResultsDirectory += '/yields_fit'
sPathToFile = '%s/%s/%s/sampler_dictionary.p' % (nameOfResultsDirectory, dir_specifier_name, filename)
if os.path.exists(sPathToFile):
dSampler = pickle.load(open(sPathToFile, 'r'))
l_chains = []
for sampler in dSampler[num_walkers]:
l_chains.append(sampler['_chain'])
a_full_chain = np.concatenate(l_chains, axis=1)
#print a_full_chain.shape
l_chains = dSampler[num_walkers][-1]['_chain'] # look at last sampler only (can change)
print 'Successfully loaded sampler!'
else:
print sPathToFile
print 'Could not find file!'
sys.exit()
print emcee.autocorr.integrated_time(np.mean(a_full_chain, axis=0), axis=0,
low=10, high=None, step=1, c=2,
fast=False)
"""
# need to figure this out
if not fit_efficiency:
numDim = 36
else:
numDim = 3
lLabelsForCorner = ['py_0', 'py_1', 'py_2', 'py_3', 'py_4', 'py_5', 'py_6', 'py_7', 'qy_0', 'qy_1', 'qy_2', 'qy_3', 'qy_4', 'qy_5', 'qy_6', 'qy_7', 'intrinsic_res_s1', 'intrinsic_res_s2', 'g1_value', 'spe_res_rv', 'g2_value', 'gas_gain_rv', 'gas_gain_width_rv', 'pf_eff_par0', 'pf_eff_par1', 's1_eff_par0', 's1_eff_par1', 's2_eff_par0', 's2_eff_par1', 'pf_stdev_par0', 'pf_stdev_par1', 'pf_stdev_par2', 'exciton_to_ion_par0_rv', 'exciton_to_ion_par1_rv', 'exciton_to_ion_par2_rv', 'scale_par']
if fit_efficiency:
lLabelsForCorner = ['scale', 's2_eff_par0', 's2_eff_par1']
samples = aSampler[:, -5:, :].reshape((-1, numDim))
start_time = time.time()
print 'Starting corner plot...\n'
fig = corner.corner(samples, labels=lLabelsForCorner, quantiles=[0.16, 0.5, 0.84], show_titles=True, title_kwargs={"fontsize": 12})
print 'Corner plot took %.3f minutes.\n\n' % ((time.time()-start_time)/60.)
# path for save
sPathForSave = './'
for directory in l_plots:
sPathForSave += directory + '/'
if not os.path.exists(sPathForSave):
os.makedirs(sPathForSave)
plot_name = 'nr_band_corner_%s' % (filename)
plot_name = 'yields_fit_%s' % (plot_name)
fig.savefig('%s%s.png' % (sPathForSave, plot_name))
"""
| [
"mda2149@columbia.edu"
] | mda2149@columbia.edu |
911baf07b0630491c0a4b906152bb42fcb0be366 | 9b72de4f01c77b92ef23cf0433d7f806802bb419 | /SPOJ/MOZPAS - Prangon and String/Prangon and String.py | a0ea818736818271596dc598de0e73defcb7acca | [] | no_license | GitPistachio/Competitive-programming | ddffdbc447669a2f8ade6118dfe4981bae948669 | f8a73f5152b2016b1603a64b7037602d2ab2c06e | refs/heads/master | 2023-05-01T20:55:18.808645 | 2023-04-21T20:45:08 | 2023-04-21T20:45:08 | 167,733,575 | 8 | 4 | null | null | null | null | UTF-8 | Python | false | false | 448 | py | # Project name : SPOJ: MOZPAS - Prangon and String
# Author : Wojciech Raszka
# E-mail : gitpistachio@gmail.com
# Date created : 2019-04-21
# Description :
# Status : Accepted (23669618)
# Tags : python
# Comment :
import string
n, m = map(int, input().split())
prangon = ''
for l in string.ascii_letters:
prangon += l*min(n - len(prangon), m)
if len(prangon) == n:
print(prangon)
break
| [
"gitpistachio@gmail.com"
] | gitpistachio@gmail.com |
45ae89103552d5b6241450ebb6673d4b04d148c3 | 49856b872815dc9d1a623a72bad081dd40cc23ca | /src/ai/__init__.py | a41be53344c106111871c751111e83c61e4bca41 | [
"BSD-2-Clause"
] | permissive | calcu16/GenericBoardGameAI | 06eece1eb5857e50384a01ea5de38b4ec4963491 | 69dc99a0988703eccb72879443dbfaaf3ddb21fc | refs/heads/main | 2023-01-23T04:50:28.350264 | 2020-11-29T23:29:01 | 2020-11-29T23:29:01 | 311,138,626 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 13 | py | # ai package
| [
"acarter@linkedin.com"
] | acarter@linkedin.com |
72952881d9b154e46425045a1436cf7b055e6414 | 68ce9d89a8cd3ebf1f1a011f5f039fcf287f2d7e | /Practica07_KohonenSOM/codigoFuente/UI/external_widgets/points_input.py | defb869f8f06837d4bd126d0e6fa9cd2c6c1c189 | [
"MIT"
] | permissive | CodeRevenge/practicas_ia_2 | 3ada6f951a7d635451676920aeccb20d47cd0fd6 | b81e3b68680b61785918b19360cb0afc5b14c26e | refs/heads/master | 2023-02-09T13:56:30.807621 | 2019-11-26T18:17:01 | 2019-11-26T18:17:01 | 205,444,362 | 1 | 0 | MIT | 2021-01-05T15:52:27 | 2019-08-30T19:25:21 | Python | UTF-8 | Python | false | false | 2,842 | py | # ------------------------------------------------------
# -------------------- points_input.py --------------------
# ------------------------------------------------------
import sys
from PyQt5.QtWidgets import QVBoxLayout, QWidget
from matplotlib.backends.backend_qt5agg import FigureCanvas
import matplotlib.pylab as plt
from matplotlib import patches as patches
import numpy as np
class Points_Input(QWidget):
def __init__(self, parent):
QWidget.__init__(self, parent)
self.layout = QVBoxLayout()
self.setLayout(self.layout)
self.layout.setContentsMargins(0,0,0,0)
# Creating de graph
self.fig = plt.figure(2)
self.ax = plt.subplot()
self.canvas = FigureCanvas(self.fig)
self.canvas.setFocus()
self.layout.addWidget(self.canvas)
self.init_graph()
self.canvas.draw()
def init_graph(self):
plt.figure(2)
plt.tight_layout()
self.ax = plt.gca()
self.fig.set_facecolor('#323232')
self.ax.grid(zorder=0)
self.ax.set_axisbelow(True)
self.ax.set_xlim([0, 5])
self.ax.set_ylim([0, 5])
self.ax.set_xticks(range(0,6))
self.ax.set_yticks(range(0,6))
self.ax.axhline(y=0, color='#323232')
self.ax.axvline(x=0, color='#323232')
self.ax.spines['right'].set_visible(False)
self.ax.spines['top'].set_visible(False)
self.ax.spines['bottom'].set_visible(False)
self.ax.spines['left'].set_visible(False)
self.ax.tick_params(axis='x', colors='#b1b1b1')
self.ax.tick_params(axis='y', colors='#b1b1b1')
def clearPlot(self):
self.fig = plt.figure(2)
self.fig.clf()
self.ax = plt.gca()
self.ax.cla()
# self.init_graph()
self.canvas.draw()
def plot_lines(self, net):
self.clearPlot()
self.fig = plt.figure(2)
self.ax = plt.gca()
self.fig.set_facecolor('#323232')
# setup axes
# self.ax = self.fig.add_subplot(111, aspect='equal')
self.ax.set_xlim((0, net.shape[0]+1))
self.ax.set_ylim((0, net.shape[1]+1))
self.ax.tick_params(axis='x', colors='#b1b1b1')
self.ax.tick_params(axis='y', colors='#b1b1b1')
# plot the rectangles
for x in range(1, net.shape[0] + 1):
for y in range(1, net.shape[1] + 1):
face_color = net[x-1,y-1,:]
face_color = [sum(face_color[:3])/3,sum(face_color[3:6])/3, sum(face_color[6:])/4]
self.ax.add_patch(patches.Rectangle((x-0.5, y-0.5), 1, 1,
# facecolor=net[x-1,y-1,:],
facecolor=face_color,
edgecolor='none'))
self.canvas.draw()
| [
"mas.arley2009@hotmail.com"
] | mas.arley2009@hotmail.com |
c40388cde769fb9ada70d3cfdd7ebacb5039179f | e22f12667ce20387a689e41c145efff91a184df1 | /tests/asserts/for.py | 565e80e94fb67656c3a995e7ac7b0f3f37718e9a | [] | no_license | liwt31/NPython | d6246b6bd7a58865a3c32763a8766d296cc38f07 | 1159715bb6d4ff9502e9fa4466ddc6f36a8b63d2 | refs/heads/master | 2020-04-13T02:22:53.516945 | 2019-02-19T09:19:17 | 2019-02-19T09:19:17 | 162,900,818 | 21 | 1 | null | null | null | null | UTF-8 | Python | false | false | 68 | py | j = 0
for i in [1,2,3]:
j = j + i
assert j == 6
print("ok")
| [
"liwt31@163.com"
] | liwt31@163.com |
2220d983c98baec53a5ea75b6be2345d77c622c7 | 075a9186a43041b062ce883604a125484db64c71 | /source_code/dependencies/Python_MyoSim/half_sarcomere/myofilaments/forces.py | 07a9188d61ec2c2469269e9ab35951bcd3fba925 | [] | no_license | mmoth-kurtis/MMotH-Vent | 0c4afa14f882e3d6fff6aa3c354d142bc00ab906 | b1caff62bfdc60000e429a35fb4a4327dfbed4ea | refs/heads/master | 2023-02-24T00:02:09.078654 | 2021-01-29T19:19:25 | 2021-01-29T19:19:25 | 233,081,781 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,807 | py | # Functions relating to forces
import numpy as np
import scipy.optimize as opt
def set_myofilament_forces(self):
self.cb_force = return_cb_force(self, 0.0)
self.pas_force = return_passive_force(self, 0.0)
self.total_force = self.cb_force + self.pas_force
def check_myofilament_forces(self, delta_hsl):
d = dict()
d['cb_force'] = return_cb_force(self, delta_hsl)
d['pas_force'] = return_passive_force(self, delta_hsl)
d['total_force'] = d['cb_force'] + d['pas_force']
return d
def return_cb_force(self, delta_hsl):
if (self.kinetic_scheme == '3state_with_SRX'):
bin_pops = self.y[2 + np.arange(0, self.no_of_x_bins)]
cb_force = \
self.parent_hs.cb_number_density * \
self.k_cb * 1e-9 * \
np.sum(bin_pops * (self.x + self.x_ps +
(self.filament_compliance_factor * delta_hsl)))
return cb_force
def return_x(self,x):
return x
def return_passive_force(self, delta_hsl):
if (self.passive_mode == 'linear'):
pas_force = self.passive_linear_k_p * \
(self.parent_hs.hs_length + delta_hsl -
self.passive_l_slack)
if (self.passive_mode == 'exponential'):
x = self.parent_hs.hs_length + delta_hsl - self.passive_l_slack
if (x > 0):
pas_force = self.passive_exp_sigma * \
(np.exp(x / self.passive_exp_L) - 1.0)
else:
pas_force = -self.passive_exp_sigma * \
(np.exp(np.abs(x) / self.passive_exp_L) - 1.0)
return pas_force
def return_hs_length_for_force(self, force):
def f(dx):
d = check_myofilament_forces(self, dx)
return d['total_force']
sol = opt.brentq(f,-1000, 1000)
return self.parent_hs.hs_length + sol
| [
"ckma224@g.uky.edu"
] | ckma224@g.uky.edu |
4973e7282b46d9706ed15045ac25c1ccdd76851e | aa4c5d11d168eb02e5596e55c3b6d2741eca69f6 | /manage.py | 06fb8bcb4a5a64027466f9f0e0f64f99f474a6a0 | [] | no_license | bigwboy/SystemManager20 | 3c07531c2e02af43bfbc0d94898e1073bfa50f29 | 2096831341dc84cb94a729ac559d6a0c4a75258f | refs/heads/master | 2021-05-05T18:47:36.016106 | 2018-01-30T05:21:11 | 2018-01-30T05:21:11 | 117,636,354 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 547 | py | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "SystemManager20.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
| [
"kevinliu830829@163.com"
] | kevinliu830829@163.com |
4c372b72b1e7e834e9fa8c9bde95f42de65c174c | 8d86cad6e7eda824f3405c297a2245496beeed5c | /geometrycalculator.py | 549c2860e4d8a31bd377f1ae05ee97e4bb3d16a7 | [] | no_license | sstappa/automatic-spoon | 94b303388955c16d6879e037710a1b2cf7945aef | 8dd17c0409920e3cee4e729eda7b0391e9de3973 | refs/heads/master | 2021-01-01T18:04:52.977333 | 2017-08-03T16:16:15 | 2017-08-03T16:16:15 | 98,240,064 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,175 | py | #GPA Calculator
#Shane Tappa
#7/30/17
def rectangle_calc():
height = 0.0
width = 0.0
area = 0.0
while True:
try:
height = float(raw_input("Enter the height of your rectangle: "))
break
except ValueError:
print("Oops! That was no valid number. Try again...")
while True:
try:
width = float(raw_input("Enter the width of your rectangle: "))
break
except ValueError:
print("Oops! That was no valid number. Try again...")
area = height * width
print "The area of your rectangle is: {:,.2f}".format(area)
def right_triangle_calc():
base = 0.0
height = 0.0
area = 0.0
while True:
try:
base = float(raw_input("Enter the base of your right rectangle: "))
break
except ValueError:
print("Oops! That was no valid number. Try again...")
while True:
try:
height = float(raw_input("Enter the height of your right rectangle: "))
break
except ValueError:
print("Oops! That was no valid number. Try again...")
area = 0.5 * base * height
print "The area of your right rectangle: {:,.2f}".format(area)
def circle_calc():
import math
radius = 0.0
area = 0.0
#print "Enter the radius of your circle:"
#radius = float(raw_input())
while True:
try:
radius = float(raw_input("Enter the radius of your circle: "))
break
except ValueError:
print("Oops! That was no valid number. Try again...")
area = 4*math.pi*radius**2
print "The area of your circle is: {:,.2f}".format(area)
choice = 0
print "Welcome to the geometry calculator"
print "Your choices are:"
print "1 = rectangule calculator, 2 = right triangle calculator"
print "3 = circle calculator, 4 = quit program"
print "Choose the shape whose area you want to calculate."
#choice = raw_input()
#choice = int(choice)
while True:
try:
choice = int(raw_input("Please enter a number: "))
break
except ValueError:
print("Oops! That was no valid number. Try again...")
while choice != 4:
if choice == 1:
print "Your choice was: %s" % choice + " (rectangle calculator)"
rectangle_calc()
elif choice == 2:
print "Your choice was: %s" % choice + " (right triangle calculator)"
right_triangle_calc()
elif choice == 3:
print "Your choice was: %s" % choice + " (circle calculator)"
circle_calc()
print ""
print "Choose another shape whose area you want to calculate."
print "1 = rectangule calculator, 2 = right triangle calculator"
print "3 = circle calculator, 4 = quit program"
while True:
try:
choice = int(raw_input("Please enter a number: "))
break
except ValueError:
print("Oops! That was no valid number. Try again...")
| [
"noreply@github.com"
] | noreply@github.com |
4d9b59df5f0fe4ca4796d0121a12dc0208a93d3e | f5b7b87d0de1459c284b6ebf3aa21c6a96e52207 | /broadgauge/views/auth.py | 8d91aca9aa0d2097097fb9062d97b809ab2611b1 | [] | no_license | iambibhas/broadgauge | cfbce9bbebdc5337918df7b378810a53c9a68f8b | 381816cb9c288b071b44f189d662611cdc57e58b | refs/heads/master | 2021-01-18T09:01:32.155941 | 2014-08-15T11:42:58 | 2014-08-15T11:42:58 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,323 | py | import web
import json
from .. import account
from .. import oauth
from .. import forms
from ..sendmail import sendmail
from ..flash import flash
from ..models import User, Organization
from ..template import render_template
urls = (
"/login", "login",
"/logout", "logout",
"/oauth/(github|google|facebook)", "oauth_callback",
"(/trainers/signup|/orgs/signup|/login)/reset", "signup_reset",
"(/trainers/signup|/orgs/signup|/login)/(github|google|facebook)", "signup_redirect",
"/trainers/signup", "trainer_signup",
"/orgs/signup", "org_signup",
)
def get_oauth_redirect_url(provider):
home = web.ctx.home
if provider == 'google' and home == 'http://0.0.0.0:8080':
# google doesn't like 0.0.0.0
home = 'http://127.0.0.1:8080'
elif provider == 'facebook' and home == 'http://127.0.0.1:8080':
# facebook doesn't like 127.0.0.1
home = 'http://0.0.0.0:8080'
return "{home}/oauth/{provider}".format(home=home, provider=provider)
def get_oauth_data():
userdata_json = web.cookies().get('oauth')
if userdata_json:
try:
return json.loads(userdata_json)
except ValueError:
pass
class login:
def GET(self):
userdata = get_oauth_data()
if userdata:
user = User.find(email=userdata['email'])
if user:
account.set_login_cookie(user.email)
raise web.seeother("/dashboard")
else:
return render_template("login.html", userdata=userdata,
error=True)
else:
return render_template("login.html", userdata=None)
class logout:
def POST(self):
account.logout()
referer = web.ctx.env.get('HTTP_REFERER', '/')
raise web.seeother(referer)
class oauth_callback:
def GET(self, service):
i = web.input(code=None, state="/")
if i.code:
redirect_uri = get_oauth_redirect_url(service)
client = oauth.oauth_service(service, redirect_uri)
userdata = client.get_userdata(i.code)
if userdata:
# login or signup
t = User.find(email=userdata['email'])
if t:
account.set_login_cookie(t.email)
raise web.seeother("/dashboard")
else:
web.setcookie("oauth", json.dumps(userdata))
raise web.seeother(i.state)
flash("Authorization failed, please try again.", category="error")
raise web.seeother(i.state)
class signup_redirect:
def GET(self, base, provider):
redirect_uri = get_oauth_redirect_url(provider)
client = oauth.oauth_service(provider, redirect_uri)
url = client.get_authorize_url(state=base)
raise web.seeother(url)
class signup_reset:
def GET(self, base):
# TODO: This should be a POST request, not GET
web.setcookie("oauth", "", expires=-1)
raise web.seeother(base)
class trainer_signup:
FORM = forms.TrainerSignupForm
TEMPLATE = "trainers/signup.html"
def GET(self):
userdata = get_oauth_data()
if userdata:
# if already logged in, send him to dashboard
user = self.find_user(email=userdata['email'])
if user:
if not user.is_trainer():
user.make_trainer()
account.set_login_cookie(user.email)
raise web.seeother("/dashboard")
form = self.FORM(userdata)
return render_template(self.TEMPLATE, form=form, userdata=userdata)
def POST(self):
userdata = get_oauth_data()
if not userdata:
return self.GET()
i = web.input()
form = self.FORM(i)
if not form.validate():
return render_template(self.TEMPLATE, form=form)
return self.signup(i, userdata)
def signup(self, i, userdata):
user = User.new(
name=i.name,
email=userdata['email'],
username=i.username,
phone=i.phone,
city=i.city,
github=userdata.get('github'),
is_trainer=True)
account.set_login_cookie(user.email)
flash("Thank you for signing up as a trainer!")
sendmail("emails/trainers/welcome.html",
subject="Welcome to Python Express",
to=user.email,
trainer=user)
raise web.seeother("/dashboard")
def find_user(self, email):
return User.find(email=email)
class org_signup(trainer_signup):
FORM = forms.OrganizationSignupForm
TEMPLATE = "orgs/signup.html"
def find_user(self, email):
# We don't limit numer of org signups per person
return None
def signup(self, i, userdata):
user = User.find(email=userdata['email'])
if not user:
user = User.new(name=userdata['name'], email=userdata['email'])
org = Organization.new(name=i.name,
city=i.city)
org.add_member(user, i.role)
account.set_login_cookie(user.email)
flash("Thank you for registering your organization with Python Express!")
raise web.seeother("/orgs/{}".format(org.id))
| [
"anandology@gmail.com"
] | anandology@gmail.com |
0a19c136e099464b3aa596b8aa85c466256d422b | 88105415f122ff7ac7c36e682a0d35928a84c6cc | /pullRequests/seriedeeuler.py | bf4d1622079e26be04c089e7d84d16633d54ba1a | [] | no_license | drknssAndrey/github-course | 37edac6e8aeafa9207d042d0915662911517bbfc | 19090ecdcce2e1f0c8a525db8725f319a06b2aec | refs/heads/master | 2020-05-29T17:48:18.906923 | 2020-04-12T13:22:37 | 2020-04-12T13:22:37 | 189,283,761 | 1 | 3 | null | 2019-10-24T00:11:21 | 2019-05-29T19:10:22 | C | UTF-8 | Python | false | false | 161 | py | def fat(a):
if a == 0:
return 1
else:
return a * fat(a-1)
s = 0
x = int(input())
for c in range(x):
s += 1/fat(c)
print("%.15f"%s)
| [
"noreply@github.com"
] | noreply@github.com |
51fa31d3f1c84dfee4fc19b997797bb617257a33 | 4bcc2f4b4608d2674f5d3923e39d1cc01a067059 | /Object Oriented Programming/11_grumpy.py | 35d5d375af4ec43bf61e2898fa426cd6c80e0d61 | [] | no_license | bettercallkyaw/All-Python-Fields | 6f57274c43631c29f6f9219b5b84c0529b9c04c0 | 3d67d48e5ee4f18d95a6d2ff6783fed1164b9e88 | refs/heads/master | 2023-08-20T12:45:46.860786 | 2021-10-23T13:59:25 | 2021-10-23T13:59:25 | 330,874,349 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 588 | py | class GrumpyDict(dict):
def __repr__(self):
print('NONE OF YOUR BUNISESS')
return super().__repr__()
def __missing__(self,key):
print(f'YOU WANT {key}? WELL IT AINT HERE!')
def __setitem__(self,key,value):
print('YOU WANT OT CHANGE THE DICTIONARY?')
print('OK FINE...')
super().__setitem__(key,value)
def __contains__(self,item):
print('NO IT AINT HERE!')
return False
data=GrumpyDict({'frist':'Tom','animal':'cat'})
print(data)
data['city']='Boston'
print(data)
'city' in data
| [
"bettercallkyaw@outlook.com"
] | bettercallkyaw@outlook.com |
38cf24e5c595728a7f5c72b09f8b2db1e0c29f92 | bf93e278bf9325742f4e549ce4232ee8ff9e47e0 | /courses/courses/spiders/courses.py | 2cf17211f612b0b2054706cfe60a4b329a794647 | [] | no_license | Chawwie/coursetree | 4d3b8bfb1c9981485730e1952989a3903411db51 | ec76e24a797d1a9a88bae0f50cce4d68e83e79e4 | refs/heads/master | 2021-02-09T11:40:52.277015 | 2019-11-06T05:42:28 | 2019-11-06T05:42:28 | 244,278,323 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,210 | py | # -*- coding: utf-8 -*-
import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
class CoursesSpider(CrawlSpider):
name = 'courses'
# allowed_domains = ['my.uq.edu.au/']
# start_urls = ['https://my.uq.edu.au/programs-courses/search.html?keywords=CSSE&searchType=course&archived=true&CourseParameters%5Bsemester%5D=&level=ugrd']
start_urls = ['https://my.uq.edu.au/programs-courses/program_list.html?acad_prog=2425']
rules = (
Rule(LinkExtractor(allow=('\/programs-courses\/course\.html\?course_code=[a-zA-Z0-9]*$', )), callback='parse_item'),
)
def parse_item(self, response):
description = response.css('#description').css('p::text').get()
if description.find("This course is not currently offered") != -1:
yield {
'name': response.css('#course-title::text').get(),
'pre': response.css('#course-prerequisite::text').get(),
'obsolete': True
}
else:
yield {
'name': response.css('#course-title::text').get(),
'pre': response.css('#course-prerequisite::text').get(),
} | [
"charleliliu@gmail.com"
] | charleliliu@gmail.com |
21599d7a7e64dcf0db7985ec616eb3690bd43f39 | 774e24bd32a36dd448a9390149c5fb531718fd96 | /venv/bin/django-admin | 11d6199337351c0713d5d018dd99d84c772f9f5a | [] | no_license | reetshrivastava/autoTextSummarizer | 69e3c54f7ea25d53196797a9a258d137b8020f3e | 03dde3dc8161fbe1181a0a0b4dcd10a6c3e042dd | refs/heads/master | 2021-01-10T05:06:36.277145 | 2016-04-16T05:41:06 | 2016-04-16T05:41:06 | 52,152,413 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 314 | #!/home/hasher/finalYearProject/autoTextSummarizer/venv/bin/python
# -*- coding: utf-8 -*-
import re
import sys
from django.core.management import execute_from_command_line
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(execute_from_command_line())
| [
"reet.shrivastava@hashedin.com"
] | reet.shrivastava@hashedin.com | |
27f1d1e42412bfb3574bdec543ba0703469f2fce | 82f6a6c50a1fef2d7522a43cc4f60e5ff80b37a8 | /solutions/Missing Number/solution.py | 0bf89957ba6d64c0deea0d059f647ac75434429a | [
"MIT"
] | permissive | nilax97/leetcode-solutions | ca0f9545ce70975617738f053e0935fac00b04d4 | d3c12f2b289662d199510e0431e177bbf3cda121 | refs/heads/master | 2023-05-14T02:21:48.893716 | 2021-06-08T13:16:53 | 2021-06-08T13:16:53 | 374,466,870 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 136 | py | class Solution:
def missingNumber(self, nums: List[int]) -> int:
return (len(nums) * (len(nums)+1))//2 - sum(nums)
| [
"agarwal.nilaksh@gmail.com"
] | agarwal.nilaksh@gmail.com |
77b6612c1c5ec7062621dabb8c700e0cb21a286f | 847c8bda0bcf43e0b47928b9c8de0e9e351e8c84 | /testsuite/tests/Q226-004__python_no_check_comment/src/space_after.py | 546da9b085691944c8c7c2ecb941f8105c6350ac | [] | no_license | Tubbz-alt/style_checker | 6c40644bcc92b8b0594ad796dfe3a12958814dee | e9aae5837983879487986ea6b062fc8b00cb97ab | refs/heads/master | 2023-01-22T13:21:55.714986 | 2020-12-02T04:33:42 | 2020-12-02T04:34:37 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 204 | py | # No_Style_Check
"""The No_Style_Check comment above has trailing spaces, and this should
cause the style_checker to ignore that comment, and therefore perform
style checks.
"""
space_before_paren ()
| [
"brobecker@adacore.com"
] | brobecker@adacore.com |
173de47073bcfee2292415ce0e9b944d48e315cb | d912423117d96cd67d23bab87c0773a07d962cc1 | /backend/socket_chat/consumers/main.py | a923f06cb91d42b37282f3545803320df8b675de | [] | no_license | modekano/ChatApp | b98f9081235c976642d024d56d1531b5120a04cf | 22cca9f3d4c25a93ca255d6616f61773da757d18 | refs/heads/master | 2020-08-19T06:03:45.010063 | 2019-10-17T11:17:07 | 2019-10-17T11:17:07 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,557 | py | from backend.socket_chat.consumers.base import BaseConsumer
from channels.db import database_sync_to_async
from backend.profiles.models import Profile
from backend.socket_chat.consumers.dialog import DialogConsumer
class MainConsumer(DialogConsumer, BaseConsumer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.dialogs = []
self._groups = []
async def channels_message(self, message):
""" Redirect Group messages to each person """
await self._send_message(message['data'], event=message['event'])
async def connect_users(self, message):
""" Connect user to rooms """
users = message['data']['users']
room = message['data']['room']
room_data = message['data']['room_data']
event = message['event']
if self.user.id in users:
print('connecting %s to %s' % (self.user.id, room))
print(room_data, room)
await self.channel_layer.group_add(room, self.channel_name)
await self._send_message(room_data[self.user.id], event=event)
async def on_authenticate_success(self):
""" Execute after user authenticate """
await self.get_user_channels(self.user)
await self.channel_layer.group_add('general', self.channel_name)
# connect to channel for all groups
if self.dialogs:
for dialog in self.dialogs:
await self.channel_layer.group_add(f'dialog_{dialog}', self.channel_name)
if self._groups:
for group in self._groups:
await self.channel_layer.group_add(f'group_{group}', self.channel_name)
async def disconnect(self, *args, **kwargs):
""" Discard from all channels """
if self.dialogs:
for dialog in self.dialogs:
await self.channel_layer.group_discard(
f'dialog_{dialog}',
self.channel_name
)
if self._groups:
for group in self._groups:
await self.channel_layer.group_discard(
f'group_{group}',
self.channel_name
)
@database_sync_to_async
def get_user_channels(self, user):
""" Get all user's dialogs & groups id """
profile = Profile.objects.get(user=user)
for dialog in profile.dialogs.values():
self.dialogs.append(dialog.get('id'))
for group in profile.groups.values():
self._groups.append(group.get('id'))
| [
"kostya.nik.3854@gmail.com"
] | kostya.nik.3854@gmail.com |
16c2ae91567af5e69813f720ed12596e55149529 | 5ff3234e9cae154b2f63cf8bfd1a79c6b6584202 | /url_shorter/settings.py | 42c9da9b71f742a4b5c2404c9e2d5ee985aa5bc5 | [] | no_license | OleksiySitnik/aiohttp-urlshortener | 76542494e9c76d66b1a61fe9d4e19ee350b7e48e | a2f2e9960857ce18f98885f235330845dee4b4b2 | refs/heads/master | 2022-12-24T22:31:40.852382 | 2019-05-26T11:33:24 | 2019-05-26T11:33:24 | 188,674,816 | 0 | 1 | null | 2022-12-14T23:36:49 | 2019-05-26T11:33:11 | Python | UTF-8 | Python | false | false | 331 | py | from pathlib import Path
import trafaret as t
from aiohttp import web
import yaml
BASE_DIR = Path(__file__).parent.parent
CONFIG_DIR = BASE_DIR / 'config'
def load_config(config_file):
with open(CONFIG_DIR / config_file, 'r') as f:
config = yaml.safe_load(f)
return config
CONFIG = load_config('config.yml')
| [
"bomchikimmmm@gmail.com"
] | bomchikimmmm@gmail.com |
788b2a61a5404d4ca362cc99744810d225ec6ba4 | 4f990e1c80ba34942aab43c6f51d5d263516c3cd | /test/test_loss.py | 56522a563c0668d160ae98ce1dd241d5ddbaae68 | [] | no_license | EmiyaNing/paddle-yolov5 | 3e7a6003a65323e07d425b769b26a865b9f327b7 | c39eb331d07049a0b884ed6d856f45c77dc5c007 | refs/heads/master | 2023-05-05T11:40:55.972433 | 2021-06-03T06:49:45 | 2021-06-03T06:49:45 | 366,685,205 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 917 | py | import sys
import paddle
import numpy as np
sys.path.append("..")
from utils.loss import ComputeLoss
from models.yolo_head import Detect_head
def test_loss():
p3 = paddle.to_tensor(np.random.rand(4, 512, 7, 7, 85), dtype='float32')
p4 = paddle.to_tensor(np.random.rand(4, 256, 14, 14, 85), dtype='float32')
p5 = paddle.to_tensor(np.random.rand(4, 128, 28, 28, 85), dtype='float32')
p = [p3, p4, p5]
targets = paddle.to_tensor(np.random.rand(88, 6), dtype='float32')
detect = Detect_head(anchors=(
[10,13, 16,30, 33,23], # P3/8
[30,61, 62,45, 59,119], # P4/16
[116,90, 156,198, 373,326] # P5/32
), ch=[128, 256, 512])
compute_loss = ComputeLoss(det = detect)
loss, temp = compute_loss(p, targets)
print(loss)
print(temp.shape)
if __name__ == '__main__':
test_loss() | [
"ningkangl@icloud.com"
] | ningkangl@icloud.com |
5ed249054576d9eaccecd2490d226c49e0b83bf6 | 00f4298b6714f34e6d56b19bc309e7ac8d824dd7 | /Twitter/Files/TwitterStream.py~ | 6074db0b3c10de4e6d5ff4cf4eb86b8c23446a1f | [] | no_license | pbarker/pytwit | 27c108836e66dbce1b2d481094c14e437d85c2e7 | f1de663108917895bc83fd17016fcfa9669e4f47 | refs/heads/master | 2021-05-27T23:53:13.608008 | 2014-11-26T02:46:33 | 2014-11-26T02:46:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,788 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2012 Gustav Arngården
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import time
import pycurl
import urllib
import json
import pymongo
import oauth2 as oauth
from nameparts import Name
import gender_package.gender_master
mongohost = 'localhost'
mongoport = 27017
connection = pymongo.Connection(mongohost, mongoport)
db = connection.mydb
API_ENDPOINT_URL = 'https://stream.twitter.com/1.1/statuses/filter.json'
USER_AGENT = 'TwitterStream 1.1' # This can be anything really
# You need to replace these with your own values
OAUTH_KEYS = {'consumer_key': 'dWQLOYclydg9jIX4hIkrcA',
'consumer_secret': 'tYwldvSefpYQ9XKgSVkgvjmOXux3BLVmQUcTCdECMs',
'access_token_key': '1538811649-DqRtRYquJskvG7J027F4yNxCVvfN3r7zgj7puk1',
'access_token_secret': 'ketQfj1wlSzOXMBYWqv9pXVyK0oGXpfAAizsEVrzw'}
# These values are posted when setting up the connection
POST_PARAMS = {'include_entities': 0,
'stall_warning': 'true',
'locations':'-105.29,38.61,-104.34,40.61'}
class TwitterStream:
def __init__(self, timeout=False):
self.oauth_token = oauth.Token(key=OAUTH_KEYS['access_token_key'], secret=OAUTH_KEYS['access_token_secret'])
self.oauth_consumer = oauth.Consumer(key=OAUTH_KEYS['consumer_key'], secret=OAUTH_KEYS['consumer_secret'])
self.conn = None
self.buffer = ''
self.timeout = timeout
self.setup_connection()
def setup_connection(self):
""" Create persistant HTTP connection to Streaming API endpoint using cURL.
"""
if self.conn:
self.conn.close()
self.buffer = ''
self.conn = pycurl.Curl()
# Restart connection if less than 1 byte/s is received during "timeout" seconds
if isinstance(self.timeout, int):
self.conn.setopt(pycurl.LOW_SPEED_LIMIT, 1)
self.conn.setopt(pycurl.LOW_SPEED_TIME, self.timeout)
self.conn.setopt(pycurl.URL, API_ENDPOINT_URL)
self.conn.setopt(pycurl.USERAGENT, USER_AGENT)
# Using gzip is optional but saves us bandwidth.
self.conn.setopt(pycurl.ENCODING, 'deflate, gzip')
self.conn.setopt(pycurl.POST, 1)
self.conn.setopt(pycurl.POSTFIELDS, urllib.urlencode(POST_PARAMS))
self.conn.setopt(pycurl.HTTPHEADER, ['Host: stream.twitter.com',
'Authorization: %s' % self.get_oauth_header()])
# self.handle_tweet is the method that are called when new tweets arrive
self.conn.setopt(pycurl.WRITEFUNCTION, self.handle_tweet)
def get_oauth_header(self):
""" Create and return OAuth header.
"""
params = {'oauth_version': '1.0',
'oauth_nonce': oauth.generate_nonce(),
'oauth_timestamp': int(time.time())}
req = oauth.Request(method='POST', parameters=params, url='%s?%s' % (API_ENDPOINT_URL,
urllib.urlencode(POST_PARAMS)))
req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), self.oauth_consumer, self.oauth_token)
return req.to_header()['Authorization'].encode('utf-8')
def start(self):
""" Start listening to Streaming endpoint.
Handle exceptions according to Twitter's recommendations.
"""
backoff_network_error = 0.25
backoff_http_error = 5
backoff_rate_limit = 60
while True:
self.setup_connection()
try:
self.conn.perform()
except:
# Network error, use linear back off up to 16 seconds
print 'Network error: %s' % self.conn.errstr()
print 'Waiting %s seconds before trying again' % backoff_network_error
time.sleep(backoff_network_error)
backoff_network_error = min(backoff_network_error + 1, 16)
continue
# HTTP Error
sc = self.conn.getinfo(pycurl.HTTP_CODE)
if sc == 420:
# Rate limit, use exponential back off starting with 1 minute and double each attempt
print 'Rate limit, waiting %s seconds' % backoff_rate_limit
time.sleep(backoff_rate_limit)
backoff_rate_limit *= 2
else:
# HTTP error, use exponential back off up to 320 seconds
print 'HTTP error %s, %s' % (sc, self.conn.errstr())
print 'Waiting %s seconds' % backoff_http_error
time.sleep(backoff_http_error)
backoff_http_error = min(backoff_http_error * 2, 320)
def handle_tweet(self, data):
""" This method is called when data is received through Streaming endpoint.
"""
self.buffer += data
global fullname
global n
global firstname
global gender
if data.endswith('\r\n') and self.buffer.strip():
# complete message received
message = json.loads(self.buffer)
self.buffer = ''
msg = ''
if message.get('limit'):
print 'Rate limiting caused us to miss %s tweets' % (message['limit'].get('track'))
elif message.get('disconnect'):
raise Exception('Got disconnect: %s' % message['disconnect'].get('reason'))
elif message.get('warning'):
print 'Got warning: %s' % message['warning'].get('message')
else:
fullname = message['user']['name']
n = Name(fullname)
firstname = n.first_name
gender = gender_package.gender_master.masta_genda(firstname)
message['gender']= gender
print "++++++++++++++" + fullname + "++++++++++++++++++++"
print "++++++++++++++" + firstname + "++++++++++++++++++++"
print "++++++++++++++" + str(gender) + "++++++++++++++++++++"
print message['created_at'], message['id'], "Username: ", message['user']['screen_name'],':', message['text'].encode('utf-8')
db.tweets.save(message)
print '*chirp*'
if __name__ == '__main__':
ts = TwitterStream()
ts.setup_connection()
ts.start()
| [
"patrickbarkerco@gmail.com"
] | patrickbarkerco@gmail.com | |
c593f5e09c932fe741aed482b1e7e5edd836f652 | c9b1487d663563d596c13533b6a09f588d824a33 | /youtubedata.py | ae56de117f1e43b30328b95cc7f9f94a93cea88d | [] | no_license | kdm0904/Project | 8d301c645c001eac2ceab341b0315867f3a50a91 | ff36c46c79b046521f95d87b02b1aba8ac607f37 | refs/heads/master | 2020-04-11T11:03:49.737844 | 2019-05-08T08:33:35 | 2019-05-08T08:33:35 | 161,735,869 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,839 | py | from bs4 import BeautifulSoup as bs
def gettitle(div):
title2 = div.find("div", {"id" : "title-wrapper"})
title1 = title2.find("h3", {"class":"title-and-badge style-scope ytd-video-renderer"})
title = title1.find("a", {"id":"video-title"})
return title.text
def getyoutuber(div):
Youtuber1 = div.find("div", {"id":"byline-inner-container"})
Youtuber = Youtuber1.find("a", {"class":"yt-simple-endpoint style-scope yt-formatted-string"})
return Youtuber.text
def getview(div):
view1 = div.find("div", {"id":"metadata-line"})
view = view1.find("span", {"class":"style-scope ytd-video-meta-block"})
return view.text
def gettime(div):
time = div.findAll("span", {"class":"style-scope ytd-video-meta-block"})
return time[1].text
def gettitles(string):
bsObj = bs(string, "html.parser")
contents = bsObj.find("div", {"id" : "contents"})
divs = contents.findAll("div")
title = []
for div in divs:
title.append(gettitle(div))
return title
def getyoutubers(string):
bsObj = bs(string, "html.parser")
contents = bsObj.find("div", {"id" : "contents"})
divs = contents.findAll("div")
youtuber = []
for div in divs:
youtuber.append(getyoutuber(div))
return youtuber
def getviews(string):
bsObj = bs(string, "html.parser")
contents = bsObj.find("div", {"id" : "contents"})
divs = contents.findAll("div")
view = []
for div in divs:
view.append(getview(div))
return view
def gettimes(string):
bsObj = bs(string, "html.parser")
contents = bsObj.find("div", {"id" : "contents"})
divs = contents.findAll("div")
time = []
for div in divs:
time.append(gettime(div))
return time
| [
"noreply@github.com"
] | noreply@github.com |
8fa92d1105c004f189b6eced9adea6d7afe7208d | bb9a4f11e61e3b81bbf73912248c6e649d49ee48 | /venv/Lib/site-packages/pyowm/utils/geo.py | e15e019ebf2188ceffa3afd2ede2022b866a4fb5 | [
"MIT"
] | permissive | samuel-c/SlackBot-2020 | 0def47df1c4b499ce801e139f32767450a56bb2a | 2350fcfe63a52d5e64cc5b467e760be7a7cee6bf | refs/heads/master | 2020-12-21T22:48:53.516313 | 2020-02-06T01:55:51 | 2020-02-06T01:55:51 | 236,590,180 | 1 | 1 | MIT | 2020-02-05T05:03:04 | 2020-01-27T20:42:04 | Python | UTF-8 | Python | false | false | 13,215 | py |
import json
import math
import geojson
EARTH_RADIUS_KM = 6378.1
# utilities
def assert_is_lat(val):
"""
Checks it the given value is a feasible decimal latitude
:param val: value to be checked
:type val: int of float
:returns: `None`
:raises: *ValueError* if value is out of latitude boundaries, *AssertionError* if type is wrong
"""
assert type(val) is float or type(val) is int, "Value must be a number"
if val < -90.0 or val > 90.0:
raise ValueError("Latitude value must be between -90 and 90")
def assert_is_lon(val):
"""
Checks it the given value is a feasible decimal longitude
:param val: value to be checked
:type val: int of float
:returns: `None`
:raises: *ValueError* if value is out of longitude boundaries, *AssertionError* if type is wrong
"""
assert type(val) is float or type(val) is int, "Value must be a number"
if val < -180.0 or val > 180.0:
raise ValueError("Longitude value must be between -180 and 180")
# classes
class Geometry:
"""
Abstract parent class for geotypes
"""
def geojson(self):
"""
Returns a GeoJSON string representation of this geotype, compliant to
RFC 7946 (https://tools.ietf.org/html/rfc7946)
:return: str
"""
raise NotImplementedError()
def as_dict(self):
"""
Returns a dict representation of this geotype
:return: dict
"""
raise NotImplementedError()
class Point(Geometry):
"""
A Point geotype. Represents a single geographic point
:param lon: decimal longitude for the geopoint
:type lon: int of float
:param lat: decimal latitude for the geopoint
:type lat: int of float
:returns: a *Point* instance
:raises: *ValueError* when negative values are provided
"""
def __init__(self, lon, lat):
assert_is_lon(lon)
assert_is_lat(lat)
self._geom = geojson.Point((lon, lat))
@property
def lon(self):
return self._geom['coordinates'][0]
@property
def lat(self):
return self._geom['coordinates'][1]
def bounding_square_polygon(self, inscribed_circle_radius_km=10.0):
"""
Returns a square polygon (bounding box) that circumscribes the circle having this geopoint as centre and
having the specified radius in kilometers.
The polygon's points calculation is based on theory exposed by: http://janmatuschek.de/LatitudeLongitudeBoundingCoordinates
by Jan Philip Matuschek, owner of the intellectual property of such material.
In short:
- locally to the geopoint, the Earth's surface is approximated to a sphere with radius = Earth's radius
- the calculation works fine also when the bounding box contains the Earth's poles and the 180 deg meridian
:param inscribed_circle_radius_km: the radius of the inscribed circle, defaults to 10 kms
:type inscribed_circle_radius_km: int or float
:return: a `pyowm.utils.geo.Polygon` instance
"""
assert isinstance(inscribed_circle_radius_km, int) or isinstance(inscribed_circle_radius_km, float)
assert inscribed_circle_radius_km > 0., 'Radius must be greater than zero'
# turn metric distance to radians on the approximated local sphere
rad_distance = float(inscribed_circle_radius_km) / EARTH_RADIUS_KM
# calculating min/max lat for bounding box
bb_min_lat_deg = self.lat * math.pi/180. - rad_distance
bb_max_lat_deg = self.lat * math.pi/180. + rad_distance
# now checking for poles...
if bb_min_lat_deg > math.radians(-90) and bb_max_lat_deg < math.radians(90): # no poles in the bounding box
delta_lon = math.asin(math.sin(rad_distance) / math.cos(math.radians(self.lat)))
bb_min_lon_deg = math.radians(self.lon) - delta_lon
if bb_min_lon_deg < math.radians(-180):
bb_min_lon_deg += 2 * math.pi
bb_max_lon_deg = math.radians(self.lon) + delta_lon
if bb_max_lon_deg > math.radians(180):
bb_max_lon_deg -= 2 * math.pi
else: # a pole is contained in the bounding box
bb_min_lat_deg = max(bb_min_lat_deg, math.radians(-90))
bb_max_lat_deg = min(bb_max_lat_deg, math.radians(90))
bb_min_lon_deg = math.radians(-180)
bb_max_lon_deg = math.radians(180)
# turn back from radians to decimal
bb_min_lat = bb_min_lat_deg * 180./math.pi
bb_max_lat = bb_max_lat_deg * 180./math.pi
bb_min_lon = bb_min_lon_deg * 180./math.pi
bb_max_lon = bb_max_lon_deg * 180./math.pi
return Polygon([[
[bb_min_lon, bb_max_lat],
[bb_max_lon, bb_max_lat],
[bb_max_lon, bb_min_lat],
[bb_min_lon, bb_min_lat],
[bb_min_lon, bb_max_lat]
]])
def geojson(self):
return geojson.dumps(self._geom)
def as_dict(self):
return json.loads(self.geojson())
@classmethod
def from_dict(self, the_dict):
"""
Builds a Point instance out of a geoJSON compliant dict
:param the_dict: the geoJSON dict
:return: `pyowm.utils.geo.Point` instance
"""
geom = geojson.loads(json.dumps(the_dict))
result = Point(0, 0)
result._geom = geom
return result
def __repr__(self):
return "<%s.%s - lon=%s, lat=%s>" % (__name__, self.__class__.__name__, self.lon, self.lat)
class MultiPoint(Geometry):
"""
A MultiPoint geotype. Represents a set of geographic points
:param list_of_tuples: list of tuples, each one being the decimal (lon, lat) coordinates of a geopoint
:type list_of_tuples: list
:returns: a *MultiPoint* instance
"""
def __init__(self, list_of_tuples):
if not list_of_tuples:
raise ValueError("A MultiPoint cannot be empty")
for t in list_of_tuples:
assert_is_lon(t[0])
assert_is_lat(t[1])
self._geom = geojson.MultiPoint(list_of_tuples)
@classmethod
def from_points(cls, iterable_of_points):
"""
Creates a MultiPoint from an iterable collection of `pyowm.utils.geo.Point` instances
:param iterable_of_points: iterable whose items are `pyowm.utils.geo.Point` instances
:type iterable_of_points: iterable
:return: a *MultiPoint* instance
"""
return MultiPoint([(p.lon, p.lat) for p in iterable_of_points])
@property
def longitudes(self):
"""
List of decimal longitudes of this MultiPoint instance
:return: list of tuples
"""
return [coords[0] for coords in self._geom['coordinates']]
@property
def latitudes(self):
"""
List of decimal latitudes of this MultiPoint instance
:return: list of tuples
"""
return [coords[1] for coords in self._geom['coordinates']]
def geojson(self):
return geojson.dumps(self._geom)
def as_dict(self):
return json.loads(self.geojson())
@classmethod
def from_dict(self, the_dict):
"""
Builds a MultiPoint instance out of a geoJSON compliant dict
:param the_dict: the geoJSON dict
:return: `pyowm.utils.geo.MultiPoint` instance
"""
geom = geojson.loads(json.dumps(the_dict))
result = MultiPoint([(0, 0), (0, 0)])
result._geom = geom
return result
class Polygon(Geometry):
"""
A Polygon geotype. Each Polygon is made up by one or more lines: a line represents a set of connected geographic
points and is conveyed by a list of points, the last one of which must coincide with the its very first one.
As said, Polygons can be also made up by multiple lines (therefore, Polygons with "holes" are allowed)
:param list_of_lists: list of lists, each sublist being a line and being composed by tuples - each one being the
decimal (lon, lat) couple of a geopoint. The last point specified MUST coincide with the first one specified
:type list_of_tuples: list
:returns: a *MultiPoint* instance
:raises: *ValueError* when last point and fist point do not coincide or when no points are specified at all
"""
def __init__(self, list_of_lists):
for l in list_of_lists:
for t in l:
assert_is_lon(t[0])
assert_is_lat(t[1])
if not list_of_lists:
raise ValueError("A Polygon cannot be empty")
first, last = list_of_lists[0][0], list_of_lists[0][-1]
if not first == last:
raise ValueError("The start and end point of Polygon must coincide")
self._geom = geojson.Polygon(list_of_lists)
def geojson(self):
return geojson.dumps(self._geom)
def as_dict(self):
return json.loads(self.geojson())
@property
def points(self):
"""
Returns the list of *Point* instances representing the points of the polygon
:return: list of *Point* objects
"""
feature = geojson.Feature(geometry=self._geom)
points_coords = list(geojson.utils.coords(feature))
return [Point(p[0], p[1]) for p in points_coords]
@classmethod
def from_dict(self, the_dict):
"""
Builds a Polygon instance out of a geoJSON compliant dict
:param the_dict: the geoJSON dict
:return: `pyowm.utils.geo.Polygon` instance
"""
geom = geojson.loads(json.dumps(the_dict))
result = Polygon([[[0, 0], [0, 0]]])
result._geom = geom
return result
@classmethod
def from_points(cls, list_of_lists):
"""
Creates a *Polygon* instance out of a list of lists, each sublist being populated with
`pyowm.utils.geo.Point` instances
:param list_of_lists: list
:type: list_of_lists: iterable_of_polygons
:returns: a *Polygon* instance
"""
result = []
for l in list_of_lists:
curve = []
for point in l:
curve.append((point.lon, point.lat))
result.append(curve)
return Polygon(result)
class MultiPolygon(Geometry):
"""
A MultiPolygon geotype. Each MultiPolygon represents a set of (also djsjoint) Polygons. Each MultiPolygon is composed
by an iterable whose elements are the list of lists defining a Polygon geotype. Please refer to the
`pyowm.utils.geo.Point` documentation for details
:param iterable_of_list_of_lists: iterable whose elements are list of lists of tuples
:type iterable_of_list_of_lists: iterable
:returns: a *MultiPolygon* instance
:raises: *ValueError* when last point and fist point do not coincide or when no points are specified at all
"""
def __init__(self, iterable_of_list_of_lists):
if not iterable_of_list_of_lists:
raise ValueError("A MultiPolygon cannot be empty")
for list_of_lists in iterable_of_list_of_lists:
Polygon(list_of_lists)
self._geom = geojson.MultiPolygon(iterable_of_list_of_lists)
def geojson(self):
return geojson.dumps(self._geom)
def as_dict(self):
return json.loads(self.geojson())
@classmethod
def from_dict(self, the_dict):
"""
Builds a MultiPolygoninstance out of a geoJSON compliant dict
:param the_dict: the geoJSON dict
:return: `pyowm.utils.geo.MultiPolygon` instance
"""
geom = geojson.loads(json.dumps(the_dict))
result = MultiPolygon([
[[[0, 0], [0, 0]]],
[[[1, 1], [1, 1]]]
])
result._geom = geom
return result
@classmethod
def from_polygons(cls, iterable_of_polygons):
"""
Creates a *MultiPolygon* instance out of an iterable of Polygon geotypes
:param iterable_of_polygons: list of `pyowm.utils.geo.Point` instances
:type iterable_of_polygons: iterable
:returns: a *MultiPolygon* instance
"""
return MultiPolygon([polygon.as_dict()['coordinates'] for polygon in iterable_of_polygons])
class GeometryBuilder:
@classmethod
def build(cls, the_dict):
"""
Builds a `pyowm.utils.geo.Geometry` subtype based on the geoJSON geometry type specified on the input dictionary
:param the_dict: a geoJSON compliant dict
:return: a `pyowm.utils.geo.Geometry` subtype instance
:raises `ValueError` if unable to the geometry type cannot be recognized
"""
assert isinstance(the_dict, dict), 'Geometry must be a dict'
geom_type = the_dict.get('type', None)
if geom_type == 'Point':
return Point.from_dict(the_dict)
elif geom_type == 'MultiPoint':
return MultiPoint.from_dict(the_dict)
elif geom_type == 'Polygon':
return Polygon.from_dict(the_dict)
elif geom_type == 'MultiPolygon':
return MultiPolygon.from_dict(the_dict)
else:
raise ValueError('Unable to build a GeoType object: unrecognized geometry type')
| [
"42325107+Deep4569@users.noreply.github.com"
] | 42325107+Deep4569@users.noreply.github.com |
630c9af1fd5f87769d2cd87621e901ba2e383c7c | 99c4d4a6592fded0e8e59652484ab226ac0bd38c | /code/batch-2/dn13 - objektni minobot/M-17021-1547.py | e7ab6dbf8eecabc84d9990edc02404615aaba381 | [] | no_license | benquick123/code-profiling | 23e9aa5aecb91753e2f1fecdc3f6d62049a990d5 | 0d496d649247776d121683d10019ec2a7cba574c | refs/heads/master | 2021-10-08T02:53:50.107036 | 2018-12-06T22:56:38 | 2018-12-06T22:56:38 | 126,011,752 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,849 | py | class Minobot:
def __init__(self):
self.x=0
self.y=0
self.direction=90
self.tab=[]
def koordinate(self):
return self.x,self.y
def naprej(self, d):
self.tab.append(['naprej',d])
if self.direction == 0 or self.direction == 360:
self.y+=d
elif self.direction == 90 or self.direction == -90:
self.x+=d
elif self.direction == 180 or self.direction == -180:
self.y-=d
elif self.direction == 270 or self.direction == -270:
self.x-=d
def desno(self):
self.tab.append(['desno',90])
self.direction += 90
if self.direction >= 360:
self.direction = 0
def levo(self):
self.tab.append(['levo',-90])
self.direction -= 90
if self.direction <= 0:
self.direction = 360
def razdalja(self):
return abs(self.x)+abs(self.y)
def razveljavi(self):
print(self.tab)
if self.tab:
if self.tab[len(self.tab)-1][0] == 'naprej':
self.naprej(-(self.tab[len(self.tab)-1][1]))
elif self.tab[len(self.tab)-1][0] == 'desno':
self.levo()
elif self.tab[len(self.tab)-1][0] == 'levo':
self.desno()
self.tab.pop()
self.tab.pop()
import unittest
class TestObvezna(unittest.TestCase):
def test_minobot(self):
a = Minobot()
b = Minobot()
self.assertEqual(a.koordinate(), (0, 0))
self.assertEqual(b.koordinate(), (0, 0))
self.assertEqual(a.razdalja(), 0)
self.assertEqual(b.razdalja(), 0)
a.naprej(1)
self.assertEqual(a.koordinate(), (1, 0))
self.assertEqual(b.koordinate(), (0, 0))
self.assertEqual(a.razdalja(), 1)
self.assertEqual(b.razdalja(), 0)
a.naprej(2)
self.assertEqual(a.koordinate(), (3, 0))
self.assertEqual(b.koordinate(), (0, 0))
self.assertEqual(a.razdalja(), 3)
self.assertEqual(b.razdalja(), 0)
b.naprej(2)
self.assertEqual(a.koordinate(), (3, 0))
self.assertEqual(b.koordinate(), (2, 0))
self.assertEqual(a.razdalja(), 3)
self.assertEqual(b.razdalja(), 2)
a.desno() # zdaj je obrnjen dol
a.naprej(4)
self.assertEqual(a.koordinate(), (3, -4))
self.assertEqual(b.koordinate(), (2, 0))
self.assertEqual(a.razdalja(), 7)
self.assertEqual(b.razdalja(), 2)
a.desno() # obrnjen je levo
a.naprej(1)
self.assertEqual(a.koordinate(), (2, -4))
self.assertEqual(b.koordinate(), (2, 0))
self.assertEqual(a.razdalja(), 6)
self.assertEqual(b.razdalja(), 2)
a.desno() # obrnjen je gor
a.naprej(1)
self.assertEqual(a.koordinate(), (2, -3))
self.assertEqual(b.koordinate(), (2, 0))
self.assertEqual(a.razdalja(), 5)
self.assertEqual(b.razdalja(), 2)
a.desno() # obrnjen desno
a.naprej(3)
self.assertEqual(a.koordinate(), (5, -3))
self.assertEqual(b.koordinate(), (2, 0))
self.assertEqual(a.razdalja(), 8)
self.assertEqual(b.razdalja(), 2)
b.levo() # obrnjen gor
b.naprej(3)
self.assertEqual(b.koordinate(), (2, 3))
self.assertEqual(b.razdalja(), 5)
b.levo() # obrnjen levo
b.naprej(3)
self.assertEqual(b.koordinate(), (-1, 3))
self.assertEqual(b.razdalja(), 4)
a.naprej(5)
self.assertEqual(a.koordinate(), (10, -3))
self.assertEqual(a.razdalja(), 13)
class TestDodatna(unittest.TestCase):
def test_undo(self):
a = Minobot()
a.desno() # gleda dol
a.naprej(4)
a.levo() # gleda desno
a.naprej(1)
a.naprej(2)
self.assertEqual(a.koordinate(), (3, -4))
a.razveljavi()
self.assertEqual(a.koordinate(), (1, -4))
a.naprej(1)
self.assertEqual(a.koordinate(), (2, -4))
a.razveljavi()
self.assertEqual(a.koordinate(), (1, -4))
a.razveljavi()
self.assertEqual(a.koordinate(), (0, -4))
a.naprej(1)
self.assertEqual(a.koordinate(), (1, -4))
a.razveljavi()
self.assertEqual(a.koordinate(), (0, -4))
a.razveljavi() # spet gleda dol
self.assertEqual(a.koordinate(), (0, -4))
a.naprej(2)
self.assertEqual(a.koordinate(), (0, -6))
a.razveljavi()
self.assertEqual(a.koordinate(), (0, -4))
a.razveljavi()
self.assertEqual(a.koordinate(), (0, 0))
a.naprej(3)
self.assertEqual(a.koordinate(), (0, -3))
a.razveljavi()
self.assertEqual(a.koordinate(), (0, 0))
a.razveljavi() # spet gleda desno
self.assertEqual(a.koordinate(), (0, 0))
a.naprej(3)
self.assertEqual(a.koordinate(), (3, 0))
a.razveljavi()
self.assertEqual(a.koordinate(), (0, 0))
a.razveljavi() # se ne usuje
self.assertEqual(a.koordinate(), (0, 0))
a.naprej(2)
self.assertEqual(a.koordinate(), (2, 0))
a.razveljavi()
self.assertEqual(a.koordinate(), (0, 0))
a.razveljavi() # se ne usuje
self.assertEqual(a.koordinate(), (0, 0))
a.razveljavi() # se ne usuje
self.assertEqual(a.koordinate(), (0, 0))
a.razveljavi() # se ne usuje
self.assertEqual(a.koordinate(), (0, 0))
a.razveljavi() # se ne usuje
self.assertEqual(a.koordinate(), (0, 0))
if __name__ == "__main__":
unittest.main()
| [
"benjamin.fele@gmail.com"
] | benjamin.fele@gmail.com |
db528857acb2029c8fdeafbe7e33b01213e19c3b | 9dfda0c510b7a5c2511baf6620d33e722d9089ab | /config.py | cbc1c0d3350c49139cd98e1e4e8198725de297fe | [] | no_license | MikeWise2718/flask-mpld2 | 736a0f2a323084e35e064024016a9c8034ad00ca | 0227602da480361d67473b6bf6fc1a53d6853745 | refs/heads/master | 2022-12-07T02:31:19.465049 | 2020-08-27T11:17:33 | 2020-08-27T11:17:33 | 290,755,204 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 307 | py | # config.py
NODE_NAME = 'absol'
# Cosmos data base encdpoints - leaving this in here for now in case I need something like this
CDB_ENDPOINT = 'https://vafsp-cdb-sqlapi.documents.azure.com:443/',
CDB_PRIMARYKEY = 'Xt7s6YDIeph4ekvHzmjQQaWWrXB08W7A8Z0DVAYrJhw0WGcKiUSUlYAZfEM88NLQZyVJi5dRLNIXsD1g2u9Hlw==',
| [
"mwise@microsoft.com"
] | mwise@microsoft.com |
d4b371038a871ea6c4c51c8868534d2b5ff67817 | c333b3cfb05f4bc08a682ca5f4d70b212e9624ff | /punyty/objects.py | 45d95c22a7c1a12f50b8844fd42352e55fd3d51a | [
"MIT"
] | permissive | jsheedy/punyty | a450f7daaf9e8b2acf5d861ac258e07e762c46c6 | 34d5bffc4cf85985537e199567c5ba2aa9105a05 | refs/heads/master | 2020-05-09T19:58:37.665508 | 2019-12-25T18:22:00 | 2019-12-25T18:22:00 | 181,391,798 | 4 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,551 | py | from math import sqrt
import numpy as np
from .object3d import Object3D
class Tetrahedron(Object3D):
vertices = np.array([
[1, 1, 1],
[-1, -1, 1],
[1, -1, -1],
[-1, 1, -1],
], dtype=np.float64)
edges = (
(0, 1),
(1, 2),
(2, 3),
(1, 3),
(0, 2),
(0, 3),
)
polys = (
(0, 1, 2),
(0, 2, 3),
(0, 3, 1),
(3, 2, 1)
)
class Cube(Object3D):
vertices = np.array([
[1, 1, -1],
[-1, 1, -1],
[-1, -1, -1],
[1, -1, -1],
[1, 1, 1],
[-1, 1, 1],
[-1, -1, 1],
[1, -1, 1]
], dtype=np.float64)
edges = (
(0, 1),
(1, 2),
(2, 3),
(3, 0),
(4, 5),
(5, 6),
(6, 7),
(7, 4),
(0, 4),
(1, 5),
(2, 6),
(3, 7),
)
polys = (
(0, 1, 2),
(2, 3, 0),
(4, 7, 6),
(6, 5, 4),
(1, 5, 6),
(6, 2, 1),
(0, 3, 7),
(7, 4, 0),
(3, 2, 6),
(6, 7, 3),
(5, 1, 0),
(0, 4, 5),
)
class Octahedron(Object3D):
vertices = np.array([
[1, 0, 0],
[-1, 0, 0],
[0, 1, 0],
[0, -1, 0],
[0, 0, 1],
[0, 0, -1],
], dtype=np.float64)
edges = (
(0, 2),
(0, 3),
(0, 4),
(0, 5),
(1, 2),
(1, 3),
(1, 4),
(1, 5),
(2, 4),
(2, 5),
(3, 4),
(3, 5),
)
polys = (
(2, 4, 0),
(2, 0, 5),
(2, 5, 1),
(2, 1, 4),
(3, 0, 4),
(3, 5, 0),
(3, 1, 5),
(3, 4, 1),
)
class Dodecahedron(Object3D):
def __init__(self, **kwargs):
super().__init__(**kwargs)
# lay out as cube + 3 rects as on
# https://en.wikipedia.org/wiki/Regular_dodecahedron?oldformat=true#Cartesian_coordinates
phi = (1 + sqrt(5)) / 2
vertices = np.array([
# cube
[1, 1, 1],
[1, -1, 1],
[-1, -1, 1],
[-1, 1, 1],
[1, 1, -1],
[1, -1, -1],
[-1, -1, -1],
[-1, 1, -1],
[phi, 1/phi, 0],
[phi, -1/phi, 0],
[-phi, -1/phi, 0],
[-phi, 1/phi, 0],
[0, phi, 1/phi],
[0, phi, -1/phi],
[0, -phi, -1/phi],
[0, -phi, 1/phi],
[1/phi, 0, phi],
[1/phi, 0, -phi],
[-1/phi, 0, -phi],
[-1/phi, 0, phi]
], dtype=np.float64)
self.edges = (
# one r/g/b vertex for each cube corner vertex
(0, 8),
(0, 12),
(0, 16),
(1, 9),
(1, 15),
(1, 16),
(2, 10),
(2, 15),
(2, 19),
(3, 11),
(3, 12),
(3, 19),
(4, 8),
(4, 13),
(4, 17),
(5, 9),
(5, 14),
(5, 17),
(6, 10),
(6, 14),
(6, 18),
(7, 11),
(7, 13),
(7, 18),
# lace up the rects exterior edges
# r
(8, 9),
(10, 11),
# g
(12, 13),
(14, 15),
# b
(17, 18),
(19, 16)
)
self.vertices = self.to_homogenous_coords(vertices / (2*phi))
| [
"joseph.sheedy@gmail.com"
] | joseph.sheedy@gmail.com |
3b555d902fbfedb62e681121fb36f092cbbc0ef5 | 4e4218d4dfa5cd72c6855b3819cae20d6d9e2527 | /MatBuilder/processIago.py | b9e08936155919482512c1f0d34739e891bff9b0 | [] | no_license | boldstelvis/PocketStudio | 8d60241929cb8a9592138f12619ab8862bdee678 | 8229f9f9cfa5e5b9bbf546cddc061bae5234cd55 | refs/heads/master | 2023-03-20T08:06:02.722711 | 2021-03-03T16:22:39 | 2021-03-03T16:22:39 | 344,145,600 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 102 | py | import build
build.MatBuild('/Users/stuartaitken/Dropbox/Projects/RT_Destiny/Assets/Iago/textures')
| [
"bold.stelvis@gmail.com"
] | bold.stelvis@gmail.com |
190737f57812491eab4446e604fdb63bd82f089d | 2157782cf5875767f8d1fe0bb07243da2e87600d | /爬虫scrapy/demo/demo/settings.py | b03be2592fc5c78edd56253e6976c5315fe8d916 | [] | no_license | mouday/SomeCodeForPython | 9bc79e40ed9ed851ac11ff6144ea080020e01fcd | ddf6bbd8a5bd78f90437ffa718ab7f17faf3c34b | refs/heads/master | 2021-05-09T22:24:47.394175 | 2018-05-11T15:34:22 | 2018-05-11T15:34:22 | 118,750,143 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 3,104 | py | # -*- coding: utf-8 -*-
# Scrapy settings for demo project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
# http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
# http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html
BOT_NAME = 'demo'
SPIDER_MODULES = ['demo.spiders']
NEWSPIDER_MODULE = 'demo.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'demo (+http://www.yourdomain.com)'
# Obey robots.txt rules
ROBOTSTXT_OBEY = True
# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32
# Configure a delay for requests for the same website (default: 0)
# See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16
# Disable cookies (enabled by default)
#COOKIES_ENABLED = False
# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False
# Override the default request headers:
#DEFAULT_REQUEST_HEADERS = {
# 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
# 'Accept-Language': 'en',
#}
# Enable or disable spider middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
# 'demo.middlewares.DemoSpiderMiddleware': 543,
#}
# Enable or disable downloader middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# 'demo.middlewares.DemoDownloaderMiddleware': 543,
#}
# Enable or disable extensions
# See http://scrapy.readthedocs.org/en/latest/topics/extensions.html
#EXTENSIONS = {
# 'scrapy.extensions.telnet.TelnetConsole': None,
#}
# Configure item pipelines
# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html
#ITEM_PIPELINES = {
# 'demo.pipelines.DemoPipeline': 300,
#}
# Enable and configure the AutoThrottle extension (disabled by default)
# See http://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 http://scrapy.readthedocs.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'
| [
"pengshiyuyx@gmail.com"
] | pengshiyuyx@gmail.com |
d070578127809bf040bfcd1729dc053505ef1ce1 | 42afba2982753b5826d2cbbd402dc56e9d17f33c | /hyperwords/corpus2sgns_params.py | 24e5984464554bb6c34e3c96ee879bdedbc570c7 | [] | no_license | AlexanderRubinstein/InterpretableEmbeddings | c8431ef50f16b39e6f2fd64b68f154ac7476e711 | cd0d214aac410b1e93c40d50bb89d2d72c11b59c | refs/heads/master | 2022-03-28T03:23:16.398398 | 2019-12-21T20:01:56 | 2019-12-21T20:01:56 | 229,467,488 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,884 | py | from docopt import docopt
# noinspection PyListCreation
def main():
args = docopt("""
Usage:
corpus2sgns.sh [options] <corpus> <output_dir>
Options:
--thr NUM The minimal word count for being in the vocabulary [default: 100]
--win NUM Window size [default: 2]
--pos Positional contexts
--dyn Dynamic context windows
--sub NUM Subsampling threshold [default: 0]
--del Delete out-of-vocabulary and subsampled placeholders
--cds NUM Context distribution smoothing [default: 1.0]
--dim NUM Dimensionality of embeddings [default: 500]
--neg NUM Number of negative samples; subtracts its log from PMI [default: 1]
--w+c Use ensemble of word and context vectors
--cpu NUM The number of threads when training SGNS [default: 1]
""")
corpus = args['<corpus>']
output_dir = args['<output_dir>']
corpus2pairs_opts = []
corpus2pairs_opts.append('--thr ' + args['--thr'])
corpus2pairs_opts.append('--win ' + args['--win'])
if args['--pos']:
corpus2pairs_opts.append('--pos')
if args['--dyn']:
corpus2pairs_opts.append('--dyn')
corpus2pairs_opts.append('--sub ' + args['--sub'])
if args['--del']:
corpus2pairs_opts.append('--del')
word2vecf_opts = []
word2vecf_opts.append('-pow ' + args['--cds'])
word2vecf_opts.append('-size ' + args['--dim'])
word2vecf_opts.append('-negative ' + args['--neg'])
word2vecf_opts.append('-threads ' + args['--cpu'])
sgns2text_opts = []
if args['--w+c']:
sgns2text_opts.append('--w+c')
print '@'.join([
corpus,
output_dir,
' '.join(corpus2pairs_opts),
' '.join(word2vecf_opts),
' '.join(sgns2text_opts)
])
if __name__ == '__main__':
main()
| [
"rubalex14@gmail.com"
] | rubalex14@gmail.com |
75ccc5e971e7897820fb56e7d4c7130e5188c704 | b60d87e9818a336f5baf43764f242a5e015c84d8 | /rasa_dm/policies/ensemble.py | 2e98c9e92d0aa143901143effc008407fb2ffd0a | [] | no_license | mukesh-mehta/Chatbot | b3062e82cae07827847fdbad18bf1cc88aa9309d | 69864a5dd96aefaa6b4958fec0513186e6af2d3d | refs/heads/master | 2023-03-04T13:54:07.391881 | 2023-02-20T14:29:33 | 2023-02-20T14:29:33 | 114,714,602 | 4 | 10 | null | 2023-02-20T14:29:34 | 2017-12-19T03:27:07 | Python | UTF-8 | Python | false | false | 3,610 | py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import io
import json
import os
import numpy as np
import rasa_dm
from builtins import str
from rasa_dm.trackers import DialogueStateTracker
from rasa_dm.util import create_dir_for_file, class_from_module_path
from typing import Text, List, Optional
class PolicyEnsemble(object):
def __init__(self, policies):
self.policies = policies
def train(self, X, y, domain, featurizer, **kwargs):
for policy in self.policies:
policy.prepare(featurizer, X.shape[1])
policy.train(X, y, domain, **kwargs)
def predict_next_action(self, tracker, domain):
# type: (DialogueStateTracker, Domain) -> (float, int)
"""Predicts the next action the bot should take after seeing x.
This should be overwritten by more advanced policies to use ML to predict the action.
Returns the index of the next action"""
probabilities = self.probabilities_using_best_policy(tracker, domain)
max_index = np.argmax(probabilities)
return max_index
def probabilities_using_best_policy(self, tracker, domain):
raise NotImplementedError
def _persist_metadata(self, path, max_history):
# type: (Text, List[Text]) -> None
"""Persists the domain specification to storage."""
domain_spec_path = os.path.join(path, 'policy_metadata.json')
create_dir_for_file(domain_spec_path)
metadata = {
"rasa_core": rasa_dm.__version__,
"max_history": max_history,
"ensemble_name": self.__module__ + "." + self.__class__.__name__,
"policy_names": [p.__module__ + "." + p.__class__.__name__ for p in self.policies]
}
with io.open(domain_spec_path, 'w') as f:
f.write(str(json.dumps(metadata, indent=2)))
def persist(self, path):
# type: (Text) -> None
"""Persists the policy to storage."""
self._persist_metadata(path, self.policies[0].max_history if self.policies else None)
for policy in self.policies:
policy.persist(path)
@classmethod
def load_metadata(cls, path):
matadata_path = os.path.join(path, 'policy_metadata.json')
with io.open(matadata_path) as f:
metadata = json.loads(f.read())
return metadata
@classmethod
def load(cls, path, featurizer):
# type: (Text, Optional[Domain]) -> PolicyEnsemble
"""Loads policy and domain specification from storage"""
metadata = cls.load_metadata(path)
policies = []
for policy_name in metadata["policy_names"]:
policy = class_from_module_path(policy_name).load(path)
policy.featurizer = featurizer
policy.max_history = metadata["max_history"]
policies.append(policy)
ensemble = class_from_module_path(metadata["ensemble_name"])(policies)
return ensemble
class SimplePolicyEnsemble(PolicyEnsemble):
def __init__(self, policies):
super(SimplePolicyEnsemble, self).__init__(policies)
def probabilities_using_best_policy(self, tracker, domain):
result = None
max_confidence = -1
for p in self.policies:
probabilities = p.predict_action_probabilities(tracker, domain)
confidence = np.max(probabilities)
if confidence > max_confidence:
max_confidence = confidence
result = probabilities
return result
| [
"mkm96.ubt2014@iitr.ac.in"
] | mkm96.ubt2014@iitr.ac.in |
8c958e900b806f0503625aae951c03d030a5cea1 | ebd6f68d47e192da7f81c528312358cfe8052c8d | /swig/Examples/test-suite/python/template_typedef_cplx4_runme.py | 25ac851fbff3855719300e610179db627047c152 | [
"Apache-2.0",
"LicenseRef-scancode-swig",
"GPL-3.0-or-later",
"LicenseRef-scancode-unknown-license-reference",
"GPL-3.0-only"
] | permissive | inishchith/DeepSpeech | 965ad34d69eb4d150ddf996d30d02a1b29c97d25 | dcb7c716bc794d7690d96ed40179ed1996968a41 | refs/heads/master | 2021-01-16T16:16:05.282278 | 2020-05-19T08:00:33 | 2020-05-19T08:00:33 | 243,180,319 | 1 | 0 | Apache-2.0 | 2020-02-26T05:54:51 | 2020-02-26T05:54:50 | null | UTF-8 | Python | false | false | 431 | py | import string
from template_typedef_cplx4 import *
#
# this is OK
#
s = Sin()
s.get_base_value()
s.get_value()
s.get_arith_value()
my_func_r(s)
make_Multiplies_double_double_double_double(s, s)
z = CSin()
z.get_base_value()
z.get_value()
z.get_arith_value()
my_func_c(z)
make_Multiplies_complex_complex_complex_complex(z, z)
#
# Here we fail
#
d = make_Identity_double()
my_func_r(d)
c = make_Identity_complex()
my_func_c(c)
| [
"inishchith@gmail.com"
] | inishchith@gmail.com |
06491f782e441082256441de2f3aeea57b0a811b | 5d2033405239dd7e64b4229689ed83410b35f2dc | /src/network3.py | ac6405a49ce95d4d22cecef136171de2cc205f84 | [
"MIT"
] | permissive | mtasende/Neural-Networks-and-Deep-Learning-Nielsen | 860d8fefca52b38a423191b73f3b3178c2bc131d | 3e78ca22d20b53fd5d87ba5c7e33da4d9e8814a5 | refs/heads/master | 2021-01-13T03:09:16.552176 | 2016-12-27T00:50:26 | 2016-12-27T00:50:26 | 77,407,621 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 13,096 | py | """network3.py
~~~~~~~~~~~~~~
A Theano-based program for training and running simple neural
networks.
Supports several layer types (fully connected, convolutional, max
pooling, softmax), and activation functions (sigmoid, tanh, and
rectified linear units, with more easily added).
When run on a CPU, this program is much faster than network.py and
network2.py. However, unlike network.py and network2.py it can also
be run on a GPU, which makes it faster still.
Because the code is based on Theano, the code is different in many
ways from network.py and network2.py. However, where possible I have
tried to maintain consistency with the earlier programs. In
particular, the API is similar to network2.py. Note that I have
focused on making the code simple, easily readable, and easily
modifiable. It is not optimized, and omits many desirable features.
This program incorporates ideas from the Theano documentation on
convolutional neural nets (notably,
http://deeplearning.net/tutorial/lenet.html ), from Misha Denil's
implementation of dropout (https://github.com/mdenil/dropout ), and
from Chris Olah (http://colah.github.io ).
"""
#### Libraries
# Standard library
import cPickle
#import pickle as cPickle
import gzip
# Third-party libraries
import numpy as np
import theano
import theano.tensor as T
from theano.tensor.nnet import conv
from theano.tensor.nnet import softmax
from theano.tensor import shared_randomstreams
from theano.tensor.signal import downsample
# Activation functions for neurons
def linear(z): return z
def ReLU(z): return T.maximum(0.0, z)
from theano.tensor.nnet import sigmoid
from theano.tensor import tanh
#### Constants
GPU = False
if GPU:
print("Trying to run under a GPU. If this is not desired, then modify "+\
"network3.py\nto set the GPU flag to False.")
try: theano.config.device = 'gpu'
except: pass # it's already set
theano.config.floatX = 'float32'
else:
print("Running with a CPU. If this is not desired, then the modify "+\
"network3.py to set\nthe GPU flag to True.")
#### Load the MNIST data
def load_data_shared(filename="../data/mnist.pkl.gz"):
f = gzip.open(filename, 'rb')
training_data, validation_data, test_data = cPickle.load(f)
#training_data, validation_data, test_data = cPickle.load(f,fix_imports=True, encoding="bytes", errors="strict")
f.close()
def shared(data):
"""Place the data into shared variables. This allows Theano to copy
the data to the GPU, if one is available.
"""
shared_x = theano.shared(
np.asarray(data[0], dtype=theano.config.floatX), borrow=True)
shared_y = theano.shared(
np.asarray(data[1], dtype=theano.config.floatX), borrow=True)
return shared_x, T.cast(shared_y, "int32")
return [shared(training_data), shared(validation_data), shared(test_data)]
#### Main class used to construct and train networks
class Network(object):
def __init__(self, layers, mini_batch_size):
"""Takes a list of `layers`, describing the network architecture, and
a value for the `mini_batch_size` to be used during training
by stochastic gradient descent.
"""
self.layers = layers
self.mini_batch_size = mini_batch_size
self.params = [param for layer in self.layers for param in layer.params]
self.x = T.matrix("x")
self.y = T.ivector("y")
init_layer = self.layers[0]
init_layer.set_inpt(self.x, self.x, self.mini_batch_size)
for j in xrange(1, len(self.layers)):
prev_layer, layer = self.layers[j-1], self.layers[j]
layer.set_inpt(
prev_layer.output, prev_layer.output_dropout, self.mini_batch_size)
self.output = self.layers[-1].output
self.output_dropout = self.layers[-1].output_dropout
def SGD(self, training_data, epochs, mini_batch_size, eta,
validation_data, test_data, lmbda=0.0):
"""Train the network using mini-batch stochastic gradient descent."""
training_x, training_y = training_data
validation_x, validation_y = validation_data
test_x, test_y = test_data
# compute number of minibatches for training, validation and testing
num_training_batches = size(training_data)/mini_batch_size
num_validation_batches = size(validation_data)/mini_batch_size
num_test_batches = size(test_data)/mini_batch_size
# define the (regularized) cost function, symbolic gradients, and updates
l2_norm_squared = sum([(layer.w**2).sum() for layer in self.layers])
cost = self.layers[-1].cost(self)+\
0.5*lmbda*l2_norm_squared/num_training_batches
grads = T.grad(cost, self.params)
updates = [(param, param-eta*grad)
for param, grad in zip(self.params, grads)]
# define functions to train a mini-batch, and to compute the
# accuracy in validation and test mini-batches.
i = T.lscalar() # mini-batch index
train_mb = theano.function(
[i], cost, updates=updates,
givens={
self.x:
training_x[i*self.mini_batch_size: (i+1)*self.mini_batch_size],
self.y:
training_y[i*self.mini_batch_size: (i+1)*self.mini_batch_size]
})
validate_mb_accuracy = theano.function(
[i], self.layers[-1].accuracy(self.y),
givens={
self.x:
validation_x[i*self.mini_batch_size: (i+1)*self.mini_batch_size],
self.y:
validation_y[i*self.mini_batch_size: (i+1)*self.mini_batch_size]
})
test_mb_accuracy = theano.function(
[i], self.layers[-1].accuracy(self.y),
givens={
self.x:
test_x[i*self.mini_batch_size: (i+1)*self.mini_batch_size],
self.y:
test_y[i*self.mini_batch_size: (i+1)*self.mini_batch_size]
})
self.test_mb_predictions = theano.function(
[i], self.layers[-1].y_out,
givens={
self.x:
test_x[i*self.mini_batch_size: (i+1)*self.mini_batch_size]
})
# Do the actual training
best_validation_accuracy = 0.0
for epoch in xrange(epochs):
for minibatch_index in xrange(num_training_batches):
iteration = num_training_batches*epoch+minibatch_index
if iteration % 1000 == 0:
print("Training mini-batch number {0}".format(iteration))
cost_ij = train_mb(minibatch_index)
if (iteration+1) % num_training_batches == 0:
validation_accuracy = np.mean(
[validate_mb_accuracy(j) for j in xrange(num_validation_batches)])
print("Epoch {0}: validation accuracy {1:.2%}".format(
epoch, validation_accuracy))
if validation_accuracy >= best_validation_accuracy:
print("This is the best validation accuracy to date.")
best_validation_accuracy = validation_accuracy
best_iteration = iteration
if test_data:
test_accuracy = np.mean(
[test_mb_accuracy(j) for j in xrange(num_test_batches)])
print('The corresponding test accuracy is {0:.2%}'.format(
test_accuracy))
print("Finished training network.")
print("Best validation accuracy of {0:.2%} obtained at iteration {1}".format(
best_validation_accuracy, best_iteration))
print("Corresponding test accuracy of {0:.2%}".format(test_accuracy))
#### Define layer types
class ConvPoolLayer(object):
"""Used to create a combination of a convolutional and a max-pooling
layer. A more sophisticated implementation would separate the
two, but for our purposes we'll always use them together, and it
simplifies the code, so it makes sense to combine them.
"""
def __init__(self, filter_shape, image_shape, poolsize=(2, 2),
activation_fn=sigmoid):
"""`filter_shape` is a tuple of length 4, whose entries are the number
of filters, the number of input feature maps, the filter height, and the
filter width.
`image_shape` is a tuple of length 4, whose entries are the
mini-batch size, the number of input feature maps, the image
height, and the image width.
`poolsize` is a tuple of length 2, whose entries are the y and
x pooling sizes.
"""
self.filter_shape = filter_shape
self.image_shape = image_shape
self.poolsize = poolsize
self.activation_fn=activation_fn
# initialize weights and biases
n_out = (filter_shape[0]*np.prod(filter_shape[2:])/np.prod(poolsize))
self.w = theano.shared(
np.asarray(
np.random.normal(loc=0, scale=np.sqrt(1.0/n_out), size=filter_shape),
dtype=theano.config.floatX),
borrow=True)
self.b = theano.shared(
np.asarray(
np.random.normal(loc=0, scale=1.0, size=(filter_shape[0],)),
dtype=theano.config.floatX),
borrow=True)
self.params = [self.w, self.b]
def set_inpt(self, inpt, inpt_dropout, mini_batch_size):
self.inpt = inpt.reshape(self.image_shape)
conv_out = conv.conv2d(
input=self.inpt, filters=self.w, filter_shape=self.filter_shape,
image_shape=self.image_shape)
pooled_out = downsample.max_pool_2d(
input=conv_out, ds=self.poolsize, ignore_border=True)
self.output = self.activation_fn(
pooled_out + self.b.dimshuffle('x', 0, 'x', 'x'))
self.output_dropout = self.output # no dropout in the convolutional layers
class FullyConnectedLayer(object):
def __init__(self, n_in, n_out, activation_fn=sigmoid, p_dropout=0.0):
self.n_in = n_in
self.n_out = n_out
self.activation_fn = activation_fn
self.p_dropout = p_dropout
# Initialize weights and biases
self.w = theano.shared(
np.asarray(
np.random.normal(
loc=0.0, scale=np.sqrt(1.0/n_out), size=(n_in, n_out)),
dtype=theano.config.floatX),
name='w', borrow=True)
self.b = theano.shared(
np.asarray(np.random.normal(loc=0.0, scale=1.0, size=(n_out,)),
dtype=theano.config.floatX),
name='b', borrow=True)
self.params = [self.w, self.b]
def set_inpt(self, inpt, inpt_dropout, mini_batch_size):
self.inpt = inpt.reshape((mini_batch_size, self.n_in))
self.output = self.activation_fn(
(1-self.p_dropout)*T.dot(self.inpt, self.w) + self.b)
self.y_out = T.argmax(self.output, axis=1)
self.inpt_dropout = dropout_layer(
inpt_dropout.reshape((mini_batch_size, self.n_in)), self.p_dropout)
self.output_dropout = self.activation_fn(
T.dot(self.inpt_dropout, self.w) + self.b)
def accuracy(self, y):
"Return the accuracy for the mini-batch."
return T.mean(T.eq(y, self.y_out))
class SoftmaxLayer(object):
def __init__(self, n_in, n_out, p_dropout=0.0):
self.n_in = n_in
self.n_out = n_out
self.p_dropout = p_dropout
# Initialize weights and biases
self.w = theano.shared(
np.zeros((n_in, n_out), dtype=theano.config.floatX),
name='w', borrow=True)
self.b = theano.shared(
np.zeros((n_out,), dtype=theano.config.floatX),
name='b', borrow=True)
self.params = [self.w, self.b]
def set_inpt(self, inpt, inpt_dropout, mini_batch_size):
self.inpt = inpt.reshape((mini_batch_size, self.n_in))
self.output = softmax((1-self.p_dropout)*T.dot(self.inpt, self.w) + self.b)
self.y_out = T.argmax(self.output, axis=1)
self.inpt_dropout = dropout_layer(
inpt_dropout.reshape((mini_batch_size, self.n_in)), self.p_dropout)
self.output_dropout = softmax(T.dot(self.inpt_dropout, self.w) + self.b)
def cost(self, net):
"Return the log-likelihood cost."
return -T.mean(T.log(self.output_dropout)[T.arange(net.y.shape[0]), net.y])
def accuracy(self, y):
"Return the accuracy for the mini-batch."
return T.mean(T.eq(y, self.y_out))
#### Miscellanea
def size(data):
"Return the size of the dataset `data`."
return data[0].get_value(borrow=True).shape[0]
def dropout_layer(layer, p_dropout):
srng = shared_randomstreams.RandomStreams(
np.random.RandomState(0).randint(999999))
mask = srng.binomial(n=1, p=1-p_dropout, size=layer.shape)
return layer*T.cast(mask, theano.config.floatX)
| [
"miguel.tasende@gmail.com"
] | miguel.tasende@gmail.com |
8d8fdbe506c47f47787dd5aab4831c37f052bbab | 8bb9c2a39b586ec7f9ef630e557541ac7d754ba6 | /Mundo 2/Python_Exercicios/ex041.py | 06782808b41f220be2af4efeb4b3da7d647d5bf5 | [] | no_license | SirGuiL/Python | 390bd18ddb8af84271d72221314bb744f8af6e09 | 4a6c51a239548fc88788f71cc54184ef598c2584 | refs/heads/main | 2023-07-09T21:07:22.890943 | 2021-08-09T16:16:25 | 2021-08-09T16:16:25 | 383,320,224 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 463 | py | from datetime import date
ano = int(input('Digite seu ano de nascimento: '))
idade = date.today().year - ano
if(idade <= 9):
print('Você se encaixa na categoria mirim.')
elif(idade <= 14):
print('Você se encaixa na categoria infantil.')
elif(idade <= 19):
print('Você se encaixa na categoria junior.')
elif(idade == 20):
print('Você se encaixa na categoria sênior.')
else:
print('Você se encaixa na categoria master.')
a = input('a') | [
"guibiel-10@hotmail.com"
] | guibiel-10@hotmail.com |
9a91b60c24903f61054fed747c3be85c66cb2793 | 256f817910dd698970fab89871c6ce66a3c416e7 | /1. solvedProblems/340. Longest Substring with At Most K Distinct Characters/340.py | e1fd7e173bc2c9b114189909699c70c7543f9303 | [] | no_license | tgaochn/leetcode | 5926c71c1555d2659f7db4eff9e8cb9054ea9b60 | 29f1bd681ae823ec6fe755c8f91bfe1ca80b6367 | refs/heads/master | 2023-02-25T16:12:42.724889 | 2021-02-04T21:05:34 | 2021-02-04T21:05:34 | 319,225,860 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,982 | py | # !/usr/bin/env python
# coding: utf-8
"""
Author:
Tian Gao (tgaochn@gmail.com)
CreationDate:
Sat, 11/28/2020, 20:48
# !! Description:
"""
import sys
from typing import List
sys.path.append('..')
from utils import binaryTree, nTree, singleLinkedList
from utils.utils import (
printMatrix,
printDict,
printList,
isMatrix,
)
ListNode = singleLinkedList.ListNode
TreeNode = binaryTree.TreeNode
Node = nTree.Node
null = None
testCaseCnt = 6
# maxFuncInputParaCnt = 8
# !! step1: replace these two lines with the given code
class Solution:
def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int:
if not k or not s: return 0
from collections import deque
n = len(s)
l, r = 0, 0
win = deque()
self.freqHash = {}
# maxStr = ''
maxLen = -float('inf')
def isValidRlt():
return len(self.freqHash) <= k
def removeEle(ele):
if self.freqHash[ele] == 1:
del self.freqHash[ele]
else:
self.freqHash[ele] -= 1
def addEle(ele):
self.freqHash.setdefault(ele, 0)
self.freqHash[ele] += 1
while r < n:
if not isValidRlt():
eleL = win.popleft()
removeEle(eleL)
l += 1
else:
if len(win) > maxLen:
maxLen = len(win)
# maxStr = ''.join(list(win))
eleR = s[r]
win.append(eleR)
addEle(eleR)
r += 1
# while not maxStr and l < n:
while maxLen >= 0 and l < n:
if isValidRlt():
if len(win) > maxLen:
maxLen = len(win)
eleL = win.popleft()
removeEle(eleL)
l += 1
return maxLen
# endFunc
# endClass
def func():
# !! step2: change function name
s = Solution()
myFuncLis = [
s.lengthOfLongestSubstringKDistinct,
# optional: add another function for comparison
]
onlyDisplayError = True
enableInput = [True] * testCaseCnt
input = [None] * testCaseCnt
expectedRlt = [None] * testCaseCnt
# enableInput[0] = False
# enableInput[1] = False
# enableInput[2] = False
# enableInput[3] = False
# enableInput[4] = False
# enableInput[5] = False
# !! step3: change input para, input para can be found in "run code" - "test case"
# ! para1
input[0] = (
"eceba",
2,
# binaryTree.buildTree(None)
# singleLinkedList.buildSingleList(None)
# nTree.buildTree(None)
)
expectedRlt[0] = 3
# ! para2
input[1] = (
None
# binaryTree.buildTree(None),
# singleLinkedList.buildSingleList(None),
# nTree.buildTree(None),
)
expectedRlt[1] = None
# ! para3
input[2] = (
None
# singleLinkedList.buildSingleList(None),
# binaryTree.buildTree(None),
# nTree.buildTree(None),
)
expectedRlt[2] = None
# ! para4
input[3] = (
None
# singleLinkedList.buildSingleList(None),
# binaryTree.buildTree(None),
# nTree.buildTree(None),
)
expectedRlt[3] = None
# ! para5
input[4] = (
None
# singleLinkedList.buildSingleList(None),
# binaryTree.buildTree(None),
# nTree.buildTree(None),
)
expectedRlt[4] = None
# ! para6
input[5] = (
None
# singleLinkedList.buildSingleList(None),
# binaryTree.buildTree(None),
# nTree.buildTree(None),
)
expectedRlt[5] = None
# !! ====================================
# function and parameters count
allInput = [(input[i], enableInput[i], expectedRlt[i]) for i in range(testCaseCnt)]
if not input[0]:
print("ERROR: please assign at least one input for input[0]!")
exit()
funcParaCnt = 1 if not isinstance(input[0], tuple) else len(input[0])
funcCnt = len(myFuncLis)
# for each test case
for inputPara, enableInput, expectedRlt in allInput:
if not enableInput or not inputPara: continue
inputParaList = [None] * funcParaCnt
if not isinstance(inputPara, tuple):
inputPara = [inputPara]
for j in range(funcParaCnt):
inputParaList[j] = inputPara[j]
# for each function
for j in range(funcCnt):
print('==' * 20)
myFunc = myFuncLis[j]
# ! manually call function, max para count: 8
rlt = None
if funcParaCnt == 1:
rlt = myFunc(inputPara[0])
if funcParaCnt == 2:
rlt = myFunc(inputPara[0], inputPara[1])
if funcParaCnt == 3:
rlt = myFunc(inputPara[0], inputPara[1], inputPara[2])
if funcParaCnt == 4:
rlt = myFunc(inputPara[0], inputPara[1], inputPara[2], inputPara[3])
if funcParaCnt == 5:
rlt = myFunc(inputPara[0], inputPara[1], inputPara[2], inputPara[3], inputPara[4])
if funcParaCnt == 6:
rlt = myFunc(inputPara[0], inputPara[1], inputPara[2], inputPara[3], inputPara[4], inputPara[5])
if funcParaCnt == 7:
rlt = myFunc(inputPara[0], inputPara[1], inputPara[2], inputPara[3], inputPara[4], inputPara[5], inputPara[6])
if funcParaCnt == 8:
rlt = myFunc(inputPara[0], inputPara[1], inputPara[2], inputPara[3], inputPara[4], inputPara[5], inputPara[6], inputPara[7])
# only output when the result is not expected
if onlyDisplayError and expectedRlt is not None and expectedRlt == rlt: continue
# output function name
if funcCnt > 1:
print('func: \t%s' % myFunc.__name__)
# output para
for k in range(funcParaCnt):
para = inputParaList[k]
formatPrint('input %s:' % (k + 1), para)
# output result
print()
if not rlt:
print('rlt:\t', rlt)
else:
formatPrint('rlt:', rlt)
if expectedRlt is not None:
if not expectedRlt:
print('expRlt:\t', expectedRlt)
else:
formatPrint('expRlt:', expectedRlt)
print('==' * 20)
# endFunc
def isSpecialInstance(myInstance):
for curType in [TreeNode, Node]:
if isinstance(myInstance, curType):
return True
return False
# endFunc
def formatPrint(prefix, data):
if isMatrix(data):
print('%s' % prefix)
printMatrix(data)
else:
splitter = '\n' if isSpecialInstance(data) else '\t'
print('%s%s%s' % (prefix, splitter, data))
# endFunc
def main():
func()
# endMain
if __name__ == "__main__":
main()
# endIf
| [
"tgaochn@gmail.com"
] | tgaochn@gmail.com |
b67b5e6d66ad477d22a129a6bb6faf2a37a69867 | ad846a63f010b808a72568c00de016fbe86d6c35 | /algotradingenv/lib/python3.8/site-packages/IPython/external/decorators/_numpy_testing_noseclasses.py | 9f8f382391de958a20ccb9a35664f5c7c66ba463 | [] | no_license | krishansinghal29/algotrade | 74ee8b1c9113812b1c7c00ded95d966791cf76f5 | 756bc2e3909558e9ae8b2243bb4dabc530f12dde | refs/heads/master | 2023-06-02T01:53:24.924672 | 2021-06-10T09:17:55 | 2021-06-10T09:17:55 | 375,641,074 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,417 | py | # IPython: modified copy of numpy.testing.noseclasses, so
# IPython.external._decorators works without numpy being installed.
# These classes implement a "known failure" error class.
import os
from nose.plugins.errorclass import ErrorClass, ErrorClassPlugin
class KnownFailureTest(Exception):
"""Raise this exception to mark a test as a known failing test."""
pass
class KnownFailure(ErrorClassPlugin):
"""Plugin that installs a KNOWNFAIL error class for the
KnownFailureClass exception. When KnownFailureTest is raised,
the exception will be logged in the knownfail attribute of the
result, 'K' or 'KNOWNFAIL' (verbose) will be output, and the
exception will not be counted as an error or failure."""
enabled = True
knownfail = ErrorClass(KnownFailureTest, label="KNOWNFAIL", isfailure=False)
def options(self, parser, env=os.environ):
env_opt = "NOSE_WITHOUT_KNOWNFAIL"
parser.add_option(
"--no-knownfail",
action="store_true",
dest="noKnownFail",
default=env.get(env_opt, False),
help="Disable special handling of KnownFailureTest " "exceptions",
)
def configure(self, options, conf):
if not self.can_configure:
return
self.conf = conf
disable = getattr(options, "noKnownFail", False)
if disable:
self.enabled = False
| [
"krishansinghal29@gmail.com"
] | krishansinghal29@gmail.com |
c54b5c58d02b449322e21a4c7e7645c6e992197f | 3150a03e5c0e3897b91472b750ab1de9751138c5 | /ppdet/metrics/mot_eval_utils.py | 8b0a03a13027995e2644cfa1159768faed8b1299 | [
"Apache-2.0"
] | permissive | lazyand/ccccAI | 95c66c7c732b3a447330acd7456e76e3e6152e8c | 2d279a0ef261d10ef051b3685e041223193f81b5 | refs/heads/main | 2023-07-01T12:27:05.361219 | 2021-08-02T10:35:22 | 2021-08-02T10:35:22 | 407,152,836 | 1 | 0 | Apache-2.0 | 2021-09-16T12:17:22 | 2021-09-16T12:17:22 | null | UTF-8 | Python | false | false | 6,589 | py | # Copyright (c) 2021 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.
import os
import numpy as np
import copy
import motmetrics as mm
mm.lap.default_solver = 'lap'
__all__ = [
'read_mot_results',
'unzip_objs',
'MOTEvaluator',
]
def read_mot_results(filename, is_gt=False, is_ignore=False):
valid_labels = {1}
ignore_labels = {2, 7, 8, 12}
results_dict = dict()
if os.path.isfile(filename):
with open(filename, 'r') as f:
for line in f.readlines():
linelist = line.split(',')
if len(linelist) < 7:
continue
fid = int(linelist[0])
if fid < 1:
continue
results_dict.setdefault(fid, list())
box_size = float(linelist[4]) * float(linelist[5])
if is_gt:
if 'MOT16-' in filename or 'MOT17-' in filename or 'MOT15-' in filename or 'MOT20-' in filename:
label = int(float(linelist[7]))
mark = int(float(linelist[6]))
if mark == 0 or label not in valid_labels:
continue
score = 1
elif is_ignore:
if 'MOT16-' in filename or 'MOT17-' in filename or 'MOT15-' in filename or 'MOT20-' in filename:
label = int(float(linelist[7]))
vis_ratio = float(linelist[8])
if label not in ignore_labels and vis_ratio >= 0:
continue
else:
continue
score = 1
else:
score = float(linelist[6])
tlwh = tuple(map(float, linelist[2:6]))
target_id = int(linelist[1])
results_dict[fid].append((tlwh, target_id, score))
return results_dict
"""
labels={'ped', ... % 1
'person_on_vhcl', ... % 2
'car', ... % 3
'bicycle', ... % 4
'mbike', ... % 5
'non_mot_vhcl', ... % 6
'static_person', ... % 7
'distractor', ... % 8
'occluder', ... % 9
'occluder_on_grnd', ... % 10
'occluder_full', ... % 11
'reflection', ... % 12
'crowd' ... % 13
};
"""
def unzip_objs(objs):
if len(objs) > 0:
tlwhs, ids, scores = zip(*objs)
else:
tlwhs, ids, scores = [], [], []
tlwhs = np.asarray(tlwhs, dtype=float).reshape(-1, 4)
return tlwhs, ids, scores
class MOTEvaluator(object):
def __init__(self, data_root, seq_name, data_type):
self.data_root = data_root
self.seq_name = seq_name
self.data_type = data_type
self.load_annotations()
self.reset_accumulator()
def load_annotations(self):
assert self.data_type == 'mot'
gt_filename = os.path.join(self.data_root, self.seq_name, 'gt',
'gt.txt')
self.gt_frame_dict = read_mot_results(gt_filename, is_gt=True)
self.gt_ignore_frame_dict = read_mot_results(
gt_filename, is_ignore=True)
def reset_accumulator(self):
self.acc = mm.MOTAccumulator(auto_id=True)
def eval_frame(self, frame_id, trk_tlwhs, trk_ids, rtn_events=False):
# results
trk_tlwhs = np.copy(trk_tlwhs)
trk_ids = np.copy(trk_ids)
# gts
gt_objs = self.gt_frame_dict.get(frame_id, [])
gt_tlwhs, gt_ids = unzip_objs(gt_objs)[:2]
# ignore boxes
ignore_objs = self.gt_ignore_frame_dict.get(frame_id, [])
ignore_tlwhs = unzip_objs(ignore_objs)[0]
# remove ignored results
keep = np.ones(len(trk_tlwhs), dtype=bool)
iou_distance = mm.distances.iou_matrix(
ignore_tlwhs, trk_tlwhs, max_iou=0.5)
if len(iou_distance) > 0:
match_is, match_js = mm.lap.linear_sum_assignment(iou_distance)
match_is, match_js = map(lambda a: np.asarray(a, dtype=int), [match_is, match_js])
match_ious = iou_distance[match_is, match_js]
match_js = np.asarray(match_js, dtype=int)
match_js = match_js[np.logical_not(np.isnan(match_ious))]
keep[match_js] = False
trk_tlwhs = trk_tlwhs[keep]
trk_ids = trk_ids[keep]
# get distance matrix
iou_distance = mm.distances.iou_matrix(gt_tlwhs, trk_tlwhs, max_iou=0.5)
# acc
self.acc.update(gt_ids, trk_ids, iou_distance)
if rtn_events and iou_distance.size > 0 and hasattr(self.acc,
'last_mot_events'):
events = self.acc.last_mot_events # only supported by https://github.com/longcw/py-motmetrics
else:
events = None
return events
def eval_file(self, filename):
self.reset_accumulator()
result_frame_dict = read_mot_results(filename, is_gt=False)
frames = sorted(list(set(result_frame_dict.keys())))
for frame_id in frames:
trk_objs = result_frame_dict.get(frame_id, [])
trk_tlwhs, trk_ids = unzip_objs(trk_objs)[:2]
self.eval_frame(frame_id, trk_tlwhs, trk_ids, rtn_events=False)
return self.acc
@staticmethod
def get_summary(accs,
names,
metrics=('mota', 'num_switches', 'idp', 'idr', 'idf1',
'precision', 'recall')):
names = copy.deepcopy(names)
if metrics is None:
metrics = mm.metrics.motchallenge_metrics
metrics = copy.deepcopy(metrics)
mh = mm.metrics.create()
summary = mh.compute_many(
accs, metrics=metrics, names=names, generate_overall=True)
return summary
@staticmethod
def save_summary(summary, filename):
import pandas as pd
writer = pd.ExcelWriter(filename)
summary.to_excel(writer)
writer.save()
| [
"1429392157@qq.com"
] | 1429392157@qq.com |
27ccdbea81862874e0b78a77232a7d471e5f184a | 6fa7f99d3d3d9b177ef01ebf9a9da4982813b7d4 | /Av2u6FKvzFvrtGEKS_18.py | 4e2d4cf4fdcb9ad90f1ec69e7cba9c1c762d567b | [] | no_license | daniel-reich/ubiquitous-fiesta | 26e80f0082f8589e51d359ce7953117a3da7d38c | 9af2700dbe59284f5697e612491499841a6c126f | refs/heads/master | 2023-04-05T06:40:37.328213 | 2021-04-06T20:17:44 | 2021-04-06T20:17:44 | 355,318,759 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 846 | py |
# Do not touch this starter code but implement the reverse function at the
# end of the LinkedList class
class Node(object):
def __init__(self, data):
self.data = data
self.next = None
class LinkedList(object):
def __init__(self):
self.head = None
self.tail = None
def insert(self, data):
new_node = Node(data)
if self.head == None:
self.head = self.tail = new_node
else:
self.tail.next = new_node
self.tail = new_node
def traverse(self):
if self.head == None:
return []
temp = self.head
result = []
while temp!=None:
result.append(temp.data)
temp = temp.next
return result
def reverse(self):
nodes = self.traverse()
self.head = self.tail = None
while nodes:
self.insert(nodes.pop(-1))
| [
"daniel.reich@danielreichs-MacBook-Pro.local"
] | daniel.reich@danielreichs-MacBook-Pro.local |
2a6923ba26403d7e7ea8efed70b9bcf624239f60 | 3a031452d9abbeb16fb3f5592245aa1bf0a6c883 | /WeatherApp.py | 5e7896d65734edc0daa71b12abe37c189960bb7d | [] | no_license | Anam0609/WeatherApp | a0285ed409678603e169df3544d7bc768109607d | 23a6b635486e2e5b20430057d0630122a291e14f | refs/heads/master | 2022-11-30T01:47:43.959224 | 2020-08-11T10:30:21 | 2020-08-11T10:30:21 | 286,714,959 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,128 | py | import tkinter as tk
import requests
from PIL import Image, ImageTk
# setting the window size
theheight = 500
thewidth = 800
# "https://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=7f65701f025236c354d7754c5a4e0b71";
def get_weather(city):
weatherkey = '7f65701f025236c354d7754c5a4e0b71'
url = 'https://api.openweathermap.org/data/2.5/weather'
# api.openweathermap.org/data/2.5/weather?q={city name},{state code}&appid={7f65701f025236c354d7754c5a4e0b71}
params1 = {'appid': weatherkey, 'q': city, 'units': 'Metric'}
response = requests.get(url, params=params1)
weather = response.json()
print(weather)
mylabel['text'] = displayingoutput(weather)
icon_name = weather["weather"][0]["icon"]
weather_image(icon_name)
def weather_image(icon):
size = int(second_frame.winfo_height() * 0.25)
img = ImageTk.PhotoImage(Image.open("./img/" + icon + ".png").resize((size, size)))
weather_icon.delete("all")
weather_icon.create_image(0, 0, anchor="nw", image=img)
weather_icon.image = img
def displayingoutput(weather):
try:
name = weather['name']
count = weather['sys']['country']
desc = weather['weather'][0]['description']
temp = weather['main']['temp']
humid = weather['main']['humidity']
result = 'Name of Town: %s \nCountry: %s \nWeather Description: %s \nHumidity: %s \nTemperature (oC)): %s' % (
name, count, desc, humid, temp)
except:
error = "Retrieving data failed"
return result
def clearing():
mylabel.config(text="")
entry.getvar("")
window = tk.Tk()
window.title("Weather app")
canvas = tk.Canvas(window, height=theheight, width=thewidth)
# ===================================================================================
background_image = ImageTk.PhotoImage(file='weather.jpg')
background_label = tk.Label(window, image=background_image)
background_label.place(relwidth=1, relheight=1)
# ======================================================================================
canvas.pack()
# background_label.pack(relwidth=1, relheight=1)
frame = tk.Frame(window, bg='#3366ff', bd=5)
frame.place(relx=0.5, rely=0.1, relwidth=0.75, relheight=0.1, anchor='n')
# textbox to enter the input city
entry = tk.Entry(frame, font=30)
entry.place(relwidth=0.65, relheight=1)
# button to invoke the weather API
myButton = tk.Button(frame, text="Get Weather", font=('arial', 20), bg="#3366ff", fg='#fff',
command=lambda: get_weather(entry.get()))
myButton.pack(side="right")
second_frame = tk.Frame(window, bg='#3366ff', bd=10)
second_frame.place(relx=0.5, rely=0.25, relwidth=0.75, relheight=0.6, anchor='n', )
mylabel = tk.Label(second_frame, font=40, bd=10, anchor='nw', justify='left')
mylabel.place(relwidth=1, relheight=1)
myclearButton = tk.Button(window, text="Clear", font=('arial', 20), bg="#3366ff", fg='#fff', command=clearing)
myclearButton.pack(side='bottom')
weather_icon = tk.Canvas(mylabel, bg="white", bd=0, highlightthickness=0)
weather_icon.place(relx=.75, rely=0, relwidth=1, relheight=0.5)
window.mainloop()
| [
"biancamajikijela95@gmail.com"
] | biancamajikijela95@gmail.com |
84f11466840388f7cd822464925153da45672a52 | 3d870343f388fcd24be17be87f9c31a8267725e6 | /feature_1.py | d7b90d46cec24099222a0979c929053c320e8da6 | [] | no_license | jhaubrich/test_repo | bd29b6238cf2771bf241664d50be8e20e950297b | 6f58bf8ce8cdffa4e3fcc16fedde1f376bc889b3 | refs/heads/master | 2016-09-09T23:03:27.877455 | 2012-12-17T15:15:01 | 2012-12-17T15:15:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 35 | py | #!/usr/bin/env
import antigravity
| [
"jesse.ctr.haubrich@faa.gov"
] | jesse.ctr.haubrich@faa.gov |
03f78e02bcb35721419e9b22592c1ff69b8001ee | e902ce7156544420a18e838ff80b7fada60fee6f | /auctions/migrations/0016_remove_listing_winner.py | 15b188088a4409ebace540badb2a9078a1921a47 | [] | no_license | martyanovandrey/Auctions | 4e45a48b044055f3ac35cbc23c6d95f6dc2094b7 | 58c70857b10c070162e496bf8da0227efedf85bd | refs/heads/master | 2023-06-25T02:26:04.015361 | 2021-07-28T17:39:06 | 2021-07-28T17:39:06 | 297,530,574 | 0 | 0 | null | 2020-10-18T19:11:44 | 2020-09-22T03:59:56 | Python | UTF-8 | Python | false | false | 328 | py | # Generated by Django 3.1 on 2020-10-16 19:57
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('auctions', '0015_auto_20201016_2256'),
]
operations = [
migrations.RemoveField(
model_name='listing',
name='winner',
),
]
| [
"37772440+martyanovandrey@users.noreply.github.com"
] | 37772440+martyanovandrey@users.noreply.github.com |
584f70937fd6dd88eaa1f8f64e86437ca7008d88 | 54f352a242a8ad6ff5516703e91da61e08d9a9e6 | /Source Codes/AtCoder/arc026/A/4566526.py | ac69b81f3ed3647b8383cbae78a92382afa0955c | [] | no_license | Kawser-nerd/CLCDSA | 5cbd8a4c3f65173e4e8e0d7ed845574c4770c3eb | aee32551795763b54acb26856ab239370cac4e75 | refs/heads/master | 2022-02-09T11:08:56.588303 | 2022-01-26T18:53:40 | 2022-01-26T18:53:40 | 211,783,197 | 23 | 9 | null | null | null | null | UTF-8 | Python | false | false | 61 | py | n,a,b=map(int,input().split());print(min(n,5)*b+max(n-5,0)*a) | [
"kwnafi@yahoo.com"
] | kwnafi@yahoo.com |
188b7d197ab77782771d8705118397eb1aae428b | 4724e33369de6f39cc7f7b1b3a7398e6080cc8f8 | /blog/views.py | 052f490f53deb4da1a222f23ce7deb930555463f | [] | no_license | aylensp/first-blog | cc28db61b5ef7d0a5d2fa1c0d58ddf1ab8aafbcd | 10bdd1725dac00ae1bdb705c284e89d2e78f880b | refs/heads/master | 2021-05-05T23:28:05.134950 | 2018-01-12T15:20:48 | 2018-01-12T15:20:48 | 116,718,084 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,826 | py | from django.contrib.auth.decorators import login_required
from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from .forms import PostForm, CommentForm
from .models import Post, Comment
# Create your views here.
def post_list(request):
posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
return render(request, 'blog/post_list.html', {'posts': posts})
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'blog/post_detail.html', {'post': post})
@login_required
def post_new(request):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.autor = request.user
# post.published_date = timezone.now()
post.save()
return redirect('post_detail', pk=post.pk)
else:
form = PostForm()
return render(request, 'blog/post_edit.html', {'form': form})
@login_required
def post_edit(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == "POST":
form = PostForm(request.POST, instance=post)
if form.is_valid():
post = form.save(commit=False)
post.autor = request.user
post.save()
return redirect('post_detail', pk=post.pk)
else:
form = PostForm(instance=post)
return render(request, 'blog/post_edit.html', {'form': form})
@login_required
def post_draft_list(request):
posts = Post.objects.filter(published_date__isnull=True).order_by('created_date')
return render(request, 'blog/post_draft_list.html', {'posts': posts})
@login_required
def post_publish(request, pk):
post = get_object_or_404(Post, pk=pk)
post.publish()
return redirect('post_detail', pk=post.pk)
@login_required
def post_remove(request, pk):
post = get_object_or_404(Post, pk=pk)
post.delete()
return redirect('post_list')
def add_comment_to_post(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.save()
return redirect('post_detail', pk=post.pk)
else:
form = CommentForm()
return render(request, 'blog/add_comment_to_post.html', {'form': form})
@login_required
def comment_approve(request, pk):
comment = get_object_or_404(Comment, pk=pk)
comment.approve()
return redirect('post_detail', pk=comment.post.pk)
@login_required
def comment_remove(request, pk):
comment = get_object_or_404(Comment, pk=pk)
comment.delete()
return redirect('post_detail', pk=comment.post.pk)
| [
"aylenpresentado@gmail.com"
] | aylenpresentado@gmail.com |
b3de9af0ea9ab10667ea7729377fab15baf9230e | def6bf52f6c01029e2c83b848b90e8b7d9f7abde | /.venv/bin/django-admin | 4a1cb14fc2c10455db411ffc85ac2f7b4507587e | [
"MIT"
] | permissive | JayB-Kayode/practice-python-and-django | c3e82bc841bd3d2aa7194cb4077f96cc5546713c | c92333965aeb28de336694c9c289278fa275918d | refs/heads/master | 2021-01-01T15:22:45.355145 | 2017-07-27T02:06:36 | 2017-07-27T02:06:36 | 97,606,980 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 318 | #!/home/jb/Documents/git/practice-python-and-django/.venv/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from django.core.management import execute_from_command_line
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(execute_from_command_line())
| [
"jdickewu@gmail.com"
] | jdickewu@gmail.com | |
366e5b6c1921361a7577480414955fd30e18ee39 | 0547c3ebab814e3fdf2616ae63f8f6c87a0ff6c5 | /846.hand-of-straights.py | 1efee8792025199a30b3260fd14120bab6d55e5d | [] | no_license | livepo/lc | b8792d2b999780af5d5ef3b6050d71170a272ca6 | 605d19be15ece90aaf09b994098716f3dd84eb6a | refs/heads/master | 2020-05-15T03:57:15.367240 | 2019-07-30T03:11:46 | 2019-07-30T03:11:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 169 | py | class Solution(object):
def isNStraightHand(self, hand, W):
"""
:type hand: List[int]
:type W: int
:rtype: bool
"""
| [
"qgmfky@gmail.com"
] | qgmfky@gmail.com |
93a07c1afd9c37dc9445fbf0acf76b1f042adfaa | 40cf4ad79c2e61ee7c1dbafc78449e4add6ba8ac | /Main.py | 265f644f5f6cc0c2189acd83c8cd33a5eabcb8c3 | [
"MIT"
] | permissive | Starrky/Problems-checker | d6bb06d5b01b0eb8ae44157a154b8d5e8b884d65 | be4c91e7c7190e12ff465c0da5a60812057f35bb | refs/heads/main | 2023-03-20T00:10:53.177760 | 2021-03-01T21:37:18 | 2021-03-01T21:37:18 | 333,546,342 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,106 | py | import configs as cfgs
import selenium
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
import glob
import os
import os.path
from os import path
import time
import csv
import openpyxl
from openpyxl import Workbook
from openpyxl import load_workbook
from os import listdir
from os.path import isfile, join
from itertools import chain
""" SPECIFY SHEETNAMES HERE """
countries_folder = cfgs.Countries_folder
onlyfiles = [f for f in listdir(countries_folder) if isfile(join(countries_folder, f))]
# Sheetnames with POS/ BOS data in excel files
sheets = cfgs.zbx_sheets
# Paths and links setup
problems_link = cfgs.zbx_problems_link
zbx = cfgs.zbx_link
username = cfgs.zbx_username
password = cfgs.zbx_password
download_loc = cfgs.download_loc
countries_folder = cfgs.Countries_folder
filename = 'zbx_problems_export.csv'
report_file = f'{download_loc}{filename}'
# Delete old zbx problems export file
files = glob.glob(f"{download_loc}*")
for f in files:
os.remove(f)
# Webdriver setup
options = webdriver.ChromeOptions()
options.add_argument('ignore-certificate-errors')
options.add_argument("--headless")
prefs = {"download.default_directory": download_loc}
options.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome(
ChromeDriverManager().install(), options=options)
# Fetching file
driver.get(problems_link)
driver.find_element_by_id("login").click()
driver.find_element_by_id("name").send_keys(username)
driver.find_element_by_id("password").send_keys(password)
driver.find_element_by_id("enter").click()
driver.find_element_by_xpath(
"/html/body/main/div[1]/div[2]/nav/form/ul/li[1]/button").click()
# Check if file was downloaded and close driver
time.sleep(5)
while path.exists(report_file) is False:
continue
else:
driver.close()
# Process the file and make dictionaries from hosts with issues
BOS = []
POS1 = []
POS2 = []
POS3 = []
POS4 = []
mapping = {}
with open(report_file) as fo:
reader = csv.DictReader(fo)
for row in reader:
mapping[row["Host"]] = row["Problem"]
for key, value in mapping.items():
if value == "BOS is unavailable by ICMP":
BOS.append(key)
if value == "POS1 is unavailable by ICMP":
POS1.append(key)
if value == "POS2 is unavailable by ICMP":
POS2.append(key)
if value == "POS3 is unavailable by ICMP":
POS3.append(key)
if value == "POS4 is unavailable by ICMP":
POS4.append(key)
print(f'\n\n *** OFFLINE DEVICES SUMMARY ***\n\nPOS1 offline for: {BOS}\n\nPOS2 offline for: {POS1}'
f'\n\nPOS3 offline for: {POS2}\n\nPOS4 offline for: {POS3}\n\nBOS offline for: {POS4}')
# Read country file and change columns showing status of devices
for file in onlyfiles:
wb = load_workbook(f'{cfgs.Countries_folder}{file}')
worksheets = wb.sheetnames
for sheet in worksheets:
if sheet in sheets:
ws = wb[sheet]
# print(file)
else:
pass
# Iterate over all rows in excel file
for row in ws.iter_rows(min_row=2, min_col=2, max_col=2):
for cell in row:
store = str(cell.value).zfill(4)
BOS_name = ws[f'E{cell.row}'].value
POS1_name = ws[f'G{cell.row}'].value
POS2_name = ws[f'I{cell.row}'].value
POS3_name = ws[f'K{cell.row}'].value
POS4_name = ws[f'M{cell.row}'].value
# Change all to OK
ws[f'F{cell.row}'] = 'ok'
ws[f'H{cell.row}'] = 'ok'
ws[f'J{cell.row}'] = 'ok'
ws[f'L{cell.row}'] = 'ok'
ws[f'N{cell.row}'] = 'ok'
# Check dictionaries
if store in BOS and BOS_name != 'brak':
ws[f'F{cell.row}'] = 'failed'
# print(f'BOS offline for {store}')
elif store in POS1 and POS1_name != 'brak':
ws[f'H{cell.row}'] = 'failed'
# print(f'POS1 offline for {store}')
elif store in POS2 and POS2_name != 'brak':
ws[f'J{cell.row}'] = 'failed'
# print(f'POS2 offline for {store}')
elif store in POS3 and POS3_name != 'brak':
ws[f'L{cell.row}'] = 'failed'
# print(f'POS3 offline for {store}')
elif store in POS4 and POS4_name != 'brak':
ws[f'N{cell.row}'] = 'failed'
# print(f'POS4 offline for {store}')
# Braki
elif POS1_name == 'brak':
ws[f'H{cell.row}'] = 'brak'
# print(f'POS4 offline for {store}')
elif POS2_name == 'brak':
ws[f'J{cell.row}'] = 'brak'
# print(f'POS4 offline for {store}')
elif POS3_name == 'brak':
ws[f'L{cell.row}'] = 'brak'
# print(f'POS4 offline for {store}')
elif POS4_name == 'brak':
ws[f'N{cell.row}'] = 'brak'
# print(f'POS4 offline for {store}')
# save file
wb.save(f'{cfgs.Countries_folder}{file}')
| [
"kuba19945@gmail.com"
] | kuba19945@gmail.com |
96bbad619bf902b5c03c90f60b751ea234ae0cb1 | 01ec5fae952211e0a0ab29dfb49a0261a8510742 | /backup/scripts/s1_src.py | 2059a709914e95436fd3845342e581a5154dc71d | [] | no_license | algoboy101/LeetCodeCrowdsource | 5cbf3394087546f9051c493b1613b5587c52056b | 25e93171fa16d6af5ab0caec08be943d2fdd7c2e | refs/heads/master | 2021-02-20T00:18:51.225422 | 2020-06-21T09:04:24 | 2020-06-21T09:04:24 | 245,323,834 | 10 | 4 | null | 2020-03-09T02:23:39 | 2020-03-06T03:43:27 | C++ | UTF-8 | Python | false | false | 2,676 | py | #!/usr/bin/env python2
#-*- coding:utf8 -*-
"""
通过source/src.txt文件获取以下信息:
d["index"] = index
d["name"] = name
d["title"] = build_title(index, name)
d["url_leetcode_cn"] = url_leetcode_cn
d["url_leetcode"]
"""
import glob
import urllib
import os
import pickle
import urllib
data = {}
fname_src = "../source/src.txt"
fname_data = "../output/data.pkl"
# url_github_prefix = "https://raw.githubusercontent.com/algoboy101/LeetCodeCrowdsource/master/_posts/QA/"
url_github_prefix = "https://github.com/algoboy101/LeetCodeCrowdsource/tree/master/_posts/QA/"
"""
解析 索引号
"""
def get_index(s):
s = s.strip()
s = ' '.join(s.split())
try:
index = int(s)
res = "%04d" % index
except:
res = s
return res
"""
解析 名字
"""
def get_name(s):
item = s.split("]")[0]
res = item.split("[")[1]
# res = item[1:]
res = res.strip()
res = ' '.join(res.split())
return res
"""
解析 leetcode_cn 链接
"""
def get_url(s):
ind = s.find("https")
s = s[ind:]
res = s.split(")")[0]
# item = item.split("(")[1]
# res = item.strip()
return res
"""
解析 leetcode_en 链接
"""
def get_url_en(url_cn):
url_en = url_cn.replace("https://leetcode-cn.com", "https://leetcode.com")
return url_en
"""
通过index和name构建title
"""
def build_title(index, name):
res = "[%s] %s" % (index, name)
# res = ' '.join([index, name])
return res
"""
根据title生成文件名
"""
def build_fname(title):
res = title + ".md"
return res
with open(fname_src) as fp:
lines = fp.readlines()
lines = [line.strip().split('|') for line in lines]
for line in lines:
d = {}
index = line[1]
index = get_index(line[1])
name = get_name(line[2])
title = build_title(index, name)
url_leetcode_cn = get_url(line[2])
url_leetcode_en = get_url_en(url_leetcode_cn)
fname = build_fname(title)
url_github = url_github_prefix + urllib.quote(fname)
d["index"] = index
d["name"] = name
d["title"] = title
d["url_leetcode_cn"] = url_leetcode_cn
d["url_leetcode_en"] = url_leetcode_en
d["url_github"] = url_github
data[index] = d
# data.append(d)
# d["url_blog"]
# d["answer_desc"]
# d["answer_code"]
# d["topic"]
# print d
# s = "%s\t%s\t%s" % (index, name, url_leetcode_cn)
# print s
# print line
# data.sort()
# for d in data:
# print d
# 创建文件夹
if not os.path.isdir(os.path.dirname(fname_data)):
os.makedirs(os.path.dirname(fname_data))
# 保存文件
with open(fname_data, "wb") as fp:
pickle.dump(data, fp)
| [
"chenwenwen0210@126.com"
] | chenwenwen0210@126.com |
947166b31d96d83cdee5e6bd191f02766a960666 | 613a5915117e995ca3ac4146de978ab29e2518c9 | /dmwTrader/technical/linreg.py | 1e32df62dfdab1e49a971c05250e76ea8a58b93a | [] | no_license | dxcv/DmwTrader | 44f4e49cbbe8276c37a46d27e3ed408aaed31ec5 | 9735227ac98224c847b9af80fc086ce87b8b1511 | refs/heads/master | 2020-06-20T11:21:56.104314 | 2017-12-28T06:04:31 | 2017-12-28T06:04:31 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,189 | py | # -*- coding: utf-8 -*-
"""
.. modulefrom:: pyalgotrade
.. moduleauthor:: Gabriel Martin Becedillas Ruiz <gabriel.becedillas@gmail.com>
revised by Zhongyu
"""
from dmwTrader import technical
from dmwTrader.utils import collections
from dmwTrader.utils import dt
import numpy as np
from scipy import stats
# Using scipy.stats.linregress instead of numpy.linalg.lstsq because of this:
# http://stackoverflow.com/questions/20736255/numpy-linalg-lstsq-with-big-values
def lsreg(x, y):
x = np.asarray(x)
y = np.asarray(y)
res = stats.linregress(x, y)
return res[0], res[1]
class LeastSquaresRegressionWindow(technical.EventWindow):
def __init__(self, windowSize):
assert(windowSize > 1)
super(LeastSquaresRegressionWindow, self).__init__(windowSize)
self.__timestamps = collections.NumPyDeque(windowSize)
def onNewValue(self, dateTime, value):
technical.EventWindow.onNewValue(self, dateTime, value)
if value is not None:
timestamp = dt.datetime_to_timestamp(dateTime)
if len(self.__timestamps):
assert(timestamp > self.__timestamps[-1])
self.__timestamps.append(timestamp)
def __getValueAtImpl(self, timestamp):
ret = None
if self.windowFull():
a, b = lsreg(self.__timestamps.data(), self.getValues())
ret = a * timestamp + b
return ret
def getTimeStamps(self):
return self.__timestamps
def getValueAt(self, dateTime):
return self.__getValueAtImpl(dt.datetime_to_timestamp(dateTime))
def getValue(self):
ret = None
if self.windowFull():
ret = self.__getValueAtImpl(self.__timestamps.data()[-1])
return ret
class LeastSquaresRegression(technical.EventBasedFilter):
"""Calculates values based on a least-squares regression.
:param dataSeries: The DataSeries instance being filtered.
:type dataSeries: :class:`pyalgotrade.dataseries.DataSeries`.
:param windowSize: The number of values to use to calculate the regression.
:type windowSize: int.
:param maxLen: The maximum number of values to hold.
Once a bounded length is full, when new items are added, a corresponding number of items are discarded from the
opposite end. If None then dataseries.DEFAULT_MAX_LEN is used.
:type maxLen: int.
"""
def __init__(self, dataSeries, windowSize, maxLen=None):
super(LeastSquaresRegression, self).__init__(dataSeries, LeastSquaresRegressionWindow(windowSize), maxLen)
def getValueAt(self, dateTime):
"""Calculates the value at a given time based on the regression line.
:param dateTime: The datetime to calculate the value at.
Will return None if there are not enough values in the underlying DataSeries.
:type dateTime: :class:`datetime.datetime`.
"""
return self.getEventWindow().getValueAt(dateTime)
class SlopeEventWindow(technical.EventWindow):
def __init__(self, windowSize):
super(SlopeEventWindow, self).__init__(windowSize)
self.__x = np.asarray(range(windowSize))
def getValue(self):
ret = None
if self.windowFull():
y = self.getValues()
ret = lsreg(self.__x, y)[0]
return ret
class Slope(technical.EventBasedFilter):
"""The Slope filter calculates the slope of a least-squares regression line.
:param dataSeries: The DataSeries instance being filtered.
:type dataSeries: :class:`pyalgotrade.dataseries.DataSeries`.
:param period: The number of values to use to calculate the slope.
:type period: int.
:param maxLen: The maximum number of values to hold.
Once a bounded length is full, when new items are added, a corresponding number of items are discarded from the
opposite end. If None then dataseries.DEFAULT_MAX_LEN is used.
:type maxLen: int.
.. note::
This filter ignores the time elapsed between the different values.
"""
def __init__(self, dataSeries, period, maxLen=None):
super(Slope, self).__init__(dataSeries, SlopeEventWindow(period), maxLen)
class TrendEventWindow(SlopeEventWindow):
def __init__(self, windowSize, positiveThreshold, negativeThreshold):
if negativeThreshold > positiveThreshold:
raise Exception("Invalid thresholds")
super(TrendEventWindow, self).__init__(windowSize)
self.__positiveThreshold = positiveThreshold
self.__negativeThreshold = negativeThreshold
def getValue(self):
ret = super(TrendEventWindow, self).getValue()
if ret is not None:
if ret > self.__positiveThreshold:
ret = True
elif ret < self.__negativeThreshold:
ret = False
else: # Between negative and postive thresholds.
ret = None
return ret
class Trend(technical.EventBasedFilter):
def __init__(self, dataSeries, trendDays, positiveThreshold=0, negativeThreshold=0, maxLen=None):
super(Trend, self).__init__(dataSeries, TrendEventWindow(trendDays, positiveThreshold, negativeThreshold), maxLen)
| [
"hezhongyu0@hotmail.com"
] | hezhongyu0@hotmail.com |
138e79d105f114c67ae8e2c12bcd6e2bc886a47f | 4b61ba2dded57be5673d5277cffadf6c13181b9f | /lab/lab1/0916/fifo_test.py | c965a8e4147e41e00289005a109b2ee141e36afe | [] | no_license | CL2228/ECE5725-Embedded_Operating_Systems | 447f15da257f5ff0b66e821dd795983aff79d32a | c9b1f44babaeba5837ce9b5d721b68050ddce05f | refs/heads/main | 2023-08-18T05:38:20.174596 | 2021-10-06T03:09:42 | 2021-10-06T03:09:42 | 406,428,404 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 529 | py | """
Names: Chenghui Li, Hehong Li
NetIDs: cl2228, hl778
Lab1, 09/09/2021 & 09/16/2021
"""
import subprocess
import sys
x= sys.stdin.readline()
while x != "q\n": # if input a q, break the while and quit the video
if x == "p\n": # if input a p, pause the video
cmd = 'echo "' + "pause" + '" > /home/pi/0916/test_fifo'
print(subprocess.check_output(cmd, shell=True))
x = sys.stdin.readline()
cmd = 'echo "quit" > /home/pi/0916/test_fifo'
print (subprocess.check_output(cmd, shell=True))
| [
"g20170282@icloud.com"
] | g20170282@icloud.com |
3f7bfbadf9329b5930c000e11628cb365ad9c346 | c46bdc2bebb8a6c5868e3a12c1c9104eeecfee48 | /chapter 15/15-3.py | b2e354ac71e5b0421e09207bd38623018d4c1e45 | [] | no_license | JoeJiang7/python-crash-course | 4612d9393918a8c460501df9a9a53e464b54c65b | 0dc7fd517e71f1ea9229c9665dfdf2111d631e25 | refs/heads/master | 2020-08-24T08:37:31.888920 | 2019-10-22T12:45:33 | 2019-10-22T12:45:33 | 216,795,431 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 573 | py | import matplotlib.pyplot as plt
from random_walk import RandomWalk
while True:
rw = RandomWalk()
rw.fill_walk()
point_numbers = list(range(rw.num_points))
plt.plot(rw.x_values, rw.y_values, linewidth=1)
plt.scatter(0, 0, c='green', edgecolors='none', s=100)
plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none', s=100)
plt.show()
while True:
keep_running = input("Make another walk? (y/n): ")
if keep_running == 'y' or keep_running == 'n':
break
if keep_running == 'n':
break
| [
"joejiang@seu.edu.cn"
] | joejiang@seu.edu.cn |
0cb367809e325a0dd6c531f0d61a66a4ad15a1a6 | 43ccd4d2b43733790b015ff0aa298fbbf8e4aea6 | /springy/indices.py | 3e81c1184b9d909163856b1438e1e3f50d1ada43 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | dboczek/springy | 9c4ff247a898724ad71cc54fd20a54599155d3e3 | e1df3e66e67b6614826b833f77a64cb95453108e | refs/heads/master | 2021-01-18T04:49:28.487870 | 2016-01-29T20:54:48 | 2016-01-29T20:54:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 9,177 | py | from collections import defaultdict
import itertools
import six
from .connections import get_connection_for_doctype
from .fields import Field
from .utils import model_to_dict, generate_index_name
from .search import IterableSearch
from .schema import model_doctype_factory, Schema
from .exceptions import DocumentDoesNotExist, FieldDoesNotExist
class AlreadyRegisteredError(Exception):
pass
class NotRegisteredError(KeyError):
pass
class IndicesRegistry(object):
def __init__(self):
self._indices = {}
self._model_indices = defaultdict(list)
def register(self, name, cls):
if not name:
raise ValueError('Index name can not be empty')
if name in self._indices:
raise AlreadyRegisteredError('Index `%s` is already registered' % name)
self._indices[name] = cls
try:
self._model_indices[cls.model].append(cls)
except:
del self._indices[name]
raise
def get(self, name):
try:
return self._indices[name]
except KeyError:
raise NotRegisteredError('Index `%s` is not registered' % name)
def get_all(self):
return self._indices.values()
def get_for_model(self, model):
return self._model_indices[model][:] # shallow copy
def unregister(self, cls):
to_unregister = []
for name, idx in self._indices.items():
if idx == cls:
to_unregister.append(name)
if not to_unregister:
raise NotRegisteredError('Index class `%s` is not registered')
self._model_indices[cls.model].remove(cls)
for name in to_unregister:
del self._indices[name]
def unregister_all(self):
self._indices={}
self._model_indices = defaultdict(list)
registry = IndicesRegistry()
class IndexOptions(object):
def __init__(self, meta, declared_fields):
self.document = getattr(meta, 'document', None)
self.optimize_query = getattr(meta, 'optimize_query', False)
self.index = getattr(meta, 'index', None)
self.read_consistency = getattr(meta, 'read_consistency', 'quorum')
self.write_consistency = getattr(meta, 'write_consistency', 'quorum')
self._field_names = getattr(meta, 'fields', None) or []
self._declared_fields = declared_fields
def setup_doctype(self, meta, index):
self.document = model_doctype_factory(meta.model, index,
fields=getattr(meta, 'fields', None),
exclude=getattr(meta, 'exclude', None)
)
class IndexBase(type):
def __new__(cls, name, bases, attrs):
super_new = super(IndexBase, cls).__new__
parents = [b for b in bases if isinstance(b, IndexBase)]
if not parents:
return super_new(cls, name, bases, attrs)
new_class = super_new(cls, name, bases, attrs)
meta = attrs.pop('Meta', None)
if not meta:
meta = getattr(new_class, 'Meta', None)
declared_fields = {}
for _attrname, _attr in new_class.__dict__.items():
if isinstance(_attr, Field):
declared_fields[_attrname]=_attr
setattr(new_class, '_meta', IndexOptions(meta, declared_fields))
setattr(new_class, 'model', getattr(meta, 'model', None))
if not new_class._meta.document:
new_class._meta.setup_doctype(meta, new_class)
setattr(new_class, '_schema', Schema(new_class._meta.document.get_all_fields()))
schema_fields = new_class._schema.get_field_names()
for fieldname in new_class._meta._field_names:
if not fieldname in schema_fields:
raise FieldDoesNotExist('Field `%s` is not defined')
index_name = new_class._meta.index or generate_index_name(new_class)
registry.register(index_name, new_class)
return new_class
class Index(six.with_metaclass(IndexBase)):
@property
def name(self):
return self._meta.index
def get_query_set(self):
"""
Return queryset for indexing
"""
return self.model._default_manager.all()
def get_search_object(self):
"""
Return search object instance
"""
return IterableSearch(index=self._meta.document._doc_type.index)
def initialize(self, using=None):
"""
Initialize / update doctype
"""
self._meta.document.init(using=using)
def create(self, datadict, meta=None):
"""
Create document instance based on arguments
"""
datadict['meta'] = meta or {}
document = self._meta.document(**datadict)
document.full_clean()
return document
def query(self, *args, **kw):
"""
Query index
"""
return self.get_search_object().query(*args, **kw)
def query_string(self, query):
"""
Query index with `query_string` and EDisMax parser.
This is shortcut for `.query('query_string', query='<terms>', use_dis_max=True)`
"""
return self.get_search_object().parse(query)
def filter(self, *args, **kw):
"""
Filter index
"""
return self.get_search_object().filter(*args, **kw)
def all(self):
"""
Return all documents query
"""
return self.get_search_object()
def to_doctype(self, obj):
"""
Convert model instance to ElasticSearch document
"""
data = model_to_dict(obj)
for field_name in self._meta._field_names:
prepared_field_name = 'prepare_%s' % field_name
if hasattr(self, prepared_field_name):
data[field_name] = getattr(self, prepared_field_name)(obj)
meta = {'id': obj.pk}
return self.create(data, meta=meta)
def delete(self, obj, fail_silently=False):
"""
Delete document that represents specified `obj` instance.
Raise DocumentDoesNotExist exception when document does not exist.
When `fail_silently` set to true, DocumentDoesNotExist will be silenced.
"""
from elasticsearch.exceptions import NotFoundError
doc = self.to_doctype(obj)
try:
doc.delete()
except NotFoundError:
if not fail_silently:
raise DocumentDoesNotExist('Document `%s` (id=%s) does not exists in index `%s`' % (
doc._doc_type.name, doc.meta.id, self.name))
def save(self, obj, force=False):
doc = self.to_doctype(obj)
doc.save()
def save_many(self, objects, using=None, consistency=None):
from elasticsearch.helpers import bulk
def generate_qs():
qs = iter(objects)
for item in qs:
yield self.to_doctype(item)
doctype_name = self._meta.document._doc_type.name
index_name = self._meta.document._doc_type.index
connection = get_connection_for_doctype(self._meta.document, using=using)
def document_to_action(x):
data = x.to_dict()
data['_op_type'] = 'index'
for key,val in x.meta.to_dict().items():
data['_%s' % key] = val
return data
actions = itertools.imap(document_to_action, generate_qs())
consistency = consistency or self._meta.write_consistency
return bulk(connection, actions, index=index_name, doc_type=doctype_name,
consistency=consistency, refresh=True)[0]
def update(self, obj):
"""
Perform create/update document only if matching indexing queryset
"""
try:
obj = self.get_query_set().filter(pk=obj.pk)[0]
except IndexError:
pass
else:
self.save(obj)
def update_queryset(self, queryset):
"""
Perform create/update of queryset but narrowed with indexing queryset
"""
qs = self.get_query_set()
qs.query.combine(queryset.query, 'and')
return self.save_many(qs)
def update_index(self, using=None, consistency=None):
self.save_many(self.get_query_set(), using=using,
consistency=consistency)
def clear_index(self, using=None, consistency=None):
from elasticsearch.helpers import scan, bulk
connection = get_connection_for_doctype(self._meta.document, using=using)
objs = scan(connection, _source_include=['__non_existent_field__'])
index_name = self._meta.document._doc_type.index
def document_to_action(x):
x['_op_type'] = 'delete'
return x
actions = itertools.imap(document_to_action, objs)
consistency = consistency or self._meta.write_consistency
bulk(connection, actions, index=index_name, consistency=consistency,
refresh=True)
def drop_index(self, using=None):
from elasticsearch.client.indices import IndicesClient
connection = get_connection_for_doctype(self._meta.document, using=using)
return IndicesClient(connection).delete(self._meta.index)
| [
"marcin.j.nowak@gmail.com"
] | marcin.j.nowak@gmail.com |
190a5ad0ef2bfe1fa70d5db8c10a62b7ca1482e2 | f1c07e84c9637c726aecca018dff4360a8523550 | /python/7-kyu/complementary-dna.py | 2922de2094797eed39d6a3b0831b293d6e397223 | [] | no_license | magladde/code-wars | d4112210fb2ecd51cc0602e4f58b75c9a4b4271b | 9409cce454e3255d97a6af020773c9aab435aab6 | refs/heads/master | 2022-06-22T23:24:12.129370 | 2020-05-12T22:58:37 | 2020-05-12T22:58:37 | 261,883,831 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 426 | py | def DNA_strand(dna):
complimentary_strand = ''
for i in range(len(dna)):
if dna[i] == 'T':
complimentary_strand += 'A'
elif dna[i] == 'A':
complimentary_strand += 'T'
elif dna[i] == 'G':
complimentary_strand += 'C'
elif dna[i] == 'C':
complimentary_strand += 'G'
return complimentary_strand
result = DNA_strand("ATTGC")
print(result) | [
"magladde@gmail.com"
] | magladde@gmail.com |
aefe95e6018e09299e56e99a58f0ee15d7083c8d | cc892dd4361525e61bb7fe892ac3928b3e508887 | /what.py | 61eb1213c7e30bac13c2307eac80444fa24641e0 | [] | no_license | Tsuirongu/PyQt | 0a3498e0906868e928bd6a261fe1a2758781267d | 3f0d3d25e43c587b68d0565d78840f1233980b54 | refs/heads/main | 2023-02-04T22:42:38.691985 | 2020-12-29T06:16:00 | 2020-12-29T06:16:00 | 325,202,705 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 9,974 | py | import sys
import os
import json
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtCore import *
from PyQt5 import QtCore, QtGui, QtWidgets
import loadCsv
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
class DragLabel(QLabel):
def __init__(self, parent=None):
super().__init__(None, parent)
self.setAcceptDrops(True)
self.model = False
def dragEnterEvent(self,e):
# e = QDragEnterEvent() # type:QDragEnterEvent
path = e.mimeData().text()
self.path = path[8:]
pixel = QPixmap(self.path)
self.setPixmap(pixel)
if e.mimeData().hasText():
e.accept()
else:
e.ignore()
def dropEvent(self, e):
res = loadCsv.identify_card(img_path=self.path)
if res == {}:
print("识别失败")
else:
self.dictV = res
self.model = True
print("识别成功")
class Ui_MainWindow(object):
"""
自动生成的代码, 请不要修改
"""
def addOne(self, theDict):
pass
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1150, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.listWidget = QtWidgets.QListWidget(self.centralwidget)
self.listWidget.setGeometry(QtCore.QRect(25, 70, 500, 500))
self.listWidget.setObjectName("listWidget")
self.searchline = QtWidgets.QLineEdit(self.centralwidget)
self.searchline.setGeometry(QtCore.QRect(25, 10, 500, 30))
self.searchB = QtWidgets.QPushButton(self.centralwidget)
self.searchB.setGeometry(QtCore.QRect(535, 10, 60, 60))
self.html = QtWidgets.QPushButton(self.centralwidget)
self.html.setGeometry(QtCore.QRect(535, 70, 60, 60))
self.addNew = QPushButton(self.centralwidget)
self.addNew.setGeometry(QtCore.QRect(535, 130, 60, 60))
self.commit = QPushButton(self.centralwidget)
self.commit.setGeometry(QtCore.QRect(535, 190, 60, 60))
self.WriteNew = QPushButton(self.centralwidget)
self.WriteNew.setGeometry(QtCore.QRect(535, 250, 60, 60))
self.putUp = QPushButton(self.centralwidget)
self.putUp.setGeometry(QtCore.QRect(600, 10, 200, 30))
self.grid = QWidget(self.centralwidget)
self.grid.setGeometry(QtCore.QRect(610, 70, 500, 500))
self.gridlayout = QGridLayout(self.grid)
self.draglabel = DragLabel(self.centralwidget)
self.draglabel.setGeometry(QtCore.QRect(600, 70, 500, 500))
self.pixel = QPixmap('./tt.png').scaled(500, 500)
self.background=QPalette()
self.background.setBrush(QPalette.Background,QBrush(QPixmap("./back.png")))
# self.label=QLabel()
# self.label.setPixmap(self.pixel)
MainWindow.setPalette(self.background)
self.draglabel.setPixmap(self.pixel)
# self.palette = QPalette()
# self.palette.setBrush(QPalette.Background, QBrush(QPixmap("./tt.jpg")))
# self.pushButton = QtWidgets.QPushButton(self.centralwidget)
# self.pushButton.setGeometry(QtCore.QRect(600, 10, 81, 31))
# self.pushButton.setObjectName("pushButton")
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.searchB.setText("搜索")
self.html.setText("地区\n可视化")
self.commit.setText("提交")
self.commit.setHidden(True)
self.putUp.setText("编辑")
self.WriteNew.setText("新增")
self.WriteNew.setHidden(True)
self.addNew.setText("载入至\nExcel")
# self.other.setPalette(self.palette)
class Windows(QMainWindow, Ui_MainWindow):
def get_item_wight(e, data):
idFont = QFont("Microsoft YaHei")
idFont.setPointSize(5)
def getEditPart(data):
# data
layout_detail = QGridLayout()
layout_detail.addWidget(QLabel(data[0]), 0, 0)
layout_detail.addWidget(QLabel(data[1]), 0, 1)
return layout_detail
# # 读取属性
# 总Widget
# 左侧部分的设置
wight = QWidget()
layout_main = QGridLayout()
layout_leftPart = QGridLayout()
# 姓名这里是唯一的,不存在多个
layout_leftPart.addWidget(QLabel(data['name'][0]), 0, 0)
# 手机号存在多个可能,需要修改
layout_leftPart.addWidget(QLabel(','.join(data['mobile'])), 1, 0)
idQ = QLabel(str(data['ID']))
idQ.setFont(idFont)
layout_leftPart.addWidget(idQ, 2, 0)
#
# # 左侧部分在上面
layoutDetail = QGridLayout()
e.Eemail = getEditPart(["Email", ','.join(data['email'])])
layoutDetail.addLayout(e.Eemail, 0, 0)
e.Eaddr = getEditPart(["Address", ','.join(data['addr'])])
layoutDetail.addLayout(e.Eaddr, 1, 0)
e.Eim = getEditPart(["QQ", ','.join(data['im'])])
layoutDetail.addLayout(e.Eim, 2, 0)
layout_main.addLayout(layout_leftPart, 0, 0)
layout_main.addLayout(layoutDetail, 0, 1)
wight.setLayout(layout_main) # 布局给wight
wight.setObjectName(data['ID'])
return wight # 返回wight
def editplace(self):
self.gridlayout.addWidget(QLabel("姓名"), 0, 0)
self.Pname = QLineEdit()
self.gridlayout.addWidget(self.Pname, 0, 1)
self.gridlayout.addWidget(QLabel("ID"), 1, 0)
self.Pid = QLineEdit()
self.Pid.setFocusPolicy(QtCore.Qt.NoFocus) # 设置不可编辑
self.gridlayout.addWidget(self.Pid, 1, 1, 1, 3)
self.gridlayout.addWidget(QLabel("头衔"), 2, 0)
self.Ptitle = QLineEdit()
self.gridlayout.addWidget(self.Ptitle, 2, 1)
self.gridlayout.addWidget(QLabel("手机"), 3, 0)
self.Pmobile = QLineEdit()
self.gridlayout.addWidget(self.Pmobile, 3, 1)
self.gridlayout.addWidget(QLabel("电话"), 3, 2)
self.Ptel = QLineEdit()
self.gridlayout.addWidget(self.Ptel, 3, 3)
self.gridlayout.addWidget(QLabel("学历"), 4, 0)
self.Pdegree = QLineEdit()
self.gridlayout.addWidget(self.Pdegree, 4, 1)
self.gridlayout.addWidget(QLabel("部门"), 5, 2)
self.Pdept = QLineEdit()
self.gridlayout.addWidget(self.Pdept, 5, 3)
self.gridlayout.addWidget(QLabel("公司"), 5, 0)
self.Pcomp = QLineEdit()
self.gridlayout.addWidget(self.Pcomp, 5, 1)
self.gridlayout.addWidget(QLabel("网址"), 4, 2)
self.Pweb = QLineEdit()
self.gridlayout.addWidget(self.Pweb, 4, 3)
self.gridlayout.addWidget(QLabel("邮编"), 6, 0)
self.Ppost = QLineEdit()
self.gridlayout.addWidget(self.Ppost, 6, 1)
self.gridlayout.addWidget(QLabel("地址"), 7, 0)
self.Paddr = QLineEdit()
self.gridlayout.addWidget(self.Paddr, 7, 1, 1, 3)
self.gridlayout.addWidget(QLabel("传真"), 6, 2)
self.Pfax = QLineEdit()
self.gridlayout.addWidget(self.Pfax, 6, 3)
self.gridlayout.addWidget(QLabel("IM"), 0, 2)
self.Pim = QLineEdit()
self.gridlayout.addWidget(self.Pim, 0, 3)
self.gridlayout.addWidget(QLabel("邮件"), 8, 0)
self.Pemail = QLineEdit()
self.gridlayout.addWidget(self.Pemail, 8, 1, 1, 3)
def Update(self, theDict): # 更新右侧的文本框
self.theDict = theDict
self.Pname.setText(''.join(theDict['name']))
self.Pid.setText(''.join(theDict['ID']))
self.Ptitle.setText(''.join(theDict['title']))
self.Pmobile.setText(''.join(theDict['mobile']))
self.Ptel.setText(''.join(theDict['tel']))
self.Pdegree.setText(''.join(theDict['degree']))
self.Pdept.setText(''.join(theDict['dept']))
self.Pcomp.setText(''.join(theDict['comp']))
self.Pweb.setText(''.join(theDict['web']))
self.Ppost.setText(''.join(theDict['post']))
self.Paddr.setText(''.join(theDict['addr']))
self.Pfax.setText(''.join(theDict['fax']))
self.Pim.setText(''.join(theDict['im']))
self.Pemail.setText(''.join(theDict['email']))
def __init__(self, data):
super(Windows, self).__init__()
self.setupUi(self)
def add(self, data):
length = len(data)
self.listWidget.clear()
for i in range(length):
item = QListWidgetItem() # 创建QListWidgetItem对象
item.setSizeHint(QSize(200, 150)) # 设置QListWidgetItem大小
widget = self.get_item_wight(data[i]) # 调用上面的函数获取对应
self.listWidget.addItem(item) # 添加item
self.listWidget.setItemWidget(item, widget) # 为item设置widget
def addOne(self, theDict):
item = QListWidgetItem() # 创建QListWidgetItem对象
item.setSizeHint(QSize(200, 150)) # 设置QListWidgetItem大小
widget = self.get_item_wight(theDict) # 调用上面的函数获取对应
self.listWidget.addItem(item) # 添加item
self.listWidget.setItemWidget(item, widget) # 为item设置widget
# data=[]
# app = QtWidgets.QApplication(sys.argv)
# windows = Windows(data)
# windows.show()
# sys.exit(app.exec_())
| [
"noreply@github.com"
] | noreply@github.com |
64bb985a43603d2cd5341cc937268b27fd0230de | 4cbc2a16074c51d928dd6686d3ba912b6c61fc88 | /simple_social/accounts/urls.py | db9ceef6d44193c2b59e06eb4322175ad7361198 | [] | no_license | andrew103/social_media_clone | b63439239630fa5cf75b9a5de6adf3b9c335824b | 7129b00038beaf1a27a9d0604351b577ff530f1f | refs/heads/master | 2020-12-02T09:11:22.378928 | 2017-07-09T20:21:38 | 2017-07-09T20:21:38 | 96,708,813 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 388 | py | from django.conf.urls import url
from django.contrib.auth import views as auth_views
from . import views
app_name = 'accounts'
urlpatterns = [
url(r'^login/$',auth_views.LoginView.as_view(template_name="accounts/login.html"), name = "login"),
url(r'^logout/$', auth_views.LogoutView.as_view(), name = "logout"),
url(r'^signup/$', views.SignUp.as_view(), name = "signup"),
]
| [
"andrew_103@rocketmail.com"
] | andrew_103@rocketmail.com |
be3f75c453bf73ade54b0a5a7997dcd2e1d53c3a | e082450b1b8b0fad78e3aa325e305f3f7cdfa5d8 | /component_add.py | 6322b4dded3571b192ff4d4fdd28fd1daeea95d1 | [] | no_license | Aditya-Kashyap/Automation | f41095f53f79d60c835f1856ff36f033ed07c167 | 0bccd805ea9d58054d7236d3faaa02e5d0c9e63e | refs/heads/master | 2020-12-22T20:04:01.197235 | 2020-04-30T07:04:18 | 2020-04-30T07:04:18 | 236,916,728 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,320 | py | class ComponentAddition:
def __init__(self):
self.arr = {"name": "sample-name", "type": "sample-type", "flavor": "sample-flavor", "description": "sample"}
@staticmethod
def comp_add():
print("Enter the Name of Component to be added")
comp_name = input()
print("Enter the Type of Components")
comp_type = input()
print("Enter the Flavor of the component")
comp_flavor = input()
print("Enter a Description for the Component")
comp_desc = input()
# Adding those new components in the shape of array:
data = {"name": comp_name, "type": comp_type, "flavor": comp_flavor, "description": comp_desc}
return data
@staticmethod
def comp_add_deploy():
# Entering Replica
print("Enter the number of Replica you want to make")
replica_no = input()
# Entering the Build Version
print("Do you want you specify the Build Version. It's mandatory if NOT specifying a Custom Docker Image")
print("Enter 1 to specify or anything else not to")
build_choice = input()
if build_choice == '1':
print("Enter the build version")
build = input()
else:
build = ""
# # Entering the Custom Docker Image
# print("Want to add a Custom Docker Image")
# print("Enter 1 to Add, Anything Else not to")
# docker_ch = input()
# if docker_ch == '1':
# print("Enter the Custom Docker Image")
# docker = input()
# data["components"][comp_name] = {"custom_docker_image", docker}
#
# # Entering the Environment Variables
# print("Do you want to add any Environment Parameters")
# print("Enter 1 to Add, Or anything else not to!")
# env_par_ch = input()
# if env_par_ch == '1':
# print("Enter the environment_parameters name and value")
# env_par_name = input("Enter the Name: ")
# env_par_value = input("Enter the Value")
# data["components"][comp_name]["environment_parameters"] = [{"name": env_par_name, "value": env_par_value}]
# else:
# data["components"][comp_name]["environment_parameters"] = []
#
# # Entering the Port
# print("Do you want to add PORT:")
# print("Enter 1 to Add to Add Port, Anything else not to")
# port_ch = input()
# if port_ch == '1':
# print("Enter the Port name and the corresponding value")
# port_name = input("Enter the Port Name")
# port_value = input("Enter the Port Value")
# data["components"][comp_name]["ports"] = [{"name": port_name, "value": port_value}]
#
# # Entering the Persistent Volume
# print("Do you want to add a Persistent Volume")
# print("Enter 1 to add or anything else not to")
# per_space = input()
# if per_space == '1':
# print("Enter the Mount Path")
# mount_path = input()
# data["components"][comp_name]["persistence"] = [{"mount_path": mount_path}]
#
# # Entering the Type of Component
# print("Is this component of type= JOB")
# print("If Yes then type 1, else anything else")
# job = input()
# if job == '1':
# data["components"][comp_name] = {"type": "job"}
# print("Select the Type of Job")
# print("Enter 1 for Normal Job")
# print("Enter 2 for Cron Job")
# job_ch = input()
# if job_ch == '1':
# job_type = 'normal job'
#
# elif job_ch == '2':
# job_type = 'cron job'
# print("Do you want to add a CronJob")
# print("Enter 1 to Add else anything for not to")
# cron_ch = input()
# if cron_ch == '1':
# print("Enter the cron schedule in the specific Cron job format")
# cron_job = input()
# data["components"][comp_name] = {"cron_schedule": cron_job}
# else:
# data["components"][comp_name] = {"cron_schedule": ""}
#
# # Entering any command to run:
# print("Do you want to Enter any Command")
# print("Enter 1 to add or anything else not to")
# command_ch = input()
# if command_ch == '1':
# print("Enter the Command to be passed")
# command = input()
# data["components"][comp_name] = {"command": command}
#
# # Entering any args to run:
# print("Do you want to Enter any Arguments")
# print("Enter 1 to add or anything else not to")
# args_ch = input()
# if args_ch == '1':
# print("Enter the number of arguments you need to pass")
# args_num = input()
# args_list = []
# for j in range(int(args_num)):
# print("Enter the Command to be passed")
# args = input()
# args_list.append(args)
# data["components"][comp_name] = {"args": args_list}
comp = {"replicas": replica_no, "build": build}
return comp
| [
"adi.inhere@gmail.com"
] | adi.inhere@gmail.com |
14d7846fd0619742b8296a89bde76be7c95dda8a | c0bd691bb09a1a8b35b07aa27ffed54a4f2e8b57 | /evaluation/questionnaires/questionnaire_eval.py | df5f85a5444a467d1352a621d37d95426a0277c0 | [] | no_license | codwest/interactive_image_segmentation_evaluation | 2302aa1cae7a012779287cf3d9a0a2356051ffc0 | 7c018b2fc0e22471dc6f820ad3f40d9c2dc1b57a | refs/heads/master | 2022-04-13T05:47:39.788961 | 2020-03-19T16:42:40 | 2020-03-19T16:42:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,392 | py | from collections import namedtuple
from typing import List, Union
import numpy as np
def generate_dummy_questionnaire_data(mode: str, num_users: int, num_prototypes: int = 1):
"""Function to generate example data"""
if mode.lower() == 'sus':
if num_prototypes == 1:
return np.random.randint(low=1, high=6, size=(num_users, 10), dtype=np.int8).tolist()
return np.random.randint(low=1, high=6, size=(num_prototypes, num_users, 10), dtype=np.int8).tolist()
elif mode.lower() == 'attrakdiff':
category_names: List[str] = ['PQ', 'ATT', 'HQ-I', 'HQ-S']
attrakdiff_data = np.random.randint(low=1, high=8, size=(num_prototypes, num_users, 28), dtype=np.int8).tolist()
if len(attrakdiff_data) == 1:
attrakdiff_data = attrakdiff_data[0]
categories: List[int] = [[0] * 7 + [1] * 7 + [2] * 7 + [3] * 7] * num_prototypes
invert_score: List[bool] = [[False] * 14 + [True] * 14] * num_prototypes
return attrakdiff_data, category_names, categories, invert_score
else:
raise ValueError('mode needs to be either "SUS" or "AttrakDiff"')
def get_sus_score(sus_data):
d = np.atleast_2d(sus_data) - 1 # dims: (num_subjects, 10_questions)
d[:, 1::2] = 4 - d[:, 1::2]
d = np.mean(d, axis=0)
return 2.5 * np.sum(d)
def normalize_attrakdiff_ratings(attrakdiff_data: List[List[int]], category_names: List[str],
categories: List[int], invert_score: List[bool]):
attrakdiff_data = np.atleast_2d(attrakdiff_data)
invert_score = np.squeeze(np.array(invert_score, dtype=np.bool))
attrakdiff_data[:, invert_score] = 8 - attrakdiff_data[:, invert_score]
del invert_score
categories = np.squeeze(categories)
categs = {na: attrakdiff_data[:, i == categories] for i, na in enumerate(category_names)}
categs = dict(sorted(categs.items(), key=lambda t: category_names.index(t[0])))
return attrakdiff_data, categs
def get_attrakdiff_score(attrakdiff_data: List[List[int]],
category_names: List[str] = ['PQ', 'ATT', 'HQ-I', 'HQ-S'],
categories: List[int] = [[0] * 7, [1] * 7, [2] * 7, [3] * 7],
invert_score: List[bool] = [[False] * 14, [True] * 14]):
attrakdiff_data = np.atleast_2d(attrakdiff_data)
attrakdiff_data, categs = normalize_attrakdiff_ratings(
attrakdiff_data, category_names, categories, invert_score)
res = [np.mean(categs[c]) for c in category_names]
res.append(np.mean((categs['HQ-I'] + categs['HQ-S']) / 2))
category_names_keyword_safe = [c.replace('-', '_') for c in category_names]
category_names_keyword_safe.append('HQ')
AttrakDiffScore = namedtuple('attrakdiff_score_for_user', category_names_keyword_safe)
return AttrakDiffScore(*res)
def evaluate_sus_questionnaire_data_per_user(data: Union[List[List[int]], List[List[List[int]]]]):
data = np.array(data)
if data.ndim == 2:
return [get_sus_score(d) for d in data]
elif data.ndim == 3:
return [evaluate_sus_questionnaire_data_per_user(d) for d in data]
else:
raise ValueError('data needs to be either 2-D or 3-D')
def evaluate_attrakdiff_questionnaire_data_per_user(data: Union[List[List[int]], List[List[List[int]]]],
category_names: List[str], categories: List[int],
invert_score: List[bool]):
data = np.array(data)
if data.ndim == 2:
return [get_attrakdiff_score(d, category_names, categories, invert_score) for d in data]
elif data.ndim == 3:
return [evaluate_attrakdiff_questionnaire_data_per_user(d, category_names, c, i)
for d, c, i in zip(data, categories, invert_score)]
else:
raise ValueError('data needs to be either 2-D or 3-D')
if __name__ == '__main__':
prototypes_sus_data = generate_dummy_questionnaire_data(mode='sus', num_users=2, num_prototypes=3)
print('# SUS')
print(*evaluate_sus_questionnaire_data_per_user(prototypes_sus_data), sep='\n', end='\n\n')
prototypes_attrakdiff_data = generate_dummy_questionnaire_data(mode='attrakdiff', num_users=2, num_prototypes=3)
print('# Attrakdiff')
print(*evaluate_attrakdiff_questionnaire_data_per_user(*prototypes_attrakdiff_data), sep='\n')
| [
"mario.amrehn@fau.de"
] | mario.amrehn@fau.de |
f8a244ebb1e4016d0d197a54d46ec5194a9c4296 | 751c37e6d6c9add85da691f9e5bcc87757cd66ec | /scripts/xdg_extract.py | 0b90ec47200135b914ba906b56648d3a014393b8 | [] | no_license | andreavanzo/lu4r_ros_interface | 23d9ecdf908bf8c21f6ad55a0eff69f0d2238121 | 1b0e249541c359e1d0054375f76d6e9f9dfb2b83 | refs/heads/master | 2021-06-09T15:31:23.071501 | 2017-01-12T13:09:48 | 2017-01-12T13:09:48 | 68,290,354 | 6 | 1 | null | null | null | null | UTF-8 | Python | false | false | 2,920 | py | import xmltodict
import json
import pprint
import os
def find_node_in_list(root,serializerID,type="@serializerID"):
if type in root:
if root[type] == serializerID:
return root
for e in root:
res = find_node(e,serializerID,type)
if res is not None:
return res
def find_node(root,serializerID,type="@serializerID"):
if type in root:
if root[type] == serializerID:
return root
for e in root:
if isinstance(root[e], dict):
res = find_node(root[e],serializerID,type)
if res is not None:
return res
elif isinstance(root[e], list):
res = find_node_in_list(root[e], serializerID, type)
if res is not None:
return res
def populate_predicate(jstring, interpretation, predicates):
frame_name = interpretation["@name"]
predicates[frame_name] = {}
#get lexical unit
lu_lemmas = []
for elem in interpretation["constituentList"].split():
lu_lemmas.append(find_node(jstring, elem)["@surface"])
predicates[frame_name]["lu"]=" ".join(lu_lemmas)
#get arguments
if isinstance(interpretation["ARGS"]["sem_arg"], list):
for arg in interpretation["ARGS"]["sem_arg"]:
element = arg["@entity"]
l = arg["constituentList"].split()
arg_lemmas=[]
for elem in l:
arg_lemmas.append(find_node(jstring, elem)["@surface"])
predicates[frame_name][element] = arg_lemmas
elif isinstance(interpretation["ARGS"]["sem_arg"], dict):
arg = interpretation["ARGS"]["sem_arg"]
element = arg["@entity"]
l = arg["constituentList"].split()
arg_lemmas=[]
for elem in l:
arg_lemmas.append(find_node(jstring, elem)["@surface"])
predicates[frame_name][element] = arg_lemmas
def find_predicates(toparse):
jstring = json.loads(json.dumps(xmltodict.parse(toparse), indent=4))
interpretation_list = jstring["TEXT"]["PARAGRAPHS"]["P"]["XDGS"]["XDG"]["interpretations"]["interpretationList"]
predicates = {}
if interpretation_list is not None:
interpretation_list = jstring["TEXT"]["PARAGRAPHS"]["P"]["XDGS"]["XDG"]["interpretations"]["interpretationList"]["item"]
if isinstance(interpretation_list, list):
for interpretation in interpretation_list:
populate_predicate(jstring, interpretation, predicates)
elif isinstance(interpretation_list, dict):
populate_predicate(jstring, interpretation_list, predicates)
return predicates
def get_sentence(jstring):
return jstring["TEXT"]["PARAGRAPHS"]["P"]["SUR"]
def read_xdg(path):
print "Opening: " + path
toparse = ""
for l in open(path, "r"):
toparse = toparse + l
return json.loads(json.dumps(xmltodict.parse(toparse), indent=4))
#pp = pprint.PrettyPrinter(indent=1)
#dir="comandi_xdg"
#for file in os.listdir(dir):
# if file.endswith(".xml"):
# jstring = read_xdg(dir+"/" + file)
# print "SENTENCE: " + get_sentence(jstring)
# predicates = find_predicates(jstring)
# pp.pprint(predicates) | [
"andrea.vanzo1@gmail.com"
] | andrea.vanzo1@gmail.com |
34166c18d83a2ff7918a33296d355457645bae1b | 5e31aec4b38d53993e416a4974842d6378148de2 | /ratelimit9/forms.py | e24bdcea3cfc3a4daca13fa599d33a637ebf942f | [
"MIT"
] | permissive | 9dev/django-ratelimit9 | b2182ef067457a742c86130f624e2792eb02890b | ac1e6affeaa1084013467349e258e52abc50e7bb | refs/heads/master | 2021-08-16T08:02:45.147091 | 2014-12-19T13:00:52 | 2014-12-19T13:00:52 | 28,229,301 | 2 | 0 | MIT | 2021-06-10T17:30:23 | 2014-12-19T12:51:54 | Python | UTF-8 | Python | false | false | 639 | py | from captcha.fields import ReCaptchaField
class Ratelimit9Form(object):
def __init__(self, *args, **kwargs):
captcha = kwargs.pop('captcha', None)
super(Ratelimit9Form, self).__init__(*args, **kwargs)
if captcha:
self.fields['captcha'] = ReCaptchaField(
# @todo enable developer to adjust this field
attrs={'theme':'white'},
error_messages={
'required': 'Enter the CAPTCHA code.',
'captcha_invalid': 'The CAPTCHA code you entered is invalid. Try again.',
}
)
| [
"9devmail@gmail.com"
] | 9devmail@gmail.com |
ea693066e5c2cfa3a129e92b9162b3156c200ed6 | 60598454222bc1e6d352993f9c4cd164cd6cc9cd | /core/migrations/0014_auto_20200723_1127.py | f07013abc7d877cba2d16a2195b83a8886e01144 | [] | no_license | nicksonlangat/mychurch | 12be8911ce1497d7c6a595d06275f21ecf58b185 | e503828cab165c9edcde89b3ef6d7c06b5eb7fdb | refs/heads/master | 2023-08-10T15:36:06.208376 | 2020-07-23T09:52:19 | 2020-07-23T09:52:19 | 281,030,716 | 0 | 1 | null | 2021-09-22T19:35:09 | 2020-07-20T06:15:58 | Python | UTF-8 | Python | false | false | 498 | py | # Generated by Django 3.0.8 on 2020-07-23 08:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0013_attendance_status'),
]
operations = [
migrations.RemoveField(
model_name='service',
name='seat_capacity',
),
migrations.AddField(
model_name='service',
name='seats',
field=models.ManyToManyField(to='core.Seat'),
),
]
| [
"nicksonlangat95@gmail.com"
] | nicksonlangat95@gmail.com |
bfe1897197b6c105575cd8e14a5f14ce2b3e933a | c56dd15329e1f1dde3c3598ac874ab628166e6ef | /malayalam chatbot/app.py | 16c6b6d124a43b7e854391bb38cefdbe01ff1422 | [
"MIT"
] | permissive | abinshoby/Auto-Suggestion-of-Malayalam-Question-using-LSTM | e9933e341571f5c9aad59f1dc84c568033381363 | 7f04f11d6d9a6b2b51450e519de8517199a640d4 | refs/heads/master | 2020-03-23T00:02:28.751720 | 2018-10-07T17:59:19 | 2018-10-07T17:59:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,029 | py | from flask import Flask
from flask import render_template
from predict_text_meaning import predict
from flask import *
import os
app = Flask(__name__)
o=""
#@app.route('/')
# def index():
# return render_template('index.html',pred=predict)
# @app.route('/pred', methods=['POST'])
# def pred():
# data=request.form['inp'];
# return predict(data)
@app.route('/')
def first():
return render_template('predict.html')
@app.route('/req', methods=['POST'])
def req():
inp = request.form['inp'];
if(len(inp)>0):
out= json.dumps({'status':'OK','suggestion':predict([inp.strip()])});#json.dumps({'status':'OK','user':user,'pass':password});
return out
else:
print("no inp")
return json.dumps({'status':'OK','suggestion':''});
@app.route('/favicon.ico')
def favicon():
return send_from_directory(os.path.join(app.root_path, 'static'),
'favicon.ico', mimetype='image/vnd.microsoft.icon')
if __name__ == '__main__':
app.run(debug=True) | [
"noreply@github.com"
] | noreply@github.com |
5479940e8409ca5cf4b10fe746b7b58d6f4ea083 | 4bae98f34747054505f11f2af0c61020bdcccf47 | /gde_test.py | 5e58bcd18c50d546d54b5070b0041d4913643387 | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | edoliberty/streaming-quantiles | 726adc679ab25dde3d88555138426211465f5faf | 500747df3088ce4f236f84f5f5887d5f9a272ab8 | refs/heads/master | 2022-11-30T17:34:24.940409 | 2022-11-19T14:22:05 | 2022-11-19T14:22:05 | 54,480,798 | 53 | 23 | Apache-2.0 | 2022-11-19T14:22:06 | 2016-03-22T14:17:23 | Jupyter Notebook | UTF-8 | Python | false | false | 1,921 | py | import unittest
import numpy as np
from gde import GDE
class TestGDE(unittest.TestCase):
def test_one_update(self):
k = 10
gde = GDE(k, 3);
gde.update([0, 0, 0]);
self.assertTrue(gde.query([0, 0, 0]) == 1);
self.assertTrue(gde.query([0.01, 0.01, 0.01]) > 0.95);
self.assertTrue(gde.query([1, 1, 1]) < 0.05);
def test_to_string(self):
gde1 = GDE(10, 4);
gde1.update([0, 0, 0, 0.0]);
gde1.update([-1.5, 123.4, 1.4e12,-5]);
gde1_serialized = gde1.to_string()
gde2 = GDE();
gde2.from_string(gde1_serialized)
self.assertTrue(gde1.d == gde2.d)
self.assertTrue(gde1.k == gde2.k)
self.assertTrue(gde1.n == gde2.n)
self.assertTrue(gde1.size == gde2.size)
self.assertTrue(gde1.max_size == gde2.max_size)
for c1, c2 in zip(gde1.compactors,gde2.compactors):
for v1, v2 in zip(c1, c2):
self.assertTrue(np.all(np.isclose(v1, v2)))
def test_merge(self):
gde1 = GDE();
gde1.update([0, 0, 0, 0.0]);
gde1.update([-1.5, 123.4, 1.4e12,-5]);
gde2 = GDE();
gde2.update([0.66, -10, 123, 0.0]);
gde1.merge(gde2)
self.assertTrue(gde1.n == 3)
self.assertTrue(gde1.size == 3)
def test_merge_size(self):
k, d, n = 17, 25, 200
gde1 = GDE(k, d);
gde2 = GDE(k, d);
for i in range(int(n/2)):
gde1.update(np.random.randn(d))
gde2.update(np.random.randn(d))
gde1.merge(gde2)
self.assertTrue(gde1.size <= n*np.log(n/k))
def test_size(self):
k, d, n = 171, 13, 2000
gde = GDE(k, d);
for i in range(n):
gde.update(np.random.randn(d))
self.assertTrue(gde.size <= n*np.log(n/k))
if __name__ == '__main__':
unittest.main()
| [
"edo.liberty@gmail.com"
] | edo.liberty@gmail.com |
fe14f2115c6d8ac2ddf2d6e11be9e9c06367e1c5 | 299eabcb14187b58f931b9adc0542f7113210e27 | /info/migrations/0005_auto_20210526_0739.py | 6e162c69faf85463ca189517dfed59244a214220 | [] | no_license | hebilidu/animal_info | e19b741162e19bc9bf4e30de6c92da079d292ed9 | 587dcfb572fedf8ce7c3d1e09cabe6e3a5754e2e | refs/heads/main | 2023-05-08T20:59:52.582903 | 2021-06-01T06:00:29 | 2021-06-01T06:00:29 | 370,058,855 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 699 | py | # Generated by Django 3.2.3 on 2021-05-26 07:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('info', '0004_passport_last_visited_country'),
]
operations = [
migrations.CreateModel(
name='Country',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=40)),
],
),
migrations.AddField(
model_name='passport',
name='visited_countries',
field=models.ManyToManyField(to='info.Country'),
),
]
| [
"git@hebi.fr"
] | git@hebi.fr |
e403926edc63a77639f93fdc497335b065b136c4 | ff15cc1435c7fc3cb099e6d3ec8a6c2dbb3bc11c | /Programming Basics with Python/First_Steps_in_Coding/01_Hello_SoftUni.py | b8b38c7ced24f1042add7de96ca3aacb2c0b96ae | [
"MIT"
] | permissive | petyakostova/Software-University | 4c6a687e365cb918e75b678378e699f8bd707fe0 | 672d887d104260f18220bfb3d4a667b96a444b23 | refs/heads/master | 2020-03-12T12:56:02.407069 | 2018-07-16T20:12:20 | 2018-07-16T20:12:20 | 130,630,180 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 55 | py | # prints the text "HelloSoftUni"
print('Hello SoftUni') | [
"petya_kostova_@abv.bg"
] | petya_kostova_@abv.bg |
39dfe7da8a352ef55114fb6b089a6e550760e664 | b29d68ea866fdf99bc92609ab6bd0654f5ad2130 | /tut2bonus.py | 0a5da54c0a6d8470ac6ae7a6e244e31d5287d40d | [] | no_license | Mulokoshi/Simon-Assignment-1 | 05299f92f244e00a6436bc15afead13168bd9ba4 | 6fba6d49676fa3b594e5480dfa8f9f61af9108ba | refs/heads/master | 2021-01-17T12:37:19.569972 | 2016-06-20T10:39:43 | 2016-06-20T10:39:43 | 56,517,751 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 552 | py | ## We obtained the difference of the two Area by integrating the function in to two parts,
## from -5 to 5. The 1st initial part is from -5 to 3 and 2nd part from
## 3 to 5, Therefore, we can conclude that the 1st integral is the sum of the two parts and the 2nd integration is
## only for the initial part.
import numpy
import scipy.integrate as quad
def mygauss(x,cent=0,sig=0.1):
return numpy.exp(-0.5*(x-cent)**2/sig**2)
I,err=quad.quad(mygauss,-5,5)
print I
I1,err=quad.quad(mygauss,-5,3)
print I1
I2,err=quad.quad(mygauss, 3,5)
print I2
| [
"simonmulokoshi@gmail.com"
] | simonmulokoshi@gmail.com |
c14d0ef0b5ded965c2955fe2dba0d3e10bce2d87 | 6978c3de8160e3e88930e8da53588bd4b63ade94 | /home/bin/syncthing-archive.py | 417b8ce7cadfa6ddf6986a17185ac93a59aea3b6 | [] | no_license | vonpupp/dotfiles-apps | 37126cdd516079db105f3acce291854b9464edf2 | b8188866193ccacf648758cb306c5265697c021c | refs/heads/master | 2022-08-04T16:22:49.088386 | 2022-07-10T00:51:27 | 2022-07-10T00:51:27 | 36,723,839 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,578 | py | #!/usr/bin/env python
# Source: https://docs.syncthing.net/users/versioning.html#external-file-versioning
# Lets assume I have a folder "default" in ~/Sync, and that within that folder there is a file docs/letter.txt that is being replaced or deleted. The script will be called as if I ran this from the command line:
# $ /Users/jb/bin/syncthing-archive.sh /Users/jb/Sync docs/letter.txt
# Local test:
# # ~/bin/syncthing-archive.py /share/android/oneplus2/Camera OpenCamera/IMG_20201011_144705.jpg
# Expected:
# # mv /share/android/oneplus2/Camera/OpenCamera/IMG_20201011_144705.jpg /share/android/oneplus2/Camera-archive/OpenCamera/IMG_20201011_144705.jpg
# On syncthing do not forget to quote the arguments:
# /share/homes/admin/bin/syncthing-archive.py "%FOLDER_PATH%" "%FILE_PATH%"
import sys
import os
if __name__ == "__main__":
folder_path = sys.argv[1]
file_path = sys.argv[2]
print(folder_path)
print(file_path)
archive_path = folder_path + '-archive'
org_filename = os.path.join(folder_path, file_path)
dst_filename = os.path.join(archive_path, file_path)
ensure_root = os.path.dirname(dst_filename)
print(ensure_root)
try:
print('create folder: {}'.format(archive_path))
os.makedirs(ensure_root)
except OSError as e:
if 'file exists' not in e.strerror.lower():
print(e)
raise(e)
try:
print('move file: {} TO {}'.format(org_filename, dst_filename))
os.rename(org_filename, dst_filename)
except Exception as e:
print(e)
raise(e)
| [
"albert@haevas.com"
] | albert@haevas.com |
33503c160832f77601867c9dd684393799d296a4 | 01341bd59e8d51e98287a23fe94460959439642e | /11_hl_max_guesses.py | e82fb20a82da8e681980f00b2e5702950ee013da | [] | no_license | williamsj71169/02_Higher_Lower | d6a39e27711b03a3f21067696fbc615486a2f540 | 7d2cf92a54f346a98f9aac64f93aae32f982e553 | refs/heads/master | 2021-01-16T12:43:24.769153 | 2020-03-15T20:45:01 | 2020-03-15T20:45:01 | 243,126,216 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 292 | py | #
import math
for item in range(0, 4):
low = int(input("Low: "))
high = int(input("High: "))
range = high - low + 1
max_raw = math.log2(range)
max_upped = math.ceil(max_raw)
max_guesses = max_upped + 1
print("Max Guesses: {}".format(max_guesses))
print()
| [
"58008516+williamsj71169@users.noreply.github.com"
] | 58008516+williamsj71169@users.noreply.github.com |
bb4865db730020b6945e02383297db7706ba99ad | c82da5e6c9287951c1c214ed172c03761d0b3940 | /Part 1 - Data Preprocessing/data_preprocessing_template.py | 5dd9e788990ab666983fbcbc4fcbdffcc43e21d5 | [] | no_license | NegiArvind/A-Z-machine-learning | 695d1cbbd20a5ca1d94533069b734d34b0b22c7e | 66b5c5e5c0abf03401016a4f932be3c24b6784c8 | refs/heads/master | 2020-04-02T04:46:54.149663 | 2018-10-21T17:20:33 | 2018-10-21T17:20:33 | 154,034,445 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 758 | py | # Data Preprocessing Template
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 3].values # first argument i.e ':' says take all rows and 3 saying take 3 column
# Splitting the dataset into the Training set and Test set
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)
# Feature Scaling
"""from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)
sc_y = StandardScaler()
y_train = sc_y.fit_transform(y_train)""" | [
"negiarvind229@gmail.com"
] | negiarvind229@gmail.com |
e77b9bf7ab6d5437d6b040caef3e6915f04fffca | a71582e89e84a4fae2595f034d06af6d8ad2d43a | /tensorflow/python/data/experimental/kernel_tests/optimization/make_numa_aware_test.py | d79ae4387c868d4821ac65787ba0bc04d47cc7d3 | [
"Apache-2.0"
] | permissive | tfboyd/tensorflow | 5328b1cabb3e24cb9534480fe6a8d18c4beeffb8 | 865004e8aa9ba630864ecab18381354827efe217 | refs/heads/master | 2021-07-06T09:41:36.700837 | 2019-04-01T20:21:03 | 2019-04-01T20:26:09 | 91,494,603 | 3 | 0 | Apache-2.0 | 2018-07-17T22:45:10 | 2017-05-16T19:06:01 | C++ | UTF-8 | Python | false | false | 1,813 | py | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for the `MakeNumaAware` optimization."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.data.experimental.ops import batching
from tensorflow.python.data.experimental.ops import optimization
from tensorflow.python.data.kernel_tests import test_base
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.framework import test_util
from tensorflow.python.platform import test
@test_util.run_all_in_graph_and_eager_modes
class MakeNumaAwareTest(test_base.DatasetTestBase):
def testMakeNumaAware(self):
dataset = dataset_ops.Dataset.range(10).apply(
optimization.assert_next(["NumaMapAndBatch"])).apply(
batching.map_and_batch(lambda x: x * x, 10))
options = dataset_ops.Options()
options.experimental_numa_aware = True
options.experimental_optimization.apply_default_optimizations = False
dataset = dataset.with_options(options)
self.assertDatasetProduces(
dataset, expected_output=[[x * x for x in range(10)]])
if __name__ == "__main__":
test.main()
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
c16f8beb6dd17e8abea992b1486d2f97065e2a08 | 324d2f9f97c1eb82746ccbede11d359ce3ee0b60 | /Inject.py | 2bbd9635a78d20608221cd38b672261cdf861488 | [] | no_license | kokobae741/koko2in1new | 03512f1cd4b2c19e0a9a5b13046665667d3fdcf4 | f3be010bfcd2810244569d049e7381bf03ba0124 | refs/heads/master | 2020-06-12T21:46:03.520115 | 2019-06-29T18:13:43 | 2019-06-29T18:13:43 | 194,435,675 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,756 | py | import os
import sys
import random
import socket
import select
import datetime
import threading
lock = threading.RLock(); os.system('cls' if os.name == 'nt' else 'clear')
def real_path(file_name):
return os.path.dirname(os.path.abspath(__file__)) + file_name
def filter_array(array):
for i in range(len(array)):
array[i] = array[i].strip()
if array[i].startswith('#'):
array[i] = ''
return [x for x in array if x]
def colors(value):
patterns = {
'R1' : '\033[31;1m', 'R2' : '\033[31;2m',
'G1' : '\033[32;1m', 'Y1' : '\033[33;1m',
'P1' : '\033[35;1m', 'CC' : '\033[0m'
}
for code in patterns:
value = value.replace('[{}]'.format(code), patterns[code])
return value
def log(value, status='', color=''):
value = colors('{color}[{time}] [CC]Mencari Server {color}{status} [CC]{color}{value}[CC]'.format(
time=datetime.datetime.now().strftime('%H:%M'),
value=value,
color=color,
status=status
))
with lock: print(value)
def log_replace(value, status='Inject', color=''):
value = colors('{}{} ({}) [CC]\r'.format(color, status, value))
with lock:
sys.stdout.write(value)
sys.stdout.flush()
class inject(object):
def __init__(self, inject_host, inject_port):
super(inject, self).__init__()
self.inject_host = str(inject_host)
self.inject_port = int(inject_port)
def log(self, value, color='[G1]'):
log(value, color=color)
def start(self):
try:
socket_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket_server.bind((self.inject_host, self.inject_port))
socket_server.listen(1)
frontend_domains = open(real_path('/config.txt.enc')).readlines()
frontend_domains = filter_array(frontend_domains)
if len(frontend_domains) == 0:
self.log('Frontend Domains not found. Please check config.txt.enc', color='G1')
return
self.log(' #====Jangan Lupa Subscribe====#\nLocal Host : 127.0.0.1\nLocal Port : 8888\nInjecksi sukses (200 OK) \nSilahkan Buka Psiphon !!!'.format(self.inject_host, self.inject_port))
while True:
socket_client, _ = socket_server.accept()
socket_client.recv(4096)
domain_fronting(socket_client, frontend_domains).start()
except Exception as exception:
self.log('Gagal!!!Mohon Restar Android anda'.format(self.inject_host, self.inject_port), color='[R1]')
class domain_fronting(threading.Thread):
def __init__(self, socket_client, frontend_domains):
super(domain_fronting, self).__init__()
self.frontend_domains = frontend_domains
self.socket_tunnel = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket_client = socket_client
self.buffer_size = 1024
self.daemon = True
def log(self, value, status='Ditemukan',
color=''):
log(value, status=status, color=color)
def handler(self, socket_tunnel, socket_client, buffer_size):
sockets = [socket_tunnel, socket_client]
timeout = 0
while True:
timeout += 1
socket_io, _, errors = select.select(sockets, [], sockets, 3)
if errors: break
if socket_io:
for sock in socket_io:
try:
data = sock.recv(buffer_size)
if not data: break
# SENT -> RECEIVED
elif sock is socket_client:
socket_tunnel.sendall(data)
elif sock is socket_tunnel:
socket_client.sendall(data)
timeout = 0
except: break
if timeout == 60: break
def run(self):
try:
self.proxy_host_port = random.choice(self.frontend_domains).split(':')
self.proxy_host = self.proxy_host_port[0]
self.proxy_port = self.proxy_host_port[1] if len(self.proxy_host_port) >= 2 and self.proxy_host_port[1] else '443'
self.log('[CC]Menghubungkan...!!!'.format(self.proxy_host, self.proxy_port))
self.socket_tunnel.connect((str(self.proxy_host), int(self.proxy_port)))
self.socket_client.sendall(b'HTTP/1.1 200 OK\r\n\r\n')
self.handler(self.socket_tunnel, self.socket_client, self.buffer_size)
self.socket_client.close()
self.socket_tunnel.close()
self.log('sukses 200 ok!!!'.format(self.proxy_host, self.proxy_port), color='[G1]')
except OSError:
self.log('Connection error', color='[CC]')
except TimeoutError:
self.log('{} not responding'.format(self.proxy_host), color='[CC]')
G = '\033[1;33m'
print G + '(|_F_A_S_T C_O_N_E_C_T U_P_D_A_T_E_|) \n'
print(colors('\n'.join([
'[G1][!]Recode By :Rendi Sakti','[CC]'
'[G1][!]Remode By :Rendi Sakti','[CC]'
'[G1][!]Injection :Telkomsel Opok','[CC]'
'[G1][!]YouTube Chanel :Rendi Sakti','[CC]' '==========================================','[CC]'
'[R1]>>>>>|[!]Developers:Aztec Rabbit[!]|<<<<<<','[CC]' '==========================================','[CC]'
'Inject [!] Telkomsel E106 dan E51 [!]','[CC]'
])))
def main():
D = ' [G1][!] masukin password nya !'
koko = 'koko'
user_input = raw_input(' [!] input password [!] : ')
if user_input != koko:
sys.exit(' [!] password salah [!]\n')
print ' [!] Asiyapp Enjoy [!]\n'
inject('127.0.0.1', '8888').start()
if __name__ == '__main__':
main() | [
"noreply@github.com"
] | noreply@github.com |
78f3b9f5927206d15c77dd073f490b9202ab0fc2 | cac93d697f9b3a75f059d725dee0251a8a81bf61 | /robot/install/lib/python2.7/dist-packages/ur_dashboard_msgs/msg/_SetModeGoal.py | 7628590a2f33e2c657df2d3e8743b53b989e0882 | [
"BSD-3-Clause"
] | permissive | satvu/TeachBot | c1394f2833649fdd72aa5b32719fef4c04bc4f70 | 5888aea544fea952afa36c097a597c5d575c8d6d | refs/heads/master | 2020-07-25T12:21:34.240127 | 2020-03-09T20:51:54 | 2020-03-09T20:51:54 | 208,287,475 | 0 | 0 | BSD-3-Clause | 2019-09-13T15:00:35 | 2019-09-13T15:00:35 | null | UTF-8 | Python | false | false | 5,203 | py | # This Python file uses the following encoding: utf-8
"""autogenerated by genpy from ur_dashboard_msgs/SetModeGoal.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
class SetModeGoal(genpy.Message):
_md5sum = "6832df07338535cc06b3835f89ba9555"
_type = "ur_dashboard_msgs/SetModeGoal"
_has_header = False #flag to mark the presence of a Header object
_full_text = """# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======
# This action is for setting the robot into a desired mode (e.g. RUNNING) and safety mode into a
# non-critical state (e.g. NORMAL or REDUCED), for example after a safety incident happened.
# goal
int8 target_robot_mode
# Stop program execution before restoring the target mode. Can be used together with 'play_program'.
bool stop_program
# Play the currently loaded program after target mode is reached.#
# NOTE: Requesting mode RUNNING in combination with this will make the robot continue the motion it
# was doing before. This might probably lead into the same problem (protective stop, EM-Stop due to
# faulty motion, etc.) If you want to be safe, set the 'stop_program' flag below and manually play
# the program after robot state is returned to normal.
# This flag will only be used when requesting mode RUNNING
bool play_program
"""
__slots__ = ['target_robot_mode','stop_program','play_program']
_slot_types = ['int8','bool','bool']
def __init__(self, *args, **kwds):
"""
Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
target_robot_mode,stop_program,play_program
:param args: complete set of field values, in .msg order
:param kwds: use keyword arguments corresponding to message field names
to set specific fields.
"""
if args or kwds:
super(SetModeGoal, self).__init__(*args, **kwds)
#message fields cannot be None, assign default values for those that are
if self.target_robot_mode is None:
self.target_robot_mode = 0
if self.stop_program is None:
self.stop_program = False
if self.play_program is None:
self.play_program = False
else:
self.target_robot_mode = 0
self.stop_program = False
self.play_program = False
def _get_types(self):
"""
internal API method
"""
return self._slot_types
def serialize(self, buff):
"""
serialize message into buffer
:param buff: buffer, ``StringIO``
"""
try:
_x = self
buff.write(_get_struct_b2B().pack(_x.target_robot_mode, _x.stop_program, _x.play_program))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize(self, str):
"""
unpack serialized message in str into this message instance
:param str: byte array of serialized message, ``str``
"""
try:
end = 0
_x = self
start = end
end += 3
(_x.target_robot_mode, _x.stop_program, _x.play_program,) = _get_struct_b2B().unpack(str[start:end])
self.stop_program = bool(self.stop_program)
self.play_program = bool(self.play_program)
return self
except struct.error as e:
raise genpy.DeserializationError(e) #most likely buffer underfill
def serialize_numpy(self, buff, numpy):
"""
serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module
"""
try:
_x = self
buff.write(_get_struct_b2B().pack(_x.target_robot_mode, _x.stop_program, _x.play_program))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize_numpy(self, str, numpy):
"""
unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module
"""
try:
end = 0
_x = self
start = end
end += 3
(_x.target_robot_mode, _x.stop_program, _x.play_program,) = _get_struct_b2B().unpack(str[start:end])
self.stop_program = bool(self.stop_program)
self.play_program = bool(self.play_program)
return self
except struct.error as e:
raise genpy.DeserializationError(e) #most likely buffer underfill
_struct_I = genpy.struct_I
def _get_struct_I():
global _struct_I
return _struct_I
_struct_b2B = None
def _get_struct_b2B():
global _struct_b2B
if _struct_b2B is None:
_struct_b2B = struct.Struct("<b2B")
return _struct_b2B
| [
"sarahvu@mit.edu"
] | sarahvu@mit.edu |
48de2103f2baa12bfa7ff1c30f880892b801a394 | 02263b003824b221e466928a997fd35f939bb655 | /core/utils/timeout.py | 4a697d94575be7bf70c57f8fdf321cc0f285f9cb | [
"Apache-2.0"
] | permissive | neoericnet/cmdbac | dad27b53a54df0a3ab76df4ea7cf4e66ec1dbf0d | 1f981e6f110728e51ba4ffdb90ff2d4ce091057a | refs/heads/master | 2020-08-06T23:54:01.631707 | 2017-11-15T05:54:47 | 2017-11-15T05:54:52 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 538 | py | from functools import wraps
import errno
import os
import signal
class TimeoutError(Exception):
pass
class timeout:
def __init__(self, seconds=1, error_message='Timeout'):
self.seconds = seconds
self.error_message = error_message
def handle_timeout(self, signum, frame):
raise TimeoutError(self.error_message)
def __enter__(self):
signal.signal(signal.SIGALRM, self.handle_timeout)
signal.alarm(self.seconds)
def __exit__(self, type, value, traceback):
signal.alarm(0) | [
"zeyuanxy@gmail.com"
] | zeyuanxy@gmail.com |
196e04b40f7912da4624f6e6f9ae396bb81751c6 | 6aaf1cc6caa35282d4acb347b11cd6dd138d7be7 | /challenge3/challenge3.py | 0b9c765f0975748ebaf095c6ddbacf41adb7b467 | [] | no_license | ntrainor1/Challenges | df3e5ab1b0415d430c988b605957bf21f70dcc66 | 555c3ab817af39d58879f7bc91ad240fa13ec07e | refs/heads/master | 2020-09-24T09:59:14.144274 | 2019-12-19T16:03:12 | 2019-12-19T16:03:12 | 225,734,728 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,666 | py | import unittest
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
class Challenge3(unittest.TestCase):
def setUp(self):
# code to startup webdriver
self.driver = webdriver.Chrome("../chromedriver.exe")
def tearDown(self):
# code to close webdriver
self.driver.close()
def test_challenge3(self):
# code for our test steps
self.driver.get("https://www.copart.com/")
WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.XPATH, "//*[@ng-if=\"popularSearches\"]")))
# table = self.driver.find_elements_by_xpath("//*[@id=\"tabTrending\"]/div[1]/div[2]")
# for item in table:
# print(str(item.text))
column_number = 1
while True:
try:
self.driver.find_element_by_xpath("//*[@ng-if=\"popularSearches\"]/div[2]/div[" + str(column_number) + "]")
row_number = 1
while True:
try:
row = self.driver.find_element_by_xpath("//*[@ng-if=\"popularSearches\"]/div[2]/div["+str(column_number)+"]/ul/li["+str(row_number)+"]/a")
print(str(row.text)+" - "+str(row.get_attribute("href")))
row_number += 1
except:
break
column_number += 1
except:
break
if __name__ == '__main__':
unittest.main()
| [
"nathaniel.trainor@sling.com"
] | nathaniel.trainor@sling.com |
596ba1a6543c1cde196b8ccaa7f46776e36327d6 | 2f02026ec22cf350d65449f90aea4dc9eb7ebc89 | /exercise3/score_strategy.py | 800fa51d73111ad3ede48da68ffb47d4b382cfe0 | [] | no_license | Ten10/NLPCourse | 3a349e2d665cebb33a083c2386772a7e176e3c1b | 6da394c188f1272950f86724f89e0de5c9d4e680 | refs/heads/master | 2020-09-11T12:08:57.581360 | 2020-03-14T17:27:31 | 2020-03-14T17:27:31 | 222,059,263 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,218 | py | import abc
from math import log10
from exercise3.corpus import Corpus
from exercise3.document import Document
from typing import Dict, List, Tuple
class ScoreStrategy(abc.ABC):
@abc.abstractmethod
def __init__(self, name: str, corpus: Corpus, **kwargs):
self.name = name
self.corpus = corpus
@abc.abstractmethod
# return dict from word to score
def score_document(self, document: Document) -> Tuple[List[float], Dict[str, List[float]]]:
pass
class TfIdfStrategy(ScoreStrategy):
def __init__(self, **kwargs):
super(TfIdfStrategy, self).__init__(name='Tf-IDF', **kwargs)
self.category_to_document_count = self.__compute_category_to_document_count(categories=self.corpus.categories)
self.__idf = self.__compute_inverse_document_frequency()
self.word_to_weighted_category: Dict[str, Dict[str, float]] = \
self.__compute_word_to_weighted_category(categories=self.corpus.categories)
self.word_types: List[str] = list(self.corpus.word_to_document_occurrences.keys())
def __compute_category_to_document_count(self, categories):
category_to_document_count = {}
for category in categories:
category_to_document_count[category] = 0
for document in self.corpus.documents:
category_to_document_count[document.category] += 1
return category_to_document_count
# IDF - inverse document frequency
def __compute_inverse_document_frequency(self) -> Dict[str, float]:
document_count = len(self.corpus.documents)
inverse_document_frequency: Dict[str, float] = {}
for word, document_occurrences in self.corpus.word_to_document_occurrences.items():
count_documents_with_word = len(document_occurrences)
word_inverse_document_frequency = log10(document_count / count_documents_with_word)
inverse_document_frequency[word] = word_inverse_document_frequency
return inverse_document_frequency
def get_word_weight_in_corpus_for_document(self, occurence: Document.WordCount, word: str) -> Tuple[float, str]:
document: Document = occurence.document
term_frequency = document.word_to_word_count[word].count if word in document.word_to_word_count else 0
return self.__idf.get(word, 0) * term_frequency, document.category
def __compute_word_to_weighted_category(self, categories: List[str]) -> Dict[str, Dict[str, float]]:
word_to_weighted_categories: Dict[str, Dict[str, float]] = {}
for word, occurrences in self.corpus.word_to_document_occurrences.items():
word_to_weighted_categories[word] = {}
for category in categories:
word_to_weighted_categories[word][category] = 0.0
for occurrence in occurrences:
weighted_score, category = self.get_word_weight_in_corpus_for_document(occurrence, word)
word_to_weighted_categories[word][category] += weighted_score
for category in categories:
document_count_in_category = self.category_to_document_count[category]
word_to_weighted_categories[word][category] /= document_count_in_category
return word_to_weighted_categories
def get_word_score_for_categories(self, word: str) -> Dict[str, float]:
return self.word_to_weighted_category.get(word, None)
# return dict from word to score
def score_document(self, document: Document) -> Tuple[List[float], Dict[str, List[float]]]:
category_word_score_for_document: Dict[str, List[float]] = {}
for category in self.corpus.categories:
category_word_score_for_document[category] = []
document_word_scoring: List[float] = []
for word, word_count in document.word_to_word_count.items():
category_weights_for_word: Dict[str, float] = self.get_word_score_for_categories(word)
if category_weights_for_word is not None:
for category, score in category_weights_for_word.items():
category_word_score_for_document[category].append(score)
else:
for category in self.corpus.categories:
category_word_score_for_document[category].append(0)
document_score_for_word, _ = self.get_word_weight_in_corpus_for_document(word=word,
occurence=word_count)
document_word_scoring.append(document_score_for_word)
return document_word_scoring, category_word_score_for_document
class BinaryStrategy(ScoreStrategy):
def __init__(self, **kwargs):
super(BinaryStrategy, self).__init__(name='binary', **kwargs)
self.is_word_in_category: Dict[str, Dict[str, bool]] = self.__calc_is_word_in_category()
def __calc_is_word_in_category(self) -> Dict[str, Dict[str, bool]]:
is_word_in_category: Dict[str, Dict[str, bool]] = {}
for word in self.corpus.word_to_document_occurrences.keys():
is_category_with_word = {}
for category in self.corpus.categories:
is_category_with_word[category] = False
for d in self.corpus.word_to_document_occurrences[word]:
is_category_with_word[d.document.category] = True
is_word_in_category[word] = is_category_with_word
return is_word_in_category
def score_document(self, document: Document) -> Tuple[List[float], Dict[str, List[float]]]:
category_word_score_for_document: Dict[str, List[float]] = {}
for category in self.corpus.categories:
category_word_score_for_document[category] = []
document_word_scoring: List[float] = []
for word, word_count in document.word_to_word_count.items():
categories_containing_words = self.is_word_in_category.get(word, {})
for category in self.corpus.categories:
category_word_score_for_document[category].append(1.0 if categories_containing_words.get(category, False) else 0.0)
document_word_scoring.append(1.0)
return document_word_scoring, category_word_score_for_document
| [
"jonathan.k@qspark.co"
] | jonathan.k@qspark.co |
05fc5187df71d55444543c1027e46b77e6aeaaa4 | b14f4302363380024ca9b5cc096dbcef230057bd | /JPA_MASTER_no_model/Deployment_code/Bin/digitization/test_main.py | 37593144c937145c1f708d138a97a481d89f0995 | [] | no_license | RajatChaudhari/Clustering_n_stuff | 1706da296656fc8c54d67c037d45ae5fd2b7b4f8 | b0de4bece13725ace69b12006c50da421478fea2 | refs/heads/master | 2020-04-22T22:36:46.926207 | 2019-02-12T10:57:46 | 2019-02-12T10:57:46 | 170,714,482 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 398 | py | import family_classifier,jp_struct,pp_struct
import mammoth
convertor = pp_struct.pp_to_struct()
clf = family_classifier.family_classify()
path = 'Manager, Human Resources Business Partners - Human Resources Business Partners - Human Resources.DOCX'
file = open(path, 'rb')
fils = mammoth.convert_to_html(file).value
family = convertor.html_to_df(fils)
print(clf.clf(family),'\n',family)
| [
"silverprince.v1@gmail.com"
] | silverprince.v1@gmail.com |
8f98d8f3660cdf41a784921e4755a08b7d2a5bd4 | beb637252e9b5ce3fa808ba4bb8f129823540cb0 | /stats/mantel/plot_ISC_subplots_mantel.py | b8137a936e43ef460f4de07aaeda554762ed9be0 | [
"MIT"
] | permissive | athiede13/free_speech | 6b4ecdfcf66cc80148fa870876836da3a0b98a03 | bde32c2d48724c98f089376876cf9888f67a9f20 | refs/heads/master | 2022-01-29T12:57:25.168260 | 2022-01-08T19:40:15 | 2022-01-08T19:40:15 | 176,300,570 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,522 | py | """
Plot subplots.
Created on Tue Sep 4 16:21:37 2018
@author: Anja Thiede <anja.thiede@helsinki.fi>
"""
import matplotlib.pyplot as plt
#%matplotlib qt
#%matplotlib inline
#to fill
filepath = '/media/cbru/SMEDY/results/mantel_correlations/2019_05_simple_model/'
filenames1 = (filepath + 'phon_clu_5.000000e-01-4Hz_613_1_lat-lh.png',
filepath + 'phon_clu_5.000000e-01-4Hz_613_1_lat-rh.png',
filepath + 'max_cluster_corr_5.000000e-01-4Hz_phon_1.png',
filepath + 'phon_clu_4-8Hz_613_1_lat-lh.png',
filepath + 'phon_clu_4-8Hz_613_1_lat-rh.png',
filepath + 'max_cluster_corr_4-8Hz_phon_1.png',
filepath + 'phon_clu_8-12Hz_613_1_med-lh.png',
filepath + 'phon_clu_8-12Hz_613_1_med-rh.png',
filepath + 'max_cluster_corr_8-12Hz_phon_1.png',
filepath + 'phon_clu_12-25Hz_613_1_lat-lh.png',
filepath + 'phon_clu_12-25Hz_613_1_lat-rh.png',
filepath + 'max_cluster_corr_12-25Hz_phon_1.png',
filepath + 'phon_clu_55-90Hz_613_1_lat-lh.png',
filepath + 'phon_clu_55-90Hz_613_1_lat-rh.png',
filepath + 'max_cluster_corr_55-90Hz_phon_1.png'
)
filenames2 = (filepath + 'read_clu_5.000000e-01-4Hz_613_1_lat-lh.png',
filepath + 'read_clu_5.000000e-01-4Hz_613_1_lat-rh.png',
filepath + 'max_cluster_corr_5.000000e-01-4Hz_read_1.png',
filepath + 'read_clu_8-12Hz_613_1_med-lh.png',
filepath + 'read_clu_8-12Hz_613_1_med-rh.png',
filepath + 'max_cluster_corr_8-12Hz_read_1.png',
filepath + 'read_clu_25-45Hz_613_1_lat-lh.png',
filepath + 'read_clu_25-45Hz_613_1_lat-rh.png',
filepath + 'max_cluster_corr_25-45Hz_read_1.png',
filepath + 'mem_clu_5.000000e-01-4Hz_613_1_lat-lh.png',
filepath + 'mem_clu_5.000000e-01-4Hz_613_1_lat-rh.png',
filepath + 'max_cluster_corr_5.000000e-01-4Hz_mem_1.png'
)
filenames3 = (filepath + 'iq_clu_5.000000e-01-4Hz_613_1_lat-lh.png',
filepath + 'iq_clu_5.000000e-01-4Hz_613_1_lat-rh.png',
filepath + 'max_cluster_corr_5.000000e-01-4Hz_iq_1.png',
)
labels1 = ['delta ', '', '',
'theta ', '', '',
'alpha ', '', '',
'beta ', '', '',
'high gamma ', '', ''
]
labels2 = ['delta ', '', '',
'alpha ', '', '',
'low gamma ', '', '',
'delta','','']
labels3 = ['delta ', '', '']
# delta \u03B4
# theta \u03B8
# alpha \u03B1
# beta \u03B2
# gamma \u03B3
#plot subplots
plt.rcParams['font.family'] = "serif"
fig1 = plt.figure(figsize=(15, 25))
fig1.tight_layout()
plt.subplots_adjust(wspace=0, hspace=0)
i = 1
for file in filenames1:
img = plt.imread(file, format='png')
ax = fig1.add_subplot(len(filenames1)/3, 3, i)
ax.imshow(img, aspect='equal')
ax.axis('off')
ax.text(1.01, 1.03, labels1[i-1], horizontalalignment='center',
verticalalignment='center', transform=ax.transAxes, fontsize=17)
if i == 2:
ax.text(0.5, 1.2, 'phonological processing', horizontalalignment='center',
verticalalignment='center', transform=ax.transAxes, fontsize=25)
i = i+1
fig1.suptitle("Regressions of speech ISCs with", fontsize=25, y=0.935)
plt.show()
fig1.savefig(filepath + 'summary_speech_correlations1.png', bbox_inches='tight', dpi=600)
fig1.savefig(filepath + 'summary_speech_correlations1.pdf', bbox_inches='tight', dpi=600)
fig1.clear()
fig2 = plt.figure(figsize=(15, 20))
fig2.tight_layout()
plt.subplots_adjust(wspace=0, hspace=0)
i = 1
for file in filenames2:
img = plt.imread(file, format='png')
ax = fig2.add_subplot(len(filenames2)/3, 3, i)
ax.imshow(img, aspect='equal')
ax.axis('off')
ax.text(1.01, 1.03, labels2[i-1], horizontalalignment='center',
verticalalignment='center', transform=ax.transAxes, fontsize=17)
if i == 2:
ax.text(0.5, 1.2, 'technical reading', horizontalalignment='center',
verticalalignment='center', transform=ax.transAxes, fontsize=25)
if i == 11:
ax.text(0.5, 1.08, 'working memory', horizontalalignment='center',
verticalalignment='center', transform=ax.transAxes, fontsize=25)
i = i+1
fig2.suptitle("Regressions of speech ISCs with", fontsize=25, y=0.95)
plt.show()
fig2.savefig(filepath + 'summary_speech_correlations2.png', bbox_inches='tight', dpi=600)
fig2.savefig(filepath + 'summary_speech_correlations2.pdf', bbox_inches='tight', dpi=600)
fig2.clear()
fig3 = plt.figure(figsize=(15, 5))
fig3.tight_layout()
plt.subplots_adjust(wspace=0, hspace=0)
i = 1
for file in filenames3:
img = plt.imread(file, format='png')
ax = fig3.add_subplot(len(filenames3)/3, 3, i)
ax.imshow(img, aspect='equal')
ax.axis('off')
ax.text(1.01, 1.03, labels3[i-1], horizontalalignment='center',
verticalalignment='center', transform=ax.transAxes, fontsize=17)
if i == 2:
ax.text(0.5, 1.18, 'IQ', horizontalalignment='center',
verticalalignment='center', transform=ax.transAxes, fontsize=25)
i = i+1
fig3.suptitle("Regressions of speech ISCs with", fontsize=25, y=1.15)
plt.show()
fig3.savefig(filepath + 'summary_speech_correlations3.png', bbox_inches='tight', dpi=600)
fig3.savefig(filepath + 'summary_speech_correlations3.pdf', bbox_inches='tight', dpi=600)
fig3.clear()
| [
"anja.thiede@helsinki.fi"
] | anja.thiede@helsinki.fi |
badb4fd17812c95118c46b700aaf4cbbb0c9698a | 3cae0e4309cdad8a9c38668c1caeb8bdbdbc7224 | /mag/data_scripts/test.py | 94b9a780e4c5fdbe67bdae193ec370c189591a8f | [] | no_license | matmcc/graph_django_neomodel | bf84cd2e0eb08a703058447a8dcb0da0e7ded8fe | cd795a76bf9dbb45441f40a206f83dc4a6176323 | refs/heads/master | 2020-12-02T09:09:21.943323 | 2020-02-13T20:17:05 | 2020-02-13T20:17:05 | 230,957,055 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 224 | py | from mag.Mag import Mag_Api
from decorators import timing
mag = Mag_Api()
p = mag.get_paper(2157025439)
r = mag.get_refs(p)
c = mag.get_cits(p)
lp = r + c
@timing
def time_this():
return mag.get_cits(lp)
time_this()
| [
"matmcconkey@gmail.com"
] | matmcconkey@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.