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 |
|---|---|---|---|---|---|---|---|---|---|---|
program/program/trackers/TrackerCorrelation.py | JankaSvK/thesis | 1 | 8100 | <filename>program/program/trackers/TrackerCorrelation.py
import dlib
class CorrelationTracker(object):
def init(self, image, bbox):
self.tracker = dlib.correlation_tracker()
x, y, x2, y2 = bbox
x2 += x
y2 += y
self.tracker.start_track(image, dlib.rectangle(x, y, x2, y2))
... | <filename>program/program/trackers/TrackerCorrelation.py
import dlib
class CorrelationTracker(object):
def init(self, image, bbox):
self.tracker = dlib.correlation_tracker()
x, y, x2, y2 = bbox
x2 += x
y2 += y
self.tracker.start_track(image, dlib.rectangle(x, y, x2, y2))
... | none | 1 | 2.937498 | 3 | |
examples/nlp/language_modeling/megatron_gpt_ckpt_to_nemo.py | rilango/NeMo | 0 | 8101 | <reponame>rilango/NeMo<filename>examples/nlp/language_modeling/megatron_gpt_ckpt_to_nemo.py<gh_stars>0
# Copyright (c) 2021, NVIDIA CORPORATION. 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... | # Copyright (c) 2021, NVIDIA CORPORATION. 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 appli... | en | 0.820553 | # Copyright (c) 2021, NVIDIA CORPORATION. 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 appli... | 1.900189 | 2 |
sdk/python/pulumi_aws/apigateway/api_key.py | dixler/pulumi-aws | 0 | 8102 | <filename>sdk/python/pulumi_aws/apigateway/api_key.py<gh_stars>0
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import json
import warnings
import pulumi
import pulumi.runtime
from t... | <filename>sdk/python/pulumi_aws/apigateway/api_key.py<gh_stars>0
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import json
import warnings
import pulumi
import pulumi.runtime
from t... | en | 0.673187 | # coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** Amazon Resource Name (ARN) The creation date of the API key The API key description. Defaults to "Managed by Pulumi". Specifies whether ... | 1.765791 | 2 |
SROMPy/optimize/ObjectiveFunction.py | jwarner308/SROMPy | 23 | 8103 | <gh_stars>10-100
# Copyright 2018 United States Government as represented by the Administrator of
# the National Aeronautics and Space Administration. No copyright is claimed in
# the United States under Title 17, U.S. Code. All Other Rights Reserved.
# The Stochastic Reduced Order Models with Python (SROMPy) platform... | # Copyright 2018 United States Government as represented by the Administrator of
# the National Aeronautics and Space Administration. No copyright is claimed in
# the United States under Title 17, U.S. Code. All Other Rights Reserved.
# The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed
# un... | en | 0.839372 | # Copyright 2018 United States Government as represented by the Administrator of # the National Aeronautics and Space Administration. No copyright is claimed in # the United States under Title 17, U.S. Code. All Other Rights Reserved. # The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed # und... | 2.223747 | 2 |
test/utils.py | vasili-v/distcovery | 0 | 8104 | import os
import errno
import sys
def mock_directory_tree(tree):
tree = dict([(os.path.join(*key), value) \
for key, value in tree.iteritems()])
def listdir(path):
try:
names = tree[path]
except KeyError:
raise OSError(errno.ENOENT, os.strerror(err... | import os
import errno
import sys
def mock_directory_tree(tree):
tree = dict([(os.path.join(*key), value) \
for key, value in tree.iteritems()])
def listdir(path):
try:
names = tree[path]
except KeyError:
raise OSError(errno.ENOENT, os.strerror(err... | none | 1 | 2.721076 | 3 | |
var/spack/repos/builtin/packages/perl-ipc-run/package.py | adrianjhpc/spack | 2 | 8105 | <reponame>adrianjhpc/spack
# Copyright 2013-2019 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)
from spack import *
class PerlIpcRun(PerlPackage):
"""IPC::Run allows you to run and inte... | # Copyright 2013-2019 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)
from spack import *
class PerlIpcRun(PerlPackage):
"""IPC::Run allows you to run and interact with child processes u... | en | 0.840465 | # Copyright 2013-2019 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) IPC::Run allows you to run and interact with child processes using files, pipes, and pseudo-ttys. Both system()-style a... | 1.274021 | 1 |
tests/test_parser_create_site_users.py | WillAyd/tabcmd | 0 | 8106 | import sys
import unittest
try:
from unittest import mock
except ImportError:
import mock
import argparse
from tabcmd.parsers.create_site_users_parser import CreateSiteUsersParser
from .common_setup import *
commandname = 'createsiteusers'
class CreateSiteUsersParserTest(unittest.TestCase):
@classmethod... | import sys
import unittest
try:
from unittest import mock
except ImportError:
import mock
import argparse
from tabcmd.parsers.create_site_users_parser import CreateSiteUsersParser
from .common_setup import *
commandname = 'createsiteusers'
class CreateSiteUsersParserTest(unittest.TestCase):
@classmethod... | none | 1 | 2.871102 | 3 | |
secretsmanager_env.py | iarlyy/secretsmanager-env | 1 | 8107 | <filename>secretsmanager_env.py
#!/usr/bin/env python
import argparse
import json
import os
import boto3
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description='''\
Output following the defined format.
Options are:
dotenv - dotenv style [default]
expo... | <filename>secretsmanager_env.py
#!/usr/bin/env python
import argparse
import json
import os
import boto3
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description='''\
Output following the defined format.
Options are:
dotenv - dotenv style [default]
expo... | en | 0.279901 | #!/usr/bin/env python \ Output following the defined format. Options are: dotenv - dotenv style [default] export - shell export style stdout - secret plain value style | 2.661996 | 3 |
109.py | juandarr/ProjectEuler | 0 | 8108 | <reponame>juandarr/ProjectEuler
"""
Finds the number of distinct ways a player can checkout a score less than 100
Author: <NAME>
"""
import math
def checkout_solutions(checkout,sequence,idx_sq,d):
'''
returns the number of solution for a given checkout value
'''
counter = 0
for double in d:
... | """
Finds the number of distinct ways a player can checkout a score less than 100
Author: <NAME>
"""
import math
def checkout_solutions(checkout,sequence,idx_sq,d):
'''
returns the number of solution for a given checkout value
'''
counter = 0
for double in d:
if double>checkout:
... | en | 0.781295 | Finds the number of distinct ways a player can checkout a score less than 100 Author: <NAME> returns the number of solution for a given checkout value | 3.546687 | 4 |
src/tevatron/tevax/loss.py | vjeronymo2/tevatron | 95 | 8109 | <filename>src/tevatron/tevax/loss.py
import jax.numpy as jnp
from jax import lax
import optax
import chex
def _onehot(labels: chex.Array, num_classes: int) -> chex.Array:
x = labels[..., None] == jnp.arange(num_classes).reshape((1,) * labels.ndim + (-1,))
x = lax.select(x, jnp.ones(x.shape), jnp.zeros(x.shape... | <filename>src/tevatron/tevax/loss.py
import jax.numpy as jnp
from jax import lax
import optax
import chex
def _onehot(labels: chex.Array, num_classes: int) -> chex.Array:
x = labels[..., None] == jnp.arange(num_classes).reshape((1,) * labels.ndim + (-1,))
x = lax.select(x, jnp.ones(x.shape), jnp.zeros(x.shape... | none | 1 | 2.025411 | 2 | |
setup.py | kinnala/gammy | 0 | 8110 | import os
from setuptools import setup, find_packages
import versioneer
if __name__ == "__main__":
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
meta = {}
base_dir = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(base_dir, 'gammy', '_m... | import os
from setuptools import setup, find_packages
import versioneer
if __name__ == "__main__":
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
meta = {}
base_dir = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(base_dir, 'gammy', '_m... | none | 1 | 1.437618 | 1 | |
fast-ml/main.py | gabrielstork/fast-ml | 1 | 8111 | <gh_stars>1-10
import root
if __name__ == '__main__':
window = root.Root()
window.mainloop()
| import root
if __name__ == '__main__':
window = root.Root()
window.mainloop() | none | 1 | 1.514983 | 2 | |
application/recommendations/__init__.py | QualiChain/qualichain_backend | 0 | 8112 | <gh_stars>0
from flask import Blueprint
recommendation_blueprint = Blueprint('recommendations', __name__)
from application.recommendations import routes | from flask import Blueprint
recommendation_blueprint = Blueprint('recommendations', __name__)
from application.recommendations import routes | none | 1 | 1.376477 | 1 | |
predictors/scene_predictor.py | XenonLamb/higan | 83 | 8113 | # python 3.7
"""Predicts the scene category, attribute."""
import numpy as np
from PIL import Image
import torch
import torch.nn.functional as F
import torchvision.transforms as transforms
from .base_predictor import BasePredictor
from .scene_wideresnet import resnet18
__all__ = ['ScenePredictor']
N... | # python 3.7
"""Predicts the scene category, attribute."""
import numpy as np
from PIL import Image
import torch
import torch.nn.functional as F
import torchvision.transforms as transforms
from .base_predictor import BasePredictor
from .scene_wideresnet import resnet18
__all__ = ['ScenePredictor']
N... | en | 0.6677 | # python 3.7 Predicts the scene category, attribute. Defines the predictor class for scene analysis. # Load category labels. # Load attribute labels. # Transform for input images. # Load pre-trained weights for category prediction. # Load additional weights for attribute prediction. | 2.634934 | 3 |
python_test.py | jackKiZhu/mypython | 0 | 8114 | <gh_stars>0
from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql://root:mysql@127.0.0.1:3306/python_github"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True
db = SQLAlchemy(app)
class User(db.Model):
id = ... | from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql://root:mysql@127.0.0.1:3306/python_github"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db... | en | 0.158915 | # user_name = request.args.get("user_name", "") # user_pwd = request.args.get("user_pwd", "") # user_is_login = User.query.filter_by(user_name=user_name, user_password=<PASSWORD>).first() # if user_is_login: # index_meg = "登陆成功" # print("登陆成功") # return render_template("login_ok.html", index_meg=index_meg) ... | 2.72872 | 3 |
src/etc/gec/3.py | iml1111/algorithm-study | 0 | 8115 | from collections import deque
def solution(N, bus_stop):
answer = [[1300 for _ in range(N)] for _ in range(N)]
bus_stop = [(x-1, y-1) for x,y in bus_stop]
q = deque(bus_stop)
for x,y in bus_stop:
answer[x][y] = 0
while q:
x, y = q.popleft()
for nx, ny in ((x-1, y), (x+1, y)... | from collections import deque
def solution(N, bus_stop):
answer = [[1300 for _ in range(N)] for _ in range(N)]
bus_stop = [(x-1, y-1) for x,y in bus_stop]
q = deque(bus_stop)
for x,y in bus_stop:
answer[x][y] = 0
while q:
x, y = q.popleft()
for nx, ny in ((x-1, y), (x+1, y)... | none | 1 | 3.29523 | 3 | |
python/tree/0103_binary_tree_zigzag_level_order_traversal.py | linshaoyong/leetcode | 6 | 8116 | <gh_stars>1-10
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
... | class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
... | en | 0.171152 | :type root: TreeNode :rtype: List[List[int]] | 3.713916 | 4 |
plaso/parsers/winreg_plugins/usbstor.py | berggren/plaso | 2 | 8117 | <filename>plaso/parsers/winreg_plugins/usbstor.py
# -*- coding: utf-8 -*-
"""File containing a Windows Registry plugin to parse the USBStor key."""
from __future__ import unicode_literals
from plaso.containers import events
from plaso.containers import time_events
from plaso.lib import definitions
from plaso.parsers ... | <filename>plaso/parsers/winreg_plugins/usbstor.py
# -*- coding: utf-8 -*-
"""File containing a Windows Registry plugin to parse the USBStor key."""
from __future__ import unicode_literals
from plaso.containers import events
from plaso.containers import time_events
from plaso.lib import definitions
from plaso.parsers ... | en | 0.739674 | # -*- coding: utf-8 -*- File containing a Windows Registry plugin to parse the USBStor key. USBStor event data attribute container. Attributes: device_type (str): type of USB device. display_name (str): display name of the USB device. key_path (str): Windows Registry key path. parent_id_prefix (str):... | 2.25435 | 2 |
damn_vulnerable_python/evil.py | CodyKochmann/damn_vulnerable_python | 1 | 8118 | ''' static analyzers are annoying so lets rename eval '''
evil = eval
| ''' static analyzers are annoying so lets rename eval '''
evil = eval
| en | 0.786376 | static analyzers are annoying so lets rename eval | 1.16442 | 1 |
rltoolkit/rltoolkit/acm/off_policy/ddpg_acm.py | MIMUW-RL/spp-rl | 7 | 8119 | import numpy as np
import torch
from torch.nn import functional as F
from rltoolkit.acm.off_policy import AcMOffPolicy
from rltoolkit.algorithms import DDPG
from rltoolkit.algorithms.ddpg.models import Actor, Critic
class DDPG_AcM(AcMOffPolicy, DDPG):
def __init__(
self, unbiased_update: bool = False, cu... | import numpy as np
import torch
from torch.nn import functional as F
from rltoolkit.acm.off_policy import AcMOffPolicy
from rltoolkit.algorithms import DDPG
from rltoolkit.algorithms.ddpg.models import Actor, Critic
class DDPG_AcM(AcMOffPolicy, DDPG):
def __init__(
self, unbiased_update: bool = False, cu... | en | 0.732886 | DDPG with AcM class Args: unbiased_update (bool, optional): Use next_obs as action for update. Defaults to { False }. refill_buffer (bool, optional): if buffer should be refilled with new observations, when its full Defaults to {False} Compute targets for... | 2.145742 | 2 |
pyroute/poi_osm.py | ftrimble/route-grower | 0 | 8120 | #!/usr/bin/python
#----------------------------------------------------------------
# OSM POI handler for pyroute
#
#------------------------------------------------------
# Copyright 2007, <NAME>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public Lic... | #!/usr/bin/python
#----------------------------------------------------------------
# OSM POI handler for pyroute
#
#------------------------------------------------------
# Copyright 2007, <NAME>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public Lic... | en | 0.729736 | #!/usr/bin/python #---------------------------------------------------------------- # OSM POI handler for pyroute # #------------------------------------------------------ # Copyright 2007, <NAME> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public Lic... | 2.033282 | 2 |
pelutils/logger.py | peleiden/pelutils | 3 | 8121 | <gh_stars>1-10
from __future__ import annotations
import os
import traceback as tb
from collections import defaultdict
from enum import IntEnum
from functools import update_wrapper
from itertools import chain
from typing import Any, Callable, DefaultDict, Generator, Iterable, Optional
from pelutils import get_timestam... | from __future__ import annotations
import os
import traceback as tb
from collections import defaultdict
from enum import IntEnum
from functools import update_wrapper
from itertools import chain
from typing import Any, Callable, DefaultDict, Generator, Iterable, Optional
from pelutils import get_timestamp, get_repo
fro... | en | 0.846948 | Logging levels by priority. Don't set any to 0, as falsiness is used in the code # https://rich.readthedocs.io/en/stable/appendix/colors.html Used for disabling logging below a certain level Example: with log.level(Levels.WARNING): log.error("This will be logged") log.info("This will not be logg... | 2.378285 | 2 |
tests/test_metrics.py | aaxelb/django-elasticsearch-metrics | 5 | 8122 | <gh_stars>1-10
import mock
import pytest
import datetime as dt
from django.utils import timezone
from elasticsearch_metrics import metrics
from elasticsearch_dsl import IndexTemplate
from elasticsearch_metrics import signals
from elasticsearch_metrics.exceptions import (
IndexTemplateNotFoundError,
IndexTempla... | import mock
import pytest
import datetime as dt
from django.utils import timezone
from elasticsearch_metrics import metrics
from elasticsearch_dsl import IndexTemplate
from elasticsearch_metrics import signals
from elasticsearch_metrics.exceptions import (
IndexTemplateNotFoundError,
IndexTemplateOutOfSyncErro... | en | 0.611583 | # regression test # template name specified in class Meta # template is not specified, so it's generated # template name specified in class Meta # template is not specified, so it's generated # TODO flesh out this test more. Try to query ES? # When settings change, template is out of sync | 2.082535 | 2 |
6 kyu/SumFibs.py | mwk0408/codewars_solutions | 6 | 8123 | <reponame>mwk0408/codewars_solutions<filename>6 kyu/SumFibs.py
from functools import lru_cache
@lru_cache
def fib(n):
return n if n<2 else fib(n-1)+fib(n-2)
def sum_fibs(n):
return sum(j for j in (fib(i) for i in range(n+1)) if j%2==0) | kyu/SumFibs.py
from functools import lru_cache
@lru_cache
def fib(n):
return n if n<2 else fib(n-1)+fib(n-2)
def sum_fibs(n):
return sum(j for j in (fib(i) for i in range(n+1)) if j%2==0) | none | 1 | 3.757506 | 4 | |
tests/unit/test_iris_helpers.py | jvegreg/ESMValCore | 0 | 8124 | <filename>tests/unit/test_iris_helpers.py
"""Tests for :mod:`esmvalcore.iris_helpers`."""
import datetime
import iris
import numpy as np
import pytest
from cf_units import Unit
from esmvalcore.iris_helpers import date2num, var_name_constraint
@pytest.fixture
def cubes():
"""Test cubes."""
cubes = iris.cube.... | <filename>tests/unit/test_iris_helpers.py
"""Tests for :mod:`esmvalcore.iris_helpers`."""
import datetime
import iris
import numpy as np
import pytest
from cf_units import Unit
from esmvalcore.iris_helpers import date2num, var_name_constraint
@pytest.fixture
def cubes():
"""Test cubes."""
cubes = iris.cube.... | en | 0.263058 | Tests for :mod:`esmvalcore.iris_helpers`. Test cubes. Test :func:`esmvalcore.iris_helpers.var_name_constraint`. | 2.531956 | 3 |
geo_regions.py | saeed-moghimi-noaa/Maxelev_plot | 0 | 8125 | <filename>geo_regions.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Geo regions for map plot
"""
__author__ = "<NAME>"
__copyright__ = "Copyright 2017, UCAR/NOAA"
__license__ = "GPL"
__version__ = "1.0"
__email__ = "<EMAIL>"
import matplotlib.pyplot as plt
from collections import defaultdict
defs = defaultd... | <filename>geo_regions.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Geo regions for map plot
"""
__author__ = "<NAME>"
__copyright__ = "Copyright 2017, UCAR/NOAA"
__license__ = "GPL"
__version__ = "1.0"
__email__ = "<EMAIL>"
import matplotlib.pyplot as plt
from collections import defaultdict
defs = defaultd... | en | 0.551239 | #!/usr/bin/env python # -*- coding: utf-8 -*- Geo regions for map plot ##IKE ##IRMA ## ISABEL ## SANDY ## ANDREW ## operational upgrade # NYC area: -74.027725,40.596099 # Tampa area: -82.455511,27.921438 # Marshall Islands: 169.107299,7.906637 # Palau: 134.461436,7.436438 | 2.359016 | 2 |
figures/plot_log_figure_paper.py | davidADSP/deepAI_paper | 21 | 8126 | <reponame>davidADSP/deepAI_paper
import numpy
import matplotlib.pyplot as plt
fig_convergence = plt.figure(1,figsize=(12,6))
x = numpy.loadtxt('log_deepAI_paper_nonlin_action_long.txt')
plt.subplot(122)
plt.plot(x[:,0])
plt.xlim([0,500])
plt.ylim([-10,200])
plt.xlabel('Steps')
plt.ylabel('Free Action')
plt.axvline(x... | import numpy
import matplotlib.pyplot as plt
fig_convergence = plt.figure(1,figsize=(12,6))
x = numpy.loadtxt('log_deepAI_paper_nonlin_action_long.txt')
plt.subplot(122)
plt.plot(x[:,0])
plt.xlim([0,500])
plt.ylim([-10,200])
plt.xlabel('Steps')
plt.ylabel('Free Action')
plt.axvline(x=230.0,linestyle=':')
plt.axvline... | none | 1 | 2.475748 | 2 | |
setup.py | matiasgrana/nagios_sql | 0 | 8127 | <gh_stars>0
#! python3
# Help from: http://www.scotttorborg.com/python-packaging/minimal.html
# https://docs.python.org/3/distutils/commandref.html#sdist-cmd
# https://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files
# https://docs.python.org/3.4/tutorial/modules.html
# Install it with python ... | #! python3
# Help from: http://www.scotttorborg.com/python-packaging/minimal.html
# https://docs.python.org/3/distutils/commandref.html#sdist-cmd
# https://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files
# https://docs.python.org/3.4/tutorial/modules.html
# Install it with python setup.py ins... | en | 0.539492 | #! python3 # Help from: http://www.scotttorborg.com/python-packaging/minimal.html # https://docs.python.org/3/distutils/commandref.html#sdist-cmd # https://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files # https://docs.python.org/3.4/tutorial/modules.html # Install it with python setup.py ins... | 2.072865 | 2 |
textnn/utils/test/test_progress_iterator.py | tongr/TextNN | 1 | 8128 | import io
import sys
from textnn.utils import ProgressIterator
#inspired by https://stackoverflow.com/a/34738440
def capture_sysout(cmd):
capturedOutput = io.StringIO() # Create StringIO object
sys.stdout = capturedOutput # and redirect stdout.
cmd() ... | import io
import sys
from textnn.utils import ProgressIterator
#inspired by https://stackoverflow.com/a/34738440
def capture_sysout(cmd):
capturedOutput = io.StringIO() # Create StringIO object
sys.stdout = capturedOutput # and redirect stdout.
cmd() ... | en | 0.696754 | #inspired by https://stackoverflow.com/a/34738440 # Create StringIO object # and redirect stdout. # Call function. # Reset redirect. # Now works as before. # expected result (with changing numbers): # 1/3 [=========>....................] - ETA: 7s # 2/3 [===================>..........] - ETA: 1s # 3/3 [===============... | 2.653333 | 3 |
reach.py | NIKH0610/class5-homework | 0 | 8129 | import os
import numpy as np
import pandas as pd
housing_df = pd.read_csv(filepath_or_buffer='~/C:\Users\nikhi\NIKH0610\class5-homework\toys-datasets\boston') | import os
import numpy as np
import pandas as pd
housing_df = pd.read_csv(filepath_or_buffer='~/C:\Users\nikhi\NIKH0610\class5-homework\toys-datasets\boston') | none | 1 | 2.407378 | 2 | |
queries/general_queries.py | souparvo/airflow-plugins | 0 | 8130 |
def insert_metatable():
"""SQL query to insert records from table insert into a table on a DB
"""
return """
INSERT INTO TABLE {{ params.target_schema }}.{{ params.target_table }} VALUES
('{{ params.schema }}', '{{ params.table }}', {{ ti.xcom_pull(key='hive_res', task_ids=params.count_inserts)[0... |
def insert_metatable():
"""SQL query to insert records from table insert into a table on a DB
"""
return """
INSERT INTO TABLE {{ params.target_schema }}.{{ params.target_table }} VALUES
('{{ params.schema }}', '{{ params.table }}', {{ ti.xcom_pull(key='hive_res', task_ids=params.count_inserts)[0... | en | 0.148354 | SQL query to insert records from table insert into a table on a DB INSERT INTO TABLE {{ params.target_schema }}.{{ params.target_table }} VALUES ('{{ params.schema }}', '{{ params.table }}', {{ ti.xcom_pull(key='hive_res', task_ids=params.count_inserts)[0][0] }}, current_timestamp(), '{{ params.type }}'); | 2.66333 | 3 |
pyvisa_py/highlevel.py | Handfeger/pyvisa-py | 1 | 8131 | # -*- coding: utf-8 -*-
"""Highlevel wrapper of the VISA Library.
:copyright: 2014-2020 by PyVISA-py Authors, see AUTHORS for more details.
:license: MIT, see LICENSE for more details.
"""
import random
from collections import OrderedDict
from typing import Any, Dict, Iterable, List, Optional, Tuple, Union, cast
fr... | # -*- coding: utf-8 -*-
"""Highlevel wrapper of the VISA Library.
:copyright: 2014-2020 by PyVISA-py Authors, see AUTHORS for more details.
:license: MIT, see LICENSE for more details.
"""
import random
from collections import OrderedDict
from typing import Any, Dict, Iterable, List, Optional, Tuple, Union, cast
fr... | en | 0.661742 | # -*- coding: utf-8 -*- Highlevel wrapper of the VISA Library. :copyright: 2014-2020 by PyVISA-py Authors, see AUTHORS for more details. :license: MIT, see LICENSE for more details. A pure Python backend for PyVISA. The object is basically a dispatcher with some common functions implemented. When a new reso... | 2.094589 | 2 |
detectron/utils/webly_vis.py | sisrfeng/NA-fWebSOD | 23 | 8132 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import cv2
import numpy as np
import os
import math
from PIL import Image, ImageDraw, ImageFont
from caffe2.python import workspace
from detectron.core.config import cf... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import cv2
import numpy as np
import os
import math
from PIL import Image, ImageDraw, ImageFont
from caffe2.python import workspace
from detectron.core.config import cf... | en | 0.417631 | # roi_score_softmax = workspace.FetchBlob('gpu_{}/{}'.format( # gpu_id, prefix + 'rois_pred_softmax')) # anchor_argmax = workspace.FetchBlob('gpu_{}/{}'.format( # gpu_id, 'anchor_argmax')) # continue # if labels_oh[b][c] == 0.0: # continue # if labels_oh[b][c] == 0.0: # continue # draw roi # roi location # draw rois_pr... | 2.217182 | 2 |
salt/runner.py | StepOneInc/salt | 1 | 8133 | # -*- coding: utf-8 -*-
'''
Execute salt convenience routines
'''
# Import python libs
from __future__ import print_function
from __future__ import absolute_import
import collections
import logging
import time
import sys
import multiprocessing
# Import salt libs
import salt.exceptions
import salt.loader
import salt.m... | # -*- coding: utf-8 -*-
'''
Execute salt convenience routines
'''
# Import python libs
from __future__ import print_function
from __future__ import absolute_import
import collections
import logging
import time
import sys
import multiprocessing
# Import salt libs
import salt.exceptions
import salt.loader
import salt.m... | en | 0.757486 | # -*- coding: utf-8 -*- Execute salt convenience routines # Import python libs # Import salt libs The interface used by the :command:`salt-run` CLI tool on the Salt Master It executes :ref:`runner modules <all-salt.runners>` which run on the Salt Master. Importing and using ``RunnerClient`` must be done o... | 2.24697 | 2 |
.venv/lib/python3.8/site-packages/poetry/core/_vendor/lark/__pyinstaller/__init__.py | RivtLib/replit01 | 1 | 8134 | # For usage of lark with PyInstaller. See https://pyinstaller-sample-hook.readthedocs.io/en/latest/index.html
import os
def get_hook_dirs():
return [os.path.dirname(__file__)] | # For usage of lark with PyInstaller. See https://pyinstaller-sample-hook.readthedocs.io/en/latest/index.html
import os
def get_hook_dirs():
return [os.path.dirname(__file__)] | en | 0.754897 | # For usage of lark with PyInstaller. See https://pyinstaller-sample-hook.readthedocs.io/en/latest/index.html | 1.603295 | 2 |
pong-pg.py | s-gv/pong-keras | 0 | 8135 | <filename>pong-pg.py
# Copyright (c) 2019 <NAME>. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import sys
import numpy as np
import gym
import tensorflow as tf
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.laye... | <filename>pong-pg.py
# Copyright (c) 2019 <NAME>. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import sys
import numpy as np
import gym
import tensorflow as tf
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.laye... | en | 0.806982 | # Copyright (c) 2019 <NAME>. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # Neural net model takes the state and outputs action and value for that state # preprocess frames prepro 210x160x3 uint8 frame into 6400 (80x80) 1D float vector. http:... | 2.413043 | 2 |
dexp/cli/dexp_commands/crop.py | JoOkuma/dexp | 0 | 8136 | import click
from arbol.arbol import aprint, asection
from dexp.cli.defaults import DEFAULT_CLEVEL, DEFAULT_CODEC, DEFAULT_STORE
from dexp.cli.parsing import _get_output_path, _parse_channels, _parse_chunks
from dexp.datasets.open_dataset import glob_datasets
from dexp.datasets.operations.crop import dataset_crop
@c... | import click
from arbol.arbol import aprint, asection
from dexp.cli.defaults import DEFAULT_CLEVEL, DEFAULT_CODEC, DEFAULT_STORE
from dexp.cli.parsing import _get_output_path, _parse_channels, _parse_chunks
from dexp.datasets.open_dataset import glob_datasets
from dexp.datasets.operations.crop import dataset_crop
@c... | en | 0.313179 | # , help='input path' # , help='output path' # # | 2.001261 | 2 |
morse_DMT/write_dipha_file_3d_revise.py | YinuoJin/DMT_loss | 1 | 8137 | import sys
from matplotlib import image as mpimg
import numpy as np
import os
DIPHA_CONST = 8067171840
DIPHA_IMAGE_TYPE_CONST = 1
DIM = 3
input_dir = os.path.join(os.getcwd(), sys.argv[1])
dipha_output_filename = sys.argv[2]
vert_filename = sys.argv[3]
input_filenames = [name
for nam... | import sys
from matplotlib import image as mpimg
import numpy as np
import os
DIPHA_CONST = 8067171840
DIPHA_IMAGE_TYPE_CONST = 1
DIM = 3
input_dir = os.path.join(os.getcwd(), sys.argv[1])
dipha_output_filename = sys.argv[2]
vert_filename = sys.argv[3]
input_filenames = [name
for nam... | en | 0.803509 | #sys.exit() # this is needed to verify you are giving dipha a dipha file # this tells dipha that we are giving an image as input # number of points # dimension # pixels in each dimension # pixel values if val != 0 and val != -1:
print('val check:', val) | 2.349253 | 2 |
microservices/validate/tools/validates.py | clodonil/pipeline_aws_custom | 0 | 8138 | """
Tools para validar o arquivo template recebido do SQS
"""
class Validate:
def __init__(self):
pass
def check_validate_yml(self, template):
"""
valida se o arquivo yml é valido
"""
if template:
return True
else:
return False
def che... | """
Tools para validar o arquivo template recebido do SQS
"""
class Validate:
def __init__(self):
pass
def check_validate_yml(self, template):
"""
valida se o arquivo yml é valido
"""
if template:
return True
else:
return False
def che... | pt | 0.638276 | Tools para validar o arquivo template recebido do SQS valida se o arquivo yml é valido Valida se a estrutura do yml é valido Valida se o template informado no arquivo yml existe validar se o protocolo e endpoint são validos | 2.877774 | 3 |
MetropolisMCMC.py | unrealTOM/MC | 4 | 8139 | import numpy as np
import matplotlib.pyplot as plt
import math
def normal(mu,sigma,x): #normal distribution
return 1/(math.pi*2)**0.5/sigma*np.exp(-(x-mu)**2/2/sigma**2)
def eval(x):
return normal(-4,1,x) + normal(4,1,x)
#return 0.3*np.exp(-0.2*x**2)+0.7*np.exp(-0.2*(x-10)**2)
def ref(x_star,x): #normal... | import numpy as np
import matplotlib.pyplot as plt
import math
def normal(mu,sigma,x): #normal distribution
return 1/(math.pi*2)**0.5/sigma*np.exp(-(x-mu)**2/2/sigma**2)
def eval(x):
return normal(-4,1,x) + normal(4,1,x)
#return 0.3*np.exp(-0.2*x**2)+0.7*np.exp(-0.2*(x-10)**2)
def ref(x_star,x): #normal... | en | 0.376885 | #normal distribution #return 0.3*np.exp(-0.2*x**2)+0.7*np.exp(-0.2*(x-10)**2) #normal distribution #initialize x0 to be 0.1 #*q(x,x_star)/p(x)/q(x_star,x)) #ax.plot(x,eval(x)/2.7) #2.7 approximates the normalizing constant #2 approximates the normalizing constant #fig.suptitle('Metropolis_Hastings for MCMC(Exp.)') #plt... | 3.176049 | 3 |
gfwlist/gen.py | lipeijian/shadowsocks-android | 137 | 8140 | <reponame>lipeijian/shadowsocks-android
#!/usr/bin/python
# -*- encoding: utf8 -*-
import itertools
import math
import sys
import IPy
def main():
china_list_set = IPy.IPSet()
for line in sys.stdin:
china_list_set.add(IPy.IP(line))
# 输出结果
for ip in china_list_set:
print '<item>' + st... | #!/usr/bin/python
# -*- encoding: utf8 -*-
import itertools
import math
import sys
import IPy
def main():
china_list_set = IPy.IPSet()
for line in sys.stdin:
china_list_set.add(IPy.IP(line))
# 输出结果
for ip in china_list_set:
print '<item>' + str(ip) + '</item>'
if __name__ == "__ma... | ja | 0.203684 | #!/usr/bin/python # -*- encoding: utf8 -*- # 输出结果 | 3.262187 | 3 |
Specialization/Personal/SortHours.py | lastralab/Statistics | 3 | 8141 | name = "mail.txt"
counts = dict()
handle = open(name)
for line in handle:
line = line.rstrip()
if line == '':
continue
words = line.split()
if words[0] == 'From':
counts[words[5][:2]] = counts.get(words[5][:2], 0) + 1
tlist = list()
for key, value in counts.items():
... | name = "mail.txt"
counts = dict()
handle = open(name)
for line in handle:
line = line.rstrip()
if line == '':
continue
words = line.split()
if words[0] == 'From':
counts[words[5][:2]] = counts.get(words[5][:2], 0) + 1
tlist = list()
for key, value in counts.items():
... | none | 1 | 3.238135 | 3 | |
core/simulators/carla_scenario_simulator.py | RangiLyu/DI-drive | 0 | 8142 | import os
from typing import Any, Dict, List, Optional
import carla
from core.simulators.carla_simulator import CarlaSimulator
from core.simulators.carla_data_provider import CarlaDataProvider
from .srunner.scenarios.route_scenario import RouteScenario, SCENARIO_CLASS_DICT
from .srunner.scenariomanager.scenario_mana... | import os
from typing import Any, Dict, List, Optional
import carla
from core.simulators.carla_simulator import CarlaSimulator
from core.simulators.carla_data_provider import CarlaDataProvider
from .srunner.scenarios.route_scenario import RouteScenario, SCENARIO_CLASS_DICT
from .srunner.scenariomanager.scenario_mana... | en | 0.743983 | Carla simualtor used to run scenarios. The simulator loads configs of provided scenario, and create hero actor, npc vehicles, walkers, world map according to it. The sensors and running status are set as common Carla simulator. When created, it will set up Carla client due to arguments, set simulator basic... | 2.524806 | 3 |
bin/run.py | Conengmo/python-empty-project | 0 | 8143 | import myproject
myproject.logs(show_level='debug')
myproject.mymod.do_something()
| import myproject
myproject.logs(show_level='debug')
myproject.mymod.do_something()
| none | 1 | 1.369227 | 1 | |
development/simple_email.py | gerold-penz/python-simplemail | 16 | 8144 | <filename>development/simple_email.py
#!/usr/bin/env python
# coding: utf-8
# BEGIN --- required only for testing, remove in real world code --- BEGIN
import os
import sys
THISDIR = os.path.dirname(os.path.abspath(__file__))
APPDIR = os.path.abspath(os.path.join(THISDIR, os.path.pardir, os.path.pardir))
sys.path.inser... | <filename>development/simple_email.py
#!/usr/bin/env python
# coding: utf-8
# BEGIN --- required only for testing, remove in real world code --- BEGIN
import os
import sys
THISDIR = os.path.dirname(os.path.abspath(__file__))
APPDIR = os.path.abspath(os.path.join(THISDIR, os.path.pardir, os.path.pardir))
sys.path.inser... | en | 0.660359 | #!/usr/bin/env python # coding: utf-8 # BEGIN --- required only for testing, remove in real world code --- BEGIN # END --- required only for testing, remove in real world code --- END | 2.795105 | 3 |
features/hdf_features.py | DerekYJC/bmi_python | 0 | 8145 | <reponame>DerekYJC/bmi_python
'''
HDF-saving features
'''
import time
import tempfile
import random
import traceback
import numpy as np
import fnmatch
import os, sys
import subprocess
from riglib import calibrations, bmi
from riglib.bmi import extractor
from riglib.experiment import traits
import hdfwriter
class Save... | '''
HDF-saving features
'''
import time
import tempfile
import random
import traceback
import numpy as np
import fnmatch
import os, sys
import subprocess
from riglib import calibrations, bmi
from riglib.bmi import extractor
from riglib.experiment import traits
import hdfwriter
class SaveHDF(object):
'''
Saves... | en | 0.788463 | HDF-saving features Saves data from registered sources into tables in an HDF file Secondary init function. See riglib.experiment.Experiment.init() Prior to starting the task, this 'init' starts an HDFWriter sink. Specify the sink class as a function in case future descendant classes want to use a different type... | 2.43676 | 2 |
common/irma/common/exceptions.py | vaginessa/irma | 0 | 8146 | <reponame>vaginessa/irma
#
# Copyright (c) 2013-2018 Quarkslab.
# This file is part of IRMA project.
#
# 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 in the top-level directory
# of this distribu... | #
# Copyright (c) 2013-2018 Quarkslab.
# This file is part of IRMA project.
#
# 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 in the top-level directory
# of this distribution and at:
#
# http:... | en | 0.860838 | # # Copyright (c) 2013-2018 Quarkslab. # This file is part of IRMA project. # # 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 in the top-level directory # of this distribution and at: # # http:... | 1.957827 | 2 |
tf_crnn/libs/infer.py | sunmengnan/city_brain | 0 | 8147 | <reponame>sunmengnan/city_brain
import time
import os
import math
import numpy as np
from libs import utils
from libs.img_dataset import ImgDataset
from nets.crnn import CRNN
from nets.cnn.paper_cnn import PaperCNN
import shutil
def calculate_accuracy(predicts, labels):
"""
:param predicts: encoded predict ... | import time
import os
import math
import numpy as np
from libs import utils
from libs.img_dataset import ImgDataset
from nets.crnn import CRNN
from nets.cnn.paper_cnn import PaperCNN
import shutil
def calculate_accuracy(predicts, labels):
"""
:param predicts: encoded predict result
:param labels: ground... | en | 0.413463 | :param predicts: encoded predict result :param labels: ground true label :return: accuracy 排除了 edit_distance == 0 的值计算编辑距离的均值 :param edit_distences: :return: Save file name: {acc}_{step}.txt :param sess: tensorflow session :param model: crnn network :param result_dir: :param name: val, t... | 2.303129 | 2 |
Day 2/Day_2_Python.py | giTan7/30-Days-Of-Code | 1 | 8148 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the solve function below.
def solve(meal_cost, tip_percent, tax_percent):
tip = (meal_cost * tip_percent)/100
tax = (meal_cost * tax_percent)/100
print(int(meal_cost + tip + tax + 0.5))
# We add 0.5 because... | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the solve function below.
def solve(meal_cost, tip_percent, tax_percent):
tip = (meal_cost * tip_percent)/100
tax = (meal_cost * tax_percent)/100
print(int(meal_cost + tip + tax + 0.5))
# We add 0.5 because... | en | 0.717038 | #!/bin/python3 # Complete the solve function below. # We add 0.5 because the float should be rounded to the nearest integer # Time complexity: O(1) # Space complexity: O(1) | 3.974538 | 4 |
modules/templates/RLPPTM/tools/mis.py | nursix/rlpptm | 1 | 8149 | # -*- coding: utf-8 -*-
#
# Helper Script for Mass-Invitation of Participant Organisations
#
# RLPPTM Template Version 1.0
#
# Execute in web2py folder after code upgrade like:
# python web2py.py -S eden -M -R applications/eden/modules/templates/RLPPTM/tools/mis.py
#
import os
import sys
from core import s3_format_dat... | # -*- coding: utf-8 -*-
#
# Helper Script for Mass-Invitation of Participant Organisations
#
# RLPPTM Template Version 1.0
#
# Execute in web2py folder after code upgrade like:
# python web2py.py -S eden -M -R applications/eden/modules/templates/RLPPTM/tools/mis.py
#
import os
import sys
from core import s3_format_dat... | en | 0.607011 | # -*- coding: utf-8 -*- # # Helper Script for Mass-Invitation of Participant Organisations # # RLPPTM Template Version 1.0 # # Execute in web2py folder after code upgrade like: # python web2py.py -S eden -M -R applications/eden/modules/templates/RLPPTM/tools/mis.py # # Batch limit (set to False to disable) # Override a... | 1.844329 | 2 |
data/train/python/22aec8fbe47f7975a1e7f4a0caa5c88c56e4a03e__init__.py | harshp8l/deep-learning-lang-detection | 84 | 8150 | def save_form(form, actor=None):
"""Allows storing a form with a passed actor. Normally, Form.save() does not accept an actor, but if you require
this to be passed (is not handled by middleware), you can use this to replace form.save().
Requires you to use the audit.Model model as the actor is passed to th... | def save_form(form, actor=None):
"""Allows storing a form with a passed actor. Normally, Form.save() does not accept an actor, but if you require
this to be passed (is not handled by middleware), you can use this to replace form.save().
Requires you to use the audit.Model model as the actor is passed to th... | en | 0.773747 | Allows storing a form with a passed actor. Normally, Form.save() does not accept an actor, but if you require this to be passed (is not handled by middleware), you can use this to replace form.save(). Requires you to use the audit.Model model as the actor is passed to the object's save method. #def intermediat... | 3.42811 | 3 |
engine/test_sysctl.py | kingsd041/os-tests | 0 | 8151 | # coding = utf-8
# Create date: 2018-11-05
# Author :Hailong
def test_sysctl(ros_kvm_with_paramiko, cloud_config_url):
command = 'sudo cat /proc/sys/kernel/domainname'
feed_back = 'test'
client = ros_kvm_with_paramiko(cloud_config='{url}/test_sysctl.yml'.format(url=cloud_config_url))
stdin, stdout, st... | # coding = utf-8
# Create date: 2018-11-05
# Author :Hailong
def test_sysctl(ros_kvm_with_paramiko, cloud_config_url):
command = 'sudo cat /proc/sys/kernel/domainname'
feed_back = 'test'
client = ros_kvm_with_paramiko(cloud_config='{url}/test_sysctl.yml'.format(url=cloud_config_url))
stdin, stdout, st... | en | 0.832735 | # coding = utf-8 # Create date: 2018-11-05 # Author :Hailong | 1.984443 | 2 |
paprika_sync/core/management/commands/import_recipes_from_file.py | grschafer/paprika-sync | 0 | 8152 | import json
import logging
from django.core.management.base import BaseCommand
from django.db import transaction
from paprika_sync.core.models import PaprikaAccount
from paprika_sync.core.serializers import RecipeSerializer, CategorySerializer
from paprika_sync.core.utils import log_start_end
logger = logging.getLo... | import json
import logging
from django.core.management.base import BaseCommand
from django.db import transaction
from paprika_sync.core.models import PaprikaAccount
from paprika_sync.core.serializers import RecipeSerializer, CategorySerializer
from paprika_sync.core.utils import log_start_end
logger = logging.getLo... | en | 0.497824 | # Remove categories if we're not bothering to import them # recipe_field_names = set([f.name for f in Recipe._meta.fields]) # Recipe.objects.create( # paprika_account=pa, # **{k: v for k, v in recipe.items() if k in recipe_field_names}, # ) # transaction.set_rollback(True) | 2.093487 | 2 |
scripts/update_asp_l1.py | sot/mica | 0 | 8153 | #!/usr/bin/env python
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import mica.archive.asp_l1
mica.archive.asp_l1.main()
| #!/usr/bin/env python
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import mica.archive.asp_l1
mica.archive.asp_l1.main()
| en | 0.567712 | #!/usr/bin/env python # Licensed under a 3-clause BSD style license - see LICENSE.rst | 0.868234 | 1 |
pair.py | hhgarnes/python-validity | 0 | 8154 | <reponame>hhgarnes/python-validity<gh_stars>0
from time import sleep
from proto9x.usb import usb
from proto9x.tls import tls
from proto9x.flash import read_flash
from proto9x.init_flash import init_flash
from proto9x.upload_fwext import upload_fwext
from proto9x.calibrate import calibrate
from proto9x.init_db import ... | from time import sleep
from proto9x.usb import usb
from proto9x.tls import tls
from proto9x.flash import read_flash
from proto9x.init_flash import init_flash
from proto9x.upload_fwext import upload_fwext
from proto9x.calibrate import calibrate
from proto9x.init_db import init_db
#usb.trace_enabled=True
#tls.trace_ena... | zh | 0.311698 | #usb.trace_enabled=True #tls.trace_enabled=True | 2.159036 | 2 |
output/models/ms_data/element/elem_q017_xsd/elem_q017.py | tefra/xsdata-w3c-tests | 1 | 8155 | from dataclasses import dataclass, field
@dataclass
class FooTest:
class Meta:
name = "fooTest"
value: str = field(
init=False,
default="Hello"
)
@dataclass
class Root:
class Meta:
name = "root"
foo_test: str = field(
init=False,
default="Hello",... | from dataclasses import dataclass, field
@dataclass
class FooTest:
class Meta:
name = "fooTest"
value: str = field(
init=False,
default="Hello"
)
@dataclass
class Root:
class Meta:
name = "root"
foo_test: str = field(
init=False,
default="Hello",... | none | 1 | 2.930167 | 3 | |
contrib_src/predict.py | modelhub-ai/mic-dkfz-brats | 1 | 8156 | import json
import os
from collections import OrderedDict
from copy import deepcopy
import SimpleITK as sitk
from batchgenerators.augmentations.utils import resize_segmentation # resize_softmax_output
from skimage.transform import resize
from torch.optim import lr_scheduler
from torch import nn
import numpy as np
impor... | import json
import os
from collections import OrderedDict
from copy import deepcopy
import SimpleITK as sitk
from batchgenerators.augmentations.utils import resize_segmentation # resize_softmax_output
from skimage.transform import resize
from torch.optim import lr_scheduler
from torch import nn
import numpy as np
impor... | en | 0.739555 | # resize_softmax_output This code is not intended to be looked at by anyone. It is messy. It is undocumented. And the entire training pipeline is missing. :param x: (c, x, y , z) :param do_mirroring: :param num_repeats: :param use_train_mode: :param batch_size: :param mirror_axes... | 2.095942 | 2 |
plot/finderror.py | architsakhadeo/Offline-Hyperparameter-Tuning-for-RL | 0 | 8157 | <reponame>architsakhadeo/Offline-Hyperparameter-Tuning-for-RL
import os
basepath = '/home/archit/scratch/cartpoles/data/hyperparam/cartpole/offline_learning/esarsa-adam/'
dirs = os.listdir(basepath)
string = ''''''
for dir in dirs:
print(dir)
subbasepath = basepath + dir + '/'
subdirs = os.listdir(subbasepath)
for ... | import os
basepath = '/home/archit/scratch/cartpoles/data/hyperparam/cartpole/offline_learning/esarsa-adam/'
dirs = os.listdir(basepath)
string = ''''''
for dir in dirs:
print(dir)
subbasepath = basepath + dir + '/'
subdirs = os.listdir(subbasepath)
for subdir in subdirs:
print(subdir)
subsubbasepath = subbasep... | none | 1 | 2.284702 | 2 | |
src/pybacked/zip_handler.py | bluePlatinum/pyback | 0 | 8158 | import os
import shutil
import tempfile
import zipfile
def archive_write(archivepath, data, filename, compression, compressionlevel):
"""
Create a file named filename in the archive and write data to it
:param archivepath: The path to the zip-archive
:type archivepath: str
:param data: The data t... | import os
import shutil
import tempfile
import zipfile
def archive_write(archivepath, data, filename, compression, compressionlevel):
"""
Create a file named filename in the archive and write data to it
:param archivepath: The path to the zip-archive
:type archivepath: str
:param data: The data t... | en | 0.736778 | Create a file named filename in the archive and write data to it :param archivepath: The path to the zip-archive :type archivepath: str :param data: The data to be written to the file :type data: str :param filename: The filename for the newly created file :type filename: str :param compres... | 4.062939 | 4 |
src/query_planner/abstract_scan_plan.py | imvinod/Eva | 1 | 8159 | <filename>src/query_planner/abstract_scan_plan.py
"""Abstract class for all the scan planners
https://www.postgresql.org/docs/9.1/using-explain.html
https://www.postgresql.org/docs/9.5/runtime-config-query.html
"""
from src.query_planner.abstract_plan import AbstractPlan
from typing import List
class AbstractScan(Abs... | <filename>src/query_planner/abstract_scan_plan.py
"""Abstract class for all the scan planners
https://www.postgresql.org/docs/9.1/using-explain.html
https://www.postgresql.org/docs/9.5/runtime-config-query.html
"""
from src.query_planner.abstract_plan import AbstractPlan
from typing import List
class AbstractScan(Abs... | en | 0.635108 | Abstract class for all the scan planners https://www.postgresql.org/docs/9.1/using-explain.html https://www.postgresql.org/docs/9.5/runtime-config-query.html Abstract class for all the scan based planners Arguments: predicate : Expression video : video on which the scan will be executed ... | 2.810113 | 3 |
tests/tools/test-tcp4-client.py | jimmy-huang/zephyr.js | 0 | 8160 | # !usr/bin/python
# coding:utf-8
import time
import socket
def main():
print "Socket client creat successful"
host = "192.0.2.1"
port = 9876
bufSize = 1024
addr = (host, port)
Timeout = 300
mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mySocket.settimeout(Timeout)
... | # !usr/bin/python
# coding:utf-8
import time
import socket
def main():
print "Socket client creat successful"
host = "192.0.2.1"
port = 9876
bufSize = 1024
addr = (host, port)
Timeout = 300
mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mySocket.settimeout(Timeout)
... | en | 0.714691 | # !usr/bin/python # coding:utf-8 | 3.154387 | 3 |
kinto/__main__.py | s-utsch/kinto | 0 | 8161 | import argparse
import sys
from cliquet.scripts import cliquet
from pyramid.scripts import pserve
from pyramid.paster import bootstrap
def main(args=None):
"""The main routine."""
if args is None:
args = sys.argv[1:]
parser = argparse.ArgumentParser(description="Kinto commands... | import argparse
import sys
from cliquet.scripts import cliquet
from pyramid.scripts import pserve
from pyramid.paster import bootstrap
def main(args=None):
"""The main routine."""
if args is None:
args = sys.argv[1:]
parser = argparse.ArgumentParser(description="Kinto commands... | en | 0.838268 | The main routine. | 2.596503 | 3 |
apis/admin.py | JumboCode/GroundWorkSomerville | 0 | 8162 | from django.contrib import admin
from django.contrib.auth.models import User
from .models import Vegetable, Harvest, Transaction, Merchandise, MerchandisePrice
from .models import PurchasedItem, UserProfile, VegetablePrice, StockedVegetable
from .models import MerchandisePhotos
admin.site.register(Vegetable)
admin.sit... | from django.contrib import admin
from django.contrib.auth.models import User
from .models import Vegetable, Harvest, Transaction, Merchandise, MerchandisePrice
from .models import PurchasedItem, UserProfile, VegetablePrice, StockedVegetable
from .models import MerchandisePhotos
admin.site.register(Vegetable)
admin.sit... | none | 1 | 1.427339 | 1 | |
tests/unit/media/test_synthesis.py | AnantTiwari-Naman/pyglet | 0 | 8163 | <gh_stars>0
from ctypes import sizeof
from io import BytesIO
import unittest
from pyglet.media.synthesis import *
local_dir = os.path.dirname(__file__)
test_data_path = os.path.abspath(os.path.join(local_dir, '..', '..', 'data'))
del local_dir
def get_test_data_file(*file_parts):
"""Get a file from the test da... | from ctypes import sizeof
from io import BytesIO
import unittest
from pyglet.media.synthesis import *
local_dir = os.path.dirname(__file__)
test_data_path = os.path.abspath(os.path.join(local_dir, '..', '..', 'data'))
del local_dir
def get_test_data_file(*file_parts):
"""Get a file from the test data directory... | en | 0.845843 | Get a file from the test data directory in an OS independent way. Supply relative file name as you would in os.path.join(). Simple test to check if synthesized sources provide data. # Should now be out of data # discard the wave header: # Compare a small chunk, to avoid hanging on mismatch: | 2.607367 | 3 |
Ejercicio/Ejercicio7.py | tavo1599/F.P2021 | 1 | 8164 | <filename>Ejercicio/Ejercicio7.py<gh_stars>1-10
#Datos de entrada
num=int(input("Ingrese un numero: "))
# Proceso
if num==10:
print("Calificacion: A")
elif num==9:
print("Calificacion: B")
elif num==8:
print("Calificacion: C")
elif num==7 and num==6:
print("Calificacion: D")
elif num<=5 and num>=0:
print("Califica... | <filename>Ejercicio/Ejercicio7.py<gh_stars>1-10
#Datos de entrada
num=int(input("Ingrese un numero: "))
# Proceso
if num==10:
print("Calificacion: A")
elif num==9:
print("Calificacion: B")
elif num==8:
print("Calificacion: C")
elif num==7 and num==6:
print("Calificacion: D")
elif num<=5 and num>=0:
print("Califica... | es | 0.936896 | #Datos de entrada # Proceso | 3.555574 | 4 |
2015/day-2/part2.py | nairraghav/advent-of-code-2019 | 0 | 8165 | <gh_stars>0
ribbon_needed = 0
with open("input.txt", "r") as puzzle_input:
for line in puzzle_input:
length, width, height = [int(item) for item in line.split("x")]
dimensions = [length, width, height]
smallest_side = min(dimensions)
dimensions.remove(smallest_side)
second_smallest_side = min(dimensions)
... | ribbon_needed = 0
with open("input.txt", "r") as puzzle_input:
for line in puzzle_input:
length, width, height = [int(item) for item in line.split("x")]
dimensions = [length, width, height]
smallest_side = min(dimensions)
dimensions.remove(smallest_side)
second_smallest_side = min(dimensions)
ribbon_n... | none | 1 | 3.689836 | 4 | |
Algorithm.Python/Alphas/GreenblattMagicFormulaAlgorithm.py | aaronwJordan/Lean | 0 | 8166 | <filename>Algorithm.Python/Alphas/GreenblattMagicFormulaAlgorithm.py<gh_stars>0
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this ... | <filename>Algorithm.Python/Alphas/GreenblattMagicFormulaAlgorithm.py<gh_stars>0
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this ... | en | 0.875752 | # QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. # Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect 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 Licen... | 2.172408 | 2 |
hw2/deeplearning/style_transfer.py | axelbr/berkeley-cs182-deep-neural-networks | 0 | 8167 | <gh_stars>0
import numpy as np
import torch
import torch.nn.functional as F
def content_loss(content_weight, content_current, content_target):
"""
Compute the content loss for style transfer.
Inputs:
- content_weight: Scalar giving the weighting for the content loss.
- content_current: features ... | import numpy as np
import torch
import torch.nn.functional as F
def content_loss(content_weight, content_current, content_target):
"""
Compute the content loss for style transfer.
Inputs:
- content_weight: Scalar giving the weighting for the content loss.
- content_current: features of the curre... | de | 0.349936 | Compute the content loss for style transfer. Inputs: - content_weight: Scalar giving the weighting for the content loss. - content_current: features of the current image; this is a PyTorch Tensor of shape (1, C_l, H_l, W_l). - content_target: features of the content image, Tensor with shape (1, C... | 3.090132 | 3 |
submissions/available/Johnson-CausalTesting/Holmes/fuzzers/Peach/Transformers/Encode/HTMLDecode.py | brittjay0104/rose6icse | 0 | 8168 | # 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 xml.sax.saxutils
from Peach.transformer import Transformer
class HtmlDecode(Transformer):
"""Decode HTML en... | # 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 xml.sax.saxutils
from Peach.transformer import Transformer
class HtmlDecode(Transformer):
"""Decode HTML en... | en | 0.897677 | # 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/. Decode HTML encoded string. | 1.929572 | 2 |
src/archive/greatcircle.py | AuraUAS/aura-core | 8 | 8169 | <gh_stars>1-10
# From: http://williams.best.vwh.net/avform.htm#GCF
import math
EPS = 0.0001
d2r = math.pi / 180.0
r2d = 180.0 / math.pi
rad2nm = (180.0 * 60.0) / math.pi
nm2rad = 1.0 / rad2nm
nm2meter = 1852
meter2nm = 1.0 / nm2meter
# p1 = (lat1(deg), lon1(deg))
# p2 = (lat2(deg), lon2(deg))
def course_and_dist(p1,... | # From: http://williams.best.vwh.net/avform.htm#GCF
import math
EPS = 0.0001
d2r = math.pi / 180.0
r2d = 180.0 / math.pi
rad2nm = (180.0 * 60.0) / math.pi
nm2rad = 1.0 / rad2nm
nm2meter = 1852
meter2nm = 1.0 / nm2meter
# p1 = (lat1(deg), lon1(deg))
# p2 = (lat2(deg), lon2(deg))
def course_and_dist(p1, p2):
# thi... | en | 0.689753 | # From: http://williams.best.vwh.net/avform.htm#GCF # p1 = (lat1(deg), lon1(deg)) # p2 = (lat2(deg), lon2(deg)) # this formulations uses postive lon = W (opposite of usual, so we # invert the longitude.) # if starting point is on a pole # EPS a small number ~ machine precision # starting from N pole # starting from S p... | 2.730258 | 3 |
app/__init__.py | JoeCare/flask_geolocation_api | 0 | 8170 | <filename>app/__init__.py
import connexion, os
from connexion.resolver import RestyResolver
from flask import json
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
# Globally accessible libraries
db = SQLAlchemy()
mm = Marshmallow()
def init_app():
"""Initialize the Connexion ap... | <filename>app/__init__.py
import connexion, os
from connexion.resolver import RestyResolver
from flask import json
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
# Globally accessible libraries
db = SQLAlchemy()
mm = Marshmallow()
def init_app():
"""Initialize the Connexion ap... | en | 0.660795 | # Globally accessible libraries Initialize the Connexion application. # Flask app and getting into app_context # Load application config # Initialize Plugins # Include our Routes/views # Register Blueprints # app.register_blueprint(auth.auth_bp) # app.register_blueprint(admin.admin_bp) | 2.208681 | 2 |
RIPv2-Simulation/Router.py | vkmanojk/Networks-VirtualLAN | 0 | 8171 | '''
Summary: Program that implements a routing deamon based on the
RIP version 2 protocol from RFC2453.
Usage: python3 Router.py <router_config_file>
Configuration File:
The user supplies a router configuration file of the format:
[Setting... | '''
Summary: Program that implements a routing deamon based on the
RIP version 2 protocol from RFC2453.
Usage: python3 Router.py <router_config_file>
Configuration File:
The user supplies a router configuration file of the format:
[Setting... | en | 0.828527 | Summary: Program that implements a routing deamon based on the
RIP version 2 protocol from RFC2453.
Usage: python3 Router.py <router_config_file>
Configuration File:
The user supplies a router configuration file of the format:
[Settings]
... | 2.951302 | 3 |
atlaselectrophysiology/extract_files.py | alowet/iblapps | 0 | 8172 | <filename>atlaselectrophysiology/extract_files.py
from ibllib.io import spikeglx
import numpy as np
import ibllib.dsp as dsp
from scipy import signal
from ibllib.misc import print_progress
from pathlib import Path
import alf.io as aio
import logging
import ibllib.ephys.ephysqc as ephysqc
from phylib.io import ... | <filename>atlaselectrophysiology/extract_files.py
from ibllib.io import spikeglx
import numpy as np
import ibllib.dsp as dsp
from scipy import signal
from ibllib.misc import print_progress
from pathlib import Path
import alf.io as aio
import logging
import ibllib.ephys.ephysqc as ephysqc
from phylib.io import ... | en | 0.670358 | Computes RMS map in time domain and spectra for each channel of Neuropixel probe
:param fbin: binary file in spike glx format (will look for attached metatdata)
:type fbin: str or pathlib.Path
:param spectra: whether to compute the power spectrum (only need for lfp data)
:type: bool
:return: ... | 2.353299 | 2 |
site_settings/models.py | shervinbdndev/Django-Shop | 13 | 8173 | from django.db import models
class SiteSettings(models.Model):
site_name = models.CharField(max_length=200 , verbose_name='Site Name')
site_url = models.CharField(max_length=200 , verbose_name='Site URL')
site_address = models.CharField(max_length=300 , verbose_name='Site Address')
site_phone = mode... | from django.db import models
class SiteSettings(models.Model):
site_name = models.CharField(max_length=200 , verbose_name='Site Name')
site_url = models.CharField(max_length=200 , verbose_name='Site URL')
site_address = models.CharField(max_length=300 , verbose_name='Site Address')
site_phone = mode... | none | 1 | 2.016893 | 2 | |
examples/basics/visuals/line_prototype.py | 3DAlgoLab/vispy | 2,617 | 8174 | # -*- coding: utf-8 -*-
# vispy: gallery 10
# Copyright (c) Vispy Development Team. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
import sys
import numpy as np
from vispy import app, gloo, visuals
from vispy.visuals.filters import Clipper, ColorFilter
from vispy.visual... | # -*- coding: utf-8 -*-
# vispy: gallery 10
# Copyright (c) Vispy Development Team. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
import sys
import numpy as np
from vispy import app, gloo, visuals
from vispy.visuals.filters import Clipper, ColorFilter
from vispy.visual... | en | 0.831172 | # -*- coding: utf-8 -*- # vispy: gallery 10 # Copyright (c) Vispy Development Team. All Rights Reserved. # Distributed under the (new) BSD License. See LICENSE.txt for more info. Example of a very simple GL-line visual. This shows the minimal set of methods that need to be reimplemented to make a new visual c... | 2.312623 | 2 |
h1st/tests/core/test_schemas_inferrer.py | Mou-Ikkai/h1st | 2 | 8175 | from unittest import TestCase
from datetime import datetime
import pyarrow as pa
import numpy as np
import pandas as pd
from h1st.schema import SchemaInferrer
class SchemaInferrerTestCase(TestCase):
def test_infer_python(self):
inferrer = SchemaInferrer()
self.assertEqual(inferrer.infer_schema(1)... | from unittest import TestCase
from datetime import datetime
import pyarrow as pa
import numpy as np
import pandas as pd
from h1st.schema import SchemaInferrer
class SchemaInferrerTestCase(TestCase):
def test_infer_python(self):
inferrer = SchemaInferrer()
self.assertEqual(inferrer.infer_schema(1)... | none | 1 | 2.654358 | 3 | |
c_core_librairies/exercise_a.py | nicolasessisbreton/pyzehe | 1 | 8176 | """
# refactoring
Refactoring is the key to successfull projects.
Refactor:
1) annuity_factor such that:
conversion to integer is handled,
no extra printing
2) policy_book into a class such that:
a function generates the book and the premium
stats and visualizations functions are avalaible
3) book_report su... | """
# refactoring
Refactoring is the key to successfull projects.
Refactor:
1) annuity_factor such that:
conversion to integer is handled,
no extra printing
2) policy_book into a class such that:
a function generates the book and the premium
stats and visualizations functions are avalaible
3) book_report su... | en | 0.875689 | # refactoring Refactoring is the key to successfull projects. Refactor: 1) annuity_factor such that: conversion to integer is handled, no extra printing 2) policy_book into a class such that: a function generates the book and the premium stats and visualizations functions are avalaible 3) book_report such t... | 2.19889 | 2 |
util/util.py | harshitAgr/vess2ret | 111 | 8177 | """Auxiliary methods."""
import os
import json
from errno import EEXIST
import numpy as np
import seaborn as sns
import cPickle as pickle
import matplotlib.pyplot as plt
sns.set()
DEFAULT_LOG_DIR = 'log'
ATOB_WEIGHTS_FILE = 'atob_weights.h5'
D_WEIGHTS_FILE = 'd_weights.h5'
class MyDict(dict):
"""
Dictionar... | """Auxiliary methods."""
import os
import json
from errno import EEXIST
import numpy as np
import seaborn as sns
import cPickle as pickle
import matplotlib.pyplot as plt
sns.set()
DEFAULT_LOG_DIR = 'log'
ATOB_WEIGHTS_FILE = 'atob_weights.h5'
D_WEIGHTS_FILE = 'd_weights.h5'
class MyDict(dict):
"""
Dictionar... | en | 0.683507 | Auxiliary methods. Dictionary that allows to access elements with dot notation. ex: >> d = MyDict({'key': 'val'}) >> d.key 'val' >> d.key2 = 'val2' >> d {'key2': 'val2', 'key': 'val'} Given an image, make sure it has 3 channels and that it is between 0 and 1. Image m... | 2.693789 | 3 |
services/apiRequests.py | CakeCrusher/voon-video_processing | 0 | 8178 | from github import Github
def parseGithubURL(url):
splitURL = url.split('/')
owner = splitURL[3]
repo = splitURL[4]
return {
"owner": owner,
"repo": repo
}
def fetchRepoFiles(owner, repo):
files = []
g = Github('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')
repo = g.get_rep... | from github import Github
def parseGithubURL(url):
splitURL = url.split('/')
owner = splitURL[3]
repo = splitURL[4]
return {
"owner": owner,
"repo": repo
}
def fetchRepoFiles(owner, repo):
files = []
g = Github('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')
repo = g.get_rep... | en | 0.315714 | # parsedUrl = parseGithubURL('https://github.com/CakeCrusher/restock_emailer') # filePaths = fetchRepoFiles(parsedUrl['owner'], parsedUrl['repo']) # files = [path.split('/')[-1] for path in filePaths] # print(files) | 2.843209 | 3 |
utils/tricks.py | HouchangX-AI/Dialog-Solution | 3 | 8179 | <gh_stars>1-10
#-*- coding: utf-8 -*-
import codecs
import random
from utils.global_names import GlobalNames, get_file_path
def modify_tokens(tokens):
new_tokens = []
pos = 0
len_ = len(tokens)
while pos < len_:
if tokens[pos] == "[":
if pos+2 < len_ and tokens[pos+2] == "]":
... | #-*- coding: utf-8 -*-
import codecs
import random
from utils.global_names import GlobalNames, get_file_path
def modify_tokens(tokens):
new_tokens = []
pos = 0
len_ = len(tokens)
while pos < len_:
if tokens[pos] == "[":
if pos+2 < len_ and tokens[pos+2] == "]":
to... | en | 0.636498 | #-*- coding: utf-8 -*- | 2.727939 | 3 |
test/functional/test_device.py | Jagadambass/Graph-Neural-Networks | 0 | 8180 | <gh_stars>0
from graphgallery.functional import device
import tensorflow as tf
import torch
def test_device():
# how about other backend?
# tf
assert isinstance(device("cpu", "tf"), str)
assert device() == 'cpu'
assert device("cpu", "tf") == 'CPU'
assert device("cpu", "tf") == 'cpu'
asser... | from graphgallery.functional import device
import tensorflow as tf
import torch
def test_device():
# how about other backend?
# tf
assert isinstance(device("cpu", "tf"), str)
assert device() == 'cpu'
assert device("cpu", "tf") == 'CPU'
assert device("cpu", "tf") == 'cpu'
assert device("de... | en | 0.708209 | # how about other backend? # tf # ?? torch | 2.669219 | 3 |
py_hanabi/card.py | krinj/hanabi-simulator | 1 | 8181 | <gh_stars>1-10
# -*- coding: utf-8 -*-
"""
A card (duh).
"""
import random
import uuid
from enum import Enum
from typing import List
from py_hanabi.settings import CARD_DECK_DISTRIBUTION
__author__ = "<NAME>"
__email__ = "<EMAIL>"
class Color(Enum):
RED = 1
BLUE = 2
GREEN = 3
YELLOW = 4
WHITE =... | # -*- coding: utf-8 -*-
"""
A card (duh).
"""
import random
import uuid
from enum import Enum
from typing import List
from py_hanabi.settings import CARD_DECK_DISTRIBUTION
__author__ = "<NAME>"
__email__ = "<EMAIL>"
class Color(Enum):
RED = 1
BLUE = 2
GREEN = 3
YELLOW = 4
WHITE = 5
class Card... | en | 0.89508 | # -*- coding: utf-8 -*- A card (duh). # self._index_hinted: List[int] = [] # self._lone_hinted: List[bool] = [] # According to hints, these are the ones we know it is NOT. Generate the starting deck for the game. | 3.185484 | 3 |
facetools/test/testcases.py | bigsassy/django-facetools | 2 | 8182 | import types
import django.test.testcases
from django.conf import settings
from facetools.models import TestUser
from facetools.common import _create_signed_request
from facetools.test import TestUserNotLoaded
from facetools.signals import sync_facebook_test_user, setup_facebook_test_client
from facetools.common impor... | import types
import django.test.testcases
from django.conf import settings
from facetools.models import TestUser
from facetools.common import _create_signed_request
from facetools.test import TestUserNotLoaded
from facetools.signals import sync_facebook_test_user, setup_facebook_test_client
from facetools.common impor... | en | 0.746631 | TestCase which makes it possible to test views when the FacebookMiddleware and SyncFacebookUser middlewares are activated. Must use the Client attached to this object (i.e. self.client). Allow code to configure the test client so it has a signed request of the specified test user for each request # Mak... | 2.056466 | 2 |
setup.py | d2gex/distpickymodel | 0 | 8183 | import setuptools
import distpickymodel
def get_long_desc():
with open("README.rst", "r") as fh:
return fh.read()
setuptools.setup(
name="distpickymodel",
version=distpickymodel.__version__,
author="<NAME>",
author_email="<EMAIL>",
description="A shared Mongoengine-based model librar... | import setuptools
import distpickymodel
def get_long_desc():
with open("README.rst", "r") as fh:
return fh.read()
setuptools.setup(
name="distpickymodel",
version=distpickymodel.__version__,
author="<NAME>",
author_email="<EMAIL>",
description="A shared Mongoengine-based model librar... | en | 0.872563 | # Exclude 'tests' and 'docs' | 1.777753 | 2 |
credentials_test.py | tinatasha/passwordgenerator | 0 | 8184 | <reponame>tinatasha/passwordgenerator
import unittest
from password import Credentials
class TestCredentials(unittest.TestCase):
"""
Class to test behaviour of the credentials class
"""
def setUp(self):
"""
Setup method that defines instructions
"""
self.new_credentials ... | import unittest
from password import Credentials
class TestCredentials(unittest.TestCase):
"""
Class to test behaviour of the credentials class
"""
def setUp(self):
"""
Setup method that defines instructions
"""
self.new_credentials = Credentials("Github","Tina","blackfa... | en | 0.862567 | Class to test behaviour of the credentials class Setup method that defines instructions Method that cleans up after each test Test for correct initialization Test to check whether app saves account credentials Test for saving multiple credentials Test to view an account credential Test to delete account credentials | 3.734887 | 4 |
homework_08/calc_fitness.py | ufpa-organization-repositories/evolutionary-computing | 0 | 8185 | <gh_stars>0
def calc_fitness(pop):
from to_decimal import to_decimal
from math import sin, sqrt
for index, elem in enumerate(pop):
# só atribui a fitness a cromossomos que ainda não possuem fitness
# print(elem[0], elem[1])
x = to_decimal(elem[0])
y = to_decimal(elem[1])
... | def calc_fitness(pop):
from to_decimal import to_decimal
from math import sin, sqrt
for index, elem in enumerate(pop):
# só atribui a fitness a cromossomos que ainda não possuem fitness
# print(elem[0], elem[1])
x = to_decimal(elem[0])
y = to_decimal(elem[1])
# x = ... | pt | 0.74066 | # só atribui a fitness a cromossomos que ainda não possuem fitness # print(elem[0], elem[1]) # x = elem[0] # y = elem[1] # populacao = [[0,0],[-3,1]] # calc_fitness(pop=populacao) # print(populacao) | 3.519131 | 4 |
pichetprofile/__init__.py | jamenor/pichetprofile | 2 | 8186 | <gh_stars>1-10
# -*- coding: utf-8 -*-
from oopschool.school import Student,Tesla,SpecialStudent,Teacher
from oopschool.newschool import Test | # -*- coding: utf-8 -*-
from oopschool.school import Student,Tesla,SpecialStudent,Teacher
from oopschool.newschool import Test | en | 0.769321 | # -*- coding: utf-8 -*- | 1.004334 | 1 |
leetcode/group2/461.py | HPluseven/playground | 1 | 8187 | <filename>leetcode/group2/461.py
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
xor = x ^ y
distance = 0
while xor:
if xor & 1:
distance += 1
xor = xor >> 1
return distance
class Solution:
def hammingDistance(self, x: i... | <filename>leetcode/group2/461.py
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
xor = x ^ y
distance = 0
while xor:
if xor & 1:
distance += 1
xor = xor >> 1
return distance
class Solution:
def hammingDistance(self, x: i... | none | 1 | 3.887426 | 4 | |
rdl/data_sources/DataSourceFactory.py | pageuppeople-opensource/relational-data-loader | 2 | 8188 | <reponame>pageuppeople-opensource/relational-data-loader
import logging
from rdl.data_sources.MsSqlDataSource import MsSqlDataSource
from rdl.data_sources.AWSLambdaDataSource import AWSLambdaDataSource
class DataSourceFactory(object):
def __init__(self, logger=None):
self.logger = logger or logging.getLog... | import logging
from rdl.data_sources.MsSqlDataSource import MsSqlDataSource
from rdl.data_sources.AWSLambdaDataSource import AWSLambdaDataSource
class DataSourceFactory(object):
def __init__(self, logger=None):
self.logger = logger or logging.getLogger(__name__)
self.sources = [MsSqlDataSource, AW... | none | 1 | 2.325039 | 2 | |
ch05/ch05-02-timeseries.py | alexmalins/kagglebook | 13 | 8189 | # ---------------------------------
# Prepare the data etc.
# ----------------------------------
import numpy as np
import pandas as pd
# train_x is the training data, train_y is the target values, and test_x is the test data
# stored in pandas DataFrames and Series (numpy arrays also used)
train = pd.read_csv('../in... | # ---------------------------------
# Prepare the data etc.
# ----------------------------------
import numpy as np
import pandas as pd
# train_x is the training data, train_y is the target values, and test_x is the test data
# stored in pandas DataFrames and Series (numpy arrays also used)
train = pd.read_csv('../in... | en | 0.815375 | # --------------------------------- # Prepare the data etc. # ---------------------------------- # train_x is the training data, train_y is the target values, and test_x is the test data # stored in pandas DataFrames and Series (numpy arrays also used) # As time-series data assume a period variable is set that changes ... | 3.229084 | 3 |
server/WitClient.py | owo/jitalk | 1 | 8190 | <reponame>owo/jitalk
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import wit
import json
class WitClient(object):
"""docstring for WitClient"""
_access_token = '<KEY>'
def __init__(self):
wit.init()
def text_query(self, text):
res = json.loads(wit.text_query(text, WitClient._access_token))
return res["o... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import wit
import json
class WitClient(object):
"""docstring for WitClient"""
_access_token = '<KEY>'
def __init__(self):
wit.init()
def text_query(self, text):
res = json.loads(wit.text_query(text, WitClient._access_token))
return res["outcomes"]
def clo... | en | 0.48183 | #!/usr/bin/env python # -*- coding: utf-8 -*- docstring for WitClient | 2.708996 | 3 |
HackerRank/Python/Easy/E0036.py | Mohammed-Shoaib/HackerRank-Problems | 54 | 8191 | <filename>HackerRank/Python/Easy/E0036.py
# Problem Statement: https://www.hackerrank.com/challenges/itertools-combinations-with-replacement/problem
from itertools import combinations_with_replacement
S, k = input().split()
for comb in combinations_with_replacement(sorted(S), int(k)):
print(''.join(comb)) | <filename>HackerRank/Python/Easy/E0036.py
# Problem Statement: https://www.hackerrank.com/challenges/itertools-combinations-with-replacement/problem
from itertools import combinations_with_replacement
S, k = input().split()
for comb in combinations_with_replacement(sorted(S), int(k)):
print(''.join(comb)) | en | 0.7307 | # Problem Statement: https://www.hackerrank.com/challenges/itertools-combinations-with-replacement/problem | 3.496933 | 3 |
visual_genome/models.py | hayyubi/visual-genome-driver | 0 | 8192 | <reponame>hayyubi/visual-genome-driver
"""
Visual Genome Python API wrapper, models
"""
class Image:
"""
Image.
ID int
url hyperlink string
width int
height int
"""
def __init__(self, id, url, width, height, coco_id, flickr_id):
self.id = id
... | """
Visual Genome Python API wrapper, models
"""
class Image:
"""
Image.
ID int
url hyperlink string
width int
height int
"""
def __init__(self, id, url, width, height, coco_id, flickr_id):
self.id = id
self.url = url
self.width ... | en | 0.482386 | Visual Genome Python API wrapper, models Image. ID int url hyperlink string width int height int Region. image int phrase string x int y int width int height int Graphs c... | 2.742899 | 3 |
python-scripts/plot_delay.py | GayashanNA/my-scripts | 0 | 8193 | <filename>python-scripts/plot_delay.py<gh_stars>0
import csv
import matplotlib.pyplot as plt
import time
PLOT_PER_WINDOW = False
WINDOW_LENGTH = 60000
BINS = 1000
delay_store = {}
perwindow_delay_store = {}
plotting_delay_store = {}
filename = "output-large.csv"
# filename = "output.csv"
# filename = "output-medium.c... | <filename>python-scripts/plot_delay.py<gh_stars>0
import csv
import matplotlib.pyplot as plt
import time
PLOT_PER_WINDOW = False
WINDOW_LENGTH = 60000
BINS = 1000
delay_store = {}
perwindow_delay_store = {}
plotting_delay_store = {}
filename = "output-large.csv"
# filename = "output.csv"
# filename = "output-medium.c... | en | 0.675943 | # filename = "output.csv" # filename = "output-medium.csv" # filename = "output-small.csv" # filename = "output-tiny.csv" # find the time delays that are within the window of choice # the histogram of the data # plt.axhline(y=0.95, color='red', label='0.95') # format epoch time to date time to be shown in the plot figu... | 2.952642 | 3 |
python_scripts/BUSCO_phylogenetics/rename_all_fa_seq.py | peterthorpe5/Methods_M.cerasi_R.padi_genome_assembly | 4 | 8194 | <filename>python_scripts/BUSCO_phylogenetics/rename_all_fa_seq.py
#!/usr/bin/env python
# author: <NAME> September 2015. The James Hutton Insitute, Dundee, UK.
# title rename single copy busco genes
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio import SeqIO
import os
from sys import stdin,argv
i... | <filename>python_scripts/BUSCO_phylogenetics/rename_all_fa_seq.py
#!/usr/bin/env python
# author: <NAME> September 2015. The James Hutton Insitute, Dundee, UK.
# title rename single copy busco genes
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio import SeqIO
import os
from sys import stdin,argv
i... | en | 0.668722 | #!/usr/bin/env python # author: <NAME> September 2015. The James Hutton Insitute, Dundee, UK. # title rename single copy busco genes ######################################################################## # functions this is a function to open busco full ouput and get a list of duplicated genes. This list is requi... | 3.236518 | 3 |
video/rest/compositionhooks/delete-hook/delete-hook.6.x.py | afeld/api-snippets | 3 | 8195 | # Download the Python helper library from twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
api_key_sid = 'SKXXXX'
api_key_secret = 'your_api_key_secret'
client = Client(api_key_sid, api_key_secret)
did_delete = client.video\
.c... | # Download the Python helper library from twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
api_key_sid = 'SKXXXX'
api_key_secret = 'your_api_key_secret'
client = Client(api_key_sid, api_key_secret)
did_delete = client.video\
.c... | en | 0.74306 | # Download the Python helper library from twilio.com/docs/python/install # Your Account Sid and Auth Token from twilio.com/console | 2.212094 | 2 |
global_info.py | AkagiYui/AzurLaneTool | 0 | 8196 | from time import sleep
debug_mode = False
time_to_exit = False
exiting = False
exit_code = 0
def get_debug_mode():
return debug_mode
def trigger_exit(_exit_code):
global time_to_exit, exit_code
exit_code = _exit_code
time_to_exit = True
sleep(0.1)
| from time import sleep
debug_mode = False
time_to_exit = False
exiting = False
exit_code = 0
def get_debug_mode():
return debug_mode
def trigger_exit(_exit_code):
global time_to_exit, exit_code
exit_code = _exit_code
time_to_exit = True
sleep(0.1)
| none | 1 | 2.201809 | 2 | |
advesarial_text/data/data_utils_test.py | slowy07/tensorflow-model-research | 0 | 8197 | from __future__ import absoulte_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from data import data_utils
data = data_utils
class SequenceWrapperTest(tf.test.TestCase):
def testDefaultTimesteps(self):
seq = data.SequenceWrapper()
t1 = seq.... | from __future__ import absoulte_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from data import data_utils
data = data_utils
class SequenceWrapperTest(tf.test.TestCase):
def testDefaultTimesteps(self):
seq = data.SequenceWrapper()
t1 = seq.... | en | 0.821909 | # For end of sequence, the token and label should be same, and weight # should be 0.0. # Tokens should be sequence twice, minus the EOS token at the end # Weights should be len-1 0.0's and len 1.0's. # Labels should be len-1 0's, and then the sequence | 2.313809 | 2 |
headlesspreview/apps.py | arush15june/wagtail-torchbox | 0 | 8198 | from django.apps import AppConfig
class HeadlesspreviewConfig(AppConfig):
name = 'headlesspreview'
| from django.apps import AppConfig
class HeadlesspreviewConfig(AppConfig):
name = 'headlesspreview'
| none | 1 | 1.118269 | 1 | |
LipSDP/solve_sdp.py | revbucket/LipSDP | 1 | 8199 | <reponame>revbucket/LipSDP
import argparse
import numpy as np
import matlab.engine
from scipy.io import savemat
import os
from time import time
def main(args):
start_time = time()
eng = matlab.engine.start_matlab()
eng.addpath(os.path.join(file_dir, 'matlab_engine'))
eng.addpath(os.path.join(file_dir,... | import argparse
import numpy as np
import matlab.engine
from scipy.io import savemat
import os
from time import time
def main(args):
start_time = time()
eng = matlab.engine.start_matlab()
eng.addpath(os.path.join(file_dir, 'matlab_engine'))
eng.addpath(os.path.join(file_dir, r'matlab_engine/weight_uti... | none | 1 | 2.161298 | 2 |