hexsha
stringlengths
40
40
size
int64
5
2.06M
ext
stringclasses
11 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
251
max_stars_repo_name
stringlengths
4
130
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
251
max_issues_repo_name
stringlengths
4
130
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
116k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
251
max_forks_repo_name
stringlengths
4
130
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
1
1.05M
avg_line_length
float64
1
1.02M
max_line_length
int64
3
1.04M
alphanum_fraction
float64
0
1
2917f447ee2f70e3835bc5750b44b618fe249b3e
623
py
Python
log.py
GregMorford/testlogging
446a61f363ad6c1470b6257f6c651021cd904468
[ "MIT" ]
null
null
null
log.py
GregMorford/testlogging
446a61f363ad6c1470b6257f6c651021cd904468
[ "MIT" ]
null
null
null
log.py
GregMorford/testlogging
446a61f363ad6c1470b6257f6c651021cd904468
[ "MIT" ]
null
null
null
import logging ## Logging Configuration ## logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) ch = logging.StreamHandler() # console handler ch.setLevel(logging.INFO) fh = logging.FileHandler('logfile.txt') fh.setLevel(logging.INFO) fmtr = logging.Formatter('%(asctime)s | [%(levelname)s] | (%(name)s) | %(message)s') fh.setFormatter(fmtr) logger.addHandler(fh) logger.addHandler(ch) #disable this to stop console output. This better than print statements as you can disable all console output in 1 spot instead of every print statement. logger.critical(f'testing a critical message from {__name__}')
32.789474
176
0.764045
29187b96b69d014696758f82a98a43412d184d30
552
py
Python
hackerrank/BetweenTwoSets.py
0x8b/HackerRank
45e1a0e2be68950505c0a75218715bd3132a428b
[ "MIT" ]
3
2019-12-04T01:22:34.000Z
2020-12-10T15:31:00.000Z
hackerrank/BetweenTwoSets.py
0x8b/HackerRank
45e1a0e2be68950505c0a75218715bd3132a428b
[ "MIT" ]
null
null
null
hackerrank/BetweenTwoSets.py
0x8b/HackerRank
45e1a0e2be68950505c0a75218715bd3132a428b
[ "MIT" ]
1
2019-12-04T01:24:01.000Z
2019-12-04T01:24:01.000Z
#!/bin/python3 import os if __name__ == "__main__": f = open(os.environ["OUTPUT_PATH"], "w") nm = input().split() n = int(nm[0]) m = int(nm[1]) a = list(map(int, input().rstrip().split())) b = list(map(int, input().rstrip().split())) total = getTotalX(a, b) f.write(str(total) + "\n") f.close()
17.25
74
0.461957
29192cb1930eb4fc8b54b5806896af754bbbc8d5
17,628
py
Python
utils.py
LlamaSi/Adaptive-PSGAIL
737cbc68c04d706da6a0bde1cb2a2c3159189f5e
[ "MIT" ]
10
2019-01-27T21:03:31.000Z
2020-09-03T16:26:23.000Z
utils.py
LlamaSi/Adaptive-PSGAIL
737cbc68c04d706da6a0bde1cb2a2c3159189f5e
[ "MIT" ]
1
2019-07-30T14:29:52.000Z
2019-08-12T12:58:37.000Z
utils.py
LlamaSi/Adaptive-PSGAIL
737cbc68c04d706da6a0bde1cb2a2c3159189f5e
[ "MIT" ]
5
2019-03-28T18:54:33.000Z
2022-03-14T06:32:53.000Z
import h5py import numpy as np import os, pdb import tensorflow as tf from rllab.envs.base import EnvSpec from rllab.envs.normalized_env import normalize as normalize_env import rllab.misc.logger as logger from sandbox.rocky.tf.algos.trpo import TRPO from sandbox.rocky.tf.policies.gaussian_mlp_policy import GaussianMLPPolicy from sandbox.rocky.tf.policies.gaussian_gru_policy import GaussianGRUPolicy from sandbox.rocky.tf.envs.base import TfEnv from sandbox.rocky.tf.spaces.discrete import Discrete from hgail.algos.hgail_impl import Level from hgail.baselines.gaussian_mlp_baseline import GaussianMLPBaseline from hgail.critic.critic import WassersteinCritic from hgail.envs.spec_wrapper_env import SpecWrapperEnv from hgail.envs.vectorized_normalized_env import vectorized_normalized_env from hgail.misc.datasets import CriticDataset, RecognitionDataset from hgail.policies.categorical_latent_sampler import CategoricalLatentSampler from hgail.policies.gaussian_latent_var_gru_policy import GaussianLatentVarGRUPolicy from hgail.policies.gaussian_latent_var_mlp_policy import GaussianLatentVarMLPPolicy from hgail.policies.latent_sampler import UniformlyRandomLatentSampler from hgail.core.models import ObservationActionMLP from hgail.policies.scheduling import ConstantIntervalScheduler from hgail.recognition.recognition_model import RecognitionModel from hgail.samplers.hierarchy_sampler import HierarchySampler import hgail.misc.utils from julia_env.julia_env import JuliaEnv ''' Const NGSIM_FILENAME_TO_ID = { 'trajdata_i101_trajectories-0750am-0805am.txt': 1, 'trajdata_i101_trajectories-0805am-0820am.txt': 2, 'trajdata_i101_trajectories-0820am-0835am.txt': 3, 'trajdata_i80_trajectories-0400-0415.txt': 4, 'trajdata_i80_trajectories-0500-0515.txt': 5, 'trajdata_i80_trajectories-0515-0530.txt': 6 }''' NGSIM_FILENAME_TO_ID = { 'trajdata_i101_trajectories-0750am-0805am.txt': 1, 'trajdata_i101-22agents-0750am-0805am.txt' : 1 } ''' Common ''' ''' Component build functions ''' ''' This is about as hacky as it gets, but I want to avoid editing the rllab source code as much as possible, so it will have to do for now. Add a reset(self, kwargs**) function to the normalizing environment https://stackoverflow.com/questions/972/adding-a-method-to-an-existing-object-instance ''' '''end of hack, back to our regularly scheduled programming''' # Raunak adding an input argument for multiagent video making ''' setup ''' ''' data utilities '''
33.705545
97
0.652144
291b3aad4ce914a07f4302fc64bb71bcd2cc87d1
8,429
py
Python
setup_py_upgrade.py
asottile/setup-py-upgrade
873c54ec4f112ed0150a8cffcc9990291568d634
[ "MIT" ]
87
2019-02-03T04:53:54.000Z
2022-03-25T07:36:46.000Z
setup_py_upgrade.py
asottile/setup-py-upgrade
873c54ec4f112ed0150a8cffcc9990291568d634
[ "MIT" ]
15
2019-03-12T04:14:35.000Z
2022-02-22T17:35:09.000Z
setup_py_upgrade.py
asottile/setup-py-upgrade
873c54ec4f112ed0150a8cffcc9990291568d634
[ "MIT" ]
8
2019-03-12T13:54:25.000Z
2022-02-22T17:40:17.000Z
import argparse import ast import configparser import io import os.path from typing import Any from typing import Dict from typing import Optional from typing import Sequence METADATA_KEYS = frozenset(( 'name', 'version', 'url', 'download_url', 'project_urls', 'author', 'author_email', 'maintainer', 'maintainer_email', 'classifiers', 'license', 'license_file', 'description', 'long_description', 'long_description_content_type', 'keywords', 'platforms', 'provides', 'requires', 'obsoletes', )) OPTIONS_AS_SECTIONS = ( 'entry_points', 'extras_require', 'package_data', 'exclude_package_data', ) OPTIONS_KEYS = frozenset(( 'zip_safe', 'setup_requires', 'install_requires', 'python_requires', 'use_2to3', 'use_2to3_fixers', 'use_2to3_exclude_fixers', 'convert_2to3_doctests', 'scripts', 'eager_resources', 'dependency_links', 'tests_require', 'include_package_data', 'packages', 'package_dir', 'namespace_packages', 'py_modules', 'data_files', # need special processing (as sections) *OPTIONS_AS_SECTIONS, )) FIND_PACKAGES_ARGS = ('where', 'exclude', 'include') if __name__ == '__main__': raise SystemExit(main())
36.489177
79
0.553684
291c77c6ee2c7b622d64d133d7665a508bb40300
106
py
Python
main/models/__init__.py
prajnamort/LambdaOJ2
5afc7ceb6022caa244f66032a19ebac14c4448da
[ "MIT" ]
2
2017-09-26T07:25:11.000Z
2021-11-24T04:19:40.000Z
main/models/__init__.py
prajnamort/LambdaOJ2
5afc7ceb6022caa244f66032a19ebac14c4448da
[ "MIT" ]
50
2017-03-31T19:54:21.000Z
2022-03-11T23:14:22.000Z
main/models/__init__.py
prajnamort/LambdaOJ2
5afc7ceb6022caa244f66032a19ebac14c4448da
[ "MIT" ]
7
2017-03-26T07:07:17.000Z
2019-12-05T01:05:41.000Z
from .user import User, MultiUserUpload from .problem import Problem, TestData from .submit import Submit
26.5
39
0.820755
291d1bd54ce729e58181e2031ec946c7078f3c67
726
py
Python
2019/tests/test_Advent2019_10.py
davidxbuck/advent2018
eed5424a8008b9c0829f5872ad6cd469ce9f70b9
[ "MIT" ]
1
2021-12-11T02:19:28.000Z
2021-12-11T02:19:28.000Z
2019/tests/test_Advent2019_10.py
davidxbuck/advent2018
eed5424a8008b9c0829f5872ad6cd469ce9f70b9
[ "MIT" ]
null
null
null
2019/tests/test_Advent2019_10.py
davidxbuck/advent2018
eed5424a8008b9c0829f5872ad6cd469ce9f70b9
[ "MIT" ]
1
2020-12-08T04:31:46.000Z
2020-12-08T04:31:46.000Z
# pytest tests import numpy as np from Advent2019_10 import Day10
30.25
71
0.488981
291d8e921326cbecc63bc712d0993323051bed1f
691
py
Python
tests/test_demo.py
aaronestrada/flask-restplus-swagger-relative
e951bad6a2c72522ac74f5353a7b0cbe5436f20f
[ "BSD-3-Clause" ]
3
2019-09-27T18:33:54.000Z
2020-03-31T15:32:32.000Z
tests/test_demo.py
aaronestrada/flask-restplus-swagger-relative
e951bad6a2c72522ac74f5353a7b0cbe5436f20f
[ "BSD-3-Clause" ]
1
2019-10-29T20:31:33.000Z
2019-11-04T14:25:08.000Z
tests/test_demo.py
aaronestrada/flask-restplus-swagger-relative
e951bad6a2c72522ac74f5353a7b0cbe5436f20f
[ "BSD-3-Clause" ]
1
2019-09-27T18:33:55.000Z
2019-09-27T18:33:55.000Z
import pytest from tests.test_application import app def test_hello_resource(client): """ Test if it is possible to access to /hello resource :param client: Test client object :return: """ response = client.get('/hello').get_json() assert response['hello'] == 'world' def test_asset_found(client): """ Test if Swagger assets are accessible from the new path :param client: Test client object :return: """ response = client.get('/this_is_a_new/path_for_swagger_internal_documentation/swaggerui/swagger-ui-bundle.js') assert response.status_code is 200
23.827586
114
0.700434
291e921dde8646cb27f33c258f33f46413f66a28
1,614
py
Python
01_Introduction to Python/3-functions-and-packages/03_multiple-arguments.py
mohd-faizy/DataScience-With-Python
13ebb10cf9083343056d5b782957241de1d595f9
[ "MIT" ]
5
2021-02-03T14:36:58.000Z
2022-01-01T10:29:26.000Z
01_Introduction to Python/3-functions-and-packages/03_multiple-arguments.py
mohd-faizy/DataScience-With-Python
13ebb10cf9083343056d5b782957241de1d595f9
[ "MIT" ]
null
null
null
01_Introduction to Python/3-functions-and-packages/03_multiple-arguments.py
mohd-faizy/DataScience-With-Python
13ebb10cf9083343056d5b782957241de1d595f9
[ "MIT" ]
3
2021-02-08T00:31:16.000Z
2022-03-17T13:52:32.000Z
''' 03 - Multiple arguments In the previous exercise, the square brackets around imag in the documentation showed us that the imag argument is optional. But Python also uses a different way to tell users about arguments being optional. Have a look at the documentation of sorted() by typing help(sorted) in the IPython Shell. You'll see that sorted() takes three arguments: iterable, key and reverse. key=None means that if you don't specify the key argument, it will be None. reverse=False means that if you don't specify the reverse argument, it will be False. In this exercise, you'll only have to specify iterable and reverse, not key. The first input you pass to sorted() will be matched to the iterable argument, but what about the second input? To tell Python you want to specify reverse without changing anything about key, you can use =: sorted(___, reverse = ___) Two lists have been created for you on the right. Can you paste them together and sort them in descending order? Note: For now, we can understand an iterable as being any collection of objects, e.g. a List. Instructions: - Use + to merge the contents of first and second into a new list: full. - Call sorted() on full and specify the reverse argument to be True. Save the sorted list as full_sorted. - Finish off by printing out full_sorted. ''' # Create lists first and second first = [11.25, 18.0, 20.0] second = [10.75, 9.50] # Paste together first and second: full full = first + second # Sort full in descending order: full_sorted full_sorted = sorted(full, reverse=True) # Print out full_sorted print(full_sorted)
35.086957
99
0.761462
291f1330f75cfc0ca15457846d8102779d88cf8f
790
py
Python
Taller_Algoritmos_02/Ejercicio_10.py
Angelio01/algoritmos_programacion-
63cb4cd4cfa01f504bf9ed927dcebf2466d6f60d
[ "MIT" ]
null
null
null
Taller_Algoritmos_02/Ejercicio_10.py
Angelio01/algoritmos_programacion-
63cb4cd4cfa01f504bf9ed927dcebf2466d6f60d
[ "MIT" ]
null
null
null
Taller_Algoritmos_02/Ejercicio_10.py
Angelio01/algoritmos_programacion-
63cb4cd4cfa01f504bf9ed927dcebf2466d6f60d
[ "MIT" ]
1
2021-10-29T19:40:32.000Z
2021-10-29T19:40:32.000Z
""" Entradas: 3 Valores flotantes que son el valor de diferentes monedas Chelines autriacos --> float --> x Dramas griegos --> float --> z Pesetas --> float --> w Salidas 4 valores flotantes que es la conversin de las anteriores monedas Pesetas --> float --> x Francos franceses --> float --> z Dolares --> float --> a Liras italianas --> float --> b """ # Entradas x1 = float(input("Dime los chelines autracos\n")) z1 = float(input("Dime los dracmas griegos\n")) w = float(input("Dime las pesetas\n")) # Caja negra x = (x1 * 956871)/100 z = z1/22.64572381 a = w/122499 b = (w*100)/9289 # Salidas print(f"\n{x1} Chelines austracos en pesetas son {x}\n{z1} Dracmas griegos en Francos franceses son {z}\n{w} Pesetas en Dolares son {a}\n{w} Pesetas en Liras italianas son {b}\n")
28.214286
180
0.679747
292038ace9f7b5e532a8a7cf41828bfb945d013c
2,844
py
Python
stardist/stardist_impl/predict_stardist_3d.py
constantinpape/deep-cell
d69cc9710af07428c79e5642febe3a39e33d11a4
[ "MIT" ]
null
null
null
stardist/stardist_impl/predict_stardist_3d.py
constantinpape/deep-cell
d69cc9710af07428c79e5642febe3a39e33d11a4
[ "MIT" ]
1
2020-07-08T13:16:32.000Z
2020-07-08T13:18:24.000Z
stardist/stardist_impl/predict_stardist_3d.py
constantinpape/deep-cell
d69cc9710af07428c79e5642febe3a39e33d11a4
[ "MIT" ]
null
null
null
import argparse import os from glob import glob import imageio from tqdm import tqdm from csbdeep.utils import normalize from stardist.models import StarDist3D # could be done more efficiently, see # https://github.com/hci-unihd/batchlib/blob/master/batchlib/segmentation/stardist_prediction.py if __name__ == '__main__': main()
36.935065
112
0.710267
29204de0e1568db751699c8bf504b18e9d16ff4b
4,049
py
Python
estacionamientos/forms.py
ShadowManu/SAGE
999626669c9a15755ed409e57864851eb27dc2c2
[ "MIT" ]
null
null
null
estacionamientos/forms.py
ShadowManu/SAGE
999626669c9a15755ed409e57864851eb27dc2c2
[ "MIT" ]
null
null
null
estacionamientos/forms.py
ShadowManu/SAGE
999626669c9a15755ed409e57864851eb27dc2c2
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import forms from estacionamientos.models import Estacionamiento, Reserva, Pago
49.987654
107
0.646826
29206dba9d120e61ae35f770db7e748c8ab7a64c
6,095
py
Python
src/krylov/gmres.py
nschloe/krylov
58813233ff732111aa56f7b1d71908fda78080be
[ "MIT" ]
36
2020-06-17T15:51:16.000Z
2021-12-30T04:33:11.000Z
src/krylov/gmres.py
nschloe/krylov
58813233ff732111aa56f7b1d71908fda78080be
[ "MIT" ]
26
2020-08-27T17:38:15.000Z
2021-11-11T20:00:07.000Z
src/krylov/gmres.py
nschloe/krylov
58813233ff732111aa56f7b1d71908fda78080be
[ "MIT" ]
5
2021-05-20T19:47:44.000Z
2022-01-03T00:20:33.000Z
""" Y. Saad, M. Schultz, GMRES: a generalized minimal residual algorithm for solving nonsymmetric linear systems, SIAM J. Sci. and Stat. Comput., 7(3), 856869, 1986, <https://doi.org/10.1137/0907058>. Other implementations: <https://petsc.org/release/docs/manualpages/KSP/KSPGMRES.html> """ from __future__ import annotations from typing import Callable import numpy as np import scipy.linalg from numpy.typing import ArrayLike from ._helpers import ( Identity, Info, LinearOperator, Product, assert_correct_shapes, clip_imag, get_default_inner, wrap_inner, ) from .arnoldi import ArnoldiHouseholder, ArnoldiMGS from .givens import givens def multi_matmul(A, b): """A @ b for many A, b (i.e., A.shape == (m,n,...), y.shape == (n,...))""" return np.einsum("ij...,j...->i...", A, b) def multi_solve_triangular(A, B): """This function calls scipy.linalg.solve_triangular for every single A. A vectorized version would be much better here. """ A_shape = A.shape a = A.reshape(A.shape[0], A.shape[1], -1) b = B.reshape(B.shape[0], -1) y = [] for k in range(a.shape[2]): if np.all(b[:, k] == 0.0): y.append(np.zeros(b[:, k].shape)) else: y.append(scipy.linalg.solve_triangular(a[:, :, k], b[:, k])) y = np.array(y).T.reshape([A_shape[0]] + list(A_shape[2:])) return y
27.331839
88
0.55767
2920920b3d2a50539ee42e0e75f03efbd2cffd7f
7,321
py
Python
backend-tests/tests/test_account_suspension.py
drewmoseley/integration
37f6374eb5faa710d14861cf5ed82e8f9cf0b149
[ "Apache-2.0" ]
null
null
null
backend-tests/tests/test_account_suspension.py
drewmoseley/integration
37f6374eb5faa710d14861cf5ed82e8f9cf0b149
[ "Apache-2.0" ]
98
2020-09-21T06:00:11.000Z
2022-03-28T01:17:19.000Z
backend-tests/tests/test_account_suspension.py
drewmoseley/integration
37f6374eb5faa710d14861cf5ed82e8f9cf0b149
[ "Apache-2.0" ]
null
null
null
# Copyright 2020 Northern.tech AS # # 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 # # https://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 pytest import random import time from testutils.api.client import ApiClient import testutils.api.useradm as useradm import testutils.api.deviceauth as deviceauth import testutils.api.tenantadm as tenantadm import testutils.api.deployments as deployments from testutils.infra.cli import CliTenantadm, CliUseradm import testutils.util.crypto from testutils.common import ( User, Device, Tenant, mongo, clean_mongo, create_org, create_random_authset, get_device_by_id_data, change_authset_status, ) class TestAccountSuspensionEnterprise: def test_user_cannot_log_in(self, tenants): tc = ApiClient(tenantadm.URL_INTERNAL) uc = ApiClient(useradm.URL_MGMT) for u in tenants[0].users: r = uc.call("POST", useradm.URL_LOGIN, auth=(u.name, u.pwd)) assert r.status_code == 200 # tenant's users can log in for u in tenants[0].users: r = uc.call("POST", useradm.URL_LOGIN, auth=(u.name, u.pwd)) assert r.status_code == 200 assert r.status_code == 200 # suspend tenant r = tc.call( "PUT", tenantadm.URL_INTERNAL_SUSPEND, tenantadm.req_status("suspended"), path_params={"tid": tenants[0].id}, ) assert r.status_code == 200 time.sleep(10) # none of tenant's users can log in for u in tenants[0].users: r = uc.call("POST", useradm.URL_LOGIN, auth=(u.name, u.pwd)) assert r.status_code == 401 # but other users still can for u in tenants[1].users: r = uc.call("POST", useradm.URL_LOGIN, auth=(u.name, u.pwd)) assert r.status_code == 200
31.021186
84
0.615353
292246bd8b4a4adc3e588a4c80c7a0ed3da6e0ed
8,985
py
Python
src/RepairManager/rules/ecc_reboot_node_rule.py
RichardZhaoW/DLWorkspace
27d3a3a82e59305bdc67dbfd69098d493f8b3cd5
[ "MIT" ]
2
2019-10-16T23:54:34.000Z
2019-11-07T00:08:32.000Z
src/RepairManager/rules/ecc_reboot_node_rule.py
RichardZhaoW/DLWorkspace
27d3a3a82e59305bdc67dbfd69098d493f8b3cd5
[ "MIT" ]
null
null
null
src/RepairManager/rules/ecc_reboot_node_rule.py
RichardZhaoW/DLWorkspace
27d3a3a82e59305bdc67dbfd69098d493f8b3cd5
[ "MIT" ]
null
null
null
import os, sys sys.path.append(os.path.dirname(os.path.abspath(__file__))) import json import logging import yaml import requests import time from actions.migrate_job_action import MigrateJobAction from actions.send_alert_action import SendAlertAction from actions.reboot_node_action import RebootNodeAction from actions.uncordon_action import UncordonAction from datetime import datetime, timedelta, timezone from rules_abc import Rule from utils import prometheus_util, k8s_util from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText activity_log = logging.getLogger('activity')
45.609137
114
0.650863
292271c92e27cc20ceca6c25b6dec338877c3ea5
2,735
py
Python
work/dib-ipa-element/virtmedia-netconf/ironic-bmc-hardware-manager/src/ironic_bmc_hardware_manager/bmc.py
alexandruavadanii/ipa-deployer
a15c349823c65b15ac6a72a73805c2cc342cb80c
[ "Apache-2.0" ]
null
null
null
work/dib-ipa-element/virtmedia-netconf/ironic-bmc-hardware-manager/src/ironic_bmc_hardware_manager/bmc.py
alexandruavadanii/ipa-deployer
a15c349823c65b15ac6a72a73805c2cc342cb80c
[ "Apache-2.0" ]
null
null
null
work/dib-ipa-element/virtmedia-netconf/ironic-bmc-hardware-manager/src/ironic_bmc_hardware_manager/bmc.py
alexandruavadanii/ipa-deployer
a15c349823c65b15ac6a72a73805c2cc342cb80c
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Nokia # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os from ironic_python_agent import hardware from ironic_python_agent import utils from oslo_log import log from oslo_concurrency import processutils LOG = log.getLogger()
32.951807
95
0.638026
2922d150cdfae741ee2f9afa07a050efc52cf07f
2,344
py
Python
museum_site/context_processors.py
DrDos0016/z2
b63e77129fefcb4f990ee1cb9952f4f708ee3a2b
[ "MIT" ]
3
2017-05-01T19:53:57.000Z
2018-08-27T20:14:43.000Z
museum_site/context_processors.py
DrDos0016/z2
b63e77129fefcb4f990ee1cb9952f4f708ee3a2b
[ "MIT" ]
null
null
null
museum_site/context_processors.py
DrDos0016/z2
b63e77129fefcb4f990ee1cb9952f4f708ee3a2b
[ "MIT" ]
1
2018-08-27T20:14:46.000Z
2018-08-27T20:14:46.000Z
from django.core.cache import cache from datetime import datetime from museum_site.models.detail import Detail from museum_site.models.file import File from museum_site.constants import TERMS_DATE from museum_site.common import ( DEBUG, EMAIL_ADDRESS, BOOT_TS, CSS_INCLUDES, UPLOAD_CAP, env_from_host, qs_sans ) from museum_site.core.detail_identifiers import *
30.441558
78
0.615614
29240155883a13930b0a3ee6e6cac004ba5b943f
671
py
Python
misago/users/views/avatarserver.py
HenryChenV/iJiangNan
68f156d264014939f0302222e16e3125119dd3e3
[ "MIT" ]
1
2017-07-25T03:04:36.000Z
2017-07-25T03:04:36.000Z
misago/users/views/avatarserver.py
HenryChenV/iJiangNan
68f156d264014939f0302222e16e3125119dd3e3
[ "MIT" ]
null
null
null
misago/users/views/avatarserver.py
HenryChenV/iJiangNan
68f156d264014939f0302222e16e3125119dd3e3
[ "MIT" ]
null
null
null
from django.contrib.auth import get_user_model from django.contrib.staticfiles.templatetags.staticfiles import static from django.shortcuts import redirect from misago.conf import settings UserModel = get_user_model()
23.964286
70
0.724292
2924b038d09501817eb856ed997e3ffe8a6813db
14,501
py
Python
csbdeep/internals/nets.py
papkov/CSBDeep
5624919fa71007bb2258592927e267967c62e25e
[ "BSD-3-Clause" ]
2
2019-07-20T08:55:29.000Z
2019-07-20T09:00:45.000Z
csbdeep/internals/nets.py
papkov/CSBDeep
5624919fa71007bb2258592927e267967c62e25e
[ "BSD-3-Clause" ]
null
null
null
csbdeep/internals/nets.py
papkov/CSBDeep
5624919fa71007bb2258592927e267967c62e25e
[ "BSD-3-Clause" ]
null
null
null
from __future__ import print_function, unicode_literals, absolute_import, division from six.moves import range, zip, map, reduce, filter from keras.layers import Input, Conv2D, Conv3D, Activation, Lambda from keras.models import Model from keras.layers.merge import Add, Concatenate import tensorflow as tf from keras import backend as K from .blocks import unet_block, unet_blocks, gaussian_2d import re from ..utils import _raise, backend_channels_last import numpy as np def custom_unet(input_shape, last_activation, n_depth=2, n_filter_base=16, kernel_size=(3,3,3), n_conv_per_depth=2, activation="relu", batch_norm=False, dropout=0.0, pool_size=(2,2,2), n_channel_out=1, residual=False, prob_out=False, long_skip=True, eps_scale=1e-3): """ TODO """ if last_activation is None: raise ValueError("last activation has to be given (e.g. 'sigmoid', 'relu')!") all((s % 2 == 1 for s in kernel_size)) or _raise(ValueError('kernel size should be odd in all dimensions.')) channel_axis = -1 if backend_channels_last() else 1 n_dim = len(kernel_size) # TODO: rewrite with conv_block conv = Conv2D if n_dim == 2 else Conv3D input = Input(input_shape, name="input") unet = unet_block(n_depth, n_filter_base, kernel_size, input_planes=input_shape[-1], activation=activation, dropout=dropout, batch_norm=batch_norm, n_conv_per_depth=n_conv_per_depth, pool=pool_size, long_skip=long_skip)(input) final = conv(n_channel_out, (1,)*n_dim, activation='linear')(unet) if residual: if not (n_channel_out == input_shape[-1] if backend_channels_last() else n_channel_out == input_shape[0]): raise ValueError("number of input and output channels must be the same for a residual net.") final = Add()([final, input]) final = Activation(activation=last_activation)(final) if prob_out: scale = conv(n_channel_out, (1,)*n_dim, activation='softplus')(unet) scale = Lambda(lambda x: x+np.float32(eps_scale))(scale) final = Concatenate(axis=channel_axis)([final, scale]) return Model(inputs=input, outputs=final) def uxnet(input_shape, n_depth=2, n_filter_base=16, kernel_size=(3, 3), n_conv_per_depth=2, activation="relu", last_activation='linear', batch_norm=False, dropout=0.0, pool_size=(2, 2), residual=True, odd_to_even=False, shortcut=None, shared_idx=[], prob_out=False, eps_scale=1e-3): """ Multi-body U-Net which learns identity by leaving one plane out in each branch :param input_shape: :param n_depth: :param n_filter_base: :param kernel_size: :param n_conv_per_depth: :param activation: :param last_activation: :param batch_norm: :param dropout: :param pool_size: :param prob_out: :param eps_scale: :return: Model """ # TODO: fill params # TODO: add odd-to-even mode # Define vars channel_axis = -1 if backend_channels_last() else 1 n_planes = input_shape[channel_axis] if n_planes % 2 != 0 and odd_to_even: raise ValueError('Odd-to-even mode does not support uneven number of planes') n_dim = len(kernel_size) conv = Conv2D if n_dim == 2 else Conv3D # Define functional model input = Input(shape=input_shape, name='input_main') # TODO test new implementation and remove old # Split planes (preserve channel) input_x = [Lambda(lambda x: x[..., i:i+1], output_shape=(None, None, 1))(input) for i in range(n_planes)] # We can train either in odd-to-even mode or in LOO mode if odd_to_even: # In this mode we stack together odd and even planes, train the net to predict even from odd and vice versa # input_x_out = [Concatenate(axis=-1)(input_x[j::2]) for j in range(2)] input_x_out = [Concatenate(axis=-1)(input_x[j::2]) for j in range(1, -1, -1)] else: # Concatenate planes back in leave-one-out way input_x_out = [Concatenate(axis=-1)([plane for i, plane in enumerate(input_x) if i != j]) for j in range(n_planes)] # if odd_to_even: # input_x_out = [Lambda(lambda x: x[..., j::2], # output_shape=(None, None, n_planes // 2), # name='{}_planes'.format('even' if j == 0 else 'odd'))(input) # for j in range(1, -1, -1)] # else: # # input_x_out = [Lambda(lambda x: x[..., tf.convert_to_tensor([i for i in range(n_planes) if i != j], dtype=tf.int32)], # # output_shape=(None, None, n_planes-1), # # name='leave_{}_plane_out'.format(j))(input) # # for j in range(n_planes)] # # input_x_out = [Lambda(lambda x: K.concatenate([x[..., :j], x[..., (j+1):]], axis=-1), # output_shape=(None, None, n_planes - 1), # name='leave_{}_plane_out'.format(j))(input) # for j in range(n_planes)] # U-Net parameters depend on mode (odd-to-even or LOO) n_blocks = 2 if odd_to_even else n_planes input_planes = n_planes // 2 if odd_to_even else n_planes-1 output_planes = n_planes // 2 if odd_to_even else 1 # Create U-Net blocks (by number of planes) unet_x = unet_blocks(n_blocks=n_blocks, input_planes=input_planes, output_planes=output_planes, n_depth=n_depth, n_filter_base=n_filter_base, kernel_size=kernel_size, activation=activation, dropout=dropout, batch_norm=batch_norm, n_conv_per_depth=n_conv_per_depth, pool=pool_size, shared_idx=shared_idx) unet_x = [unet(inp_out) for unet, inp_out in zip(unet_x, input_x_out)] # Version without weight sharing: # unet_x = [unet_block(n_depth, n_filter_base, kernel_size, # activation=activation, dropout=dropout, batch_norm=batch_norm, # n_conv_per_depth=n_conv_per_depth, pool=pool_size, # prefix='out_{}_'.format(i))(inp_out) for i, inp_out in enumerate(input_x_out)] # TODO: rewritten for sharing -- remove commented below # Convolve n_filter_base to 1 as each U-Net predicts a single plane # unet_x = [conv(1, (1,) * n_dim, activation=activation)(unet) for unet in unet_x] if residual: if odd_to_even: # For residual U-Net sum up output for odd planes with even planes and vice versa unet_x = [Add()([unet, inp]) for unet, inp in zip(unet_x, input_x[::-1])] else: # For residual U-Net sum up output with its neighbor (next for the first plane, previous for the rest unet_x = [Add()([unet, inp]) for unet, inp in zip(unet_x, [input_x[1]]+input_x[:-1])] # Concatenate outputs of blocks, should receive (None, None, None, n_planes) # TODO assert to check shape? if odd_to_even: # Split even and odd, assemble them together in the correct order # TODO tests unet_even = [Lambda(lambda x: x[..., i:i+1], output_shape=(None, None, 1), name='even_{}'.format(i))(unet_x[0]) for i in range(n_planes // 2)] unet_odd = [Lambda(lambda x: x[..., i:i+1], output_shape=(None, None, 1), name='odd_{}'.format(i))(unet_x[1]) for i in range(n_planes // 2)] unet_x = list(np.array(list(zip(unet_even, unet_odd))).flatten()) unet = Concatenate(axis=-1)(unet_x) if shortcut is not None: # We can create a shortcut without long skip connection to prevent noise memorization if shortcut == 'unet': shortcut_block = unet_block(long_skip=False, input_planes=n_planes, n_depth=n_depth, n_filter_base=n_filter_base, kernel_size=kernel_size, activation=activation, dropout=dropout, batch_norm=batch_norm, n_conv_per_depth=n_conv_per_depth, pool=pool_size)(input) shortcut_block = conv(n_planes, (1,) * n_dim, activation='linear', name='shortcut_final_conv')(shortcut_block) # Or a simple gaussian blur block elif shortcut == 'gaussian': shortcut_block = gaussian_2d(n_planes, k=13, s=7)(input) else: raise ValueError('Shortcut should be either unet or gaussian') # TODO add or concatenate? unet = Add()([unet, shortcut_block]) # unet = Concatenate(axis=-1)([unet, shortcut_unet]) # Final activation layer final = Activation(activation=last_activation)(unet) if prob_out: scale = conv(n_planes, (1,)*n_dim, activation='softplus')(unet) scale = Lambda(lambda x: x+np.float32(eps_scale))(scale) final = Concatenate(axis=channel_axis)([final, scale]) return Model(inputs=input, outputs=final) def common_unet(n_dim=2, n_depth=1, kern_size=3, n_first=16, n_channel_out=1, residual=True, prob_out=False, long_skip=True, last_activation='linear'): """ Construct a common CARE neural net based on U-Net [1]_ and residual learning [2]_ to be used for image restoration/enhancement. Parameters ---------- n_dim : int number of image dimensions (2 or 3) n_depth : int number of resolution levels of U-Net architecture kern_size : int size of convolution filter in all image dimensions n_first : int number of convolution filters for first U-Net resolution level (value is doubled after each downsampling operation) n_channel_out : int number of channels of the predicted output image residual : bool if True, model will internally predict the residual w.r.t. the input (typically better) requires number of input and output image channels to be equal prob_out : bool standard regression (False) or probabilistic prediction (True) if True, model will predict two values for each input pixel (mean and positive scale value) last_activation : str name of activation function for the final output layer Returns ------- function Function to construct the network, which takes as argument the shape of the input image Example ------- >>> model = common_unet(2, 1,3,16, 1, True, False)(input_shape) References ---------- .. [1] Olaf Ronneberger, Philipp Fischer, Thomas Brox, *U-Net: Convolutional Networks for Biomedical Image Segmentation*, MICCAI 2015 .. [2] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun. *Deep Residual Learning for Image Recognition*, CVPR 2016 """ return _build_this modelname = re.compile("^(?P<model>resunet|unet)(?P<n_dim>\d)(?P<prob_out>p)?_(?P<n_depth>\d+)_(?P<kern_size>\d+)_(?P<n_first>\d+)(_(?P<n_channel_out>\d+)out)?(_(?P<last_activation>.+)-last)?$") def common_unet_by_name(model): r"""Shorthand notation for equivalent use of :func:`common_unet`. Parameters ---------- model : str define model to be created via string, which is parsed as a regular expression: `^(?P<model>resunet|unet)(?P<n_dim>\d)(?P<prob_out>p)?_(?P<n_depth>\d+)_(?P<kern_size>\d+)_(?P<n_first>\d+)(_(?P<n_channel_out>\d+)out)?(_(?P<last_activation>.+)-last)?$` Returns ------- function Calls :func:`common_unet` with the respective parameters. Raises ------ ValueError If argument `model` is not a valid string according to the regular expression. Example ------- >>> model = common_unet_by_name('resunet2_1_3_16_1out')(input_shape) >>> # equivalent to: model = common_unet(2, 1,3,16, 1, True, False)(input_shape) Todo ---- Backslashes in docstring for regexp not rendered correctly. """ m = modelname.fullmatch(model) if m is None: raise ValueError("model name '%s' unknown, must follow pattern '%s'" % (model, modelname.pattern)) # from pprint import pprint # pprint(m.groupdict()) options = {k:int(m.group(k)) for k in ['n_depth','n_first','kern_size']} options['prob_out'] = m.group('prob_out') is not None options['residual'] = {'unet': False, 'resunet': True}[m.group('model')] options['n_dim'] = int(m.group('n_dim')) options['n_channel_out'] = 1 if m.group('n_channel_out') is None else int(m.group('n_channel_out')) if m.group('last_activation') is not None: options['last_activation'] = m.group('last_activation') return common_unet(**options) def receptive_field_unet(n_depth, kern_size, pool_size=2, n_dim=2, img_size=1024): """Receptive field for U-Net model (pre/post for each dimension).""" x = np.zeros((1,)+(img_size,)*n_dim+(1,)) mid = tuple([s//2 for s in x.shape[1:-1]]) x[(slice(None),) + mid + (slice(None),)] = 1 model = custom_unet ( x.shape[1:], n_depth=n_depth, kernel_size=[kern_size]*n_dim, pool_size=[pool_size]*n_dim, n_filter_base=8, activation='linear', last_activation='linear', ) y = model.predict(x)[0,...,0] y0 = model.predict(0*x)[0,...,0] ind = np.where(np.abs(y-y0)>0) return [(m-np.min(i), np.max(i)-m) for (m, i) in zip(mid, ind)]
42.65
194
0.626371
2926efa5e44ae3f3f146e72b77c97765b7854b95
1,602
py
Python
src/inf/runtime_data.py
feagi/feagi-core
d83c51480fcbe153fa14b2360b4d61f6ae4e2811
[ "Apache-2.0" ]
11
2020-02-18T16:03:10.000Z
2021-12-06T19:53:06.000Z
src/inf/runtime_data.py
feagi/feagi-core
d83c51480fcbe153fa14b2360b4d61f6ae4e2811
[ "Apache-2.0" ]
34
2019-12-17T04:59:42.000Z
2022-01-18T20:58:46.000Z
src/inf/runtime_data.py
feagi/feagi-core
d83c51480fcbe153fa14b2360b4d61f6ae4e2811
[ "Apache-2.0" ]
3
2019-12-16T06:09:56.000Z
2020-10-18T12:01:31.000Z
parameters = {} genome = {} genome_stats = {} genome_test_stats = [] brain = {} cortical_list = [] cortical_map = {} intercortical_mapping = [] block_dic = {} upstream_neurons = {} memory_list = {} activity_stats = {} temp_neuron_list = [] original_genome_id = [] fire_list = [] termination_flag = False variation_counter_actual = 0 exposure_counter_actual = 0 mnist_training = {} mnist_testing = {} top_10_utf_memory_neurons = {} top_10_utf_neurons = {} v1_members = [] prunning_candidates = set() genome_id = "" event_id = '_' blueprint = "" comprehension_queue = '' working_directory = '' connectome_path = '' paths = {} watchdog_queue = '' exit_condition = False fcl_queue = '' proximity_queue = '' last_ipu_activity = '' last_alertness_trigger = '' influxdb = '' mongodb = '' running_in_container = False hardware = '' gazebo = False stimulation_data = {} hw_controller_path = '' hw_controller = None opu_pub = None router_address = None burst_timer = 1 # rules = "" brain_is_running = False # live_mode_status can have modes of idle, learning, testing, tbd live_mode_status = 'idle' fcl_history = {} brain_run_id = "" burst_detection_list = {} burst_count = 0 fire_candidate_list = {} previous_fcl = {} future_fcl = {} labeled_image = [] training_neuron_list_utf = {} training_neuron_list_img = {} empty_fcl_counter = 0 neuron_mp_list = [] pain_flag = False cumulative_neighbor_count = 0 time_neuron_update = '' time_apply_plasticity_ext = '' plasticity_time_total = None plasticity_time_total_p1 = None plasticity_dict = {} tester_test_stats = {} # Flags flag_ready_to_inject_image = False
20.025
65
0.737828
2928594f2134be43b667f4c09f4d5b6dedb23ea3
494
py
Python
scripts/topo_countries.py
taufikhe/Censof-Mini-Project
44ced8c3176a58705de4d247c3ec79c664a4951f
[ "MIT" ]
null
null
null
scripts/topo_countries.py
taufikhe/Censof-Mini-Project
44ced8c3176a58705de4d247c3ec79c664a4951f
[ "MIT" ]
null
null
null
scripts/topo_countries.py
taufikhe/Censof-Mini-Project
44ced8c3176a58705de4d247c3ec79c664a4951f
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- import subprocess from geonamescache import GeonamesCache gc = GeonamesCache() toposrc = '../data/states-provinces.json' for iso2, country in gc.get_countries().items(): iso3 = country['iso3'] topojson = 'mapshaper -i {0} -filter \'"{1}" == adm0_a3\' -filter-fields fips,name -o format=topojson {1}.json' subprocess.call(topojson.format(toposrc, iso3), shell=True) subprocess.call('mv *.json ../src/topojson/countries/', shell=True)
32.933333
115
0.694332
29288c1ce5e2846258708e5fc3231b1fb34cbf4a
10,768
py
Python
nordb/database/nordic2sql.py
MrCubanfrog/NorDB
8348733d10799e9ae40744fbd7b200fcc09a9a3a
[ "MIT" ]
1
2021-06-08T20:46:10.000Z
2021-06-08T20:46:10.000Z
nordb/database/nordic2sql.py
MrCubanfrog/NorDB
8348733d10799e9ae40744fbd7b200fcc09a9a3a
[ "MIT" ]
null
null
null
nordb/database/nordic2sql.py
MrCubanfrog/NorDB
8348733d10799e9ae40744fbd7b200fcc09a9a3a
[ "MIT" ]
null
null
null
""" This module contains all information for pushing a NordicEvent object into the database. Functions and Classes --------------------- """ import psycopg2 import os import re import datetime from nordb.core import usernameUtilities from nordb.database import creationInfo INSERT_COMMANDS = { 1: ( "INSERT INTO " "nordic_header_main " "(origin_time, origin_date, location_model, " "distance_indicator, event_desc_id, epicenter_latitude, " "epicenter_longitude, depth, depth_control, " "locating_indicator, epicenter_reporting_agency, " "stations_used, rms_time_residuals, magnitude_1, " "type_of_magnitude_1, magnitude_reporting_agency_1, " "magnitude_2, type_of_magnitude_2, magnitude_reporting_agency_2, " "magnitude_3, type_of_magnitude_3, magnitude_reporting_agency_3, " "event_id) " "VALUES " "(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, " "%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) " "RETURNING " "id;" ), 2: ( "INSERT INTO " "nordic_header_macroseismic " "(description, diastrophism_code, tsunami_code, seiche_code, " "cultural_effects, unusual_effects, maximum_observed_intensity, " "maximum_intensity_qualifier, intensity_scale, macroseismic_latitude, " "macroseismic_longitude, macroseismic_magnitude, type_of_magnitude, " "logarithm_of_radius, logarithm_of_area_1, bordering_intensity_1, " "logarithm_of_area_2, bordering_intensity_2, quality_rank, " "reporting_agency, event_id) " "VALUES " "(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, " " %s, %s, %s, %s, %s, %s) " "RETURNING " "id" ), 3: ( "INSERT INTO " "nordic_header_comment " "(h_comment, event_id) " "VALUES " "(%s, %s) " "RETURNING " "id " ), 5: ( "INSERT INTO " "nordic_header_error " "(gap, second_error, epicenter_latitude_error, " "epicenter_longitude_error, depth_error, " "magnitude_error, header_id) " "VALUES " "(%s, %s, %s, %s, %s, %s, %s)" "RETURNING " "id" ), 6: ( "INSERT INTO " "nordic_header_waveform " "(waveform_info, event_id) " "VALUES " "(%s, %s) " "RETURNING " "id " ), 7: ( "INSERT INTO " "nordic_phase_data " "(station_code, sp_instrument_type, sp_component, quality_indicator, " "phase_type, weight, first_motion, observation_time, " "signal_duration, max_amplitude, max_amplitude_period, back_azimuth, " "apparent_velocity, signal_to_noise, azimuth_residual, " "travel_time_residual, location_weight, epicenter_distance, " "epicenter_to_station_azimuth, event_id) " "VALUES " "(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, " "%s, %s, %s, %s, %s, %s, %s, %s, %s) " "RETURNING " "id " ), } def event2Database(nordic_event, solution_type = "O", nordic_filename = None, f_creation_id = None, e_id = -1, privacy_level='public', db_conn = None): """ Function that pushes a NordicEvent object to the database :param NordicEvent nordic_event: Event that will be pushed to the database :param int solution_type: event type id :param str nordic_filename: name of the file from which the nordic is read from :param int f_creation_id: id of the creation_info entry in the database :param int e_id: id of the event to which this event will be attached to by event_root. If -1 then this event will not be attached to aything. :param string privacy_level: privacy level of the event in the database """ if db_conn is None: conn = usernameUtilities.log2nordb() else: conn = db_conn if f_creation_id is None: creation_id = creationInfo.createCreationInfo(privacy_level, conn) else: creation_id = f_creation_id author_id = None for header in nordic_event.comment_h: search = re.search(r'\((\w{3})\)', header.h_comment) if search is not None: author_id = search.group(0)[1:-1] if author_id is None: author_id = '---' cur = conn.cursor() try: cur.execute("SELECT allow_multiple FROM solution_type WHERE type_id = %s", (solution_type,)) ans = cur.fetchone() if ans is None: raise Exception("{0} is not a valid solution_type! Either add the event type to the database or use another solution_type".format(solution_type)) allow_multiple = ans[0] filename_id = -1 cur.execute("SELECT id FROM nordic_file WHERE file_location = %s", (nordic_filename,)) filenameids = cur.fetchone() if filenameids is not None: filename_id = filenameids[0] root_id = -1 if nordic_event.root_id != -1: root_id = nordic_event.root_id if e_id >= 0: cur.execute("SELECT root_id, solution_type FROM nordic_event WHERE id = %s", (e_id,)) try: root_id, old_solution_type = cur.fetchone() except: raise Exception("Given linking even_id does not exist in the database!") if e_id == -1 and nordic_event.root_id == -1: cur.execute("INSERT INTO nordic_event_root DEFAULT VALUES RETURNING id;") root_id = cur.fetchone()[0] if filename_id == -1: cur.execute("INSERT INTO nordic_file (file_location) VALUES (%s) RETURNING id", (nordic_filename,)) filename_id = cur.fetchone()[0] cur.execute("INSERT INTO " + "nordic_event " + "(solution_type, root_id, nordic_file_id, author_id, creation_id) " + "VALUES " + "(%s, %s, %s, %s, %s) " + "RETURNING " + "id", (solution_type, root_id, filename_id, author_id, creation_id) ) event_id = cur.fetchone()[0] nordic_event.event_id = event_id if e_id != -1 and solution_type == old_solution_type and not allow_multiple: cur.execute("UPDATE nordic_event SET solution_type = 'O' WHERE id = %s", (e_id,)) main_header_id = -1 for main in nordic_event.main_h: main.event_id = event_id main.h_id = executeCommand( cur, INSERT_COMMANDS[1], main.getAsList(), True)[0][0] if main.error_h is not None: main.error_h.header_id = main.h_id main.error_h.h_id = executeCommand( cur, INSERT_COMMANDS[5], main.error_h.getAsList(), True)[0][0] for macro in nordic_event.macro_h: macro.event_id = event_id macro.h_id = executeCommand(cur, INSERT_COMMANDS[2], macro.getAsList(), True)[0][0] for comment in nordic_event.comment_h: comment.event_id = event_id comment.h_id = executeCommand( cur, INSERT_COMMANDS[3], comment.getAsList(), True)[0][0] for waveform in nordic_event.waveform_h: waveform.event_id = event_id waveform.h_id = executeCommand( cur, INSERT_COMMANDS[6], waveform.getAsList(), True)[0][0] for phase_data in nordic_event.data: phase_data.event_id = event_id d_id = executeCommand( cur, INSERT_COMMANDS[7], phase_data.getAsList(), True)[0][0] phase_data.d_id = d_id conn.commit() except Exception as e: raise e finally: if f_creation_id is None: creationInfo.deleteCreationInfoIfUnnecessary(creation_id, db_conn=conn) if db_conn is None: conn.close() def executeCommand(cur, command, vals, returnValue): """ Function for for executing a command with values and handling exceptions :param Psycopg.Cursor cur: cursor object from psycopg2 library :param str command: the sql command string :param list vals: list of values for the command :param bool returnValue: boolean values for if the command returns a value :returns: Values returned by the query or None if returnValue is False """ cur.execute(command, vals) if returnValue: return cur.fetchall() else: return None
42.393701
157
0.474554
29289d486b584b87f177ccbe912f80c30f1f15ef
973
py
Python
movie_trailer_website/media.py
mradenovic/movie-trailer-website
08f53af08f9aeaa1deb5a10fa391e02aa7274ca3
[ "MIT" ]
null
null
null
movie_trailer_website/media.py
mradenovic/movie-trailer-website
08f53af08f9aeaa1deb5a10fa391e02aa7274ca3
[ "MIT" ]
null
null
null
movie_trailer_website/media.py
mradenovic/movie-trailer-website
08f53af08f9aeaa1deb5a10fa391e02aa7274ca3
[ "MIT" ]
null
null
null
"""This module contains class definitions for storing media files""" import webbrowser
33.551724
84
0.651593
292a0a9f6e7bb7e898c14f4da99751f0b33adf70
1,700
py
Python
201-vmss-bottle-autoscale/workserver.py
kollexy/azure-quickstart-templates
02dd10e4004db1f52e772a474d460620ff975270
[ "MIT" ]
10
2020-03-17T14:22:57.000Z
2022-02-12T02:42:30.000Z
201-vmss-bottle-autoscale/workserver.py
kollexy/azure-quickstart-templates
02dd10e4004db1f52e772a474d460620ff975270
[ "MIT" ]
17
2020-08-12T09:28:42.000Z
2021-10-11T05:16:45.000Z
201-vmss-bottle-autoscale/workserver.py
gjlumsden/azure-quickstart-templates
70935bff823b8650386f6d3223dc199a66c4efd2
[ "MIT" ]
16
2019-06-28T09:49:29.000Z
2022-02-05T16:35:36.000Z
# workserver.py - simple HTTP server with a do_work / stop_work API # GET /do_work activates a worker thread which uses CPU # GET /stop_work signals worker thread to stop import math import socket import threading import time from bottle import route, run hostname = socket.gethostname() hostport = 9000 keepworking = False # boolean to switch worker thread on or off # thread which maximizes CPU usage while the keepWorking global is True # start the worker thread worker_thread = threading.Thread(target=workerthread, args=()) worker_thread.start() run(host=hostname, port=hostport)
25
106
0.657059
292abc115693fa0811cb421e9f5c9743d0e6e3a6
7,521
py
Python
year_3/databases_sem1/lab1/cli.py
honchardev/KPI
f8425681857c02a67127ffb05c0af0563a8473e1
[ "MIT" ]
null
null
null
year_3/databases_sem1/lab1/cli.py
honchardev/KPI
f8425681857c02a67127ffb05c0af0563a8473e1
[ "MIT" ]
21
2020-03-24T16:26:04.000Z
2022-02-18T15:56:16.000Z
year_3/databases_sem1/lab1/cli.py
honchardev/KPI
f8425681857c02a67127ffb05c0af0563a8473e1
[ "MIT" ]
null
null
null
from maxdb import DB def _open(self): """Create DB instance and preload default models.""" self._db = DB(self._path) products = self._db.table( 'Products', columns={'name': 'str', 'price': 'int'} ) orders = self._db.table( 'Orders', columns={'product': 'fk', 'client': 'str', 'destination': 'addr'} ) try: products.insert_multiple([ {"name": ("product1", "str"), "price": ("50", "int")}, {"name": ("product2", "str"), "price": ("100", "int")}, {"name": ("product3", "str"), "price": ("200", "int")}, ]) except: pass try: orders.insert_multiple([ { "product": ({'table': 'Products', 'fkid': '1'}, 'fk'), "client": ("honchar", "str"), "destination": ("Kyiv", "addr") }, { "product": ({'table': 'Products', 'fkid': '2'}, 'fk'), "client": ("honchar2", "str"), "destination": ("Kyiv2", "addr") }, { "product": ({'table': 'Products', 'fkid': '3'}, 'fk'), "client": ("honchar3", "str"), "destination": ("Kyiv3", "addr") }, ]) except: pass self.run('help', *()) def _close(self, _): """Close DB instance routine.""" self._db.close() def __enter__(self): self._open() return self def __exit__(self, exc_type, exc_val, exc_tb): self._close(None)
37.049261
108
0.505252
292adf5e7c8f6222d531917fc0a7844f832f27cb
1,348
py
Python
Ar_Script/past/eg_用户信息用户界面.py
archerckk/PyTest
610dd89df8d70c096f4670ca11ed2f0ca3196ca5
[ "MIT" ]
null
null
null
Ar_Script/past/eg_用户信息用户界面.py
archerckk/PyTest
610dd89df8d70c096f4670ca11ed2f0ca3196ca5
[ "MIT" ]
1
2020-01-19T01:19:57.000Z
2020-01-19T01:19:57.000Z
Ar_Script/past/eg_用户信息用户界面.py
archerckk/PyTest
610dd89df8d70c096f4670ca11ed2f0ca3196ca5
[ "MIT" ]
null
null
null
import easygui as g # judge=1 # def judge_null(tmp): # if tmp.isspace()or len(tmp)==0: # return judge==0 # # while 1: # user_info=g.multenterbox(title='', # msg='*\t*\t*\t*E-mail', # fields=['*','*','','*','QQ','*E-mail'] # ) # # if judge_null(user_info[0])==0: # g.msgbox(title='',msg='') # elif judge_null(user_info[1])==0: # g.msgbox(title='',msg='') # elif judge_null(user_info[3])==0: # g.msgbox(title='',msg='') # elif judge_null(user_info[5])==0: # g.msgbox(title='',msg='E-mail') # else: # g.msgbox(title='',msg='') # break #2 title='' msg='' field_list=['*','*','','*','QQ','*E-mail'] field_value=[] field_value = g.multenterbox(msg,title,field_list) while 1: if field_value==None: break err_msg='' for i in range(len(field_list)): option=field_list[i].strip() if field_value[i].strip()==''and option[0]=='*': err_msg+='%s\n\n'%(field_list[i]) if err_msg=='': break field_value = g.multenterbox(err_msg, title, field_list,field_value) print(''+str(field_value))
29.304348
85
0.568249
292ba35b429971f678a3c9a45a66bf36fb9ad5d7
962
py
Python
examples/pspm_pupil/model_defs.py
fmelinscak/cognibench
372513b8756a342c0df222dcea5ff6d1d69fbcec
[ "MIT" ]
3
2020-07-31T00:42:40.000Z
2021-03-19T03:08:19.000Z
examples/pspm_pupil/model_defs.py
fmelinscak/cognibench
372513b8756a342c0df222dcea5ff6d1d69fbcec
[ "MIT" ]
null
null
null
examples/pspm_pupil/model_defs.py
fmelinscak/cognibench
372513b8756a342c0df222dcea5ff6d1d69fbcec
[ "MIT" ]
1
2020-11-13T23:13:34.000Z
2020-11-13T23:13:34.000Z
from cognibench.models import CNBModel from cognibench.capabilities import ContinuousAction, ContinuousObservation from cognibench.continuous import ContinuousSpace from cognibench.models.wrappers import MatlabWrapperMixin
34.357143
87
0.705821
292c8b618a05d121aa88ca4e594589616cd5c14c
254
py
Python
core/layouts/pixel_list.py
TheGentlemanOctopus/oracle
2857b9c1886548d9aefcb480ce6e77169ee9e7ef
[ "MIT" ]
null
null
null
core/layouts/pixel_list.py
TheGentlemanOctopus/oracle
2857b9c1886548d9aefcb480ce6e77169ee9e7ef
[ "MIT" ]
6
2018-05-13T14:44:20.000Z
2018-07-10T10:12:08.000Z
core/layouts/pixel_list.py
TheGentlemanOctopus/oracle
2857b9c1886548d9aefcb480ce6e77169ee9e7ef
[ "MIT" ]
null
null
null
from layout import Layout
21.166667
54
0.562992
292db3dd254935b6485aa3e5a0431e5e9297d7e2
2,328
py
Python
test/programytest/clients/restful/test_config.py
minhdc/documented-programy
fe947d68c0749201fbe93ee5644d304235d0c626
[ "MIT" ]
null
null
null
test/programytest/clients/restful/test_config.py
minhdc/documented-programy
fe947d68c0749201fbe93ee5644d304235d0c626
[ "MIT" ]
null
null
null
test/programytest/clients/restful/test_config.py
minhdc/documented-programy
fe947d68c0749201fbe93ee5644d304235d0c626
[ "MIT" ]
null
null
null
import unittest from programy.config.file.yaml_file import YamlConfigurationFile from programy.clients.restful.config import RestConfiguration from programy.clients.events.console.config import ConsoleConfiguration
36.375
93
0.660653
29313d16ae55bd60b3205923aa0959f4632a0038
1,211
py
Python
Assignments/06.py
zexhan17/Data-Structures-and-Algorithms-using-Python
b5fd3d47c2eb7bf93eb88b276799d6663cd602e4
[ "MIT" ]
null
null
null
Assignments/06.py
zexhan17/Data-Structures-and-Algorithms-using-Python
b5fd3d47c2eb7bf93eb88b276799d6663cd602e4
[ "MIT" ]
null
null
null
Assignments/06.py
zexhan17/Data-Structures-and-Algorithms-using-Python
b5fd3d47c2eb7bf93eb88b276799d6663cd602e4
[ "MIT" ]
null
null
null
# Write a recursive function to count the number of nodes in a Tree. (first do your self then see code) Q # 2: '''The height of a tree is the maximum number of levels in the tree. So, a tree with just one node has a height of 1. If the root has children which are leaves, the height of the tree is 2. The height of a TreeNode can be computed recursively using a simple algorithm: The height Of a TreeNode With no children is 1. If it has children the height is: max of height of its two sub-trees + 1. Write a clean, recursive function for the TreeNode class that calculates the height based on the above statement(first do your self then see code) ''' print(self.val) if self.left.val > self.val or self.right.val < self.val return False
31.868421
201
0.734104
29320044fb1e6ea2d550bb85edcedd897afb61eb
28,020
py
Python
flask_app.py
mdaeron/clumpycrunch
463d9241477acc557c4635b4d4f1f5338bf37617
[ "BSD-3-Clause" ]
null
null
null
flask_app.py
mdaeron/clumpycrunch
463d9241477acc557c4635b4d4f1f5338bf37617
[ "BSD-3-Clause" ]
1
2020-05-27T21:09:16.000Z
2020-05-27T21:09:16.000Z
flask_app.py
mdaeron/clumpycrunch
463d9241477acc557c4635b4d4f1f5338bf37617
[ "BSD-3-Clause" ]
null
null
null
#! /usr/bin/env python3 # from datetime import datetime # from random import choices # from string import ascii_lowercase from flask import Flask, request, render_template, Response, send_file from flaskext.markdown import Markdown from D47crunch import D47data, pretty_table, make_csv, smart_type from D47crunch import __version__ as vD47crunch import zipfile, io, time from pylab import * from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas import base64 from werkzeug.wsgi import FileWrapper from matplotlib import rcParams # rcParams['backend'] = 'Agg' # rcParams['interactive'] = False rcParams['font.family'] = 'Helvetica' rcParams['font.sans-serif'] = 'Helvetica' rcParams['font.size'] = 10 rcParams['mathtext.fontset'] = 'custom' rcParams['mathtext.rm'] = 'sans' rcParams['mathtext.bf'] = 'sans:bold' rcParams['mathtext.it'] = 'sans:italic' rcParams['mathtext.cal'] = 'sans:italic' rcParams['mathtext.default'] = 'rm' rcParams['xtick.major.size'] = 4 rcParams['xtick.major.width'] = 1 rcParams['ytick.major.size'] = 4 rcParams['ytick.major.width'] = 1 rcParams['axes.grid'] = False rcParams['axes.linewidth'] = 1 rcParams['grid.linewidth'] = .75 rcParams['grid.linestyle'] = '-' rcParams['grid.alpha'] = .15 rcParams['savefig.dpi'] = 150 __author__ = 'Mathieu Daron' __contact__ = 'daeron@lsce.ipsl.fr' __copyright__ = 'Copyright (c) 2020 Mathieu Daron' __license__ = 'Modified BSD License - https://opensource.org/licenses/BSD-3-Clause' __date__ = '2020-04-22' __version__ = '2.1.dev2' rawdata_input_str = '''UID\tSession\tSample\td45\td46\td47\tNominal_d13C_VPDB\tNominal_d18O_VPDB A01\tSession01\tETH-1\t5.795017\t11.627668\t16.893512\t2.02\t-2.19 A02\tSession01\tIAEA-C1\t6.219070\t11.491072\t17.277490 A03\tSession01\tETH-2\t-6.058681\t-4.817179\t-11.635064\t-10.17\t-18.69 A04\tSession01\tIAEA-C2\t-3.861839\t4.941839\t0.606117 A05\tSession01\tETH-3\t5.543654\t12.052277\t17.405548\t1.71\t-1.78 A06\tSession01\tMERCK\t-35.929352\t-2.087501\t-39.548484 A07\tSession01\tETH-4\t-6.222218\t-5.194170\t-11.944111 A08\tSession01\tETH-2\t-6.067055\t-4.877104\t-11.699265\t-10.17\t-18.69 A09\tSession01\tMERCK\t-35.930739\t-2.080798\t-39.545632 A10\tSession01\tETH-1\t5.788207\t11.559104\t16.801908\t2.02\t-2.19 A11\tSession01\tETH-4\t-6.217508\t-5.221407\t-11.987503 A12\tSession01\tIAEA-C2\t-3.876921\t4.868892\t0.521845 A13\tSession01\tETH-3\t5.539840\t12.013444\t17.368631\t1.71\t-1.78 A14\tSession01\tIAEA-C1\t6.219046\t11.447846\t17.234280 A15\tSession01\tMERCK\t-35.932060\t-2.088659\t-39.531627 A16\tSession01\tETH-3\t5.516658\t11.978320\t17.295740\t1.71\t-1.78 A17\tSession01\tETH-4\t-6.223370\t-5.253980\t-12.025298 A18\tSession01\tETH-2\t-6.069734\t-4.868368\t-11.688559\t-10.17\t-18.69 A19\tSession01\tIAEA-C1\t6.213642\t11.465109\t17.244547 A20\tSession01\tETH-1\t5.789982\t11.535603\t16.789811\t2.02\t-2.19 A21\tSession01\tETH-4\t-6.205703\t-5.144529\t-11.909160 A22\tSession01\tIAEA-C1\t6.212646\t11.406548\t17.187214 A23\tSession01\tETH-3\t5.531413\t11.976697\t17.332700\t1.71\t-1.78 A24\tSession01\tMERCK\t-35.926347\t-2.124579\t-39.582201 A25\tSession01\tETH-1\t5.786979\t11.527864\t16.775547\t2.02\t-2.19 A26\tSession01\tIAEA-C2\t-3.866505\t4.874630\t0.525332 A27\tSession01\tETH-2\t-6.076302\t-4.922424\t-11.753283\t-10.17\t-18.69 A28\tSession01\tIAEA-C2\t-3.878438\t4.818588\t0.467595 A29\tSession01\tETH-3\t5.546458\t12.133931\t17.501646\t1.71\t-1.78 A30\tSession01\tETH-1\t5.802916\t11.642685\t16.904286\t2.02\t-2.19 A31\tSession01\tETH-2\t-6.069274\t-4.847919\t-11.677722\t-10.17\t-18.69 A32\tSession01\tETH-3\t5.523018\t12.007363\t17.362080\t1.71\t-1.78 A33\tSession01\tETH-1\t5.802333\t11.616032\t16.884255\t2.02\t-2.19 A34\tSession01\tETH-3\t5.537375\t12.000263\t17.350856\t1.71\t-1.78 A35\tSession01\tETH-2\t-6.060713\t-4.893088\t-11.728465\t-10.17\t-18.69 A36\tSession01\tETH-3\t5.532342\t11.990022\t17.342273\t1.71\t-1.78 A37\tSession01\tETH-3\t5.533622\t11.980853\t17.342245\t1.71\t-1.78 A38\tSession01\tIAEA-C2\t-3.867587\t4.893554\t0.540404 A39\tSession01\tIAEA-C1\t6.201760\t11.406628\t17.189625 A40\tSession01\tETH-1\t5.802150\t11.563414\t16.836189\t2.02\t-2.19 A41\tSession01\tETH-2\t-6.068598\t-4.897545\t-11.722343\t-10.17\t-18.69 A42\tSession01\tMERCK\t-35.928359\t-2.098440\t-39.577150 A43\tSession01\tETH-4\t-6.219175\t-5.168031\t-11.936923 A44\tSession01\tIAEA-C2\t-3.871671\t4.871517\t0.518290 B01\tSession02\tETH-1\t5.800180\t11.640916\t16.939044\t2.02\t-2.19 B02\tSession02\tETH-1\t5.799584\t11.631297\t16.917656\t2.02\t-2.19 B03\tSession02\tIAEA-C1\t6.225135\t11.512637\t17.335876 B04\tSession02\tETH-2\t-6.030415\t-4.746444\t-11.525506\t-10.17\t-18.69 B05\tSession02\tIAEA-C2\t-3.837017\t4.992780\t0.675292 B06\tSession02\tETH-3\t5.536997\t12.048918\t17.420228\t1.71\t-1.78 B07\tSession02\tMERCK\t-35.928379\t-2.105615\t-39.594573 B08\tSession02\tETH-4\t-6.218801\t-5.185168\t-11.964407 B09\tSession02\tETH-2\t-6.068197\t-4.840037\t-11.686296\t-10.17\t-18.69 B10\tSession02\tMERCK\t-35.926951\t-2.071047\t-39.546767 B11\tSession02\tETH-1\t5.782634\t11.571818\t16.835185\t2.02\t-2.19 B12\tSession02\tETH-2\t-6.070168\t-4.877700\t-11.703876\t-10.17\t-18.69 B13\tSession02\tETH-4\t-6.214873\t-5.190550\t-11.967040 B14\tSession02\tIAEA-C2\t-3.853550\t4.919425\t0.584634 B15\tSession02\tETH-3\t5.522265\t12.011737\t17.368407\t1.71\t-1.78 B16\tSession02\tIAEA-C1\t6.219374\t11.447014\t17.264258 B17\tSession02\tMERCK\t-35.927733\t-2.103033\t-39.603494 B18\tSession02\tETH-3\t5.527002\t11.984062\t17.332660\t1.71\t-1.78 B19\tSession02\tIAEA-C2\t-3.850358\t4.889230\t0.562794 B20\tSession02\tETH-4\t-6.222398\t-5.263817\t-12.033650 B21\tSession02\tETH-3\t5.525478\t11.970096\t17.340498\t1.71\t-1.78 B22\tSession02\tETH-2\t-6.070129\t-4.941487\t-11.773824\t-10.17\t-18.69 B23\tSession02\tIAEA-C1\t6.217001\t11.434152\t17.232308 B24\tSession02\tETH-1\t5.793421\t11.533191\t16.810838\t2.02\t-2.19 B25\tSession02\tETH-4\t-6.217740\t-5.198048\t-11.977179 B26\tSession02\tIAEA-C1\t6.216912\t11.425200\t17.234224 B27\tSession02\tETH-3\t5.522238\t11.932174\t17.286903\t1.71\t-1.78 B28\tSession02\tMERCK\t-35.914404\t-2.133955\t-39.614612 B29\tSession02\tETH-1\t5.784156\t11.517244\t16.786548\t2.02\t-2.19 B30\tSession02\tIAEA-C2\t-3.852750\t4.884339\t0.551587 B31\tSession02\tETH-2\t-6.068631\t-4.924103\t-11.764507\t-10.17\t-18.69 B32\tSession02\tETH-4\t-6.220238\t-5.231375\t-12.009300 B33\tSession02\tIAEA-C2\t-3.855245\t4.866571\t0.534914 B34\tSession02\tETH-1\t5.788790\t11.544306\t16.809117\t2.02\t-2.19 B35\tSession02\tMERCK\t-35.935017\t-2.173682\t-39.664046 B36\tSession02\tETH-3\t5.518320\t11.955048\t17.300668\t1.71\t-1.78 B37\tSession02\tETH-1\t5.790564\t11.521174\t16.781304\t2.02\t-2.19 B38\tSession02\tETH-4\t-6.218809\t-5.205256\t-11.979998 B39\tSession02\tIAEA-C1\t6.204774\t11.391335\t17.181310 B40\tSession02\tETH-2\t-6.076424\t-4.967973\t-11.815466\t-10.17\t-18.69 C01\tSession03\tETH-3\t5.541868\t12.129615\t17.503738\t1.71\t-1.78 C02\tSession03\tETH-3\t5.534395\t12.034601\t17.391274\t1.71\t-1.78 C03\tSession03\tETH-1\t5.797568\t11.563575\t16.857871\t2.02\t-2.19 C04\tSession03\tETH-3\t5.529415\t11.969512\t17.342673\t1.71\t-1.78 C05\tSession03\tETH-1\t5.794026\t11.526540\t16.806934\t2.02\t-2.19 C06\tSession03\tETH-3\t5.527210\t11.937462\t17.294015\t1.71\t-1.78 C07\tSession03\tIAEA-C1\t6.220521\t11.430197\t17.242458 C08\tSession03\tETH-2\t-6.064061\t-4.900852\t-11.732976\t-10.17\t-18.69 C09\tSession03\tIAEA-C2\t-3.846482\t4.889242\t0.558395 C10\tSession03\tETH-1\t5.789644\t11.520663\t16.795837\t2.02\t-2.19 C11\tSession03\tETH-4\t-6.219385\t-5.258604\t-12.036476 C12\tSession03\tMERCK\t-35.936631\t-2.161769\t-39.693775 C13\tSession03\tETH-2\t-6.076357\t-4.939912\t-11.803553\t-10.17\t-18.69 C14\tSession03\tIAEA-C2\t-3.862518\t4.850015\t0.499777 C15\tSession03\tETH-3\t5.515822\t11.928316\t17.287739\t1.71\t-1.78 C16\tSession03\tETH-4\t-6.216625\t-5.252914\t-12.033781 C17\tSession03\tETH-1\t5.792540\t11.537788\t16.801906\t2.02\t-2.19 C18\tSession03\tIAEA-C1\t6.218853\t11.447394\t17.270859 C19\tSession03\tETH-2\t-6.070107\t-4.944520\t-11.806885\t-10.17\t-18.69 C20\tSession03\tMERCK\t-35.935001\t-2.155577\t-39.675070 C21\tSession03\tETH-3\t5.542309\t12.082338\t17.471951\t1.71\t-1.78 C22\tSession03\tETH-4\t-6.209017\t-5.137393\t-11.920935 C23\tSession03\tETH-1\t5.796781\t11.621197\t16.905496\t2.02\t-2.19 C24\tSession03\tMERCK\t-35.926449\t-2.053921\t-39.576918 C25\tSession03\tETH-2\t-6.057158\t-4.797641\t-11.644824\t-10.17\t-18.69 C26\tSession03\tIAEA-C1\t6.221982\t11.501725\t17.321709 C27\tSession03\tETH-3\t5.535162\t12.023486\t17.396560\t1.71\t-1.78 C28\tSession03\tIAEA-C2\t-3.836934\t4.984196\t0.665651 C29\tSession03\tETH-3\t5.531331\t11.991300\t17.353622\t1.71\t-1.78 C30\tSession03\tIAEA-C2\t-3.844008\t4.926554\t0.601156 C31\tSession03\tETH-2\t-6.063163\t-4.907454\t-11.765065\t-10.17\t-18.69 C32\tSession03\tMERCK\t-35.941566\t-2.163022\t-39.704731 C33\tSession03\tETH-3\t5.523894\t11.992718\t17.363902\t1.71\t-1.78 C34\tSession03\tIAEA-C1\t6.220801\t11.462090\t17.282153 C35\tSession03\tETH-1\t5.794369\t11.563017\t16.845673\t2.02\t-2.19 C36\tSession03\tETH-4\t-6.221257\t-5.272969\t-12.055444 C37\tSession03\tETH-3\t5.517832\t11.957180\t17.312487\t1.71\t-1.78 C38\tSession03\tETH-2\t-6.053330\t-4.909476\t-11.740852\t-10.17\t-18.69 C39\tSession03\tIAEA-C1\t6.217139\t11.440085\t17.244787 C40\tSession03\tETH-1\t5.794091\t11.541948\t16.826158\t2.02\t-2.19 C41\tSession03\tIAEA-C2\t-3.803466\t4.894953\t0.624184 C42\tSession03\tETH-3\t5.513788\t11.933062\t17.286883\t1.71\t-1.78 C43\tSession03\tETH-1\t5.793334\t11.569668\t16.844535\t2.02\t-2.19 C44\tSession03\tETH-2\t-6.064928\t-4.935031\t-11.786336\t-10.17\t-18.69 C45\tSession03\tETH-4\t-6.216796\t-5.300373\t-12.075033 C46\tSession03\tETH-3\t5.521772\t11.933713\t17.283775\t1.71\t-1.78 C47\tSession03\tMERCK\t-35.937762\t-2.181553\t-39.739636 D01\tSession04\tETH-4\t-6.218867\t-5.242334\t-12.032129 D02\tSession04\tIAEA-C1\t6.218458\t11.435622\t17.238776 D03\tSession04\tETH-3\t5.522006\t11.946540\t17.300601\t1.71\t-1.78 D04\tSession04\tMERCK\t-35.931765\t-2.175265\t-39.716152 D05\tSession04\tETH-1\t5.786884\t11.560397\t16.823187\t2.02\t-2.19 D06\tSession04\tIAEA-C2\t-3.846071\t4.861980\t0.534465 D07\tSession04\tETH-2\t-6.072653\t-4.917987\t-11.786215\t-10.17\t-18.69 D08\tSession04\tETH-3\t5.516592\t11.923729\t17.275641\t1.71\t-1.78 D09\tSession04\tETH-1\t5.789889\t11.531354\t16.804221\t2.02\t-2.19 D10\tSession04\tIAEA-C2\t-3.845074\t4.865635\t0.546284 D11\tSession04\tETH-1\t5.795006\t11.507829\t16.772751\t2.02\t-2.19 D12\tSession04\tETH-1\t5.791371\t11.540606\t16.822704\t2.02\t-2.19 D13\tSession04\tETH-2\t-6.074029\t-4.937379\t-11.786614\t-10.17\t-18.69 D14\tSession04\tETH-4\t-6.216977\t-5.273352\t-12.057294 D15\tSession04\tIAEA-C1\t6.214304\t11.412869\t17.227005 D16\tSession04\tETH-2\t-6.071021\t-4.966406\t-11.812116\t-10.17\t-18.69 D17\tSession04\tETH-3\t5.543181\t12.065648\t17.455042\t1.71\t-1.78 D18\tSession04\tETH-1\t5.805793\t11.632212\t16.937561\t2.02\t-2.19 D19\tSession04\tIAEA-C1\t6.230425\t11.518038\t17.342943 D20\tSession04\tETH-2\t-6.049292\t-4.811109\t-11.639895\t-10.17\t-18.69 D21\tSession04\tIAEA-C2\t-3.829436\t4.967992\t0.665451 D22\tSession04\tETH-3\t5.538827\t12.064780\t17.438156\t1.71\t-1.78 D23\tSession04\tMERCK\t-35.935604\t-2.092229\t-39.632228 D24\tSession04\tETH-4\t-6.215430\t-5.166894\t-11.939419 D25\tSession04\tETH-2\t-6.068214\t-4.868420\t-11.716099\t-10.17\t-18.69 D26\tSession04\tMERCK\t-35.918898\t-2.041585\t-39.566777 D27\tSession04\tETH-1\t5.786924\t11.584138\t16.861248\t2.02\t-2.19 D28\tSession04\tETH-2\t-6.062115\t-4.820423\t-11.664703\t-10.17\t-18.69 D29\tSession04\tETH-4\t-6.210819\t-5.160997\t-11.943417 D30\tSession04\tIAEA-C2\t-3.842542\t4.937635\t0.603831 D31\tSession04\tETH-3\t5.527648\t11.985083\t17.353603\t1.71\t-1.78 D32\tSession04\tIAEA-C1\t6.221429\t11.481788\t17.284825 D33\tSession04\tMERCK\t-35.922066\t-2.113682\t-39.642962 D34\tSession04\tETH-3\t5.521955\t11.989323\t17.345179\t1.71\t-1.78 D35\tSession04\tIAEA-C2\t-3.838229\t4.937180\t0.617586 D36\tSession04\tETH-4\t-6.215638\t-5.221584\t-11.999819 D37\tSession04\tETH-2\t-6.067508\t-4.893477\t-11.754488\t-10.17\t-18.69 D38\tSession04\tIAEA-C1\t6.214580\t11.440629\t17.254051''' app = Flask(__name__) Markdown(app, extensions = [ 'markdown.extensions.tables', # 'pymdownx.magiclink', # 'pymdownx.betterem', 'pymdownx.highlight', 'pymdownx.tilde', 'pymdownx.caret', # 'pymdownx.emoji', # 'pymdownx.tasklist', 'pymdownx.superfences' ]) default_payload = { 'display_results': False, 'error_msg': '', 'rawdata_input_str': rawdata_input_str, 'o17_R13_VPDB': 0.01118, 'o17_R18_VSMOW': 0.0020052, 'o17_R17_VSMOW': 0.00038475, 'o17_lambda': 0.528, 'd13C_stdz_setting': 'd13C_stdz_setting_2pt', 'd18O_stdz_setting': 'd18O_stdz_setting_2pt', 'wg_setting': 'wg_setting_fromsamples', # 'wg_setting_fromsample_samplename': 'ETH-3', # 'wg_setting_fromsample_d13C': 1.71, # 'wg_setting_fromsample_d18O': -1.78, 'acidfrac_setting': 1.008129, 'rf_input_str': '0.258\tETH-1\n0.256\tETH-2\n0.691\tETH-3', 'stdz_method_setting': 'stdz_method_setting_pooled', } def start(): payload = default_payload.copy() # payload['token'] = datetime.now().strftime('%y%m%d') + ''.join(choices(ascii_lowercase, k=5)) return render_template('main.html', payload = payload, vD47crunch = vD47crunch) def proceed(): payload = dict(request.form) data = D47data() if payload['d13C_stdz_setting'] == 'd13C_stdz_setting_2pt': data.d13C_STANDARDIZATION_METHOD = '2pt' elif payload['d13C_stdz_setting'] == 'd13C_stdz_setting_1pt': data.d13C_STANDARDIZATION_METHOD = '1pt' elif payload['d13C_stdz_setting'] == 'd13C_stdz_setting_none': data.d13C_STANDARDIZATION_METHOD = 'none' if payload['d18O_stdz_setting'] == 'd18O_stdz_setting_2pt': data.d18O_STANDARDIZATION_METHOD = '2pt' elif payload['d18O_stdz_setting'] == 'd18O_stdz_setting_1pt': data.d18O_STANDARDIZATION_METHOD = '1pt' elif payload['d18O_stdz_setting'] == 'd18O_stdz_setting_none': data.d18O_STANDARDIZATION_METHOD = 'none' anchors = [l.split('\t') for l in payload['rf_input_str'].splitlines() if '\t' in l] data.Nominal_D47 = {l[1]: float(l[0]) for l in anchors} try: data.R13_VPDB = float(payload['o17_R13_VPDB']) except: payload['error_msg'] = 'Check the value of R13_VPDB in oxygen-17 correction settings.' return render_template('main.html', payload = payload, vD47crunch = vD47crunch) try: data.R18_VSMOW = float(payload['o17_R18_VSMOW']) except: payload['error_msg'] = 'Check the value of R18_VSMOW in oxygen-17 correction settings.' return render_template('main.html', payload = payload, vD47crunch = vD47crunch) try: data.R17_VSMOW = float(payload['o17_R17_VSMOW']) except: payload['error_msg'] = 'Check the value of R17_VSMOW in oxygen-17 correction settings.' return render_template('main.html', payload = payload, vD47crunch = vD47crunch) try: data.lambda_17 = float(payload['o17_lambda']) except: payload['error_msg'] = 'Check the value of in oxygen-17 correction settings.' return render_template('main.html', payload = payload, vD47crunch = vD47crunch) data.input(payload['rawdata_input_str']) # try: # data.input(payload['rawdata_input_str'], '\t') # except: # payload['error_msg'] = 'Raw data input failed for some reason.' # return render_template('main.html', payload = payload, vD47crunch = vD47crunch) for r in data: for k in ['UID', 'Sample', 'Session', 'd45', 'd46', 'd47']: if k not in r or r[k] == '': payload['error_msg'] = f'Analysis "{r["UID"]}" is missing field "{k}".' return render_template('main.html', payload = payload, vD47crunch = vD47crunch) for k in ['d45', 'd46', 'd47']: if not isinstance(r[k], (int, float)): payload['error_msg'] = f'Analysis "{r["UID"]}" should have a valid number for field "{k}".' return render_template('main.html', payload = payload, vD47crunch = vD47crunch) if payload['wg_setting'] == 'wg_setting_fromsamples': # if payload['wg_setting_fromsample_samplename'] == '': # payload['error_msg'] = 'Empty sample name in WG settings.' # return render_template('main.html', payload = payload, vD47crunch = vD47crunch) # # wg_setting_fromsample_samplename = payload['wg_setting_fromsample_samplename'] # # for s in data.sessions: # if wg_setting_fromsample_samplename not in [r['Sample'] for r in data.sessions[s]['data']]: # payload['error_msg'] = f'Sample name from WG settings ("{wg_setting_fromsample_samplename}") not found in session "{s}".' # return render_template('main.html', payload = payload, vD47crunch = vD47crunch) # # try: # wg_setting_fromsample_d13C = float(payload['wg_setting_fromsample_d13C']) # except: # payload['error_msg'] = 'Check the 13C value in WG settings.' # return render_template('main.html', payload = payload, vD47crunch = vD47crunch) # # try: # wg_setting_fromsample_d18O = float(payload['wg_setting_fromsample_d18O']) # except: # payload['error_msg'] = 'Check the 18O value in WG settings.' # return render_template('main.html', payload = payload, vD47crunch = vD47crunch) try: acidfrac = float(payload['acidfrac_setting']) except: payload['error_msg'] = 'Check the acid fractionation value.' return render_template('main.html', payload = payload, vD47crunch = vD47crunch) if acidfrac == 0: payload['error_msg'] = 'Acid fractionation value should be greater than zero.' return render_template('main.html', payload = payload, vD47crunch = vD47crunch) if payload['wg_setting'] == 'wg_setting_fromsamples': data.Nominal_d13C_VPDB = {} data.Nominal_d18O_VPDB = {} for r in data: if 'Nominal_d13C_VPDB' in r: if r['Sample'] in data.Nominal_d13C_VPDB: if data.Nominal_d13C_VPDB[r['Sample']] != r['Nominal_d13C_VPDB']: payload['error_msg'] = f"Inconsistent <span class='field'>Nominal_d13C_VPDB</span> value for {r['Sample']} (analysis: {r['UID']})." return render_template('main.html', payload = payload, vD47crunch = vD47crunch) else: data.Nominal_d13C_VPDB[r['Sample']] = r['Nominal_d13C_VPDB'] if 'Nominal_d18O_VPDB' in r: if r['Sample'] in data.Nominal_d18O_VPDB: if data.Nominal_d18O_VPDB[r['Sample']] != r['Nominal_d18O_VPDB']: payload['error_msg'] = f"Inconsistent <span class='field'>Nominal_d18O_VPDB</span> value for {r['Sample']} (analysis {r['UID']})." return render_template('main.html', payload = payload, vD47crunch = vD47crunch) else: data.Nominal_d18O_VPDB[r['Sample']] = r['Nominal_d18O_VPDB'] try: data.wg(a18_acid = acidfrac) except: payload['error_msg'] = 'WG computation failed for some reason.' return render_template('main.html', payload = payload, vD47crunch = vD47crunch) if payload['wg_setting'] == 'wg_setting_explicit': for r in data: for k in ['d13Cwg_VPDB', 'd18Owg_VSMOW']: if k not in r: payload['error_msg'] = f'Analysis "{r["UID"]}" is missing field "{k}".' return render_template('main.html', payload = payload, vD47crunch = vD47crunch) try: data.crunch() except: payload['error_msg'] = 'Crunching step failed for some reason.' return render_template('main.html', payload = payload, vD47crunch = vD47crunch) method = { 'stdz_method_setting_pooled': 'pooled', 'stdz_method_setting_indep_sessions': 'indep_sessions', }[payload['stdz_method_setting']] data.standardize( consolidate_tables = False, consolidate_plots = False, method = method) csv = 'Session,a,b,c,va,vb,vc,covab,covac,covbc,Xa,Ya,Xu,Yu' for session in data.sessions: s = data.sessions[session] Ga = [r for r in s['data'] if r['Sample'] in data.anchors] Gu = [r for r in s['data'] if r['Sample'] in data.unknowns] csv += f"\n{session},{s['a']},{s['b']},{s['c']},{s['CM'][0,0]},{s['CM'][1,1]},{s['CM'][2,2]},{s['CM'][0,1]},{s['CM'][0,2]},{s['CM'][1,2]},{';'.join([str(r['d47']) for r in Ga])},{';'.join([str(r['D47']) for r in Ga])},{';'.join([str(r['d47']) for r in Gu])},{';'.join([str(r['D47']) for r in Gu])}" # payload['error_msg'] = 'Foo bar.' # return str(payload).replace(', ','\n') payload['display_results'] = True payload['csv_of_sessions'] = csv summary = data.summary(save_to_file = False, print_out = False) tosessions = data.table_of_sessions(save_to_file = False, print_out = False) payload['summary'] = pretty_table(summary, header = 0) payload['summary_rows'] = len(payload['summary'].splitlines())+2 payload['summary_cols'] = len(payload['summary'].splitlines()[0]) payload['table_of_sessions'] = pretty_table(tosessions) payload['table_of_sessions_rows'] = len(payload['table_of_sessions'].splitlines())+1 payload['table_of_sessions_cols'] = len(payload['table_of_sessions'].splitlines()[0]) payload['table_of_sessions_csv'] = make_csv(tosessions) tosamples = data.table_of_samples(save_to_file = False, print_out = False) payload['table_of_samples'] = pretty_table(tosamples) payload['table_of_samples'] = payload['table_of_samples'][:] + 'NB: d18O_VSMOW is the composition of the analyzed CO2.' payload['table_of_samples_rows'] = len(payload['table_of_samples'].splitlines()) payload['table_of_samples_cols'] = len(payload['table_of_samples'].splitlines()[0])+1 payload['table_of_samples_csv'] = make_csv(tosamples) toanalyses = data.table_of_analyses(save_to_file = False, print_out = False) payload['table_of_analyses'] = pretty_table(toanalyses) payload['table_of_analyses_rows'] = len(payload['table_of_analyses'].splitlines())+1 payload['table_of_analyses_cols'] = len(payload['table_of_analyses'].splitlines()[0]) payload['table_of_analyses_csv'] = make_csv(toanalyses) covars = "\n\nCOVARIANCE BETWEEN SAMPLE 47 VALUES:\n\n" txt = [['Sample #1', 'Sample #2', 'Covariance', 'Correlation']] unknowns = [k for k in data.unknowns] for k, s1 in enumerate(unknowns): for s2 in unknowns[k+1:]: txt += [[ s1, s2, f"{data.sample_D47_covar(s1,s2):.4e}", f"{data.sample_D47_covar(s1,s2)/data.samples[s1]['SE_D47']/data.samples[s2]['SE_D47']:.6f}", ]] covars += pretty_table(txt, align = '<<>>') payload['report'] = f"Report generated on {time.asctime()}\nClumpyCrunch v{__version__} using D47crunch v{vD47crunch}" payload['report'] += "\n\nOXYGEN-17 CORRECTION PARAMETERS:\n" + pretty_table([['R13_VPDB', 'R18_VSMOW', 'R17_VSMOW', 'lambda_17'], [payload['o17_R13_VPDB'], payload['o17_R18_VSMOW'], payload['o17_R17_VSMOW'], payload['o17_lambda']]], align = '<<<<') if payload['wg_setting'] == 'wg_setting_fromsample': payload['report'] += f"\n\nWG compositions constrained by sample {wg_setting_fromsample_samplename} with:" payload['report'] += f"\n 13C_VPDB = {wg_setting_fromsample_d13C}" payload['report'] += f"\n 18O_VPDB = {wg_setting_fromsample_d18O}" payload['report'] += f"\n(18O/16O) AFF = {wg_setting_fromsample_acidfrac}\n" elif payload['wg_setting'] == 'wg_setting_explicit': payload['report'] += f"\n\nWG compositions specified by user.\n" payload['report'] += f"\n\nSUMMARY:\n{payload['summary']}" payload['report'] += f"\n\nSAMPLES:\n{payload['table_of_samples']}\n" payload['report'] += f"\n\nSESSIONS:\n{payload['table_of_sessions']}" payload['report'] += f"\n\nANALYSES:\n{payload['table_of_analyses']}" payload['report'] += covars txt = payload['csv_of_sessions'] txt = [[x.strip() for x in l.split(',')] for l in txt.splitlines() if l.strip()] sessions = [{k: smart_type(v) for k,v in zip(txt[0], l)} for l in txt[1:]] payload['plots'] = [] for s in sessions: s['Xa'] = [float(x) for x in s['Xa'].split(';')] s['Ya'] = [float(x) for x in s['Ya'].split(';')] s['Xu'] = [float(x) for x in s['Xu'].split(';')] s['Yu'] = [float(x) for x in s['Yu'].split(';')] for s in sessions: fig = figure(figsize = (3,3)) subplots_adjust(.2,.15,.95,.9) plot_session(s) pngImage = io.BytesIO() FigureCanvas(fig).print_png(pngImage) pngImageB64String = "data:image/png;base64," pngImageB64String += base64.b64encode(pngImage.getvalue()).decode('utf8') payload['plots'] += [pngImageB64String] close(fig) return(render_template('main.html', payload = payload, vD47crunch = vD47crunch)) # @app.route("/csv/<foo>/<filename>", methods = ['POST']) # def get_file(foo, filename): # payload = dict(request.form) # return Response( # payload[foo], # mimetype='text/plain', # headers={'Content-Disposition': f'attachment;filename="{filename}"'} # )
44.975923
300
0.715667
29333564f5a91482a951f19d8cd3aa5ce9a5bfe9
6,505
py
Python
rubric_sampling/experiments/train_rnn.py
YangAzure/rubric-sampling-public
24e8c6bc154633566f93a20661c67484029c3591
[ "MIT" ]
20
2019-01-29T03:21:40.000Z
2022-03-04T08:52:24.000Z
rubric_sampling/experiments/train_rnn.py
YangAzure/rubric-sampling-public
24e8c6bc154633566f93a20661c67484029c3591
[ "MIT" ]
null
null
null
rubric_sampling/experiments/train_rnn.py
YangAzure/rubric-sampling-public
24e8c6bc154633566f93a20661c67484029c3591
[ "MIT" ]
5
2019-08-31T11:49:23.000Z
2021-03-18T13:22:58.000Z
r"""Train a neural network to predict feedback for a program string.""" from __future__ import division from __future__ import print_function from __future__ import absolute_import import os import sys import random import numpy as np from tqdm import tqdm import torch import torch.optim as optim import torch.utils.data as data import torch.nn.functional as F from .models import ProgramRNN from .utils import AverageMeter, save_checkpoint, merge_args_with_dict from .datasets import load_dataset from .config import default_hyperparams from .rubric_utils.load_params import get_label_params, get_max_seq_len if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument('dataset', type=str, help='annotated|synthetic') parser.add_argument('problem_id', type=int, help='1|2|3|4|5|6|7|8') parser.add_argument('out_dir', type=str, help='where to save outputs') parser.add_argument('--cuda', action='store_true', default=False, help='enables CUDA training [default: False]') args = parser.parse_args() args.cuda = args.cuda and torch.cuda.is_available() merge_args_with_dict(args, default_hyperparams) device = torch.device('cuda' if args.cuda else 'cpu') args.max_seq_len = get_max_seq_len(args.problem_id) label_dim, _, _, _, _ = get_label_params(args.problem_id) # reproducibility torch.manual_seed(args.seed) np.random.seed(args.seed) if not os.path.isdir(args.out_dir): os.makedirs(args.out_dir) train_dataset = load_dataset( args.dataset, args.problem_id, 'train', vocab=None, max_seq_len=args.max_seq_len, min_occ=args.min_occ) val_dataset = load_dataset( args.dataset, args.problem_id, 'val', vocab=train_dataset.vocab, max_seq_len=args.max_seq_len, min_occ=args.min_occ) test_dataset = load_dataset(args.dataset, args.problem_id, 'test', vocab=train_dataset.vocab, max_seq_len=args.max_seq_len, min_occ=args.min_occ) train_loader = data.DataLoader(train_dataset, batch_size=args.batch_size, shuffle=True) val_loader = data.DataLoader(val_dataset, batch_size=args.batch_size, shuffle=False) test_loader = data.DataLoader(test_dataset, batch_size=args.batch_size, shuffle=False) model = ProgramRNN( args.z_dim, label_dim, train_dataset.vocab_size, embedding_dim=args.embedding_dim, hidden_dim=args.hidden_dim, num_layers=args.num_layers) model = model.to(device) optimizer = optim.Adam(model.parameters(), lr=args.lr) best_loss = sys.maxint track_train_loss = np.zeros(args.epochs) track_val_loss = np.zeros(args.epochs) track_test_loss = np.zeros(args.epochs) track_train_acc = np.zeros(args.epochs) track_val_acc = np.zeros(args.epochs) track_test_acc = np.zeros(args.epochs) for epoch in xrange(1, args.epochs + 1): train_loss, train_acc = train(epoch) val_loss, val_acc = test(epoch, val_loader, name='Val') test_loss, test_acc = test(epoch, test_loader, name='Test') track_train_loss[epoch - 1] = train_loss track_val_loss[epoch - 1] = val_loss track_test_loss[epoch - 1] = test_loss track_train_acc[epoch - 1] = train_acc track_val_acc[epoch - 1] = val_acc track_test_acc[epoch - 1] = test_acc is_best = val_loss < best_loss best_loss = min(val_loss, best_loss) save_checkpoint({ 'state_dict': model.state_dict(), 'cmd_line_args': args, 'vocab': train_dataset.vocab, }, is_best, folder=args.out_dir) np.save(os.path.join(args.out_dir, 'train_loss.npy'), track_train_loss) np.save(os.path.join(args.out_dir, 'val_loss.npy'), track_val_loss) np.save(os.path.join(args.out_dir, 'test_loss.npy'), track_test_loss) np.save(os.path.join(args.out_dir, 'train_acc.npy'), track_train_acc) np.save(os.path.join(args.out_dir, 'val_acc.npy'), track_val_acc) np.save(os.path.join(args.out_dir, 'test_acc.npy'), track_test_acc)
39.907975
107
0.632283
2933954edd28122f5eaf709201de52733e9a677c
1,232
py
Python
python/code.py
Warabhi/ga-learner-dsmp-repo
610a7e6cc161a1fec26911f4e054f2a325b5f5fc
[ "MIT" ]
null
null
null
python/code.py
Warabhi/ga-learner-dsmp-repo
610a7e6cc161a1fec26911f4e054f2a325b5f5fc
[ "MIT" ]
null
null
null
python/code.py
Warabhi/ga-learner-dsmp-repo
610a7e6cc161a1fec26911f4e054f2a325b5f5fc
[ "MIT" ]
null
null
null
# -------------- # Code starts here class_1 = ['Geoffrey Hinton' , 'Andrew Ng' , 'Sebastian Raschka' , 'Yoshua Bengio'] class_2 = ['Hilary Mason' , 'Carla Gentry' , 'Corinna Cortes'] new_class = class_1 + class_2 print(new_class) new_class.append('Peter Warden') print(new_class) del new_class[5] print(new_class) # Code ends here # -------------- # Code starts here courses = {'Math': 65 , 'English': 70 , 'History': 80 , 'French': 70 , 'Science': 60} total = sum(courses.values()) print(total) percentage = total/500*100 print(percentage) # Code ends here # -------------- # Code starts here mathematics = { 'Geoffrey Hinton' : 78, 'Andrew Ng' : 95, 'Sebastian Raschka' : 65 , 'Yoshua Benjio' : 50 , 'Hilary Mason' : 70 , 'Corinna Cortes' : 66 , 'Peter Warden' : 75} max_marks_scored = max(mathematics, key=mathematics.get) print(max_marks_scored) topper = max_marks_scored print(topper) # Code ends here # -------------- # Given string topper = ' andrew ng' # Code starts here first_name = topper.split()[0] print(first_name) last_name = topper.split()[1] print(last_name) full_name = last_name +' '+ first_name print(full_name) certificate_name = full_name.upper() print(certificate_name) # Code ends here
23.245283
90
0.668019
2934aab8985e093039352c584291d05e82d940ca
1,629
py
Python
checklog.py
mtibbett67/pymodules
9a7dcd16fb2107029edaabde766c1dbdb769713c
[ "MIT" ]
null
null
null
checklog.py
mtibbett67/pymodules
9a7dcd16fb2107029edaabde766c1dbdb769713c
[ "MIT" ]
null
null
null
checklog.py
mtibbett67/pymodules
9a7dcd16fb2107029edaabde766c1dbdb769713c
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' NAME: checklog.py DESCRIPTION: This script checks the tail of the log file and lists the disk space CREATED: Sun Mar 15 22:53:54 2015 VERSION: 1.0 AUTHOR: Mark Tibbett AUTHOR_EMAIL: mtibbett67@gmail.com URL: N/A DOWNLOAD_URL: N/A INSTALL_REQUIRES: [] PACKAGES: [] SCRIPTS: [] ''' # Standard library imports import os import sys import subprocess # Related third party imports # Local application/library specific imports # Console colors W = '\033[0m' # white (normal) R = '\033[31m' # red G = '\033[32m' # green O = '\033[33m' # orange B = '\033[34m' # blue P = '\033[35m' # purple C = '\033[36m' # cyan GR = '\033[37m' # gray # Section formats SEPARATOR = B + '=' * 80 + W NL = '\n' # Clear the terminal os.system('clear') # Check for root or sudo. Remove if not needed. UID = os.getuid() if UID != 0: print R + ' [!]' + O + ' ERROR:' + G + ' sysupdate' + O + \ ' must be run as ' + R + 'root' + W # print R + ' [!]' + O + ' login as root (' + W + 'su root' + O + ') \ # or try ' + W + 'sudo ./wifite.py' + W os.execvp('sudo', ['sudo'] + sys.argv) else: print NL print G + 'You are running this script as ' + R + 'root' + W print NL + SEPARATOR + NL LOG = ['tail', '/var/log/messages'] DISK = ['df', '-h'] def check(arg1, arg2): '''Call subprocess to check logs''' print G + arg1 + W + NL item = subprocess.check_output(arg2) #subprocess.call(arg2) print item + NL + SEPARATOR + NL check('Runing tail on messages', LOG) check('Disk usage', DISK)
16.793814
73
0.581952
29351a72a75c3ab6afce56723dbd2096b63f981a
726
py
Python
algorithms/implementation/minimum_distances.py
avenet/hackerrank
e522030a023af4ff50d5fc64bd3eba30144e006c
[ "MIT" ]
null
null
null
algorithms/implementation/minimum_distances.py
avenet/hackerrank
e522030a023af4ff50d5fc64bd3eba30144e006c
[ "MIT" ]
null
null
null
algorithms/implementation/minimum_distances.py
avenet/hackerrank
e522030a023af4ff50d5fc64bd3eba30144e006c
[ "MIT" ]
null
null
null
n = int(input().strip()) items = [ int(A_temp) for A_temp in input().strip().split(' ') ] items_map = {} result = None for i, item in enumerate(items): if item not in items_map: items_map[item] = [i] else: items_map[item].append(i) for _, item_indexes in items_map.items(): items_indexes_length = len(item_indexes) if items_indexes_length > 1: for i in range(items_indexes_length): for j in range(i + 1, items_indexes_length): diff = item_indexes[j] - item_indexes[i] if result is None: result = diff elif diff < result: result = diff print(result if result else -1)
22.6875
56
0.566116
29378cd6da10a2986ee1d848cbb7564bb46bcde6
15,518
py
Python
spore/spore.py
pavankkota/SPoRe
3062368a84130ec64bdbd7ca66de7f2b7287330e
[ "MIT" ]
1
2021-06-23T15:51:57.000Z
2021-06-23T15:51:57.000Z
spore/spore.py
pavankkota/SPoRe
3062368a84130ec64bdbd7ca66de7f2b7287330e
[ "MIT" ]
null
null
null
spore/spore.py
pavankkota/SPoRe
3062368a84130ec64bdbd7ca66de7f2b7287330e
[ "MIT" ]
null
null
null
""" Sparse Poisson Recovery (SPoRe) module for solving Multiple Measurement Vector problem with Poisson signals (MMVP) by batch stochastic gradient ascent and Monte Carlo integration Authors: Pavan Kota, Daniel LeJeune Reference: [1] P. K. Kota, D. LeJeune, R. A. Drezek, and R. G. Baraniuk, "Extreme Compressed Sensing of Poisson Rates from Multiple Measurements," Mar. 2021. arXiv ID: """ from abc import ABC, abstractmethod import numpy as np import time import pdb from .mmv_models import FwdModelGroup, SPoReFwdModelGroup
41.491979
169
0.543756
2938d769b525d23fcc668a6eb476387c4aae2966
734
py
Python
306/translate_cds.py
jsh/pybites
73c79ed962c15247cead173b17f69f248ea51b96
[ "MIT" ]
null
null
null
306/translate_cds.py
jsh/pybites
73c79ed962c15247cead173b17f69f248ea51b96
[ "MIT" ]
null
null
null
306/translate_cds.py
jsh/pybites
73c79ed962c15247cead173b17f69f248ea51b96
[ "MIT" ]
null
null
null
"""Use translation table to translate coding sequence to protein.""" from Bio.Data import CodonTable # type: ignore from Bio.Seq import Seq # type: ignore def translate_cds(cds: str, translation_table: str) -> str: """Translate coding sequence to protein. :param cds: str: DNA coding sequence (CDS) :param translation_table: str: translation table as defined in Bio.Seq.Seq.CodonTable.ambiguous_generic_by_name :return: str: Protein sequence """ table = CodonTable.ambiguous_dna_by_name[translation_table] cds = "".join(cds.split()) # clean out whitespace coding_dna = Seq(cds) protein = coding_dna.translate(table, cds=True, to_stop=True) return str(protein)
36.7
71
0.700272
29392d7c293c0b529284bdff29493ae4994d22ba
206
py
Python
example.py
n0emis/pycodimd
cec7135babe63f0c40fdb9eac7ede50e145cd512
[ "MIT" ]
1
2020-04-20T22:06:49.000Z
2020-04-20T22:06:49.000Z
example.py
n0emis/pycodimd
cec7135babe63f0c40fdb9eac7ede50e145cd512
[ "MIT" ]
null
null
null
example.py
n0emis/pycodimd
cec7135babe63f0c40fdb9eac7ede50e145cd512
[ "MIT" ]
null
null
null
from pycodimd import CodiMD cmd = CodiMD('https://md.noemis.me') #cmd.login('user@example.com','CorrectHorseBatteryStaple') cmd.load_cookies() print(cmd.history()[-1]['text']) # Print Name of latest Note
29.428571
61
0.73301
293ac2ae42d575f893f18bae2751d93e4e138ae8
75
py
Python
PP4E-Examples-1.4/Examples/PP4E/System/Environment/echoenv.py
AngelLiang/PP4E
3a7f63b366e1e4700b4d2524884696999a87ba9d
[ "MIT" ]
null
null
null
PP4E-Examples-1.4/Examples/PP4E/System/Environment/echoenv.py
AngelLiang/PP4E
3a7f63b366e1e4700b4d2524884696999a87ba9d
[ "MIT" ]
null
null
null
PP4E-Examples-1.4/Examples/PP4E/System/Environment/echoenv.py
AngelLiang/PP4E
3a7f63b366e1e4700b4d2524884696999a87ba9d
[ "MIT" ]
null
null
null
import os print('echoenv...', end=' ') print('Hello,', os.environ['USER'])
18.75
35
0.613333
293afc12acd3adc92103d2c686f2476332649203
4,137
py
Python
plix/displays.py
freelan-developers/plix
69114b3e522330af802800e09a432c1a84220f88
[ "MIT" ]
1
2017-05-22T11:52:01.000Z
2017-05-22T11:52:01.000Z
plix/displays.py
freelan-developers/plix
69114b3e522330af802800e09a432c1a84220f88
[ "MIT" ]
4
2015-03-12T16:59:36.000Z
2015-03-12T17:34:15.000Z
plix/displays.py
freelan-developers/plix
69114b3e522330af802800e09a432c1a84220f88
[ "MIT" ]
1
2018-03-04T21:43:33.000Z
2018-03-04T21:43:33.000Z
""" Display command results. """ from __future__ import unicode_literals from contextlib import contextmanager from argparse import Namespace from io import BytesIO from colorama import AnsiToWin32 from chromalog.stream import stream_has_color_support from chromalog.colorizer import Colorizer from chromalog.mark.helpers.simple import ( warning, important, success, error, )
27.397351
79
0.583273
293dd5d900ef2c6130d4549dd1b873aa939a8cba
6,167
py
Python
plugins/Autocomplete/plugin.py
mogad0n/Limnoria
f31e5c4b9a77e30918d6b93f69d69f3b8f910e3c
[ "BSD-3-Clause" ]
476
2015-01-04T17:42:59.000Z
2021-08-13T07:40:54.000Z
plugins/Autocomplete/plugin.py
mogad0n/Limnoria
f31e5c4b9a77e30918d6b93f69d69f3b8f910e3c
[ "BSD-3-Clause" ]
491
2015-01-01T04:12:23.000Z
2021-08-12T19:24:47.000Z
plugins/Autocomplete/plugin.py
mogad0n/Limnoria
f31e5c4b9a77e30918d6b93f69d69f3b8f910e3c
[ "BSD-3-Clause" ]
203
2015-01-02T18:29:43.000Z
2021-08-15T12:52:22.000Z
### # Copyright (c) 2020-2021, The Limnoria Contributors # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions, and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions, and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the author of this software nor the name of # contributors to this software may be used to endorse or promote products # derived from this software without specific prior written consent. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. ### from supybot import conf, ircutils, ircmsgs, callbacks from supybot.i18n import PluginInternationalization _ = PluginInternationalization("Autocomplete") REQUEST_TAG = "+draft/autocomplete-request" RESPONSE_TAG = "+draft/autocomplete-response" def _commonPrefix(L): """Takes a list of lists, and returns their longest common prefix.""" assert L if len(L) == 1: return L[0] for n in range(1, max(map(len, L)) + 1): prefix = L[0][:n] for item in L[1:]: if prefix != item[:n]: return prefix[0:-1] assert False def _getAutocompleteResponse(irc, msg, payload): """Returns the value of the +draft/autocomplete-response tag for the given +draft/autocomplete-request payload.""" tokens = callbacks.tokenize( payload, channel=msg.channel, network=irc.network ) normalized_payload = " ".join(tokens) candidate_commands = _getCandidates(irc, normalized_payload) if len(candidate_commands) == 0: # No result return None elif len(candidate_commands) == 1: # One result, return it directly commands = candidate_commands else: # Multiple results, return only the longest common prefix + one word tokenized_candidates = [ callbacks.tokenize(c, channel=msg.channel, network=irc.network) for c in candidate_commands ] common_prefix = _commonPrefix(tokenized_candidates) words_after_prefix = { candidate[len(common_prefix)] for candidate in tokenized_candidates } commands = [ " ".join(common_prefix + [word]) for word in words_after_prefix ] # strip what the user already typed assert all(command.startswith(normalized_payload) for command in commands) normalized_payload_length = len(normalized_payload) response_items = [ command[normalized_payload_length:] for command in commands ] return "\t".join(sorted(response_items)) def _getCandidates(irc, normalized_payload): """Returns a list of commands starting with the normalized_payload.""" candidates = set() for cb in irc.callbacks: cb_commands = cb.listCommands() # copy them with the plugin name (optional when calling a command) # at the beginning plugin_name = cb.canonicalName() cb_commands += [plugin_name + " " + command for command in cb_commands] candidates |= { command for command in cb_commands if command.startswith(normalized_payload) } return candidates Class = Autocomplete # vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:
34.071823
79
0.66564
293e981880ad85e96c9f610aaeaa19c42550d236
2,237
py
Python
utils/preprocess_twitter.py
arnavk/tumblr-emotions
0ed03201ab833b8b400cb0cff6c5b064fac5edfb
[ "Apache-2.0" ]
null
null
null
utils/preprocess_twitter.py
arnavk/tumblr-emotions
0ed03201ab833b8b400cb0cff6c5b064fac5edfb
[ "Apache-2.0" ]
null
null
null
utils/preprocess_twitter.py
arnavk/tumblr-emotions
0ed03201ab833b8b400cb0cff6c5b064fac5edfb
[ "Apache-2.0" ]
null
null
null
""" preprocess-twitter.py python preprocess-twitter.py "Some random text with #hashtags, @mentions and http://t.co/kdjfkdjf (links). :)" Script for preprocessing tweets by Romain Paulus with small modifications by Jeffrey Pennington with translation to Python by Motoki Wu Translation of Ruby script to create features for GloVe vectors for Twitter data. http://nlp.stanford.edu/projects/glove/preprocess-twitter.rb """ import sys import regex as re FLAGS = re.MULTILINE | re.DOTALL if __name__ == '__main__': _, text = sys.argv if text == "test": text = "I TEST alllll kinds of #hashtags and #HASHTAGS, @mentions and 3000 (http://t.co/dkfjkdf). w/ <3 :) haha!!!!!" tokens = tokenize(text) print(tokens)
34.415385
125
0.591417
2940e9042fa0fc027376618fe6d76d1057e9e9bd
37,124
py
Python
pyPLANES/pw/pw_classes.py
matael/pyPLANES
7f591090446303884c9a3d049e42233efae0b7f4
[ "MIT" ]
null
null
null
pyPLANES/pw/pw_classes.py
matael/pyPLANES
7f591090446303884c9a3d049e42233efae0b7f4
[ "MIT" ]
null
null
null
pyPLANES/pw/pw_classes.py
matael/pyPLANES
7f591090446303884c9a3d049e42233efae0b7f4
[ "MIT" ]
1
2020-12-15T16:24:08.000Z
2020-12-15T16:24:08.000Z
#! /usr/bin/env python # -*- coding:utf8 -*- # # pw_classes.py # # This file is part of pyplanes, a software distributed under the MIT license. # For any question, please contact one of the authors cited below. # # Copyright (c) 2020 # Olivier Dazel <olivier.dazel@univ-lemans.fr> # Mathieu Gaborit <gaborit@kth.se> # Peter Gransson <pege@kth.se> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # import numpy as np import numpy.linalg as LA import matplotlib.pyplot as plt from mediapack import from_yaml from mediapack import Air, PEM, EqFluidJCA from pyPLANES.utils.io import initialisation_out_files_plain from pyPLANES.core.calculus import PwCalculus from pyPLANES.core.multilayer import MultiLayer from pyPLANES.pw.pw_layers import FluidLayer from pyPLANES.pw.pw_interfaces import FluidFluidInterface, RigidBacking Air = Air() # def initialise_PW_solver(L, b): # nb_PW = 0 # dofs = [] # for _layer in L: # if _layer.medium.MODEL == "fluid": # dofs.append(nb_PW+np.arange(2)) # nb_PW += 2 # elif _layer.medium.MODEL == "pem": # dofs.append(nb_PW+np.arange(6)) # nb_PW += 6 # elif _layer.medium.MODEL == "elastic": # dofs.append(nb_PW+np.arange(4)) # nb_PW += 4 # interface = [] # for i_l, _layer in enumerate(L[:-1]): # interface.append((L[i_l].medium.MODEL, L[i_l+1].medium.MODEL)) # return nb_PW, interface, dofs # class Solver_PW(PwCalculus): # def __init__(self, **kwargs): # PwCalculus.__init__(self, **kwargs) # ml = kwargs.get("ml") # termination = kwargs.get("termination") # self.layers = [] # for _l in ml: # if _l[0] == "Air": # mat = Air # else: # mat = from_yaml(_l[0]+".yaml") # d = _l[1] # self.layers.append(Layer(mat,d)) # if termination in ["trans", "transmission","Transmission"]: # self.backing = "Transmission" # else: # self.backing = backing.rigid # self.kx, self.ky, self.k = None, None, None # self.shift_plot = kwargs.get("shift_pw", 0.) # self.plot = kwargs.get("plot_results", [False]*6) # self.result = {} # self.outfiles_directory = False # initialisation_out_files_plain(self) # def write_out_files(self, out): # self.out_file.write("{:.12e}\t".format(self.current_frequency)) # abs = 1-np.abs(out["R"])**2 # self.out_file.write("{:.12e}\t".format(abs)) # self.out_file.write("\n") # def interface_fluid_fluid(self, ieq, iinter, L, d, M): # SV_1, k_y_1 = fluid_SV(self.kx, self.k, L[iinter].medium.K) # SV_2, k_y_2 = fluid_SV(self.kx, self.k, L[iinter+1].medium.K) # M[ieq, d[iinter+0][0]] = SV_1[0, 0]*np.exp(-1j*k_y_1*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = SV_1[0, 1] # M[ieq, d[iinter+1][0]] = -SV_2[0, 0] # M[ieq, d[iinter+1][1]] = -SV_2[0, 1]*np.exp(-1j*k_y_2*L[iinter+1].thickness) # ieq += 1 # M[ieq, d[iinter+0][0]] = SV_1[1, 0]*np.exp(-1j*k_y_1*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = SV_1[1, 1] # M[ieq, d[iinter+1][0]] = -SV_2[1, 0] # M[ieq, d[iinter+1][1]] = -SV_2[1, 1]*np.exp(-1j*k_y_2*L[iinter+1].thickness) # ieq += 1 # return ieq # def interface_fluid_rigid(self, M, ieq, L, d): # SV, k_y = fluid_SV(self.kx, self.k, L.medium.K) # M[ieq, d[0]] = SV[0, 0]*np.exp(-1j*k_y*L.thickness) # M[ieq, d[1]] = SV[0, 1] # ieq += 1 # return ieq # def semi_infinite_medium(self, M, ieq, L, d): # M[ieq, d[1]] = 1. # ieq += 1 # return ieq # def interface_pem_pem(self, ieq, iinter, L, d, M): # SV_1, k_y_1 = PEM_SV(L[iinter].medium, self.kx) # SV_2, k_y_2 = PEM_SV(L[iinter+1].medium, self.kx) # for _i in range(6): # M[ieq, d[iinter+0][0]] = SV_1[_i, 0]*np.exp(-1j*k_y_1[0]*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = SV_1[_i, 1]*np.exp(-1j*k_y_1[1]*L[iinter].thickness) # M[ieq, d[iinter+0][2]] = SV_1[_i, 2]*np.exp(-1j*k_y_1[2]*L[iinter].thickness) # M[ieq, d[iinter+0][3]] = SV_1[_i, 3] # M[ieq, d[iinter+0][4]] = SV_1[_i, 4] # M[ieq, d[iinter+0][5]] = SV_1[_i, 5] # M[ieq, d[iinter+1][0]] = -SV_2[_i, 0] # M[ieq, d[iinter+1][1]] = -SV_2[_i, 1] # M[ieq, d[iinter+1][2]] = -SV_2[_i, 2] # M[ieq, d[iinter+1][3]] = -SV_2[_i, 3]*np.exp(-1j*k_y_2[0]*L[iinter+1].thickness) # M[ieq, d[iinter+1][4]] = -SV_2[_i, 4]*np.exp(-1j*k_y_2[1]*L[iinter+1].thickness) # M[ieq, d[iinter+1][5]] = -SV_2[_i, 5]*np.exp(-1j*k_y_2[2]*L[iinter+1].thickness) # ieq += 1 # return ieq # def interface_fluid_pem(self, ieq, iinter, L, d, M): # SV_1, k_y_1 = fluid_SV(self.kx, self.k, L[iinter].medium.K) # SV_2, k_y_2 = PEM_SV(L[iinter+1].medium,self.kx) # # print(k_y_2) # M[ieq, d[iinter+0][0]] = SV_1[0, 0]*np.exp(-1j*k_y_1*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = SV_1[0, 1] # M[ieq, d[iinter+1][0]] = -SV_2[2, 0] # M[ieq, d[iinter+1][1]] = -SV_2[2, 1] # M[ieq, d[iinter+1][2]] = -SV_2[2, 2] # M[ieq, d[iinter+1][3]] = -SV_2[2, 3]*np.exp(-1j*k_y_2[0]*L[iinter+1].thickness) # M[ieq, d[iinter+1][4]] = -SV_2[2, 4]*np.exp(-1j*k_y_2[1]*L[iinter+1].thickness) # M[ieq, d[iinter+1][5]] = -SV_2[2, 5]*np.exp(-1j*k_y_2[2]*L[iinter+1].thickness) # ieq += 1 # M[ieq, d[iinter+0][0]] = SV_1[1, 0]*np.exp(-1j*k_y_1*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = SV_1[1, 1] # M[ieq, d[iinter+1][0]] = -SV_2[4, 0] # M[ieq, d[iinter+1][1]] = -SV_2[4, 1] # M[ieq, d[iinter+1][2]] = -SV_2[4, 2] # M[ieq, d[iinter+1][3]] = -SV_2[4, 3]*np.exp(-1j*k_y_2[0]*L[iinter+1].thickness) # M[ieq, d[iinter+1][4]] = -SV_2[4, 4]*np.exp(-1j*k_y_2[1]*L[iinter+1].thickness) # M[ieq, d[iinter+1][5]] = -SV_2[4, 5]*np.exp(-1j*k_y_2[2]*L[iinter+1].thickness) # ieq += 1 # M[ieq, d[iinter+1][0]] = SV_2[0, 0] # M[ieq, d[iinter+1][1]] = SV_2[0, 1] # M[ieq, d[iinter+1][2]] = SV_2[0, 2] # M[ieq, d[iinter+1][3]] = SV_2[0, 3]*np.exp(-1j*k_y_2[0]*L[iinter+1].thickness) # M[ieq, d[iinter+1][4]] = SV_2[0, 4]*np.exp(-1j*k_y_2[1]*L[iinter+1].thickness) # M[ieq, d[iinter+1][5]] = SV_2[0, 5]*np.exp(-1j*k_y_2[2]*L[iinter+1].thickness) # ieq += 1 # M[ieq, d[iinter+1][0]] = SV_2[3, 0] # M[ieq, d[iinter+1][1]] = SV_2[3, 1] # M[ieq, d[iinter+1][2]] = SV_2[3, 2] # M[ieq, d[iinter+1][3]] = SV_2[3, 3]*np.exp(-1j*k_y_2[0]*L[iinter+1].thickness) # M[ieq, d[iinter+1][4]] = SV_2[3, 4]*np.exp(-1j*k_y_2[1]*L[iinter+1].thickness) # M[ieq, d[iinter+1][5]] = SV_2[3, 5]*np.exp(-1j*k_y_2[2]*L[iinter+1].thickness) # ieq += 1 # return ieq # def interface_elastic_pem(self, ieq, iinter, L, d, M): # SV_1, k_y_1 = elastic_SV(L[iinter].medium,self.kx, self.omega) # SV_2, k_y_2 = PEM_SV(L[iinter+1].medium,self.kx) # # print(k_y_2) # M[ieq, d[iinter+0][0]] = -SV_1[0, 0]*np.exp(-1j*k_y_1[0]*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = -SV_1[0, 1]*np.exp(-1j*k_y_1[1]*L[iinter].thickness) # M[ieq, d[iinter+0][2]] = -SV_1[0, 2] # M[ieq, d[iinter+0][3]] = -SV_1[0, 3] # M[ieq, d[iinter+1][0]] = SV_2[0, 0] # M[ieq, d[iinter+1][1]] = SV_2[0, 1] # M[ieq, d[iinter+1][2]] = SV_2[0, 2] # M[ieq, d[iinter+1][3]] = SV_2[0, 3]*np.exp(-1j*k_y_2[0]*L[iinter+1].thickness) # M[ieq, d[iinter+1][4]] = SV_2[0, 4]*np.exp(-1j*k_y_2[1]*L[iinter+1].thickness) # M[ieq, d[iinter+1][5]] = SV_2[0, 5]*np.exp(-1j*k_y_2[2]*L[iinter+1].thickness) # ieq += 1 # M[ieq, d[iinter+0][0]] = -SV_1[1, 0]*np.exp(-1j*k_y_1[0]*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = -SV_1[1, 1]*np.exp(-1j*k_y_1[1]*L[iinter].thickness) # M[ieq, d[iinter+0][2]] = -SV_1[1, 2] # M[ieq, d[iinter+0][3]] = -SV_1[1, 3] # M[ieq, d[iinter+1][0]] = SV_2[1, 0] # M[ieq, d[iinter+1][1]] = SV_2[1, 1] # M[ieq, d[iinter+1][2]] = SV_2[1, 2] # M[ieq, d[iinter+1][3]] = SV_2[1, 3]*np.exp(-1j*k_y_2[0]*L[iinter+1].thickness) # M[ieq, d[iinter+1][4]] = SV_2[1, 4]*np.exp(-1j*k_y_2[1]*L[iinter+1].thickness) # M[ieq, d[iinter+1][5]] = SV_2[1, 5]*np.exp(-1j*k_y_2[2]*L[iinter+1].thickness) # ieq += 1 # M[ieq, d[iinter+0][0]] = -SV_1[1, 0]*np.exp(-1j*k_y_1[0]*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = -SV_1[1, 1]*np.exp(-1j*k_y_1[1]*L[iinter].thickness) # M[ieq, d[iinter+0][2]] = -SV_1[1, 2] # M[ieq, d[iinter+0][3]] = -SV_1[1, 3] # M[ieq, d[iinter+1][0]] = SV_2[2, 0] # M[ieq, d[iinter+1][1]] = SV_2[2, 1] # M[ieq, d[iinter+1][2]] = SV_2[2, 2] # M[ieq, d[iinter+1][3]] = SV_2[2, 3]*np.exp(-1j*k_y_2[0]*L[iinter+1].thickness) # M[ieq, d[iinter+1][4]] = SV_2[2, 4]*np.exp(-1j*k_y_2[1]*L[iinter+1].thickness) # M[ieq, d[iinter+1][5]] = SV_2[2, 5]*np.exp(-1j*k_y_2[2]*L[iinter+1].thickness) # ieq += 1 # M[ieq, d[iinter+0][0]] = -SV_1[2, 0]*np.exp(-1j*k_y_1[0]*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = -SV_1[2, 1]*np.exp(-1j*k_y_1[1]*L[iinter].thickness) # M[ieq, d[iinter+0][2]] = -SV_1[2, 2] # M[ieq, d[iinter+0][3]] = -SV_1[2, 3] # M[ieq, d[iinter+1][0]] = (SV_2[3, 0]-SV_2[4, 0]) # M[ieq, d[iinter+1][1]] = (SV_2[3, 1]-SV_2[4, 1]) # M[ieq, d[iinter+1][2]] = (SV_2[3, 2]-SV_2[4, 2]) # M[ieq, d[iinter+1][3]] = (SV_2[3, 3]-SV_2[4, 3])*np.exp(-1j*k_y_2[0]*L[iinter+1].thickness) # M[ieq, d[iinter+1][4]] = (SV_2[3, 4]-SV_2[4, 4])*np.exp(-1j*k_y_2[1]*L[iinter+1].thickness) # M[ieq, d[iinter+1][5]] = (SV_2[3, 5]-SV_2[4, 5])*np.exp(-1j*k_y_2[2]*L[iinter+1].thickness) # ieq += 1 # M[ieq, d[iinter+0][0]] = -SV_1[3, 0]*np.exp(-1j*k_y_1[0]*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = -SV_1[3, 1]*np.exp(-1j*k_y_1[1]*L[iinter].thickness) # M[ieq, d[iinter+0][2]] = -SV_1[3, 2] # M[ieq, d[iinter+0][3]] = -SV_1[3, 3] # M[ieq, d[iinter+1][0]] = SV_2[5, 0] # M[ieq, d[iinter+1][1]] = SV_2[5, 1] # M[ieq, d[iinter+1][2]] = SV_2[5, 2] # M[ieq, d[iinter+1][3]] = SV_2[5, 3]*np.exp(-1j*k_y_2[0]*L[iinter+1].thickness) # M[ieq, d[iinter+1][4]] = SV_2[5, 4]*np.exp(-1j*k_y_2[1]*L[iinter+1].thickness) # M[ieq, d[iinter+1][5]] = SV_2[5, 5]*np.exp(-1j*k_y_2[2]*L[iinter+1].thickness) # ieq += 1 # return ieq # def interface_pem_elastic(self, ieq, iinter, L, d, M): # SV_1, k_y_1 = PEM_SV(L[iinter].medium,self.kx) # SV_2, k_y_2 = elastic_SV(L[iinter+1].medium,self.kx, self.omega) # # print(k_y_2) # M[ieq, d[iinter+0][0]] = SV_1[0, 0]*np.exp(-1j*k_y_1[0]*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = SV_1[0, 1]*np.exp(-1j*k_y_1[1]*L[iinter].thickness) # M[ieq, d[iinter+0][2]] = SV_1[0, 2]*np.exp(-1j*k_y_1[2]*L[iinter].thickness) # M[ieq, d[iinter+0][3]] = SV_1[0, 3] # M[ieq, d[iinter+0][4]] = SV_1[0, 4] # M[ieq, d[iinter+0][5]] = SV_1[0, 5] # M[ieq, d[iinter+1][0]] = -SV_2[0, 0] # M[ieq, d[iinter+1][1]] = -SV_2[0, 1] # M[ieq, d[iinter+1][2]] = -SV_2[0, 2]*np.exp(-1j*k_y_2[0]*L[iinter+1].thickness) # M[ieq, d[iinter+1][3]] = -SV_2[0, 3]*np.exp(-1j*k_y_2[1]*L[iinter+1].thickness) # ieq += 1 # M[ieq, d[iinter+0][0]] = SV_1[1, 0]*np.exp(-1j*k_y_1[0]*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = SV_1[1, 1]*np.exp(-1j*k_y_1[1]*L[iinter].thickness) # M[ieq, d[iinter+0][2]] = SV_1[1, 2]*np.exp(-1j*k_y_1[2]*L[iinter].thickness) # M[ieq, d[iinter+0][3]] = SV_1[1, 3] # M[ieq, d[iinter+0][4]] = SV_1[1, 4] # M[ieq, d[iinter+0][5]] = SV_1[1, 5] # M[ieq, d[iinter+1][0]] = -SV_2[1, 0] # M[ieq, d[iinter+1][1]] = -SV_2[1, 1] # M[ieq, d[iinter+1][2]] = -SV_2[1, 2]*np.exp(-1j*k_y_2[0]*L[iinter+1].thickness) # M[ieq, d[iinter+1][3]] = -SV_2[1, 3]*np.exp(-1j*k_y_2[1]*L[iinter+1].thickness) # ieq += 1 # M[ieq, d[iinter+0][0]] = SV_1[2, 0]*np.exp(-1j*k_y_1[0]*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = SV_1[2, 1]*np.exp(-1j*k_y_1[1]*L[iinter].thickness) # M[ieq, d[iinter+0][2]] = SV_1[2, 2]*np.exp(-1j*k_y_1[2]*L[iinter].thickness) # M[ieq, d[iinter+0][3]] = SV_1[2, 3] # M[ieq, d[iinter+0][4]] = SV_1[2, 4] # M[ieq, d[iinter+0][5]] = SV_1[2, 5] # M[ieq, d[iinter+1][0]] = -SV_2[1, 0] # M[ieq, d[iinter+1][1]] = -SV_2[1, 1] # M[ieq, d[iinter+1][2]] = -SV_2[1, 2]*np.exp(-1j*k_y_2[0]*L[iinter+1].thickness) # M[ieq, d[iinter+1][3]] = -SV_2[1, 3]*np.exp(-1j*k_y_2[1]*L[iinter+1].thickness) # ieq += 1 # M[ieq, d[iinter+0][0]] = (SV_1[3, 0]-SV_1[4, 0])*np.exp(-1j*k_y_1[0]*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = (SV_1[3, 1]-SV_1[4, 1])*np.exp(-1j*k_y_1[1]*L[iinter].thickness) # M[ieq, d[iinter+0][2]] = (SV_1[3, 2]-SV_1[4, 2])*np.exp(-1j*k_y_1[2]*L[iinter].thickness) # M[ieq, d[iinter+0][3]] = (SV_1[3, 3]-SV_1[4, 3]) # M[ieq, d[iinter+0][4]] = (SV_1[3, 4]-SV_1[4, 4]) # M[ieq, d[iinter+0][5]] = (SV_1[3, 5]-SV_1[4, 5]) # M[ieq, d[iinter+1][0]] = -SV_2[2, 0] # M[ieq, d[iinter+1][1]] = -SV_2[2, 1] # M[ieq, d[iinter+1][2]] = -SV_2[2, 2]*np.exp(-1j*k_y_2[0]*L[iinter+1].thickness) # M[ieq, d[iinter+1][3]] = -SV_2[2, 3]*np.exp(-1j*k_y_2[1]*L[iinter+1].thickness) # ieq += 1 # M[ieq, d[iinter+0][0]] = SV_1[5, 0]*np.exp(-1j*k_y_1[0]*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = SV_1[5, 1]*np.exp(-1j*k_y_1[1]*L[iinter].thickness) # M[ieq, d[iinter+0][2]] = SV_1[5, 2]*np.exp(-1j*k_y_1[2]*L[iinter].thickness) # M[ieq, d[iinter+0][3]] = SV_1[5, 3] # M[ieq, d[iinter+0][4]] = SV_1[5, 4] # M[ieq, d[iinter+0][5]] = SV_1[5, 5] # M[ieq, d[iinter+1][0]] = -SV_2[3, 0] # M[ieq, d[iinter+1][1]] = -SV_2[3, 1] # M[ieq, d[iinter+1][2]] = -SV_2[3, 2]*np.exp(-1j*k_y_2[0]*L[iinter+1].thickness) # M[ieq, d[iinter+1][3]] = -SV_2[3, 3]*np.exp(-1j*k_y_2[1]*L[iinter+1].thickness) # ieq += 1 # return ieq # def interface_elastic_elastic(self, ieq, iinter, L, d, M): # SV_1, k_y_1 = elastic_SV(L[iinter].medium,self.kx, self.omega) # SV_2, k_y_2 = elastic_SV(L[iinter+1].medium,self.kx, self.omega) # for _i in range(4): # M[ieq, d[iinter+0][0]] = SV_1[_i, 0]*np.exp(-1j*k_y_1[0]*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = SV_1[_i, 1]*np.exp(-1j*k_y_1[1]*L[iinter].thickness) # M[ieq, d[iinter+0][2]] = SV_1[_i, 2] # M[ieq, d[iinter+0][3]] = SV_1[_i, 3] # M[ieq, d[iinter+1][0]] = -SV_2[_i, 0] # M[ieq, d[iinter+1][1]] = -SV_2[_i, 1] # M[ieq, d[iinter+1][2]] = -SV_2[_i, 2]*np.exp(-1j*k_y_2[0]*L[iinter+1].thickness) # M[ieq, d[iinter+1][3]] = -SV_2[_i, 3]*np.exp(-1j*k_y_2[1]*L[iinter+1].thickness) # ieq += 1 # return ieq # def interface_fluid_elastic(self, ieq, iinter, L, d, M): # SV_1, k_y_1 = fluid_SV(self.kx, self.k, L[iinter].medium.K) # SV_2, k_y_2 = elastic_SV(L[iinter+1].medium, self.kx, self.omega) # # Continuity of u_y # M[ieq, d[iinter+0][0]] = SV_1[0, 0]*np.exp(-1j*k_y_1*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = SV_1[0, 1] # M[ieq, d[iinter+1][0]] = -SV_2[1, 0] # M[ieq, d[iinter+1][1]] = -SV_2[1, 1] # M[ieq, d[iinter+1][2]] = -SV_2[1, 2]*np.exp(-1j*k_y_2[0]*L[iinter+1].thickness) # M[ieq, d[iinter+1][3]] = -SV_2[1, 3]*np.exp(-1j*k_y_2[1]*L[iinter+1].thickness) # ieq += 1 # # sigma_yy = -p # M[ieq, d[iinter+0][0]] = SV_1[1, 0]*np.exp(-1j*k_y_1*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = SV_1[1, 1] # M[ieq, d[iinter+1][0]] = SV_2[2, 0] # M[ieq, d[iinter+1][1]] = SV_2[2, 1] # M[ieq, d[iinter+1][2]] = SV_2[2, 2]*np.exp(-1j*k_y_2[0]*L[iinter+1].thickness) # M[ieq, d[iinter+1][3]] = SV_2[2, 3]*np.exp(-1j*k_y_2[1]*L[iinter+1].thickness) # ieq += 1 # # sigma_xy = 0 # M[ieq, d[iinter+1][0]] = SV_2[0, 0] # M[ieq, d[iinter+1][1]] = SV_2[0, 1] # M[ieq, d[iinter+1][2]] = SV_2[0, 2]*np.exp(-1j*k_y_2[0]*L[iinter+1].thickness) # M[ieq, d[iinter+1][3]] = SV_2[0, 3]*np.exp(-1j*k_y_2[1]*L[iinter+1].thickness) # ieq += 1 # return ieq # def interface_pem_fluid(self, ieq, iinter, L, d, M): # SV_1, k_y_1 = PEM_SV(L[iinter].medium, self.kx) # SV_2, k_y_2 = fluid_SV(self.kx, self.k, L[iinter+1].medium.K) # # print(k_y_2) # M[ieq, d[iinter+0][0]] = -SV_1[2, 0]*np.exp(-1j*k_y_1[0]*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = -SV_1[2, 1]*np.exp(-1j*k_y_1[1]*L[iinter].thickness) # M[ieq, d[iinter+0][2]] = -SV_1[2, 2]*np.exp(-1j*k_y_1[2]*L[iinter].thickness) # M[ieq, d[iinter+0][3]] = -SV_1[2, 3] # M[ieq, d[iinter+0][4]] = -SV_1[2, 4] # M[ieq, d[iinter+0][5]] = -SV_1[2, 5] # M[ieq, d[iinter+1][0]] = SV_2[0, 0] # M[ieq, d[iinter+1][1]] = SV_2[0, 1]*np.exp(-1j*k_y_2*L[iinter+1].thickness) # ieq += 1 # M[ieq, d[iinter+0][0]] = -SV_1[4, 0]*np.exp(-1j*k_y_1[0]*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = -SV_1[4, 1]*np.exp(-1j*k_y_1[1]*L[iinter].thickness) # M[ieq, d[iinter+0][2]] = -SV_1[4, 2]*np.exp(-1j*k_y_1[2]*L[iinter].thickness) # M[ieq, d[iinter+0][3]] = -SV_1[4, 3] # M[ieq, d[iinter+0][4]] = -SV_1[4, 4] # M[ieq, d[iinter+0][5]] = -SV_1[4, 5] # M[ieq, d[iinter+1][0]] = SV_2[1, 0] # M[ieq, d[iinter+1][1]] = SV_2[1, 1]*np.exp(-1j*k_y_2*L[iinter+1].thickness) # ieq += 1 # M[ieq, d[iinter+0][0]] = SV_1[0, 0]*np.exp(-1j*k_y_1[0]*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = SV_1[0, 1]*np.exp(-1j*k_y_1[1]*L[iinter].thickness) # M[ieq, d[iinter+0][2]] = SV_1[0, 2]*np.exp(-1j*k_y_1[2]*L[iinter].thickness) # M[ieq, d[iinter+0][3]] = SV_1[0, 3] # M[ieq, d[iinter+0][4]] = SV_1[0, 4] # M[ieq, d[iinter+0][5]] = SV_1[0, 5] # ieq += 1 # M[ieq, d[iinter+0][0]] = SV_1[3, 0]*np.exp(-1j*k_y_1[0]*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = SV_1[3, 1]*np.exp(-1j*k_y_1[1]*L[iinter].thickness) # M[ieq, d[iinter+0][2]] = SV_1[3, 2]*np.exp(-1j*k_y_1[2]*L[iinter].thickness) # M[ieq, d[iinter+0][3]] = SV_1[3, 3] # M[ieq, d[iinter+0][4]] = SV_1[3, 4] # M[ieq, d[iinter+0][5]] = SV_1[3, 5] # ieq += 1 # return ieq # def interface_elastic_fluid(self, ieq, iinter, L, d, M): # SV_1, k_y_1 = elastic_SV(L[iinter].medium, self.kx, self.omega) # SV_2, k_y_2 = fluid_SV(self.kx, self.k, L[iinter+1].medium.K) # # Continuity of u_y # M[ieq, d[iinter+0][0]] = -SV_1[1, 0]*np.exp(-1j*k_y_1[0]*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = -SV_1[1, 1]*np.exp(-1j*k_y_1[1]*L[iinter].thickness) # M[ieq, d[iinter+0][2]] = -SV_1[1, 2] # M[ieq, d[iinter+0][3]] = -SV_1[1, 3] # M[ieq, d[iinter+1][0]] = SV_2[0, 0] # M[ieq, d[iinter+1][1]] = SV_2[0, 1]*np.exp(-1j*k_y_2*L[iinter+1].thickness) # ieq += 1 # # sigma_yy = -p # M[ieq, d[iinter+0][0]] = SV_1[2, 0]*np.exp(-1j*k_y_1[0]*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = SV_1[2, 1]*np.exp(-1j*k_y_1[1]*L[iinter].thickness) # M[ieq, d[iinter+0][2]] = SV_1[2, 2] # M[ieq, d[iinter+0][3]] = SV_1[2, 3] # M[ieq, d[iinter+1][0]] = SV_2[1, 0] # M[ieq, d[iinter+1][1]] = SV_2[1, 1]*np.exp(-1j*k_y_2*L[iinter+1].thickness) # ieq += 1 # # sigma_xy = 0 # M[ieq, d[iinter+0][0]] = SV_1[0, 0]*np.exp(-1j*k_y_1[0]*L[iinter].thickness) # M[ieq, d[iinter+0][1]] = SV_1[0, 1]*np.exp(-1j*k_y_1[1]*L[iinter].thickness) # M[ieq, d[iinter+0][2]] = SV_1[0, 2] # M[ieq, d[iinter+0][3]] = SV_1[0, 3] # ieq += 1 # return ieq # def interface_elastic_rigid(self, M, ieq, L, d): # SV, k_y = elastic_SV(L.medium,self.kx, self.omega) # M[ieq, d[0]] = SV[1, 0]*np.exp(-1j*k_y[0]*L.thickness) # M[ieq, d[1]] = SV[1, 1]*np.exp(-1j*k_y[1]*L.thickness) # M[ieq, d[2]] = SV[1, 2] # M[ieq, d[3]] = SV[1, 3] # ieq += 1 # M[ieq, d[0]] = SV[3, 0]*np.exp(-1j*k_y[0]*L.thickness) # M[ieq, d[1]] = SV[3, 1]*np.exp(-1j*k_y[1]*L.thickness) # M[ieq, d[2]] = SV[3, 2] # M[ieq, d[3]] = SV[3, 3] # ieq += 1 # return ieq # def interface_pem_rigid(self, M, ieq, L, d): # SV, k_y = PEM_SV(L.medium, self.kx) # M[ieq, d[0]] = SV[1, 0]*np.exp(-1j*k_y[0]*L.thickness) # M[ieq, d[1]] = SV[1, 1]*np.exp(-1j*k_y[1]*L.thickness) # M[ieq, d[2]] = SV[1, 2]*np.exp(-1j*k_y[2]*L.thickness) # M[ieq, d[3]] = SV[1, 3] # M[ieq, d[4]] = SV[1, 4] # M[ieq, d[5]] = SV[1, 5] # ieq += 1 # M[ieq, d[0]] = SV[2, 0]*np.exp(-1j*k_y[0]*L.thickness) # M[ieq, d[1]] = SV[2, 1]*np.exp(-1j*k_y[1]*L.thickness) # M[ieq, d[2]] = SV[2, 2]*np.exp(-1j*k_y[2]*L.thickness) # M[ieq, d[3]] = SV[2, 3] # M[ieq, d[4]] = SV[2, 4] # M[ieq, d[5]] = SV[2, 5] # ieq += 1 # M[ieq, d[0]] = SV[5, 0]*np.exp(-1j*k_y[0]*L.thickness) # M[ieq, d[1]] = SV[5, 1]*np.exp(-1j*k_y[1]*L.thickness) # M[ieq, d[2]] = SV[5, 2]*np.exp(-1j*k_y[2]*L.thickness) # M[ieq, d[3]] = SV[5, 3] # M[ieq, d[4]] = SV[5, 4] # M[ieq, d[5]] = SV[5, 5] # ieq += 1 # return ieq # def plot_sol_PW(self, X, dofs): # x_start = self.shift_plot # for _l, _layer in enumerate(self.layers): # x_f = np.linspace(0, _layer.thickness,200) # x_b = x_f-_layer.thickness # if _layer.medium.MODEL == "fluid": # SV, k_y = fluid_SV(self.kx, self.k, _layer.medium.K) # pr = SV[1, 0]*np.exp(-1j*k_y*x_f)*X[dofs[_l][0]] # pr += SV[1, 1]*np.exp( 1j*k_y*x_b)*X[dofs[_l][1]] # ut = SV[0, 0]*np.exp(-1j*k_y*x_f)*X[dofs[_l][0]] # ut += SV[0, 1]*np.exp( 1j*k_y*x_b)*X[dofs[_l][1]] # if self.plot[2]: # plt.figure(2) # plt.plot(x_start+x_f, np.abs(pr), 'r') # plt.plot(x_start+x_f, np.imag(pr), 'm') # plt.title("Pressure") # # plt.figure(5) # # plt.plot(x_start+x_f,np.abs(ut),'b') # # plt.plot(x_start+x_f,np.imag(ut),'k') # if _layer.medium.MODEL == "pem": # SV, k_y = PEM_SV(_layer.medium, self.kx) # ux, uy, pr, ut = 0*1j*x_f, 0*1j*x_f, 0*1j*x_f, 0*1j*x_f # for i_dim in range(3): # ux += SV[1, i_dim ]*np.exp(-1j*k_y[i_dim]*x_f)*X[dofs[_l][i_dim]] # ux += SV[1, i_dim+3]*np.exp( 1j*k_y[i_dim]*x_b)*X[dofs[_l][i_dim+3]] # uy += SV[5, i_dim ]*np.exp(-1j*k_y[i_dim]*x_f)*X[dofs[_l][i_dim]] # uy += SV[5, i_dim+3]*np.exp( 1j*k_y[i_dim]*x_b)*X[dofs[_l][i_dim+3]] # pr += SV[4, i_dim ]*np.exp(-1j*k_y[i_dim]*x_f)*X[dofs[_l][i_dim]] # pr += SV[4, i_dim+3]*np.exp( 1j*k_y[i_dim]*x_b)*X[dofs[_l][i_dim+3]] # ut += SV[2, i_dim ]*np.exp(-1j*k_y[i_dim]*x_f)*X[dofs[_l][i_dim]] # ut += SV[2, i_dim+3]*np.exp( 1j*k_y[i_dim]*x_b)*X[dofs[_l][i_dim+3]] # if self.plot[0]: # plt.figure(0) # plt.plot(x_start+x_f, np.abs(uy), 'r') # plt.plot(x_start+x_f, np.imag(uy), 'm') # plt.title("Solid displacement along x") # if self.plot[1]: # plt.figure(1) # plt.plot(x_start+x_f, np.abs(ux), 'r') # plt.plot(x_start+x_f, np.imag(ux), 'm') # plt.title("Solid displacement along y") # if self.plot[2]: # plt.figure(2) # plt.plot(x_start+x_f, np.abs(pr), 'r') # plt.plot(x_start+x_f, np.imag(pr), 'm') # plt.title("Pressure") # if _layer.medium.MODEL == "elastic": # SV, k_y = elastic_SV(_layer.medium, self.kx, self.omega) # ux, uy, pr, sig = 0*1j*x_f, 0*1j*x_f, 0*1j*x_f, 0*1j*x_f # for i_dim in range(2): # ux += SV[1, i_dim ]*np.exp(-1j*k_y[i_dim]*x_f)*X[dofs[_l][i_dim]] # ux += SV[1, i_dim+2]*np.exp( 1j*k_y[i_dim]*x_b)*X[dofs[_l][i_dim+2]] # uy += SV[3, i_dim ]*np.exp(-1j*k_y[i_dim]*x_f)*X[dofs[_l][i_dim]] # uy += SV[3, i_dim+2]*np.exp( 1j*k_y[i_dim]*x_b)*X[dofs[_l][i_dim+2]] # pr -= SV[2, i_dim ]*np.exp(-1j*k_y[i_dim]*x_f)*X[dofs[_l][i_dim]] # pr -= SV[2, i_dim+2]*np.exp( 1j*k_y[i_dim]*x_b)*X[dofs[_l][i_dim+2]] # sig -= SV[0, i_dim ]*np.exp(-1j*k_y[i_dim]*x_f)*X[dofs[_l][i_dim]] # sig -= SV[0, i_dim+2]*np.exp( 1j*k_y[i_dim]*x_b)*X[dofs[_l][i_dim+2]] # if self.plot[0]: # plt.figure(0) # plt.plot(x_start+x_f, np.abs(uy), 'r') # plt.plot(x_start+x_f, np.imag(uy), 'm') # plt.title("Solid displacement along x") # if self.plot[1]: # plt.figure(1) # plt.plot(x_start+x_f, np.abs(ux), 'r') # plt.plot(x_start+x_f, np.imag(ux), 'm') # plt.title("Solid displacement along y") # # if self.plot[2]: # # plt.figure(2) # # plt.plot(x_start+x_f, np.abs(pr), 'r') # # plt.plot(x_start+x_f, np.imag(pr), 'm') # # plt.title("Sigma_yy") # # if self.plot[2]: # # plt.figure(3) # # plt.plot(x_start+x_f, np.abs(sig), 'r') # # plt.plot(x_start+x_f, np.imag(sig), 'm') # # plt.title("Sigma_xy") # x_start += _layer.thickness # def PEM_SV(mat,ky): # ''' S={0:\hat{\sigma}_{xy}, 1:u_y^s, 2:u_y^t, 3:\hat{\sigma}_{yy}, 4:p, 5:u_x^s}''' # kx_1 = np.sqrt(mat.delta_1**2-ky**2) # kx_2 = np.sqrt(mat.delta_2**2-ky**2) # kx_3 = np.sqrt(mat.delta_3**2-ky**2) # kx = np.array([kx_1, kx_2, kx_3]) # delta = np.array([mat.delta_1, mat.delta_2, mat.delta_3]) # alpha_1 = -1j*mat.A_hat*mat.delta_1**2-1j*2*mat.N*kx[0]**2 # alpha_2 = -1j*mat.A_hat*mat.delta_2**2-1j*2*mat.N*kx[1]**2 # alpha_3 = -2*1j*mat.N*kx[2]*ky # SV = np.zeros((6,6), dtype=complex) # SV[0:6, 0] = np.array([-2*1j*mat.N*kx[0]*ky, kx[0], mat.mu_1*kx[0], alpha_1, 1j*delta[0]**2*mat.K_eq_til*mat.mu_1, ky]) # SV[0:6, 3] = np.array([ 2*1j*mat.N*kx[0]*ky,-kx[0],-mat.mu_1*kx[0], alpha_1, 1j*delta[0]**2*mat.K_eq_til*mat.mu_1, ky]) # SV[0:6, 1] = np.array([-2*1j*mat.N*kx[1]*ky, kx[1], mat.mu_2*kx[1],alpha_2, 1j*delta[1]**2*mat.K_eq_til*mat.mu_2, ky]) # SV[0:6, 4] = np.array([ 2*1j*mat.N*kx[1]*ky,-kx[1],-mat.mu_2*kx[1],alpha_2, 1j*delta[1]**2*mat.K_eq_til*mat.mu_2, ky]) # SV[0:6, 2] = np.array([1j*mat.N*(kx[2]**2-ky**2), ky, mat.mu_3*ky, alpha_3, 0., -kx[2]]) # SV[0:6, 5] = np.array([1j*mat.N*(kx[2]**2-ky**2), ky, mat.mu_3*ky, -alpha_3, 0., kx[2]]) # return SV, kx # def elastic_SV(mat,ky, omega): # ''' S={0:\sigma_{xy}, 1: u_y, 2 \sigma_{yy}, 3 u_x}''' # P_mat = mat.lambda_ + 2.*mat.mu # delta_p = omega*np.sqrt(mat.rho/P_mat) # delta_s = omega*np.sqrt(mat.rho/mat.mu) # kx_p = np.sqrt(delta_p**2-ky**2) # kx_s = np.sqrt(delta_s**2-ky**2) # kx = np.array([kx_p, kx_s]) # alpha_p = -1j*mat.lambda_*delta_p**2 - 2j*mat.mu*kx[0]**2 # alpha_s = 2j*mat.mu*kx[1]*ky # SV = np.zeros((4, 4), dtype=np.complex) # SV[0:4, 0] = np.array([-2.*1j*mat.mu*kx[0]*ky, kx[0], alpha_p, ky]) # SV[0:4, 2] = np.array([ 2.*1j*mat.mu*kx[0]*ky, -kx[0], alpha_p, ky]) # SV[0:4, 1] = np.array([1j*mat.mu*(kx[1]**2-ky**2), ky,-alpha_s, -kx[1]]) # SV[0:4, 3] = np.array([1j*mat.mu*(kx[1]**2-ky**2), ky, alpha_s, kx[1]]) # return SV, kx # def fluid_SV(kx, k, K): # ''' S={0:u_y , 1:p}''' # ky = np.sqrt(k**2-kx**2) # SV = np.zeros((2, 2), dtype=complex) # SV[0, 0:2] = np.array([ky/(1j*K*k**2), -ky/(1j*K*k**2)]) # SV[1, 0:2] = np.array([1, 1]) # return SV, ky # def resolution_PW_imposed_displacement(S, p): # # print("k={}".format(p.k)) # Layers = S.layers.copy() # n, interfaces, dofs = initialise_PW_solver(Layers, S.backing) # M = np.zeros((n, n), dtype=complex) # i_eq = 0 # # Loop on the layers # for i_inter, _inter in enumerate(interfaces): # if _inter[0] == "fluid": # if _inter[1] == "fluid": # i_eq = interface_fluid_fluid(i_eq, i_inter, Layers, dofs, M, p) # if _inter[1] == "pem": # i_eq = interface_fluid_pem(i_eq, i_inter, Layers, dofs, M, p) # elif _inter[0] == "pem": # if _inter[1] == "fluid": # i_eq = interface_pem_fluid(i_eq, i_inter, Layers, dofs, M, p) # if _inter[1] == "pem": # i_eq = interface_pem_pem(i_eq, i_inter, Layers, dofs, M, p) # if S.backing == backing.rigid: # if Layers[-1].medium.MODEL == "fluid": # i_eq = interface_fluid_rigid(M, i_eq, Layers[-1], dofs[-1], p) # elif Layers[-1].medium.MODEL == "pem": # i_eq = interface_pem_rigid(M, i_eq, Layers[-1], dofs[-1], p) # if Layers[0].medium.MODEL == "fluid": # F = np.zeros(n, dtype=complex) # SV, k_y = fluid_SV(p.kx, p.k, Layers[0].medium.K) # M[i_eq, dofs[0][0]] = SV[0, 0] # M[i_eq, dofs[0][1]] = SV[0, 1]*np.exp(-1j*k_y*Layers[0].thickness) # F[i_eq] = 1. # elif Layers[0].medium.MODEL == "pem": # SV, k_y = PEM_SV(Layers[0].medium, p.kx) # M[i_eq, dofs[0][0]] = SV[2, 0] # M[i_eq, dofs[0][1]] = SV[2, 1] # M[i_eq, dofs[0][2]] = SV[2, 2] # M[i_eq, dofs[0][3]] = SV[2, 3]*np.exp(-1j*k_y[0]*Layers[0].thickness) # M[i_eq, dofs[0][4]] = SV[2, 4]*np.exp(-1j*k_y[1]*Layers[0].thickness) # M[i_eq, dofs[0][5]] = SV[2, 5]*np.exp(-1j*k_y[2]*Layers[0].thickness) # F = np.zeros(n, dtype=complex) # F[i_eq] = 1. # i_eq +=1 # M[i_eq, dofs[0][0]] = SV[0, 0] # M[i_eq, dofs[0][1]] = SV[0, 1] # M[i_eq, dofs[0][2]] = SV[0, 2] # M[i_eq, dofs[0][3]] = SV[0, 3]*np.exp(-1j*k_y[0]*Layers[0].thickness) # M[i_eq, dofs[0][4]] = SV[0, 4]*np.exp(-1j*k_y[1]*Layers[0].thickness) # M[i_eq, dofs[0][5]] = SV[0, 5]*np.exp(-1j*k_y[2]*Layers[0].thickness) # i_eq += 1 # M[i_eq, dofs[0][0]] = SV[3, 0] # M[i_eq, dofs[0][1]] = SV[3, 1] # M[i_eq, dofs[0][2]] = SV[3, 2] # M[i_eq, dofs[0][3]] = SV[3, 3]*np.exp(-1j*k_y[0]*Layers[0].thickness) # M[i_eq, dofs[0][4]] = SV[3, 4]*np.exp(-1j*k_y[1]*Layers[0].thickness) # M[i_eq, dofs[0][5]] = SV[3, 5]*np.exp(-1j*k_y[2]*Layers[0].thickness) # X = LA.solve(M, F) # # print("|R pyPLANES_PW| = {}".format(np.abs(X[0]))) # print("R pyPLANES_PW = {}".format(X[0])) # plot_sol_PW(S, X, dofs, p)
48.911726
132
0.502721
29419686dd2aebba28a504da3cc741b420dcf049
9,001
py
Python
mmtbx/conformation_dependent_library/mcl.py
pcxod/cctbx_project
d43dfb157cd7432292b30c0329b7491d5a356657
[ "BSD-3-Clause-LBNL" ]
null
null
null
mmtbx/conformation_dependent_library/mcl.py
pcxod/cctbx_project
d43dfb157cd7432292b30c0329b7491d5a356657
[ "BSD-3-Clause-LBNL" ]
1
2020-05-26T17:46:17.000Z
2020-05-26T17:55:19.000Z
mmtbx/conformation_dependent_library/mcl.py
pcxod/cctbx_project
d43dfb157cd7432292b30c0329b7491d5a356657
[ "BSD-3-Clause-LBNL" ]
1
2022-02-08T10:11:07.000Z
2022-02-08T10:11:07.000Z
from __future__ import absolute_import, division, print_function import sys import time from cctbx.array_family import flex from scitbx.math import superpose from mmtbx.conformation_dependent_library import mcl_sf4_coordination from six.moves import range from mmtbx.conformation_dependent_library import metal_coordination_library def superpose_ideal_ligand_on_poor_ligand(ideal_hierarchy, poor_hierarchy, ): """Function superpose an ideal ligand onto the mangled ligand from a ligand fitting procedure Args: ideal_hierarchy (pdb_hierarchy): Ideal ligand poor_hierarchy (pdb_hierarchy): Poor ligand with correct c.o.m. and same atom names in order. Could become more sophisticated. """ sites_moving = flex.vec3_double() sites_fixed = flex.vec3_double() for atom1, atom2 in zip(ideal_hierarchy.atoms(), poor_hierarchy.atoms()): assert atom1.name==atom2.name, '%s!=%s' % (atom1.quote(),atom2.quote()) sites_moving.append(atom1.xyz) sites_fixed.append(atom2.xyz) lsq_fit = superpose.least_squares_fit( reference_sites = sites_fixed, other_sites = sites_moving) sites_new = ideal_hierarchy.atoms().extract_xyz() sites_new = lsq_fit.r.elems * sites_new + lsq_fit.t.elems # rmsd = sites_fixed.rms_difference(lsq_fit.other_sites_best_fit()) ideal_hierarchy.atoms().set_xyz(sites_new) return ideal_hierarchy if __name__=="__main__": from iotbx import pdb ideal_inp=pdb.pdb_input(sys.argv[1]) ideal_hierarchy = ideal_inp.construct_hierarchy() poor_inp=pdb.pdb_input(sys.argv[2]) poor_hierarchy = poor_inp.construct_hierarchy() ideal_hierarchy = superpose_ideal_ligand_on_poor_ligand(ideal_hierarchy, poor_hierarchy) ideal_hierarchy.write_pdb_file('new.pdb')
37.504167
103
0.63093
294225b79ce42a07375fda887c5ff1ca0b02cbd1
15,778
py
Python
tests/test_install.py
dfroger/conda
c0f99ff46b217d081501e66f4dcd7bcdb5d9c6aa
[ "BSD-3-Clause" ]
null
null
null
tests/test_install.py
dfroger/conda
c0f99ff46b217d081501e66f4dcd7bcdb5d9c6aa
[ "BSD-3-Clause" ]
null
null
null
tests/test_install.py
dfroger/conda
c0f99ff46b217d081501e66f4dcd7bcdb5d9c6aa
[ "BSD-3-Clause" ]
null
null
null
from contextlib import contextmanager import random import shutil import stat import tempfile import unittest from os.path import join from conda import install from conda.install import (PaddingError, binary_replace, update_prefix, warn_failed_remove, duplicates_to_remove) from .decorators import skip_if_no_mock from .helpers import mock patch = mock.patch if mock else None def generate_all_false_mocks(self): return self.generate_mocks(False, False, False) class duplicates_to_remove_TestCase(unittest.TestCase): if __name__ == '__main__': unittest.main()
38.20339
97
0.609266
29422d091e83652a21c0e3588c5f7b69d97c82a9
728
py
Python
django_elastic_appsearch/slicer.py
CorrosiveKid/django_elastic_appsearch
85da7642aac566164b8bc06894e97a048fd3116e
[ "MIT" ]
11
2019-08-07T01:31:42.000Z
2021-02-02T08:12:24.000Z
django_elastic_appsearch/slicer.py
CorrosiveKid/django_elastic_appsearch
85da7642aac566164b8bc06894e97a048fd3116e
[ "MIT" ]
148
2019-08-01T04:22:28.000Z
2021-05-10T19:06:31.000Z
django_elastic_appsearch/slicer.py
infoxchange/django_elastic_appsearch
65229586f0392d8d8cb143ab625081c89fa4cb64
[ "MIT" ]
6
2019-08-26T10:00:42.000Z
2021-02-01T03:54:02.000Z
"""A Queryset slicer for Django."""
28
69
0.60989
29424d0f4478d5925df5fb2792f4b3b4b39494a0
402
py
Python
newsite/news/urls.py
JasperStfun/Django_C
1307f2e9c827f751e8640f50179f1b744c222d63
[ "Unlicense" ]
null
null
null
newsite/news/urls.py
JasperStfun/Django_C
1307f2e9c827f751e8640f50179f1b744c222d63
[ "Unlicense" ]
null
null
null
newsite/news/urls.py
JasperStfun/Django_C
1307f2e9c827f751e8640f50179f1b744c222d63
[ "Unlicense" ]
null
null
null
from django.urls import path from . import views urlpatterns = [ path('', views.news_home, name='news_home'), path('create', views.create, name='create'), path('<int:pk>', views.NewsDetailView.as_view(), name='news-detail'), path('<int:pk>/update', views.NewsUpdateView.as_view(), name='news-update'), path('<int:pk>/delete', views.NewsDeleteView.as_view(), name='news-delete'), ]
36.545455
80
0.674129
29428a3c880266295d54c48af9bca30d4cdda98d
412
py
Python
module/phase_one/headers.py
cqr-cryeye-forks/Florid
21ea7abbe5448dca0c485232bdcf870ba2648d68
[ "Apache-2.0" ]
7
2020-03-22T02:44:26.000Z
2022-02-23T01:57:29.000Z
module/phase_one/headers.py
h4zze1/Florid-Scanner
0a8600ce2bdd24f16e45504b00c714ecbb8930af
[ "Apache-2.0" ]
1
2019-02-07T13:41:47.000Z
2019-02-07T13:41:47.000Z
module/phase_one/headers.py
h4zze1/Florid-Scanner
0a8600ce2bdd24f16e45504b00c714ecbb8930af
[ "Apache-2.0" ]
3
2020-03-22T02:44:27.000Z
2021-08-03T00:52:38.000Z
import requests import lib.common MODULE_NAME = 'headers'
20.6
78
0.652913
2942faf9418139b387fac9d36b23ead11b7dcd5e
1,234
py
Python
ekorpkit/io/fetch/edgar/edgar.py
entelecheia/ekorpkit
400cb15005fdbcaa2ab0c311e338799283f28fe0
[ "CC-BY-4.0" ]
4
2022-02-26T10:54:16.000Z
2022-02-26T11:01:56.000Z
ekorpkit/io/fetch/edgar/edgar.py
entelecheia/ekorpkit
400cb15005fdbcaa2ab0c311e338799283f28fe0
[ "CC-BY-4.0" ]
1
2022-03-25T06:37:12.000Z
2022-03-25T06:45:53.000Z
ekorpkit/io/fetch/edgar/edgar.py
entelecheia/ekorpkit
400cb15005fdbcaa2ab0c311e338799283f28fe0
[ "CC-BY-4.0" ]
null
null
null
import os import requests from bs4 import BeautifulSoup from ekorpkit import eKonf from ekorpkit.io.download.web import web_download, web_download_unzip
31.641026
73
0.644246
2944646b37b0ab25dfa73f854ed036b7d6e77c63
3,470
py
Python
HARK/ConsumptionSaving/tests/test_PerfForesightConsumerType.py
michiboo/HARK
de2aab467de19da2ce76de1b58fb420f421bc85b
[ "Apache-2.0" ]
null
null
null
HARK/ConsumptionSaving/tests/test_PerfForesightConsumerType.py
michiboo/HARK
de2aab467de19da2ce76de1b58fb420f421bc85b
[ "Apache-2.0" ]
null
null
null
HARK/ConsumptionSaving/tests/test_PerfForesightConsumerType.py
michiboo/HARK
de2aab467de19da2ce76de1b58fb420f421bc85b
[ "Apache-2.0" ]
null
null
null
from HARK.ConsumptionSaving.ConsIndShockModel import PerfForesightConsumerType import numpy as np import unittest
35.408163
111
0.625072
2944814c5ae01dfc5daf1a2ce4f89caabba6e70c
3,893
py
Python
src-gen/openapi_server/models/config.py
etherisc/bima-bolt-api
14201a3055d94ff9c42afbb755109a69e77248f4
[ "Apache-2.0" ]
null
null
null
src-gen/openapi_server/models/config.py
etherisc/bima-bolt-api
14201a3055d94ff9c42afbb755109a69e77248f4
[ "Apache-2.0" ]
null
null
null
src-gen/openapi_server/models/config.py
etherisc/bima-bolt-api
14201a3055d94ff9c42afbb755109a69e77248f4
[ "Apache-2.0" ]
null
null
null
# coding: utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from openapi_server.models.base_model_ import Model from openapi_server.models.component import Component from openapi_server import util from openapi_server.models.component import Component # noqa: E501
25.444444
96
0.579245
2944fda074b1c1551c4b520622df91dd49749873
1,003
py
Python
txt_annotation.py
bubbliiiing/classification-keras
b914c5d8526cccbeb3ae8d8f2fea4c8bbabf1d94
[ "MIT" ]
30
2021-01-23T15:51:20.000Z
2022-03-26T13:37:49.000Z
txt_annotation.py
PARILM/classification-keras
91e558b5a128449b81acc4f6983f01e420b2039d
[ "MIT" ]
4
2021-01-22T08:58:57.000Z
2022-03-17T14:21:07.000Z
txt_annotation.py
PARILM/classification-keras
91e558b5a128449b81acc4f6983f01e420b2039d
[ "MIT" ]
10
2021-01-31T01:23:35.000Z
2022-02-17T11:53:05.000Z
import os from os import getcwd #---------------------------------------------# # classes # model_datatxt #---------------------------------------------# classes = ["cat", "dog"] sets = ["train", "test"] wd = getcwd() for se in sets: list_file = open('cls_' + se + '.txt', 'w') datasets_path = "datasets/" + se types_name = os.listdir(datasets_path) for type_name in types_name: if type_name not in classes: continue cls_id = classes.index(type_name) photos_path = os.path.join(datasets_path, type_name) photos_name = os.listdir(photos_path) for photo_name in photos_name: _, postfix = os.path.splitext(photo_name) if postfix not in ['.jpg', '.png', '.jpeg']: continue list_file.write(str(cls_id) + ";" + '%s/%s'%(wd, os.path.join(photos_path, photo_name))) list_file.write('\n') list_file.close()
31.34375
101
0.521436
29451165b051aed5989a0318d992368267c8109d
5,272
py
Python
S4/S4 Library/simulation/relationships/sim_knowledge.py
NeonOcean/Environment
ca658cf66e8fd6866c22a4a0136d415705b36d26
[ "CC-BY-4.0" ]
1
2021-05-20T19:33:37.000Z
2021-05-20T19:33:37.000Z
S4/S4 Library/simulation/relationships/sim_knowledge.py
NeonOcean/Environment
ca658cf66e8fd6866c22a4a0136d415705b36d26
[ "CC-BY-4.0" ]
null
null
null
S4/S4 Library/simulation/relationships/sim_knowledge.py
NeonOcean/Environment
ca658cf66e8fd6866c22a4a0136d415705b36d26
[ "CC-BY-4.0" ]
null
null
null
from protocolbuffers import SimObjectAttributes_pb2 as protocols from careers.career_unemployment import CareerUnemployment import services import sims4 logger = sims4.log.Logger('Relationship', default_owner='jjacobson')
39.939394
161
0.660281
29452ec5be15d28b45cb5711c4822ec7f8c5c51e
1,001
py
Python
233_number_of_digt_one.py
gengwg/leetcode
0af5256ec98149ef5863f3bba78ed1e749650f6e
[ "Apache-2.0" ]
2
2018-04-24T19:17:40.000Z
2018-04-24T19:33:52.000Z
233_number_of_digt_one.py
gengwg/leetcode
0af5256ec98149ef5863f3bba78ed1e749650f6e
[ "Apache-2.0" ]
null
null
null
233_number_of_digt_one.py
gengwg/leetcode
0af5256ec98149ef5863f3bba78ed1e749650f6e
[ "Apache-2.0" ]
3
2020-06-17T05:48:52.000Z
2021-01-02T06:08:25.000Z
# Given an integer n, count the total number of digit 1 appearing # in all non-negative integers less than or equal to n. # # For example: # Given n = 13, # Return 6, because digit 1 occurred in the following numbers: # 1, 10, 11, 12, 13. # if __name__ == "__main__": print Solution().countDigitOne(13)
22.75
65
0.548452
29458e025d37036dcc3d6da38653c530afc7e75e
13,954
py
Python
Search Algorithms.py
fzehracetin/A-Star-and-Best-First-Search
78be430f0c3523aa78d9822ec8aa19615fd3e500
[ "Apache-2.0" ]
1
2021-02-24T10:13:22.000Z
2021-02-24T10:13:22.000Z
Search Algorithms.py
fzehracetin/A-Star-and-Best-First-Search
78be430f0c3523aa78d9822ec8aa19615fd3e500
[ "Apache-2.0" ]
null
null
null
Search Algorithms.py
fzehracetin/A-Star-and-Best-First-Search
78be430f0c3523aa78d9822ec8aa19615fd3e500
[ "Apache-2.0" ]
null
null
null
from PIL import Image from math import sqrt import numpy as np import time import matplotlib.backends.backend_tkagg import matplotlib.pyplot as plt def distance(point, x, y): return sqrt((point.x - x)**2 + (point.y - y)**2) def insert_in_heap(heap, top, point): heap.append(point) i = top parent = (i - 1)/2 while i >= 1 and heap[int(i)].f < heap[int(parent)].f: heap[int(i)], heap[int(parent)] = heap[int(parent)], heap[int(i)] # swap i = parent parent = (i - 1) / 2 return def calculate_weight(x, y, liste, top, point, visited, index1, index2): if visited[int(x)][int(y)] == 0: r, g, b = image.getpixel((x, y)) if x == end.x and y == end.y: print("Path found.") if r is 0: r = 1 new_point = Point(x, y, 0) new_point.parent = point new_point.h = distance(end, x, y) * (256 - r) new_point.g = 0 if index1 == 1: # a_star new_point.g = new_point.parent.g + 256 - r new_point.f = new_point.h + new_point.g # bfs'de g = 0 if index2 == 0: # stack liste.append(new_point) else: # heap insert_in_heap(liste, top, new_point) top += 1 visited[int(x)][int(y)] = 1 return top def add_neighbours(point, liste, top, visited, index1, index2): # print(point.x, point.y) if (point.x == width - 1 and point.y == height - 1) or (point.x == 0 and point.y == 0) or \ (point.x == 0 and point.y == height - 1) or (point.x == width - 1 and point.y == 0): # print("first if") if point.x == width - 1 and point.y == height - 1: constx = -1 consty = -1 elif point.x == 0 and point.y == 0: constx = 1 consty = 1 elif point.x == width - 1 and point.y == 0: constx = 1 consty = -1 else: constx = -1 consty = 1 top = calculate_weight(point.x + constx, point.y, liste, top, point, visited, index1, index2) top = calculate_weight(point.x, point.y + consty, liste, top, point, visited, index1, index2) top = calculate_weight(point.x + constx, point.y + consty, liste, top, point, visited, index1, index2) elif point.x == 0 or point.x == width - 1: # print("nd if") top = calculate_weight(point.x, point.y - 1, liste, top, point, visited, index1, index2) top = calculate_weight(point.x, point.y + 1, liste, top, point, visited, index1, index2) if point.x == 0: const = 1 else: const = -1 top = calculate_weight(point.x + const, point.y - 1, liste, top, point, visited, index1, index2) top = calculate_weight(point.x + const, point.y + 1, liste, top, point, visited, index1, index2) top = calculate_weight(point.x + const, point.y, liste, top, point, visited, index1, index2) elif point.y == 0 or point.y == height - 1: # print("3rd if") top = calculate_weight(point.x - 1, point.y, liste, top, point, visited, index1, index2) top = calculate_weight(point.x + 1, point.y, liste, top, point, visited, index1, index2) if point.y == 0: const = 1 else: const = -1 top = calculate_weight(point.x - 1, point.y + const, liste, top, point, visited, index1, index2) top = calculate_weight(point.x + 1, point.y + const, liste, top, point, visited, index1, index2) top = calculate_weight(point.x, point.y + const, liste, top, point, visited, index1, index2) else: # print("4th if") top = calculate_weight(point.x - 1, point.y, liste, top, point, visited, index1, index2) top = calculate_weight(point.x - 1, point.y - 1, liste, top, point, visited, index1, index2) top = calculate_weight(point.x - 1, point.y + 1, liste, top, point, visited, index1, index2) top = calculate_weight(point.x + 1, point.y - 1, liste, top, point, visited, index1, index2) top = calculate_weight(point.x + 1, point.y, liste, top, point, visited, index1, index2) top = calculate_weight(point.x + 1, point.y + 1, liste, top, point, visited, index1, index2) top = calculate_weight(point.x, point.y + 1, liste, top, point, visited, index1, index2) top = calculate_weight(point.x, point.y - 1, liste, top, point, visited, index1, index2) return top def paint(point): yol = [] while not point.equal(start): yol.append(point) image.putpixel((int(point.x), int(point.y)), (60, 255, 0)) point = point.parent end_time = time.time() # image.show() '''print("--------------YOL------------------") for i in range(len(yol)): print("x: {}, y:{}, distance:{}".format(yol[i].x, yol[i].y, yol[i].f)) print("------------------------------------")''' return image, (end_time - start_time) def bfs_and_a_star_with_stack(index): stack = [] top = 0 found = False point = None stack.append(start) visited = np.zeros((width, height)) visited[int(start.x)][int(start.y)] = 1 j = 0 max_element = 0 while stack and not found: point = stack.pop(top) # print("x: {}, y:{}, f:{}".format(point.x, point.y, point.f)) top -= 1 if point.equal(end): found = True else: top = add_neighbours(point, stack, top, visited, index, 0) stack.sort(key=lambda point: point.f, reverse=True) if len(stack) > max_element: max_element = len(stack) j += 1 if found: result_image, total_time = paint(point) # print("Stackten ekilen eleman says: ", j) # print("Stackteki maksimum eleman says: ", max_element) return result_image, total_time, j, max_element def find_smallest_child(heap, i, top): if 2 * i + 2 < top: # has two child if heap[2*i + 1].f < heap[2*i + 2].f: return 2*i + 1 else: return 2*i + 2 elif 2*i + 1 < top: # has one child return 2*i + 1 else: # has no child return 0 def remove_min(heap, top): if top == 0: return None min_point = heap[0] top -= 1 heap[0] = heap[top] del heap[top] i = 0 index = find_smallest_child(heap, i, top) while index != 0 and heap[i].f > heap[index].f: heap[i], heap[index] = heap[index], heap[i] i = index index = find_smallest_child(heap, i, top) return min_point, top def bfs_and_a_star_with_heap(index): heap = [] found = False yol = [] point = None heap.append(start) visited = np.zeros((width, height)) visited[int(start.x)][int(start.y)] = 1 j = 0 top = 1 max_element = 0 while heap and not found: point, top = remove_min(heap, top) # print("x: {}, y:{}, f:{}".format(point.x, point.y, point.f)) if point.equal(end): found = True else: top = add_neighbours(point, heap, top, visited, index, 1) if len(heap) > max_element: max_element = len(heap) j += 1 if found: result_image, total_time = paint(point) else: return return result_image, total_time, j, max_element if __name__ == "__main__": print("UYARI: Seilecek grnt exe dosyas ile ayn klasrde olmaldr.") image_name = input("Algoritmann zerinde alaca grntnn ismini giriniz (rnek input: image.png): ") print(image_name) print("-------------------Algoritmalar------------------") print("1- Best First Search with Stack") print("2- Best First Search with Heap") print("3- A* with Stack") print("4- A* with Heap") print("5- Analiz (tm algoritmalarn almalarn ve kyaslamalarn gr)") alg = input("Algoritmay ve veri yapsnn numarasn seiniz (rnek input: 1): ") image = Image.open(image_name) width, height = image.size image = image.convert('RGB') print("Grntnn genilii: {}, ykseklii: {}".format(width, height)) print("NOT: Balang ve biti noktasnn koordinatlar genilik ve uzunluktan kk olmaldr.") sx, sy = input("Balang noktasnn x ve y piksel koordinatlarn srasyla giriniz (rnek input: 350 100): ").split() ex, ey = input("Biti noktasnn x ve y piksel koordinatlarn srasyla giriniz (rnek input: 200 700): ").split() start = Point(int(sx), int(sy), -1) start.parent = -1 end = Point(int(ex), int(ey), -1) start_time = time.time() if int(alg) == 1: result_image, total_time, n_elements, max_elements = bfs_and_a_star_with_stack(0) elif int(alg) == 2: result_image, total_time, n_elements, max_elements = bfs_and_a_star_with_heap(0) elif int(alg) == 3: result_image, total_time, n_elements, max_elements = bfs_and_a_star_with_stack(1) elif int(alg) == 4: result_image, total_time, n_elements, max_elements = bfs_and_a_star_with_heap(1) elif int(alg) == 5: result_image, total_time, n_elements, max_elements = bfs_and_a_star_with_stack(0) output1 = Output(result_image, total_time, n_elements, max_elements) print(n_elements, total_time, max_elements) output1.name = "BFS with Stack" print("1/4") image = Image.open(image_name) width, height = image.size image = image.convert('RGB') start_time = time.time() result_image, total_time, n_elements, max_elements = bfs_and_a_star_with_heap(0) output2 = Output(result_image, total_time, n_elements, max_elements) print(n_elements, total_time, max_elements) output2.name = "BFS with Heap" print("2/4") image = Image.open(image_name) width, height = image.size image = image.convert('RGB') start_time = time.time() result_image, total_time, n_elements, max_elements = bfs_and_a_star_with_stack(1) output3 = Output(result_image, total_time, n_elements, max_elements) output3.name = "A* with Stack" print(n_elements, total_time, max_elements) print("3/4") image = Image.open(image_name) width, height = image.size image = image.convert('RGB') start_time = time.time() result_image, total_time, n_elements, max_elements = bfs_and_a_star_with_heap(1) output4 = Output(result_image, total_time, n_elements, max_elements) output4.name = "A* with Heap" print("4/4") output1.plot_times(output2, output3, output4) output1.plot_max_elements(output2, output3, output4) output1.plot_n_elements(output2, output3, output4) print("Bastrlan grntler srasyla BFS stack, BFS heap, A* stack ve A* heap eklindedir.") fname = image_name.split('.') output1.result_image.show() output1.result_image.save(fname[0] + "BFS_stack.png") output2.result_image.show() output2.result_image.save(fname[0] + "BFS_heap.png") output3.result_image.show() output3.result_image.save(fname[0] + "A_star_stack.png") output4.result_image.show() output4.result_image.save(fname[0] + "A_star_heap.png") exit(0) else: print("Algoritma numaras hatal girildi, tekrar deneyin.") exit(0) print("Stackten ekilen eleman says: ", n_elements) print("Stackteki maksimum eleman says: ", max_elements) print("Toplam sre: ", total_time) result_image.show()
35.68798
124
0.580264
2945bb791202db0434b867efcbc0fdb23fb1256d
624
py
Python
time_test.py
Shb742/rnnoise_python
e370e85984d5909111c9e6e7e4a627bf4de76648
[ "BSD-3-Clause" ]
32
2019-05-24T08:51:36.000Z
2022-03-10T06:10:08.000Z
time_test.py
Shb742/rnnoise_python
e370e85984d5909111c9e6e7e4a627bf4de76648
[ "BSD-3-Clause" ]
3
2020-08-06T09:40:51.000Z
2021-04-21T08:50:20.000Z
time_test.py
Shb742/rnnoise_python
e370e85984d5909111c9e6e7e4a627bf4de76648
[ "BSD-3-Clause" ]
5
2019-09-19T05:54:33.000Z
2021-04-21T08:50:29.000Z
#Author Shoaib Omar import time import rnnoise import numpy as np time_rnnoise()
28.363636
71
0.692308
29461dc478380b16ce5a78cc8afb8aa1b8e6189a
1,092
py
Python
tests/test_shell.py
jakubtyniecki/pact
c23547a2aed1d612180528e33ec1ce021f9badb6
[ "MIT" ]
2
2017-01-12T10:24:31.000Z
2020-06-11T16:05:05.000Z
tests/test_shell.py
jakubtyniecki/pact
c23547a2aed1d612180528e33ec1ce021f9badb6
[ "MIT" ]
null
null
null
tests/test_shell.py
jakubtyniecki/pact
c23547a2aed1d612180528e33ec1ce021f9badb6
[ "MIT" ]
null
null
null
""" shell sort tests module """ import unittest import random from sort import shell from tests import helper
22.285714
80
0.574176
2946888881fb3eee8c4a9270d71f7bab3158abad
666
py
Python
k8s_apps/admin/dump_inventory_file.py
AkadioInc/firefly
d6c48ff9999ffedcaa294fcd956eb97b90408583
[ "BSD-2-Clause" ]
null
null
null
k8s_apps/admin/dump_inventory_file.py
AkadioInc/firefly
d6c48ff9999ffedcaa294fcd956eb97b90408583
[ "BSD-2-Clause" ]
null
null
null
k8s_apps/admin/dump_inventory_file.py
AkadioInc/firefly
d6c48ff9999ffedcaa294fcd956eb97b90408583
[ "BSD-2-Clause" ]
null
null
null
import h5pyd from datetime import datetime import tzlocal BUCKET="firefly-hsds" inventory_domain = "/FIREfly/inventory.h5" f = h5pyd.File(inventory_domain, "r", bucket=BUCKET) table = f["inventory"] for row in table: filename = row[0].decode('utf-8') if row[1]: start = formatTime(row[1]) else: start = 0 if row[2]: stop = formatTime(row[2]) else: stop = 0 print(f"{filename}\t{start}\t{stop}") print(f"{table.nrows} rows")
22.965517
66
0.666667
2946dbe0237daa4f111129ff8959628dbb456b22
2,640
py
Python
enaml/qt/qt_timer.py
xtuzy/enaml
a1b5c0df71c665b6ef7f61d21260db92d77d9a46
[ "BSD-3-Clause-Clear" ]
1,080
2015-01-04T14:29:34.000Z
2022-03-29T05:44:51.000Z
enaml/qt/qt_timer.py
xtuzy/enaml
a1b5c0df71c665b6ef7f61d21260db92d77d9a46
[ "BSD-3-Clause-Clear" ]
308
2015-01-05T22:44:13.000Z
2022-03-30T21:19:18.000Z
enaml/qt/qt_timer.py
xtuzy/enaml
a1b5c0df71c665b6ef7f61d21260db92d77d9a46
[ "BSD-3-Clause-Clear" ]
123
2015-01-25T16:33:48.000Z
2022-02-25T19:57:10.000Z
#------------------------------------------------------------------------------ # Copyright (c) 2013-2017, Nucleic Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. #------------------------------------------------------------------------------ from atom.api import Typed from enaml.widgets.timer import ProxyTimer from .QtCore import QTimer from .qt_toolkit_object import QtToolkitObject
27.789474
79
0.46553
29487962f697ad1bbd8acf9245d0ea5da17bae4f
12,488
py
Python
mindhome_alpha/erpnext/erpnext_integrations/doctype/mpesa_settings/test_mpesa_settings.py
Mindhome/field_service
3aea428815147903eb9af1d0c1b4b9fc7faed057
[ "MIT" ]
1
2021-04-29T14:55:29.000Z
2021-04-29T14:55:29.000Z
mindhome_alpha/erpnext/erpnext_integrations/doctype/mpesa_settings/test_mpesa_settings.py
Mindhome/field_service
3aea428815147903eb9af1d0c1b4b9fc7faed057
[ "MIT" ]
null
null
null
mindhome_alpha/erpnext/erpnext_integrations/doctype/mpesa_settings/test_mpesa_settings.py
Mindhome/field_service
3aea428815147903eb9af1d0c1b4b9fc7faed057
[ "MIT" ]
1
2021-04-29T14:39:01.000Z
2021-04-29T14:39:01.000Z
# -*- coding: utf-8 -*- # Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and Contributors # See license.txt from __future__ import unicode_literals from json import dumps import frappe import unittest from erpnext.erpnext_integrations.doctype.mpesa_settings.mpesa_settings import process_balance_info, verify_transaction from erpnext.accounts.doctype.pos_invoice.test_pos_invoice import create_pos_invoice def get_test_account_balance_response(): """Response received after calling the account balance API.""" return { "ResultType":0, "ResultCode":0, "ResultDesc":"The service request has been accepted successfully.", "OriginatorConversationID":"10816-694520-2", "ConversationID":"AG_20200927_00007cdb1f9fb6494315", "TransactionID":"LGR0000000", "ResultParameters":{ "ResultParameter":[ { "Key":"ReceiptNo", "Value":"LGR919G2AV" }, { "Key":"Conversation ID", "Value":"AG_20170727_00004492b1b6d0078fbe" }, { "Key":"FinalisedTime", "Value":20170727101415 }, { "Key":"Amount", "Value":10 }, { "Key":"TransactionStatus", "Value":"Completed" }, { "Key":"ReasonType", "Value":"Salary Payment via API" }, { "Key":"TransactionReason" }, { "Key":"DebitPartyCharges", "Value":"Fee For B2C Payment|KES|33.00" }, { "Key":"DebitAccountType", "Value":"Utility Account" }, { "Key":"InitiatedTime", "Value":20170727101415 }, { "Key":"Originator Conversation ID", "Value":"19455-773836-1" }, { "Key":"CreditPartyName", "Value":"254708374149 - John Doe" }, { "Key":"DebitPartyName", "Value":"600134 - Safaricom157" } ] }, "ReferenceData":{ "ReferenceItem":{ "Key":"Occasion", "Value":"aaaa" } } } def get_payment_request_response_payload(Amount=500): """Response received after successfully calling the stk push process request API.""" CheckoutRequestID = frappe.utils.random_string(10) return { "MerchantRequestID": "8071-27184008-1", "CheckoutRequestID": CheckoutRequestID, "ResultCode": 0, "ResultDesc": "The service request is processed successfully.", "CallbackMetadata": { "Item": [ { "Name": "Amount", "Value": Amount }, { "Name": "MpesaReceiptNumber", "Value": "LGR7OWQX0R" }, { "Name": "TransactionDate", "Value": 20201006113336 }, { "Name": "PhoneNumber", "Value": 254723575670 } ] } } def get_payment_callback_payload(Amount=500, CheckoutRequestID="ws_CO_061020201133231972", MpesaReceiptNumber="LGR7OWQX0R"): """Response received from the server as callback after calling the stkpush process request API.""" return { "Body":{ "stkCallback":{ "MerchantRequestID":"19465-780693-1", "CheckoutRequestID":CheckoutRequestID, "ResultCode":0, "ResultDesc":"The service request is processed successfully.", "CallbackMetadata":{ "Item":[ { "Name":"Amount", "Value":Amount }, { "Name":"MpesaReceiptNumber", "Value":MpesaReceiptNumber }, { "Name":"Balance" }, { "Name":"TransactionDate", "Value":20170727154800 }, { "Name":"PhoneNumber", "Value":254721566839 } ] } } } } def get_account_balance_callback_payload(): """Response received from the server as callback after calling the account balance API.""" return { "Result":{ "ResultType": 0, "ResultCode": 0, "ResultDesc": "The service request is processed successfully.", "OriginatorConversationID": "16470-170099139-1", "ConversationID": "AG_20200927_00007cdb1f9fb6494315", "TransactionID": "OIR0000000", "ResultParameters": { "ResultParameter": [ { "Key": "AccountBalance", "Value": "Working Account|KES|481000.00|481000.00|0.00|0.00" }, { "Key": "BOCompletedTime", "Value": 20200927234123 } ] }, "ReferenceData": { "ReferenceItem": { "Key": "QueueTimeoutURL", "Value": "https://internalsandbox.safaricom.co.ke/mpesa/abresults/v1/submit" } } } }
35.177465
124
0.738629
2948b21202accf70d658d0b73f9aafb72b41be55
114
py
Python
b2accessdeprovisioning/configparser.py
EUDAT-B2ACCESS/b2access-deprovisioning-report
2260347a4e1f522386c188c0dfae2e94bc5b2a40
[ "Apache-2.0" ]
null
null
null
b2accessdeprovisioning/configparser.py
EUDAT-B2ACCESS/b2access-deprovisioning-report
2260347a4e1f522386c188c0dfae2e94bc5b2a40
[ "Apache-2.0" ]
null
null
null
b2accessdeprovisioning/configparser.py
EUDAT-B2ACCESS/b2access-deprovisioning-report
2260347a4e1f522386c188c0dfae2e94bc5b2a40
[ "Apache-2.0" ]
2
2017-10-05T07:26:39.000Z
2017-10-05T07:27:54.000Z
from __future__ import absolute_import import yaml with open("config.yml", "r") as f: config = yaml.load(f)
16.285714
38
0.710526
2948ba6edb0a75f155add6e7fa7726939cd6ba56
3,870
py
Python
res_mods/mods/packages/xvm_main/python/vehinfo_tiers.py
peterbartha/ImmunoMod
cbf8cd49893d7082a347c1f72c0e39480869318a
[ "MIT" ]
null
null
null
res_mods/mods/packages/xvm_main/python/vehinfo_tiers.py
peterbartha/ImmunoMod
cbf8cd49893d7082a347c1f72c0e39480869318a
[ "MIT" ]
1
2016-04-03T13:31:39.000Z
2016-04-03T16:48:26.000Z
res_mods/mods/packages/xvm_main/python/vehinfo_tiers.py
peterbartha/ImmunoMod
cbf8cd49893d7082a347c1f72c0e39480869318a
[ "MIT" ]
null
null
null
""" XVM (c) www.modxvm.com 2013-2017 """ # PUBLIC # PRIVATE from logger import * from gui.shared.utils.requesters import REQ_CRITERIA from helpers import dependency from skeletons.gui.shared import IItemsCache _special = { # Data from http://forum.worldoftanks.ru/index.php?/topic/41221- # Last update: 23.05.2017 # level 2 'germany:G53_PzI': [ 2, 2 ], 'uk:GB76_Mk_VIC': [ 2, 2 ], 'usa:A19_T2_lt': [ 2, 4 ], 'usa:A93_T7_Combat_Car': [ 2, 2 ], # level 3 'germany:G36_PzII_J': [ 3, 4 ], 'japan:J05_Ke_Ni_B': [ 3, 4 ], 'ussr:R34_BT-SV': [ 3, 4 ], 'ussr:R50_SU76I': [ 3, 4 ], 'ussr:R56_T-127': [ 3, 4 ], 'ussr:R67_M3_LL': [ 3, 4 ], 'ussr:R86_LTP': [ 3, 4 ], # level 4 'france:F14_AMX40': [ 4, 6 ], 'germany:G35_B-1bis_captured': [ 4, 4 ], 'japan:J06_Ke_Ho': [ 4, 6 ], 'uk:GB04_Valentine': [ 4, 6 ], 'uk:GB60_Covenanter': [ 4, 6 ], 'ussr:R12_A-20': [ 4, 6 ], 'ussr:R31_Valentine_LL': [ 4, 4 ], 'ussr:R44_T80': [ 4, 6 ], 'ussr:R68_A-32': [ 4, 5 ], # level 5 'germany:G104_Stug_IV': [ 5, 6 ], 'germany:G32_PzV_PzIV': [ 5, 6 ], 'germany:G32_PzV_PzIV_ausf_Alfa': [ 5, 6 ], 'germany:G70_PzIV_Hydro': [ 5, 6 ], 'uk:GB20_Crusader': [ 5, 7 ], 'uk:GB51_Excelsior': [ 5, 6 ], 'uk:GB68_Matilda_Black_Prince': [ 5, 6 ], 'usa:A21_T14': [ 5, 6 ], 'usa:A44_M4A2E4': [ 5, 6 ], 'ussr:R32_Matilda_II_LL': [ 5, 6 ], 'ussr:R33_Churchill_LL': [ 5, 6 ], 'ussr:R38_KV-220': [ 5, 6 ], 'ussr:R38_KV-220_beta': [ 5, 6 ], 'ussr:R78_SU_85I': [ 5, 6 ], # level 6 'germany:G32_PzV_PzIV_CN': [ 6, 7 ], 'germany:G32_PzV_PzIV_ausf_Alfa_CN': [ 6, 7 ], 'uk:GB63_TOG_II': [ 6, 7 ], # level 7 'germany:G48_E-25': [ 7, 8 ], 'germany:G78_Panther_M10': [ 7, 8 ], 'uk:GB71_AT_15A': [ 7, 8 ], 'usa:A86_T23E3': [ 7, 8 ], 'ussr:R98_T44_85': [ 7, 8 ], 'ussr:R99_T44_122': [ 7, 8 ], # level 8 'china:Ch01_Type59': [ 8, 9 ], 'china:Ch03_WZ-111': [ 8, 9 ], 'china:Ch14_T34_3': [ 8, 9 ], 'china:Ch23_112': [ 8, 9 ], 'france:F65_FCM_50t': [ 8, 9 ], 'germany:G65_JagdTiger_SdKfz_185': [ 8, 9 ], 'usa:A45_M6A2E1': [ 8, 9 ], 'usa:A80_T26_E4_SuperPershing': [ 8, 9 ], 'ussr:R54_KV-5': [ 8, 9 ], 'ussr:R61_Object252': [ 8, 9 ], 'ussr:R61_Object252_BF': [ 8, 9 ], }
36.857143
93
0.445478
294933d7ee4435c7faf58b9337983fadc1b0d19b
6,099
py
Python
pypy/module/cpyext/test/test_pystrtod.py
m4sterchain/mesapy
ed546d59a21b36feb93e2309d5c6b75aa0ad95c9
[ "Apache-2.0", "OpenSSL" ]
381
2018-08-18T03:37:22.000Z
2022-02-06T23:57:36.000Z
pypy/module/cpyext/test/test_pystrtod.py
m4sterchain/mesapy
ed546d59a21b36feb93e2309d5c6b75aa0ad95c9
[ "Apache-2.0", "OpenSSL" ]
16
2018-09-22T18:12:47.000Z
2022-02-22T20:03:59.000Z
pypy/module/cpyext/test/test_pystrtod.py
m4sterchain/mesapy
ed546d59a21b36feb93e2309d5c6b75aa0ad95c9
[ "Apache-2.0", "OpenSSL" ]
30
2018-08-20T03:16:34.000Z
2022-01-12T17:39:22.000Z
import math from pypy.module.cpyext import pystrtod from pypy.module.cpyext.test.test_api import BaseApiTest, raises_w from rpython.rtyper.lltypesystem import rffi from rpython.rtyper.lltypesystem import lltype from pypy.module.cpyext.pystrtod import PyOS_string_to_double
37.881988
70
0.624529
294a474ec8bf0bc2d0dc645a827ce6425f19ce7f
3,529
py
Python
mathics/core/systemsymbols.py
Mathics3/mathics-core
54dc3c00a42cd893c6430054e125291b6eb55ead
[ "Apache-2.0" ]
90
2021-09-11T14:14:00.000Z
2022-03-29T02:08:29.000Z
mathics/core/systemsymbols.py
Mathics3/mathics-core
54dc3c00a42cd893c6430054e125291b6eb55ead
[ "Apache-2.0" ]
187
2021-09-13T01:00:41.000Z
2022-03-31T11:52:52.000Z
mathics/core/systemsymbols.py
Mathics3/mathics-core
54dc3c00a42cd893c6430054e125291b6eb55ead
[ "Apache-2.0" ]
10
2021-10-05T15:44:26.000Z
2022-03-21T12:34:33.000Z
# -*- coding: utf-8 -*- from mathics.core.symbols import Symbol # Some other common Symbols. This list is sorted in alphabetic order. SymbolAssumptions = Symbol("$Assumptions") SymbolAborted = Symbol("$Aborted") SymbolAll = Symbol("All") SymbolAlternatives = Symbol("Alternatives") SymbolAnd = Symbol("And") SymbolAppend = Symbol("Append") SymbolApply = Symbol("Apply") SymbolAssociation = Symbol("Association") SymbolAutomatic = Symbol("Automatic") SymbolBlank = Symbol("Blank") SymbolBlend = Symbol("Blend") SymbolByteArray = Symbol("ByteArray") SymbolCatalan = Symbol("Catalan") SymbolColorData = Symbol("ColorData") SymbolComplex = Symbol("Complex") SymbolComplexInfinity = Symbol("ComplexInfinity") SymbolCondition = Symbol("Condition") SymbolConditionalExpression = Symbol("ConditionalExpression") Symbol_Context = Symbol("$Context") Symbol_ContextPath = Symbol("$ContextPath") SymbolCos = Symbol("Cos") SymbolD = Symbol("D") SymbolDerivative = Symbol("Derivative") SymbolDirectedInfinity = Symbol("DirectedInfinity") SymbolDispatch = Symbol("Dispatch") SymbolE = Symbol("E") SymbolEdgeForm = Symbol("EdgeForm") SymbolEqual = Symbol("Equal") SymbolExpandAll = Symbol("ExpandAll") SymbolEulerGamma = Symbol("EulerGamma") SymbolFailed = Symbol("$Failed") SymbolFunction = Symbol("Function") SymbolGamma = Symbol("Gamma") SymbolGet = Symbol("Get") SymbolGoldenRatio = Symbol("GoldenRatio") SymbolGraphics = Symbol("Graphics") SymbolGreater = Symbol("Greater") SymbolGreaterEqual = Symbol("GreaterEqual") SymbolGrid = Symbol("Grid") SymbolHoldForm = Symbol("HoldForm") SymbolIndeterminate = Symbol("Indeterminate") SymbolImplies = Symbol("Implies") SymbolInfinity = Symbol("Infinity") SymbolInfix = Symbol("Infix") SymbolInteger = Symbol("Integer") SymbolIntegrate = Symbol("Integrate") SymbolLeft = Symbol("Left") SymbolLess = Symbol("Less") SymbolLessEqual = Symbol("LessEqual") SymbolLog = Symbol("Log") SymbolMachinePrecision = Symbol("MachinePrecision") SymbolMakeBoxes = Symbol("MakeBoxes") SymbolMessageName = Symbol("MessageName") SymbolMinus = Symbol("Minus") SymbolMap = Symbol("Map") SymbolMatrixPower = Symbol("MatrixPower") SymbolMaxPrecision = Symbol("$MaxPrecision") SymbolMemberQ = Symbol("MemberQ") SymbolMinus = Symbol("Minus") SymbolN = Symbol("N") SymbolNeeds = Symbol("Needs") SymbolNIntegrate = Symbol("NIntegrate") SymbolNone = Symbol("None") SymbolNot = Symbol("Not") SymbolNull = Symbol("Null") SymbolNumberQ = Symbol("NumberQ") SymbolNumericQ = Symbol("NumericQ") SymbolOptionValue = Symbol("OptionValue") SymbolOr = Symbol("Or") SymbolOverflow = Symbol("Overflow") SymbolPackages = Symbol("$Packages") SymbolPattern = Symbol("Pattern") SymbolPi = Symbol("Pi") SymbolPiecewise = Symbol("Piecewise") SymbolPoint = Symbol("Point") SymbolPossibleZeroQ = Symbol("PossibleZeroQ") SymbolQuiet = Symbol("Quiet") SymbolRational = Symbol("Rational") SymbolReal = Symbol("Real") SymbolRow = Symbol("Row") SymbolRowBox = Symbol("RowBox") SymbolRGBColor = Symbol("RGBColor") SymbolSuperscriptBox = Symbol("SuperscriptBox") SymbolRule = Symbol("Rule") SymbolRuleDelayed = Symbol("RuleDelayed") SymbolSequence = Symbol("Sequence") SymbolSeries = Symbol("Series") SymbolSeriesData = Symbol("SeriesData") SymbolSet = Symbol("Set") SymbolSimplify = Symbol("Simplify") SymbolSin = Symbol("Sin") SymbolSlot = Symbol("Slot") SymbolStringQ = Symbol("StringQ") SymbolStyle = Symbol("Style") SymbolTable = Symbol("Table") SymbolToString = Symbol("ToString") SymbolUndefined = Symbol("Undefined") SymbolXor = Symbol("Xor")
33.932692
69
0.765373
294bff20d8c499704a706ccaf6f51e0e5fd8ce4d
5,821
py
Python
exercises/ali/cartpole-MCTS/cartpole.py
alik604/ra
6058a9adb47db93bb86bcb2c224930c5731d663d
[ "Unlicense" ]
null
null
null
exercises/ali/cartpole-MCTS/cartpole.py
alik604/ra
6058a9adb47db93bb86bcb2c224930c5731d663d
[ "Unlicense" ]
5
2021-03-26T01:30:13.000Z
2021-04-22T22:19:03.000Z
exercises/ali/cartpole-MCTS/cartpole.py
alik604/ra
6058a9adb47db93bb86bcb2c224930c5731d663d
[ "Unlicense" ]
1
2021-05-05T00:57:43.000Z
2021-05-05T00:57:43.000Z
# from https://github.com/kvwoerden/mcts-cartpole # ---------------------------------------------------------------------------- # # Imports # # ---------------------------------------------------------------------------- # import os import time import random import argparse <<<<<<< HEAD ======= from types import SimpleNamespace >>>>>>> MCTS import gym from gym import logger from gym.wrappers.monitoring.video_recorder import VideoRecorder from Simple_mcts import MCTSAgent <<<<<<< HEAD # ---------------------------------------------------------------------------- # # Constants # # ---------------------------------------------------------------------------- # SEED = 28 EPISODES = 1 ENVIRONMENT = 'CartPole-v0' LOGGER_LEVEL = logger.WARN ITERATION_BUDGET = 80 LOOKAHEAD_TARGET = 100 MAX_EPISODE_STEPS = 1500 VIDEO_BASEPATH = '.\\video' # './video' START_CP = 20 ======= from Agent import dqn_agent # ---------------------------------------------------------------------------- # # Constants # # ---------------------------------------------------------------------------- # LOGGER_LEVEL = logger.WARN args = dict() args['env_name'] = 'CartPole-v0' args['episodes'] = 10 args['seed'] = 28 args['iteration_budget'] = 8000 # The number of iterations for each search step. Increasing this should lead to better performance.') args['lookahead_target'] = 10000 # The target number of steps the agent aims to look forward.' args['max_episode_steps'] = 1500 # The maximum number of steps to play. args['video_basepath'] = '.\\video' # './video' args['start_cp'] = 20 # The start value of C_p, the value that the agent changes to try to achieve the lookahead target. Decreasing this makes the search tree deeper, increasing this makes the search tree wider. args = SimpleNamespace(**args) >>>>>>> MCTS # ---------------------------------------------------------------------------- # # Main loop # # ---------------------------------------------------------------------------- # if __name__ == '__main__': <<<<<<< HEAD random.seed(SEED) parser = argparse.ArgumentParser( description='Run a Monte Carlo Tree Search agent on the Cartpole environment', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--env_id', nargs='?', default=ENVIRONMENT, help='The environment to run (only CartPole-v0 is supperted)') parser.add_argument('--episodes', nargs='?', default=EPISODES, type=int, help='The number of episodes to run.') parser.add_argument('--iteration_budget', nargs='?', default=ITERATION_BUDGET, type=int, help='The number of iterations for each search step. Increasing this should lead to better performance.') parser.add_argument('--lookahead_target', nargs='?', default=LOOKAHEAD_TARGET, type=int, help='The target number of steps the agent aims to look forward.') parser.add_argument('--max_episode_steps', nargs='?', default=MAX_EPISODE_STEPS, type=int, help='The maximum number of steps to play.') parser.add_argument('--video_basepath', nargs='?', default=VIDEO_BASEPATH, help='The basepath where the videos will be stored.') parser.add_argument('--start_cp', nargs='?', default=START_CP, type=int, help='The start value of C_p, the value that the agent changes to try to achieve the lookahead target. Decreasing this makes the search tree deeper, increasing this makes the search tree wider.') parser.add_argument('--seed', nargs='?', default=SEED, type=int, help='The random seed.') args = parser.parse_args() logger.set_level(LOGGER_LEVEL) env = gym.make(args.env_id) env.seed(args.seed) agent = MCTSAgent(args.iteration_budget, args.env_id) ======= logger.set_level(LOGGER_LEVEL) random.seed(args.seed) env = gym.make(args.env_name) env.seed(args.seed) Q_net = dqn_agent() agent = MCTSAgent(args.iteration_budget, env, Q_net) >>>>>>> MCTS timestr = time.strftime("%Y%m%d-%H%M%S") reward = 0 done = False for i in range(args.episodes): ob = env.reset() env._max_episode_steps = args.max_episode_steps video_path = os.path.join( args.video_basepath, f"output_{timestr}_{i}.mp4") <<<<<<< HEAD rec = VideoRecorder(env, path=video_path) ======= # rec = VideoRecorder(env, path=video_path) >>>>>>> MCTS try: sum_reward = 0 node = None all_nodes = [] C_p = args.start_cp while True: print("################") env.render() <<<<<<< HEAD rec.capture_frame() ======= # rec.capture_frame() >>>>>>> MCTS action, node, C_p = agent.act(env.state, n_actions=env.action_space.n, node=node, C_p=C_p, lookahead_target=args.lookahead_target) ob, reward, done, _ = env.step(action) print("### observed state: ", ob) sum_reward += reward print("### sum_reward: ", sum_reward) if done: <<<<<<< HEAD rec.close() break except KeyboardInterrupt as e: rec.close() ======= # rec.close() break except KeyboardInterrupt as e: # rec.close() >>>>>>> MCTS env.close() raise e env.close()
39.067114
219
0.519842
294c561a401bd6bdb0db578e7797d3a5175a9a58
318
py
Python
wildlifecompliance/components/applications/cron.py
preranaandure/wildlifecompliance
bc19575f7bccf7e19adadbbaf5d3eda1d1aee4b5
[ "Apache-2.0" ]
1
2020-12-07T17:12:40.000Z
2020-12-07T17:12:40.000Z
wildlifecompliance/components/applications/cron.py
preranaandure/wildlifecompliance
bc19575f7bccf7e19adadbbaf5d3eda1d1aee4b5
[ "Apache-2.0" ]
14
2020-01-08T08:08:26.000Z
2021-03-19T22:59:46.000Z
wildlifecompliance/components/applications/cron.py
preranaandure/wildlifecompliance
bc19575f7bccf7e19adadbbaf5d3eda1d1aee4b5
[ "Apache-2.0" ]
15
2020-01-08T08:02:28.000Z
2021-11-03T06:48:32.000Z
from django_cron import CronJobBase, Schedule
21.2
50
0.704403
294ddecc4d289926d35a18bd81582fdedcf038ee
2,999
py
Python
optional-plugins/CSVPlugin/CSVContext.py
owlfish/pubtal
fb20a0acf2769b2c06012b65bd462f02da12bd1c
[ "BSD-3-Clause" ]
null
null
null
optional-plugins/CSVPlugin/CSVContext.py
owlfish/pubtal
fb20a0acf2769b2c06012b65bd462f02da12bd1c
[ "BSD-3-Clause" ]
null
null
null
optional-plugins/CSVPlugin/CSVContext.py
owlfish/pubtal
fb20a0acf2769b2c06012b65bd462f02da12bd1c
[ "BSD-3-Clause" ]
null
null
null
import ASV from simpletal import simpleTAL, simpleTALES try: import logging except: import InfoLogging as logging import codecs
26.307018
92
0.686896
294e1d0fe03b7258df243ff2841d037d1b8158e8
2,484
py
Python
wagtail/admin/forms/comments.py
stephiescastle/wagtail
391f46ef91ca4a7bbf339bf9e9a738df3eb8e179
[ "BSD-3-Clause" ]
null
null
null
wagtail/admin/forms/comments.py
stephiescastle/wagtail
391f46ef91ca4a7bbf339bf9e9a738df3eb8e179
[ "BSD-3-Clause" ]
null
null
null
wagtail/admin/forms/comments.py
stephiescastle/wagtail
391f46ef91ca4a7bbf339bf9e9a738df3eb8e179
[ "BSD-3-Clause" ]
null
null
null
from django.forms import BooleanField, ValidationError from django.utils.timezone import now from django.utils.translation import gettext as _ from .models import WagtailAdminModelForm
34.5
129
0.594605
294e291b1d27799d1015e0d511b66da83b03b728
1,039
py
Python
run_db_data.py
MahirMahbub/email-client
71ab85f987f783b703b58780444c072bd683927e
[ "MIT" ]
null
null
null
run_db_data.py
MahirMahbub/email-client
71ab85f987f783b703b58780444c072bd683927e
[ "MIT" ]
4
2021-08-01T16:29:48.000Z
2021-08-01T16:58:36.000Z
run_db_data.py
MahirMahbub/email-client
71ab85f987f783b703b58780444c072bd683927e
[ "MIT" ]
null
null
null
import os from sqlalchemy.orm import Session from db.database import SessionLocal
23.088889
79
0.549567
29509faf87f0d6a17ff1205ace918609c71b08fe
1,750
py
Python
five/five_copy.py
ngd-b/python-demo
0341c1620bcde1c1d886cb9e75dc6db3722273c8
[ "MIT" ]
1
2019-10-09T13:40:13.000Z
2019-10-09T13:40:13.000Z
five/five_copy.py
ngd-b/python-demo
0341c1620bcde1c1d886cb9e75dc6db3722273c8
[ "MIT" ]
null
null
null
five/five_copy.py
ngd-b/python-demo
0341c1620bcde1c1d886cb9e75dc6db3722273c8
[ "MIT" ]
null
null
null
#!/usr/bin/python # -*- coding:utf-8 -*- print("hello world") f = None try: f = open("./hello.txt","r",encoding="utf8") print(f.read(5),end='') print(f.read(5),end='') print(f.read(5)) except IOError as e: print(e) finally: if f: f.close() # with auto call the methods' close with open("./hello.txt","r",encoding="utf8") as f: print(f.read()) # readlines() with open("./hello.txt","r",encoding="utf8") as f: for line in f.readlines(): print(line.strip()) # with open("./hello_1.txt","w",encoding="utf8") as f: f.write("!") with open("./hello.txt","a",encoding="utf8") as f: f.write(" 70!") # StringIO / BytesIO from io import StringIO # str = StringIO('init') # while True: s = str.readline() if s == '': break print(s.strip()) # str.write("!") str.write(" ") # print(str.getvalue()) ''' while True: s = str.readline() if s == '': break print(s.strip()) ''' # from io import BytesIO bi = BytesIO() bi.write("".encode("utf-8")) print(bi.getvalue()) by = BytesIO(b'\xe4\xbd\xa0\xe5\xa5\xbd') print(by.read()) # OS import os # nt print(os.name) # python <module 'ntpath' from 'G:\\python-3.7\\lib\\ntpath.py'> print(os.path) # print(os.environ) # 'bobol' print(os.getlogin()) # os.mkdir("./foo/") # os.rmdir("./foo/") ''' os.path ''' # 'G:\\pythonDemo\\python-demo\\five' print(os.path.abspath("./")) # False print(os.path.exists("./foo")) # 4096 print(os.path.getsize("../")) # False print(os.path.isabs("../"))
19.444444
72
0.6
2951e1c21121343a134fe48bfcc73abc7a482cb1
6,355
py
Python
examples/batch_ts_insert.py
bureau14/qdb-api-python
2a010df3252d39bc4d529f545547c5cefb9fe86e
[ "BSD-3-Clause" ]
9
2015-09-02T20:13:13.000Z
2020-07-16T14:17:36.000Z
examples/batch_ts_insert.py
bureau14/qdb-api-python
2a010df3252d39bc4d529f545547c5cefb9fe86e
[ "BSD-3-Clause" ]
5
2018-02-20T10:47:02.000Z
2020-05-20T10:05:49.000Z
examples/batch_ts_insert.py
bureau14/qdb-api-python
2a010df3252d39bc4d529f545547c5cefb9fe86e
[ "BSD-3-Clause" ]
1
2018-04-01T11:12:56.000Z
2018-04-01T11:12:56.000Z
# Copyright (c) 2009-2020, quasardb SAS. All rights reserved. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of quasardb nor the names of its contributors may # be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY QUASARDB AND CONTRIBUTORS ``AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # from __future__ import print_function from builtins import range as xrange, int import os from socket import gethostname import sys import inspect import traceback import random import time import datetime import locale import numpy as np import quasardb STOCK_COLUMN = "stock_id" OPEN_COLUMN = "open" CLOSE_COLUMN = "close" HIGH_COLUMN = "high" LOW_COLUMN = "low" VOLUME_COLUMN = "volume" if __name__ == "__main__": try: if len(sys.argv) != 3: print("usage: ", sys.argv[0], " quasardb_uri points_count") sys.exit(1) main(sys.argv[1], int(sys.argv[2])) except Exception as ex: # pylint: disable=W0703 print("An error ocurred:", str(ex)) traceback.print_exc()
40.737179
165
0.70181
295371af41debc44d7d6cd681954bb737b9ceb2b
2,128
py
Python
tests/backends/test_flashtext_backend.py
openredact/pii-identifier
97eaef56d6de59718501095d631a0fb49700e45a
[ "MIT" ]
14
2020-07-31T18:45:29.000Z
2022-02-21T13:24:00.000Z
tests/backends/test_flashtext_backend.py
openredact/pii-identifier
97eaef56d6de59718501095d631a0fb49700e45a
[ "MIT" ]
7
2020-07-31T06:17:21.000Z
2021-05-23T08:40:24.000Z
tests/backends/test_flashtext_backend.py
openredact/pii-identifier
97eaef56d6de59718501095d631a0fb49700e45a
[ "MIT" ]
1
2020-09-30T01:42:57.000Z
2020-09-30T01:42:57.000Z
from nerwhal.backends.flashtext_backend import FlashtextBackend from nerwhal.recognizer_bases import FlashtextRecognizer
26.6
63
0.62218
2954339ee63d8f3aeb46e217258769ecc01fa43c
1,444
py
Python
new_rdsmysql.py
AdminTurnedDevOps/AWS_Solutions_Architect_Python
5389f8c9dfbda7b0b49a94a93e9b070420ca9ece
[ "MIT" ]
30
2019-01-13T20:14:07.000Z
2022-02-06T15:08:01.000Z
new_rdsmysql.py
AdminTurnedDevOps/AWS_Solutions_Architect_Python
5389f8c9dfbda7b0b49a94a93e9b070420ca9ece
[ "MIT" ]
1
2019-01-13T23:52:39.000Z
2019-01-14T14:39:45.000Z
new_rdsmysql.py
AdminTurnedDevOps/AWS_Solutions_Architect_Python
5389f8c9dfbda7b0b49a94a93e9b070420ca9ece
[ "MIT" ]
26
2019-01-13T21:32:23.000Z
2022-03-20T05:19:03.000Z
import boto3 import sys import time import logging import getpass dbname = sys.argv[1] instanceID = sys.argv[2] storage = sys.argv[3] dbInstancetype = sys.argv[4] dbusername = sys.argv[5] new_rdsmysql(dbname, instanceID, storage, dbInstancetype, dbusername)
27.769231
83
0.587258
295527972ae5a65fd8aad67870244e225d07dc77
2,657
py
Python
src/tzscan/tzscan_block_api.py
Twente-Mining/tezos-reward-distributor
8df0745fdb44cbd765084303882545202d2427f3
[ "MIT" ]
null
null
null
src/tzscan/tzscan_block_api.py
Twente-Mining/tezos-reward-distributor
8df0745fdb44cbd765084303882545202d2427f3
[ "MIT" ]
null
null
null
src/tzscan/tzscan_block_api.py
Twente-Mining/tezos-reward-distributor
8df0745fdb44cbd765084303882545202d2427f3
[ "MIT" ]
null
null
null
import random import requests from api.block_api import BlockApi from exception.tzscan import TzScanException from log_config import main_logger logger = main_logger HEAD_API = {'MAINNET': {'HEAD_API_URL': 'https://api%MIRROR%.tzscan.io/v2/head'}, 'ALPHANET': {'HEAD_API_URL': 'http://api.alphanet.tzscan.io/v2/head'}, 'ZERONET': {'HEAD_API_URL': 'http://api.zeronet.tzscan.io/v2/head'} } REVELATION_API = {'MAINNET': {'HEAD_API_URL': 'https://api%MIRROR%.tzscan.io/v1/operations/%PKH%?type=Reveal'}, 'ALPHANET': {'HEAD_API_URL': 'https://api.alphanet.tzscan.io/v1/operations/%PKH%?type=Reveal'}, 'ZERONET': {'HEAD_API_URL': 'https://api.zeronet.tzscan.io/v1/operations/%PKH%?type=Reveal'} } if __name__ == '__main__': test_get_revelation()
32.402439
116
0.621377
29554b0b9e721e4b0e9ff426e2c29a4e943ecd1c
10,086
py
Python
python/cuxfilter/tests/charts/core/test_core_non_aggregate.py
Anhmike/cuxfilter
a8b25b1c37ac0e5435acb7261f6fcbf677d96bfa
[ "Apache-2.0" ]
201
2018-12-21T18:32:40.000Z
2022-03-22T11:50:29.000Z
python/cuxfilter/tests/charts/core/test_core_non_aggregate.py
Anhmike/cuxfilter
a8b25b1c37ac0e5435acb7261f6fcbf677d96bfa
[ "Apache-2.0" ]
258
2018-12-27T07:37:50.000Z
2022-03-31T20:01:32.000Z
python/cuxfilter/tests/charts/core/test_core_non_aggregate.py
Anhmike/cuxfilter
a8b25b1c37ac0e5435acb7261f6fcbf677d96bfa
[ "Apache-2.0" ]
51
2019-01-10T19:03:09.000Z
2022-03-08T01:37:11.000Z
import pytest import cudf import mock from cuxfilter.charts.core.non_aggregate.core_non_aggregate import ( BaseNonAggregate, ) from cuxfilter.dashboard import DashBoard from cuxfilter import DataFrame from cuxfilter.layouts import chart_view
30.288288
78
0.561967
29560939d9082f0d01fcc95be50270dfe0f453ac
4,265
py
Python
tunobase/tagging/migrations/0001_initial.py
unomena/tunobase-core
fd24e378c87407131805fa56ade8669fceec8dfa
[ "BSD-3-Clause" ]
null
null
null
tunobase/tagging/migrations/0001_initial.py
unomena/tunobase-core
fd24e378c87407131805fa56ade8669fceec8dfa
[ "BSD-3-Clause" ]
null
null
null
tunobase/tagging/migrations/0001_initial.py
unomena/tunobase-core
fd24e378c87407131805fa56ade8669fceec8dfa
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models
56.118421
182
0.597655
2959af169e729db8be7ba1725d5b1686b6c154d4
6,462
py
Python
b.py
lbarchive/b.py
18b533dc40e5fdf7ba62209b51584927c2dd9ba0
[ "MIT" ]
null
null
null
b.py
lbarchive/b.py
18b533dc40e5fdf7ba62209b51584927c2dd9ba0
[ "MIT" ]
null
null
null
b.py
lbarchive/b.py
18b533dc40e5fdf7ba62209b51584927c2dd9ba0
[ "MIT" ]
null
null
null
#!/usr/bin/env python # Copyright (C) 2013-2016 by Yu-Jie Lin # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """ ============ b.py command ============ Commands ======== ============= ======================= command supported services ============= ======================= ``blogs`` ``b`` ``post`` ``b``, ``wp`` ``generate`` ``base``, ``b``, ``wp`` ``checklink`` ``base``, ``b``, ``wp`` ``search`` ``b`` ============= ======================= Descriptions: ``blogs`` list blogs. This can be used for blog IDs lookup. ``post`` post or update a blog post. ``generate`` generate HTML file at ``<TEMP>/draft.html``, where ``<TEMP>`` is the system's temporary directory. The generation can output a preview html at ``<TEMP>/preview.html`` if there is ``tmpl.html``. It will replace ``%%Title%%`` with post title and ``%%Content%%`` with generated HTML. ``checklink`` check links in generated HTML using lnkckr_. ``search`` search blog .. _lnkckr: https://pypi.python.org/pypi/lnkckr """ from __future__ import print_function import argparse as ap import codecs import imp import logging import os import sys import traceback from bpy.handlers import handlers from bpy.services import find_service, services __program__ = 'b.py' __description__ = 'Post to Blogger or WordPress in markup language seamlessly' __copyright__ = 'Copyright 2013-2016, Yu Jie Lin' __license__ = 'MIT License' __version__ = '0.11.0' __website__ = 'http://bitbucket.org/livibetter/b.py' __author__ = 'Yu-Jie Lin' __author_email__ = 'livibetter@gmail.com' # b.py stuff ############ # filename of local configuration without '.py' suffix. BRC = 'brc' if __name__ == '__main__': main()
29.108108
79
0.660786
295a62c87a95c13de9ca2d600326020d699ab2e2
8,729
py
Python
spyder/plugins/outlineexplorer/api.py
suokunlong/spyder
2d5d450fdcef232fb7f38e7fefc27f0e7f704c9a
[ "MIT" ]
1
2018-05-03T02:14:15.000Z
2018-05-03T02:14:15.000Z
spyder/plugins/outlineexplorer/api.py
jastema/spyder
0ef48ea227c53f57556cd8002087dc404b0108b0
[ "MIT" ]
null
null
null
spyder/plugins/outlineexplorer/api.py
jastema/spyder
0ef48ea227c53f57556cd8002087dc404b0108b0
[ "MIT" ]
1
2020-03-05T03:09:11.000Z
2020-03-05T03:09:11.000Z
# -*- coding: utf-8 -*- # # Copyright Spyder Project Contributors # Licensed under the terms of the MIT License # (see spyder/__init__.py for details) """Outline explorer API. You need to declare a OutlineExplorerProxy, and a function for handle the edit_goto Signal. class OutlineExplorerProxyCustom(OutlineExplorerProxy): ... def handle_go_to(name, line, text): ... outlineexplorer = OutlineExplorerWidget(None) oe_proxy = OutlineExplorerProxyCustom(name) outlineexplorer.set_current_editor(oe_proxy, update=True, clear=False) outlineexplorer.edit_goto.connect(handle_go_to) """ import re from qtpy.QtCore import Signal, QObject from qtpy.QtGui import QTextBlock from spyder.config.base import _ from spyder.config.base import running_under_pytest def is_cell_header(block): """Check if the given block is a cell header.""" if not block.isValid(): return False data = block.userData() return (data and data.oedata and data.oedata.def_type == OutlineExplorerData.CELL) def cell_index(block): """Get the cell index of the given block.""" index = len(list(document_cells(block, forward=False))) if is_cell_header(block): return index + 1 return index def cell_name(block): """ Get the cell name the block is in. If the cell is unnamed, return the cell index instead. """ if is_cell_header(block): header = block.userData().oedata else: try: header = next(document_cells(block, forward=False)) except StopIteration: # This cell has no header, so it is the first cell. return 0 if header.has_name(): return header.def_name else: # No name, return the index return cell_index(block) def is_valid(self): """Check if the oedata has a valid block attached.""" block = self.block return (block and block.isValid() and block.userData() and hasattr(block.userData(), 'oedata') and block.userData().oedata == self ) def has_name(self): """Check if cell has a name.""" if self._def_name: return True else: return False def get_block_number(self): """Get the block number.""" if not self.is_valid(): # Avoid calling blockNumber if not a valid block return None return self.block.blockNumber()
29.096667
74
0.595601
295bcd4e3374d50cf1562ad240b9c1e9e4ac0fc7
3,132
py
Python
seamless/core/__init__.py
sjdv1982/seamless
1b814341e74a56333c163f10e6f6ceab508b7df9
[ "MIT" ]
15
2017-06-07T12:49:12.000Z
2020-07-25T18:06:04.000Z
seamless/core/__init__.py
sjdv1982/seamless
1b814341e74a56333c163f10e6f6ceab508b7df9
[ "MIT" ]
110
2016-06-21T23:20:44.000Z
2022-02-24T16:15:22.000Z
seamless/core/__init__.py
sjdv1982/seamless
1b814341e74a56333c163f10e6f6ceab508b7df9
[ "MIT" ]
6
2016-06-21T11:19:22.000Z
2019-01-21T13:45:39.000Z
import weakref from .mount import mountmanager from .macro_mode import get_macro_mode, macro_mode_on from . import cell as cell_module from .cell import Cell, cell from . import context as context_module from .context import Context, context from .worker import Worker from .transformer import Transformer, transformer from .structured_cell import StructuredCell, Inchannel, Outchannel from .macro import Macro, macro, path from .reactor import Reactor, reactor from .unilink import unilink
30.705882
102
0.628672
295bf91559d8557674834d5e4100c334bcac0923
11,613
py
Python
oguilem/configuration/config.py
dewberryants/oGUIlem
28271fdc0fb6ffba0037f30f9f9858bec32b0d13
[ "BSD-3-Clause" ]
2
2022-02-23T13:16:47.000Z
2022-03-07T09:47:29.000Z
oguilem/configuration/config.py
dewberryants/oGUIlem
28271fdc0fb6ffba0037f30f9f9858bec32b0d13
[ "BSD-3-Clause" ]
null
null
null
oguilem/configuration/config.py
dewberryants/oGUIlem
28271fdc0fb6ffba0037f30f9f9858bec32b0d13
[ "BSD-3-Clause" ]
1
2022-02-23T13:16:49.000Z
2022-02-23T13:16:49.000Z
import os import re import sys from oguilem.configuration.fitness import OGUILEMFitnessFunctionConfiguration from oguilem.configuration.ga import OGUILEMGlobOptConfig from oguilem.configuration.geometry import OGUILEMGeometryConfig from oguilem.configuration.utils import ConnectedValue, ConfigFileManager from oguilem.resources import options
43.494382
118
0.533023
295cb6523225a5b823029ec4f2d16b55a8369739
8,705
py
Python
xpd_workflow/temp_graph.py
CJ-Wright/xpd_workflow
f3fd84831b86b696631759946c3af9b16b45de26
[ "BSD-3-Clause" ]
null
null
null
xpd_workflow/temp_graph.py
CJ-Wright/xpd_workflow
f3fd84831b86b696631759946c3af9b16b45de26
[ "BSD-3-Clause" ]
4
2016-08-25T02:59:05.000Z
2016-09-28T22:32:34.000Z
xpd_workflow/temp_graph.py
CJ-Wright/xpd_workflow
f3fd84831b86b696631759946c3af9b16b45de26
[ "BSD-3-Clause" ]
null
null
null
from __future__ import (division, print_function) import matplotlib.cm as cmx import matplotlib.colors as colors from matplotlib import gridspec from metadatastore.api import db_connect as mds_db_connect from filestore.api import db_connect as fs_db_connect fs_db_connect( **{'database': 'data-processing-dev', 'host': 'localhost', 'port': 27017}) mds_db_connect( **{'database': 'data-processing-dev', 'host': 'localhost', 'port': 27017}) from databroker import db, get_events from datamuxer import DataMuxer from sidewinder_spec.utils.handlers import * import logging from xpd_workflow.parsers import parse_xrd_standard logger = logging.getLogger(__name__) if __name__ == '__main__': import os import numpy as np import matplotlib.pyplot as plt save = True lam = 1.54059 # Standard reflections for sample components niox_hkl = ['111', '200', '220', '311', '222', '400', '331', '420', '422', '511'] niox_tth = np.asarray( [37.44, 43.47, 63.20, 75.37, 79.87, 95.58, 106.72, 111.84, 129.98, 148.68]) pr3_hkl = ['100', '001', '110', '101', '111', '200', '002', '210', '211', '112', '202'] pr3_tth = np.asarray( [22.96, 24.33, 32.70, 33.70, 41.18, 46.92, 49.86, 52.86, 59.00, 60.91, 70.87] ) pr4_hkl = ['111', '113', '008', '117', '200', '119', '028', '0014', '220', '131', '1115', '0214', '317', '31Na', '2214', '040', '400'] pr4_tth = np.asarray( [23.43, 25.16, 25.86, 32.62, 33.36, 37.67, 42.19, 46.11, 47.44, 53.18, 55.55, 57.72, 59.10, 59.27, 68.25, 68.71, 70.00] ) pr2_tth, pr2int, pr2_hkl = parse_xrd_standard( '/mnt/bulk-data/research_data/Pr2NiO4orthorhombicPDF#97-008-1577.txt') pr2_tth = pr2_tth[pr2int > 5.] prox_hkl = ['111', '200', '220', '311', '222', '400', '331', '420', '422', '511', '440', '531', '600'] prox_tth = np.asarray( [28.25, 32.74, 46.99, 55.71, 58.43, 68.59, 75.73, 78.08, 87.27, 94.12, 105.63, 112.90, 115.42] ) standard_names = [ # 'NiO', 'Pr3Ni2O7', 'Pr2NiO4', # 'Pr4' 'Pr6O11' ] master_hkl = [ # niox_hkl, pr3_hkl, pr2_hkl, # pr4_hkl prox_hkl ] master_tth = [ # niox_tth, pr3_tth, pr2_tth, # pr4_tth prox_tth ] color_map = [ # 'red', 'blue', 'black', 'red' ] line_style = ['--', '-.', ':', ] ns = [1, 2, 3, 4, 5, # 18, 20, 22, 16, 28, 29, 27, 26 ] # ns = [26] ns.sort() # for i in ns: legended_hkl = [] print(i) folder = '/mnt/bulk-data/research_data/USC_beamtime/APS_March_2016/S' + str( i) + '/temp_exp' hdr = db(run_folder=folder)[0] dm = DataMuxer() dm.append_events(get_events(hdr)) df = dm.to_sparse_dataframe() print(df.keys()) binned = dm.bin_on('img', interpolation={'T': 'linear'}) # key_list = [f for f in os.listdir(folder) if # f.endswith('.gr') and not f.startswith('d')] key_list = [f for f in os.listdir(folder) if f.endswith('.chi') and not f.startswith('d') and f.strip( '0.chi') != '' and int( f.lstrip('0').strip('.chi')) % 2 == 1] key_list.sort() key_list = key_list[:-1] # key_list2.sort() idxs = [int(os.path.splitext(f)[0]) for f in key_list] Ts = binned['T'].values[idxs] output = os.path.splitext(key_list[0])[-1][1:] if key_list[0].endswith('.gr'): offset = .1 skr = 0 else: skr = 8 offset = .001 data_list = [(np.loadtxt(os.path.join(folder, f), skiprows=skr )[:, 0], np.loadtxt(os.path.join(folder, f), skiprows=skr )[:, 1]) for f in key_list] ylim_min = None for xmax, length in zip( [len(data_list[0][0]) - 1, len(data_list[0][0]) - 1], ['short', 'full']): fig = plt.figure(figsize=(26, 12)) gs = gridspec.GridSpec(1, 2, width_ratios=[5, 1]) ax1 = plt.subplot(gs[0]) if length == 'short': ax1.set_xlim(1.5, 4.5) ax2 = plt.subplot(gs[1], sharey=ax1) plt.setp(ax2.get_yticklabels(), visible=False) cm = plt.get_cmap('viridis') cNorm = colors.Normalize(vmin=0, vmax=len(key_list)) scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cm) for idx in range(len(key_list)): xnm, y = data_list[idx] colorVal = scalarMap.to_rgba(idx) if output == 'chi': x = xnm / 10. ax1.plot(x[:xmax], y[:xmax] + idx * offset, color=colorVal) ax2.plot(Ts[idx], y[-1] + idx * offset, marker='o', color=colorVal) if ylim_min is None or ylim_min > np.min( y[:xmax + idx * offset]): ylim_min = np.min(y[:xmax + idx * offset]) ax2.set_xticklabels([str(f) for f in ax2.get_xticks()], rotation=90) if output == 'gr': bnds = ['O-Pr', 'O-Ni', 'Ni-Ni', 'Pr-Pr', 'Ni-Pr', 'O-Pr', 'O-Ni', 'Ni-Ni-Ni', 'Pr-Ni', 'Pr-Pr', 'Pr-Ni-O', 'Ni-Pr-Ni', 'Pr-Pr', 'Rs:Pr-Pr', 'Rs:Pr_Pr'] bnd_lens = [2.320, 1.955, 3.883, 3.765, 3.186, 2.771, 2.231, 7.767, 4.426, 6.649, 4.989, 5.404, 3.374, 3.910, 8.801] # ax1.grid(True) # ax2.grid(True) for bnd, bnd_len in zip(bnds, bnd_lens): ax1.axvline(bnd_len, color='grey', linestyle='--') ax3 = ax1.twiny() ax3.set_xticks(np.asarray(bnd_lens) / x[xmax]) ax3.set_xticklabels(bnds, rotation=90) else: std_axis = [] for n, hkls, tths, color, ls in zip(standard_names, master_hkl, master_tth, color_map, line_style): std_axis.append(ax1.twiny()) ax3 = std_axis[-1] hkl_q = np.pi * 4 * np.sin(np.deg2rad(tths / 2)) / lam for k, (hkl, q) in enumerate(zip(hkls, hkl_q)): if n not in legended_hkl: ax1.axvline(q, color=color, linestyle=ls, lw=2, label=n ) legended_hkl.append(n) else: ax1.axvline(q, color=color, linestyle=ls, lw=2, ) a = hkl_q > ax1.get_xlim()[0] b = hkl_q < ax1.get_xlim()[1] c = a & b ax3.set_xticks(list((hkl_q[c] - ax1.get_xlim()[0]) / ( ax1.get_xlim()[1] - ax1.get_xlim()[0]) )) ax3.set_xticklabels(hkls, rotation=90, color=color) ax2.set_xlabel('Temperature C') if output == 'gr': fig.suptitle('S{} PDF'.format(i)) ax1.set_xlabel(r"$r (\AA)$") ax1.set_ylabel(r"$G (\AA^{-2})$") elif output == 'chi': fig.suptitle('S{} I(Q)'.format(i)) ax1.set_xlabel(r"$Q (\AA^{-1})$") ax1.set_ylabel(r"$I (Q) $") ax1.set_ylim(ylim_min) ax1.legend() gs.tight_layout(fig, rect=[0, 0, 1, .98], w_pad=1e-6) if save: fig.savefig(os.path.join('/mnt/bulk-data/Dropbox/', 'S{}_{}_output_{}.png'.format( i, length, output))) fig.savefig(os.path.join('/mnt/bulk-data/Dropbox/', 'S{}_{}_output_{}.eps'.format( i, length, output))) else: plt.show()
38.688889
84
0.443538
295d0342f32753f768fc55a488c38b501e122b06
12,101
py
Python
winnow/core.py
bgschiller/winnow
0fde7fcc9e2fe3519528feb9115658aa3b3954e5
[ "MIT" ]
3
2017-08-10T16:20:29.000Z
2018-09-19T01:33:13.000Z
winnow/core.py
bgschiller/winnow
0fde7fcc9e2fe3519528feb9115658aa3b3954e5
[ "MIT" ]
null
null
null
winnow/core.py
bgschiller/winnow
0fde7fcc9e2fe3519528feb9115658aa3b3954e5
[ "MIT" ]
1
2019-11-29T20:17:23.000Z
2019-11-29T20:17:23.000Z
from __future__ import unicode_literals import copy import json from six import string_types from . import default_operators from . import sql_prepare from . import values from .error import WinnowError from .templating import SqlFragment from .templating import WinnowSql
37.934169
122
0.614081
295d64816bed48df8774a68b70c332508540215b
12,525
py
Python
ibis/bigquery/client.py
tswast/ibis
2f6d47e4c33cefd7ea1d679bb1d9253c2245993b
[ "Apache-2.0" ]
null
null
null
ibis/bigquery/client.py
tswast/ibis
2f6d47e4c33cefd7ea1d679bb1d9253c2245993b
[ "Apache-2.0" ]
null
null
null
ibis/bigquery/client.py
tswast/ibis
2f6d47e4c33cefd7ea1d679bb1d9253c2245993b
[ "Apache-2.0" ]
null
null
null
import regex as re import time import collections import datetime import six import pandas as pd import google.cloud.bigquery as bq from multipledispatch import Dispatcher import ibis import ibis.common as com import ibis.expr.operations as ops import ibis.expr.types as ir import ibis.expr.schema as sch import ibis.expr.datatypes as dt import ibis.expr.lineage as lin from ibis.compat import parse_version from ibis.client import Database, Query, SQLClient from ibis.bigquery import compiler as comp from google.api.core.exceptions import BadRequest NATIVE_PARTITION_COL = '_PARTITIONTIME' _IBIS_TYPE_TO_DTYPE = { 'string': 'STRING', 'int64': 'INT64', 'double': 'FLOAT64', 'boolean': 'BOOL', 'timestamp': 'TIMESTAMP', 'date': 'DATE', } _DTYPE_TO_IBIS_TYPE = { 'INT64': dt.int64, 'FLOAT64': dt.double, 'BOOL': dt.boolean, 'STRING': dt.string, 'DATE': dt.date, # FIXME: enforce no tz info 'DATETIME': dt.timestamp, 'TIME': dt.time, 'TIMESTAMP': dt.timestamp, 'BYTES': dt.binary, } _LEGACY_TO_STANDARD = { 'INTEGER': 'INT64', 'FLOAT': 'FLOAT64', 'BOOLEAN': 'BOOL', } class BigQueryCursor(object): """Cursor to allow the BigQuery client to reuse machinery in ibis/client.py """ def _find_scalar_parameter(expr): """:func:`~ibis.expr.lineage.traverse` function to find all :class:`~ibis.expr.types.ScalarParameter` instances and yield the operation and the parent expresssion's resolved name. Parameters ---------- expr : ibis.expr.types.Expr Returns ------- Tuple[bool, object] """ op = expr.op() if isinstance(op, ops.ScalarParameter): result = op, expr.get_name() else: result = None return lin.proceed, result class BigQueryQuery(Query): class BigQueryAPIProxy(object): def get_datasets(self): return list(self.client.list_datasets()) def get_dataset(self, dataset_id): return self.client.dataset(dataset_id) def get_table(self, table_id, dataset_id, reload=True): (table_id, dataset_id) = _ensure_split(table_id, dataset_id) table = self.client.dataset(dataset_id).table(table_id) if reload: table.reload() return table def get_schema(self, table_id, dataset_id): return self.get_table(table_id, dataset_id).schema def run_sync_query(self, stmt): query = self.client.run_sync_query(stmt) query.use_legacy_sql = False query.run() # run_sync_query is not really synchronous: there's a timeout while not query.job.done(): query.job.reload() time.sleep(0.1) return query class BigQueryDatabase(Database): pass bigquery_param = Dispatcher('bigquery_param') class BigQueryClient(SQLClient): sync_query = BigQueryQuery database_class = BigQueryDatabase proxy_class = BigQueryAPIProxy dialect = comp.BigQueryDialect def table(self, *args, **kwargs): t = super(BigQueryClient, self).table(*args, **kwargs) if NATIVE_PARTITION_COL in t.columns: col = ibis.options.bigquery.partition_col assert col not in t return (t .mutate(**{col: t[NATIVE_PARTITION_COL]}) .drop([NATIVE_PARTITION_COL])) return t def _build_ast(self, expr, context): result = comp.build_ast(expr, context) return result def _execute_query(self, dml, async=False): klass = self.async_query if async else self.sync_query inst = klass(self, dml, query_parameters=dml.context.params) df = inst.execute() return df def _fully_qualified_name(self, name, database): dataset_id = database or self.dataset_id return dataset_id + '.' + name def _get_table_schema(self, qualified_name): return self.get_schema(qualified_name) def _execute(self, stmt, results=True, query_parameters=None): # TODO(phillipc): Allow **kwargs in calls to execute query = self._proxy.client.run_sync_query(stmt) query.use_legacy_sql = False query.query_parameters = query_parameters or [] query.run() # run_sync_query is not really synchronous: there's a timeout while not query.job.done(): query.job.reload() time.sleep(0.1) return BigQueryCursor(query) def database(self, name=None): if name is None: name = self.dataset_id return self.database_class(name, self) _DTYPE_TO_IBIS_TYPE = { 'INT64': dt.int64, 'FLOAT64': dt.double, 'BOOL': dt.boolean, 'STRING': dt.string, 'DATE': dt.date, # FIXME: enforce no tz info 'DATETIME': dt.timestamp, 'TIME': dt.time, 'TIMESTAMP': dt.timestamp, 'BYTES': dt.binary, } _LEGACY_TO_STANDARD = { 'INTEGER': 'INT64', 'FLOAT': 'FLOAT64', 'BOOLEAN': 'BOOL', }
28.020134
79
0.660918
295d6dddae668ee8a211bf176e96dec0fc246700
1,583
py
Python
5 kyu/Family Tree Ancestors.py
mwk0408/codewars_solutions
9b4f502b5f159e68024d494e19a96a226acad5e5
[ "MIT" ]
6
2020-09-03T09:32:25.000Z
2020-12-07T04:10:01.000Z
5 kyu/Family Tree Ancestors.py
mwk0408/codewars_solutions
9b4f502b5f159e68024d494e19a96a226acad5e5
[ "MIT" ]
1
2021-12-13T15:30:21.000Z
2021-12-13T15:30:21.000Z
5 kyu/Family Tree Ancestors.py
mwk0408/codewars_solutions
9b4f502b5f159e68024d494e19a96a226acad5e5
[ "MIT" ]
null
null
null
from math import log, ceil
32.979167
139
0.53885
295da24723071b30363f5dee9937e755f296d5c6
690
py
Python
tests/make_expected_lookup.py
bfis/coffea
e5e67d410e86faee1172fcc864774d7024d97653
[ "BSD-3-Clause" ]
77
2019-06-09T14:23:33.000Z
2022-03-22T21:34:01.000Z
tests/make_expected_lookup.py
bfis/coffea
e5e67d410e86faee1172fcc864774d7024d97653
[ "BSD-3-Clause" ]
353
2019-06-05T23:54:39.000Z
2022-03-31T21:21:47.000Z
tests/make_expected_lookup.py
bfis/coffea
e5e67d410e86faee1172fcc864774d7024d97653
[ "BSD-3-Clause" ]
71
2019-06-07T02:04:11.000Z
2022-03-05T21:03:45.000Z
import numpy as np import ROOT from dummy_distributions import dummy_pt_eta counts, test_in1, test_in2 = dummy_pt_eta() f = ROOT.TFile.Open("samples/testSF2d.root") sf = f.Get("scalefactors_Tight_Electron") xmin, xmax = sf.GetXaxis().GetXmin(), sf.GetXaxis().GetXmax() ymin, ymax = sf.GetYaxis().GetXmin(), sf.GetYaxis().GetXmax() test_out = np.empty_like(test_in1) for i, (eta, pt) in enumerate(zip(test_in1, test_in2)): if xmax <= eta: eta = xmax - 1.0e-5 elif eta < xmin: eta = xmin if ymax <= pt: pt = ymax - 1.0e-5 elif pt < ymin: pt = ymin ib = sf.FindBin(eta, pt) test_out[i] = sf.GetBinContent(ib) print(repr(test_out))
24.642857
61
0.649275
295e24a9ef2f154bf2eab43ba3f883adfaf8378d
5,755
py
Python
engine/sentiment_analysis.py
zgeorg03/nesase
4dae70994cd0c730a88b4a54e6b8e29868aafb09
[ "BSD-3-Clause" ]
2
2020-12-30T18:03:01.000Z
2021-08-08T21:05:43.000Z
engine/sentiment_analysis.py
zgeorg03/nesase
4dae70994cd0c730a88b4a54e6b8e29868aafb09
[ "BSD-3-Clause" ]
null
null
null
engine/sentiment_analysis.py
zgeorg03/nesase
4dae70994cd0c730a88b4a54e6b8e29868aafb09
[ "BSD-3-Clause" ]
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 14 17:42:27 2018 @author: zgeorg03 """ import re import json # Used for converting json to dictionary import datetime # Used for date conversions import matplotlib.pyplot as plt import numpy as np from sentiment import Sentiment import json if __name__ == '__main__': file_name = "./log" #max_articles = 1000 p = Parser(file_name,file_out='data-26-04.json') p.parse() p.write() print('Finished')
31.277174
137
0.559687
295e89c3127cdc64f86ba1f4504dbc0c0e95c2df
1,214
py
Python
ch05/recursion.py
laszlokiraly/LearningAlgorithms
032a3cc409546619cf41220821d081cde54bbcce
[ "MIT" ]
74
2021-05-06T22:03:18.000Z
2022-03-25T04:37:51.000Z
ch05/recursion.py
laszlokiraly/LearningAlgorithms
032a3cc409546619cf41220821d081cde54bbcce
[ "MIT" ]
null
null
null
ch05/recursion.py
laszlokiraly/LearningAlgorithms
032a3cc409546619cf41220821d081cde54bbcce
[ "MIT" ]
19
2021-07-16T11:42:00.000Z
2022-03-22T00:25:49.000Z
"""Recursive implementations.""" def find_max(A): """invoke recursive function to find maximum value in A.""" def rmax(lo, hi): """Use recursion to find maximum value in A[lo:hi+1].""" if lo == hi: return A[lo] mid = (lo+hi) // 2 L = rmax(lo, mid) R = rmax(mid+1, hi) return max(L, R) return rmax(0, len(A)-1) def find_max_with_count(A): """Count number of comparisons.""" def frmax(lo, hi): """Use recursion to find maximum value in A[lo:hi+1] incl. count""" if lo == hi: return (0, A[lo]) mid = (lo+hi)//2 ctleft,left = frmax(lo, mid) ctright,right = frmax(mid+1, hi) return (1+ctleft+ctright, max(left, right)) return frmax(0, len(A)-1) def count(A,target): """invoke recursive function to return number of times target appears in A.""" def rcount(lo, hi, target): """Use recursion to find maximum value in A[lo:hi+1].""" if lo == hi: return 1 if A[lo] == target else 0 mid = (lo+hi)//2 left = rcount(lo, mid, target) right = rcount(mid+1, hi, target) return left + right return rcount(0, len(A)-1, target)
26.977778
82
0.555189
295eeef6c40b7545564ffef7ae9d385146c2bde6
3,084
py
Python
setup.py
koonimaru/DeepGMAP
7daac354229fc25fba81649b741921345dc5db05
[ "Apache-2.0" ]
11
2018-06-27T11:45:47.000Z
2021-07-01T15:32:56.000Z
setup.py
koonimaru/DeepGMAP
7daac354229fc25fba81649b741921345dc5db05
[ "Apache-2.0" ]
3
2020-01-28T21:45:15.000Z
2020-04-20T02:40:48.000Z
setup.py
koonimaru/DeepGMAP
7daac354229fc25fba81649b741921345dc5db05
[ "Apache-2.0" ]
1
2018-10-19T19:43:27.000Z
2018-10-19T19:43:27.000Z
#from distutils.core import setup from setuptools import setup, find_packages from distutils.extension import Extension import re import os import codecs here = os.path.abspath(os.path.dirname(__file__)) try: from Cython.Distutils import build_ext except ImportError: use_cython = False else: use_cython = True cmdclass = { } ext_modules = [ ] if use_cython: ext_modules += [ Extension("deepgmap.data_preprocessing_tools.seq_to_binary2", [ "deepgmap/data_preprocessing_tools/seq_to_binary2.pyx" ]), #Extension("data_preprocessing_tools.queue", [ "deepgmap/data_preprocessing_tools/queue.pyx" ],libraries=["calg"]), Extension("deepgmap.post_train_tools.cython_util", [ "deepgmap/post_train_tools/cython_util.pyx" ]), ] cmdclass.update({ 'build_ext': build_ext }) else: ext_modules += [ Extension("deepgmap.data_preprocessing_tools.seq_to_binary2", [ "deepgmap/data_preprocessing_tools/seq_to_binary2.c" ]), Extension("deepgmap.post_train_tools.cython_util", [ "deepgmap/post_train_tools/cython_util.c" ]), ] #print(find_version("deepgmap", "__init__.py")) setup( name='DeepGMAP', #version=VERSION, version=find_version("deepgmap", "__init__.py"), description='Learning and predicting gene regulatory sequences in genomes', author='Koh Onimaru', author_email='koh.onimaru@gmail.com', url='', packages=['deepgmap','deepgmap.train','deepgmap.network_constructors','deepgmap.post_train_tools','deepgmap.data_preprocessing_tools','deepgmap.misc'], #packages=find_packages('deepgmap'), #packages=['deepgmap.'], package_dir={'DeepGMAP':'deepgmap'}, #package_data = { # '': ['enhancer_prediction/*', '*.pyx', '*.pxd', '*.c', '*.h'], #}, scripts=['bin/deepgmap', ], #packages=find_packages(), cmdclass = cmdclass, ext_modules=ext_modules, classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: Developers', 'Programming Language :: Python :: 3.6', 'License :: OSI Approved :: Apache Software License ', 'Operating System :: POSIX :: Linux', 'Topic :: Scientific/Engineering :: Bio-Informatics', 'Topic :: Scientific/Engineering :: Artificial Intelligence', ], install_requires=['tensorflow>=1.15', 'numpy', 'matplotlib', 'sklearn', 'tornado', 'natsort', 'psutil', 'pyBigWig'], long_description=open('README.rst').read(), )
34.651685
155
0.664073
295f637700f993cfd8e37b0ff39f106d2c2a6469
1,716
py
Python
{{cookiecutter.project_slug}}/api/__init__.py
Steamboat/cookiecutter-devops
6f07329c9e54b76e671a0308d343d2d9ebff5343
[ "BSD-3-Clause" ]
null
null
null
{{cookiecutter.project_slug}}/api/__init__.py
Steamboat/cookiecutter-devops
6f07329c9e54b76e671a0308d343d2d9ebff5343
[ "BSD-3-Clause" ]
null
null
null
{{cookiecutter.project_slug}}/api/__init__.py
Steamboat/cookiecutter-devops
6f07329c9e54b76e671a0308d343d2d9ebff5343
[ "BSD-3-Clause" ]
null
null
null
import logging from flask import Flask from flask_sqlalchemy import SQLAlchemy as _BaseSQLAlchemy from flask_migrate import Migrate from flask_cors import CORS from flask_talisman import Talisman from flask_ipban import IpBan from config import Config, get_logger_handler # database db = SQLAlchemy() migrate = Migrate() cors = CORS() talisman = Talisman() global_config = Config() ip_ban = IpBan(ban_seconds=200, ban_count=global_config.IP_BAN_LIST_COUNT) # logging logger = logging.getLogger('frontend') from api import models
32.377358
106
0.740093
295f7531aae2696a47947cc69a933b6673909fb5
4,937
py
Python
weibospider/pipelines.py
czyczyyzc/WeiboSpider
41b9c97cb01d41cb4a62efdd452451b5ef25bdbc
[ "MIT" ]
2
2021-03-26T03:02:52.000Z
2021-04-01T11:08:46.000Z
weibospider/pipelines.py
czyczyyzc/WeiboSpider
41b9c97cb01d41cb4a62efdd452451b5ef25bdbc
[ "MIT" ]
null
null
null
weibospider/pipelines.py
czyczyyzc/WeiboSpider
41b9c97cb01d41cb4a62efdd452451b5ef25bdbc
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- import os import csv import pymongo from pymongo.errors import DuplicateKeyError from settings import MONGO_HOST, MONGO_PORT, SAVE_ROOT
40.467213
118
0.611302
295f767e353179afb030c3f6f2c390f8073634e9
6,020
py
Python
tests/test_gc3_config.py
ericmharris/gc3-query
0bf5226130aafbb1974aeb96d93ee1996833e87d
[ "MIT" ]
null
null
null
tests/test_gc3_config.py
ericmharris/gc3-query
0bf5226130aafbb1974aeb96d93ee1996833e87d
[ "MIT" ]
null
null
null
tests/test_gc3_config.py
ericmharris/gc3-query
0bf5226130aafbb1974aeb96d93ee1996833e87d
[ "MIT" ]
null
null
null
from pathlib import Path from requests.auth import _basic_auth_str import pytest from bravado_core.formatter import SwaggerFormat, NO_OP from gc3_query.lib.gc3_config import GC3Config, IDMCredential TEST_BASE_DIR: Path = Path(__file__).parent.joinpath("GC3Config") config_dir = TEST_BASE_DIR.joinpath("config") # @pytest.fixture() # def get_bravado_config_setup(): # gc3_config = GC3Config() # assert 'iaas_classic' in gc3_config # yield (gc3_config) # # def test_bravado_client_config(get_bravado_config_setup): # gc3_config = get_bravado_config_setup # assert 'iaas_classic' in gc3_config # bravado_client_config = gc3_config.bravado_client_config # assert bravado_client_config # assert 'formats' not in bravado_client_config # assert not 'include_missing_properties' in bravado_client_config # assert 'also_return_response' in bravado_client_config # bravado_client_config_2 = gc3_config.bravado_client_config # assert bravado_client_config==bravado_client_config_2 # assert bravado_client_config is not bravado_client_config_2 # assert isinstance(bravado_client_config, dict) # # def test_bravado_core_config(get_bravado_config_setup): # gc3_config = get_bravado_config_setup # assert 'iaas_classic' in gc3_config # bravado_core_config = gc3_config.bravado_core_config # assert bravado_core_config # assert 'formats' in bravado_core_config # assert 'include_missing_properties' in bravado_core_config # assert not 'also_return_response' in bravado_core_config # bravado_core_config_2 = gc3_config.bravado_core_config # assert bravado_core_config==bravado_core_config_2 # assert bravado_core_config is not bravado_core_config_2 # assert isinstance(bravado_core_config, dict) # assert isinstance(bravado_core_config['formats'], list) # # # # def test_bravado_config(get_bravado_config_setup): # gc3_config = get_bravado_config_setup # assert 'iaas_classic' in gc3_config # bravado_config = gc3_config.bravado_config # assert bravado_config # assert 'formats' in bravado_config # assert 'include_missing_properties' in bravado_config # assert 'also_return_response' in bravado_config # bravado_config_2 = gc3_config.bravado_config # assert bravado_config==bravado_config_2 # assert bravado_config is not bravado_config_2 # assert isinstance(bravado_config, dict) # assert isinstance(bravado_config['formats'], list) # # def test_BRAVADO_CONFIG(get_constants_setup): # gc3_config = get_constants_setup # bravado_config = gc3_config.BRAVADO_CONFIG # assert bravado_config # assert 'formats' in bravado_config # assert 'include_missing_properties' in bravado_config # assert 'also_return_response' in bravado_config # assert isinstance(bravado_config, dict) # assert isinstance(bravado_config['formats'], list) # assert bravado_config['formats'] # formats = [f.format for f in bravado_config['formats']] # assert 'json-bool' in formats # assert all([isinstance(i , SwaggerFormat) for i in bravado_config['formats']])
39.605263
96
0.767608
2960cfa3589dae062b2a5ee5a75ad678bb175e9d
2,871
py
Python
lab6/server/datapredict.py
zhiji95/iot
4202f00a79b429d5f5083bca6e914fcff09df294
[ "Apache-2.0" ]
2
2019-09-20T01:38:40.000Z
2020-10-13T21:18:18.000Z
lab6/server/datapredict.py
zw2497/4764
28caec1947c1b1479d2ec9c8ecba8cd599d66d23
[ "Apache-2.0" ]
null
null
null
lab6/server/datapredict.py
zw2497/4764
28caec1947c1b1479d2ec9c8ecba8cd599d66d23
[ "Apache-2.0" ]
null
null
null
import machine from machine import * import ssd1306 import time import socket import urequests as requests import json word = {'body':8} labels = ['c', 'o', 'l', 'u', 'm', 'b', 'i', 'a','null'] HOST = '18.218.158.249' PORT = 8080 flag = 0 stop = False data = {} xdata = [] ydata = [] n = 0 do_connect() switchA = machine.Pin(0, machine.Pin.IN, machine.Pin.PULL_UP) switchA.irq(trigger=machine.Pin.IRQ_RISING, handler=switchAcallback) switchC = machine.Pin(2, machine.Pin.IN, machine.Pin.PULL_UP) switchC.irq(trigger=machine.Pin.IRQ_RISING, handler=switchCcallback) spi = machine.SPI(1, baudrate=2000000, polarity=1, phase=1) cs = machine.Pin(15, machine.Pin.OUT) cs.value(0) spi.write(b'\x2d') spi.write(b'\x2b') cs.value(1) cs.value(0) spi.write(b'\x31') spi.write(b'\x0f') cs.value(1) i2c = machine.I2C(-1, machine.Pin(5), machine.Pin(4)) oled = ssd1306.SSD1306_I2C(128, 32, i2c) while True: x = 0 y = 0 sendstatus = "null" if (flag): cs.value(0) test1 = spi.read(5, 0xf2) cs.value(1) cs.value(0) test2 = spi.read(5, 0xf3) cs.value(1) cs.value(0) test3 = spi.read(5, 0xf4) cs.value(1) cs.value(0) test4 = spi.read(5, 0xf5) cs.value(1) x = dp(test2[1]) y = dp(test4[1]) xdata.append(x) ydata.append(y) sendstatus = "collect" + str(len(xdata)) + ' '+ ' ' + str(x) + ' ' + str(y) if send: word = sendData() sendstatus = "send success" flag = 0 send = False oled.fill(0) oled.text(labels[word['body']], 0, 0) oled.text(sendstatus, 0,10) oled.show()
20.804348
83
0.554859
2960f549fc004cf3590c25e915c7395ebd3b5e4d
79
py
Python
Geometry/VeryForwardGeometry/python/dd4hep/geometryRPFromDD_2021_cfi.py
PKUfudawei/cmssw
8fbb5ce74398269c8a32956d7c7943766770c093
[ "Apache-2.0" ]
2
2020-10-26T18:40:32.000Z
2021-04-10T16:33:25.000Z
Geometry/VeryForwardGeometry/python/dd4hep/geometryRPFromDD_2021_cfi.py
gartung/cmssw
3072dde3ce94dcd1791d778988198a44cde02162
[ "Apache-2.0" ]
25
2016-06-24T20:55:32.000Z
2022-02-01T19:24:45.000Z
Geometry/VeryForwardGeometry/python/dd4hep/geometryRPFromDD_2021_cfi.py
gartung/cmssw
3072dde3ce94dcd1791d778988198a44cde02162
[ "Apache-2.0" ]
8
2016-03-25T07:17:43.000Z
2021-07-08T17:11:21.000Z
from Geometry.VeryForwardGeometry.dd4hep.v5.geometryRPFromDD_2021_cfi import *
39.5
78
0.886076
2962e10ff2cdb13a6dd7a8ef80474fffa61365b3
1,464
py
Python
examples/plots/warmup_schedule.py
shuoyangd/pytorch_warmup
b3557afa6fcfc04e9ddc6ff08a1ae51e8a0ce5df
[ "MIT" ]
170
2019-11-03T06:14:42.000Z
2022-03-18T08:21:44.000Z
examples/plots/warmup_schedule.py
shuoyangd/pytorch_warmup
b3557afa6fcfc04e9ddc6ff08a1ae51e8a0ce5df
[ "MIT" ]
5
2020-05-18T16:53:33.000Z
2021-11-12T13:03:14.000Z
examples/plots/warmup_schedule.py
shuoyangd/pytorch_warmup
b3557afa6fcfc04e9ddc6ff08a1ae51e8a0ce5df
[ "MIT" ]
21
2019-11-06T10:55:21.000Z
2022-02-23T21:38:12.000Z
import argparse import matplotlib.pyplot as plt import torch from pytorch_warmup import * parser = argparse.ArgumentParser(description='Warmup schedule') parser.add_argument('--output', type=str, default='none', choices=['none', 'png', 'pdf'], help='Output file type (default: none)') args = parser.parse_args() beta2 = 0.999 max_step = 3000 plt.plot(range(1, max_step+1), get_rates(RAdamWarmup, beta2, max_step), label='RAdam') plt.plot(range(1, max_step+1), get_rates(UntunedExponentialWarmup, beta2, max_step), label='Untuned Exponential') plt.plot(range(1, max_step+1), get_rates(UntunedLinearWarmup, beta2, max_step), label='Untuned Linear') plt.legend() plt.title('Warmup Schedule') plt.xlabel('Iteration') plt.ylabel(r'Warmup factor $(\omega_t)$') if args.output == 'none': plt.show() else: plt.savefig(f'warmup_schedule.{args.output}')
34.857143
113
0.693306
2965377859485f3e331393d42e82329e9f5b3052
2,107
py
Python
plugins/httpev.py
wohali/gizzy
c9d4ee9cdcf6fdbf260869365b944f29c660e6aa
[ "Apache-2.0" ]
3
2015-09-11T23:34:36.000Z
2018-04-05T21:17:08.000Z
plugins/httpev.py
wohali/gizzy
c9d4ee9cdcf6fdbf260869365b944f29c660e6aa
[ "Apache-2.0" ]
null
null
null
plugins/httpev.py
wohali/gizzy
c9d4ee9cdcf6fdbf260869365b944f29c660e6aa
[ "Apache-2.0" ]
null
null
null
"""\ This plugin merely enables other plugins to accept data over HTTP. If a plugin defines a module level function named "httpev" it will be invoked for POST requests to the url http://$hostname/event/$pluginname. The function is invoked from the thread in the web.py request context and as such has access to the full web.py API. """ import base64 import json import web web.config.debug = False def load(): s = Server() s.start() return s def unload(s): s.stop()
26.670886
76
0.591362
29656dc8827f4e4fcb777d91bc04e2895b6de0ad
773
py
Python
ex056.py
danilodelucio/Exercicios_Curso_em_Video
d59e1b4efaf27dd0fc828a608201613c69ac333d
[ "MIT" ]
null
null
null
ex056.py
danilodelucio/Exercicios_Curso_em_Video
d59e1b4efaf27dd0fc828a608201613c69ac333d
[ "MIT" ]
null
null
null
ex056.py
danilodelucio/Exercicios_Curso_em_Video
d59e1b4efaf27dd0fc828a608201613c69ac333d
[ "MIT" ]
null
null
null
somaIdade = 0 maiorIdade = 0 nomeVelho = '' totmulher20 = 0 for p in range(1, 3): print('---- {} PESSOA ----'.format(p)) nome = str(input('Nome: ')).strip() idade = int(input('Idade: ')) sexo = str(input('Sexo [M/F]: ')) somaIdade += idade if p == 1 and sexo in 'Mm': maiorIdade = idade nomeVelho = nome if sexo in 'Mm' and idade > maiorIdade: maiorIdade = idade nomeVelho = nome if sexo in 'Ff' and idade < 20: totmulher20 += 1 mediaIdade = int(somaIdade / 4) print('A mdia de idade do grupo de pessoas de {} anos.'.format(mediaIdade)) print('O homem mais velho tem {} anos e se chama {}.'.format(maiorIdade, nomeVelho)) print('Ao todo so {} mulher com menos de 20 anos.'.format(totmulher20))
30.92
84
0.606727
2966debf755863b57841211c2eb24e99ff45937a
6,583
py
Python
python/promort.py
simleo/promort_pipeline
03b9d3553a3dade57d0007e230230b02dd70832f
[ "MIT" ]
null
null
null
python/promort.py
simleo/promort_pipeline
03b9d3553a3dade57d0007e230230b02dd70832f
[ "MIT" ]
null
null
null
python/promort.py
simleo/promort_pipeline
03b9d3553a3dade57d0007e230230b02dd70832f
[ "MIT" ]
3
2020-07-29T15:03:40.000Z
2020-10-06T11:16:04.000Z
"""\ PROMORT example. """ import argparse import random import sys import pyecvl.ecvl as ecvl import pyeddl.eddl as eddl from pyeddl.tensor import Tensor import models if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("in_ds", metavar="INPUT_DATASET") parser.add_argument("--epochs", type=int, metavar="INT", default=50) parser.add_argument("--batch-size", type=int, metavar="INT", default=32) parser.add_argument("--gpu", action="store_true") parser.add_argument("--out-dir", metavar="DIR", help="if set, save images in this directory") main(parser.parse_args())
37.19209
98
0.556433
2967592aac9355f4e077c19d82c1790326f4a71b
343
py
Python
src/view/services_update_page.py
nbilbo/services_manager
74e0471a1101305303a96d39963cc98fc0645a64
[ "MIT" ]
null
null
null
src/view/services_update_page.py
nbilbo/services_manager
74e0471a1101305303a96d39963cc98fc0645a64
[ "MIT" ]
null
null
null
src/view/services_update_page.py
nbilbo/services_manager
74e0471a1101305303a96d39963cc98fc0645a64
[ "MIT" ]
null
null
null
from src.view.services_page import ServicesPage from src.view.services_add_page import ServicesAddPage
34.3
54
0.723032
2967a056b02745df6754455d5a9a7411cbb1bfd2
7,543
py
Python
Lib/site-packages/wagtail/utils/l18n/translation.py
SyahmiAmin/belikilo
0a26dadb514683456ea0dbdcbcfcbf65e09d5dbb
[ "bzip2-1.0.6" ]
null
null
null
Lib/site-packages/wagtail/utils/l18n/translation.py
SyahmiAmin/belikilo
0a26dadb514683456ea0dbdcbcfcbf65e09d5dbb
[ "bzip2-1.0.6" ]
null
null
null
Lib/site-packages/wagtail/utils/l18n/translation.py
SyahmiAmin/belikilo
0a26dadb514683456ea0dbdcbcfcbf65e09d5dbb
[ "bzip2-1.0.6" ]
null
null
null
import os import gettext import bisect from locale import getdefaultlocale from collections.abc import MutableMapping from copy import copy, deepcopy import six _trans = Trans() if six.PY2: else:
27.32971
78
0.571258
2967c010afb3c90f1b88a872839f1b992255abcc
272
py
Python
playground/sockets/server.py
tunki/lang-training
79b9f59a7187053f540f9057c585747762ca8890
[ "MIT" ]
null
null
null
playground/sockets/server.py
tunki/lang-training
79b9f59a7187053f540f9057c585747762ca8890
[ "MIT" ]
4
2020-03-10T19:20:21.000Z
2021-06-07T15:39:48.000Z
proglangs-learning/python/example_sockets/server.py
helq/old_code
a432faf1b340cb379190a2f2b11b997b02d1cd8d
[ "CC0-1.0" ]
null
null
null
import socket s = socket.socket() s.bind(("localhost", 9999)) s.listen(1) sc, addr = s.accept() while True: recibido = sc.recv(1024) if recibido == "quit": break print "Recibido:", recibido sc.send(recibido) print "adios" sc.close() s.close()
13.6
31
0.617647
29682fb767c90bc573a3f797e4f0ca061a3378d9
743
py
Python
examples/example_contour.py
moghimis/geojsoncontour
23f298cb5c5ae4b7000024423493e109a9cc908d
[ "MIT" ]
63
2016-10-31T06:55:47.000Z
2022-02-04T06:47:32.000Z
examples/example_contour.py
moghimis/geojsoncontour
23f298cb5c5ae4b7000024423493e109a9cc908d
[ "MIT" ]
20
2016-09-26T15:25:53.000Z
2020-11-11T18:26:32.000Z
examples/example_contour.py
moghimis/geojsoncontour
23f298cb5c5ae4b7000024423493e109a9cc908d
[ "MIT" ]
26
2016-06-15T02:39:10.000Z
2022-02-04T06:48:15.000Z
import numpy import matplotlib.pyplot as plt import geojsoncontour # Create lat and lon vectors and grid data grid_size = 1.0 latrange = numpy.arange(-90.0, 90.0, grid_size) lonrange = numpy.arange(-180.0, 180.0, grid_size) X, Y = numpy.meshgrid(lonrange, latrange) Z = numpy.sqrt(X * X + Y * Y) n_contours = 10 levels = numpy.linspace(start=0, stop=100, num=n_contours) # Create a contour plot plot from grid (lat, lon) data figure = plt.figure() ax = figure.add_subplot(111) contour = ax.contour(lonrange, latrange, Z, levels=levels, cmap=plt.cm.jet) # Convert matplotlib contour to geojson geojsoncontour.contour_to_geojson( contour=contour, geojson_filepath='out.geojson', min_angle_deg=10.0, ndigits=3, unit='m' )
26.535714
75
0.729475