max_stars_repo_path stringlengths 4 286 | max_stars_repo_name stringlengths 5 119 | max_stars_count int64 0 191k | id stringlengths 1 7 | content stringlengths 6 1.03M | content_cleaned stringlengths 6 1.03M | language stringclasses 111
values | language_score float64 0.03 1 | comments stringlengths 0 556k | edu_score float64 0.32 5.03 | edu_int_score int64 0 5 |
|---|---|---|---|---|---|---|---|---|---|---|
ProjectEuler/9.py | RobVor/Python | 0 | 6626551 | """A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2."""
def Pythagorean_Triplet(N):
for a in range(1,N):
for b in range(1,N):
c = 1000 - a - b
if c > 0:
if c*c==a*a+b*b:
... | """A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2."""
def Pythagorean_Triplet(N):
for a in range(1,N):
for b in range(1,N):
c = 1000 - a - b
if c > 0:
if c*c==a*a+b*b:
... | en | 0.743266 | A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. | 4.377424 | 4 |
marmot/representations/tests/test_word_qe_representation_generator.py | qe-team/marmot | 19 | 6626552 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import unittest
import os
import yaml
import marmot
from marmot.representations.word_qe_representation_generator import WordQERepresentationGenerator
from marmot.experiment.import_utils import build_object
def join_with_module_path(loader, node):
""" define custom tag h... | #!/usr/bin/python
# -*- coding: utf-8 -*-
import unittest
import os
import yaml
import marmot
from marmot.representations.word_qe_representation_generator import WordQERepresentationGenerator
from marmot.experiment.import_utils import build_object
def join_with_module_path(loader, node):
""" define custom tag h... | en | 0.63436 | #!/usr/bin/python # -*- coding: utf-8 -*- define custom tag handler to join paths with the path of the marmot module ## register the tag handler # TODO: test that tokenization happens like we expect | 2.502521 | 3 |
verification/referee.py | CheckiO-Missions/checkio-mission-family-gifts | 0 | 6626553 | <reponame>CheckiO-Missions/checkio-mission-family-gifts
from checkio.signals import ON_CONNECT
from checkio import api
from checkio.referees.io import CheckiOReferee
from tests import TESTS
cover = """def cover(f, data):
return f(set(str(x) for x in data[0]), tuple(set(str(n) for n in coup) for coup in data[1]))
... | from checkio.signals import ON_CONNECT
from checkio import api
from checkio.referees.io import CheckiOReferee
from tests import TESTS
cover = """def cover(f, data):
return f(set(str(x) for x in data[0]), tuple(set(str(n) for n in coup) for coup in data[1]))
"""
ERR_REPEAT = "Every person should be able to give t... | en | 0.306534 | def cover(f, data): return f(set(str(x) for x in data[0]), tuple(set(str(n) for n in coup) for coup in data[1])) # add_allowed_modules=[], # add_close_builtins=[], # remove_allowed_modules=[] | 2.862688 | 3 |
det3d/datasets/pipelines/__init__.py | reinforcementdriving/CIA-SSD | 382 | 6626554 | from .compose import Compose
from .formating import Reformat
# from .loading import LoadAnnotations, LoadImageFromFile, LoadProposals
from .loading import *
from .test_aug import MultiScaleFlipAug
from .transforms import (
Expand,
MinIoURandomCrop,
Normalize,
Pad,
PhotoMetricDistortion,
RandomC... | from .compose import Compose
from .formating import Reformat
# from .loading import LoadAnnotations, LoadImageFromFile, LoadProposals
from .loading import *
from .test_aug import MultiScaleFlipAug
from .transforms import (
Expand,
MinIoURandomCrop,
Normalize,
Pad,
PhotoMetricDistortion,
RandomC... | en | 0.428708 | # from .loading import LoadAnnotations, LoadImageFromFile, LoadProposals | 1.447724 | 1 |
meteocalc/windchill.py | malexer/meteocalc | 20 | 6626555 | <filename>meteocalc/windchill.py<gh_stars>10-100
"""Module for calculation of Wind chill.
Wind-chill or windchill (popularly wind chill factor) is the lowering of
body temperature due to the passing-flow of lower-temperature air.
Wind chill numbers are always lower than the air temperature for values
where the formul... | <filename>meteocalc/windchill.py<gh_stars>10-100
"""Module for calculation of Wind chill.
Wind-chill or windchill (popularly wind chill factor) is the lowering of
body temperature due to the passing-flow of lower-temperature air.
Wind chill numbers are always lower than the air temperature for values
where the formul... | en | 0.750588 | Module for calculation of Wind chill. Wind-chill or windchill (popularly wind chill factor) is the lowering of body temperature due to the passing-flow of lower-temperature air. Wind chill numbers are always lower than the air temperature for values where the formula is valid. When the apparent temperature is higher ... | 4.059145 | 4 |
iotbx/examples/pdb_hierarchy.py | dperl-sol/cctbx_project | 155 | 6626556 | from __future__ import absolute_import, division, print_function
import iotbx.pdb
import random
import sys
def run(args):
for file_name in args:
pdb_inp = iotbx.pdb.input(file_name=file_name)
#
hierarchy = pdb_inp.construct_hierarchy()
#
hierarchy.overall_counts().show()
#
print("""
#... | from __future__ import absolute_import, division, print_function
import iotbx.pdb
import random
import sys
def run(args):
for file_name in args:
pdb_inp = iotbx.pdb.input(file_name=file_name)
#
hierarchy = pdb_inp.construct_hierarchy()
#
hierarchy.overall_counts().show()
#
print("""
#... | en | 0.857442 | # # # # Primary "view" of hierarchy: # model, chain, residue_group, atom_group, atom # # Secondary (read-only) "view" of the hierarchy: # model, chain, conformer, residue, atom # # Special case: if there are no alt. conf. you can eliminate one # level of the hierarchy (which may be more intuitive at fir... | 2.198142 | 2 |
glance_store/tests/functional/swift/test_functional_swift.py | mail2nsrajesh/glance_store | 0 | 6626557 | # Copyright 2015 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | # Copyright 2015 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | en | 0.846256 | # Copyright 2015 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ... | 1.666386 | 2 |
tests/garage/torch/algos/test_pearl.py | cnheider/garage | 0 | 6626558 | """This script is a test that fails when PEARL performance is too low."""
import pickle
import pytest
from garage.envs import MetaWorldSetTaskEnv, normalize, PointEnv
from garage.experiment.deterministic import set_seed
from garage.experiment.task_sampler import SetTaskSampler
from garage.sampler import LocalSampler
... | """This script is a test that fails when PEARL performance is too low."""
import pickle
import pytest
from garage.envs import MetaWorldSetTaskEnv, normalize, PointEnv
from garage.experiment.deterministic import set_seed
from garage.experiment.task_sampler import SetTaskSampler
from garage.sampler import LocalSampler
... | en | 0.872055 | This script is a test that fails when PEARL performance is too low. # pylint: disable=unused-import # noqa: F401 # pylint: disable=broad-except # isort:skip Test class for PEARL. Test PEARL with ML1 Push environment. # create multi-task environment and sample tasks Test pickle and unpickle. # This line is just to impro... | 2.156543 | 2 |
decisiontree/migrations/0005_auto_20180808_1125.py | datamade/rapidsms-decisiontree-app | 1 | 6626559 | <filename>decisiontree/migrations/0005_auto_20180808_1125.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-08-08 11:25
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('... | <filename>decisiontree/migrations/0005_auto_20180808_1125.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-08-08 11:25
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('... | en | 0.786689 | # -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-08-08 11:25 | 1.77309 | 2 |
qtgmc_modern/filters/__init__.py | Ichunjo/secret-project | 1 | 6626560 | """
Interface implementing various vapoursynth filters
"""
# flake8: noqa
from ._deinterlacers import *
from ._denoisers import *
from ._conv import *
from ._mvtools import *
| """
Interface implementing various vapoursynth filters
"""
# flake8: noqa
from ._deinterlacers import *
from ._denoisers import *
from ._conv import *
from ._mvtools import *
| en | 0.544107 | Interface implementing various vapoursynth filters # flake8: noqa | 0.997325 | 1 |
02. Algorithms/04. Recursion/Problems/08. Factorial of N/Solution.py | dr490n1s3d-3d8/Data-Structures-and-Algorithms | 1 | 6626561 | # Factorial of a number using recursion
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
num = 7
# check if the number is negative
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
... | # Factorial of a number using recursion
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
num = 7
# check if the number is negative
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
... | en | 0.598742 | # Factorial of a number using recursion # check if the number is negative | 4.315842 | 4 |
utils/function.py | gabriel-tjio/ASH | 0 | 6626562 | <reponame>gabriel-tjio/ASH
import torch
def calc_mean_std(feat, eps=1e-5):
# eps is a small value added to the variance to avoid divide-by-zero.
size = feat.size()
assert (len(size) == 4)
N, C = size[:2]
feat_var = feat.view(N, C, -1).var(dim=2) + eps
feat_std = feat_var.sqrt().view(N, C, 1, 1... | import torch
def calc_mean_std(feat, eps=1e-5):
# eps is a small value added to the variance to avoid divide-by-zero.
size = feat.size()
assert (len(size) == 4)
N, C = size[:2]
feat_var = feat.view(N, C, -1).var(dim=2) + eps
feat_std = feat_var.sqrt().view(N, C, 1, 1)
feat_mean = feat.view... | en | 0.83043 | # eps is a small value added to the variance to avoid divide-by-zero. # eps is a small value added to the variance to avoid divide-by-zero. # eps is a small value added to the variance to avoid divide-by-zero. # arbitrary mask # arbitrary mask # takes 3D feat (C, H, W), return mean and std of array within channels # as... | 2.697952 | 3 |
ichnaea/data/station.py | JaredKerim-Mozilla/ichnaea | 0 | 6626563 | from collections import defaultdict
from ichnaea.data.base import DataTask
from ichnaea.geocalc import (
distance,
range_to_points,
)
from ichnaea.models import (
Cell,
CellArea,
CellBlacklist,
CellObservation,
Wifi,
WifiBlacklist,
WifiObservation,
)
from ichnaea import util
class... | from collections import defaultdict
from ichnaea.data.base import DataTask
from ichnaea.geocalc import (
distance,
range_to_points,
)
from ichnaea.models import (
Cell,
CellArea,
CellBlacklist,
CellObservation,
Wifi,
WifiBlacklist,
WifiObservation,
)
from ichnaea import util
class... | en | 0.871855 | # This function returns True if the station was found to be moving. # calculate extremes of observations, existing location estimate # and existing extreme values # calculate sphere-distance from opposite corners of # bounding box containing current location estimate # and new observations; if too big, station is movin... | 2.275813 | 2 |
trecs/tests/test_PopularityRecommender.py | amywinecoff/t-recs | 0 | 6626564 | from trecs.models import PopularityRecommender
from trecs.components import Creators
import numpy as np
import pytest
import test_helpers
class TestPopularityRecommender:
def test_default(self):
c = PopularityRecommender()
test_helpers.assert_correct_num_users(c.num_users, c, c.users_hat.shape[0])... | from trecs.models import PopularityRecommender
from trecs.components import Creators
import numpy as np
import pytest
import test_helpers
class TestPopularityRecommender:
def test_default(self):
c = PopularityRecommender()
test_helpers.assert_correct_num_users(c.num_users, c, c.users_hat.shape[0])... | en | 0.852394 | # init with given arguments # init with partially given arguments # |A| shouldn't match item_repr.shape[0] # |A| shouldn't match user_repr.shape[1] # also check other params # check that measurements are the same # check that measurements are the same # 5 users, 5 attributes # 5 items, 5 attributes # this item will be ... | 2.231647 | 2 |
Chapter04/chapter-4/codeblock/cb-mnist.py | PacktPublishing/Deep-Learning-Essentials | 24 | 6626565 | import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
def cnn_model_fn(features, labels, mode):
# Input Layer
INPUT = tf.reshape(features["x"], [-1, 28, 28, 1])
# Conv-1 Layer
CONV1 = tf.layers.conv2d(
inputs=INPUT,
filters=32,
ke... | import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
def cnn_model_fn(features, labels, mode):
# Input Layer
INPUT = tf.reshape(features["x"], [-1, 28, 28, 1])
# Conv-1 Layer
CONV1 = tf.layers.conv2d(
inputs=INPUT,
filters=32,
ke... | en | 0.670345 | # Input Layer # Conv-1 Layer # Pool-1 Layer # Conv-2 Layer # Pool-2 Layer # Pool-2 Flattened Layer # Dropout Layer # Calculate Loss (for both TRAIN and EVAL modes) # Configure the Training Op (for TRAIN mode) | 3.091342 | 3 |
pywslegislature/services/__init__.py | JacksonMaxfield/wa_legislature | 5 | 6626566 | <filename>pywslegislature/services/__init__.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Services module for pywslegislature."""
# include all exampleParameters
from .exampleParameters import ExampleParameters # noqa: F401, F403
# import all services
from .amendmentService import AmendmentService # noqa: ... | <filename>pywslegislature/services/__init__.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Services module for pywslegislature."""
# include all exampleParameters
from .exampleParameters import ExampleParameters # noqa: F401, F403
# import all services
from .amendmentService import AmendmentService # noqa: ... | en | 0.331874 | #!/usr/bin/env python # -*- coding: utf-8 -*- Services module for pywslegislature. # include all exampleParameters # noqa: F401, F403 # import all services # noqa: F401, F403 # noqa: F401, F403 # noqa: F401, F403 # noqa: F401, F403 # noqa: F401, F403 # noqa: F401, F403 # noqa: F401, F403 # noqa: F401, F403 # noqa: F401... | 1.449699 | 1 |
yann/modules/shape.py | michalwols/yann | 32 | 6626567 | from torch.nn import Module
from ..exceptions import ShapeInferenceError
class Reshape(Module):
method = None
def __init__(self, *dims):
super(Reshape, self).__init__()
self.dims = dims
def forward(self, input):
return getattr(input, self.method)(*self.dims)
def state_dict(self, destination=None... | from torch.nn import Module
from ..exceptions import ShapeInferenceError
class Reshape(Module):
method = None
def __init__(self, *dims):
super(Reshape, self).__init__()
self.dims = dims
def forward(self, input):
return getattr(input, self.method)(*self.dims)
def state_dict(self, destination=None... | en | 0.694703 | # TODO: modify the model to drop the Infer nodes and replace them with the initialized module | 2.303735 | 2 |
propnet/web/app.py | dwinston/propnet | 0 | 6626568 | import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_table_experiments as dt
from dash.dependencies import Input, Output, State
from propnet import log_stream
from propnet.web.layouts_models import model_layout, models_index
from propnet.web.layouts_symbols import symbol_layo... | import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_table_experiments as dt
from dash.dependencies import Input, Output, State
from propnet import log_stream
from propnet.web.layouts_models import model_layout, models_index
from propnet.web.layouts_symbols import symbol_layo... | en | 0.518335 | # TODO: Fix math rendering # TODO: remove this? #dcc.Link('Models', href='/model'), #html.Span(' • '), #dcc.Link('Properties', href='/property'), #html.Span(' • '), # header # hidden table to make sure table component loads # (Dash limitation; may be removed in future) # standard Dash css, fork this for a custom theme ... | 2.006684 | 2 |
movimentacoes/models.py | robsonleal/challenge_backend | 0 | 6626569 | from django.db import models
from datetime import datetime
# Create your models here.
class Receita(models.Model):
descricao = models.CharField(max_length=100)
valor = models.CharField(max_length=10)
data = models.DateField(default=datetime.now, blank=True)
class Despesa(models.Model):
descricao = mod... | from django.db import models
from datetime import datetime
# Create your models here.
class Receita(models.Model):
descricao = models.CharField(max_length=100)
valor = models.CharField(max_length=10)
data = models.DateField(default=datetime.now, blank=True)
class Despesa(models.Model):
descricao = mod... | en | 0.963489 | # Create your models here. | 2.462155 | 2 |
simpleflow/format.py | David-Wobrock/simpleflow | 69 | 6626570 | <gh_stars>10-100
import os
from sqlite3 import OperationalError
from uuid import uuid4
import lazy_object_proxy
from diskcache import Cache
from simpleflow import constants, logger, storage
from simpleflow.settings import SIMPLEFLOW_ENABLE_DISK_CACHE
from simpleflow.utils import json_dumps, json_loads_or_raw
JUMBO_F... | import os
from sqlite3 import OperationalError
from uuid import uuid4
import lazy_object_proxy
from diskcache import Cache
from simpleflow import constants, logger, storage
from simpleflow.settings import SIMPLEFLOW_ENABLE_DISK_CACHE
from simpleflow.utils import json_dumps, json_loads_or_raw
JUMBO_FIELDS_MEMORY_CACH... | en | 0.889103 | # wrapped into a function so easier to override for tests # trim trailing / if there, would provoke double slashes down the road # 1/ memory cache # 2/ disk cache # NB: this cache may also be triggered on activity workers, where it's not that # useful. The performance hit should be minimal. To be improved later. # NB2:... | 2.137801 | 2 |
conclusions/6-graphs/GraphQuiz-solution.py | balajisomasale/Udacity_Data-Structures-and-algorithms | 0 | 6626571 | <filename>conclusions/6-graphs/GraphQuiz-solution.py
def get_edge_list(self):
edge_list = []
for edge_object in self.edges:
edge = (edge_object.value, edge_object.node_from.value, edge_object.node_to.value)
edge_list.append(edge)
return edge_list
def get_adjacency_list(self):
max_index ... | <filename>conclusions/6-graphs/GraphQuiz-solution.py
def get_edge_list(self):
edge_list = []
for edge_object in self.edges:
edge = (edge_object.value, edge_object.node_from.value, edge_object.node_to.value)
edge_list.append(edge)
return edge_list
def get_adjacency_list(self):
max_index ... | none | 1 | 3.365783 | 3 | |
my_vim_files/python27/Lib/test/test_unicode_file.py | satsaeid/dotfiles | 0 | 6626572 | <reponame>satsaeid/dotfiles<filename>my_vim_files/python27/Lib/test/test_unicode_file.py
# Test some Unicode file name semantics
# We dont test many operations on files other than
# that their names can be used with Unicode characters.
import os, glob, time, shutil
import unicodedata
import unittest
from test.t... | # Test some Unicode file name semantics
# We dont test many operations on files other than
# that their names can be used with Unicode characters.
import os, glob, time, shutil
import unicodedata
import unittest
from test.test_support import run_unittest, TESTFN_UNICODE
from test.test_support import TESTFN_ENC... | en | 0.877249 | # Test some Unicode file name semantics # We dont test many operations on files other than # that their names can be used with Unicode characters. # Either the file system encoding is None, or the file name # cannot be encoded in the file system encoding. # The file system encoding does not support Latin-1 # (which tes... | 3.045214 | 3 |
homeassistant/components/cover/garadget.py | TastyPi/home-assistant | 13 | 6626573 | """
Platform for the garadget cover component.
For more details about this platform, please refer to the documentation
https://home-assistant.io/components/garadget/
"""
import logging
import voluptuous as vol
import requests
from homeassistant.components.cover import CoverDevice, PLATFORM_SCHEMA
from homeassistant... | """
Platform for the garadget cover component.
For more details about this platform, please refer to the documentation
https://home-assistant.io/components/garadget/
"""
import logging
import voluptuous as vol
import requests
from homeassistant.components.cover import CoverDevice, PLATFORM_SCHEMA
from homeassistant... | en | 0.819768 | Platform for the garadget cover component. For more details about this platform, please refer to the documentation https://home-assistant.io/components/garadget/ # Validation of the user's configuration Setup the Demo covers. Representation of a demo cover. # pylint: disable=no-self-use, too-many-instance-attributes I... | 1.975181 | 2 |
Regression/prepare_file_travis.py | ruohai0925/artemis | 0 | 6626574 | <reponame>ruohai0925/artemis
# Copyright 2018-2019 <NAME>, <NAME>, <NAME>
# <NAME>
#
# This file is part of WarpX.
#
# License: BSD-3-Clause-LBNL
# This script modifies `WarpX-test.ini` (which is used for nightly builds)
# and creates the file `travis-test.ini` (which is used for continous
# integration on TravisCI (h... | # Copyright 2018-2019 <NAME>, <NAME>, <NAME>
# <NAME>
#
# This file is part of WarpX.
#
# License: BSD-3-Clause-LBNL
# This script modifies `WarpX-test.ini` (which is used for nightly builds)
# and creates the file `travis-test.ini` (which is used for continous
# integration on TravisCI (https://travis-ci.org/)
# The ... | en | 0.8177 | # Copyright 2018-2019 <NAME>, <NAME>, <NAME> # <NAME> # # This file is part of WarpX. # # License: BSD-3-Clause-LBNL # This script modifies `WarpX-test.ini` (which is used for nightly builds) # and creates the file `travis-test.ini` (which is used for continous # integration on TravisCI (https://travis-ci.org/) # The s... | 1.765017 | 2 |
ex/ex100.py | Ozcry/PythonExercicio | 0 | 6626575 | '''Faça um programa que tenha uma lista chamada números e duas funções chamadas sorteia() e somaPar(). A primeira função
vai sortear 5 números e vai colocá-los dentro da lista e a segunda função vai mostrar a soma entre todos os valores
PARES sorteados pela função anterior.'''
from random import randint
from time impor... | '''Faça um programa que tenha uma lista chamada números e duas funções chamadas sorteia() e somaPar(). A primeira função
vai sortear 5 números e vai colocá-los dentro da lista e a segunda função vai mostrar a soma entre todos os valores
PARES sorteados pela função anterior.'''
from random import randint
from time impor... | pt | 0.992826 | Faça um programa que tenha uma lista chamada números e duas funções chamadas sorteia() e somaPar(). A primeira função vai sortear 5 números e vai colocá-los dentro da lista e a segunda função vai mostrar a soma entre todos os valores PARES sorteados pela função anterior. | 4.143519 | 4 |
source/tool/tuner.py | douglasresende/lambda-deep-learning-demo | 80 | 6626576 | import os
import random
import importlib
from source.tool import config_parser
CONVERT_STR2NUM = ["piecewise_lr_decay", "piecewise_boundaries"]
def type_convert(v):
""" convert value to int, float or str"""
try:
float(v)
tp = 1 if v.count(".") == 0 else 2
except ValueError:
tp =... | import os
import random
import importlib
from source.tool import config_parser
CONVERT_STR2NUM = ["piecewise_lr_decay", "piecewise_boundaries"]
def type_convert(v):
""" convert value to int, float or str"""
try:
float(v)
tp = 1 if v.count(".") == 0 else 2
except ValueError:
tp =... | en | 0.348751 | convert value to int, float or str # Run application # Optional: use a different split for evaluation # Should not use testing dataset # inputter_config.dataset_meta = \ # os.path.expanduser(config.eval_dataset_meta) # Parse config file # Setup the tuning jobs # Update fixed params (epochs needs to be reset) # Upda... | 2.727533 | 3 |
rl-multilayer/setup.py | hammer-wang/oml-ppo | 8 | 6626577 | <gh_stars>1-10
from setuptools import setup
setup(name='RLMultilayer',
version='0.0.1',
install_requires=['gym', 'tmm'] # And any other dependencies
) | from setuptools import setup
setup(name='RLMultilayer',
version='0.0.1',
install_requires=['gym', 'tmm'] # And any other dependencies
) | en | 0.390392 | # And any other dependencies | 1.133809 | 1 |
mqtt/mqtt.py | robinvanemden/sensors | 3 | 6626578 | <reponame>robinvanemden/sensors
"""
JADS 2020 Data-Driven Food Value Chain course
Introduction to Sensors
Minimal MQTT client demo - demonstrates ease of use.
Makes use of the open http://www.mqtt-dashboard.com/index.html
And yes, globals are evil ;)
"""
import threading
import paho.mqtt.client ... | """
JADS 2020 Data-Driven Food Value Chain course
Introduction to Sensors
Minimal MQTT client demo - demonstrates ease of use.
Makes use of the open http://www.mqtt-dashboard.com/index.html
And yes, globals are evil ;)
"""
import threading
import paho.mqtt.client as mqtt
import os
def on_conne... | en | 0.610516 | JADS 2020 Data-Driven Food Value Chain course Introduction to Sensors Minimal MQTT client demo - demonstrates ease of use. Makes use of the open http://www.mqtt-dashboard.com/index.html And yes, globals are evil ;) | 2.960768 | 3 |
components/fuselage/primitives/fcone.py | skilkis/KBE | 6 | 6626579 | <filename>components/fuselage/primitives/fcone.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Required ParaPy Modules
from parapy.geom import *
from parapy.core import *
# Required Modules
from fframe import *
from mframe import *
from directories import *
from math import sqrt
__author__ = ["<NAME>"]
__all__ = ... | <filename>components/fuselage/primitives/fcone.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Required ParaPy Modules
from parapy.geom import *
from parapy.core import *
# Required Modules
from fframe import *
from mframe import *
from directories import *
from math import sqrt
__author__ = ["<NAME>"]
__all__ = ... | en | 0.517934 | #!/usr/bin/env python # -*- coding: utf-8 -*- # Required ParaPy Modules # Required Modules This creates the nose or tailcone for the fuselage. :returns: Nose and/or tailcone for fuselage :param support_frame: This is an FFrame Class :type support_frame: FFrame # A parameter for debugging, turns the visibi... | 2.321459 | 2 |
post/admin.py | abdukhashimov/django-rest-blog-2 | 0 | 6626580 | <reponame>abdukhashimov/django-rest-blog-2
from django.contrib import admin
from post.models import Post, Category, Tag
class PostAdmin(admin.ModelAdmin):
fields = ('title', 'thumbnail', 'content', 'tag', 'category')
def save_model(self, request, obj, form, change):
obj.author = request.user
... | from django.contrib import admin
from post.models import Post, Category, Tag
class PostAdmin(admin.ModelAdmin):
fields = ('title', 'thumbnail', 'content', 'tag', 'category')
def save_model(self, request, obj, form, change):
obj.author = request.user
return super().save_model(request, obj, fo... | none | 1 | 2.114059 | 2 | |
eSports/users/views.py | bdg-python-team1/Tournament_Project | 0 | 6626581 | from django.shortcuts import render, redirect
from .models import Profile
from .forms import UserRegisterForm, ProfileUpdateForm
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.decorators ... | from django.shortcuts import render, redirect
from .models import Profile
from .forms import UserRegisterForm, ProfileUpdateForm
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.decorators ... | en | 0.42662 | # def register(request): # registered = False # if request.method == 'POST': # user_form = UserRegisterForm(data=request.POST) # profile_form = ProfileUpdateForm(data=request.POST) # # if user_form.is_valid() and profile_form.is_valid(): # user = u... | 2.16989 | 2 |
paxos/practical.py | hnfgns/paxos | 1 | 6626582 | <reponame>hnfgns/paxos
'''
This module builds upon the essential Paxos implementation and adds
functionality required for most practical uses of the algorithm.
'''
from paxos import essential
from paxos.essential import ProposalID
class Messenger (essential.Messenger):
def send_prepare_nack(self, to_uid, p... | '''
This module builds upon the essential Paxos implementation and adds
functionality required for most practical uses of the algorithm.
'''
from paxos import essential
from paxos.essential import ProposalID
class Messenger (essential.Messenger):
def send_prepare_nack(self, to_uid, proposal_id, promised_id... | en | 0.874554 | This module builds upon the essential Paxos implementation and adds functionality required for most practical uses of the algorithm. Sends a Prepare Nack message for the proposal to the specified node Sends a Accept! Nack message for the proposal to the specified node Called when leadership has been aquired. This is no... | 2.847674 | 3 |
lib/datasets/tools/multilabel_list.py | Flsahkong/seeDiff | 321 | 6626583 | <reponame>Flsahkong/seeDiff
import os
import xml.etree.ElementTree as ET
import sys
argvs = sys.argv
def load_image_set_index(ref):
"""
Load the indexes listed in this dataset's image set file.
"""
# Example path to image set file:
# self._devkit_path + /VOCdevkit2007/VOC2007/ImageSets/Main/val.txt... | import os
import xml.etree.ElementTree as ET
import sys
argvs = sys.argv
def load_image_set_index(ref):
"""
Load the indexes listed in this dataset's image set file.
"""
# Example path to image set file:
# self._devkit_path + /VOCdevkit2007/VOC2007/ImageSets/Main/val.txt
image_set_file = os.pat... | en | 0.778022 | Load the indexes listed in this dataset's image set file. # Example path to image set file: # self._devkit_path + /VOCdevkit2007/VOC2007/ImageSets/Main/val.txt Load image and bounding boxes info from XML file in the PASCAL VOC format. | 2.960005 | 3 |
exercicio14.py | juniooor/Exercicios-python | 0 | 6626584 | #<NAME>-Pescador, homem de bem, comprou um microcomputador para controlar o rendimento diário de seu trabalho. Toda vez que ele traz um peso de peixes maior que o estabelecido pelo regulamento de pesca do estado de São Paulo (50 quilos) deve pagar uma multa de R$ 4,00 por quilo excedente. João precisa que você faça um ... | #<NAME>-Pescador, homem de bem, comprou um microcomputador para controlar o rendimento diário de seu trabalho. Toda vez que ele traz um peso de peixes maior que o estabelecido pelo regulamento de pesca do estado de São Paulo (50 quilos) deve pagar uma multa de R$ 4,00 por quilo excedente. João precisa que você faça um ... | pt | 0.968845 | #<NAME>-Pescador, homem de bem, comprou um microcomputador para controlar o rendimento diário de seu trabalho. Toda vez que ele traz um peso de peixes maior que o estabelecido pelo regulamento de pesca do estado de São Paulo (50 quilos) deve pagar uma multa de R$ 4,00 por quilo excedente. João precisa que você faça um ... | 3.656868 | 4 |
Python_3/tests/ex_debug_test.py | waynegm/OpendTect-External-Attributes | 22 | 6626585 | <reponame>waynegm/OpendTect-External-Attributes<filename>Python_3/tests/ex_debug_test.py
# External Attribute Debug Test
#
import sys,os
import numpy as np
import web_pdb
#
sys.path.insert(0, os.path.join(sys.path[0], '..'))
import extattrib as xa
#
xa.params = {
'Inputs': ['Input1'],
'Parallel' : False
}
#
def doCom... | # External Attribute Debug Test
#
import sys,os
import numpy as np
import web_pdb
#
sys.path.insert(0, os.path.join(sys.path[0], '..'))
import extattrib as xa
#
xa.params = {
'Inputs': ['Input1'],
'Parallel' : False
}
#
def doCompute():
#
# Start debugging before computation starts
#
web_pdb.set_trace()
#
while T... | en | 0.500944 | # External Attribute Debug Test # # # # # # Start debugging before computation starts # # # # Add some more local variables # # # # | 2.132638 | 2 |
pypeline/common/formats/newick.py | KHanghoj/epiPALEOMIX | 2 | 6626586 | #!/usr/bin/python
#
# Copyright (c) 2012 <NAME> <<EMAIL>>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify... | #!/usr/bin/python
#
# Copyright (c) 2012 <NAME> <<EMAIL>>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify... | en | 0.815288 | #!/usr/bin/python # # Copyright (c) 2012 <NAME> <<EMAIL>> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify... | 1.837702 | 2 |
R/init_data.py | Xiaojieqiu/scLVM | 0 | 6626587 | import sys
import scipy as SP
import pylab as PL
from matplotlib import cm
import h5py
#make sure your paths point to limix and scLVM directories
limix_path = '/Users/florian/Code/python_code/limix-0.6.4/build/release.darwin/interfaces/python'
sclvm_path = '/Users/florian/Code/python_code/scPy/scLVM/'
sys.path.append(l... | import sys
import scipy as SP
import pylab as PL
from matplotlib import cm
import h5py
#make sure your paths point to limix and scLVM directories
limix_path = '/Users/florian/Code/python_code/limix-0.6.4/build/release.darwin/interfaces/python'
sclvm_path = '/Users/florian/Code/python_code/scPy/scLVM/'
sys.path.append(l... | en | 0.847866 | #make sure your paths point to limix and scLVM directories #import scLVM | 1.35537 | 1 |
Ejercicio4/src/exercise4.py | NAL-GitHub-Octavio/TECMTY.TC1028.Python.py.Basicos | 0 | 6626588 | <gh_stars>0
def main():
#escribe tu código abajo de esta línea
main()
| def main():
#escribe tu código abajo de esta línea
main() | es | 0.99885 | #escribe tu código abajo de esta línea | 1.744954 | 2 |
ml/main.py | Ldude162/AP-CSP | 1 | 6626589 | <gh_stars>1-10
import pandas as pd
import numpy as np
'''
This is how I originally imported the data.
data = pd.read_csv('./ml/data.csv', sep=',', header=None)
ratings = pd.read_csv('./ml/ratings.csv', sep=',', header=None)
people = pd.read_csv('./ml/people.csv', sep=',', header=None)
movies = data.loc[1:57, 2]
ra... | import pandas as pd
import numpy as np
'''
This is how I originally imported the data.
data = pd.read_csv('./ml/data.csv', sep=',', header=None)
ratings = pd.read_csv('./ml/ratings.csv', sep=',', header=None)
people = pd.read_csv('./ml/people.csv', sep=',', header=None)
movies = data.loc[1:57, 2]
ratings = ratings... | en | 0.903597 | This is how I originally imported the data. data = pd.read_csv('./ml/data.csv', sep=',', header=None) ratings = pd.read_csv('./ml/ratings.csv', sep=',', header=None) people = pd.read_csv('./ml/people.csv', sep=',', header=None) movies = data.loc[1:57, 2] ratings = ratings.astype(float) ratings.to_numpy() movies.to... | 3.802667 | 4 |
sort/performance.py | dsysoev/fun-with-algorithms | 11 | 6626590 | # coding: utf-8
import os
import timeit
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('seaborn')
import argparse
import tempfile
import pandas as pd
# noinspection PyUnresolvedReferences
from insertionsort import insertionsort
# noinspection PyUnresolvedReferences
from me... | # coding: utf-8
import os
import timeit
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('seaborn')
import argparse
import tempfile
import pandas as pd
# noinspection PyUnresolvedReferences
from insertionsort import insertionsort
# noinspection PyUnresolvedReferences
from me... | en | 0.638377 | # coding: utf-8 # noinspection PyUnresolvedReferences # noinspection PyUnresolvedReferences # noinspection PyUnresolvedReferences # noinspection PyUnresolvedReferences # noinspection PyUnresolvedReferences # noinspection PyUnresolvedReferences # noinspection PyUnresolvedReferences # noinspection PyUnresolvedReferences ... | 2.447037 | 2 |
examples/ibllib/ephys_qc_raw.py | SebastianBruijns/ibllib | 0 | 6626591 | <reponame>SebastianBruijns/ibllib<gh_stars>0
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from ibllib.ephys import ephysqc
import alf.io
def _plot_spectra(outpath, typ, savefig=True):
spec = alf.io.load_object(outpath, '_iblqc_ephysSpectralDensity' + typ.uppe... | from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from ibllib.ephys import ephysqc
import alf.io
def _plot_spectra(outpath, typ, savefig=True):
spec = alf.io.load_object(outpath, '_iblqc_ephysSpectralDensity' + typ.upper())
sns.set_style("whitegrid")
plt.... | en | 0.938101 | # make sure you send a path for the time being and not a string | 2.349291 | 2 |
problems/leetcode/66.py | JayMonari/py-personal | 0 | 6626592 | <reponame>JayMonari/py-personal
from typing import List
def plus_one(digits: List[int]) -> List[int]:
remainder = False
for idx in reversed(range(len(digits))):
digits[idx] += 1
if digits[idx] != 10:
remainder = False
break
remainder = True
digits[idx] ... | from typing import List
def plus_one(digits: List[int]) -> List[int]:
remainder = False
for idx in reversed(range(len(digits))):
digits[idx] += 1
if digits[idx] != 10:
remainder = False
break
remainder = True
digits[idx] = 0
if remainder:
di... | none | 1 | 3.573251 | 4 | |
pyparrot/DroneVision.py | DavidMutchler/pyparrot | 0 | 6626593 | """
DroneVision is separated from the main Mambo/Bebop class to enable the use of the drone without the FPV camera.
If you want to do vision processing, you will need to create a DroneVision object to capture the
video stream.
Note that this module relies on the opencv module and the ffmpeg program
Ffmpeg write the i... | """
DroneVision is separated from the main Mambo/Bebop class to enable the use of the drone without the FPV camera.
If you want to do vision processing, you will need to create a DroneVision object to capture the
video stream.
Note that this module relies on the opencv module and the ffmpeg program
Ffmpeg write the i... | en | 0.828027 | DroneVision is separated from the main Mambo/Bebop class to enable the use of the drone without the FPV camera. If you want to do vision processing, you will need to create a DroneVision object to capture the video stream. Note that this module relies on the opencv module and the ffmpeg program Ffmpeg write the image... | 3.136504 | 3 |
example_ngd.py | maryamhgf/backpack | 0 | 6626594 | import torch
import torchvision
# The main BackPACK functionalities
from backpack import backpack, extend
# The diagonal GGN extension
# from backpack.extensions import DiagGGNMC
import torch.optim as optim
from backpack.extensions import TRIAL
from torchsummary import summary
import time
# fixing HTTPS issue on Colab... | import torch
import torchvision
# The main BackPACK functionalities
from backpack import backpack, extend
# The diagonal GGN extension
# from backpack.extensions import DiagGGNMC
import torch.optim as optim
from backpack.extensions import TRIAL
from torchsummary import summary
import time
# fixing HTTPS issue on Colab... | en | 0.433603 | # The main BackPACK functionalities # The diagonal GGN extension # from backpack.extensions import DiagGGNMC # fixing HTTPS issue on Colab # torch.set_default_dtype(torch.float64) # This layer did not exist in Pytorch 1.0 # Hyperparameters # 0: matmul # 1: fft # 2: conv2d # -1: silent mode [only backpropagation] # [7]:... | 2.255942 | 2 |
odl_video/envs.py | mitodl/odl-video-service | 3 | 6626595 | <reponame>mitodl/odl-video-service<filename>odl_video/envs.py
"""Functions reading and parsing environment variables"""
from ast import literal_eval
import os
from django.core.exceptions import ImproperlyConfigured
class EnvironmentVariableParseException(ImproperlyConfigured):
"""Environment variable was not par... | """Functions reading and parsing environment variables"""
from ast import literal_eval
import os
from django.core.exceptions import ImproperlyConfigured
class EnvironmentVariableParseException(ImproperlyConfigured):
"""Environment variable was not parsed correctly"""
def get_string(name, default):
"""
... | en | 0.755499 | Functions reading and parsing environment variables Environment variable was not parsed correctly Get an environment variable as a string. Args: name (str): An environment variable name default (str): The default value to use if the environment variable doesn't exist. Returns: str: ... | 3.761736 | 4 |
Beginner/URI_2311.py | rbshadow/Python_URI | 3 | 6626596 | <gh_stars>1-10
def math():
test_case = int(input())
for i in range(test_case):
count = 0
name = input()
degree = float(input())
lis_t = list(map(float, input().strip().split()))
maximum = max(lis_t)
minimum = min(lis_t)
lis_t.remove(maximum)
lis_... | def math():
test_case = int(input())
for i in range(test_case):
count = 0
name = input()
degree = float(input())
lis_t = list(map(float, input().strip().split()))
maximum = max(lis_t)
minimum = min(lis_t)
lis_t.remove(maximum)
lis_t.remove(minimu... | none | 1 | 3.597315 | 4 | |
dis_cover/analysis/__init__.py | louismerlin/dis-cover | 2 | 6626597 | """Method and class related to the analysis"""
from .analysis import analyze, CppClass
| """Method and class related to the analysis"""
from .analysis import analyze, CppClass
| en | 0.883281 | Method and class related to the analysis | 0.989775 | 1 |
lib/spack/spack/operating_systems/_operating_system.py | LiamBindle/spack | 2,360 | 6626598 | <gh_stars>1000+
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import llnl.util.lang
import spack.util.spack_yaml as syaml
@llnl.util.lang.lazy_lexicographic_ordering
... | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import llnl.util.lang
import spack.util.spack_yaml as syaml
@llnl.util.lang.lazy_lexicographic_ordering
class OperatingS... | en | 0.879129 | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) Base class for all the Operating Systems. On a multiple architecture machine, the architecture spec field can be set t... | 2.204532 | 2 |
eth/tools/builder/chain/builders.py | gsalgado/py-evm | 1 | 6626599 | <reponame>gsalgado/py-evm
import functools
import time
from typing import (
cast,
Any,
Callable,
Dict,
Iterable,
Tuple,
Type,
Union,
)
from eth_utils.toolz import (
curry,
merge,
pipe,
)
from eth_typing import (
Address,
BlockNumber,
Hash32,
)
from eth_utils im... | import functools
import time
from typing import (
cast,
Any,
Callable,
Dict,
Iterable,
Tuple,
Type,
Union,
)
from eth_utils.toolz import (
curry,
merge,
pipe,
)
from eth_typing import (
Address,
BlockNumber,
Hash32,
)
from eth_utils import (
to_dict,
to... | en | 0.672402 | Run the provided object through the series of applicator functions. If ``obj`` is an instances of :class:`~eth.chains.base.BaseChain` the applicators will be run on a copy of the chain and thus will not mutate the provided chain instance. # # Constructors (creation of chain classes) # Assign the given name... | 1.948448 | 2 |
airflow_log_grepper/log_grepper.py | 7yl4r/airflow_log_grepper | 0 | 6626600 | # script which outputs status overview of airflow worker logs searched for
# known error strings.
# good for use as a telegraf exec to monitor airflow via graphite/influxdb.
# Rather than using this with telegraf, a cronjob combined with the
# following format puts less strain on the db here (NOTE that the
# crontab p... | # script which outputs status overview of airflow worker logs searched for
# known error strings.
# good for use as a telegraf exec to monitor airflow via graphite/influxdb.
# Rather than using this with telegraf, a cronjob combined with the
# following format puts less strain on the db here (NOTE that the
# crontab p... | en | 0.733921 | # script which outputs status overview of airflow worker logs searched for # known error strings. # good for use as a telegraf exec to monitor airflow via graphite/influxdb. # Rather than using this with telegraf, a cronjob combined with the # following format puts less strain on the db here (NOTE that the # crontab pe... | 2.452925 | 2 |
engage-analytics/lei.py | oliveriopt/mood-analytics | 0 | 6626601 | <reponame>oliveriopt/mood-analytics
#!/usr/bin/env python3
import time
import sys
import shutil
import logging.config
from src.lei.src.read_path import *
from src.lei.src.read_source_files import ImportLeiFile
from src.lei.src.read_transform_file import *
from src.lei.src.split_file import *
from src.lei.src.inject_s... | #!/usr/bin/env python3
import time
import sys
import shutil
import logging.config
from src.lei.src.read_path import *
from src.lei.src.read_source_files import ImportLeiFile
from src.lei.src.read_transform_file import *
from src.lei.src.split_file import *
from src.lei.src.inject_sql import *
from src.utilities impor... | en | 0.153477 | #!/usr/bin/env python3 # Logger ### IMPORT FILE AND DOWNLOAD THE FILE TO /DATA/ FOLDER ## SPLIT BIG FILE JSON ### READ FILES JSON ALREADY SPLITTED ## DELETE TEMP FILE | 2.222398 | 2 |
python/ray/tune/integration/mlflow.py | siddgoel/ray | 22 | 6626602 | from typing import Dict, Callable, Optional
import logging
import ray
from ray.tune.trainable import Trainable
from ray.tune.logger import Logger, LoggerCallback
from ray.tune.result import TRAINING_ITERATION, TIMESTEPS_TOTAL
from ray.tune.trial import Trial
from ray.util.annotations import Deprecated
from ray.util.ml... | from typing import Dict, Callable, Optional
import logging
import ray
from ray.tune.trainable import Trainable
from ray.tune.logger import Logger, LoggerCallback
from ray.tune.result import TRAINING_ITERATION, TIMESTEPS_TOTAL
from ray.tune.trial import Trial
from ray.util.annotations import Deprecated
from ray.util.ml... | en | 0.718278 | MLflow Logger to automatically log Tune results and config to MLflow. MLflow (https://mlflow.org) Tracking is an open source library for recording and querying experiments. This Ray Tune ``LoggerCallback`` sends information (config parameters, training results & metrics, and artifacts) to MLflow for au... | 2.393143 | 2 |
meraki_sdk/models/two_four_ghz_settings_1_model.py | meraki/meraki-python-sdk | 37 | 6626603 | <reponame>meraki/meraki-python-sdk<filename>meraki_sdk/models/two_four_ghz_settings_1_model.py
# -*- coding: utf-8 -*-
"""
meraki_sdk
This file was automatically generated for meraki by APIMATIC v2.0 ( https://apimatic.io ).
"""
class TwoFourGhzSettings1Model(object):
"""Implementation of th... | # -*- coding: utf-8 -*-
"""
meraki_sdk
This file was automatically generated for meraki by APIMATIC v2.0 ( https://apimatic.io ).
"""
class TwoFourGhzSettings1Model(object):
"""Implementation of the 'TwoFourGhzSettings1' model.
Settings related to 2.4Ghz band
Attributes:
... | en | 0.747898 | # -*- coding: utf-8 -*- meraki_sdk
This file was automatically generated for meraki by APIMATIC v2.0 ( https://apimatic.io ). Implementation of the 'TwoFourGhzSettings1' model.
Settings related to 2.4Ghz band
Attributes:
max_power (int): Sets max power (dBm) of 2.4Ghz band. Can be integer
... | 2.271135 | 2 |
statsmodels/iolib/tests/test_foreign.py | diego-mazon/statsmodels | 0 | 6626604 | <reponame>diego-mazon/statsmodels
"""
Tests for iolib/foreign.py
"""
import os
import warnings
from datetime import datetime
from io import BytesIO
from numpy.testing import assert_array_equal, assert_, assert_equal
import numpy as np
from pandas import DataFrame, isnull
import pandas.util.testing as ptesting
import p... | """
Tests for iolib/foreign.py
"""
import os
import warnings
from datetime import datetime
from io import BytesIO
from numpy.testing import assert_array_equal, assert_, assert_equal
import numpy as np
from pandas import DataFrame, isnull
import pandas.util.testing as ptesting
import pytest
from statsmodels.compat.pyt... | en | 0.80824 | Tests for iolib/foreign.py # Test precisions # Test genfromdta vs. results/macrodta.npy created with genfromtxt. # NOTE: Stata handles data very oddly. Round tripping from csv to dta # to ndarray 2710.349 (csv) -> 2510.2491 (stata) -> 2710.34912109375 # (dta/ndarray) # dta is int64 'i8' given to Stata writer # ... | 1.960297 | 2 |
tests/infer/test_enum.py | adam-coogan/pyro | 0 | 6626605 | <filename>tests/infer/test_enum.py
from __future__ import absolute_import, division, print_function
import logging
import math
import os
import timeit
from collections import defaultdict
import pytest
import torch
from torch.autograd import grad
from torch.distributions import constraints, kl_divergence
import pyro
... | <filename>tests/infer/test_enum.py
from __future__ import absolute_import, division, print_function
import logging
import math
import os
import timeit
from collections import defaultdict
import pytest
import torch
from torch.autograd import grad
from torch.distributions import constraints, kl_divergence
import pyro
... | en | 0.754966 | # python 3 # python 2 # The usual dist.Bernoulli avoids NANs by clamping log prob. This unsafe version # allows us to test additional NAN avoidance in _compute_dice_elbo(). # A simple Gaussian mixture model, with no vectorization. # This non-vectorized version is exponential in data_size: # A Gaussian mixture model, wi... | 1.900388 | 2 |
dataRecovery1.py | ShrohanMohapatra/softMatterAlgos | 1 | 6626606 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 27 12:23:12 2021
@author: shrohanmohapatra
"""
import mph
client = mph.start(cores=1)
model = client.load('2DGeometryExample.mph')
#print(client.names())
#print(client.models())
print(model.parameters())
for (name, value) in model.parameters().item... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 27 12:23:12 2021
@author: shrohanmohapatra
"""
import mph
client = mph.start(cores=1)
model = client.load('2DGeometryExample.mph')
#print(client.names())
#print(client.models())
print(model.parameters())
for (name, value) in model.parameters().item... | en | 0.457991 | #!/usr/bin/env python3 # -*- coding: utf-8 -*- Created on Sun Jun 27 12:23:12 2021 @author: shrohanmohapatra #print(client.names()) #print(client.models()) | 2.979054 | 3 |
amqp_worker/serializer.py | cheese-drawer/lib-python-amqp-worker | 0 | 6626607 | <reponame>cheese-drawer/lib-python-amqp-worker<filename>amqp_worker/serializer.py
"""Shared behavior for serializing messages sent & received by Workers."""
import gzip
from json import JSONEncoder
from logging import getLogger
from typing import (
cast,
Any,
Protocol,
Optional,
Union,
List,
... | """Shared behavior for serializing messages sent & received by Workers."""
import gzip
from json import JSONEncoder
from logging import getLogger
from typing import (
cast,
Any,
Protocol,
Optional,
Union,
List,
Tuple,
Dict,
)
from .response import Response, OkResponse, ErrResponse
LO... | en | 0.828988 | Shared behavior for serializing messages sent & received by Workers. Define expected behavior for an object capable of encoding JSON. Encode a given object as JSON. Convert a given object to a type that is encodable to JSON. Extend JSONEncoder to parse Response objects. Convert OkResponse & ErrResponse to dictionaries.... | 2.935566 | 3 |
demisto_sdk/commands/common/tests/dashboard_test.py | yalonso7/demisto-sdk | 0 | 6626608 | <reponame>yalonso7/demisto-sdk<filename>demisto_sdk/commands/common/tests/dashboard_test.py
from typing import Optional
import pytest
from demisto_sdk.commands.common.hook_validations.dashboard import \
DashboardValidator
from demisto_sdk.commands.common.hook_validations.structure import \
StructureValidator
f... | from typing import Optional
import pytest
from demisto_sdk.commands.common.hook_validations.dashboard import \
DashboardValidator
from demisto_sdk.commands.common.hook_validations.structure import \
StructureValidator
from mock import patch
def mock_structure(file_path=None, current_file=None, old_file=None)... | en | 0.236905 | # type: (Optional[str], Optional[dict], Optional[dict]) -> StructureValidator | 2.325068 | 2 |
src/py_tldr/core.py | iamgodot/pytldr | 5 | 6626609 | <gh_stars>1-10
import platform as platform_
import sys
from functools import partial
from os import environ
from pathlib import Path as LibPath
from typing import List
import toml
from click import Choice, Path, argument
from click import command as command_
from click import get_app_dir, option, pass_context, secho
f... | import platform as platform_
import sys
from functools import partial
from os import environ
from pathlib import Path as LibPath
from typing import List
import toml
from click import Choice, Path, argument
from click import command as command_
from click import get_app_dir, option, pass_context, secho
from yaspin impo... | en | 0.741894 | # pylint: disable=unused-argument # pylint: disable=unused-argument Build a config dict from either default or custom path. Currently custom config file is used without validation, so misconfiguration may cause errors. Also note `toml` should used as file format. Collaborative cheatsheets for console comma... | 1.95175 | 2 |
Chapter 07/stock/search.py | bpbpublications/Time-Series-Forecasting-using-Deep-Learning | 7 | 6626610 | import time
from pathlib import Path
from nni.experiment import Experiment
# Search Space
fast_choices = {"_type": "choice", "_value": [3, 5, 7, 9]}
slow_choices = {"_type": "choice", "_value": [14, 20, 40]}
length_choices = {"_type": "choice", "_value": [5, 10, 20]}
ind_choices = [
{"_name": "ao", "fast": fast_ch... | import time
from pathlib import Path
from nni.experiment import Experiment
# Search Space
fast_choices = {"_type": "choice", "_value": [3, 5, 7, 9]}
slow_choices = {"_type": "choice", "_value": [14, 20, 40]}
length_choices = {"_type": "choice", "_value": [5, 10, 20]}
ind_choices = [
{"_name": "ao", "fast": fast_ch... | en | 0.391095 | # Search Space # Search Configuration # Search Name # Search Tuner Settings # Running Search # Awaiting Results | 2.107445 | 2 |
pipsqueak/pip/freeze.py | svrana/pipsqueak | 0 | 6626611 | import os
import re
import logging
from pipsqueak.pip.vcs import vcs, get_src_requirement
from pipsqueak.pip.util import dist_is_editable
logger = logging.getLogger(__file__)
class FrozenRequirement(object):
def __init__(self, name, req, editable, location, comments=()):
self.name = name
self.re... | import os
import re
import logging
from pipsqueak.pip.vcs import vcs, get_src_requirement
from pipsqueak.pip.util import dist_is_editable
logger = logging.getLogger(__file__)
class FrozenRequirement(object):
def __init__(self, name, req, editable, location, comments=()):
self.name = name
self.re... | en | 0.576925 | # !! Could not determine repository location' # FIXME: could not find svn URL in dependency_links ' #egg=%s' % ( | 2.337919 | 2 |
core/evaluate_gan.py | brian220/sketch_part_rec | 1 | 6626612 | <reponame>brian220/sketch_part_rec<gh_stars>1-10
# 176 39f5eecbfb2470846666a748bda83f67
# 41753 a58f8f1bd61094b3ff2c92c2a4f65876
# 2603 27c00ec2b6ec279958e80128fd34c2b1
# 37247 484f0070df7d5375492d9da2668ec34c
# 36881 4231883e92a3c1a21c62d11641ffbd35
import json
import numpy as np
import os, sys
import torch
... | # 176 39f5eecbfb2470846666a748bda83f67
# 41753 a58f8f1bd61094b3ff2c92c2a4f65876
# 2603 27c00ec2b6ec279958e80128fd34c2b1
# 37247 484f0070df7d5375492d9da2668ec34c
# 36881 4231883e92a3c1a21c62d11641ffbd35
import json
import numpy as np
import os, sys
import torch
import torch.backends.cudnn
import torch.utils.da... | en | 0.59148 | # 176 39f5eecbfb2470846666a748bda83f67 # 41753 a58f8f1bd61094b3ff2c92c2a4f65876 # 2603 27c00ec2b6ec279958e80128fd34c2b1 # 37247 484f0070df7d5375492d9da2668ec34c # 36881 4231883e92a3c1a21c62d11641ffbd35 # Enable the inbuilt cudnn auto-tuner to find the best algorithm to use # Set up networks # The parameters her... | 1.313259 | 1 |
api.py | KirillDmit/xmljson | 0 | 6626613 | import datetime
from itertools import groupby
from urllib.request import urlopen
from json import loads
def get_date(x):
return datetime.datetime.strptime(x['timestamp'], '%Y-%m-%dT%H:%M:%SZ').date()
url = 'https://ru.wikipedia.org/w/api.php?action=query&format=json&prop=revisions&rvlimit=500&titles=%D0%93%D1%8... | import datetime
from itertools import groupby
from urllib.request import urlopen
from json import loads
def get_date(x):
return datetime.datetime.strptime(x['timestamp'], '%Y-%m-%dT%H:%M:%SZ').date()
url = 'https://ru.wikipedia.org/w/api.php?action=query&format=json&prop=revisions&rvlimit=500&titles=%D0%93%D1%8... | ru | 0.9397 | #2021-11-28 - день ухода Градского из жизни | 3.047541 | 3 |
applications/FluidDynamicsApplication/python_scripts/stokes_solver.py | HubertBalcerzak/Kratos | 0 | 6626614 | # importing the Kratos Library
import KratosMultiphysics as kratoscore
import KratosMultiphysics.FluidDynamicsApplication as cfd
import KratosMultiphysics.python_linear_solver_factory as linear_solver_factory
def AddVariables(model_part, settings=None):
model_part.AddNodalSolutionStepVariable(kratoscore.VELOCITY)... | # importing the Kratos Library
import KratosMultiphysics as kratoscore
import KratosMultiphysics.FluidDynamicsApplication as cfd
import KratosMultiphysics.python_linear_solver_factory as linear_solver_factory
def AddVariables(model_part, settings=None):
model_part.AddNodalSolutionStepVariable(kratoscore.VELOCITY)... | en | 0.581823 | # importing the Kratos Library #model_part.AddNodalSolutionStepVariable(kratoscore.VISCOSITY) #TODO: decide if it is needed. if constant it could be passed in properties #in case this variable could be removed if no reactions must be computed #model_part.AddNodalSolutionStepVariable(kratoscore.REACTION_WATER_PRESSURE) ... | 2.288943 | 2 |
scrapy_poi/utils/preset_items.py | ygo-prometheus/bilibili_danmaku_sensor | 0 | 6626615 | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class ErrorItem(scrapy.Item):
created_time = scrapy.Field()
created_time_ts = scrapy.Field()
reason = scrapy.Field()
request = scrapy.Fi... | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class ErrorItem(scrapy.Item):
created_time = scrapy.Field()
created_time_ts = scrapy.Field()
reason = scrapy.Field()
request = scrapy.Fi... | en | 0.638537 | # -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html | 2.109244 | 2 |
models/speech_silence_tpotclassifier.py | jim-schwoebel/pauses | 18 | 6626616 | import numpy as np
import json, pickle
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.svm import LinearSVC
# NOTE: Make sure that the class is labeled 'target' in the data file
g=json.load(open('speech_silence_tpotclassifier_.json'))
tpot_data=g['labels']
features=g['data']
tra... | import numpy as np
import json, pickle
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.svm import LinearSVC
# NOTE: Make sure that the class is labeled 'target' in the data file
g=json.load(open('speech_silence_tpotclassifier_.json'))
tpot_data=g['labels']
features=g['data']
tra... | en | 0.894309 | # NOTE: Make sure that the class is labeled 'target' in the data file # Average CV score on the training set was:0.9527629233511586 | 2.936551 | 3 |
.editorconfig*.py | bastula/regressors | 1 | 6626617 | <gh_stars>1-10
# http://editorconfig.org
root = true
[*]
indent_style = space
indent_size = 4
trim_trailing_whitespace = true
insert_final_newline = true
charset = utf-8
end_of_line = lf
[*.bat]
indent_style = tab
end_of_line = crlf
[LICENSE]
insert_final_newline = false
[Makefile]
indent_style = tab
| # http://editorconfig.org
root = true
[*]
indent_style = space
indent_size = 4
trim_trailing_whitespace = true
insert_final_newline = true
charset = utf-8
end_of_line = lf
[*.bat]
indent_style = tab
end_of_line = crlf
[LICENSE]
insert_final_newline = false
[Makefile]
indent_style = tab | es | 0.371743 | # http://editorconfig.org | 1.091883 | 1 |
100 Python Exercises/Day 3/11.py | elipopovadev/Tournament-Tracker | 0 | 6626618 | <filename>100 Python Exercises/Day 3/11.py<gh_stars>0
''' Question 11
Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input and then check whether they are divisible by 5 or not.
The numbers that are divisible by 5 are to be printed in a comma separated sequence.
Example:
0100,... | <filename>100 Python Exercises/Day 3/11.py<gh_stars>0
''' Question 11
Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input and then check whether they are divisible by 5 or not.
The numbers that are divisible by 5 are to be printed in a comma separated sequence.
Example:
0100,... | en | 0.918408 | Question 11 Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input and then check whether they are divisible by 5 or not. The numbers that are divisible by 5 are to be printed in a comma separated sequence. Example: 0100,0011,1010,1001,1010 Then the output should be: 1010 | 3.911133 | 4 |
samples/pattern_model.py | mode89/esn | 3 | 6626619 | import esn
import imp
import signals
import random
SEED = 0
PATTERN_LENGTH = 1
PATTERN_PAUSE = 0.5
OUTPUT_PULSE_AMPLITUDE = 0.9
OUTPUT_PULSE_LENGTH = 0.1
WASHOUT_TIME = 10.0
TRAIN_TIME = 100.0
VARIABLE_MAGNITUDE = True
FALSE_PATTERN = True
CONNECTIVITY = 0.5
TEACHER_FORCING = False
USE_ORTHONORMAL_MATRIX = True
TRAINI... | import esn
import imp
import signals
import random
SEED = 0
PATTERN_LENGTH = 1
PATTERN_PAUSE = 0.5
OUTPUT_PULSE_AMPLITUDE = 0.9
OUTPUT_PULSE_LENGTH = 0.1
WASHOUT_TIME = 10.0
TRAIN_TIME = 100.0
VARIABLE_MAGNITUDE = True
FALSE_PATTERN = True
CONNECTIVITY = 0.5
TEACHER_FORCING = False
USE_ORTHONORMAL_MATRIX = True
TRAINI... | none | 1 | 2.678037 | 3 | |
tests_python/tests_alpha/protocol.py | Sudha247/tezos | 0 | 6626620 | import datetime
from enum import Enum, auto
from typing import Optional
from copy import deepcopy
from tools import constants, utils
HASH = constants.ALPHA
DAEMON = constants.ALPHA_DAEMON
PARAMETERS = constants.ALPHA_PARAMETERS
TENDERBAKE_PARAMETERS = deepcopy(PARAMETERS)
TENDERBAKE_PARAMETERS['consensus_threshold'] ... | import datetime
from enum import Enum, auto
from typing import Optional
from copy import deepcopy
from tools import constants, utils
HASH = constants.ALPHA
DAEMON = constants.ALPHA_DAEMON
PARAMETERS = constants.ALPHA_PARAMETERS
TENDERBAKE_PARAMETERS = deepcopy(PARAMETERS)
TENDERBAKE_PARAMETERS['consensus_threshold'] ... | en | 0.59812 | Args: protocol (Protocol): protocol id (either CURRENT or PREV). Defaults to CURRENT Returns: A fresh copy of the protocol parameters w.r.t to protocol # deepcopy call prevents any unforeseen and unwanted side effects # on the array parameters # e.g., bootstrap_accounts, comm... | 2.561329 | 3 |
bin/count_boundary_reads_star_python2.py | ablifedev/SUVA | 1 | 6626621 | <filename>bin/count_boundary_reads_star_python2.py<gh_stars>1-10
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
####################################################################################
# Copyright (C) 2015-2019 by ABLIFE
#################################################################################... | <filename>bin/count_boundary_reads_star_python2.py<gh_stars>1-10
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
####################################################################################
# Copyright (C) 2015-2019 by ABLIFE
#################################################################################... | en | 0.215688 | #!/usr/bin/env python3 # -*- coding: utf-8 -*- #################################################################################### # Copyright (C) 2015-2019 by ABLIFE #################################################################################### # 名称:expression_quantity_calculation.py # 描述:计算表达量 # 作者:程超 # 创建时间:2... | 1.870337 | 2 |
test/augmenter/spectrogram/test_time_masking.py | techthiyanes/nlpaug | 3,121 | 6626622 | <gh_stars>1000+
import unittest
import os
from dotenv import load_dotenv
import numpy as np
from nlpaug.util import AudioLoader
import nlpaug.augmenter.spectrogram as nas
class TestTimeMasking(unittest.TestCase):
@classmethod
def setUpClass(cls):
env_config_path = os.path.abspath(os.path.join(
... | import unittest
import os
from dotenv import load_dotenv
import numpy as np
from nlpaug.util import AudioLoader
import nlpaug.augmenter.spectrogram as nas
class TestTimeMasking(unittest.TestCase):
@classmethod
def setUpClass(cls):
env_config_path = os.path.abspath(os.path.join(
os.path.di... | en | 0.447543 | # https://freewavesamples.com/yamaha-v50-rock-beat-120-bpm | 2.533675 | 3 |
sdk/python/flet/progress.py | flet-dev/flet | 0 | 6626623 | <gh_stars>0
from typing import Optional
from beartype import beartype
from flet.control import Control
class Progress(Control):
def __init__(
self,
label=None,
id=None,
ref=None,
description=None,
value=None,
bar_height=None,
width=None,
he... | from typing import Optional
from beartype import beartype
from flet.control import Control
class Progress(Control):
def __init__(
self,
label=None,
id=None,
ref=None,
description=None,
value=None,
bar_height=None,
width=None,
height=None,
... | en | 0.329529 | # value # description # bar_height # label | 2.513537 | 3 |
test_case_generator.py | jeticg/CMPT411-HW2 | 0 | 6626624 | <reponame>jeticg/CMPT411-HW2
import random
import sys
class KBTestCaseGenerator():
def __init__(self, length=10, atoms=10):
self.generate(length, atoms)
return
def generate(self, length, atoms):
self.atomList = []
self.sentenceList = []
for i in range(atoms):
... | import random
import sys
class KBTestCaseGenerator():
def __init__(self, length=10, atoms=10):
self.generate(length, atoms)
return
def generate(self, length, atoms):
self.atomList = []
self.sentenceList = []
for i in range(atoms):
self.atomList.append('a' +... | none | 1 | 3.124117 | 3 | |
kbc_pul/popularity/entity_counting/count_to_normalized_popularity.py | ML-KULeuven/KBC-as-PU-Learning | 4 | 6626625 | from abc import abstractmethod
from functools import partial
from typing import Callable
from kbc_pul.popularity.logistic_functions import logistic_popularity_function
class AbstractCountToNormalizedPopularityMapper:
"""
Maps a value in R to [0,1]
"""
@classmethod
def is_value_normalized(cls, va... | from abc import abstractmethod
from functools import partial
from typing import Callable
from kbc_pul.popularity.logistic_functions import logistic_popularity_function
class AbstractCountToNormalizedPopularityMapper:
"""
Maps a value in R to [0,1]
"""
@classmethod
def is_value_normalized(cls, va... | en | 0.800385 | Maps a value in R to [0,1] | 3.21108 | 3 |
traffic.py | jakeflo88/pythonClass | 0 | 6626626 | market_2nd = {'ns': 'green', 'ew': 'red'}
def switchLights(intersection):
for key in intersection.keys():
if intersection[key] == 'green':
intersection[key] = 'yellow'
elif intersection[key] == 'yellow':
intersection[key] = 'red'
elif intersection[key] == 're... | market_2nd = {'ns': 'green', 'ew': 'red'}
def switchLights(intersection):
for key in intersection.keys():
if intersection[key] == 'green':
intersection[key] = 'yellow'
elif intersection[key] == 'yellow':
intersection[key] = 'red'
elif intersection[key] == 're... | none | 1 | 3.759002 | 4 | |
my_vim_files/python27/Lib/test/test_difflib.py | satsaeid/dotfiles | 0 | 6626627 | <filename>my_vim_files/python27/Lib/test/test_difflib.py
import difflib
from test.test_support import run_unittest, findfile
import unittest
import doctest
import sys
class TestSFbugs(unittest.TestCase):
def test_ratio_for_null_seqn(self):
# Check clearing of SF bug 763023
s = difflib.Se... | <filename>my_vim_files/python27/Lib/test/test_difflib.py
import difflib
from test.test_support import run_unittest, findfile
import unittest
import doctest
import sys
class TestSFbugs(unittest.TestCase):
def test_ratio_for_null_seqn(self):
# Check clearing of SF bug 763023
s = difflib.Se... | en | 0.879752 | # Check clearing of SF bug 763023 # Check fix for bug #979794 # Check fix for bug #1488943 1. Beautiful is beTTer than ugly.
2. Explicit is better than implicit.
3. Simple is better than complex.
4. Complex is better than complicated. 1. Beautiful is better than ugly.
3. Simple is better than complex.... | 2.495894 | 2 |
tests/sources/python/2_advanced/src/modules/auxiliar.py | ramonamela/compss | 31 | 6626628 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
PyCOMPSs Testbench Tasks
========================
"""
# Imports
from pycompss.api.task import task
@task(returns=list)
def function_B(v):
import platform
return list(platform.uname())
def app2(*args):
from pycompss.api.api import compss_wait_on
result... | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
PyCOMPSs Testbench Tasks
========================
"""
# Imports
from pycompss.api.task import task
@task(returns=list)
def function_B(v):
import platform
return list(platform.uname())
def app2(*args):
from pycompss.api.api import compss_wait_on
result... | en | 0.54547 | #!/usr/bin/python # -*- coding: utf-8 -*- PyCOMPSs Testbench Tasks ======================== # Imports | 1.904604 | 2 |
src/environments/slp_sml.py | grockious/lcrl | 18 | 6626629 | from src.environments.slippery_grid import SlipperyGrid
import numpy as np
# an example slippery grid
# only the labelling function needs to be specified
# create a SlipperyGrid object
slp_sml = SlipperyGrid(shape=[12, 10], initial_state=[2, 0], slip_probability=0.05)
# define the labellings
labels = np.empty([slp_s... | from src.environments.slippery_grid import SlipperyGrid
import numpy as np
# an example slippery grid
# only the labelling function needs to be specified
# create a SlipperyGrid object
slp_sml = SlipperyGrid(shape=[12, 10], initial_state=[2, 0], slip_probability=0.05)
# define the labellings
labels = np.empty([slp_s... | en | 0.371844 | # an example slippery grid # only the labelling function needs to be specified # create a SlipperyGrid object # define the labellings # override the labels | 2.611243 | 3 |
tfx/orchestration/experimental/core/task_schedulers/manual_task_scheduler.py | avelez93/tfx | 1 | 6626630 | # Copyright 2021 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | # Copyright 2021 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | en | 0.852087 | # Copyright 2021 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a... | 1.928795 | 2 |
legion/jupyterlab-plugin/legion/jupyterlab/handlers/helper.py | legion-platform/legion | 19 | 6626631 | #
# Copyright 2019 EPAM Systems
#
# 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 a... | #
# Copyright 2019 EPAM Systems
#
# 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 a... | en | 0.738911 | # # Copyright 2019 EPAM Systems # # 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 a... | 1.893384 | 2 |
ColorDropperShapedFrame.py | Metallicow/ColorDropper | 1 | 6626632 | <filename>ColorDropperShapedFrame.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
## Copyright (c) 2017 <NAME>
##
## Permission is hereby granted, free of charge, to any person obtaining a copy
## of this software and associated documentation files (the "Software"), to deal
## in the Software without restriction, inc... | <filename>ColorDropperShapedFrame.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
## Copyright (c) 2017 <NAME>
##
## Permission is hereby granted, free of charge, to any person obtaining a copy
## of this software and associated documentation files (the "Software"), to deal
## in the Software without restriction, inc... | en | 0.631763 | #!/usr/bin/env python # -*- coding: utf-8 -*- ## Copyright (c) 2017 <NAME> ## ## Permission is hereby granted, free of charge, to any person obtaining a copy ## of this software and associated documentation files (the "Software"), to deal ## in the Software without restriction, including without limitation the rights #... | 2.211595 | 2 |
saga/namespace/entry.py | nikmagini/pilot | 13 | 6626633 |
__author__ = "<NAME>"
__copyright__ = "Copyright 2012-2013, The SAGA Project"
__license__ = "MIT"
import radical.utils.signatures as rus
import saga.adaptors.base as sab
import saga.exceptions as se
import saga.session as ss
import saga.task as st
import saga.url as s... |
__author__ = "<NAME>"
__copyright__ = "Copyright 2012-2013, The SAGA Project"
__license__ = "MIT"
import radical.utils.signatures as rus
import saga.adaptors.base as sab
import saga.exceptions as se
import saga.session as ss
import saga.task as st
import saga.url as s... | en | 0.502825 | # ------------------------------------------------------------------------------ # Represents a SAGA namespace entry as defined in GFD.90 The saga.namespace.Entry class represents, as the name indicates, an entry in some (local or remote) namespace. That class offers a number of operations on that entry, ... | 1.935638 | 2 |
ecl/tests/functional/baremetal/test_server.py | keiichi-hikita/eclsdk | 0 | 6626634 | <reponame>keiichi-hikita/eclsdk
# 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... | # 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 t... | en | 0.791043 | # 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 t... | 1.938767 | 2 |
setup.py | dota2tools/dtrspnsy | 0 | 6626635 | import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="dtrspnsy",
version="0.0.2",
author="upgradehq",
author_email="<EMAIL>",
description="search dota 2 responses english/russian/chinese",
long_description=lon... | import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="dtrspnsy",
version="0.0.2",
author="upgradehq",
author_email="<EMAIL>",
description="search dota 2 responses english/russian/chinese",
long_description=lon... | en | 0.782346 | # for pathlib and f strings | 1.589823 | 2 |
ir_datasets/datasets/dpr_w100.py | seanmacavaney/ir_datasets | 0 | 6626636 | <gh_stars>0
from typing import NamedTuple, Tuple
import ijson
import contextlib
import itertools
import ir_datasets
from ir_datasets.util import GzipExtract
from ir_datasets.datasets.base import Dataset, YamlDocumentation
from ir_datasets.formats import TsvDocs, BaseQueries, TrecQrels
_logger = ir_datasets.log.easy()
... | from typing import NamedTuple, Tuple
import ijson
import contextlib
import itertools
import ir_datasets
from ir_datasets.util import GzipExtract
from ir_datasets.datasets.base import Dataset, YamlDocumentation
from ir_datasets.formats import TsvDocs, BaseQueries, TrecQrels
_logger = ir_datasets.log.easy()
NAME = 'dp... | en | 0.992582 | # already built | 2.085419 | 2 |
ytcc/storage.py | alexkohler/ytgrep | 22 | 6626637 | # -*- coding: UTF-8 -*-
import re
import os
import hashlib
class Storage():
def __init__(self, video_url: str) -> None:
self.video_url = video_url
def get_file_path(self) -> str:
return 'subtitle_{0}.en.vtt'.format(re.sub(
r'[^\w-]', '', hashlib.md5(str(self.video_url).encode('u... | # -*- coding: UTF-8 -*-
import re
import os
import hashlib
class Storage():
def __init__(self, video_url: str) -> None:
self.video_url = video_url
def get_file_path(self) -> str:
return 'subtitle_{0}.en.vtt'.format(re.sub(
r'[^\w-]', '', hashlib.md5(str(self.video_url).encode('u... | en | 0.222803 | # -*- coding: UTF-8 -*- | 2.611652 | 3 |
PacoteDownload/Mundo 3 do curso/desafio 082.py | Gabriel-ER/CursoEmVideodoYoutube-Python- | 0 | 6626638 | lista = []
pares = []
impares = []
while True:
r = input("Enter para continuar: ").upper().strip()
if r == '':
lista.append(int(input("Número: ")))
else:
for i in lista:
if i % 2 == 0:
pares.append(i)
else:
impares.append(i)
pri... | lista = []
pares = []
impares = []
while True:
r = input("Enter para continuar: ").upper().strip()
if r == '':
lista.append(int(input("Número: ")))
else:
for i in lista:
if i % 2 == 0:
pares.append(i)
else:
impares.append(i)
pri... | none | 1 | 3.640152 | 4 | |
marginTrading/tests/test_marginTradingCalc_GUI/test_marginTradingCalc_GUI.py | sambiase/pycrypto | 3 | 6626639 | <reponame>sambiase/pycrypto
from marginTrading import marginTradingCalculation_GUI_v1 as mtc
import tkinter as tk
def test_init():
mtc.MarginTradingCalcGui.__init__(tk)
def test_mt_calculation():
mtc.MarginTradingCalcGui.mt_calculation(None,50,3,5,10)
def test_input_data():
mtc.MarginTradingCalcGui.in... | from marginTrading import marginTradingCalculation_GUI_v1 as mtc
import tkinter as tk
def test_init():
mtc.MarginTradingCalcGui.__init__(tk)
def test_mt_calculation():
mtc.MarginTradingCalcGui.mt_calculation(None,50,3,5,10)
def test_input_data():
mtc.MarginTradingCalcGui.input_data(tk)
def test_res_... | none | 1 | 2.205512 | 2 | |
tftime/layers/transformer.py | nagikomo/time-series-model | 7 | 6626640 | from tensorflow.keras import layers, Sequential
import tensorflow as tf
class PositionAdd(layers.Layer):
def build(self, input_shape):
self.pe = self.add_weight("pe", [input_shape[1], input_shape[2]],
initializer=tf.keras.initializers.zeros())
def call(self,... | from tensorflow.keras import layers, Sequential
import tensorflow as tf
class PositionAdd(layers.Layer):
def build(self, input_shape):
self.pe = self.add_weight("pe", [input_shape[1], input_shape[2]],
initializer=tf.keras.initializers.zeros())
def call(self,... | none | 1 | 2.646209 | 3 | |
remote/util.py | zadjii/nebula | 2 | 6626641 | <filename>remote/util.py
from models.Session import Session
from common_util import *
from remote.models.Cloud import Cloud
from remote.models.User import User
def get_user_from_session(db, session_id):
# rd = Error()
# sess_obj = db.session.query(Session).filter_by(uuid=session_id).first()
# if sess_obj ... | <filename>remote/util.py
from models.Session import Session
from common_util import *
from remote.models.Cloud import Cloud
from remote.models.User import User
def get_user_from_session(db, session_id):
# rd = Error()
# sess_obj = db.session.query(Session).filter_by(uuid=session_id).first()
# if sess_obj ... | en | 0.353584 | # rd = Error() # sess_obj = db.session.query(Session).filter_by(uuid=session_id).first() # if sess_obj is None: # rd = Error('No session exists on remote for sid:{}'.format(session_id)) # else: # user = sess_obj.user # if user is None: # rd = Error('No user exists on remote\'s session, sid:{}'.forma... | 2.390145 | 2 |
scripts/update-compdb.py | xiaohongchen1991/clang-xform | 2 | 6626642 | #!/usr/bin/env python
"""
update compile_commands.json file used in unit test framework
"""
import argparse
import os
import sys
import re
import json
def main(argv):
parser = argparse.ArgumentParser()
parser.add_argument(
'json_file',
type=str,
nargs='?',
default='compile_co... | #!/usr/bin/env python
"""
update compile_commands.json file used in unit test framework
"""
import argparse
import os
import sys
import re
import json
def main(argv):
parser = argparse.ArgumentParser()
parser.add_argument(
'json_file',
type=str,
nargs='?',
default='compile_co... | en | 0.512531 | #!/usr/bin/env python update compile_commands.json file used in unit test framework # update directory # write compdbs back to compile_commands.json | 2.916483 | 3 |
vnpy/app/portfolio_strategy/engine.py | longliveh/vnpy | 1 | 6626643 | """"""
import importlib
import glob
import traceback
from collections import defaultdict
from pathlib import Path
from typing import Dict, List, Set, Tuple, Type, Any, Callable
from datetime import datetime, timedelta
from concurrent.futures import ThreadPoolExecutor
from tzlocal import get_localzone
from vnpy.event ... | """"""
import importlib
import glob
import traceback
from collections import defaultdict
from pathlib import Path
from typing import Dict, List, Set, Tuple, Type, Any, Callable
from datetime import datetime, timedelta
from concurrent.futures import ThreadPoolExecutor
from tzlocal import get_localzone
from vnpy.event ... | en | 0.692761 | Init RQData client. Query bar data from RQData. # Filter duplicate trade push Send a new order to server. # Round order price and volume to nearest incremental value # Create request and send order. # Convert with offset converter # Send Orders # Add strategy name as order reference # Check if sending order successful ... | 1.874012 | 2 |
release/stubs.min/System/Net/__init___parts/OpenWriteCompletedEventArgs.py | htlcnn/ironpython-stubs | 182 | 6626644 | <filename>release/stubs.min/System/Net/__init___parts/OpenWriteCompletedEventArgs.py<gh_stars>100-1000
class OpenWriteCompletedEventArgs(AsyncCompletedEventArgs):
""" Provides data for the System.Net.WebClient.OpenWriteCompleted event. """
Result=property(lambda self: object(),lambda self,v: None,lambda self: None)... | <filename>release/stubs.min/System/Net/__init___parts/OpenWriteCompletedEventArgs.py<gh_stars>100-1000
class OpenWriteCompletedEventArgs(AsyncCompletedEventArgs):
""" Provides data for the System.Net.WebClient.OpenWriteCompleted event. """
Result=property(lambda self: object(),lambda self,v: None,lambda self: None)... | en | 0.710321 | Provides data for the System.Net.WebClient.OpenWriteCompleted event. Gets a writable stream that is used to send data to a server.
Get: Result(self: OpenWriteCompletedEventArgs) -> Stream | 1.608729 | 2 |
Lego-Collector-Dilemma/code.py | ashwin2401/ga-learner-dsmp-repo | 1 | 6626645 | # --------------
import pandas as pd
import numpy as np
from sklearn.cross_validation import train_test_split
# code starts here
df = pd.read_csv(path)
df.head(5)
X = df.drop(['list_price'],axis=1)
y = df['list_price']
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.3,random_state=6)
# code ends he... | # --------------
import pandas as pd
import numpy as np
from sklearn.cross_validation import train_test_split
# code starts here
df = pd.read_csv(path)
df.head(5)
X = df.drop(['list_price'],axis=1)
y = df['list_price']
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.3,random_state=6)
# code ends he... | en | 0.480485 | # -------------- # code starts here # code ends here # -------------- # code starts here # code ends here # -------------- # Code starts here # Code ends here # -------------- # Code starts here # Code ends here # -------------- # Code starts here # Code ends here | 3.089717 | 3 |
buddy/types/structured.py | ucbrise/buddy | 1 | 6626646 |
class Collection:
def __init__(self, key, value):
self.key = key,
self.value = value
class QueryString:
def __init__(self, query):
assert isinstance(query, str)
# Check that it's syntactically valid SQL
self.query = query
class Table(Collection):
def __init__(se... |
class Collection:
def __init__(self, key, value):
self.key = key,
self.value = value
class QueryString:
def __init__(self, query):
assert isinstance(query, str)
# Check that it's syntactically valid SQL
self.query = query
class Table(Collection):
def __init__(se... | en | 0.899595 | # Check that it's syntactically valid SQL | 2.916702 | 3 |
python/fmcc.py | wittrup/crap | 1 | 6626647 | from faulhaber_const import commands as FMCC
fautmel=['GTYP', 'GSER', 'VER', 'GN', 'GCL', 'GRM', 'GKN', 'RM', 'KN', 'ANSW', 'NET', 'CST', 'CO', 'SO', 'TO', 'SAVE', 'BAUD', 'NODEADR', 'GNODEADR', 'GADV', 'EN', 'DI', 'GTIMEOUT', 'TIMEOUT', 'UPTIME', 'SADV']
from crcmod.predefined import mkCrcFun as mkCrcFunPre
from crcm... | from faulhaber_const import commands as FMCC
fautmel=['GTYP', 'GSER', 'VER', 'GN', 'GCL', 'GRM', 'GKN', 'RM', 'KN', 'ANSW', 'NET', 'CST', 'CO', 'SO', 'TO', 'SAVE', 'BAUD', 'NODEADR', 'GNODEADR', 'GADV', 'EN', 'DI', 'GTIMEOUT', 'TIMEOUT', 'UPTIME', 'SADV']
from crcmod.predefined import mkCrcFun as mkCrcFunPre
from crcm... | none | 1 | 1.940733 | 2 | |
tests/unit/utils/test_net_thread.py | pyl1b/p2p0mq | 0 | 6626648 | # -*- coding: utf-8 -*-
"""
"""
from __future__ import unicode_literals
from __future__ import print_function
import logging
import threading
from unittest import TestCase
from unittest.mock import MagicMock, patch
from p2p0mq.utils.thread.netthread import KoNetThread, ThreadAuthenticator
logger = logging.getLogger(... | # -*- coding: utf-8 -*-
"""
"""
from __future__ import unicode_literals
from __future__ import print_function
import logging
import threading
from unittest import TestCase
from unittest.mock import MagicMock, patch
from p2p0mq.utils.thread.netthread import KoNetThread, ThreadAuthenticator
logger = logging.getLogger(... | en | 0.306537 | # -*- coding: utf-8 -*- # self.testee.context.destroy() | 2.375974 | 2 |
jwstobsim/__init__.py | roberthammer/JWST-observation-simulator | 1 | 6626649 | <reponame>roberthammer/JWST-observation-simulator<filename>jwstobsim/__init__.py
__all__ = ['utils']
#__version__ = "0.0.1"
from .utils import *
| __all__ = ['utils']
#__version__ = "0.0.1"
from .utils import * | en | 0.465929 | #__version__ = "0.0.1" | 1.040872 | 1 |
aio/aio-proxy/aio_proxy/parsers/section_activite_principale.py | etalab/api-search-annuaire-entreprises | 3 | 6626650 | <gh_stars>1-10
from typing import Optional
from aio_proxy.labels.helpers import sections_codes_naf
def validate_section_activite_principale(
section_activite_principale_clean: str,
) -> Optional[str]:
"""Check the validity of section_activite_principale.
Args:
section_activite_principale_clean(s... | from typing import Optional
from aio_proxy.labels.helpers import sections_codes_naf
def validate_section_activite_principale(
section_activite_principale_clean: str,
) -> Optional[str]:
"""Check the validity of section_activite_principale.
Args:
section_activite_principale_clean(str, optional):
... | en | 0.590445 | Check the validity of section_activite_principale. Args: section_activite_principale_clean(str, optional): section_activite_principale extracted and cleaned. Returns: None if section_activite_principale_clean is None. section_activite_principale_clean if valid. Raises: ... | 2.583366 | 3 |