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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e0274bb01109146cf480d663260e32b7e8a8cc2d
| 580 |
py
|
Python
|
portfolio/urls.py
|
ramza007/Ramza.io
|
2172d9ac13e87becbc8644ad5755070f48fab8da
|
[
"Apache-2.0"
] | 3 |
2019-12-16T16:47:16.000Z
|
2020-07-28T19:47:34.000Z
|
portfolio/urls.py
|
ramza007/Ramza.io
|
2172d9ac13e87becbc8644ad5755070f48fab8da
|
[
"Apache-2.0"
] | 15 |
2019-12-05T03:38:19.000Z
|
2022-03-13T02:35:30.000Z
|
portfolio/urls.py
|
ramza007/Ramza.io
|
2172d9ac13e87becbc8644ad5755070f48fab8da
|
[
"Apache-2.0"
] | null | null | null |
from django.conf.urls import url
from django.urls import path, include,re_path
from . import views
from rest_framework.authtoken.views import obtain_auth_token
urlpatterns = [
path('', views.index, name='index'),
path('about', views.about, name='about'),
path('projects', views.projects, name='projects'),
path('photos', views.photos, name='photos'),
re_path(r'^api/projects/$', views.ProjectList.as_view()),
re_path(r'^api-token-auth/', obtain_auth_token),
re_path(r'api/project/project-id/(?P<pk>[0-9]+)/$', views.ProjectDescription.as_view()),
]
| 34.117647 | 92 | 0.7 |
e027abc215159b586950e87882ad8ad4be055155
| 407 |
py
|
Python
|
tests/resources/mlflow-test-plugin/mlflow_test_plugin/file_store.py
|
iPieter/kiwi
|
76b66872fce68873809a0dea112e2ed552ae5b63
|
[
"Apache-2.0"
] | null | null | null |
tests/resources/mlflow-test-plugin/mlflow_test_plugin/file_store.py
|
iPieter/kiwi
|
76b66872fce68873809a0dea112e2ed552ae5b63
|
[
"Apache-2.0"
] | 1 |
2021-01-24T13:34:51.000Z
|
2021-01-24T13:34:51.000Z
|
tests/resources/mlflow-test-plugin/mlflow_test_plugin/file_store.py
|
iPieter/kiwi
|
76b66872fce68873809a0dea112e2ed552ae5b63
|
[
"Apache-2.0"
] | null | null | null |
from six.moves import urllib
from kiwi.store.tracking.file_store import FileStore
| 31.307692 | 75 | 0.746929 |
e02820e74734d672d90f15bf093da7319a0c92ba
| 12,815 |
py
|
Python
|
tests/server/test_flask_api.py
|
YuhangCh/terracotta
|
867ba5f7425fa88881f4c161d81cc7311f4f9c4e
|
[
"MIT"
] | null | null | null |
tests/server/test_flask_api.py
|
YuhangCh/terracotta
|
867ba5f7425fa88881f4c161d81cc7311f4f9c4e
|
[
"MIT"
] | null | null | null |
tests/server/test_flask_api.py
|
YuhangCh/terracotta
|
867ba5f7425fa88881f4c161d81cc7311f4f9c4e
|
[
"MIT"
] | null | null | null |
from io import BytesIO
import json
import urllib.parse
from collections import OrderedDict
from PIL import Image
import numpy as np
import pytest
def test_get_keys(client, use_testdb):
rv = client.get('/keys')
expected_response = [
{'key': 'key1'},
{'key': 'akey'},
{'key': 'key2', 'description': 'key2'}
]
assert rv.status_code == 200
assert expected_response == json.loads(rv.data)['keys']
def test_get_metadata(client, use_testdb):
rv = client.get('/metadata/val11/x/val12/')
assert rv.status_code == 200
assert ['extra_data'] == json.loads(rv.data)['metadata']
def test_get_metadata_nonexisting(client, use_testdb):
rv = client.get('/metadata/val11/x/NONEXISTING/')
assert rv.status_code == 404
def test_get_datasets(client, use_testdb):
rv = client.get('/datasets')
assert rv.status_code == 200
datasets = json.loads(rv.data, object_pairs_hook=OrderedDict)['datasets']
assert len(datasets) == 4
assert OrderedDict([('key1', 'val11'), ('akey', 'x'), ('key2', 'val12')]) in datasets
def test_get_datasets_pagination(client, use_testdb):
# no page (implicit 0)
rv = client.get('/datasets?limit=2')
assert rv.status_code == 200
response = json.loads(rv.data, object_pairs_hook=OrderedDict)
assert response['limit'] == 2
assert response['page'] == 0
first_datasets = response['datasets']
assert len(first_datasets) == 2
assert OrderedDict([('key1', 'val11'), ('akey', 'x'), ('key2', 'val12')]) in first_datasets
# second page
rv = client.get('/datasets?limit=2&page=1')
assert rv.status_code == 200
response = json.loads(rv.data, object_pairs_hook=OrderedDict)
assert response['limit'] == 2
assert response['page'] == 1
last_datasets = response['datasets']
assert len(last_datasets) == 2
assert OrderedDict([('key1', 'val11'), ('akey', 'x'), ('key2', 'val12')]) not in last_datasets
# page out of range
rv = client.get('/datasets?limit=2&page=1000')
assert rv.status_code == 200
assert not json.loads(rv.data)['datasets']
# invalid page
rv = client.get('/datasets?page=-1')
assert rv.status_code == 400
# invalid limit
rv = client.get('/datasets?limit=-1')
assert rv.status_code == 400
def test_get_datasets_selective(client, use_testdb):
rv = client.get('/datasets?key1=val21')
assert rv.status_code == 200
assert len(json.loads(rv.data)['datasets']) == 3
rv = client.get('/datasets?key1=val21&key2=val23')
assert rv.status_code == 200
assert len(json.loads(rv.data)['datasets']) == 1
def test_get_datasets_unknown_key(client, use_testdb):
rv = client.get('/datasets?UNKNOWN=val21')
assert rv.status_code == 400
def test_get_singleband_greyscale(client, use_testdb, raster_file_xyz):
import terracotta
settings = terracotta.get_settings()
x, y, z = raster_file_xyz
rv = client.get(f'/singleband/val11/x/val12/{z}/{x}/{y}.png')
assert rv.status_code == 200
img = Image.open(BytesIO(rv.data))
assert np.asarray(img).shape == settings.DEFAULT_TILE_SIZE
def test_get_singleband_extra_args(client, use_testdb, raster_file_xyz):
import terracotta
settings = terracotta.get_settings()
x, y, z = raster_file_xyz
rv = client.get(f'/singleband/val11/x/val12/{z}/{x}/{y}.png?foo=bar&baz=quz')
assert rv.status_code == 200
img = Image.open(BytesIO(rv.data))
assert np.asarray(img).shape == settings.DEFAULT_TILE_SIZE
def test_get_singleband_cmap(client, use_testdb, raster_file_xyz):
import terracotta
settings = terracotta.get_settings()
x, y, z = raster_file_xyz
rv = client.get(f'/singleband/val11/x/val12/{z}/{x}/{y}.png?colormap=jet')
assert rv.status_code == 200
img = Image.open(BytesIO(rv.data))
assert np.asarray(img).shape == settings.DEFAULT_TILE_SIZE
def test_get_singleband_preview(client, use_testdb):
import terracotta
settings = terracotta.get_settings()
rv = client.get(f'/singleband/val11/x/val12/preview.png?colormap=jet')
assert rv.status_code == 200
img = Image.open(BytesIO(rv.data))
assert np.asarray(img).shape == settings.DEFAULT_TILE_SIZE
def urlsafe_json(payload):
payload_json = json.dumps(payload)
return urllib.parse.quote_plus(payload_json, safe=r',.[]{}:"')
def test_get_singleband_explicit_cmap(client, use_testdb, raster_file_xyz):
import terracotta
settings = terracotta.get_settings()
x, y, z = raster_file_xyz
explicit_cmap = {1: (0, 0, 0), 2.0: (255, 255, 255, 20), 3: '#ffffff', 4: 'abcabc'}
rv = client.get(f'/singleband/val11/x/val12/{z}/{x}/{y}.png?colormap=explicit'
f'&explicit_color_map={urlsafe_json(explicit_cmap)}')
assert rv.status_code == 200, rv.data.decode('utf-8')
img = Image.open(BytesIO(rv.data))
assert np.asarray(img).shape == settings.DEFAULT_TILE_SIZE
def test_get_singleband_explicit_cmap_invalid(client, use_testdb, raster_file_xyz):
x, y, z = raster_file_xyz
explicit_cmap = {1: (0, 0, 0), 2: (255, 255, 255), 3: '#ffffff', 4: 'abcabc'}
rv = client.get(f'/singleband/val11/x/val12/{z}/{x}/{y}.png?'
f'explicit_color_map={urlsafe_json(explicit_cmap)}')
assert rv.status_code == 400
rv = client.get(f'/singleband/val11/x/val12/{z}/{x}/{y}.png?colormap=jet'
f'&explicit_color_map={urlsafe_json(explicit_cmap)}')
assert rv.status_code == 400
rv = client.get(f'/singleband/val11/x/val12/{z}/{x}/{y}.png?colormap=explicit')
assert rv.status_code == 400
explicit_cmap[3] = 'omgomg'
rv = client.get(f'/singleband/val11/x/val12/{z}/{x}/{y}.png?colormap=explicit'
f'&explicit_color_map={urlsafe_json(explicit_cmap)}')
assert rv.status_code == 400
explicit_cmap = [(255, 255, 255)]
rv = client.get(f'/singleband/val11/x/val12/{z}/{x}/{y}.png?colormap=explicit'
f'&explicit_color_map={urlsafe_json(explicit_cmap)}')
assert rv.status_code == 400
rv = client.get(f'/singleband/val11/x/val12/{z}/{x}/{y}.png?colormap=explicit'
f'&explicit_color_map=foo')
assert rv.status_code == 400
def test_get_singleband_stretch(client, use_testdb, raster_file_xyz):
import terracotta
settings = terracotta.get_settings()
x, y, z = raster_file_xyz
for stretch_range in ('[0,1]', '[0,null]', '[null, 1]', '[null,null]', 'null'):
rv = client.get(f'/singleband/val11/x/val12/{z}/{x}/{y}.png?stretch_range={stretch_range}')
assert rv.status_code == 200
img = Image.open(BytesIO(rv.data))
assert np.asarray(img).shape == settings.DEFAULT_TILE_SIZE
| 30.731415 | 99 | 0.65595 |
e02908fac191deeaa9eb04515ee51d7d466320c5
| 1,695 |
py
|
Python
|
url.py
|
matthieucan/shorturl
|
a7f7fab61e8b23b352590797ca4959ed166c865e
|
[
"WTFPL"
] | 1 |
2018-10-19T01:57:29.000Z
|
2018-10-19T01:57:29.000Z
|
url.py
|
matthieucan/shorturl
|
a7f7fab61e8b23b352590797ca4959ed166c865e
|
[
"WTFPL"
] | null | null | null |
url.py
|
matthieucan/shorturl
|
a7f7fab61e8b23b352590797ca4959ed166c865e
|
[
"WTFPL"
] | null | null | null |
def base_conv(n, input_base=10, output_base=10):
"""
Converts a number n from base input_base to base output_base.
The following symbols are used to represent numbers:
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
n can be an int if input_base <= 10, and a string otherwise.
The result will be a string.
"""
numbers = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
## base 10 conversion
n = str(n)
size = len(n)
baseten = 0
for i in range(size):
baseten += numbers.index(n[i]) * input_base ** (size - 1 - i)
## base output_base conversion
# we search the biggest number m such that n^m < x
max_power = 0
while output_base ** (max_power + 1) <= baseten:
max_power += 1
result = ""
for i in range(max_power + 1):
coeff = baseten / (output_base ** (max_power - i))
baseten -= coeff * (output_base ** (max_power - i))
result += numbers[coeff]
return result
if __name__ == "__main__":
assert(base_conv(10) == "10")
assert(base_conv(42) == "42")
assert(base_conv(5673576) == "5673576")
assert(base_conv(10, input_base=2) == "2")
assert(base_conv(101010, input_base=2) == "42")
assert(base_conv(43, input_base=10, output_base=2) == "101011")
assert(base_conv(256**3 - 1, input_base=10, output_base=16) == "ffffff")
assert(base_conv("d9bbb9d0ceabf", input_base=16, output_base=8) ==
"154673563503165277")
assert(base_conv("154673563503165277", input_base=8, output_base=10) ==
"3830404793297599")
assert(base_conv(0, input_base=3, output_base=50) == "0")
| 36.06383 | 78 | 0.640708 |
e02960393a5a94bda69769c1a73c609b148e700d
| 13,612 |
py
|
Python
|
src/qtt/qiskit/passes.py
|
codecrap/qtt
|
39a8bf21f7bcab94940a66f4d553a14bf34f82b0
|
[
"MIT"
] | null | null | null |
src/qtt/qiskit/passes.py
|
codecrap/qtt
|
39a8bf21f7bcab94940a66f4d553a14bf34f82b0
|
[
"MIT"
] | null | null | null |
src/qtt/qiskit/passes.py
|
codecrap/qtt
|
39a8bf21f7bcab94940a66f4d553a14bf34f82b0
|
[
"MIT"
] | null | null | null |
import logging
from typing import Dict, List, Optional
import numpy as np
import qiskit
from qiskit.circuit import Barrier, Delay, Reset
from qiskit.circuit.library import (CRXGate, CRYGate, CRZGate, CZGate,
PhaseGate, RXGate, RYGate, RZGate, U1Gate,
U2Gate, U3Gate, UGate)
from qiskit.circuit.library.standard_gates import (CU1Gate, RZZGate, SdgGate,
SGate, TdgGate, TGate,
ZGate)
from qiskit.circuit.quantumcircuit import QuantumCircuit
from qiskit.converters.circuit_to_dag import circuit_to_dag
from qiskit.dagcircuit import DAGCircuit
from qiskit.transpiler.basepasses import TransformationPass
logger = logging.getLogger(__name__)
| 36.591398 | 115 | 0.563914 |
e029ad3e92c68df36a0c0c69723e696b156c5364
| 5,616 |
py
|
Python
|
IAFNNESTA.py
|
JonathanAlis/IAFNNESTA
|
6845bed7e41a162a60e65d709f37cf975c8c8a4e
|
[
"MIT"
] | 3 |
2021-05-13T05:51:42.000Z
|
2022-02-06T13:36:52.000Z
|
IAFNNESTA.py
|
JonathanAlis/IAFNNESTA
|
6845bed7e41a162a60e65d709f37cf975c8c8a4e
|
[
"MIT"
] | null | null | null |
IAFNNESTA.py
|
JonathanAlis/IAFNNESTA
|
6845bed7e41a162a60e65d709f37cf975c8c8a4e
|
[
"MIT"
] | 1 |
2022-02-06T13:36:39.000Z
|
2022-02-06T13:36:39.000Z
|
import IAFNNesterov
import numpy as np
from scipy import sparse
import fil2mat
if __name__ == "__main__":
print(help())
| 35.770701 | 215 | 0.51834 |
e029f3704209eae0d9983e10eec83eadf0c6a288
| 6,952 |
py
|
Python
|
hypatia/util/__init__.py
|
pfw/hypatia
|
407cd62e4817c85188aa6abdf204c5aaff5ab570
|
[
"ZPL-2.1"
] | null | null | null |
hypatia/util/__init__.py
|
pfw/hypatia
|
407cd62e4817c85188aa6abdf204c5aaff5ab570
|
[
"ZPL-2.1"
] | null | null | null |
hypatia/util/__init__.py
|
pfw/hypatia
|
407cd62e4817c85188aa6abdf204c5aaff5ab570
|
[
"ZPL-2.1"
] | null | null | null |
import itertools
import BTrees
from persistent import Persistent
from ZODB.broken import Broken
from zope.interface import implementer
_marker = object()
from .. import exc
from ..interfaces import (
IResultSet,
STABLE,
)
| 31.174888 | 85 | 0.60889 |
e02a89e62a53d61fc9086acef78dc03df26f1de7
| 2,140 |
py
|
Python
|
backend/listings/migrations/0001_initial.py
|
relaxxpls/Music-Control
|
76f5d10904f820607b3eb756850d5c5d7d89d875
|
[
"MIT"
] | null | null | null |
backend/listings/migrations/0001_initial.py
|
relaxxpls/Music-Control
|
76f5d10904f820607b3eb756850d5c5d7d89d875
|
[
"MIT"
] | null | null | null |
backend/listings/migrations/0001_initial.py
|
relaxxpls/Music-Control
|
76f5d10904f820607b3eb756850d5c5d7d89d875
|
[
"MIT"
] | null | null | null |
# Generated by Django 3.2.3 on 2021-05-30 04:28
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
| 48.636364 | 158 | 0.583645 |
e02ae313e5c6ccbda99f1c423609cc20c6a48485
| 483 |
py
|
Python
|
examples/example_without_CommandSet/my_listeners.py
|
LeConstellationniste/DiscordFramework
|
24d4b9b7cb0a21d3cec9d5362ab0828c5e15a3af
|
[
"CC0-1.0"
] | 1 |
2021-01-27T14:55:03.000Z
|
2021-01-27T14:55:03.000Z
|
examples/example_without_CommandSet/my_listeners.py
|
LeConstellationniste/DiscordFramework
|
24d4b9b7cb0a21d3cec9d5362ab0828c5e15a3af
|
[
"CC0-1.0"
] | null | null | null |
examples/example_without_CommandSet/my_listeners.py
|
LeConstellationniste/DiscordFramework
|
24d4b9b7cb0a21d3cec9d5362ab0828c5e15a3af
|
[
"CC0-1.0"
] | null | null | null |
import asyncio
import discord
# Just with a function to add to the bot.
# A Listener already created with the function
from discordEasy.objects import Listener
listener_on_message = Listener(on_message)
| 28.411765 | 78 | 0.784679 |
e02beca3eabc9ebe9a2e1d16196b54fbf1a8bc1b
| 4,024 |
py
|
Python
|
pianonet/serving/app.py
|
robgon-art/pianonet
|
8d8a827bc8d310b8ce3f66259bbdf72648e9ca32
|
[
"MIT"
] | 14 |
2020-09-01T11:16:28.000Z
|
2021-05-02T18:04:21.000Z
|
pianonet/serving/app.py
|
robgon-art/pianonet
|
8d8a827bc8d310b8ce3f66259bbdf72648e9ca32
|
[
"MIT"
] | 5 |
2020-11-13T18:46:05.000Z
|
2022-02-10T01:16:13.000Z
|
pianonet/serving/app.py
|
robgon-art/pianonet
|
8d8a827bc8d310b8ce3f66259bbdf72648e9ca32
|
[
"MIT"
] | 3 |
2020-09-02T15:05:00.000Z
|
2021-05-02T18:04:24.000Z
|
import os
import random
from flask import Flask, request, send_from_directory
from werkzeug.utils import secure_filename
from pianonet.core.pianoroll import Pianoroll
from pianonet.model_inspection.performance_from_pianoroll import get_performance_from_pianoroll
app = Flask(__name__)
base_path = "/app/"
# base_path = "/Users/angsten/PycharmProjects/pianonet"
performances_path = os.path.join(base_path, 'data', 'performances')
def get_random_midi_file_name():
"""
Get a random midi file name that will not ever collide.
"""
return str(random.randint(0, 10000000000000000000)) + ".midi"
def get_performance_path(midi_file_name):
"""
Returns full path to performaqnce midi file given a file name.
"""
return os.path.join(performances_path, midi_file_name)
if __name__ == '__main__':
app.run(host='0.0.0.0')
| 31.685039 | 115 | 0.706511 |
e02cef0666c1161f8f7f1e91555b80b350dae71e
| 4,965 |
py
|
Python
|
app.py
|
rafalbigaj/epidemic-model-visualization
|
35829180b5a53697b336e8615d854a21b3395f59
|
[
"Apache-2.0"
] | null | null | null |
app.py
|
rafalbigaj/epidemic-model-visualization
|
35829180b5a53697b336e8615d854a21b3395f59
|
[
"Apache-2.0"
] | null | null | null |
app.py
|
rafalbigaj/epidemic-model-visualization
|
35829180b5a53697b336e8615d854a21b3395f59
|
[
"Apache-2.0"
] | null | null | null |
import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import logging
import json
import os
import pandas as pd
from datetime import datetime
from datetime import timedelta
from urllib import parse
import requests
logger = logging.getLogger(__name__)
external_stylesheets = [dbc.themes.DARKLY]
is_cf_instance = os.environ.get('CF_INSTANCE_GUID', '') != ''
port = int(os.environ.get('PORT', 8050))
host = os.environ.get('CF_INSTANCE_INTERNAL_IP', '127.0.0.1')
wml_api_key = os.environ['WML_API_KEY']
wml_scoring_url = os.environ['WML_SCORING_URL']
url = parse.urlparse(wml_scoring_url)
wml_base_url = url._replace(path='').geturl()
wml_instance_id = url.path.split('/')[3]
logger.setLevel(logging.INFO if is_cf_instance else logging.DEBUG)
logger.info('Starting %s server: %s:%d', 'CF' if is_cf_instance else 'local', host, port)
logger.info('WML URL: %s', wml_base_url)
logger.info('WML instance ID: %s', wml_instance_id)
wml_credentials = {
"apikey": wml_api_key,
"instance_id": wml_instance_id,
"url": wml_base_url,
}
iam_token_endpoint = 'https://iam.cloud.ibm.com/identity/token'
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = serve_layout
if __name__ == '__main__':
app.run_server(debug=(not is_cf_instance), port=port, host=host)
| 34.006849 | 132 | 0.67291 |
e02d1d4df9c56883a92d8546af5497c549276afd
| 1,106 |
py
|
Python
|
src/sweetrpg_library_api/application/blueprints/systems/manager.py
|
paulyhedral/sweetrpg-library-api
|
0105e963ef4321398aa66d7cb3aa9c2df1c4f375
|
[
"MIT"
] | null | null | null |
src/sweetrpg_library_api/application/blueprints/systems/manager.py
|
paulyhedral/sweetrpg-library-api
|
0105e963ef4321398aa66d7cb3aa9c2df1c4f375
|
[
"MIT"
] | 33 |
2021-09-18T23:52:05.000Z
|
2022-03-30T12:25:49.000Z
|
src/sweetrpg_library_api/application/blueprints/systems/manager.py
|
sweetrpg/library-api
|
0105e963ef4321398aa66d7cb3aa9c2df1c4f375
|
[
"MIT"
] | null | null | null |
# -*- coding: utf-8 -*-
__author__ = "Paul Schifferer <[email protected]>"
"""
"""
from flask_rest_jsonapi import ResourceList, ResourceDetail, ResourceRelationship
from sweetrpg_library_objects.api.system.schema import SystemAPISchema
from sweetrpg_api_core.data import APIData
from sweetrpg_library_objects.model.system import System
from sweetrpg_library_api.application.db import db
from sweetrpg_library_api.application.blueprints.setup import model_info
# class SystemAuthorRelationship(ResourceRelationship):
# schema = SystemAPISchema
# data_layer = {
# "class": APIData,
# "type": "system",
# "model": System,
# "db": db,
# "model_info": model_info
# }
| 28.358974 | 106 | 0.683544 |
e02e416aacee98cfdb91a5328f2267836f5a1229
| 6,862 |
py
|
Python
|
tests/test_ordering.py
|
deepio-oc/pabot
|
ebf1894c6d35b2ddd5c4bca01bceb25189358106
|
[
"Apache-2.0"
] | 379 |
2015-02-02T17:47:45.000Z
|
2022-03-20T16:51:05.000Z
|
tests/test_ordering.py
|
deepio-oc/pabot
|
ebf1894c6d35b2ddd5c4bca01bceb25189358106
|
[
"Apache-2.0"
] | 406 |
2015-02-12T07:41:53.000Z
|
2022-03-28T23:35:32.000Z
|
tests/test_ordering.py
|
deepio-oc/pabot
|
ebf1894c6d35b2ddd5c4bca01bceb25189358106
|
[
"Apache-2.0"
] | 159 |
2015-01-16T13:42:20.000Z
|
2022-03-30T19:48:15.000Z
|
from robot import __version__ as ROBOT_VERSION
import sys
import tempfile
import textwrap
import unittest
import shutil
import subprocess
| 35.189744 | 273 | 0.557418 |
e02e814aa08f31a0fd4f302fa151aca0b7af7756
| 984 |
py
|
Python
|
setup.py
|
Commonists/pageview-api
|
39e8b3c3c82f64a500e3dd4f306451c81c7e31b7
|
[
"MIT"
] | 21 |
2015-12-02T12:06:38.000Z
|
2022-02-11T16:16:06.000Z
|
setup.py
|
Commonists/pageview-api
|
39e8b3c3c82f64a500e3dd4f306451c81c7e31b7
|
[
"MIT"
] | 3 |
2016-04-19T19:56:25.000Z
|
2020-08-27T09:52:42.000Z
|
setup.py
|
Commonists/pageview-api
|
39e8b3c3c82f64a500e3dd4f306451c81c7e31b7
|
[
"MIT"
] | 6 |
2017-10-27T15:39:51.000Z
|
2020-12-17T02:11:52.000Z
|
#!/usr/bin/python
# -*- coding: latin-1 -*-
"""Setup script."""
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
try:
import pageviewapi
version = pageviewapi.__version__
except ImportError:
version = 'Undefined'
classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Utilities'
]
packages = ['pageviewapi']
requires = ['requests', 'attrdict']
setup(
name='pageviewapi',
version=version,
author='Commonists',
author_email='[email protected]',
url='http://github.com/Commonists/pageview-api',
description='Wikimedia Pageview API client',
long_description=open('README.md').read(),
license='MIT',
packages=packages,
install_requires=requires,
classifiers=classifiers
)
| 22.883721 | 52 | 0.670732 |
e030b341c624d43cef697abc742e82664391c682
| 416 |
py
|
Python
|
task1b.py
|
juby-gif/assignment1
|
3d39478fdc371e80a546caac545561145afbb080
|
[
"BSD-3-Clause"
] | null | null | null |
task1b.py
|
juby-gif/assignment1
|
3d39478fdc371e80a546caac545561145afbb080
|
[
"BSD-3-Clause"
] | null | null | null |
task1b.py
|
juby-gif/assignment1
|
3d39478fdc371e80a546caac545561145afbb080
|
[
"BSD-3-Clause"
] | null | null | null |
#a2_t1b.py
#This program is to convert Celsius to Kelvin
c = 25.0
f = 100.0
k = c_to_k(c)
fa = f_to_c(f)
print("Celsius of " + str(c) + " is " + str(k) + " in Kelvin")
print("Farenheit of " + str(f) + " is " + str(fa) + " in Celsius")
| 24.470588 | 67 | 0.605769 |
e0315471bd1a35e31c6a9cdd93a2a2a27365d479
| 2,702 |
py
|
Python
|
TWLight/emails/views.py
|
jajodiaraghav/TWLight
|
22359ab0b95ee3653e8ffa0eb698acd7bb8ebf70
|
[
"MIT"
] | 1 |
2019-10-24T04:49:52.000Z
|
2019-10-24T04:49:52.000Z
|
TWLight/emails/views.py
|
jajodiaraghav/TWLight
|
22359ab0b95ee3653e8ffa0eb698acd7bb8ebf70
|
[
"MIT"
] | 1 |
2019-03-29T15:29:45.000Z
|
2019-03-29T15:57:20.000Z
|
TWLight/emails/views.py
|
jajodiaraghav/TWLight
|
22359ab0b95ee3653e8ffa0eb698acd7bb8ebf70
|
[
"MIT"
] | 1 |
2019-09-26T14:40:27.000Z
|
2019-09-26T14:40:27.000Z
|
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse, reverse_lazy
from django.core.mail import BadHeaderError, send_mail
from django.http import HttpResponse, HttpResponseRedirect
from django.utils.decorators import method_decorator
from django.utils.translation import ugettext_lazy as _
from django.views.generic.edit import FormView
from TWLight.emails.forms import ContactUsForm
from TWLight.emails.signals import ContactUs
| 43.580645 | 126 | 0.657661 |
e0322ebc94878f3dc7b69955feb764a97d3db29b
| 1,997 |
py
|
Python
|
frontend/config.py
|
lcbm/cs-data-ingestion
|
314525285bfefe726d86c232937b05d273e44e7f
|
[
"0BSD"
] | null | null | null |
frontend/config.py
|
lcbm/cs-data-ingestion
|
314525285bfefe726d86c232937b05d273e44e7f
|
[
"0BSD"
] | null | null | null |
frontend/config.py
|
lcbm/cs-data-ingestion
|
314525285bfefe726d86c232937b05d273e44e7f
|
[
"0BSD"
] | null | null | null |
"""Flask App configuration file."""
import logging
import os
import dotenv
import frontend.constants as constants
dotenv.load_dotenv(os.path.join(constants.BASEDIR, "frontend.env"))
config = {
"development": "frontend.config.Development",
"staging": "frontend.config.Staging",
"production": "frontend.config.Production",
"default": "frontend.config.Development",
}
def configure_app(app):
"""Configures the Flask app according to the FLASK_ENV
envar. In case FLASK_ENV is not defined, then use the
'default' configuration.
Parameters
----------
app: flask.Flask
Flask app Module.
"""
# Configure app
config_name = os.environ.get("FLASK_ENV", "default")
app.config.from_object(config[config_name])
# Configure logging
handler = logging.FileHandler(app.config["LOGGING_LOCATION"])
handler.setLevel(app.config["LOGGING_LEVEL"])
formatter = logging.Formatter(app.config["LOGGING_FORMAT"])
handler.setFormatter(formatter)
app.logger.addHandler(handler)
| 21.473118 | 67 | 0.667001 |
e032bc66a6f5b0a211c59ba883502067921d3427
| 2,961 |
py
|
Python
|
tests/test_dsl.py
|
goodreferences/ElasticQuery
|
579e387c5a7c1cbbeab999050c0d2faa80ded821
|
[
"MIT"
] | null | null | null |
tests/test_dsl.py
|
goodreferences/ElasticQuery
|
579e387c5a7c1cbbeab999050c0d2faa80ded821
|
[
"MIT"
] | null | null | null |
tests/test_dsl.py
|
goodreferences/ElasticQuery
|
579e387c5a7c1cbbeab999050c0d2faa80ded821
|
[
"MIT"
] | null | null | null |
# ElasticQuery
# File: tests/test_dsl.py
# Desc: tests for ElasticQuery DSL objects (Filter, Query, Aggregate)
from os import path
from unittest import TestCase
from jsontest import JsonTest
from elasticquery import Query, Aggregate, Suggester
from elasticquery.exceptions import (
NoQueryError, NoAggregateError, NoSuggesterError,
MissingArgError
)
from .util import assert_equal
CLASS_NAMES = {
'_query': Query
}
| 26.675676 | 72 | 0.646066 |
e033806ab7ea22ebae1fd718d44b4fe732b6c01d
| 360 |
py
|
Python
|
models/SelectionGAN/person_transfer/tool/rm_insnorm_running_vars.py
|
xianjian-xie/pose-generation
|
ad0495e80c6fe1e7690fa8691f1eb11b4e9bca32
|
[
"MIT"
] | 445 |
2019-04-14T17:48:11.000Z
|
2022-03-20T11:53:30.000Z
|
models/SelectionGAN/person_transfer/tool/rm_insnorm_running_vars.py
|
xianjian-xie/pose-generation
|
ad0495e80c6fe1e7690fa8691f1eb11b4e9bca32
|
[
"MIT"
] | 17 |
2019-06-03T11:34:22.000Z
|
2022-02-28T01:26:13.000Z
|
models/SelectionGAN/person_transfer/tool/rm_insnorm_running_vars.py
|
xianjian-xie/pose-generation
|
ad0495e80c6fe1e7690fa8691f1eb11b4e9bca32
|
[
"MIT"
] | 71 |
2019-04-16T01:55:39.000Z
|
2022-03-22T05:09:59.000Z
|
import torch
ckp_path = './checkpoints/fashion_PATN/latest_net_netG.pth'
save_path = './checkpoints/fashion_PATN_v1.0/latest_net_netG.pth'
states_dict = torch.load(ckp_path)
states_dict_new = states_dict.copy()
for key in states_dict.keys():
if "running_var" in key or "running_mean" in key:
del states_dict_new[key]
torch.save(states_dict_new, save_path)
| 32.727273 | 65 | 0.794444 |
e03555c89ef682c9881524e84b3f99fb40c60411
| 3,916 |
py
|
Python
|
script/dummy/arm_control.py
|
amazon-picking-challenge/team_pfn
|
2f76524b067d816d8407f6c4fae4e6d33939c024
|
[
"Apache-2.0"
] | 7 |
2016-09-04T02:07:04.000Z
|
2017-05-25T02:31:07.000Z
|
script/dummy/arm_control.py
|
amazon-picking-challenge/team_pfn
|
2f76524b067d816d8407f6c4fae4e6d33939c024
|
[
"Apache-2.0"
] | null | null | null |
script/dummy/arm_control.py
|
amazon-picking-challenge/team_pfn
|
2f76524b067d816d8407f6c4fae4e6d33939c024
|
[
"Apache-2.0"
] | null | null | null |
#!/usr/bin/python
# Copyright 2016 Preferred Networks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy
import rospy
import actionlib
from geometry_msgs.msg import Twist, Vector3
from apc2016.msg import *
if __name__ == '__main__':
rospy.init_node("arm_control_dummy", anonymous=True)
DummyArmControl()
rospy.spin()
| 39.959184 | 78 | 0.589122 |
e035deed8737a8c4ccc24d990b915152d4728210
| 3,115 |
py
|
Python
|
cogs/events.py
|
rompdodger/RompDodger
|
9c8b481d9f69e05c15f01271f6c18e09ab2723e6
|
[
"MIT"
] | null | null | null |
cogs/events.py
|
rompdodger/RompDodger
|
9c8b481d9f69e05c15f01271f6c18e09ab2723e6
|
[
"MIT"
] | null | null | null |
cogs/events.py
|
rompdodger/RompDodger
|
9c8b481d9f69e05c15f01271f6c18e09ab2723e6
|
[
"MIT"
] | null | null | null |
import json
import discord
from utils.time import format_time
from utils import utilities
from discord.ext import commands
from discord import Embed
| 39.43038 | 163 | 0.733547 |
e036c8bce2480207e7560bdb8a009054bcbca43d
| 1,333 |
py
|
Python
|
Task/Parallel-calculations/Python/parallel-calculations-2.py
|
LaudateCorpus1/RosettaCodeData
|
9ad63ea473a958506c041077f1d810c0c7c8c18d
|
[
"Info-ZIP"
] | 1 |
2018-11-09T22:08:38.000Z
|
2018-11-09T22:08:38.000Z
|
Task/Parallel-calculations/Python/parallel-calculations-2.py
|
seanwallawalla-forks/RosettaCodeData
|
9ad63ea473a958506c041077f1d810c0c7c8c18d
|
[
"Info-ZIP"
] | null | null | null |
Task/Parallel-calculations/Python/parallel-calculations-2.py
|
seanwallawalla-forks/RosettaCodeData
|
9ad63ea473a958506c041077f1d810c0c7c8c18d
|
[
"Info-ZIP"
] | 1 |
2018-11-09T22:08:40.000Z
|
2018-11-09T22:08:40.000Z
|
import multiprocessing
# ========== #Python3 - concurrent
from math import floor, sqrt
numbers = [
112272537195293,
112582718962171,
112272537095293,
115280098190773,
115797840077099,
1099726829285419]
# numbers = [33, 44, 55, 275]
# ========== #Python3 - concurrent
if __name__ == '__main__':
print('For these numbers:')
print('\n '.join(str(p) for p in numbers))
number, all_factors = prime_factors_of_number_with_lowest_prime_factor(numbers)
print(' The one with the largest minimum prime factor is {}:'.format(number))
print(' All its prime factors in order are: {}'.format(all_factors))
| 28.361702 | 84 | 0.650413 |
e036f44b7fa0f2862267ed2ae2bb354dffc8bc0b
| 260 |
py
|
Python
|
setup.py
|
clin366/airpollutionnowcast
|
f9152583eebc4ad747c8d0510460334a5fb23ff9
|
[
"MIT"
] | null | null | null |
setup.py
|
clin366/airpollutionnowcast
|
f9152583eebc4ad747c8d0510460334a5fb23ff9
|
[
"MIT"
] | 9 |
2020-03-24T18:12:45.000Z
|
2022-02-10T00:36:57.000Z
|
setup.py
|
clin366/airpollutionnowcast
|
f9152583eebc4ad747c8d0510460334a5fb23ff9
|
[
"MIT"
] | null | null | null |
from setuptools import find_packages, setup
setup(
name='src',
packages=find_packages(),
version='0.1.0',
description='Project: Nowcasting the air pollution using online search log',
author='Emory University(IR Lab)',
license='MIT',
)
| 23.636364 | 80 | 0.692308 |
e037cc498ab758b47d57f427145d459d775fb063
| 339 |
py
|
Python
|
problems/p0048/s48.py
|
ahrarmonsur/euler
|
4174790637806521a4ea2973abeb76c96c64a782
|
[
"MIT"
] | 1 |
2017-12-19T21:18:48.000Z
|
2017-12-19T21:18:48.000Z
|
problems/p0048/s48.py
|
ahrarmonsur/euler
|
4174790637806521a4ea2973abeb76c96c64a782
|
[
"MIT"
] | null | null | null |
problems/p0048/s48.py
|
ahrarmonsur/euler
|
4174790637806521a4ea2973abeb76c96c64a782
|
[
"MIT"
] | null | null | null |
"""
Project Euler Problem 48
Self powers
Solved by Ahrar Monsur
The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317.
Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000.
"""
main()
| 17.842105 | 74 | 0.575221 |
e037f80102198e6c3f910c89e80dfa13f614bfb4
| 1,109 |
py
|
Python
|
BigData/sparkTask/test.py
|
Rainstyd/rainsty
|
9a0d5f46c20faf909c4194f315fb9960652cffc6
|
[
"Apache-2.0"
] | 1 |
2020-03-25T01:13:35.000Z
|
2020-03-25T01:13:35.000Z
|
BigData/sparkTask/test.py
|
Rainstyed/rainsty
|
f74e0ccaf16d1871c9d1870bd8a7c8a63243fcf5
|
[
"Apache-2.0"
] | 1 |
2022-01-06T23:49:21.000Z
|
2022-01-06T23:49:21.000Z
|
BigData/sparkTask/test.py
|
rainstyd/rainsty
|
9a0d5f46c20faf909c4194f315fb9960652cffc6
|
[
"Apache-2.0"
] | 1 |
2020-03-20T08:48:36.000Z
|
2020-03-20T08:48:36.000Z
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
@author: rainsty
@file: test.py
@time: 2020-01-04 18:36:57
@description:
"""
import os
from pyspark.sql import SparkSession
os.environ['JAVA_HOME'] = '/root/jdk'
os.environ['SPARK_HOME'] = '/root/spark'
os.environ['PYTHON_HOME'] = "/root/python"
os.environ['PYSPARK_PYTHON'] = "/usr/bin/python"
os.environ['SPARK_MASTER_IP'] = 'rainsty'
logFile = "/root/spark/README.md"
spark = create_spark_context()
logData = spark.read.text(logFile).cache()
numAs = logData.filter(logData.value.contains('a')).count()
numBs = logData.filter(logData.value.contains('b')).count()
print("Lines with a: %i, lines with b: %i" % (numAs, numBs))
spark.stop()
| 24.108696 | 60 | 0.640216 |
e03860989956f152e97aacd3a94938522a675b8e
| 1,042 |
py
|
Python
|
esercizi/areaSottesaCompareNumPy.py
|
gdv/python-alfabetizzazione
|
d87561222de8a230db11d8529c49cf1702aec326
|
[
"MIT"
] | null | null | null |
esercizi/areaSottesaCompareNumPy.py
|
gdv/python-alfabetizzazione
|
d87561222de8a230db11d8529c49cf1702aec326
|
[
"MIT"
] | null | null | null |
esercizi/areaSottesaCompareNumPy.py
|
gdv/python-alfabetizzazione
|
d87561222de8a230db11d8529c49cf1702aec326
|
[
"MIT"
] | 1 |
2019-03-26T11:14:33.000Z
|
2019-03-26T11:14:33.000Z
|
import numpy as np
import timeit
numIntervalli = input('inserire il numero di intervalli in [0.0, 1.0] ')
deltaIntervallo = 1.0 / float(numIntervalli)
print "larghezza intervallo", deltaIntervallo
start = timeit.default_timer()
xIntervalli = []
yIntervalli = []
i = 0
while i < numIntervalli:
xIntervallo = i*deltaIntervallo
xIntervalli.append(xIntervallo)
yIntervalli.append(effe(xIntervallo))
i += 1
areaSottesa = 0.0
for altezza in yIntervalli:
areaSottesa += altezza * deltaIntervallo
endOld = timeit.default_timer()
print "l'area sottesa dalla curva vale ", areaSottesa
xNPIntervalli = np.linspace(0.0, 1.0, numIntervalli, endpoint=False)
yNPIntervalli = -xNPIntervalli * (xNPIntervalli - 1.0)
npArea = np.sum(yNPIntervalli*deltaIntervallo)
endNP = timeit.default_timer()
# print xNPIntervalli
# print xIntervalli
# print yNPIntervalli
# print yIntervalli
print "area numpy = ", npArea
print "old timing = ", endOld - start, "numPy timing = ", endNP - endOld
| 24.809524 | 72 | 0.726488 |
e039092d052960d2f6c3a01770cd6d300e7b630a
| 8,810 |
py
|
Python
|
json_codegen/generators/python3_marshmallow/object_generator.py
|
expobrain/json-schema-codegen
|
e22b386333c6230e5d6f5984fd947fdd7b947e82
|
[
"MIT"
] | 21 |
2018-06-15T16:08:57.000Z
|
2022-02-11T16:16:11.000Z
|
json_codegen/generators/python3_marshmallow/object_generator.py
|
expobrain/json-schema-codegen
|
e22b386333c6230e5d6f5984fd947fdd7b947e82
|
[
"MIT"
] | 14 |
2018-08-09T18:02:19.000Z
|
2022-01-24T18:04:17.000Z
|
json_codegen/generators/python3_marshmallow/object_generator.py
|
expobrain/json-schema-codegen
|
e22b386333c6230e5d6f5984fd947fdd7b947e82
|
[
"MIT"
] | 4 |
2018-11-30T18:19:10.000Z
|
2021-11-18T04:04:36.000Z
|
import ast
from json_codegen.generators.python3_marshmallow.utils import Annotations, class_name
| 34.414063 | 108 | 0.484222 |
e039c81acd8d1fcb88f92f04b6556a716666da98
| 12,736 |
py
|
Python
|
testing/regrid/testEsmfGridToMeshRegridCsrv.py
|
xylar/cdat
|
8a5080cb18febfde365efc96147e25f51494a2bf
|
[
"BSD-3-Clause"
] | 62 |
2018-03-30T15:46:56.000Z
|
2021-12-08T23:30:24.000Z
|
testing/regrid/testEsmfGridToMeshRegridCsrv.py
|
xylar/cdat
|
8a5080cb18febfde365efc96147e25f51494a2bf
|
[
"BSD-3-Clause"
] | 114 |
2018-03-21T01:12:43.000Z
|
2021-07-05T12:29:54.000Z
|
testing/regrid/testEsmfGridToMeshRegridCsrv.py
|
CDAT/uvcdat
|
5133560c0c049b5c93ee321ba0af494253b44f91
|
[
"BSD-3-Clause"
] | 14 |
2018-06-06T02:42:47.000Z
|
2021-11-26T03:27:00.000Z
|
#!/usr/bin/env python
#
# $Id: ESMP_GridToMeshRegridCsrv.py,v 1.5 2012/04/23 23:00:14 rokuingh Exp $
#===============================================================================
# ESMP/examples/ESMP_GridToMeshRegrid.py
#===============================================================================
"""
ESMP_GridToMeshRegridCsrv.py
Two ESMP_Field objects are created, one on a Grid and the other on a Mesh. The
source Field is set to an analytic function, and a conservative regridding
operation is performed from the source to the destination Field. After
the regridding is completed, the destination Field is compared to the
exact solution over that domain.
"""
import cdms2
import ESMP
import numpy as _NP
import unittest
def grid_create():
'''
PRECONDITIONS: ESMP has been initialized.
POSTCONDITIONS: A ESMP_Grid has been created.
'''
ub_x = float(4)
ub_y = float(4)
lb_x = float(0)
lb_y = float(0)
max_x = float(4)
max_y = float(4)
min_x = float(0)
min_y = float(0)
cellwidth_x = (max_x-min_x)/(ub_x-lb_x)
cellwidth_y = (max_y-min_y)/(ub_y-lb_y)
cellcenter_x = cellwidth_x/2
cellcenter_y = cellwidth_y/2
maxIndex = _NP.array([ub_x,ub_y], dtype=_NP.int32)
grid = ESMP.ESMP_GridCreateNoPeriDim(maxIndex,
coordSys=ESMP.ESMP_COORDSYS_CART)
## CORNERS
ESMP.ESMP_GridAddCoord(grid, staggerloc=ESMP.ESMP_STAGGERLOC_CORNER)
exLB_corner, exUB_corner = ESMP.ESMP_GridGetCoord(grid, \
ESMP.ESMP_STAGGERLOC_CORNER)
# get the coordinate pointers and set the coordinates
[x,y] = [0, 1]
gridXCorner = ESMP.ESMP_GridGetCoordPtr(grid, x, ESMP.ESMP_STAGGERLOC_CORNER)
gridYCorner = ESMP.ESMP_GridGetCoordPtr(grid, y, ESMP.ESMP_STAGGERLOC_CORNER)
#print 'lower corner bounds = [{0},{1}]'.format(exLB_corner[0],exLB_corner[1])
#print 'upper corner bounds = [{0},{1}]'.format(exUB_corner[0],exUB_corner[1])
p = 0
for i1 in range(exLB_corner[1], exUB_corner[1]):
for i0 in range(exLB_corner[0], exUB_corner[0]):
gridXCorner[p] = float(i0)*cellwidth_x
gridYCorner[p] = float(i1)*cellwidth_y
p = p + 1
#print 'Grid corner coordinates:'
p = 0
for i1 in range(exLB_corner[1], exUB_corner[1]):
for i0 in range(exLB_corner[0], exUB_corner[0]):
#print '[{0},{1}]'.format(gridXCorner[p], gridYCorner[p])
p = p + 1
#print '\n'
## CENTERS
ESMP.ESMP_GridAddCoord(grid, staggerloc=ESMP.ESMP_STAGGERLOC_CENTER)
exLB_center, exUB_center = ESMP.ESMP_GridGetCoord(grid, \
ESMP.ESMP_STAGGERLOC_CENTER)
# get the coordinate pointers and set the coordinates
[x,y] = [0, 1]
gridXCenter = ESMP.ESMP_GridGetCoordPtr(grid, x, ESMP.ESMP_STAGGERLOC_CENTER)
gridYCenter = ESMP.ESMP_GridGetCoordPtr(grid, y, ESMP.ESMP_STAGGERLOC_CENTER)
#print 'lower corner bounds = [{0},{1}]'.format(exLB_center[0],exLB_center[1])
#print 'upper corner bounds = [{0},{1}]'.format(exUB_center[0],exUB_center[1])
p = 0
for i1 in range(exLB_center[1], exUB_center[1]):
for i0 in range(exLB_center[0], exUB_center[0]):
gridXCenter[p] = float(i0)*cellwidth_x + cellwidth_x/2.0
gridYCenter[p] = float(i1)*cellwidth_y + cellwidth_y/2.0
p = p + 1
#print 'Grid center coordinates:'
p = 0
for i1 in range(exLB_center[1], exUB_center[1]):
for i0 in range(exLB_center[0], exUB_center[0]):
#print '[{0},{1}]'.format(gridXCenter[p], gridYCenter[p])
p = p + 1
#print '\n'
return grid
def mesh_create_3x3(mesh):
'''
PRECONDITIONS: An ESMP_Mesh has been declared.
POSTCONDITIONS: A 3x3 ESMP_Mesh has been created.
3x3 Mesh
3.0 2.0 13 -------14 --------15--------16
| | | |
| 7 | 8 | 9 |
| | | |
2.5 1.5 9 ------- 10 --------11--------12
| | | |
| 4 | 5 | 6 |
| | | |
1.5 0.5 5 ------- 6 -------- 7-------- 8
| | | |
| 1 | 2 | 3 |
| | | |
1.0 0.0 1 ------- 2 -------- 3-------- 4
0.0 0.5 1.5 2.0
1.0 1.5 2.5 3.0
Node Ids at corners
Element Ids in centers
(Everything owned by PET 0)
'''
# set up a simple mesh
num_node = 16
num_elem = 9
nodeId = _NP.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])
'''
# this is for grid to mesh
nodeCoord = _NP.array([1.0,1.0, 1.5,1.0, 2.5,1.0, 3.0,1.0,
1.0,1.5, 1.5,1.5, 2.5,1.5, 3.0,1.5,
1.0,2.5, 1.5,2.5, 2.5,2.5, 3.0,2.5,
1.0,3.0, 1.5,3.0, 2.5,3.0, 3.0,3.0])
'''
# this is for mesh to grid
nodeCoord = _NP.array([0.0,0.0, 1.5,0.0, 2.5,0.0, 4.0,0.0,
0.0,1.5, 1.5,1.5, 2.5,1.5, 4.0,1.5,
0.0,2.5, 1.5,2.5, 2.5,2.5, 4.0,2.5,
0.0,4.0, 1.5,4.0, 2.5,4.0, 4.0,4.0])
nodeOwner = _NP.zeros(num_node, dtype=_NP.int32)
elemId = _NP.array([1,2,3,4,5,6,7,8,9], dtype=_NP.int32)
elemType = _NP.ones(num_elem, dtype=_NP.int32)
elemType*=ESMP.ESMP_MESHELEMTYPE_QUAD
elemConn = _NP.array([0,1,5,4,
1,2,6,5,
2,3,7,6,
4,5,9,8,
5,6,10,9,
6,7,11,10,
8,9,13,12,
9,10,14,13,
10,11,15,14], dtype=_NP.int32)
ESMP.ESMP_MeshAddNodes(mesh,num_node,nodeId,nodeCoord,nodeOwner)
ESMP.ESMP_MeshAddElements(mesh,num_elem,elemId,elemType,elemConn)
#print 'Mesh coordinates:'
for i in range(num_node):
x = nodeCoord[2*i]
y = nodeCoord[2*i+1]
#print '[{0},{1}]'.format(x, y)
#print '\n'
return mesh, nodeCoord, elemType, elemConn
def create_ESMPmesh_3x3():
'''
PRECONDITIONS: ESMP is initialized.
POSTCONDITIONS: An ESMP_Mesh (3x3) has been created and returned as 'mesh'.
'''
# Two parametric dimensions, and three spatial dimensions
mesh = ESMP.ESMP_MeshCreate(2,2)
mesh, nodeCoord, elemType, elemConn = mesh_create_3x3(mesh)
return mesh, nodeCoord, elemType, elemConn
def create_ESMPfieldgrid(grid, name):
'''
PRECONDITIONS: An ESMP_Grid has been created, and 'name' is a string that
will be used to initialize the name of a new ESMP_Field.
POSTCONDITIONS: An ESMP_Field has been created.
'''
# defaults to center staggerloc
field = ESMP.ESMP_FieldCreateGrid(grid, name)
return field
def build_analyticfieldgrid(field, grid):
'''
PRECONDITIONS: An ESMP_Field has been created.
POSTCONDITIONS: The 'field' has been initialized to an analytic field.
'''
# get the field pointer first
fieldPtr = ESMP.ESMP_FieldGetPtr(field)
# get the grid bounds and coordinate pointers
exLB, exUB = ESMP.ESMP_GridGetCoord(grid, ESMP.ESMP_STAGGERLOC_CENTER)
# get the coordinate pointers and set the coordinates
[x,y] = [0, 1]
gridXCoord = ESMP.ESMP_GridGetCoordPtr(grid, x, ESMP.ESMP_STAGGERLOC_CENTER)
gridYCoord = ESMP.ESMP_GridGetCoordPtr(grid, y, ESMP.ESMP_STAGGERLOC_CENTER)
#print "Grid center coordinates"
p = 0
for i1 in range(exLB[1], exUB[1]):
for i0 in range(exLB[0], exUB[0]):
xc = gridXCoord[p]
yc = gridYCoord[p]
fieldPtr[p] = 20.0+xc+yc
#fieldPtr[p] = 20.0+xc*yc+yc**2
#print '[{0},{1}] = {2}'.format(xc,yc,fieldPtr[p])
p = p + 1
#print "\n"
return field
def create_ESMPfield(mesh, name):
'''
PRECONDITIONS: An ESMP_Mesh has been created, and 'name' is a string that
will be used to initialize the name of a new ESMP_Field.
POSTCONDITIONS: An ESMP_Field has been created.
'''
field = ESMP.ESMP_FieldCreate(mesh, name, meshloc=ESMP.ESMP_MESHLOC_ELEMENT)
return field
def build_analyticfield(field, nodeCoord, elemType, elemConn):
'''
PRECONDITIONS: An ESMP_Field has been created.
POSTCONDITIONS: The 'field' has been initialized to an analytic field.
'''
# get the field pointer first
fieldPtr = ESMP.ESMP_FieldGetPtr(field, 0)
# set the field to a vanilla initial field for now
#print "Mesh center coordinates"
offset = 0
for i in range(field.size): # this routine assumes this field is on elements
if (elemType[i] == ESMP.ESMP_MESHELEMTYPE_TRI):
raise NameError("Cannot compute a non-constant analytic field for a mesh\
with triangular elements!")
x1 = nodeCoord[(elemConn[offset])*2]
x2 = nodeCoord[(elemConn[offset+1])*2]
y1 = nodeCoord[(elemConn[offset+1])*2+1]
y2 = nodeCoord[(elemConn[offset+3])*2+1]
x = (x1+x2)/2.0
y = (y1+y2)/2.0
fieldPtr[i] = 20.0+x+y
#fieldPtr[i] = 20.0+x*y+y**2
#print '[{0},{1}] = {2}'.format(x,y,fieldPtr[i])
offset = offset + 4
#print "\n"
return field
def run_regridding(srcfield, dstfield):
'''
PRECONDITIONS: Two ESMP_Fields have been created and a regridding operation
is desired from 'srcfield' to 'dstfield'.
POSTCONDITIONS: An ESMP regridding operation has set the data on 'dstfield'.
'''
# call the regridding functions
routehandle = ESMP.ESMP_FieldRegridStore(srcfield, dstfield,
regridmethod=ESMP.ESMP_REGRIDMETHOD_CONSERVE,
unmappedaction=ESMP.ESMP_UNMAPPEDACTION_ERROR)
ESMP.ESMP_FieldRegrid(srcfield, dstfield, routehandle)
ESMP.ESMP_FieldRegridRelease(routehandle)
return dstfield
def compare_fields(field1, field2):
'''
PRECONDITIONS: Two ESMP_Fields have been created and a comparison of the
the values is desired between 'srcfield' and 'dstfield'.
POSTCONDITIONS: The values on 'srcfield' and 'dstfield' are compared.
returns True if the fileds are comparable (success)
'''
# get the data pointers for the fields
field1ptr = ESMP.ESMP_FieldGetPtr(field1)
field2ptr = ESMP.ESMP_FieldGetPtr(field2)
# compare point values of field1 to field2
# first verify they are the same size
if (field1.size != field2.size):
raise NameError('compare_fields: Fields must be the same size!')
# initialize to True, and check for False point values
correct = True
totalErr = 0.0
for i in range(field1.size):
err = abs(field1ptr[i] - field2ptr[i])/abs(field2ptr[i])
if err > .06:
correct = False
print "ACCURACY ERROR - "+str(err)
print "field1 = {0} : field2 = {1}\n".format(field1ptr[i], field2ptr[i])
totalErr += err
if correct:
print " - PASS - Total Error = "+str(totalErr)
return True
else:
print " - FAIL - Total Error = "+str(totalErr)
return False
if __name__ == '__main__':
ESMP.ESMP_LogSet(True)
print "" # Spacer
suite = unittest.TestLoader().loadTestsFromTestCase(TestESMP_GridToMeshRegridCsrv)
unittest.TextTestRunner(verbosity = 1).run(suite)
| 33.515789 | 86 | 0.613693 |
e03a335c46211edd43cb24ddb42d950cbfd7fa71
| 1,184 |
py
|
Python
|
test/mock_module.py
|
ariffyasri/lale
|
326012c3c3dd884fae0093fe0c45596e4f9c0d72
|
[
"Apache-2.0"
] | 1 |
2020-04-28T11:27:48.000Z
|
2020-04-28T11:27:48.000Z
|
test/mock_module.py
|
ariffyasri/lale
|
326012c3c3dd884fae0093fe0c45596e4f9c0d72
|
[
"Apache-2.0"
] | null | null | null |
test/mock_module.py
|
ariffyasri/lale
|
326012c3c3dd884fae0093fe0c45596e4f9c0d72
|
[
"Apache-2.0"
] | 1 |
2020-07-30T10:06:23.000Z
|
2020-07-30T10:06:23.000Z
|
# Copyright 2019 IBM Corporation
#
# 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 sklearn.neighbors
# class that follows scikit-learn conventions but lacks schemas,
# for the purpose of testing how to wrap an operator without schemas
| 34.823529 | 74 | 0.72973 |
e03bee15bfc41f500be41ba4168c4029ea4dba20
| 3,770 |
py
|
Python
|
scripts/beautify.py
|
lukaschoebel/POTUSgen
|
7b88ba63f0ddab199937df909c5af3271a833cf3
|
[
"MIT"
] | null | null | null |
scripts/beautify.py
|
lukaschoebel/POTUSgen
|
7b88ba63f0ddab199937df909c5af3271a833cf3
|
[
"MIT"
] | 5 |
2020-03-25T08:02:45.000Z
|
2020-04-08T20:07:42.000Z
|
scripts/beautify.py
|
lukaschoebel/POTUSgen
|
7b88ba63f0ddab199937df909c5af3271a833cf3
|
[
"MIT"
] | null | null | null |
import json
import re
import sys
def beautify(name):
''' Loading, filtering and saving the JSON tweet file to a newly generated .txt file
:type: name: String
:rtype: output: .txt
'''
filename = name + '.json'
output_name = name + "_filtered.txt"
with open(filename, "r", encoding="utf-8") as input:
with open(output_name, "w", encoding="utf-8") as output:
document = json.load(input)
# Filter only the messages that are not retweeted
# >> Version i): for tweets from archive "master_XXXX.json"
# document = [x['full_text'] for x in document if x['user']['screen_name'] == 'realDonaldTrump' and 'full_text' in x]
# >> Version ii): for self-scraped tweets via https://github.com/bpb27/twitter_scraping
# document = [x['text'] for x in document if x['user']['screen_name'] == 'realDonaldTrump' and 'text' in x]
# >> Version iii): Data set from https://github.com/MatthewWolff/MarkovTweets/
document = [x['text'] for x in document]
# Clean and only include not retweeted messages
document = [deep_clean(x) for x in document if deep_clean(x) is not None]
# Preventing unicode characters by ensuring false ascii encoding
for _, value in enumerate(document):
output.write(json.dumps(value, ensure_ascii=False) + "\n")
# json.dump(document, output, ensure_ascii=False, indent=4)
print(f">> Sucessfully cleaned {filename} and saved it to {output_name}")
def deep_clean(s):
''' Deep cleaning of filtered tweets. Replaces common symbols and kills quotation marks/apostrophes.
:type: s: String
:rtype: s: String
'''
# Return None if given tweet is a retweet
if s[:2] == 'RT':
return None
# Delete all URLs because they don't make for interesting tweets.
s = re.sub(r'http[\S]*', '', s)
# Replace some common unicode symbols with raw character variants
s = re.sub(r'\\u2026', '...', s)
s = re.sub(r'', '', s)
s = re.sub(r'\\u2019', "'", s)
s = re.sub(r'\\u2018', "'", s)
s = re.sub(r"&", r"&", s)
s = re.sub(r'\\n', r"", s)
# Delete emoji modifying characters
s = re.sub(chr(127996), '', s)
s = re.sub(chr(65039), '', s)
# Kill apostrophes & punctuation because they confuse things.
s = re.sub(r"'", r"", s)
s = re.sub(r"", r"", s)
s = re.sub(r"", r"", s)
s = re.sub('[()]', r'', s)
s = re.sub(r'"', r"", s)
# Collapse multiples of certain chars
s = re.sub('([.-])+', r'\1', s)
# Pad sentence punctuation chars with whitespace
s = re.sub('([^0-9])([.,!?])([^0-9])', r'\1 \2 \3', s)
# Remove extra whitespace (incl. newlines)
s = ' '.join(s.split()).lower()
# Define emoji_pattern
emoji_pattern = re.compile("["
u"\U0001F600-\U0001F64F" # emoticons
u"\U0001F300-\U0001F5FF" # symbols & pictographs
u"\U0001F680-\U0001F6FF" # transport & map symbols
u"\U0001F1E0-\U0001F1FF" # flags (iOS)
u"\U0001F1F2-\U0001F1F4" # Macau flag
u"\U0001F1E6-\U0001F1FF" # flags
u"\U0001F600-\U0001F64F"
u"\U00002702-\U000027B0"
u"\U000024C2-\U0001F251"
u"\U0001f926-\U0001f937"
u"\U0001F1F2"
u"\U0001F1F4"
u"\U0001F620"
u"\u200d"
u"\u2640-\u2642"
"]+", flags=re.UNICODE)
s = emoji_pattern.sub(r'', s)
# Care for a special case where the first char is a "."
# return s[1:] if s[0] == "." else s
if len(s):
return s[1:] if s[0] == "." else s
return None
if __name__ == "__main__":
if len(sys.argv) - 1: beautify(sys.argv[1])
| 33.963964 | 129 | 0.571088 |
e03c2a58883f30a7a78a6973c7fd5ce571d96bba
| 1,746 |
py
|
Python
|
result2gaofentype/pkl2txt_ggm.py
|
G-Naughty/Fine-grained-OBB-Detection
|
8c82c4c178f0b6bba077ff9d906a81bf8e04789c
|
[
"Apache-2.0"
] | 2 |
2022-02-06T07:45:03.000Z
|
2022-03-11T14:18:32.000Z
|
result2gaofentype/pkl2txt_ggm.py
|
G-Naughty/Fine-grained-OBB-Detection
|
8c82c4c178f0b6bba077ff9d906a81bf8e04789c
|
[
"Apache-2.0"
] | null | null | null |
result2gaofentype/pkl2txt_ggm.py
|
G-Naughty/Fine-grained-OBB-Detection
|
8c82c4c178f0b6bba077ff9d906a81bf8e04789c
|
[
"Apache-2.0"
] | null | null | null |
import BboxToolkit as bt
import pickle
import copy
import numpy as np
path1="/home/hnu1/GGM/OBBDetection/work_dir/oriented_obb_contrast_catbalance/dets.pkl"
path2="/home/hnu1/GGM/OBBDetection/data/FaIR1M/test/annfiles/ori_annfile.pkl"#
with open(path2,'rb') as f: #/home/disk/FAIR1M_1000_split/val/annfiles/ori_annfile.pkl
data2 = pickle.load(f)
with open(path1,'rb') as f:
obbdets = pickle.load(f)
polydets=copy.deepcopy(obbdets)
for i in range(len(obbdets)):
for j in range(len(obbdets[0][1])):
data=obbdets[i][1][j]
if data.size!= 0:
polys=[]
for k in range(len(data)):
poly = bt.obb2poly(data[k][0:5])
poly=np.append(poly,data[k][5])
polys.append(poly)
else:
polys=[]
polydets[i][1][j]=polys
savepath="/home/hnu1/GGM/OBBDetection/work_dir/oriented_obb_contrast_catbalance/result_txt/"
for i in range(len(polydets)):
txtfile=savepath+polydets[i][0]+".txt"
f = open(txtfile, "w")
for j in range(len(polydets[0][1])):
if polydets[i][1][j]!=[]:
for k in range(len(polydets[i][1][j])):
f.write(str(polydets[i][1][j][k][0])+" "+
str(polydets[i][1][j][k][1])+" "+
str(polydets[i][1][j][k][2])+" "+
str(polydets[i][1][j][k][3])+" "+
str(polydets[i][1][j][k][4])+" "+
str(polydets[i][1][j][k][5])+" "+
str(polydets[i][1][j][k][6])+" "+
str(polydets[i][1][j][k][7])+" "+
str(data2["cls"][j])+" "+
str(polydets[i][1][j][k][8])+"\n")
f.close()
| 40.604651 | 95 | 0.512027 |
e03e3fafddd8bfe7f29e435a8b1b27b522698dbd
| 938 |
py
|
Python
|
initializer_3d.py
|
HarperCallahan/taichi_ferrofluid
|
6113f6c7d9d9d612b6dadc500cf91b576c2d05ea
|
[
"MIT"
] | null | null | null |
initializer_3d.py
|
HarperCallahan/taichi_ferrofluid
|
6113f6c7d9d9d612b6dadc500cf91b576c2d05ea
|
[
"MIT"
] | null | null | null |
initializer_3d.py
|
HarperCallahan/taichi_ferrofluid
|
6113f6c7d9d9d612b6dadc500cf91b576c2d05ea
|
[
"MIT"
] | null | null | null |
import taichi as ti
import utils
from apic_extension import *
| 31.266667 | 136 | 0.557569 |
e03ebf0129e76590fab9b3f72a3301cc3f5c22ca
| 1,265 |
py
|
Python
|
copy_block_example.py
|
MilesCranmer/bifrost_paper
|
654408cd7e34e7845cee58100fe459e1422e4859
|
[
"MIT"
] | null | null | null |
copy_block_example.py
|
MilesCranmer/bifrost_paper
|
654408cd7e34e7845cee58100fe459e1422e4859
|
[
"MIT"
] | null | null | null |
copy_block_example.py
|
MilesCranmer/bifrost_paper
|
654408cd7e34e7845cee58100fe459e1422e4859
|
[
"MIT"
] | null | null | null |
from copy import deepcopy
import bifrost as bf
from bifrost.pipeline import TransformBlock
from bifrost.ndarray import copy_array
bc = bf.BlockChainer()
bc.blocks.read_wav(['hey_jude.wav'], gulp_nframe=4096)
bc.custom(copy_block)(space='cuda')# $\tikzmark{gpu-start}$
bc.views.split_axis('time', 256, label='fine_time')
bc.blocks.fft(axes='fine_time', axis_labels='freq')
bc.blocks.detect(mode='scalar')
bc.blocks.transpose(['time', 'pol', 'freq'])#$\tikzmark{gpu-end}$
bc.blocks.copy(space='system')
bc.blocks.quantize('i8')
bc.blocks.write_sigproc()
pipeline = bf.get_default_pipeline()# $\tikzmark{pipeline-start}$
pipeline.shutdown_on_signals()
pipeline.run()#$\tikzmark{pipeline-end}$
| 30.853659 | 98 | 0.674308 |
e0404632a7378b088279de3e94aac11c26a9e183
| 1,540 |
py
|
Python
|
monasca_persister/conf/influxdb.py
|
zhangjianweibj/monasca-persister
|
0c5d8a7c5553001f2d38227347f482201f92c8e1
|
[
"Apache-2.0"
] | null | null | null |
monasca_persister/conf/influxdb.py
|
zhangjianweibj/monasca-persister
|
0c5d8a7c5553001f2d38227347f482201f92c8e1
|
[
"Apache-2.0"
] | 1 |
2020-03-13T12:30:29.000Z
|
2020-03-13T12:38:16.000Z
|
monasca_persister/conf/influxdb.py
|
zhangjianweibj/monasca-persister
|
0c5d8a7c5553001f2d38227347f482201f92c8e1
|
[
"Apache-2.0"
] | null | null | null |
# (C) Copyright 2016-2017 Hewlett Packard Enterprise Development LP
# Copyright 2017 FUJITSU LIMITED
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from oslo_config import cfg
influxdb_opts = [
cfg.StrOpt('database_name',
help='database name where metrics are stored',
default='mon'),
cfg.HostAddressOpt('ip_address',
help='Valid IP address or hostname '
'to InfluxDB instance'),
cfg.PortOpt('port',
help='port to influxdb',
default=8086),
cfg.StrOpt('user',
help='influxdb user ',
default='mon_persister'),
cfg.StrOpt('password',
secret=True,
help='influxdb password')]
influxdb_group = cfg.OptGroup(name='influxdb',
title='influxdb')
| 32.765957 | 69 | 0.653896 |
e040676396d83dae688cf225c1f4290cf1100f35
| 192 |
py
|
Python
|
test_print_json.py
|
huangsen365/boto3-docker
|
42d46ce4433dd037006d6b8d01db3fe444b9d8dd
|
[
"Apache-2.0"
] | null | null | null |
test_print_json.py
|
huangsen365/boto3-docker
|
42d46ce4433dd037006d6b8d01db3fe444b9d8dd
|
[
"Apache-2.0"
] | null | null | null |
test_print_json.py
|
huangsen365/boto3-docker
|
42d46ce4433dd037006d6b8d01db3fe444b9d8dd
|
[
"Apache-2.0"
] | null | null | null |
import json
your_json = '["foo", {"bar":["baz", null, 1.0, 2]}]'
parsed = json.loads(your_json)
print(type(your_json))
print(type(parsed))
#print(json.dumps(parsed, indent=4, sort_keys=True))
| 27.428571 | 52 | 0.6875 |
e041875337916a4d8560bbab0e0b68edca74373b
| 13,929 |
py
|
Python
|
src/solutions/common/integrations/cirklo/api.py
|
goubertbrent/oca-backend
|
b9f59cc02568aecb55d4b54aec05245790ea25fd
|
[
"Apache-2.0"
] | null | null | null |
src/solutions/common/integrations/cirklo/api.py
|
goubertbrent/oca-backend
|
b9f59cc02568aecb55d4b54aec05245790ea25fd
|
[
"Apache-2.0"
] | null | null | null |
src/solutions/common/integrations/cirklo/api.py
|
goubertbrent/oca-backend
|
b9f59cc02568aecb55d4b54aec05245790ea25fd
|
[
"Apache-2.0"
] | null | null | null |
# -*- coding: utf-8 -*-
# Copyright 2020 Green Valley Belgium NV
#
# 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.
#
# @@license_version:1.7@@
import cloudstorage
import logging
from babel.dates import format_datetime
from datetime import datetime
from google.appengine.ext import ndb, deferred, db
from typing import List
from xlwt import Worksheet, Workbook, XFStyle
from mcfw.cache import invalidate_cache
from mcfw.consts import REST_TYPE_TO
from mcfw.exceptions import HttpBadRequestException, HttpForbiddenException, HttpNotFoundException
from mcfw.restapi import rest
from mcfw.rpc import returns, arguments
from rogerthat.bizz.gcs import get_serving_url
from rogerthat.bizz.service import re_index_map_only
from rogerthat.consts import FAST_QUEUE
from rogerthat.models import ServiceIdentity
from rogerthat.models.settings import ServiceInfo
from rogerthat.rpc import users
from rogerthat.rpc.users import get_current_session
from rogerthat.utils import parse_date
from rogerthat.utils.service import create_service_identity_user
from shop.models import Customer
from solutions import translate
from solutions.common.bizz import SolutionModule, broadcast_updates_pending
from solutions.common.bizz.campaignmonitor import send_smart_email_without_check
from solutions.common.consts import OCA_FILES_BUCKET
from solutions.common.dal import get_solution_settings
from solutions.common.integrations.cirklo.cirklo import get_city_id_by_service_email, whitelist_merchant, \
list_whitelisted_merchants, list_cirklo_cities
from solutions.common.integrations.cirklo.models import CirkloCity, CirkloMerchant, SignupLanguageProperty, \
SignupMails, CirkloAppInfo
from solutions.common.integrations.cirklo.to import CirkloCityTO, CirkloVoucherListTO, CirkloVoucherServiceTO, \
WhitelistVoucherServiceTO
from solutions.common.restapi.services import _check_is_city
| 42.858462 | 120 | 0.710604 |
e042a55525baf01a1dd738c8dd3863fa44f09d50
| 1,624 |
py
|
Python
|
aplpy/tests/test_grid.py
|
nbrunett/aplpy
|
f5d128faf3568adea753d52c11ba43014d25d90a
|
[
"MIT"
] | null | null | null |
aplpy/tests/test_grid.py
|
nbrunett/aplpy
|
f5d128faf3568adea753d52c11ba43014d25d90a
|
[
"MIT"
] | null | null | null |
aplpy/tests/test_grid.py
|
nbrunett/aplpy
|
f5d128faf3568adea753d52c11ba43014d25d90a
|
[
"MIT"
] | 1 |
2018-02-26T03:04:19.000Z
|
2018-02-26T03:04:19.000Z
|
import matplotlib
matplotlib.use('Agg')
import numpy as np
from astropy.tests.helper import pytest
from .. import FITSFigure
| 20.049383 | 39 | 0.618842 |
e0435a8bdb5ad3ee4a83d670d6af34fbe9094657
| 12,910 |
py
|
Python
|
vz.py
|
ponyatov/vz
|
f808dd0dca9b6aa7a3e492d2ee0797ab96cd23a1
|
[
"MIT"
] | null | null | null |
vz.py
|
ponyatov/vz
|
f808dd0dca9b6aa7a3e492d2ee0797ab96cd23a1
|
[
"MIT"
] | null | null | null |
vz.py
|
ponyatov/vz
|
f808dd0dca9b6aa7a3e492d2ee0797ab96cd23a1
|
[
"MIT"
] | null | null | null |
import os, sys
Project(
title='ViZual language environment',
about='''
* object (hyper)graph interpreter
'''
).sync()
| 32.849873 | 96 | 0.449109 |
e044775152d95d5fb032af9b89fee05b4ac263fe
| 2,630 |
py
|
Python
|
src/server.py
|
FlakM/fastai_text_serving
|
8262c2c1192c5e11df2e06b494ab9cf88c1dcd2a
|
[
"Apache-2.0"
] | null | null | null |
src/server.py
|
FlakM/fastai_text_serving
|
8262c2c1192c5e11df2e06b494ab9cf88c1dcd2a
|
[
"Apache-2.0"
] | null | null | null |
src/server.py
|
FlakM/fastai_text_serving
|
8262c2c1192c5e11df2e06b494ab9cf88c1dcd2a
|
[
"Apache-2.0"
] | null | null | null |
import asyncio
import logging
import aiohttp
import uvicorn
from fastai.vision import *
from starlette.applications import Starlette
from starlette.middleware.cors import CORSMiddleware
from starlette.responses import JSONResponse
# put your url here here
model_file_url = 'https://www.dropbox.com/s/...?raw=1'
model_file_name = 'model'
path = Path(__file__).parent
logging.basicConfig(format="%(levelname)s: %(message)s", level=logging.INFO)
logger = logging.getLogger()
logger.setLevel(logging.INFO)
app = Starlette()
app.add_middleware(CORSMiddleware, allow_origins=['*'], allow_headers=['X-Requested-With', 'Content-Type'])
loop = asyncio.get_event_loop()
tasks = [asyncio.ensure_future(setup_learner())]
model, classes = loop.run_until_complete(asyncio.gather(*tasks))[0]
loop.close()
if __name__ == '__main__':
if 'serve' in sys.argv: uvicorn.run(app, host='0.0.0.0' port=4000)
| 30.941176 | 107 | 0.692776 |
e0448da70febec0759bc638d5a460760c3964480
| 402 |
py
|
Python
|
tcpserver.py
|
justforbalance/CSnet
|
c1e049f63d245c5d464a2d6e9aa7d3daf15bf2b6
|
[
"MIT"
] | null | null | null |
tcpserver.py
|
justforbalance/CSnet
|
c1e049f63d245c5d464a2d6e9aa7d3daf15bf2b6
|
[
"MIT"
] | null | null | null |
tcpserver.py
|
justforbalance/CSnet
|
c1e049f63d245c5d464a2d6e9aa7d3daf15bf2b6
|
[
"MIT"
] | null | null | null |
from socket import *
serverPort = 12001
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(('', serverPort))
serverSocket.listen(1)
print("the server is ready to receive")
while True:
connectionSocket,addr = serverSocket.accept()
sentence = connectionSocket.recv(1024).decode()
sentence = sentence.upper()
connectionSocket.send(sentence.encode())
connectionSocket.close()
| 33.5 | 51 | 0.753731 |
e044ab975c816db8531273f338dcef5b52d8c7ce
| 1,061 |
py
|
Python
|
src/geneflow/extend/local_workflow.py
|
jhphan/geneflow2
|
a39ab97e6425ee45584cfc15b5740e94a5bf7512
|
[
"Apache-2.0"
] | 7 |
2019-04-11T03:50:51.000Z
|
2020-03-27T15:59:04.000Z
|
src/geneflow/extend/local_workflow.py
|
jhphan/geneflow2
|
a39ab97e6425ee45584cfc15b5740e94a5bf7512
|
[
"Apache-2.0"
] | 1 |
2019-05-06T14:18:42.000Z
|
2019-05-08T22:06:12.000Z
|
src/geneflow/extend/local_workflow.py
|
jhphan/geneflow2
|
a39ab97e6425ee45584cfc15b5740e94a5bf7512
|
[
"Apache-2.0"
] | 6 |
2019-04-10T20:25:27.000Z
|
2021-12-16T15:59:59.000Z
|
"""This module contains the GeneFlow LocalWorkflow class."""
| 18.293103 | 60 | 0.524034 |
e0453a8ff093c7c5f6bb2239656a47c98c50cec7
| 2,849 |
py
|
Python
|
S12/tensornet/engine/ops/lr_scheduler.py
|
abishek-raju/EVA4B2
|
189f4062c85d91f43c1381087a9c89ff794e5428
|
[
"Apache-2.0"
] | 4 |
2020-06-18T13:07:19.000Z
|
2022-01-07T10:51:10.000Z
|
S12/tensornet/engine/ops/lr_scheduler.py
|
abishek-raju/EVA4B2
|
189f4062c85d91f43c1381087a9c89ff794e5428
|
[
"Apache-2.0"
] | 1 |
2021-07-31T04:34:46.000Z
|
2021-08-11T05:55:57.000Z
|
S12/tensornet/engine/ops/lr_scheduler.py
|
abishek-raju/EVA4B2
|
189f4062c85d91f43c1381087a9c89ff794e5428
|
[
"Apache-2.0"
] | 4 |
2020-08-09T07:10:46.000Z
|
2021-01-16T14:57:23.000Z
|
from torch.optim.lr_scheduler import StepLR, ReduceLROnPlateau, OneCycleLR
def step_lr(optimizer, step_size, gamma=0.1, last_epoch=-1):
"""Create LR step scheduler.
Args:
optimizer (torch.optim): Model optimizer.
step_size (int): Frequency for changing learning rate.
gamma (float): Factor for changing learning rate. (default: 0.1)
last_epoch (int): The index of last epoch. (default: -1)
Returns:
StepLR: Learning rate scheduler.
"""
return StepLR(optimizer, step_size=step_size, gamma=gamma, last_epoch=last_epoch)
def reduce_lr_on_plateau(optimizer, factor=0.1, patience=10, verbose=False, min_lr=0):
"""Create LR plateau reduction scheduler.
Args:
optimizer (torch.optim): Model optimizer.
factor (float, optional): Factor by which the learning rate will be reduced.
(default: 0.1)
patience (int, optional): Number of epoch with no improvement after which learning
rate will be will be reduced. (default: 10)
verbose (bool, optional): If True, prints a message to stdout for each update.
(default: False)
min_lr (float, optional): A scalar or a list of scalars. A lower bound on the
learning rate of all param groups or each group respectively. (default: 0)
Returns:
ReduceLROnPlateau instance.
"""
return ReduceLROnPlateau(
optimizer, factor=factor, patience=patience, verbose=verbose, min_lr=min_lr
)
def one_cycle_lr(
optimizer, max_lr, epochs, steps_per_epoch, pct_start=0.5, div_factor=10.0, final_div_factor=10000
):
"""Create One Cycle Policy for Learning Rate.
Args:
optimizer (torch.optim): Model optimizer.
max_lr (float): Upper learning rate boundary in the cycle.
epochs (int): The number of epochs to train for. This is used along with
steps_per_epoch in order to infer the total number of steps in the cycle.
steps_per_epoch (int): The number of steps per epoch to train for. This is
used along with epochs in order to infer the total number of steps in the cycle.
pct_start (float, optional): The percentage of the cycle (in number of steps)
spent increasing the learning rate. (default: 0.5)
div_factor (float, optional): Determines the initial learning rate via
initial_lr = max_lr / div_factor. (default: 10.0)
final_div_factor (float, optional): Determines the minimum learning rate via
min_lr = initial_lr / final_div_factor. (default: 1e4)
Returns:
OneCycleLR instance.
"""
return OneCycleLR(
optimizer, max_lr, epochs=epochs, steps_per_epoch=steps_per_epoch,
pct_start=pct_start, div_factor=div_factor, final_div_factor=final_div_factor
)
| 40.7 | 102 | 0.679537 |
e045d172e3aa9769db37dd0c8977af6b2b83dca1
| 10,889 |
py
|
Python
|
armi/reactor/tests/test_zones.py
|
youngmit/armi
|
67688e4e67d2a217dfc7b1ccfa64028c20b57a5b
|
[
"Apache-2.0"
] | null | null | null |
armi/reactor/tests/test_zones.py
|
youngmit/armi
|
67688e4e67d2a217dfc7b1ccfa64028c20b57a5b
|
[
"Apache-2.0"
] | null | null | null |
armi/reactor/tests/test_zones.py
|
youngmit/armi
|
67688e4e67d2a217dfc7b1ccfa64028c20b57a5b
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 2019 TerraPower, LLC
#
# 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.
"""Test for Zones"""
import copy
import unittest
import armi
from armi import settings
from armi.reactor import assemblies
from armi.reactor import blueprints
from armi.reactor import geometry
from armi.reactor import grids
from armi.reactor import reactors
from armi.reactor import zones
from armi.reactor.flags import Flags
from armi.reactor.tests import test_reactors
from armi.utils import pathTools
from armi.settings.fwSettings import globalSettings
THIS_DIR = pathTools.armiAbsDirFromName(__name__)
if __name__ == "__main__":
# import sys;sys.argv = ['', 'Zones_InReactor.test_buildRingZones']
unittest.main()
| 39.740876 | 113 | 0.629718 |
e04601e1749bc51e7e5f74ca383f947dc25e7da9
| 562 |
py
|
Python
|
islam_fitz/survey/migrations/0005_auto_20210712_2132.py
|
OmarEhab177/Islam_fitz
|
6ad0eb21549895a6fe537e8413022b82bc530c57
|
[
"MIT"
] | null | null | null |
islam_fitz/survey/migrations/0005_auto_20210712_2132.py
|
OmarEhab177/Islam_fitz
|
6ad0eb21549895a6fe537e8413022b82bc530c57
|
[
"MIT"
] | 2 |
2022-03-01T12:17:05.000Z
|
2022-03-30T12:19:55.000Z
|
islam_fitz/survey/migrations/0005_auto_20210712_2132.py
|
OmarEhab177/Islam_fitz
|
6ad0eb21549895a6fe537e8413022b82bc530c57
|
[
"MIT"
] | null | null | null |
# Generated by Django 3.1.12 on 2021-07-12 19:32
from django.db import migrations, models
| 23.416667 | 61 | 0.592527 |
e046ccaf1594be44b4bc74501cfe08b79d45a1d7
| 490 |
py
|
Python
|
Examples/WorkingWithOutlookMSGs/CreateAndSaveOutlookNote.py
|
Muzammil-khan/Aspose.Email-Python-Dotnet
|
04ca3a6f440339f3ddf316218f92d15d66f24e7e
|
[
"MIT"
] | 5 |
2019-01-28T05:17:12.000Z
|
2020-04-14T14:31:34.000Z
|
Examples/WorkingWithOutlookMSGs/CreateAndSaveOutlookNote.py
|
Muzammil-khan/Aspose.Email-Python-Dotnet
|
04ca3a6f440339f3ddf316218f92d15d66f24e7e
|
[
"MIT"
] | 1 |
2019-01-28T16:07:26.000Z
|
2021-11-25T10:59:52.000Z
|
Examples/WorkingWithOutlookMSGs/CreateAndSaveOutlookNote.py
|
Muzammil-khan/Aspose.Email-Python-Dotnet
|
04ca3a6f440339f3ddf316218f92d15d66f24e7e
|
[
"MIT"
] | 6 |
2018-07-16T14:57:34.000Z
|
2020-08-30T05:59:52.000Z
|
import aspose.email.mapi.msg as msg
from aspose.email.mapi import MapiNote, NoteSaveFormat, NoteColor
if __name__ == '__main__':
run()
| 25.789474 | 77 | 0.746939 |
e04830a8bb6dffa22a3b7aa461ea3221561a26cd
| 6,114 |
py
|
Python
|
nonebot/internal/adapter/template.py
|
mobyw/nonebot2
|
36663f1a8a51bd89f4a60110047e73719adcc73d
|
[
"MIT"
] | null | null | null |
nonebot/internal/adapter/template.py
|
mobyw/nonebot2
|
36663f1a8a51bd89f4a60110047e73719adcc73d
|
[
"MIT"
] | null | null | null |
nonebot/internal/adapter/template.py
|
mobyw/nonebot2
|
36663f1a8a51bd89f4a60110047e73719adcc73d
|
[
"MIT"
] | null | null | null |
import functools
from string import Formatter
from typing import (
TYPE_CHECKING,
Any,
Set,
Dict,
List,
Type,
Tuple,
Union,
Generic,
Mapping,
TypeVar,
Callable,
Optional,
Sequence,
cast,
overload,
)
if TYPE_CHECKING:
from .message import Message, MessageSegment
TM = TypeVar("TM", bound="Message")
TF = TypeVar("TF", str, "Message")
FormatSpecFunc = Callable[[Any], str]
FormatSpecFunc_T = TypeVar("FormatSpecFunc_T", bound=FormatSpecFunc)
def format(self, *args, **kwargs):
""""""
return self._format(args, kwargs)
def format_map(self, mapping: Mapping[str, Any]) -> TF:
""", """
return self._format([], mapping)
| 33.048649 | 85 | 0.56248 |
e048929c57d8279d48bbfdb7b6430abd2459ceab
| 243 |
py
|
Python
|
Others/code_festival/code-festival-2015-final-open/a.py
|
KATO-Hiro/AtCoder
|
cbbdb18e95110b604728a54aed83a6ed6b993fde
|
[
"CC0-1.0"
] | 2 |
2020-06-12T09:54:23.000Z
|
2021-05-04T01:34:07.000Z
|
Others/code_festival/code-festival-2015-final-open/a.py
|
KATO-Hiro/AtCoder
|
cbbdb18e95110b604728a54aed83a6ed6b993fde
|
[
"CC0-1.0"
] | 961 |
2020-06-23T07:26:22.000Z
|
2022-03-31T21:34:52.000Z
|
Others/code_festival/code-festival-2015-final-open/a.py
|
KATO-Hiro/AtCoder
|
cbbdb18e95110b604728a54aed83a6ed6b993fde
|
[
"CC0-1.0"
] | null | null | null |
# -*- coding: utf-8 -*-
if __name__ == '__main__':
main()
| 16.2 | 52 | 0.440329 |
e048b527992db2f1543fe57b684fc1f640173519
| 328 |
py
|
Python
|
python_Project/Day_16-20/test_2.py
|
Zzz-ww/Python-prac
|
c97f2c16b74a2c1df117f377a072811cc596f98b
|
[
"MIT"
] | null | null | null |
python_Project/Day_16-20/test_2.py
|
Zzz-ww/Python-prac
|
c97f2c16b74a2c1df117f377a072811cc596f98b
|
[
"MIT"
] | null | null | null |
python_Project/Day_16-20/test_2.py
|
Zzz-ww/Python-prac
|
c97f2c16b74a2c1df117f377a072811cc596f98b
|
[
"MIT"
] | null | null | null |
"""
"""
names = ['', '', '', '', '']
courses = ['', '', '']
#
scores = [[None] * len(courses) for _ in range(len(names))]
for row, name in enumerate(names):
for col, course in enumerate(courses):
scores[row][col] = float(input(f'{name}{course}:'))
print(scores)
| 25.230769 | 66 | 0.591463 |
e04a69c5ceb81801a0a97e45ded8c53330ccbc76
| 18,672 |
py
|
Python
|
asr/dataloaders/am_dataloader.py
|
Z-yq/audioSamples.github.io
|
53c474288f0db1a3acfe40ba57a4cd5f2aecbcd3
|
[
"Apache-2.0"
] | 1 |
2022-03-03T02:51:55.000Z
|
2022-03-03T02:51:55.000Z
|
asr/dataloaders/am_dataloader.py
|
Z-yq/audioSamples.github.io
|
53c474288f0db1a3acfe40ba57a4cd5f2aecbcd3
|
[
"Apache-2.0"
] | null | null | null |
asr/dataloaders/am_dataloader.py
|
Z-yq/audioSamples.github.io
|
53c474288f0db1a3acfe40ba57a4cd5f2aecbcd3
|
[
"Apache-2.0"
] | null | null | null |
import logging
import random
import numpy as np
import pypinyin
import tensorflow as tf
from augmentations.augments import Augmentation
from utils.speech_featurizers import SpeechFeaturizer
from utils.text_featurizers import TextFeaturizer
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
import time
| 43.322506 | 152 | 0.530366 |
e04c1f351c8c0376a0ea90e165d6e346051fee43
| 7,612 |
py
|
Python
|
migrations/versions/2018_04_20_data_src_refactor.py
|
AlexKouzy/ethnicity-facts-and-figures-publisher
|
18ab2495a8633f585e18e607c7f75daa564a053d
|
[
"MIT"
] | null | null | null |
migrations/versions/2018_04_20_data_src_refactor.py
|
AlexKouzy/ethnicity-facts-and-figures-publisher
|
18ab2495a8633f585e18e607c7f75daa564a053d
|
[
"MIT"
] | null | null | null |
migrations/versions/2018_04_20_data_src_refactor.py
|
AlexKouzy/ethnicity-facts-and-figures-publisher
|
18ab2495a8633f585e18e607c7f75daa564a053d
|
[
"MIT"
] | null | null | null |
"""empty message
Revision ID: 2018_04_20_data_src_refactor
Revises: 2018_04_11_add_sandbox_topic
Create Date: 2018-04-20 13:03:32.478880
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
from sqlalchemy.dialects.postgresql import ARRAY
revision = '2018_04_20_data_src_refactor'
down_revision = '2018_04_11_add_sandbox_topic'
branch_labels = None
depends_on = None
| 62.909091 | 152 | 0.759721 |
e04ce14b43e2b6f0784e3b17efec18f6e25f76d2
| 1,897 |
py
|
Python
|
lib/core/parse/cmdline.py
|
vikas-kundu/phonedict
|
6795cab0024e792340c43d95552162a985b891f6
|
[
"MIT"
] | null | null | null |
lib/core/parse/cmdline.py
|
vikas-kundu/phonedict
|
6795cab0024e792340c43d95552162a985b891f6
|
[
"MIT"
] | null | null | null |
lib/core/parse/cmdline.py
|
vikas-kundu/phonedict
|
6795cab0024e792340c43d95552162a985b891f6
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# coded by Vikas Kundu https://github.com/vikas-kundu
# -------------------------------------------
import sys
import getopt
import time
import config
from lib.core.parse import banner
from lib.core import util
from lib.core import installer
| 28.313433 | 129 | 0.461255 |
e04d583757322341dcf56eb5852389f9fd5b2748
| 1,634 |
py
|
Python
|
mistral/tests/unit/utils/test_utils.py
|
shubhamdang/mistral
|
3c83837f6ce1e4ab74fb519a63e82eaae70f9d2d
|
[
"Apache-2.0"
] | 205 |
2015-06-21T11:51:47.000Z
|
2022-03-05T04:00:04.000Z
|
mistral/tests/unit/utils/test_utils.py
|
shubhamdang/mistral
|
3c83837f6ce1e4ab74fb519a63e82eaae70f9d2d
|
[
"Apache-2.0"
] | 8 |
2015-06-23T14:47:58.000Z
|
2021-01-28T06:06:44.000Z
|
mistral/tests/unit/utils/test_utils.py
|
shubhamdang/mistral
|
3c83837f6ce1e4ab74fb519a63e82eaae70f9d2d
|
[
"Apache-2.0"
] | 110 |
2015-06-14T03:34:38.000Z
|
2021-11-11T12:12:56.000Z
|
# Copyright 2013 - Mirantis, Inc.
# Copyright 2015 - StackStorm, Inc.
# Copyright 2015 - Huawei Technologies Co. Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from mistral import exceptions as exc
from mistral.tests.unit import base
from mistral.utils import ssh_utils
from mistral_lib import utils
| 29.178571 | 77 | 0.632191 |
e04da5eb604fc61099ea52110ba3398380247444
| 2,660 |
py
|
Python
|
shoutcast_api/shoutcast_request.py
|
scls19fr/shoutcast_api
|
89a9e826b82411ae5f24ea28e1b1cb22eaaa0890
|
[
"MIT"
] | 6 |
2020-03-03T06:07:31.000Z
|
2021-11-24T19:20:12.000Z
|
shoutcast_api/shoutcast_request.py
|
scls19fr/shoutcast_api
|
89a9e826b82411ae5f24ea28e1b1cb22eaaa0890
|
[
"MIT"
] | 6 |
2020-11-17T20:30:30.000Z
|
2020-11-22T04:09:36.000Z
|
shoutcast_api/shoutcast_request.py
|
scls19fr/shoutcast_api
|
89a9e826b82411ae5f24ea28e1b1cb22eaaa0890
|
[
"MIT"
] | 1 |
2020-11-17T20:11:38.000Z
|
2020-11-17T20:11:38.000Z
|
import xmltodict
import json
from .models import Tunein
from .utils import _init_session
from .Exceptions import APIException
base_url = 'http://api.shoutcast.com'
tunein_url = 'http://yp.shoutcast.com/{base}?id={id}'
tuneins = [Tunein('/sbin/tunein-station.pls'), Tunein('/sbin/tunein-station.m3u'), Tunein('/sbin/tunein-station.xspf')]
| 38.550725 | 119 | 0.697368 |
e04ec585b764ff6cb1ec40221ed614d384e735f8
| 581 |
py
|
Python
|
django_app_permissions/management/commands/resolve_app_groups.py
|
amp89/django-app-permissions
|
11f576d2118f5b73fdbefa0675acc3374a5a9749
|
[
"MIT"
] | 2 |
2020-09-04T04:12:30.000Z
|
2020-10-20T00:12:01.000Z
|
django_app_permissions/management/commands/resolve_app_groups.py
|
amp89/django-app-permissions
|
11f576d2118f5b73fdbefa0675acc3374a5a9749
|
[
"MIT"
] | 4 |
2020-09-06T22:29:18.000Z
|
2020-09-11T01:19:50.000Z
|
django_app_permissions/management/commands/resolve_app_groups.py
|
amp89/django-app-permissions
|
11f576d2118f5b73fdbefa0675acc3374a5a9749
|
[
"MIT"
] | null | null | null |
from django.core.management.base import BaseCommand, no_translations
from django.contrib.auth.models import Group
from django.conf import settings
import sys
| 32.277778 | 95 | 0.693632 |
e04f5b24d6bd2e775a7ec943b8b4d08de4e402bf
| 34,343 |
py
|
Python
|
swift/common/db.py
|
sunzz679/swift-2.4.0--source-read
|
64355268da5265440f5f7e8d280dd8cd4c2cf2a2
|
[
"Apache-2.0"
] | null | null | null |
swift/common/db.py
|
sunzz679/swift-2.4.0--source-read
|
64355268da5265440f5f7e8d280dd8cd4c2cf2a2
|
[
"Apache-2.0"
] | null | null | null |
swift/common/db.py
|
sunzz679/swift-2.4.0--source-read
|
64355268da5265440f5f7e8d280dd8cd4c2cf2a2
|
[
"Apache-2.0"
] | null | null | null |
# Copyright (c) 2010-2012 OpenStack Foundation
#
# 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.
""" Database code for Swift """
from contextlib import contextmanager, closing
import hashlib
import logging
import os
from uuid import uuid4
import sys
import time
import errno
import six.moves.cPickle as pickle
from swift import gettext_ as _
from tempfile import mkstemp
from eventlet import sleep, Timeout
import sqlite3
from swift.common.constraints import MAX_META_COUNT, MAX_META_OVERALL_SIZE
from swift.common.utils import json, Timestamp, renamer, \
mkdirs, lock_parent_directory, fallocate
from swift.common.exceptions import LockTimeout
from swift.common.swob import HTTPBadRequest
#: Whether calls will be made to preallocate disk space for database files.
DB_PREALLOCATION = False
#: Timeout for trying to connect to a DB
BROKER_TIMEOUT = 25
#: Pickle protocol to use
PICKLE_PROTOCOL = 2
#: Max number of pending entries
PENDING_CAP = 131072
def dict_factory(crs, row):
"""
This should only be used when you need a real dict,
i.e. when you're going to serialize the results.
"""
return dict(
((col[0], row[idx]) for idx, col in enumerate(crs.description)))
def chexor(old, name, timestamp):
"""
Each entry in the account and container databases is XORed by the 128-bit
hash on insert or delete. This serves as a rolling, order-independent hash
of the contents. (check + XOR)
:param old: hex representation of the current DB hash
:param name: name of the object or container being inserted
:param timestamp: internalized timestamp of the new record
:returns: a hex representation of the new hash value
"""
if name is None:
raise Exception('name is None!')
new = hashlib.md5(('%s-%s' % (name, timestamp)).encode('utf8')).hexdigest()
return '%032x' % (int(old, 16) ^ int(new, 16))
def get_db_connection(path, timeout=30, okay_to_create=False):
"""
Returns a properly configured SQLite database connection.
:param path: path to DB
:param timeout: timeout for connection
:param okay_to_create: if True, create the DB if it doesn't exist
:returns: DB connection object
"""
try:
connect_time = time.time()
conn = sqlite3.connect(path, check_same_thread=False,
factory=GreenDBConnection, timeout=timeout)
if path != ':memory:' and not okay_to_create:
# attempt to detect and fail when connect creates the db file
stat = os.stat(path)
if stat.st_size == 0 and stat.st_ctime >= connect_time:
os.unlink(path)
raise DatabaseConnectionError(path,
'DB file created by connect?')
conn.row_factory = sqlite3.Row
conn.text_factory = str
with closing(conn.cursor()) as cur:
cur.execute('PRAGMA synchronous = NORMAL')
cur.execute('PRAGMA count_changes = OFF')
cur.execute('PRAGMA temp_store = MEMORY')
cur.execute('PRAGMA journal_mode = DELETE')
conn.create_function('chexor', 3, chexor)
except sqlite3.DatabaseError:
import traceback
raise DatabaseConnectionError(path, traceback.format_exc(),
timeout=timeout)
return conn
def _is_deleted(self, conn):
"""
Check if the database is considered deleted
:param conn: database conn
:returns: True if the DB is considered to be deleted, False otherwise
"""
raise NotImplementedError()
def is_deleted(self):
"""
Check if the DB is considered to be deleted.
:returns: True if the DB is considered to be deleted, False otherwise
"""
if self.db_file != ':memory:' and not os.path.exists(self.db_file):
return True
self._commit_puts_stale_ok()
with self.get() as conn:
return self._is_deleted(conn)
def merge_timestamps(self, created_at, put_timestamp, delete_timestamp):
"""
Used in replication to handle updating timestamps.
:param created_at: create timestamp
:param put_timestamp: put timestamp
:param delete_timestamp: delete timestamp
"""
with self.get() as conn:
old_status = self._is_deleted(conn)
conn.execute('''
UPDATE %s_stat SET created_at=MIN(?, created_at),
put_timestamp=MAX(?, put_timestamp),
delete_timestamp=MAX(?, delete_timestamp)
''' % self.db_type, (created_at, put_timestamp, delete_timestamp))
if old_status != self._is_deleted(conn):
timestamp = Timestamp(time.time())
self._update_status_changed_at(conn, timestamp.internal)
conn.commit()
def get_items_since(self, start, count):
"""
Get a list of objects in the database between start and end.
:param start: start ROWID
:param count: number to get
:returns: list of objects between start and end
"""
self._commit_puts_stale_ok()
with self.get() as conn:
curs = conn.execute('''
SELECT * FROM %s WHERE ROWID > ? ORDER BY ROWID ASC LIMIT ?
''' % self.db_contains_type, (start, count))
curs.row_factory = dict_factory
return [r for r in curs]
def get_sync(self, id, incoming=True):
"""
Gets the most recent sync point for a server from the sync table.
:param id: remote ID to get the sync_point for
:param incoming: if True, get the last incoming sync, otherwise get
the last outgoing sync
:returns: the sync point, or -1 if the id doesn't exist.
"""
with self.get() as conn:
row = conn.execute(
"SELECT sync_point FROM %s_sync WHERE remote_id=?"
% ('incoming' if incoming else 'outgoing'), (id,)).fetchone()
if not row:
return -1
return row['sync_point']
def get_syncs(self, incoming=True):
"""
Get a serialized copy of the sync table.
:param incoming: if True, get the last incoming sync, otherwise get
the last outgoing sync
:returns: list of {'remote_id', 'sync_point'}
"""
with self.get() as conn:
curs = conn.execute('''
SELECT remote_id, sync_point FROM %s_sync
''' % ('incoming' if incoming else 'outgoing'))
result = []
for row in curs:
result.append({'remote_id': row[0], 'sync_point': row[1]})
return result
def get_replication_info(self):
"""
Get information about the DB required for replication.
:returns: dict containing keys from get_info plus max_row and metadata
Note:: get_info's <db_contains_type>_count is translated to just
"count" and metadata is the raw string.
"""
info = self.get_info()
info['count'] = info.pop('%s_count' % self.db_contains_type)
info['metadata'] = self.get_raw_metadata()
info['max_row'] = self.get_max_row()
return info
#
def _commit_puts(self, item_list=None):
"""
Scan for .pending files and commit the found records by feeding them
to merge_items(). Assume that lock_parent_directory has already been
called.
:param item_list: A list of items to commit in addition to .pending
"""
if self.db_file == ':memory:' or not os.path.exists(self.pending_file):
return
if item_list is None:
item_list = []
self._preallocate()
if not os.path.getsize(self.pending_file):
if item_list:
self.merge_items(item_list)
return
with open(self.pending_file, 'r+b') as fp:
for entry in fp.read().split(':'):
if entry:
try:
self._commit_puts_load(item_list, entry)
except Exception:
self.logger.exception(
_('Invalid pending entry %(file)s: %(entry)s'),
{'file': self.pending_file, 'entry': entry})
if item_list:
self.merge_items(item_list)
try:
os.ftruncate(fp.fileno(), 0)
except OSError as err:
if err.errno != errno.ENOENT:
raise
def _commit_puts_stale_ok(self):
"""
Catch failures of _commit_puts() if broker is intended for
reading of stats, and thus does not care for pending updates.
"""
if self.db_file == ':memory:' or not os.path.exists(self.pending_file):
return
try:
with lock_parent_directory(self.pending_file,
self.pending_timeout):
self._commit_puts()
except LockTimeout:
if not self.stale_reads_ok:
raise
def _commit_puts_load(self, item_list, entry):
"""
Unmarshall the :param:entry and append it to :param:item_list.
This is implemented by a particular broker to be compatible
with its :func:`merge_items`.
"""
raise NotImplementedError
def make_tuple_for_pickle(self, record):
"""
Turn this db record dict into the format this service uses for
pending pickles.
"""
raise NotImplementedError
def merge_syncs(self, sync_points, incoming=True):
"""
Merge a list of sync points with the incoming sync table.
:param sync_points: list of sync points where a sync point is a dict of
{'sync_point', 'remote_id'}
:param incoming: if True, get the last incoming sync, otherwise get
the last outgoing sync
"""
with self.get() as conn:
for rec in sync_points:
try:
conn.execute('''
INSERT INTO %s_sync (sync_point, remote_id)
VALUES (?, ?)
''' % ('incoming' if incoming else 'outgoing'),
(rec['sync_point'], rec['remote_id']))
except sqlite3.IntegrityError:
conn.execute('''
UPDATE %s_sync SET sync_point=max(?, sync_point)
WHERE remote_id=?
''' % ('incoming' if incoming else 'outgoing'),
(rec['sync_point'], rec['remote_id']))
conn.commit()
def update_metadata(self, metadata_updates, validate_metadata=False):
"""
Updates the metadata dict for the database. The metadata dict values
are tuples of (value, timestamp) where the timestamp indicates when
that key was set to that value. Key/values will only be overwritten if
the timestamp is newer. To delete a key, set its value to ('',
timestamp). These empty keys will eventually be removed by
:func:`reclaim`
"""
#old_metadata
old_metadata = self.metadata
#
if set(metadata_updates).issubset(set(old_metadata)):
#
for key, (value, timestamp) in metadata_updates.items():
if timestamp > old_metadata[key][1]:
break
else:
#
return
#
with self.get() as conn:
try:
md = conn.execute('SELECT metadata FROM %s_stat' %
self.db_type).fetchone()[0]
md = json.loads(md) if md else {}
utf8encodekeys(md)
except sqlite3.OperationalError as err:
if 'no such column: metadata' not in str(err):
raise
conn.execute("""
ALTER TABLE %s_stat
ADD COLUMN metadata TEXT DEFAULT '' """ % self.db_type)
md = {}
#
for key, value_timestamp in metadata_updates.items():
value, timestamp = value_timestamp
if key not in md or timestamp > md[key][1]:
md[key] = value_timestamp
if validate_metadata:
DatabaseBroker.validate_metadata(md)
conn.execute('UPDATE %s_stat SET metadata = ?' % self.db_type,
(json.dumps(md),))
conn.commit()
def reclaim(self, age_timestamp, sync_timestamp):
"""
Delete rows from the db_contains_type table that are marked deleted
and whose created_at timestamp is < age_timestamp. Also deletes rows
from incoming_sync and outgoing_sync where the updated_at timestamp is
< sync_timestamp.
In addition, this calls the DatabaseBroker's :func:`_reclaim` method.
:param age_timestamp: max created_at timestamp of object rows to delete
:param sync_timestamp: max update_at timestamp of sync rows to delete
"""
if self.db_file != ':memory:' and os.path.exists(self.pending_file):
with lock_parent_directory(self.pending_file,
self.pending_timeout):
self._commit_puts()
with self.get() as conn:
conn.execute('''
DELETE FROM %s WHERE deleted = 1 AND %s < ?
''' % (self.db_contains_type, self.db_reclaim_timestamp),
(age_timestamp,))
try:
conn.execute('''
DELETE FROM outgoing_sync WHERE updated_at < ?
''', (sync_timestamp,))
conn.execute('''
DELETE FROM incoming_sync WHERE updated_at < ?
''', (sync_timestamp,))
except sqlite3.OperationalError as err:
# Old dbs didn't have updated_at in the _sync tables.
if 'no such column: updated_at' not in str(err):
raise
DatabaseBroker._reclaim(self, conn, age_timestamp)
conn.commit()
def _reclaim(self, conn, timestamp):
"""
Removes any empty metadata values older than the timestamp using the
given database connection. This function will not call commit on the
conn, but will instead return True if the database needs committing.
This function was created as a worker to limit transactions and commits
from other related functions.
:param conn: Database connection to reclaim metadata within.
:param timestamp: Empty metadata items last updated before this
timestamp will be removed.
:returns: True if conn.commit() should be called
"""
try:
md = conn.execute('SELECT metadata FROM %s_stat' %
self.db_type).fetchone()[0]
if md:
md = json.loads(md)
keys_to_delete = []
for key, (value, value_timestamp) in md.items():
if value == '' and value_timestamp < timestamp:
keys_to_delete.append(key)
if keys_to_delete:
for key in keys_to_delete:
del md[key]
conn.execute('UPDATE %s_stat SET metadata = ?' %
self.db_type, (json.dumps(md),))
return True
except sqlite3.OperationalError as err:
if 'no such column: metadata' not in str(err):
raise
return False
def update_put_timestamp(self, timestamp):
"""
Update the put_timestamp. Only modifies it if it is greater than
the current timestamp.
:param timestamp: internalized put timestamp
"""
with self.get() as conn:
conn.execute(
'UPDATE %s_stat SET put_timestamp = ?'
' WHERE put_timestamp < ?' % self.db_type,
(timestamp, timestamp))
conn.commit()
def update_status_changed_at(self, timestamp):
"""
Update the status_changed_at field in the stat table. Only
modifies status_changed_at if the timestamp is greater than the
current status_changed_at timestamp.
:param timestamp: internalized timestamp
"""
with self.get() as conn:
self._update_status_changed_at(conn, timestamp)
conn.commit()
def _update_status_changed_at(self, conn, timestamp):
conn.execute(
'UPDATE %s_stat SET status_changed_at = ?'
' WHERE status_changed_at < ?' % self.db_type,
(timestamp, timestamp))
| 38.032115 | 79 | 0.573945 |
e0530a4b979886c9eec477ba716b7cb1d54f44a5
| 12,101 |
py
|
Python
|
xdl/utils/prop_limits.py
|
mcrav/xdl
|
c120a1cf50a9b668a79b118700930eb3d60a9298
|
[
"MIT"
] | null | null | null |
xdl/utils/prop_limits.py
|
mcrav/xdl
|
c120a1cf50a9b668a79b118700930eb3d60a9298
|
[
"MIT"
] | null | null | null |
xdl/utils/prop_limits.py
|
mcrav/xdl
|
c120a1cf50a9b668a79b118700930eb3d60a9298
|
[
"MIT"
] | null | null | null |
"""Prop limits are used to validate the input given to xdl elements. For
example, a volume property should be a positive number, optionally followed by
volume units. The prop limit is used to check that input supplied is valid for
that property.
"""
import re
from typing import List, Optional
##################
# Regex patterns #
##################
#: Pattern to match a positive or negative float,
#: e.g. '0', '-1', '1', '-10.3', '10.3', '0.0' would all be matched by this
#: pattern.
FLOAT_PATTERN: str = r'([-]?[0-9]+(?:[.][0-9]+)?)'
#: Pattern to match a positive float,
#: e.g. '0', 1', '10.3', '0.0' would all be matched by this pattern, but not
#: '-10.3' or '-1'.
POSITIVE_FLOAT_PATTERN: str = r'([0-9]+(?:[.][0-9]+)?)'
#: Pattern to match boolean strings, specifically matching 'true' and 'false'
#: case insensitvely.
BOOL_PATTERN: str = r'(false|False|true|True)'
#: Pattern to match all accepted volumes units case insensitvely, or empty string.
VOLUME_UNITS_PATTERN: str = r'(l|L|litre|litres|liter|liters|ml|mL|cm3|cc|milliltre|millilitres|milliliter|milliliters|cl|cL|centiltre|centilitres|centiliter|centiliters|dl|dL|deciltre|decilitres|deciliter|deciliters|ul|uL|l|L|microlitre|microlitres|microliter|microliters)?'
#: Pattern to match all accepted mass units, or empty string.
MASS_UNITS_PATTERN: str = r'(g|gram|grams|kg|kilogram|kilograms|mg|milligram|milligrams|ug|g|microgram|micrograms)?'
#: Pattern to match all accepted temperature units, or empty string.
TEMP_UNITS_PATTERN: str = r'(C|K|F)?'
#: Pattern to match all accepted time units, or empty string.
TIME_UNITS_PATTERN = r'(days|day|h|hr|hrs|hour|hours|m|min|mins|minute|minutes|s|sec|secs|second|seconds)?'
#: Pattern to match all accepted pressure units, or empty string.
PRESSURE_UNITS_PATTERN = r'(mbar|bar|torr|Torr|mmhg|mmHg|atm|Pa|pa)?'
#: Pattern to match all accepted rotation speed units, or empty string.
ROTATION_SPEED_UNITS_PATTERN = r'(rpm|RPM)?'
#: Pattern to match all accepted length units, or empty string.
DISTANCE_UNITS_PATTERN = r'(nm|m|mm|cm|m|km)?'
#: Pattern to match all accepted mol units, or empty string.
MOL_UNITS_PATTERN = r'(mmol|mol)?'
###############
# Prop limits #
###############
def generate_quantity_units_pattern(
quantity_pattern: str,
units_pattern: str,
hint: Optional[str] = '',
default: Optional[str] = ''
) -> PropLimit:
"""
Convenience function to generate PropLimit object for different quantity
types, i.e. for variations on the number followed by unit pattern.
Args:
quantity_pattern (str): Pattern to match the number expected. This will
typically be ``POSITIVE_FLOAT_PATTERN`` or ``FLOAT_PATTERN``.
units_pattern (str): Pattern to match the units expected or empty
string. Empty string is matched as not including units is allowed
as in this case standard units are used.
hint (str): Hint for the prop limit to tell the user what correct input
should look like in the case of an errror.
default (str): Default value for the prop limit, should use standard
units for the prop involved.
"""
return PropLimit(
regex=r'^((' + quantity_pattern + r'[ ]?'\
+ units_pattern + r'$)|(^' + quantity_pattern + r'))$',
hint=hint,
default=default
)
# NOTE: It is important here that defaults use the standard unit for that
# quantity type as XDL app uses this to add in default units.
#: Prop limit for volume props.
VOLUME_PROP_LIMIT: PropLimit = PropLimit(
regex=r'^(all|(' + POSITIVE_FLOAT_PATTERN + r'[ ]?'\
+ VOLUME_UNITS_PATTERN + r')|(' + POSITIVE_FLOAT_PATTERN + r'))$',
hint='Expecting number followed by standard volume units, e.g. "5.5 mL"',
default='0 mL',
)
#: Prop limit for mass props.
MASS_PROP_LIMIT: PropLimit = generate_quantity_units_pattern(
POSITIVE_FLOAT_PATTERN,
MASS_UNITS_PATTERN,
hint='Expecting number followed by standard mass units, e.g. "2.3 g"',
default='0 g'
)
#: Prop limit for mol props.
MOL_PROP_LIMIT: PropLimit = generate_quantity_units_pattern(
POSITIVE_FLOAT_PATTERN,
MOL_UNITS_PATTERN,
hint='Expecting number followed by mol or mmol, e.g. "2.3 mol".',
default='0 mol',
)
#: Prop limit for temp props.
TEMP_PROP_LIMIT: PropLimit = generate_quantity_units_pattern(
FLOAT_PATTERN,
TEMP_UNITS_PATTERN,
hint='Expecting number in degrees celsius or number followed by standard temperature units, e.g. "25", "25C", "298 K".',
default='25C',
)
#: Prop limit for time props.
TIME_PROP_LIMIT: PropLimit = generate_quantity_units_pattern(
POSITIVE_FLOAT_PATTERN,
TIME_UNITS_PATTERN,
hint='Expecting number followed by standard time units, e.g. "15 mins", "3 hrs".',
default='0 secs'
)
#: Prop limit for pressure props.
PRESSURE_PROP_LIMIT: PropLimit = generate_quantity_units_pattern(
POSITIVE_FLOAT_PATTERN,
PRESSURE_UNITS_PATTERN,
hint='Expecting number followed by standard pressure units, e.g. "50 mbar", "1 atm".',
default='1013.25 mbar'
)
#: Prop limit for rotation speed props.
ROTATION_SPEED_PROP_LIMIT: PropLimit = generate_quantity_units_pattern(
POSITIVE_FLOAT_PATTERN,
ROTATION_SPEED_UNITS_PATTERN,
hint='Expecting RPM value, e.g. "400 RPM".',
default='400 RPM',
)
#: Prop limit for wavelength props.
WAVELENGTH_PROP_LIMIT: PropLimit = generate_quantity_units_pattern(
POSITIVE_FLOAT_PATTERN,
DISTANCE_UNITS_PATTERN,
hint='Expecting wavelength, e.g. "400 nm".',
default='400 nm'
)
#: Prop limit for any props requiring a positive integer such as ``repeats``.
#: Used if no explicit property is given and prop type is ``int``.
POSITIVE_INT_PROP_LIMIT: PropLimit = PropLimit(
r'[0-9]+',
hint='Expecting positive integer value, e.g. "3"',
default='1',
)
#: Prop limit for any props requiring a positive float. Used if no explicit
#: prop type is given and prop type is ``float``.
POSITIVE_FLOAT_PROP_LIMIT: PropLimit = PropLimit(
regex=POSITIVE_FLOAT_PATTERN,
hint='Expecting positive float value, e.g. "3", "3.5"',
default='0',
)
#: Prop limit for any props requiring a boolean value. Used if no explicit prop
#: type is given and prop type is ``bool``.
BOOL_PROP_LIMIT: PropLimit = PropLimit(
BOOL_PATTERN,
hint='Expecting one of "false" or "true".',
default='false',
)
#: Prop limit for ``WashSolid`` ``stir`` prop. This is a special case as the
#: value can be ``True``, ``False`` or ``'solvent'``.
WASH_SOLID_STIR_PROP_LIMIT: PropLimit = PropLimit(
r'(' + BOOL_PATTERN + r'|solvent)',
enum=['true', 'solvent', 'false'],
hint='Expecting one of "true", "false" or "solvent".',
default='True'
)
#: Prop limit for ``Separate`` ``purpose`` prop. One of 'extract' or 'wash'.
SEPARATION_PURPOSE_PROP_LIMIT: PropLimit = PropLimit(enum=['extract', 'wash'])
#: Prop limit for ``Separate`` ``product_phase`` prop. One of 'top' or 'bottom'.
SEPARATION_PRODUCT_PHASE_PROP_LIMIT: PropLimit = PropLimit(enum=['top', 'bottom'])
#: Prop limit for ``Add`` ``purpose`` prop. One of 'neutralize', 'precipitate',
#: 'dissolve', 'basify', 'acidify' or 'dilute'.
ADD_PURPOSE_PROP_LIMIT = PropLimit(
enum=[
'neutralize',
'precipitate',
'dissolve',
'basify',
'acidify',
'dilute',
]
)
#: Prop limit for ``HeatChill`` ``purpose`` prop. One of 'control-exotherm',
#: 'reaction' or 'unstable-reagent'.
HEATCHILL_PURPOSE_PROP_LIMIT = PropLimit(
enum=['control-exotherm', 'reaction', 'unstable-reagent']
)
#: Prop limit for ``Stir`` ``purpose`` prop. 'dissolve' is only option.
STIR_PURPOSE_PROP_LIMIT = PropLimit(
enum=['dissolve']
)
#: Prop limit for ``Reagent`` ``role`` prop. One of 'solvent', 'reagent',
#: 'catalyst', 'substrate', 'acid', 'base' or 'activating-agent'.
REAGENT_ROLE_PROP_LIMIT = PropLimit(
enum=[
'solvent',
'reagent',
'catalyst',
'substrate',
'acid',
'base',
'activating-agent'
]
)
#: Prop limit for ``Component`` ``component_type`` prop. One of 'reactor',
#: 'filter', 'separator', 'rotavap' or 'flask'.
COMPONENT_TYPE_PROP_LIMIT: PropLimit = PropLimit(
enum=['reactor', 'filter', 'separator', 'rotavap', 'flask']
)
#: Pattern matching a float of value 100, e.g. '100', '100.0', '100.000' would
#: all be matched.
_hundred_float: str = r'(100(?:[.][0]+)?)'
#: Pattern matching any float between 10.000 and 99.999.
_ten_to_ninety_nine_float: str = r'([0-9][0-9](?:[.][0-9]+)?)'
#: Pattern matching any float between 0 and 9.999.
_zero_to_ten_float: str = r'([0-9](?:[.][0-9]+)?)'
#: Pattern matching float between 0 and 100. Used for percentages.
PERCENT_RANGE_PROP_LIMIT: PropLimit = PropLimit(
r'^(' + _hundred_float + '|'\
+ _ten_to_ninety_nine_float + '|' + _zero_to_ten_float + ')$',
hint='Expecting number from 0-100 representing a percentage, e.g. "50", "8.5".',
default='0',
)
| 35.591176 | 277 | 0.650029 |
e0531fdc3eeb8a1247c13837ac5c2a532816fd2e
| 3,884 |
py
|
Python
|
dit/utils/bindargs.py
|
leoalfonso/dit
|
e7d5f680b3f170091bb1e488303f4255eeb11ef4
|
[
"BSD-3-Clause"
] | 1 |
2021-03-15T08:51:42.000Z
|
2021-03-15T08:51:42.000Z
|
dit/utils/bindargs.py
|
leoalfonso/dit
|
e7d5f680b3f170091bb1e488303f4255eeb11ef4
|
[
"BSD-3-Clause"
] | null | null | null |
dit/utils/bindargs.py
|
leoalfonso/dit
|
e7d5f680b3f170091bb1e488303f4255eeb11ef4
|
[
"BSD-3-Clause"
] | null | null | null |
"""
Provides usable args and kwargs from inspect.getcallargs.
For Python 3.3 and above, this module is unnecessary and can be achieved using
features from PEP 362:
http://www.python.org/dev/peps/pep-0362/
For example, to override a parameter of some function:
>>> import inspect
>>> def func(a, b=1, c=2, d=3):
... return a, b, c, d
...
>>> def override_c(*args, **kwargs):
... sig = inspect.signature(override)
... ba = sig.bind(*args, **kwargs)
... ba['c'] = 10
... return func(*ba.args, *ba.kwargs)
...
>>> override_c(0, c=3)
(0, 1, 10, 3)
Also useful:
http://www.python.org/dev/peps/pep-3102/
"""
import sys
import inspect
from inspect import getcallargs
try:
from inspect import getfullargspec
except ImportError:
# Python 2.X
from collections import namedtuple
from inspect import getargspec
FullArgSpec = namedtuple('FullArgSpec',
'args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations')
def bindcallargs_leq32(_fUnCtIoN_, *args, **kwargs):
"""Binds arguments and keyword arguments to a function or method.
Returns a tuple (bargs, bkwargs) suitable for manipulation and passing
to the specified function.
`bargs` consists of the bound args, varargs, and kwonlyargs from
getfullargspec. `bkwargs` consists of the bound varkw from getfullargspec.
Both can be used in a call to the specified function. Any default
parameter values are included in the output.
Examples
--------
>>> def func(a, b=3, *args, **kwargs):
... pass
>>> bindcallargs(func, 5)
((5, 3), {})
>>> bindcallargs(func, 5, 4, 3, 2, 1, hello='there')
((5, 4, 3, 2, 1), {'hello': 'there'})
>>> args, kwargs = bindcallargs(func, 5)
>>> kwargs['b'] = 5 # overwrite default value for b
>>> func(*args, **kwargs)
"""
# It is necessary to choose an unlikely variable name for the function.
# The reason is that any kwarg by the same name will cause a TypeError
# due to multiple values being passed for that argument name.
func = _fUnCtIoN_
callargs = getcallargs(func, *args, **kwargs)
spec = getfullargspec(func)
# Construct all args and varargs and use them in bargs
bargs = [callargs[arg] for arg in spec.args]
if spec.varargs is not None:
bargs.extend(callargs[spec.varargs])
bargs = tuple(bargs)
# Start with kwonlyargs.
bkwargs = {kwonlyarg: callargs[kwonlyarg] for kwonlyarg in spec.kwonlyargs}
# Add in kwonlydefaults for unspecified kwonlyargs only.
# Since keyword only arguements aren't allowed in python2, and we
# don't support python 3.0, 3.1, 3.2, this should never be executed:
if spec.kwonlydefaults is not None: # pragma: no cover
bkwargs.update({k: v for k, v in spec.kwonlydefaults.items()
if k not in bkwargs})
# Add in varkw.
if spec.varkw is not None:
bkwargs.update(callargs[spec.varkw])
return bargs, bkwargs
if sys.version_info[0:2] < (3,3):
bindcallargs = bindcallargs_leq32
else:
bindcallargs = bindcallargs_geq33
| 31.072 | 79 | 0.65036 |
e053d13d8a4cd7c86d2670f87f97133354905c98
| 36,370 |
py
|
Python
|
tests/python/gaia-ui-tests/gaiatest/gaia_test.py
|
AmyYLee/gaia
|
a5dbae8235163d7f985bdeb7d649268f02749a8b
|
[
"Apache-2.0"
] | 1 |
2020-04-06T13:02:09.000Z
|
2020-04-06T13:02:09.000Z
|
tests/python/gaia-ui-tests/gaiatest/gaia_test.py
|
AmyYLee/gaia
|
a5dbae8235163d7f985bdeb7d649268f02749a8b
|
[
"Apache-2.0"
] | null | null | null |
tests/python/gaia-ui-tests/gaiatest/gaia_test.py
|
AmyYLee/gaia
|
a5dbae8235163d7f985bdeb7d649268f02749a8b
|
[
"Apache-2.0"
] | null | null | null |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import json
import os
import sys
import time
from marionette import MarionetteTestCase
from marionette.by import By
from marionette.errors import NoSuchElementException
from marionette.errors import ElementNotVisibleException
from marionette.errors import TimeoutException
from marionette.errors import StaleElementException
from marionette.errors import InvalidResponseException
import mozdevice
def remove_all_contacts(self, default_script_timeout=60000):
self.marionette.switch_to_frame()
self.marionette.set_script_timeout(max(default_script_timeout, 1000 * len(self.all_contacts)))
result = self.marionette.execute_async_script('return GaiaDataLayer.removeAllContacts();', special_powers=True)
assert result, 'Unable to remove all contacts'
self.marionette.set_script_timeout(default_script_timeout)
def get_setting(self, name):
return self.marionette.execute_async_script('return GaiaDataLayer.getSetting("%s")' % name, special_powers=True)
def get_bool_pref(self, name):
"""Returns the value of a Gecko boolean pref, which is different from a Gaia setting."""
return self._get_pref('Bool', name)
def set_bool_pref(self, name, value):
"""Sets the value of a Gecko boolean pref, which is different from a Gaia setting."""
return self._set_pref('Bool', name, value)
def get_int_pref(self, name):
"""Returns the value of a Gecko integer pref, which is different from a Gaia setting."""
return self._get_pref('Int', name)
def set_int_pref(self, name, value):
"""Sets the value of a Gecko integer pref, which is different from a Gaia setting."""
return self._set_pref('Int', name, value)
def get_char_pref(self, name):
"""Returns the value of a Gecko string pref, which is different from a Gaia setting."""
return self._get_pref('Char', name)
def set_char_pref(self, name, value):
"""Sets the value of a Gecko string pref, which is different from a Gaia setting."""
return self._set_pref('Char', name, value)
def connect_to_cell_data(self):
self.marionette.switch_to_frame()
result = self.marionette.execute_async_script("return GaiaDataLayer.connectToCellData()", special_powers=True)
assert result, 'Unable to connect to cell data'
def disable_cell_data(self):
self.marionette.switch_to_frame()
result = self.marionette.execute_async_script("return GaiaDataLayer.disableCellData()", special_powers=True)
assert result, 'Unable to disable cell data'
def delete_all_sms(self):
self.marionette.switch_to_frame()
return self.marionette.execute_async_script("return GaiaDataLayer.deleteAllSms();", special_powers=True)
def delete_all_call_log_entries(self):
"""The call log needs to be open and focused in order for this to work."""
self.marionette.execute_script('window.wrappedJSObject.RecentsDBManager.deleteAll();')
def kill_active_call(self):
self.marionette.execute_script("var telephony = window.navigator.mozTelephony; " +
"if(telephony.active) telephony.active.hangUp();")
def sdcard_files(self, extension=''):
files = self.marionette.execute_async_script(
'return GaiaDataLayer.getAllSDCardFiles();')
if len(extension):
return [filename for filename in files if filename.endswith(extension)]
return files
def send_sms(self, number, message):
import json
number = json.dumps(number)
message = json.dumps(message)
result = self.marionette.execute_async_script('return GaiaDataLayer.sendSMS(%s, %s)' % (number, message), special_powers=True)
assert result, 'Unable to send SMS to recipient %s with text %s' % (number, message)
class GaiaDevice(object):
def push_file(self, source, count=1, destination='', progress=None):
if not destination.count('.') > 0:
destination = '/'.join([destination, source.rpartition(os.path.sep)[-1]])
self.manager.mkDirs(destination)
self.manager.pushFile(source, destination)
if count > 1:
for i in range(1, count + 1):
remote_copy = '_%s.'.join(iter(destination.split('.'))) % i
self.manager._checkCmd(['shell', 'dd', 'if=%s' % destination, 'of=%s' % remote_copy])
if progress:
progress.update(i)
self.manager.removeFile(destination)
class GaiaTestCase(MarionetteTestCase):
_script_timeout = 60000
_search_timeout = 10000
# deafult timeout in seconds for the wait_for methods
_default_timeout = 30
def change_orientation(self, orientation):
""" There are 4 orientation states which the phone can be passed in:
portrait-primary(which is the default orientation), landscape-primary, portrait-secondary and landscape-secondary
"""
self.marionette.execute_async_script("""
if (arguments[0] === arguments[1]) {
marionetteScriptFinished();
}
else {
var expected = arguments[1];
window.screen.onmozorientationchange = function(e) {
console.log("Received 'onmozorientationchange' event.");
waitFor(
function() {
window.screen.onmozorientationchange = null;
marionetteScriptFinished();
},
function() {
return window.screen.mozOrientation === expected;
}
);
};
console.log("Changing orientation to '" + arguments[1] + "'.");
window.screen.mozLockOrientation(arguments[1]);
};""", script_args=[self.screen_orientation, orientation])
def wait_for_element_present(self, by, locator, timeout=_default_timeout):
timeout = float(timeout) + time.time()
while time.time() < timeout:
time.sleep(0.5)
try:
return self.marionette.find_element(by, locator)
except NoSuchElementException:
pass
else:
raise TimeoutException(
'Element %s not present before timeout' % locator)
def wait_for_element_not_present(self, by, locator, timeout=_default_timeout):
timeout = float(timeout) + time.time()
while time.time() < timeout:
time.sleep(0.5)
try:
self.marionette.find_element(by, locator)
except NoSuchElementException:
break
else:
raise TimeoutException(
'Element %s still present after timeout' % locator)
def wait_for_element_displayed(self, by, locator, timeout=_default_timeout):
timeout = float(timeout) + time.time()
e = None
while time.time() < timeout:
time.sleep(0.5)
try:
if self.marionette.find_element(by, locator).is_displayed():
break
except (NoSuchElementException, StaleElementException) as e:
pass
else:
# This is an effortless way to give extra debugging information
if isinstance(e, NoSuchElementException):
raise TimeoutException('Element %s not present before timeout' % locator)
else:
raise TimeoutException('Element %s present but not displayed before timeout' % locator)
def wait_for_element_not_displayed(self, by, locator, timeout=_default_timeout):
timeout = float(timeout) + time.time()
while time.time() < timeout:
time.sleep(0.5)
try:
if not self.marionette.find_element(by, locator).is_displayed():
break
except StaleElementException:
pass
except NoSuchElementException:
break
else:
raise TimeoutException(
'Element %s still visible after timeout' % locator)
def wait_for_condition(self, method, timeout=_default_timeout,
message="Condition timed out"):
"""Calls the method provided with the driver as an argument until the \
return value is not False."""
end_time = time.time() + timeout
while time.time() < end_time:
try:
value = method(self.marionette)
if value:
return value
except (NoSuchElementException, StaleElementException):
pass
time.sleep(0.5)
else:
raise TimeoutException(message)
def is_element_present(self, by, locator):
try:
self.marionette.find_element(by, locator)
return True
except:
return False
def is_element_displayed(self, by, locator):
try:
return self.marionette.find_element(by, locator).is_displayed()
except (NoSuchElementException, ElementNotVisibleException):
return False
| 41.376564 | 139 | 0.648474 |
e053d242f75ab9ddd50217184c0c2cd558a9aad9
| 5,591 |
py
|
Python
|
library/__mozilla__/pyjamas/DOM.py
|
certik/pyjamas
|
5bb72e63e50f09743ac986f4c9690ba50c499ba9
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
library/__mozilla__/pyjamas/DOM.py
|
certik/pyjamas
|
5bb72e63e50f09743ac986f4c9690ba50c499ba9
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
library/__mozilla__/pyjamas/DOM.py
|
certik/pyjamas
|
5bb72e63e50f09743ac986f4c9690ba50c499ba9
|
[
"ECL-2.0",
"Apache-2.0"
] | 1 |
2019-08-13T20:32:25.000Z
|
2019-08-13T20:32:25.000Z
|
# This is what is in GWT 1.5 for getAbsoluteLeft. err...
#"""
# // We cannot use DOMImpl here because offsetLeft/Top return erroneous
# // values when overflow is not visible. We have to difference screenX
# // here due to a change in getBoxObjectFor which causes inconsistencies
# // on whether the calculations are inside or outside of the element's
# // border.
# try {
# return $doc.getBoxObjectFor(elem).screenX
# - $doc.getBoxObjectFor($doc.documentElement).screenX;
# } catch (e) {
# // This works around a bug in the FF3 betas. The bug
# // should be fixed before they release, so this can
# // be removed at a later date.
# // https://bugzilla.mozilla.org/show_bug.cgi?id=409111
# // DOMException.WRONG_DOCUMENT_ERR == 4
# if (e.code == 4) {
# return 0;
# }
# throw e;
# }
#"""
# This is what is in GWT 1.5 for getAbsoluteTop. err...
#"""
# // We cannot use DOMImpl here because offsetLeft/Top return erroneous
# // values when overflow is not visible. We have to difference screenY
# // here due to a change in getBoxObjectFor which causes inconsistencies
# // on whether the calculations are inside or outside of the element's
# // border.
# try {
# return $doc.getBoxObjectFor(elem).screenY
# - $doc.getBoxObjectFor($doc.documentElement).screenY;
# } catch (e) {
# // This works around a bug in the FF3 betas. The bug
# // should be fixed before they release, so this can
# // be removed at a later date.
# // https://bugzilla.mozilla.org/show_bug.cgi?id=409111
# // DOMException.WRONG_DOCUMENT_ERR == 4
# if (e.code == 4) {
# return 0;
# }
# throw e;
# }
#"""
| 29.119792 | 84 | 0.571275 |
e05432743bd72af1411301793f19ae278f8a6b5a
| 485 |
py
|
Python
|
apps/vendors/migrations/0090_auto_20160610_2125.py
|
ExpoAshique/ProveBanking__s
|
f0b45fffea74d00d14014be27aa50fe5f42f6903
|
[
"MIT"
] | null | null | null |
apps/vendors/migrations/0090_auto_20160610_2125.py
|
ExpoAshique/ProveBanking__s
|
f0b45fffea74d00d14014be27aa50fe5f42f6903
|
[
"MIT"
] | null | null | null |
apps/vendors/migrations/0090_auto_20160610_2125.py
|
ExpoAshique/ProveBanking__s
|
f0b45fffea74d00d14014be27aa50fe5f42f6903
|
[
"MIT"
] | null | null | null |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-06-10 21:25
from __future__ import unicode_literals
from django.db import migrations, models
| 23.095238 | 86 | 0.626804 |
e0543e59c4fcb122d63759114f58b779ede6cdce
| 540 |
py
|
Python
|
graph/articulation_points.py
|
fujihiraryo/library
|
cdb01e710219d7111f890d09f89531916dd03533
|
[
"MIT"
] | null | null | null |
graph/articulation_points.py
|
fujihiraryo/library
|
cdb01e710219d7111f890d09f89531916dd03533
|
[
"MIT"
] | 4 |
2020-12-16T10:00:00.000Z
|
2021-02-12T12:51:50.000Z
|
graph/articulation_points.py
|
fujihiraryo/python-kyopro-library
|
cdb01e710219d7111f890d09f89531916dd03533
|
[
"MIT"
] | null | null | null |
from depth_first_search import DFS
| 25.714286 | 62 | 0.522222 |
e055245acd2ad8d01c1ab4aacd02a9a0e3b9e3b6
| 1,558 |
py
|
Python
|
database.py
|
AndreAngelucci/popcorn_time_bot
|
710b77b59d6c62569c1bf6984c7cf9adac8ea840
|
[
"MIT"
] | null | null | null |
database.py
|
AndreAngelucci/popcorn_time_bot
|
710b77b59d6c62569c1bf6984c7cf9adac8ea840
|
[
"MIT"
] | 1 |
2021-06-02T00:39:42.000Z
|
2021-06-02T00:39:42.000Z
|
database.py
|
AndreAngelucci/popcorn_time_bot
|
710b77b59d6c62569c1bf6984c7cf9adac8ea840
|
[
"MIT"
] | null | null | null |
import pymongo
from conf import Configuracoes
| 39.948718 | 88 | 0.617458 |
e0553357877f320fcfcfc9bb4fdd3aa6b5cc2f78
| 2,947 |
py
|
Python
|
sensor_core/sleep.py
|
JorisHerbots/niip_iot_zombie_apocalypse
|
3ff848f3dab1dde9d2417d0a2c56a76a85e18920
|
[
"MIT"
] | null | null | null |
sensor_core/sleep.py
|
JorisHerbots/niip_iot_zombie_apocalypse
|
3ff848f3dab1dde9d2417d0a2c56a76a85e18920
|
[
"MIT"
] | null | null | null |
sensor_core/sleep.py
|
JorisHerbots/niip_iot_zombie_apocalypse
|
3ff848f3dab1dde9d2417d0a2c56a76a85e18920
|
[
"MIT"
] | null | null | null |
import machine
import pycom
import utime
from exceptions import Exceptions
| 32.032609 | 121 | 0.646759 |
e0554c3395746111d418fbf380163f0e080e4265
| 1,260 |
py
|
Python
|
pytorch_gleam/search/rerank_format.py
|
Supermaxman/pytorch-gleam
|
8b0d8dddc812e8ae120c9760fd44fe93da3f902d
|
[
"Apache-2.0"
] | null | null | null |
pytorch_gleam/search/rerank_format.py
|
Supermaxman/pytorch-gleam
|
8b0d8dddc812e8ae120c9760fd44fe93da3f902d
|
[
"Apache-2.0"
] | null | null | null |
pytorch_gleam/search/rerank_format.py
|
Supermaxman/pytorch-gleam
|
8b0d8dddc812e8ae120c9760fd44fe93da3f902d
|
[
"Apache-2.0"
] | null | null | null |
import torch
import argparse
from collections import defaultdict
import os
import json
if __name__ == '__main__':
main()
| 25.714286 | 86 | 0.743651 |
e055f89145eb203a0a63bfdad54931948d02ec37
| 388 |
py
|
Python
|
des036.py
|
LeonardoPereirajr/Curso_em_video_Python
|
9d8a97ba3389c8e86b37dfd089fab5d04adc146d
|
[
"MIT"
] | null | null | null |
des036.py
|
LeonardoPereirajr/Curso_em_video_Python
|
9d8a97ba3389c8e86b37dfd089fab5d04adc146d
|
[
"MIT"
] | null | null | null |
des036.py
|
LeonardoPereirajr/Curso_em_video_Python
|
9d8a97ba3389c8e86b37dfd089fab5d04adc146d
|
[
"MIT"
] | null | null | null |
casa = int(input('Qual o valor da casa? '))
sal = int(input('Qual seu salario? '))
prazo = int(input('Quantos meses deseja pagar ? '))
parcela = casa/prazo
margem = sal* (30/100)
if parcela > margem:
print('Este negocio no foi aprovado, aumente o prazo .')
else:
print("Negocio aprovado pois a parcela de R$ {} e voce pode pagar R$ {} mensais".format(parcela,margem))
| 38.8 | 111 | 0.664948 |
e05606e62a7f260ca58d2f3413562fa3ee898b64
| 1,000 |
py
|
Python
|
HackBitApp/migrations/0003_roadmap.py
|
SukhadaM/HackBit-Interview-Preparation-Portal
|
f4c6b0d7168a4ea4ffcf1569183b1614752d9946
|
[
"MIT"
] | null | null | null |
HackBitApp/migrations/0003_roadmap.py
|
SukhadaM/HackBit-Interview-Preparation-Portal
|
f4c6b0d7168a4ea4ffcf1569183b1614752d9946
|
[
"MIT"
] | null | null | null |
HackBitApp/migrations/0003_roadmap.py
|
SukhadaM/HackBit-Interview-Preparation-Portal
|
f4c6b0d7168a4ea4ffcf1569183b1614752d9946
|
[
"MIT"
] | null | null | null |
# Generated by Django 3.1.7 on 2021-03-27 18:22
from django.db import migrations, models
| 34.482759 | 114 | 0.571 |
e0573523b4d451bef7e8afb67ef1d49c8d3db2d3
| 1,051 |
py
|
Python
|
Other_Python/Kernel_Methods/matrix_operations.py
|
Romit-Maulik/Tutorials-Demos-Practice
|
a58ddc819f24a16f7059e63d7f201fc2cd23e03a
|
[
"MIT"
] | null | null | null |
Other_Python/Kernel_Methods/matrix_operations.py
|
Romit-Maulik/Tutorials-Demos-Practice
|
a58ddc819f24a16f7059e63d7f201fc2cd23e03a
|
[
"MIT"
] | null | null | null |
Other_Python/Kernel_Methods/matrix_operations.py
|
Romit-Maulik/Tutorials-Demos-Practice
|
a58ddc819f24a16f7059e63d7f201fc2cd23e03a
|
[
"MIT"
] | null | null | null |
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 22 14:36:48 2020
@author: matth
"""
import autograd.numpy as np
#%% Kernel operations
# Returns the norm of the pairwise difference
# Returns the pairwise inner product
if __name__ == '__main__':
print('This is the matrix operations file')
| 25.02381 | 79 | 0.676499 |
e0576a003dfb918c45d8ae2afa80c98a64287387
| 2,371 |
py
|
Python
|
cors/resources/cors-makeheader.py
|
meyerweb/wpt
|
f04261533819893c71289614c03434c06856c13e
|
[
"BSD-3-Clause"
] | 14,668 |
2015-01-01T01:57:10.000Z
|
2022-03-31T23:33:32.000Z
|
cors/resources/cors-makeheader.py
|
meyerweb/wpt
|
f04261533819893c71289614c03434c06856c13e
|
[
"BSD-3-Clause"
] | 7,642 |
2018-05-28T09:38:03.000Z
|
2022-03-31T20:55:48.000Z
|
cors/resources/cors-makeheader.py
|
meyerweb/wpt
|
f04261533819893c71289614c03434c06856c13e
|
[
"BSD-3-Clause"
] | 5,941 |
2015-01-02T11:32:21.000Z
|
2022-03-31T16:35:46.000Z
|
import json
from wptserve.utils import isomorphic_decode
| 33.871429 | 100 | 0.619148 |
e057de6d96dbc248f4a0c02caf3e3c52ad4ff136
| 1,053 |
py
|
Python
|
device_osc_grid.py
|
wlfyit/PiLightsLib
|
98e39af45f05d0ee44e2f166de5b654d58df33ae
|
[
"MIT"
] | null | null | null |
device_osc_grid.py
|
wlfyit/PiLightsLib
|
98e39af45f05d0ee44e2f166de5b654d58df33ae
|
[
"MIT"
] | null | null | null |
device_osc_grid.py
|
wlfyit/PiLightsLib
|
98e39af45f05d0ee44e2f166de5b654d58df33ae
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python3
from pythonosc import osc_bundle_builder
from pythonosc import osc_message_builder
from pythonosc import udp_client
from .device import DeviceObj
# OSC Grid Object
| 24.488372 | 100 | 0.636277 |
e0581bc2242266c4f411267aa587a7bfd0afc840
| 965 |
py
|
Python
|
main/models.py
|
StevenSume/EasyCMDB
|
c2c44c9efe2de2729659d81ef886abff242ac1c5
|
[
"Apache-2.0"
] | 2 |
2019-08-23T06:04:12.000Z
|
2019-09-16T07:27:16.000Z
|
main/models.py
|
StevenSume/EasyCMDB
|
c2c44c9efe2de2729659d81ef886abff242ac1c5
|
[
"Apache-2.0"
] | null | null | null |
main/models.py
|
StevenSume/EasyCMDB
|
c2c44c9efe2de2729659d81ef886abff242ac1c5
|
[
"Apache-2.0"
] | null | null | null |
from .app import db
| 26.805556 | 67 | 0.592746 |
e05894d94e1647d1250203e64a76b21248195718
| 1,274 |
py
|
Python
|
test.py
|
iron-io/iron_cache_python
|
f68f5a5e216e3189397ffd7d243de0d53bf7c764
|
[
"BSD-2-Clause"
] | 3 |
2015-08-01T13:30:16.000Z
|
2021-03-22T10:25:57.000Z
|
test.py
|
iron-io/iron_cache_python
|
f68f5a5e216e3189397ffd7d243de0d53bf7c764
|
[
"BSD-2-Clause"
] | 1 |
2015-06-02T08:53:44.000Z
|
2015-06-02T09:59:17.000Z
|
test.py
|
iron-io/iron_cache_python
|
f68f5a5e216e3189397ffd7d243de0d53bf7c764
|
[
"BSD-2-Clause"
] | 3 |
2015-05-12T18:13:52.000Z
|
2016-09-08T20:43:40.000Z
|
from iron_cache import *
import unittest
import requests
if __name__ == '__main__':
unittest.main()
| 31.073171 | 56 | 0.631868 |
e059b01690fb071d4b03811c7664f63e0007961b
| 3,914 |
py
|
Python
|
lib_exec/StereoPipeline/libexec/asp_image_utils.py
|
sebasmurphy/iarpa
|
aca39cc5390a153a9779a636ab2523e65cb6d3b0
|
[
"MIT"
] | 20 |
2017-02-01T14:54:57.000Z
|
2022-01-25T06:34:35.000Z
|
lib_exec/StereoPipeline/libexec/asp_image_utils.py
|
sebasmurphy/iarpa
|
aca39cc5390a153a9779a636ab2523e65cb6d3b0
|
[
"MIT"
] | 3 |
2020-04-21T12:11:26.000Z
|
2021-01-10T07:00:51.000Z
|
lib_exec/StereoPipeline/libexec/asp_image_utils.py
|
sebasmurphy/iarpa
|
aca39cc5390a153a9779a636ab2523e65cb6d3b0
|
[
"MIT"
] | 10 |
2017-12-18T18:45:25.000Z
|
2021-11-22T02:43:03.000Z
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# __BEGIN_LICENSE__
# Copyright (c) 2009-2013, United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration. All
# rights reserved.
#
# The NGT platform is 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.
# __END_LICENSE__
"""
Basic functions for working with images on disk.
"""
import sys, os, re, subprocess, string, time, errno
import asp_string_utils
def stripRgbImageAlphaChannel(inputPath, outputPath):
"""Makes an RGB copy of an RBGA image"""
cmd = 'gdal_translate ' + inputPath + ' ' + outputPath + ' -b 1 -b 2 -b 3 -co "COMPRESS=LZW" -co "TILED=YES" -co "BLOCKXSIZE=256" -co "BLOCKYSIZE=256"'
print cmd
os.system(cmd)
def getImageSize(imagePath):
"""Returns the size [samples, lines] in an image"""
# Make sure the input file exists
if not os.path.exists(imagePath):
raise Exception('Image file ' + imagePath + ' not found!')
# Use subprocess to suppress the command output
cmd = ['gdalinfo', imagePath]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
textOutput, err = p.communicate()
# Extract the size from the text
sizePos = textOutput.find('Size is')
endPos = textOutput.find('\n', sizePos+7)
sizeStr = textOutput[sizePos+7:endPos]
sizeStrs = sizeStr.strip().split(',')
numSamples = int(sizeStrs[0])
numLines = int(sizeStrs[1])
size = [numSamples, numLines]
return size
def isIsisFile(filePath):
"""Returns True if the file is an ISIS file, False otherwise."""
# Currently we treat all files with .cub extension as ISIS files
extension = os.path.splitext(filePath)[1]
return (extension == '.cub')
def getImageStats(imagePath):
"""Obtains some image statistics from gdalinfo"""
if not os.path.exists(imagePath):
raise Exception('Image file ' + imagePath + ' not found!')
# Call command line tool silently
cmd = ['gdalinfo', imagePath, '-stats']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
textOutput, err = p.communicate()
# Statistics are computed seperately for each band
bandStats = []
band = 0
while (True): # Loop until we run out of bands
# Look for the stats line for this band
bandString = 'Band ' + str(band+1) + ' Block='
bandLoc = textOutput.find(bandString)
if bandLoc < 0:
return bandStats # Quit if we did not find it
# Now parse out the statistics for this band
bandMaxStart = textOutput.find('STATISTICS_MAXIMUM=', bandLoc)
bandMeanStart = textOutput.find('STATISTICS_MEAN=', bandLoc)
bandMinStart = textOutput.find('STATISTICS_MINIMUM=', bandLoc)
bandStdStart = textOutput.find('STATISTICS_STDDEV=', bandLoc)
bandMax = asp_string_utils.getNumberAfterEqualSign(textOutput, bandMaxStart)
bandMean = asp_string_utils.getNumberAfterEqualSign(textOutput, bandMeanStart)
bandMin = asp_string_utils.getNumberAfterEqualSign(textOutput, bandMinStart)
bandStd = asp_string_utils.getNumberAfterEqualSign(textOutput, bandStdStart)
# Add results to the output list
bandStats.append( (bandMin, bandMax, bandMean, bandStd) )
band = band + 1 # Move to the next band
| 34.946429 | 155 | 0.67348 |
e05b4851d3707561c8c65e7a4b20ce903889be85
| 1,550 |
py
|
Python
|
src/sv-pipeline/04_variant_resolution/scripts/merge_RdTest_genotypes.py
|
leipzig/gatk-sv
|
96566cbbaf0f8f9c8452517b38eea1e5dd6ed33a
|
[
"BSD-3-Clause"
] | 76 |
2020-06-18T21:31:43.000Z
|
2022-03-02T18:42:58.000Z
|
src/sv-pipeline/04_variant_resolution/scripts/merge_RdTest_genotypes.py
|
iamh2o/gatk-sv
|
bf3704bd1d705339577530e267cd4d1b2f77a17f
|
[
"BSD-3-Clause"
] | 195 |
2020-06-22T15:12:28.000Z
|
2022-03-28T18:06:46.000Z
|
src/sv-pipeline/04_variant_resolution/scripts/merge_RdTest_genotypes.py
|
iamh2o/gatk-sv
|
bf3704bd1d705339577530e267cd4d1b2f77a17f
|
[
"BSD-3-Clause"
] | 39 |
2020-07-03T06:47:18.000Z
|
2022-03-03T03:47:25.000Z
|
#!/usr/bin/env python
import argparse
DELIMITER = "\t"
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('genotypes')
parser.add_argument('GQ')
parser.add_argument('fout')
args = parser.parse_args()
merge(args.genotypes, args.GQ, args.fout)
| 36.046512 | 120 | 0.627742 |
e05c65974024f19246bfde72289d00cbac7e1014
| 32 |
py
|
Python
|
esperanto_analyzer/web/__init__.py
|
fidelisrafael/esperanto-analyzer
|
af1e8609ec0696e3d1975aa0ba0c88e5f04f8468
|
[
"BSD-2-Clause"
] | 18 |
2018-09-05T00:46:47.000Z
|
2021-12-08T08:54:35.000Z
|
esperanto_analyzer/web/__init__.py
|
fidelisrafael/esperanto-analyzer
|
af1e8609ec0696e3d1975aa0ba0c88e5f04f8468
|
[
"BSD-2-Clause"
] | null | null | null |
esperanto_analyzer/web/__init__.py
|
fidelisrafael/esperanto-analyzer
|
af1e8609ec0696e3d1975aa0ba0c88e5f04f8468
|
[
"BSD-2-Clause"
] | 3 |
2019-03-12T17:54:18.000Z
|
2020-01-11T13:05:03.000Z
|
from .api.server import run_app
| 16 | 31 | 0.8125 |
e05cac875b2516b4ba7c777d72d8ac768173cf38
| 3,091 |
py
|
Python
|
crawling/sns/main.py
|
CSID-DGU/2021-2-OSSP2-TwoRolless-2
|
e9381418e3899d8e1e78415e9ab23b73b4f30a95
|
[
"MIT"
] | null | null | null |
crawling/sns/main.py
|
CSID-DGU/2021-2-OSSP2-TwoRolless-2
|
e9381418e3899d8e1e78415e9ab23b73b4f30a95
|
[
"MIT"
] | null | null | null |
crawling/sns/main.py
|
CSID-DGU/2021-2-OSSP2-TwoRolless-2
|
e9381418e3899d8e1e78415e9ab23b73b4f30a95
|
[
"MIT"
] | 1 |
2021-10-15T05:19:20.000Z
|
2021-10-15T05:19:20.000Z
|
import tweepy
import traceback
import time
import pymongo
from tweepy import OAuthHandler
from pymongo import MongoClient
from pymongo.cursor import CursorType
twitter_consumer_key = ""
twitter_consumer_secret = ""
twitter_access_token = ""
twitter_access_secret = ""
auth = OAuthHandler(twitter_consumer_key, twitter_consumer_secret)
auth.set_access_token(twitter_access_token, twitter_access_secret)
api = tweepy.API(auth)
conn_str = ""
my_client = pymongo.MongoClient(conn_str)
if __name__ == '__main__':
while True:
print("cycles start")
mydb = my_client['TwoRolless']
mycol = mydb['sns']
mycol.remove({})
crawllTwit("@m_thelastman", "")
crawllTwit("@Musical_NarGold", "_")
crawllTwit("@rndworks", "")
crawllTwit("@ninestory9", "")
crawllTwit("@companyrang", "")
crawllTwit("@companyrang", "")
crawllTwit("@page1company", "")
crawllTwit("@HONGcompany", "")
crawllTwit("@orchardmusical", "")
crawllTwit("@livecorp2011", "")
crawllTwit("@shownote", "")
crawllTwit("@od_musical", "")
crawllTwit("@kontentz", "")
crawllTwit("@i_seensee", "")
crawllTwit("@doublek_ent", "")
crawllTwit("@Insight_Since96", "")
print("cycle end")
print("sleep 30 seconds")
time.sleep(30)
print("sleep end")
| 29.438095 | 126 | 0.547072 |
e05cbd467aaeb3118a784785e85a274a27c23842
| 698 |
py
|
Python
|
demos/interactive-classifier/config.py
|
jepabe/Demo_earth2
|
ab20c3a9114904219688b16f8a1273e68927e6f9
|
[
"Apache-2.0"
] | 1,909 |
2015-04-22T20:18:22.000Z
|
2022-03-31T13:42:03.000Z
|
demos/interactive-classifier/config.py
|
jepabe/Demo_earth2
|
ab20c3a9114904219688b16f8a1273e68927e6f9
|
[
"Apache-2.0"
] | 171 |
2015-09-24T05:49:49.000Z
|
2022-03-14T00:54:50.000Z
|
demos/interactive-classifier/config.py
|
jepabe/Demo_earth2
|
ab20c3a9114904219688b16f8a1273e68927e6f9
|
[
"Apache-2.0"
] | 924 |
2015-04-23T05:43:18.000Z
|
2022-03-28T12:11:31.000Z
|
#!/usr/bin/env python
"""Handles Earth Engine service account configuration."""
import ee
# The service account email address authorized by your Google contact.
# Set up a service account as described in the README.
EE_ACCOUNT = '[email protected]'
# The private key associated with your service account in Privacy Enhanced
# Email format (.pem suffix). To convert a private key from the RSA format
# (.p12 suffix) to .pem, run the openssl command like this:
# openssl pkcs12 -in downloaded-privatekey.p12 -nodes -nocerts > privatekey.pem
EE_PRIVATE_KEY_FILE = 'privatekey.pem'
EE_CREDENTIALS = ee.ServiceAccountCredentials(EE_ACCOUNT, EE_PRIVATE_KEY_FILE)
| 41.058824 | 79 | 0.787966 |
e05d022e20ec708234ba466419ce63a57d30ac77
| 2,716 |
py
|
Python
|
PythonScripting/NumbersInPython.py
|
Neo-sunny/pythonProgs
|
a9d2359d8a09d005d0ba6f94d7d256bf91499793
|
[
"MIT"
] | null | null | null |
PythonScripting/NumbersInPython.py
|
Neo-sunny/pythonProgs
|
a9d2359d8a09d005d0ba6f94d7d256bf91499793
|
[
"MIT"
] | null | null | null |
PythonScripting/NumbersInPython.py
|
Neo-sunny/pythonProgs
|
a9d2359d8a09d005d0ba6f94d7d256bf91499793
|
[
"MIT"
] | null | null | null |
"""
Demonstration of numbers in Python
"""
# Python has an integer type called int
print("int")
print("---")
print(0)
print(1)
print(-3)
print(70383028364830)
print("")
# Python has a real number type called float
print("float")
print("-----")
print(0.0)
print(7.35)
print(-43.2)
print("")
# Limited precision
print("Precision")
print("---------")
print(4.56372883832331773)
print(1.23456789012345678)
print("")
# Scientific/exponential notation
print("Scientific notation")
print("-------------------")
print(5e32)
print(999999999999999999999999999999999999999.9)
print("")
# Infinity
print("Infinity")
print("--------")
print(1e500)
print(-1e500)
print("")
# Conversions
print("Conversions between numeric types")
print("---------------------------------")
print(float(3))
print(float(99999999999999999999999999999999999999))
print(int(3.0))
print(int(3.7))
print(int(-3.7))
"""
Demonstration of simple arithmetic expressions in Python
"""
# Unary + and -
print("Unary operators")
print(+3)
print(-5)
print(+7.86)
print(-3348.63)
print("")
# Simple arithmetic
print("Addition and Subtraction")
print(1 + 2)
print(48 - 89)
print(3.45 + 2.7)
print(87.3384 - 12.35)
print(3 + 6.7)
print(9.8 - 4)
print("")
print("Multiplication")
print(3 * 2)
print(7.8 * 27.54)
print(7 * 8.2)
print("")
print("Division")
print(8 / 2)
print(3 / 2)
print(7.538 / 14.3)
print(8 // 2)
print(3 // 2)
print(7.538 // 14.3)
print("")
print("Exponentiation")
print(3 ** 2)
print(5 ** 4)
print(32.6 ** 7)
print(9 ** 0.5)
"""
Demonstration of compound arithmetic expressions in Python
"""
# Expressions can include multiple operations
print("Compound expressions")
print(3 + 5 + 7 + 27)
#Operator with same precedence are evaluated from left to right
print(18 - 6 + 4)
print("")
# Operator precedence defines how expressions are evaluated
print("Operator precedence")
print(7 + 3 * 5)
print(5.5 * 6 // 2 + 8)
print(-3 ** 2)
print("")
# Use parentheses to change evaluation order
print("Grouping with parentheses")
print((7 + 3) * 5)
print(5.5 * ((6 // 2) + 8))
print((-3) ** 2)
"""
Demonstration of the use of variables and how to assign values to
them.
"""
# The = operator can be used to assign values to variables
bakers_dozen = 12 + 1
temperature = 93
# Variables can be used as values and in expressions
print(temperature, bakers_dozen)
print("celsius:", (temperature - 32) * 5 / 9)
print("fahrenheit:", float(temperature))
# You can assign a different value to an existing variable
temperature = 26
print("new value:", temperature)
# Multiple variables can be used in arbitrary expressions
offset = 32
multiplier = 5.0 / 9.0
celsius = (temperature - offset) * multiplier
print("celsius value:", celsius)
| 17.522581 | 65 | 0.674521 |
e05e6c4440c357c867a4c38e37f726c4d615e768
| 1,676 |
py
|
Python
|
3DBeam/source/solving_strategies/strategies/linear_solver.py
|
JoZimmer/Beam-Models
|
e701c0bae6e3035e7a07cc590da4a132b133dcff
|
[
"BSD-3-Clause"
] | null | null | null |
3DBeam/source/solving_strategies/strategies/linear_solver.py
|
JoZimmer/Beam-Models
|
e701c0bae6e3035e7a07cc590da4a132b133dcff
|
[
"BSD-3-Clause"
] | null | null | null |
3DBeam/source/solving_strategies/strategies/linear_solver.py
|
JoZimmer/Beam-Models
|
e701c0bae6e3035e7a07cc590da4a132b133dcff
|
[
"BSD-3-Clause"
] | 1 |
2022-01-05T17:32:32.000Z
|
2022-01-05T17:32:32.000Z
|
from source.solving_strategies.strategies.solver import Solver
| 38.976744 | 80 | 0.590095 |
e05ea195ece947573587efca60ad05b204af43f6
| 1,095 |
py
|
Python
|
payment/migrations/0002_auto_20171125_0022.py
|
Littledelma/mofadog
|
5a7c6672da248e400a8a5746506a6e7b273c9510
|
[
"MIT"
] | null | null | null |
payment/migrations/0002_auto_20171125_0022.py
|
Littledelma/mofadog
|
5a7c6672da248e400a8a5746506a6e7b273c9510
|
[
"MIT"
] | 1 |
2021-06-08T03:28:08.000Z
|
2021-06-08T03:28:08.000Z
|
payment/migrations/0002_auto_20171125_0022.py
|
Littledelma/mofadog
|
5a7c6672da248e400a8a5746506a6e7b273c9510
|
[
"MIT"
] | 1 |
2021-06-08T03:23:34.000Z
|
2021-06-08T03:23:34.000Z
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-11-24 16:22
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
| 33.181818 | 138 | 0.63379 |
e05fe1dabdb8d88cb6b7077a77b9ecb4a63a39fd
| 841 |
py
|
Python
|
src/sqlfluff/rules/L024.py
|
NathanHowell/sqlfluff
|
9eb30226d77727cd613947e144a0abe483151f18
|
[
"MIT"
] | 3,024 |
2020-10-01T11:03:51.000Z
|
2022-03-31T16:42:00.000Z
|
src/sqlfluff/rules/L024.py
|
NathanHowell/sqlfluff
|
9eb30226d77727cd613947e144a0abe483151f18
|
[
"MIT"
] | 2,395 |
2020-09-30T12:59:21.000Z
|
2022-03-31T22:05:29.000Z
|
src/sqlfluff/rules/L024.py
|
NathanHowell/sqlfluff
|
9eb30226d77727cd613947e144a0abe483151f18
|
[
"MIT"
] | 246 |
2020-10-02T17:08:03.000Z
|
2022-03-30T17:43:51.000Z
|
"""Implementation of Rule L024."""
from sqlfluff.core.rules.doc_decorators import document_fix_compatible
from sqlfluff.rules.L023 import Rule_L023
| 21.564103 | 70 | 0.652794 |
e061aa108e5ec8060888f9dff1215ff5763d024a
| 2,847 |
py
|
Python
|
projects/scocen/cmd_components_simple.py
|
mikeireland/chronostar
|
fcf37614e1d145f3a5e265e54512bf8cd98051a0
|
[
"MIT"
] | 4 |
2018-05-28T11:05:42.000Z
|
2021-05-14T01:13:11.000Z
|
projects/scocen/cmd_components_simple.py
|
mikeireland/chronostar
|
fcf37614e1d145f3a5e265e54512bf8cd98051a0
|
[
"MIT"
] | 13 |
2019-08-14T07:30:24.000Z
|
2021-11-08T23:44:29.000Z
|
projects/scocen/cmd_components_simple.py
|
mikeireland/chronostar
|
fcf37614e1d145f3a5e265e54512bf8cd98051a0
|
[
"MIT"
] | 4 |
2016-04-21T08:25:26.000Z
|
2021-02-25T06:53:52.000Z
|
"""
Plot CMDs for each component.
"""
import numpy as np
from astropy.table import Table
import matplotlib.pyplot as plt
import matplotlib.cm as cm
plt.ion()
# Pretty plots
from fig_settings import *
############################################
# Some things are the same for all the plotting scripts and we put
# this into a single library to avoid confusion.
import scocenlib as lib
data_filename = lib.data_filename
comps_filename = lib.comps_filename
compnames = lib.compnames
colors = lib.colors
############################################
# Minimal probability required for membership
pmin_membership = 0.5
############################################
# how to split subplots
grid = [5, 5]
# CMD limits
xlim = [-1, 5]
ylim = [17, -3]
############################################
# Read data
try:
tab = tab0
comps = comps0
except:
tab0 = Table.read(data_filename)
Gmag = tab0['phot_g_mean_mag'] - 5 * np.log10(1.0 / (tab0['parallax'] * 1e-3) / 10) # tab['parallax'] in micro arcsec
tab0['Gmag'] = Gmag
comps0 = Table.read(comps_filename)
tab = tab0
comps = comps0
# Main sequence parametrization
# fitpar for pmag, rpmag
fitpar = [0.17954163, -2.48748376, 12.9279348, -31.35434182, 38.31330583, -12.25864507]
poly = np.poly1d(fitpar)
x = np.linspace(1, 4, 100)
y = poly(x)
m = y > 4
yms = y[m]
xms = x[m]
print('Plotting %d components.'%len(comps))
fig=plt.figure()
for i, c in enumerate(comps):
ax = fig.add_subplot(grid[0], grid[1], i+1) # TODO: adjust this if needed
comp_ID = c['comp_ID']
col=tab['membership%s'%comp_ID]
mask = col > pmin_membership
t=tab[mask]
if len(t)>100:
alpha=0.5
else:
alpha=1
t.sort('membership%s'%comp_ID)
#~ t.reverse()
#~ ax.scatter(t['bp_rp'], t['Gmag'], s=1, c='k', alpha=alpha)
ax.scatter(t['bp_rp'], t['Gmag'], s=1, c=t['membership%s'%comp_ID], alpha=1, vmin=0.5, vmax=1, cmap=cm.jet)
ax=plot_MS_parametrisation_and_spectral_types(ax, xlim, ylim)
age=c['Age']
ax.set_title('%s (%.2f$\pm$%.2f Myr %s) %d'%(comp_ID, age, c['Crossing_time'], c['Age_reliable'], len(t)))
#~ plt.tight_layout()
plt.show()
| 26.858491 | 122 | 0.601686 |
e061c15bed338723a46d4f04e8c849cc852fe7c0
| 5,326 |
py
|
Python
|
test/test_cursor_binding.py
|
rhlahuja/snowflake-connector-python
|
6abc56c970cdb698a833b7f6ac9cbe7dfa667abd
|
[
"Apache-2.0"
] | null | null | null |
test/test_cursor_binding.py
|
rhlahuja/snowflake-connector-python
|
6abc56c970cdb698a833b7f6ac9cbe7dfa667abd
|
[
"Apache-2.0"
] | null | null | null |
test/test_cursor_binding.py
|
rhlahuja/snowflake-connector-python
|
6abc56c970cdb698a833b7f6ac9cbe7dfa667abd
|
[
"Apache-2.0"
] | null | null | null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012-2018 Snowflake Computing Inc. All right reserved.
#
import pytest
from snowflake.connector.errors import (ProgrammingError)
def test_binding_security(conn_cnx, db_parameters):
"""
SQL Injection Tests
"""
try:
with conn_cnx() as cnx:
cnx.cursor().execute(
"CREATE OR REPLACE TABLE {name} "
"(aa INT, bb STRING)".format(
name=db_parameters['name']))
cnx.cursor().execute(
"INSERT INTO {name} VALUES(%s, %s)".format(
name=db_parameters['name']),
(1, 'test1'))
cnx.cursor().execute(
"INSERT INTO {name} VALUES(%(aa)s, %(bb)s)".format(
name=db_parameters['name']),
{'aa': 2, 'bb': 'test2'})
for rec in cnx.cursor().execute(
"SELECT * FROM {name} ORDER BY 1 DESC".format(
name=db_parameters['name'])):
break
assert rec[0] == 2, 'First column'
assert rec[1] == 'test2', 'Second column'
for rec in cnx.cursor().execute(
"SELECT * FROM {name} WHERE aa=%s".format(
name=db_parameters['name']), (1,)):
break
assert rec[0] == 1, 'First column'
assert rec[1] == 'test1', 'Second column'
# SQL injection safe test
# Good Example
with pytest.raises(ProgrammingError):
cnx.cursor().execute(
"SELECT * FROM {name} WHERE aa=%s".format(
name=db_parameters['name']),
("1 or aa>0",))
with pytest.raises(ProgrammingError):
cnx.cursor().execute(
"SELECT * FROM {name} WHERE aa=%(aa)s".format(
name=db_parameters['name']),
{"aa": "1 or aa>0"})
# Bad Example in application. DON'T DO THIS
c = cnx.cursor()
c.execute("SELECT * FROM {name} WHERE aa=%s".format(
name=db_parameters['name']) % ("1 or aa>0",))
rec = c.fetchall()
assert len(rec) == 2, "not raising error unlike the previous one."
finally:
with conn_cnx() as cnx:
cnx.cursor().execute(
"drop table if exists {name}".format(
name=db_parameters['name']))
def test_binding_list(conn_cnx, db_parameters):
"""
SQL binding list type for IN
"""
try:
with conn_cnx() as cnx:
cnx.cursor().execute(
"CREATE OR REPLACE TABLE {name} "
"(aa INT, bb STRING)".format(
name=db_parameters['name']))
cnx.cursor().execute(
"INSERT INTO {name} VALUES(%s, %s)".format(
name=db_parameters['name']),
(1, 'test1'))
cnx.cursor().execute(
"INSERT INTO {name} VALUES(%(aa)s, %(bb)s)".format(
name=db_parameters['name']),
{'aa': 2, 'bb': 'test2'})
cnx.cursor().execute(
"INSERT INTO {name} VALUES(3, 'test3')".format(
name=db_parameters['name']))
for rec in cnx.cursor().execute("""
SELECT * FROM {name} WHERE aa IN (%s) ORDER BY 1 DESC
""".format(name=db_parameters['name']), ([1, 3],)):
break
assert rec[0] == 3, 'First column'
assert rec[1] == 'test3', 'Second column'
for rec in cnx.cursor().execute(
"SELECT * FROM {name} WHERE aa=%s".format(
name=db_parameters['name']), (1,)):
break
assert rec[0] == 1, 'First column'
assert rec[1] == 'test1', 'Second column'
rec = cnx.cursor().execute("""
SELECT * FROM {name} WHERE aa IN (%s) ORDER BY 1 DESC
""".format(name=db_parameters['name']), ((1,),))
finally:
with conn_cnx() as cnx:
cnx.cursor().execute(
"drop table if exists {name}".format(
name=db_parameters['name']))
def test_unsupported_binding(conn_cnx, db_parameters):
"""
Unsupported data binding
"""
try:
with conn_cnx() as cnx:
cnx.cursor().execute(
"CREATE OR REPLACE TABLE {name} "
"(aa INT, bb STRING)".format(
name=db_parameters['name']))
cnx.cursor().execute(
"INSERT INTO {name} VALUES(%s, %s)".format(
name=db_parameters['name']),
(1, 'test1'))
sql = 'select count(*) from {name} where aa=%s'.format(
name=db_parameters['name'])
with cnx.cursor() as cur:
rec = cur.execute(sql, (1,)).fetchone()
assert rec[0] is not None, 'no value is returned'
# dict
with pytest.raises(ProgrammingError):
cnx.cursor().execute(sql, ({'value': 1},))
finally:
with conn_cnx() as cnx:
cnx.cursor().execute(
"drop table if exists {name}".format(
name=db_parameters['name']))
| 36.731034 | 78 | 0.480473 |
e061da410580634f463731e3265faeb51909f55c
| 1,071 |
py
|
Python
|
taln2016/icsisumm-primary-sys34_v1/nltk/nltk-0.9.2/nltk/model/__init__.py
|
hectormartinez/rougexstem
|
32da9eab253cb88fc1882e59026e8b5b40900a25
|
[
"Apache-2.0"
] | null | null | null |
taln2016/icsisumm-primary-sys34_v1/nltk/nltk-0.9.2/nltk/model/__init__.py
|
hectormartinez/rougexstem
|
32da9eab253cb88fc1882e59026e8b5b40900a25
|
[
"Apache-2.0"
] | null | null | null |
taln2016/icsisumm-primary-sys34_v1/nltk/nltk-0.9.2/nltk/model/__init__.py
|
hectormartinez/rougexstem
|
32da9eab253cb88fc1882e59026e8b5b40900a25
|
[
"Apache-2.0"
] | null | null | null |
# Natural Language Toolkit: Language Models
#
# Copyright (C) 2001-2008 University of Pennsylvania
# Author: Steven Bird <[email protected]>
# URL: <http://nltk.sf.net>
# For license information, see LICENSE.TXT
| 31.5 | 78 | 0.6676 |
e06275178027bd16b4be36faab1b32af531b42cb
| 1,047 |
py
|
Python
|
flask-graphene-sqlalchemy/models.py
|
JovaniPink/flask-apps
|
de887f15261c286986cf38d234d49f7e4eb79c1a
|
[
"MIT"
] | null | null | null |
flask-graphene-sqlalchemy/models.py
|
JovaniPink/flask-apps
|
de887f15261c286986cf38d234d49f7e4eb79c1a
|
[
"MIT"
] | null | null | null |
flask-graphene-sqlalchemy/models.py
|
JovaniPink/flask-apps
|
de887f15261c286986cf38d234d49f7e4eb79c1a
|
[
"MIT"
] | null | null | null |
import os
from graphene_sqlalchemy import SQLAlchemyObjectType
from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
POSTGRES_CONNECTION_STRING = (
os.environ.get("POSTGRES_CONNECTION_STRING")
or "postgres://postgres:password@localhost:6432/postgres"
)
engine = create_engine(POSTGRES_CONNECTION_STRING, convert_unicode=True)
db_session = scoped_session(
sessionmaker(autocommit=False, autoflush=False, bind=engine)
)
Base = declarative_base()
Base.query = db_session.query_property()
| 26.175 | 72 | 0.770774 |
e06418cb46f2f01ccc35fc22e565190b30c821ed
| 16,478 |
py
|
Python
|
curlypiv/synthetics/microsig.py
|
sean-mackenzie/curlypiv
|
21c96c1bb1ba2548c4d5bebb389eb66ff58f851d
|
[
"MIT"
] | null | null | null |
curlypiv/synthetics/microsig.py
|
sean-mackenzie/curlypiv
|
21c96c1bb1ba2548c4d5bebb389eb66ff58f851d
|
[
"MIT"
] | 1 |
2021-06-14T17:24:43.000Z
|
2021-06-14T17:24:43.000Z
|
curlypiv/synthetics/microsig.py
|
sean-mackenzie/curlypiv
|
21c96c1bb1ba2548c4d5bebb389eb66ff58f851d
|
[
"MIT"
] | null | null | null |
# microsig
"""
Author: Maximilliano Rossi
More detail about the MicroSIG can be found at:
Website:
https://gitlab.com/defocustracking/microsig-python
Publication:
Rossi M, Synthetic image generator for defocusing and astigmatic PIV/PTV, Meas. Sci. Technol., 31, 017003 (2020)
DOI:10.1088/1361-6501/ab42bb.
"""
import numpy as np
import imageio
import tkinter as tk
import os
from os import listdir
from os.path import isfile, basename, join, isdir
import sys
import glob
# import time as tm
from tkinter import filedialog
# ----- code adapted by Sean MacKenzie ------
# 2.0 define class
# %%
# %%
# %%
# %%
# %%
# %%
if __name__ == '__main__':
run()
| 32.956 | 119 | 0.506615 |
e0651470e7323b974d75e2d23e40d53bc5af99ea
| 4,146 |
py
|
Python
|
planning/scenario_planning/lane_driving/motion_planning/obstacle_avoidance_planner/scripts/trajectory_visualizer.py
|
kmiya/AutowareArchitectureProposal.iv
|
386b52c9cc90f4535ad833014f2f9500f0e64ccf
|
[
"Apache-2.0"
] | null | null | null |
planning/scenario_planning/lane_driving/motion_planning/obstacle_avoidance_planner/scripts/trajectory_visualizer.py
|
kmiya/AutowareArchitectureProposal.iv
|
386b52c9cc90f4535ad833014f2f9500f0e64ccf
|
[
"Apache-2.0"
] | null | null | null |
planning/scenario_planning/lane_driving/motion_planning/obstacle_avoidance_planner/scripts/trajectory_visualizer.py
|
kmiya/AutowareArchitectureProposal.iv
|
386b52c9cc90f4535ad833014f2f9500f0e64ccf
|
[
"Apache-2.0"
] | 1 |
2021-07-20T09:38:30.000Z
|
2021-07-20T09:38:30.000Z
|
# Copyright 2020 Tier IV, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# TODO(kosuke murakami): write ros2 visualizer
# import rospy
# from autoware_planning_msgs.msg import Trajectory
# from autoware_planning_msgs.msg import TrajectoryPoint
# import matplotlib.pyplot as plt
# import numpy as np
# import tf
# from geometry_msgs.msg import Vector3
# def quaternion_to_euler(quaternion):
# """Convert Quaternion to Euler Angles
# quaternion: geometry_msgs/Quaternion
# euler: geometry_msgs/Vector3
# """
# e = tf.transformations.euler_from_quaternion(
# (quaternion.x, quaternion.y, quaternion.z, quaternion.w))
# return Vector3(x=e[0], y=e[1], z=e[2])
# class TrajectoryVisualizer():
# def __init__(self):
# self.in_trajectory = Trajectory()
# self.debug_trajectory = Trajectory()
# self.debug_fixed_trajectory = Trajectory()
# self.plot_done1 = True
# self.plot_done2 = True
# self.plot_done3 = True
# self.length = 50
# self.substatus1 = rospy.Subscriber(
# "/planning/scenario_planning/lane_driving/motion_planning/obstacle_avoidance_planner/trajectory",
# Trajectory, self.CallBackTraj, queue_size=1, tcp_nodelay=True)
# rospy.Timer(rospy.Duration(0.3), self.timerCallback)
# def CallBackTraj(self, cmd):
# if (self.plot_done1):
# self.in_trajectory = cmd
# self.plot_done1 = False
# def CallBackDebugTraj(self, cmd):
# if (self.plot_done2):
# self.debug_trajectory = cmd
# self.plot_done2 = False
# def CallBackDebugFixedTraj(self, cmd):
# if (self.plot_done3):
# self.debug_fixed_trajectory = cmd
# self.plot_done3 = False
# def timerCallback(self, event):
# self.plotTrajectory()
# self.plot_done1 = True
# self.plot_done2 = True
# self.plot_done3 = True
# def CalcArcLength(self, traj):
# s_arr = []
# ds = 0.0
# s_sum = 0.0
# if len(traj.points) > 0:
# s_arr.append(s_sum)
# for i in range(1, len(traj.points)):
# p0 = traj.points[i-1]
# p1 = traj.points[i]
# dx = p1.pose.position.x - p0.pose.position.x
# dy = p1.pose.position.y - p0.pose.position.y
# ds = np.sqrt(dx**2 + dy**2)
# s_sum += ds
# if(s_sum > self.length):
# break
# s_arr.append(s_sum)
# return s_arr
# def CalcX(self, traj):
# v_list = []
# for p in traj.points:
# v_list.append(p.pose.position.x)
# return v_list
# def CalcY(self, traj):
# v_list = []
# for p in traj.points:
# v_list.append(p.pose.position.y)
# return v_list
# def CalcYaw(self, traj, s_arr):
# v_list = []
# for p in traj.points:
# v_list.append(quaternion_to_euler(p.pose.orientation).z)
# return v_list[0: len(s_arr)]
# def plotTrajectory(self):
# plt.clf()
# ax3 = plt.subplot(1, 1, 1)
# x = self.CalcArcLength(self.in_trajectory)
# y = self.CalcYaw(self.in_trajectory, x)
# if len(x) == len(y):
# ax3.plot(x, y, label="final", marker="*")
# ax3.set_xlabel("arclength [m]")
# ax3.set_ylabel("yaw")
# plt.pause(0.01)
# def main():
# rospy.init_node("trajectory_visualizer")
# TrajectoryVisualizer()
# rospy.spin()
# if __name__ == "__main__":
# main()
| 30.485294 | 109 | 0.600338 |
e067ec51a3742d007fe87145e158ef565747647f
| 2,642 |
py
|
Python
|
main/forms.py
|
agokhale11/test2
|
deddf17e7bb67777251cf73cbdb5f6970c16050a
|
[
"MIT"
] | null | null | null |
main/forms.py
|
agokhale11/test2
|
deddf17e7bb67777251cf73cbdb5f6970c16050a
|
[
"MIT"
] | 7 |
2020-06-05T18:32:16.000Z
|
2022-03-11T23:24:17.000Z
|
main/forms.py
|
agokhale11/test2
|
deddf17e7bb67777251cf73cbdb5f6970c16050a
|
[
"MIT"
] | null | null | null |
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.contrib.auth.models import User
from django import forms
# If you don't do this you cannot use Bootstrap CSS
| 41.28125 | 136 | 0.62869 |
e068d2bbe0be95225acd32e5324a05a51bc85276
| 5,641 |
py
|
Python
|
pandas 9 - Statistics Information on data sets.py
|
PythonProgramming/Pandas-Basics-with-2.7
|
a6ecd5ac7c25dba83e934549903f229de89290d3
|
[
"MIT"
] | 10 |
2015-07-16T05:46:10.000Z
|
2020-10-28T10:35:50.000Z
|
pandas 9 - Statistics Information on data sets.py
|
PythonProgramming/Pandas-Basics-with-2.7
|
a6ecd5ac7c25dba83e934549903f229de89290d3
|
[
"MIT"
] | null | null | null |
pandas 9 - Statistics Information on data sets.py
|
PythonProgramming/Pandas-Basics-with-2.7
|
a6ecd5ac7c25dba83e934549903f229de89290d3
|
[
"MIT"
] | 9 |
2017-01-31T18:57:25.000Z
|
2019-09-10T08:52:57.000Z
|
import pandas as pd
from pandas import DataFrame
df = pd.read_csv('sp500_ohlc.csv', index_col = 'Date', parse_dates=True)
df['H-L'] = df.High - df.Low
# Giving us count (rows), mean (avg), std (standard deviation for the entire
# set), minimum for the set, maximum for the set, and some %s in that range.
print( df.describe())
x = input('enter to cont')
# gives us correlation data. Remember the 3d chart we plotted?
# now you can see if correlation of H-L and Volume also is correlated
# with price swings. Correlations for your correlations
print( df.corr())
x = input('enter to cont')
# covariance... now plenty of people know what correlation is, but what in the
# heck is covariance.
# Let's defined the two.
# covariance is the measure of how two variables change together.
# correlation is the measure of how two variables move in relation to eachother.
# so covariance is a more direct assessment of the relationship between two variables.
# Maybe a better way to put it is that covariance is the measure of the strength of correlation.
print( df.cov())
x = input('enter to cont')
print( df[['Volume','H-L']].corr())
x = input('enter to cont')
# see how it makes a table?
# so now, we can actually perform a service that some people actually pay for
# I once had a short freelance gig doing this
# so a popular form of analysis within especially forex is to compare correlations between
# the currencies. The idea here is that you pace one currency with another.
#
import datetime
import pandas.io.data
C = pd.io.data.get_data_yahoo('C',
start=datetime.datetime(2011, 10, 1),
end=datetime.datetime(2014, 1, 1))
AAPL = pd.io.data.get_data_yahoo('AAPL',
start=datetime.datetime(2011, 10, 1),
end=datetime.datetime(2014, 1, 1))
MSFT = pd.io.data.get_data_yahoo('MSFT',
start=datetime.datetime(2011, 10, 1),
end=datetime.datetime(2014, 1, 1))
TSLA = pd.io.data.get_data_yahoo('TSLA',
start=datetime.datetime(2011, 10, 1),
end=datetime.datetime(2014, 1, 1))
print( C.head())
x = input('enter to cont')
del C['Open']
# , 'high', 'low', 'close', 'volume'
del C['High']
del C['Low']
del C['Close']
del C['Volume']
corComp = C
corComp.rename(columns={'Adj Close': 'C'}, inplace=True)
corComp['AAPL'] = AAPL['Adj Close']
corComp['MSFT'] = MSFT['Adj Close']
corComp['TSLA'] = TSLA['Adj Close']
print( corComp.head())
x = input('enter to cont')
print( corComp.corr())
x = input('enter to cont')
C = pd.io.data.get_data_yahoo('C',
start=datetime.datetime(2011, 10, 1),
end=datetime.datetime(2014, 1, 1))
AAPL = pd.io.data.get_data_yahoo('AAPL',
start=datetime.datetime(2011, 10, 1),
end=datetime.datetime(2014, 1, 1))
MSFT = pd.io.data.get_data_yahoo('MSFT',
start=datetime.datetime(2011, 10, 1),
end=datetime.datetime(2014, 1, 1))
TSLA = pd.io.data.get_data_yahoo('TSLA',
start=datetime.datetime(2011, 10, 1),
end=datetime.datetime(2014, 1, 1))
BAC = pd.io.data.get_data_yahoo('BAC',
start=datetime.datetime(2011, 10, 1),
end=datetime.datetime(2014, 1, 1))
BBRY = pd.io.data.get_data_yahoo('BBRY',
start=datetime.datetime(2011, 10, 1),
end=datetime.datetime(2014, 1, 1))
CMG = pd.io.data.get_data_yahoo('CMG',
start=datetime.datetime(2011, 10, 1),
end=datetime.datetime(2014, 1, 1))
EBAY = pd.io.data.get_data_yahoo('EBAY',
start=datetime.datetime(2011, 10, 1),
end=datetime.datetime(2014, 1, 1))
JPM = pd.io.data.get_data_yahoo('JPM',
start=datetime.datetime(2011, 10, 1),
end=datetime.datetime(2014, 1, 1))
SBUX = pd.io.data.get_data_yahoo('SBUX',
start=datetime.datetime(2011, 10, 1),
end=datetime.datetime(2014, 1, 1))
TGT = pd.io.data.get_data_yahoo('TGT',
start=datetime.datetime(2011, 10, 1),
end=datetime.datetime(2014, 1, 1))
WFC = pd.io.data.get_data_yahoo('WFC',
start=datetime.datetime(2011, 10, 1),
end=datetime.datetime(2014, 1, 1))
x = input('enter to cont')
print( C.head())
del C['Open']
# , 'high', 'low', 'close', 'volume'
del C['High']
del C['Low']
del C['Close']
del C['Volume']
corComp = C
corComp.rename(columns={'Adj Close': 'C'}, inplace=True)
corComp['BAC'] = BAC['Adj Close']
corComp['MSFT'] = MSFT['Adj Close']
corComp['TSLA'] = TSLA['Adj Close']
corComp['AAPL'] = AAPL['Adj Close']
corComp['BBRY'] = BBRY['Adj Close']
corComp['CMG'] = CMG['Adj Close']
corComp['EBAY'] = EBAY['Adj Close']
corComp['JPM'] = JPM['Adj Close']
corComp['SBUX'] = SBUX['Adj Close']
corComp['TGT'] = TGT['Adj Close']
corComp['WFC'] = WFC['Adj Close']
print( corComp.head())
x = input('enter to cont')
print( corComp.corr())
x = input('enter to cont')
fancy = corComp.corr()
fancy.to_csv('bigmoney.csv')
| 32.606936 | 96 | 0.565148 |
e06b5b33923a9795875422db89edadd2030423bd
| 292 |
py
|
Python
|
working/tkinter_widget/test.py
|
songdaegeun/school-zone-enforcement-system
|
b5680909fd5a348575563534428d2117f8dc2e3f
|
[
"MIT"
] | null | null | null |
working/tkinter_widget/test.py
|
songdaegeun/school-zone-enforcement-system
|
b5680909fd5a348575563534428d2117f8dc2e3f
|
[
"MIT"
] | null | null | null |
working/tkinter_widget/test.py
|
songdaegeun/school-zone-enforcement-system
|
b5680909fd5a348575563534428d2117f8dc2e3f
|
[
"MIT"
] | null | null | null |
import cv2
import numpy as np
import threading
t1 = threading.Thread(target=test)
t1.start()
| 18.25 | 44 | 0.60274 |
e06beb7e97ea00b98e3ff8423b4c33335a68172e
| 7,856 |
py
|
Python
|
ceilometer/compute/virt/hyperv/utilsv2.py
|
aristanetworks/ceilometer
|
8776b137f82f71eef1241bcb1600de10c1f77394
|
[
"Apache-2.0"
] | 2 |
2015-09-07T09:15:26.000Z
|
2015-09-30T02:13:23.000Z
|
ceilometer/compute/virt/hyperv/utilsv2.py
|
aristanetworks/ceilometer
|
8776b137f82f71eef1241bcb1600de10c1f77394
|
[
"Apache-2.0"
] | null | null | null |
ceilometer/compute/virt/hyperv/utilsv2.py
|
aristanetworks/ceilometer
|
8776b137f82f71eef1241bcb1600de10c1f77394
|
[
"Apache-2.0"
] | 1 |
2019-09-16T02:11:41.000Z
|
2019-09-16T02:11:41.000Z
|
# Copyright 2013 Cloudbase Solutions Srl
#
# Author: Claudiu Belu <[email protected]>
# Alessandro Pilotti <[email protected]>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Utility class for VM related operations.
Based on the "root/virtualization/v2" namespace available starting with
Hyper-V Server / Windows Server 2012.
"""
import sys
if sys.platform == 'win32':
import wmi
from oslo.config import cfg
from ceilometer.compute.virt import inspector
from ceilometer.openstack.common.gettextutils import _
from ceilometer.openstack.common import log as logging
CONF = cfg.CONF
LOG = logging.getLogger(__name__)
| 37.056604 | 78 | 0.66777 |
e06fed7cfa54e3e815b314104d5c76b1f273336e
| 1,126 |
py
|
Python
|
src/cli.py
|
cajones314/avocd2019
|
268e03c5d1bb5b3e14459b831916bb7846f40def
|
[
"MIT"
] | null | null | null |
src/cli.py
|
cajones314/avocd2019
|
268e03c5d1bb5b3e14459b831916bb7846f40def
|
[
"MIT"
] | null | null | null |
src/cli.py
|
cajones314/avocd2019
|
268e03c5d1bb5b3e14459b831916bb7846f40def
|
[
"MIT"
] | null | null | null |
# system
from io import IOBase, StringIO
import os
# 3rd party
import click
# internal
from days import DayFactory
# import logging
# logger = logging.getLogger(__name__)
# logger.setLevel(logging.DEBUG)
# ch = logging.StreamHandler()
# logger.addHandler(ch)
if __name__ == "__main__":
# pylint: disable=no-value-for-parameter
cli()
| 28.15 | 122 | 0.69627 |
e0702674ad6cf140cbb31a3b885b600b8569c9c4
| 17,033 |
py
|
Python
|
option_c.py
|
wrosecrans/colormap
|
0b6a3b7e4caa5df72e7bad8ba196acfbbe5e5946
|
[
"CC0-1.0"
] | 231 |
2015-06-03T01:28:13.000Z
|
2022-03-27T02:02:42.000Z
|
option_c.py
|
CatarinaL/colormap
|
bc549477db0c12b54a5928087552ad2cf274980f
|
[
"CC0-1.0"
] | 10 |
2015-06-06T23:06:06.000Z
|
2019-10-25T20:10:48.000Z
|
option_c.py
|
CatarinaL/colormap
|
bc549477db0c12b54a5928087552ad2cf274980f
|
[
"CC0-1.0"
] | 97 |
2015-06-04T00:46:34.000Z
|
2022-01-23T17:37:24.000Z
|
from matplotlib.colors import LinearSegmentedColormap
from numpy import nan, inf
# Used to reconstruct the colormap in viscm
parameters = {'xp': [-5.4895292543686764, 14.790571669586654, 82.5546687431056, 29.15531114139253, -4.1316769886951761, -13.002076438907238],
'yp': [-35.948168839230306, -42.273376159885785, -28.845467523197698, 52.03426124197, 36.832712600868973, 40.792291220556734],
'min_JK': 16.8314150305,
'max_JK': 95}
cm_data = [[ 5.03832136e-02, 2.98028976e-02, 5.27974883e-01],
[ 6.35363639e-02, 2.84259729e-02, 5.33123681e-01],
[ 7.53531234e-02, 2.72063728e-02, 5.38007001e-01],
[ 8.62217979e-02, 2.61253206e-02, 5.42657691e-01],
[ 9.63786097e-02, 2.51650976e-02, 5.47103487e-01],
[ 1.05979704e-01, 2.43092436e-02, 5.51367851e-01],
[ 1.15123641e-01, 2.35562500e-02, 5.55467728e-01],
[ 1.23902903e-01, 2.28781011e-02, 5.59423480e-01],
[ 1.32380720e-01, 2.22583774e-02, 5.63250116e-01],
[ 1.40603076e-01, 2.16866674e-02, 5.66959485e-01],
[ 1.48606527e-01, 2.11535876e-02, 5.70561711e-01],
[ 1.56420649e-01, 2.06507174e-02, 5.74065446e-01],
[ 1.64069722e-01, 2.01705326e-02, 5.77478074e-01],
[ 1.71573925e-01, 1.97063415e-02, 5.80805890e-01],
[ 1.78950212e-01, 1.92522243e-02, 5.84054243e-01],
[ 1.86212958e-01, 1.88029767e-02, 5.87227661e-01],
[ 1.93374449e-01, 1.83540593e-02, 5.90329954e-01],
[ 2.00445260e-01, 1.79015512e-02, 5.93364304e-01],
[ 2.07434551e-01, 1.74421086e-02, 5.96333341e-01],
[ 2.14350298e-01, 1.69729276e-02, 5.99239207e-01],
[ 2.21196750e-01, 1.64970484e-02, 6.02083323e-01],
[ 2.27982971e-01, 1.60071509e-02, 6.04867403e-01],
[ 2.34714537e-01, 1.55015065e-02, 6.07592438e-01],
[ 2.41396253e-01, 1.49791041e-02, 6.10259089e-01],
[ 2.48032377e-01, 1.44393586e-02, 6.12867743e-01],
[ 2.54626690e-01, 1.38820918e-02, 6.15418537e-01],
[ 2.61182562e-01, 1.33075156e-02, 6.17911385e-01],
[ 2.67702993e-01, 1.27162163e-02, 6.20345997e-01],
[ 2.74190665e-01, 1.21091423e-02, 6.22721903e-01],
[ 2.80647969e-01, 1.14875915e-02, 6.25038468e-01],
[ 2.87076059e-01, 1.08554862e-02, 6.27294975e-01],
[ 2.93477695e-01, 1.02128849e-02, 6.29490490e-01],
[ 2.99855122e-01, 9.56079551e-03, 6.31623923e-01],
[ 3.06209825e-01, 8.90185346e-03, 6.33694102e-01],
[ 3.12543124e-01, 8.23900704e-03, 6.35699759e-01],
[ 3.18856183e-01, 7.57551051e-03, 6.37639537e-01],
[ 3.25150025e-01, 6.91491734e-03, 6.39512001e-01],
[ 3.31425547e-01, 6.26107379e-03, 6.41315649e-01],
[ 3.37683446e-01, 5.61830889e-03, 6.43048936e-01],
[ 3.43924591e-01, 4.99053080e-03, 6.44710195e-01],
[ 3.50149699e-01, 4.38202557e-03, 6.46297711e-01],
[ 3.56359209e-01, 3.79781761e-03, 6.47809772e-01],
[ 3.62553473e-01, 3.24319591e-03, 6.49244641e-01],
[ 3.68732762e-01, 2.72370721e-03, 6.50600561e-01],
[ 3.74897270e-01, 2.24514897e-03, 6.51875762e-01],
[ 3.81047116e-01, 1.81356205e-03, 6.53068467e-01],
[ 3.87182639e-01, 1.43446923e-03, 6.54176761e-01],
[ 3.93304010e-01, 1.11388259e-03, 6.55198755e-01],
[ 3.99410821e-01, 8.59420809e-04, 6.56132835e-01],
[ 4.05502914e-01, 6.78091517e-04, 6.56977276e-01],
[ 4.11580082e-01, 5.77101735e-04, 6.57730380e-01],
[ 4.17642063e-01, 5.63847476e-04, 6.58390492e-01],
[ 4.23688549e-01, 6.45902780e-04, 6.58956004e-01],
[ 4.29719186e-01, 8.31008207e-04, 6.59425363e-01],
[ 4.35733575e-01, 1.12705875e-03, 6.59797077e-01],
[ 4.41732123e-01, 1.53984779e-03, 6.60069009e-01],
[ 4.47713600e-01, 2.07954744e-03, 6.60240367e-01],
[ 4.53677394e-01, 2.75470302e-03, 6.60309966e-01],
[ 4.59622938e-01, 3.57374415e-03, 6.60276655e-01],
[ 4.65549631e-01, 4.54518084e-03, 6.60139383e-01],
[ 4.71456847e-01, 5.67758762e-03, 6.59897210e-01],
[ 4.77343929e-01, 6.97958743e-03, 6.59549311e-01],
[ 4.83210198e-01, 8.45983494e-03, 6.59094989e-01],
[ 4.89054951e-01, 1.01269996e-02, 6.58533677e-01],
[ 4.94877466e-01, 1.19897486e-02, 6.57864946e-01],
[ 5.00677687e-01, 1.40550640e-02, 6.57087561e-01],
[ 5.06454143e-01, 1.63333443e-02, 6.56202294e-01],
[ 5.12206035e-01, 1.88332232e-02, 6.55209222e-01],
[ 5.17932580e-01, 2.15631918e-02, 6.54108545e-01],
[ 5.23632990e-01, 2.45316468e-02, 6.52900629e-01],
[ 5.29306474e-01, 2.77468735e-02, 6.51586010e-01],
[ 5.34952244e-01, 3.12170300e-02, 6.50165396e-01],
[ 5.40569510e-01, 3.49501310e-02, 6.48639668e-01],
[ 5.46157494e-01, 3.89540334e-02, 6.47009884e-01],
[ 5.51715423e-01, 4.31364795e-02, 6.45277275e-01],
[ 5.57242538e-01, 4.73307585e-02, 6.43443250e-01],
[ 5.62738096e-01, 5.15448092e-02, 6.41509389e-01],
[ 5.68201372e-01, 5.57776706e-02, 6.39477440e-01],
[ 5.73631859e-01, 6.00281369e-02, 6.37348841e-01],
[ 5.79028682e-01, 6.42955547e-02, 6.35126108e-01],
[ 5.84391137e-01, 6.85790261e-02, 6.32811608e-01],
[ 5.89718606e-01, 7.28775875e-02, 6.30407727e-01],
[ 5.95010505e-01, 7.71902878e-02, 6.27916992e-01],
[ 6.00266283e-01, 8.15161895e-02, 6.25342058e-01],
[ 6.05485428e-01, 8.58543713e-02, 6.22685703e-01],
[ 6.10667469e-01, 9.02039303e-02, 6.19950811e-01],
[ 6.15811974e-01, 9.45639838e-02, 6.17140367e-01],
[ 6.20918555e-01, 9.89336721e-02, 6.14257440e-01],
[ 6.25986869e-01, 1.03312160e-01, 6.11305174e-01],
[ 6.31016615e-01, 1.07698641e-01, 6.08286774e-01],
[ 6.36007543e-01, 1.12092335e-01, 6.05205491e-01],
[ 6.40959444e-01, 1.16492495e-01, 6.02064611e-01],
[ 6.45872158e-01, 1.20898405e-01, 5.98867442e-01],
[ 6.50745571e-01, 1.25309384e-01, 5.95617300e-01],
[ 6.55579615e-01, 1.29724785e-01, 5.92317494e-01],
[ 6.60374266e-01, 1.34143997e-01, 5.88971318e-01],
[ 6.65129493e-01, 1.38566428e-01, 5.85582301e-01],
[ 6.69845385e-01, 1.42991540e-01, 5.82153572e-01],
[ 6.74522060e-01, 1.47418835e-01, 5.78688247e-01],
[ 6.79159664e-01, 1.51847851e-01, 5.75189431e-01],
[ 6.83758384e-01, 1.56278163e-01, 5.71660158e-01],
[ 6.88318440e-01, 1.60709387e-01, 5.68103380e-01],
[ 6.92840088e-01, 1.65141174e-01, 5.64521958e-01],
[ 6.97323615e-01, 1.69573215e-01, 5.60918659e-01],
[ 7.01769334e-01, 1.74005236e-01, 5.57296144e-01],
[ 7.06177590e-01, 1.78437000e-01, 5.53656970e-01],
[ 7.10548747e-01, 1.82868306e-01, 5.50003579e-01],
[ 7.14883195e-01, 1.87298986e-01, 5.46338299e-01],
[ 7.19181339e-01, 1.91728906e-01, 5.42663338e-01],
[ 7.23443604e-01, 1.96157962e-01, 5.38980786e-01],
[ 7.27670428e-01, 2.00586086e-01, 5.35292612e-01],
[ 7.31862231e-01, 2.05013174e-01, 5.31600995e-01],
[ 7.36019424e-01, 2.09439071e-01, 5.27908434e-01],
[ 7.40142557e-01, 2.13863965e-01, 5.24215533e-01],
[ 7.44232102e-01, 2.18287899e-01, 5.20523766e-01],
[ 7.48288533e-01, 2.22710942e-01, 5.16834495e-01],
[ 7.52312321e-01, 2.27133187e-01, 5.13148963e-01],
[ 7.56303937e-01, 2.31554749e-01, 5.09468305e-01],
[ 7.60263849e-01, 2.35975765e-01, 5.05793543e-01],
[ 7.64192516e-01, 2.40396394e-01, 5.02125599e-01],
[ 7.68090391e-01, 2.44816813e-01, 4.98465290e-01],
[ 7.71957916e-01, 2.49237220e-01, 4.94813338e-01],
[ 7.75795522e-01, 2.53657797e-01, 4.91170517e-01],
[ 7.79603614e-01, 2.58078397e-01, 4.87539124e-01],
[ 7.83382636e-01, 2.62499662e-01, 4.83917732e-01],
[ 7.87132978e-01, 2.66921859e-01, 4.80306702e-01],
[ 7.90855015e-01, 2.71345267e-01, 4.76706319e-01],
[ 7.94549101e-01, 2.75770179e-01, 4.73116798e-01],
[ 7.98215577e-01, 2.80196901e-01, 4.69538286e-01],
[ 8.01854758e-01, 2.84625750e-01, 4.65970871e-01],
[ 8.05466945e-01, 2.89057057e-01, 4.62414580e-01],
[ 8.09052419e-01, 2.93491117e-01, 4.58869577e-01],
[ 8.12611506e-01, 2.97927865e-01, 4.55337565e-01],
[ 8.16144382e-01, 3.02368130e-01, 4.51816385e-01],
[ 8.19651255e-01, 3.06812282e-01, 4.48305861e-01],
[ 8.23132309e-01, 3.11260703e-01, 4.44805781e-01],
[ 8.26587706e-01, 3.15713782e-01, 4.41315901e-01],
[ 8.30017584e-01, 3.20171913e-01, 4.37835947e-01],
[ 8.33422053e-01, 3.24635499e-01, 4.34365616e-01],
[ 8.36801237e-01, 3.29104836e-01, 4.30905052e-01],
[ 8.40155276e-01, 3.33580106e-01, 4.27454836e-01],
[ 8.43484103e-01, 3.38062109e-01, 4.24013059e-01],
[ 8.46787726e-01, 3.42551272e-01, 4.20579333e-01],
[ 8.50066132e-01, 3.47048028e-01, 4.17153264e-01],
[ 8.53319279e-01, 3.51552815e-01, 4.13734445e-01],
[ 8.56547103e-01, 3.56066072e-01, 4.10322469e-01],
[ 8.59749520e-01, 3.60588229e-01, 4.06916975e-01],
[ 8.62926559e-01, 3.65119408e-01, 4.03518809e-01],
[ 8.66077920e-01, 3.69660446e-01, 4.00126027e-01],
[ 8.69203436e-01, 3.74211795e-01, 3.96738211e-01],
[ 8.72302917e-01, 3.78773910e-01, 3.93354947e-01],
[ 8.75376149e-01, 3.83347243e-01, 3.89975832e-01],
[ 8.78422895e-01, 3.87932249e-01, 3.86600468e-01],
[ 8.81442916e-01, 3.92529339e-01, 3.83228622e-01],
[ 8.84435982e-01, 3.97138877e-01, 3.79860246e-01],
[ 8.87401682e-01, 4.01761511e-01, 3.76494232e-01],
[ 8.90339687e-01, 4.06397694e-01, 3.73130228e-01],
[ 8.93249647e-01, 4.11047871e-01, 3.69767893e-01],
[ 8.96131191e-01, 4.15712489e-01, 3.66406907e-01],
[ 8.98983931e-01, 4.20391986e-01, 3.63046965e-01],
[ 9.01807455e-01, 4.25086807e-01, 3.59687758e-01],
[ 9.04601295e-01, 4.29797442e-01, 3.56328796e-01],
[ 9.07364995e-01, 4.34524335e-01, 3.52969777e-01],
[ 9.10098088e-01, 4.39267908e-01, 3.49610469e-01],
[ 9.12800095e-01, 4.44028574e-01, 3.46250656e-01],
[ 9.15470518e-01, 4.48806744e-01, 3.42890148e-01],
[ 9.18108848e-01, 4.53602818e-01, 3.39528771e-01],
[ 9.20714383e-01, 4.58417420e-01, 3.36165582e-01],
[ 9.23286660e-01, 4.63250828e-01, 3.32800827e-01],
[ 9.25825146e-01, 4.68103387e-01, 3.29434512e-01],
[ 9.28329275e-01, 4.72975465e-01, 3.26066550e-01],
[ 9.30798469e-01, 4.77867420e-01, 3.22696876e-01],
[ 9.33232140e-01, 4.82779603e-01, 3.19325444e-01],
[ 9.35629684e-01, 4.87712357e-01, 3.15952211e-01],
[ 9.37990034e-01, 4.92666544e-01, 3.12575440e-01],
[ 9.40312939e-01, 4.97642038e-01, 3.09196628e-01],
[ 9.42597771e-01, 5.02639147e-01, 3.05815824e-01],
[ 9.44843893e-01, 5.07658169e-01, 3.02433101e-01],
[ 9.47050662e-01, 5.12699390e-01, 2.99048555e-01],
[ 9.49217427e-01, 5.17763087e-01, 2.95662308e-01],
[ 9.51343530e-01, 5.22849522e-01, 2.92274506e-01],
[ 9.53427725e-01, 5.27959550e-01, 2.88883445e-01],
[ 9.55469640e-01, 5.33093083e-01, 2.85490391e-01],
[ 9.57468770e-01, 5.38250172e-01, 2.82096149e-01],
[ 9.59424430e-01, 5.43431038e-01, 2.78700990e-01],
[ 9.61335930e-01, 5.48635890e-01, 2.75305214e-01],
[ 9.63202573e-01, 5.53864931e-01, 2.71909159e-01],
[ 9.65023656e-01, 5.59118349e-01, 2.68513200e-01],
[ 9.66798470e-01, 5.64396327e-01, 2.65117752e-01],
[ 9.68525639e-01, 5.69699633e-01, 2.61721488e-01],
[ 9.70204593e-01, 5.75028270e-01, 2.58325424e-01],
[ 9.71835007e-01, 5.80382015e-01, 2.54931256e-01],
[ 9.73416145e-01, 5.85761012e-01, 2.51539615e-01],
[ 9.74947262e-01, 5.91165394e-01, 2.48151200e-01],
[ 9.76427606e-01, 5.96595287e-01, 2.44766775e-01],
[ 9.77856416e-01, 6.02050811e-01, 2.41387186e-01],
[ 9.79232922e-01, 6.07532077e-01, 2.38013359e-01],
[ 9.80556344e-01, 6.13039190e-01, 2.34646316e-01],
[ 9.81825890e-01, 6.18572250e-01, 2.31287178e-01],
[ 9.83040742e-01, 6.24131362e-01, 2.27937141e-01],
[ 9.84198924e-01, 6.29717516e-01, 2.24595006e-01],
[ 9.85300760e-01, 6.35329876e-01, 2.21264889e-01],
[ 9.86345421e-01, 6.40968508e-01, 2.17948456e-01],
[ 9.87332067e-01, 6.46633475e-01, 2.14647532e-01],
[ 9.88259846e-01, 6.52324832e-01, 2.11364122e-01],
[ 9.89127893e-01, 6.58042630e-01, 2.08100426e-01],
[ 9.89935328e-01, 6.63786914e-01, 2.04858855e-01],
[ 9.90681261e-01, 6.69557720e-01, 2.01642049e-01],
[ 9.91364787e-01, 6.75355082e-01, 1.98452900e-01],
[ 9.91984990e-01, 6.81179025e-01, 1.95294567e-01],
[ 9.92540939e-01, 6.87029567e-01, 1.92170500e-01],
[ 9.93031693e-01, 6.92906719e-01, 1.89084459e-01],
[ 9.93456302e-01, 6.98810484e-01, 1.86040537e-01],
[ 9.93813802e-01, 7.04740854e-01, 1.83043180e-01],
[ 9.94103226e-01, 7.10697814e-01, 1.80097207e-01],
[ 9.94323596e-01, 7.16681336e-01, 1.77207826e-01],
[ 9.94473934e-01, 7.22691379e-01, 1.74380656e-01],
[ 9.94553260e-01, 7.28727890e-01, 1.71621733e-01],
[ 9.94560594e-01, 7.34790799e-01, 1.68937522e-01],
[ 9.94494964e-01, 7.40880020e-01, 1.66334918e-01],
[ 9.94355411e-01, 7.46995448e-01, 1.63821243e-01],
[ 9.94140989e-01, 7.53136955e-01, 1.61404226e-01],
[ 9.93850778e-01, 7.59304390e-01, 1.59091984e-01],
[ 9.93482190e-01, 7.65498551e-01, 1.56890625e-01],
[ 9.93033251e-01, 7.71719833e-01, 1.54807583e-01],
[ 9.92505214e-01, 7.77966775e-01, 1.52854862e-01],
[ 9.91897270e-01, 7.84239120e-01, 1.51041581e-01],
[ 9.91208680e-01, 7.90536569e-01, 1.49376885e-01],
[ 9.90438793e-01, 7.96858775e-01, 1.47869810e-01],
[ 9.89587065e-01, 8.03205337e-01, 1.46529128e-01],
[ 9.88647741e-01, 8.09578605e-01, 1.45357284e-01],
[ 9.87620557e-01, 8.15977942e-01, 1.44362644e-01],
[ 9.86509366e-01, 8.22400620e-01, 1.43556679e-01],
[ 9.85314198e-01, 8.28845980e-01, 1.42945116e-01],
[ 9.84031139e-01, 8.35315360e-01, 1.42528388e-01],
[ 9.82652820e-01, 8.41811730e-01, 1.42302653e-01],
[ 9.81190389e-01, 8.48328902e-01, 1.42278607e-01],
[ 9.79643637e-01, 8.54866468e-01, 1.42453425e-01],
[ 9.77994918e-01, 8.61432314e-01, 1.42808191e-01],
[ 9.76264977e-01, 8.68015998e-01, 1.43350944e-01],
[ 9.74443038e-01, 8.74622194e-01, 1.44061156e-01],
[ 9.72530009e-01, 8.81250063e-01, 1.44922913e-01],
[ 9.70532932e-01, 8.87896125e-01, 1.45918663e-01],
[ 9.68443477e-01, 8.94563989e-01, 1.47014438e-01],
[ 9.66271225e-01, 9.01249365e-01, 1.48179639e-01],
[ 9.64021057e-01, 9.07950379e-01, 1.49370428e-01],
[ 9.61681481e-01, 9.14672479e-01, 1.50520343e-01],
[ 9.59275646e-01, 9.21406537e-01, 1.51566019e-01],
[ 9.56808068e-01, 9.28152065e-01, 1.52409489e-01],
[ 9.54286813e-01, 9.34907730e-01, 1.52921158e-01],
[ 9.51726083e-01, 9.41670605e-01, 1.52925363e-01],
[ 9.49150533e-01, 9.48434900e-01, 1.52177604e-01],
[ 9.46602270e-01, 9.55189860e-01, 1.50327944e-01],
[ 9.44151742e-01, 9.61916487e-01, 1.46860789e-01],
[ 9.41896120e-01, 9.68589814e-01, 1.40955606e-01],
[ 9.40015097e-01, 9.75158357e-01, 1.31325517e-01]]
test_cm = LinearSegmentedColormap.from_list(__file__, cm_data)
if __name__ == "__main__":
import matplotlib.pyplot as plt
import numpy as np
try:
from viscm import viscm
viscm(test_cm)
except ImportError:
print("viscm not found, falling back on simple display")
plt.imshow(np.linspace(0, 100, 256)[None, :], aspect='auto',
cmap=test_cm)
plt.show()
| 60.187279 | 141 | 0.577291 |
e0709fa966341538c2d49529de984d39878ed846
| 3,885 |
py
|
Python
|
RPI/yolov5/algorithm/planner/algorithms/hybrid_astar/draw/draw.py
|
Aditya239233/MDP
|
87491e1d67e547c11f4bdd5d784d120473429eae
|
[
"MIT"
] | 4 |
2022-01-14T15:06:43.000Z
|
2022-01-18T14:45:04.000Z
|
RPI/yolov5/algorithm/planner/algorithms/hybrid_astar/draw/draw.py
|
Aditya239233/MDP
|
87491e1d67e547c11f4bdd5d784d120473429eae
|
[
"MIT"
] | null | null | null |
RPI/yolov5/algorithm/planner/algorithms/hybrid_astar/draw/draw.py
|
Aditya239233/MDP
|
87491e1d67e547c11f4bdd5d784d120473429eae
|
[
"MIT"
] | null | null | null |
import matplotlib.pyplot as plt
import numpy as np
import math
from algorithm.planner.utils.car_utils import Car_C
PI = np.pi
def draw_car(x, y, yaw, steer, color='black', extended_car=True):
if extended_car:
car = np.array([[-Car_C.RB, -Car_C.RB, Car_C.RF, Car_C.RF, -Car_C.RB, Car_C.ACTUAL_RF, Car_C.ACTUAL_RF, -Car_C.ACTUAL_RB, -Car_C.ACTUAL_RB],
[Car_C.W / 2, -Car_C.W / 2, -Car_C.W / 2, Car_C.W / 2, Car_C.W / 2, Car_C.W/2, -Car_C.W/2, -Car_C.W/2, Car_C.W/2]])
else:
car = np.array([[-Car_C.RB, -Car_C.RB, Car_C.RF, Car_C.RF, -Car_C.RB],
[Car_C.W / 2, -Car_C.W / 2, -Car_C.W / 2, Car_C.W / 2, Car_C.W / 2]])
wheel = np.array([[-Car_C.TR, -Car_C.TR, Car_C.TR, Car_C.TR, -Car_C.TR],
[Car_C.TW / 4, -Car_C.TW / 4, -Car_C.TW / 4, Car_C.TW / 4, Car_C.TW / 4]])
rlWheel = wheel.copy()
rrWheel = wheel.copy()
frWheel = wheel.copy()
flWheel = wheel.copy()
Rot1 = np.array([[math.cos(yaw), -math.sin(yaw)],
[math.sin(yaw), math.cos(yaw)]])
Rot2 = np.array([[math.cos(steer), math.sin(steer)],
[-math.sin(steer), math.cos(steer)]])
frWheel = np.dot(Rot2, frWheel)
flWheel = np.dot(Rot2, flWheel)
frWheel += np.array([[Car_C.WB], [-Car_C.WD / 2]])
flWheel += np.array([[Car_C.WB], [Car_C.WD / 2]])
rrWheel[1, :] -= Car_C.WD / 2
rlWheel[1, :] += Car_C.WD / 2
frWheel = np.dot(Rot1, frWheel)
flWheel = np.dot(Rot1, flWheel)
rrWheel = np.dot(Rot1, rrWheel)
rlWheel = np.dot(Rot1, rlWheel)
car = np.dot(Rot1, car)
frWheel += np.array([[x], [y]])
flWheel += np.array([[x], [y]])
rrWheel += np.array([[x], [y]])
rlWheel += np.array([[x], [y]])
car += np.array([[x], [y]])
plt.plot(car[0, :], car[1, :], color)
plt.plot(frWheel[0, :], frWheel[1, :], color)
plt.plot(rrWheel[0, :], rrWheel[1, :], color)
plt.plot(flWheel[0, :], flWheel[1, :], color)
plt.plot(rlWheel[0, :], rlWheel[1, :], color)
Arrow(x, y, yaw, Car_C.WB * 0.8, color)
| 33.491379 | 148 | 0.53565 |
e0712713ade0b6560e6616c234015a83c6ef39c9
| 696 |
py
|
Python
|
models/database_models/comment_model.py
|
RuiCoreSci/Flask-Restful
|
03f98a17487d407b69b853a9bf0ed20d2c5b003b
|
[
"MIT"
] | 7 |
2020-05-24T02:15:46.000Z
|
2020-11-26T07:14:44.000Z
|
models/database_models/comment_model.py
|
RuiCoreSci/Flask-Restful
|
03f98a17487d407b69b853a9bf0ed20d2c5b003b
|
[
"MIT"
] | 12 |
2020-05-17T10:46:29.000Z
|
2021-05-06T20:08:37.000Z
|
models/database_models/comment_model.py
|
RuiCoreSci/Flask-Restful
|
03f98a17487d407b69b853a9bf0ed20d2c5b003b
|
[
"MIT"
] | 4 |
2020-05-09T07:26:09.000Z
|
2021-10-31T07:09:10.000Z
|
from sqlalchemy import Integer, Text, DateTime, func, Boolean, text
from models.database_models import Base, Column
| 40.941176 | 106 | 0.728448 |
e072653c74adbd64f985b81e9b674ad50e5a700a
| 27,779 |
py
|
Python
|
aws_deploy/ecs/helper.py
|
jmsantorum/aws-deploy
|
f117cff3a5440ee42470feaa2a83263c3212cf10
|
[
"BSD-3-Clause"
] | null | null | null |
aws_deploy/ecs/helper.py
|
jmsantorum/aws-deploy
|
f117cff3a5440ee42470feaa2a83263c3212cf10
|
[
"BSD-3-Clause"
] | null | null | null |
aws_deploy/ecs/helper.py
|
jmsantorum/aws-deploy
|
f117cff3a5440ee42470feaa2a83263c3212cf10
|
[
"BSD-3-Clause"
] | 1 |
2021-08-05T12:07:11.000Z
|
2021-08-05T12:07:11.000Z
|
import json
import re
from datetime import datetime
from json.decoder import JSONDecodeError
import click
from boto3.session import Session
from boto3_type_annotations.ecs import Client
from botocore.exceptions import ClientError, NoCredentialsError
from dateutil.tz.tz import tzlocal
from dictdiffer import diff
JSON_LIST_REGEX = re.compile(r'^\[.*\]$')
LAUNCH_TYPE_EC2 = 'EC2'
LAUNCH_TYPE_FARGATE = 'FARGATE'
class EcsTaskDefinition(object):
def show_diff(self, show_diff: bool = False):
if show_diff:
click.secho('Task definition modified:')
for d in self._diff:
click.secho(f' {str(d)}', fg='blue')
click.secho('')
def get_tag(self, key):
for tag in self.tags:
if tag['key'] == key:
return tag['value']
return None
def set_tag(self, key: str, value: str):
if key and value:
done = False
for tag in self.tags:
if tag['key'] == key:
if tag['value'] != value:
diff = EcsTaskDefinitionDiff(
container=None,
field=f"tags['{key}']",
value=value,
old_value=tag['value']
)
self._diff.append(diff)
tag['value'] = value
done = True
break
if not done:
diff = EcsTaskDefinitionDiff(container=None, field=f"tags['{key}']", value=value, old_value=None)
self._diff.append(diff)
self.tags.append({'key': key, 'value': value})
class EcsTaskDefinitionDiff(object):
| 34.767209 | 119 | 0.585586 |
e07447362c2cd948e8959b2a92a8309441af1ece
| 3,715 |
py
|
Python
|
sbm.py
|
emmaling27/networks-research
|
be209e2b653a1fe9eec480a94538d59104e4aa23
|
[
"MIT"
] | null | null | null |
sbm.py
|
emmaling27/networks-research
|
be209e2b653a1fe9eec480a94538d59104e4aa23
|
[
"MIT"
] | null | null | null |
sbm.py
|
emmaling27/networks-research
|
be209e2b653a1fe9eec480a94538d59104e4aa23
|
[
"MIT"
] | null | null | null |
import networkx as nx
from scipy.special import comb
import attr
| 35.04717 | 125 | 0.54105 |
e0745cd9bd4ca77f2c09e9dd6bb425b9d75991b3
| 4,516 |
py
|
Python
|
src/data/graph/ops/anagram_transform_op.py
|
PhilHarnish/forge
|
663f19d759b94d84935c14915922070635a4af65
|
[
"MIT"
] | 2 |
2020-08-18T18:43:09.000Z
|
2020-08-18T20:05:59.000Z
|
src/data/graph/ops/anagram_transform_op.py
|
PhilHarnish/forge
|
663f19d759b94d84935c14915922070635a4af65
|
[
"MIT"
] | null | null | null |
src/data/graph/ops/anagram_transform_op.py
|
PhilHarnish/forge
|
663f19d759b94d84935c14915922070635a4af65
|
[
"MIT"
] | null | null | null |
from typing import Callable, Collection, Iterable, List, Union
from data.anagram import anagram_iter
from data.graph import _op_mixin, bloom_mask, bloom_node, bloom_node_reducer
Transformer = Callable[['bloom_node.BloomNode'], 'bloom_node.BloomNode']
_SPACE_MASK = bloom_mask.for_alpha(' ')
def _normalize_state(
exit_node: 'bloom_node.BloomNode',
index: Union[Iterable, anagram_iter.AnagramIter]) -> _AnagramState:
if isinstance(index, _AnagramState):
return index
# `index` is an iterable list of ???, one-by-one these will be taken as a
# route to the `exit_node`.
initial_anagrams = anagram_iter.from_choices(index)
index = _AnagramTransformIndex(exit_node, initial_anagrams)
return _AnagramState(index, initial_anagrams)
| 35.84127 | 79 | 0.717449 |
e074a8e70a88cdf3e39529ffdda1dc94abc0febf
| 15,854 |
py
|
Python
|
gogapi/api.py
|
tikki/pygogapi
|
f1b3a811444dc521ea4ad7884104086b52348995
|
[
"MIT"
] | 23 |
2017-01-03T21:00:27.000Z
|
2022-01-25T22:08:39.000Z
|
gogapi/api.py
|
tikki/pygogapi
|
f1b3a811444dc521ea4ad7884104086b52348995
|
[
"MIT"
] | 3 |
2017-06-06T23:08:30.000Z
|
2019-01-28T02:20:34.000Z
|
gogapi/api.py
|
tikki/pygogapi
|
f1b3a811444dc521ea4ad7884104086b52348995
|
[
"MIT"
] | 8 |
2017-02-10T15:13:32.000Z
|
2020-04-18T11:17:15.000Z
|
import json
import re
import logging
import html.parser
import zlib
import requests
from gogapi import urls
from gogapi.base import NotAuthorizedError, logger
from gogapi.product import Product, Series
from gogapi.search import SearchResult
DEBUG_JSON = False
GOGDATA_RE = re.compile(r"gogData\.?(.*?) = (.+);")
CLIENT_VERSION = "1.2.17.9" # Just for their statistics
USER_AGENT = "GOGGalaxyClient/{} pygogapi/0.1".format(CLIENT_VERSION)
REQUEST_RETRIES = 3
PRODUCT_EXPANDABLE = [
"downloads", "expanded_dlcs", "description", "screenshots", "videos",
"related_products", "changelog"
]
USER_EXPANDABLE = ["friendStatus", "wishlistStatus", "blockedStatus"]
LOCALE_CODES = ["de-DE", "en-US", "fr-FR", "pt-BR", "pl-PL", "ru-RU", "zh-Hans"]
CURRENCY_CODES = [
"USD", "EUR", "GBP", "AUD", "RUB", "PLN", "CAD", "CHF", "NOK", "SEK", "DKK"
]
| 32.892116 | 80 | 0.628233 |
e0756c223fe0a2644bdda0e4b367139a612e5089
| 943 |
py
|
Python
|
setup.py
|
gibsonMatt/stacks-pairwise
|
8f3cde603c2bfed255f6c399557e9332072886fb
|
[
"MIT"
] | null | null | null |
setup.py
|
gibsonMatt/stacks-pairwise
|
8f3cde603c2bfed255f6c399557e9332072886fb
|
[
"MIT"
] | null | null | null |
setup.py
|
gibsonMatt/stacks-pairwise
|
8f3cde603c2bfed255f6c399557e9332072886fb
|
[
"MIT"
] | null | null | null |
import pathlib
import os
from setuptools import setup
# The directory containing this file
HERE = pathlib.Path(__file__).parent
# The text of the README file
README = (HERE / "README.md").read_text()
# specify requirements of your package here
REQUIREMENTS = ['biopython', 'numpy', 'pandas']
setup(name='stacksPairwise',
version='0.0.0',
description='Calculate pairwise divergence (pairwise pi) from Stacks `samples.fa` output fle',
long_description=README,
long_description_content_type="text/markdown",
url='https://github.com/gibsonmatt/stacks-pairwise',
author='Matt Gibson',
author_email='[email protected]',
license='MIT',
packages=['stacksPairwise'],
install_requires=REQUIREMENTS,
entry_points={
"console_scripts": [
"stacksPairwise=stacksPairwise.__main__:main"
]
},
keywords='genetics genotyping sequencing Stacks'
)
| 29.46875 | 100 | 0.694592 |
e076824b715f780b36bdb8e03020e256a3cf8b8d
| 156 |
py
|
Python
|
csv_experiment.py
|
komax/spanningtree-crossingnumber
|
444c8809a543905000a63c9d2ff1dcfb31835766
|
[
"MIT"
] | 2 |
2019-01-07T22:12:09.000Z
|
2020-05-08T06:44:19.000Z
|
csv_experiment.py
|
komax/spanningtree-crossingnumber
|
444c8809a543905000a63c9d2ff1dcfb31835766
|
[
"MIT"
] | null | null | null |
csv_experiment.py
|
komax/spanningtree-crossingnumber
|
444c8809a543905000a63c9d2ff1dcfb31835766
|
[
"MIT"
] | null | null | null |
#! /usr/bin/env python
import os
import sys
args = sys.argv[1:]
os.system('python -O -m spanningtree.csv_experiment_statistics ' +
' '.join(args))
| 19.5 | 66 | 0.673077 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.