code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
from ....pgrest import *
from ...constants import Constants
from ..rcconstants import REDCapConstants
from ..rcaptable import RcapTable
__all__ = ["RcapDailyItems6MoV036MonthDaily"]
class RcapDailyItems6MoV036MonthDaily(RcapTable):
"""Daily Items 6 Mo V03 6Month Daily"""
__redcap_form_name = "daily_items_6... | src/vbr/tableclasses/redcap/autogenerated/daily_items_6_mo_v03_6month_daily.py | from ....pgrest import *
from ...constants import Constants
from ..rcconstants import REDCapConstants
from ..rcaptable import RcapTable
__all__ = ["RcapDailyItems6MoV036MonthDaily"]
class RcapDailyItems6MoV036MonthDaily(RcapTable):
"""Daily Items 6 Mo V03 6Month Daily"""
__redcap_form_name = "daily_items_6... | 0.510496 | 0.370453 |
import logging
from json import JSONDecodeError
from celery import shared_task
from django.core.cache import cache
from nacl.exceptions import BadSignatureError
from thenewboston.blocks.signatures import verify_signature
from thenewboston.utils.format import format_address
from thenewboston.utils.messages import get_m... | v1/tasks/sync.py | import logging
from json import JSONDecodeError
from celery import shared_task
from django.core.cache import cache
from nacl.exceptions import BadSignatureError
from thenewboston.blocks.signatures import verify_signature
from thenewboston.utils.format import format_address
from thenewboston.utils.messages import get_m... | 0.528777 | 0.173113 |
from django.shortcuts import render
from rest_framework import generics
from authentication import models
from .serializers import UsuarioSerializer, UsuarioSigninSerializer
from . import serializers
from .authlog import token_expire_handler, expires_in
from django.contrib.auth import authenticate
from rest_framewor... | firstdjango/api/views.py | from django.shortcuts import render
from rest_framework import generics
from authentication import models
from .serializers import UsuarioSerializer, UsuarioSigninSerializer
from . import serializers
from .authlog import token_expire_handler, expires_in
from django.contrib.auth import authenticate
from rest_framewor... | 0.416678 | 0.067886 |
import logging
import time
import threading
import kombu
import socket
from umbra.browser import BrowserPool, BrowsingException
class AmqpBrowserController:
"""
Consumes amqp messages representing requests to browse urls, from the
specified amqp queue (default: "urls") on the specified amqp exchange
(... | umbra/controller.py |
import logging
import time
import threading
import kombu
import socket
from umbra.browser import BrowserPool, BrowsingException
class AmqpBrowserController:
"""
Consumes amqp messages representing requests to browse urls, from the
specified amqp queue (default: "urls") on the specified amqp exchange
(... | 0.597138 | 0.091788 |
import asyncio
import itertools
import functools
import math
import re
from attr import __description__
import discord
import os
from discord.ext import tasks, commands
from discord.ext.commands.errors import MissingPermissions
from discord.user import Profile
from discord.utils import get
from dns.message ... | cogs/utilities.py | import asyncio
import itertools
import functools
import math
import re
from attr import __description__
import discord
import os
from discord.ext import tasks, commands
from discord.ext.commands.errors import MissingPermissions
from discord.user import Profile
from discord.utils import get
from dns.message ... | 0.283385 | 0.127979 |
# 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
# distribut... | LR/lr/controllers/services.py |
# 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
# distribut... | 0.514644 | 0.136292 |
from Queue import Empty, Queue
from boto.exception import S3ResponseError
from boto.pyami.config import Config
from boto.s3.connection import S3Connection
from boto.s3.key import Key
from boto import utils
from filechunkio import FileChunkIO
from logging import handlers
from multiprocessing import Pool
from threading i... | s3ingest.py | from Queue import Empty, Queue
from boto.exception import S3ResponseError
from boto.pyami.config import Config
from boto.s3.connection import S3Connection
from boto.s3.key import Key
from boto import utils
from filechunkio import FileChunkIO
from logging import handlers
from multiprocessing import Pool
from threading i... | 0.334372 | 0.086093 |
import copy
# a potential has a set of variables and a CPT
variable_c = ('c', 2)
variable_s = ('s', 2)
variable_r = ('r', 2)
variable_w = ('w', 2)
pc_vars = (variable_c,)
pc_cpt = {
(0,) : 0.5,
(1,) : 0.5
}
pot_c = (pc_vars, pc_cpt)
pr_vars = (variable_c, variable_r)
pr_cpt = {
... | my_engine/notebooks/potential.py | import copy
# a potential has a set of variables and a CPT
variable_c = ('c', 2)
variable_s = ('s', 2)
variable_r = ('r', 2)
variable_w = ('w', 2)
pc_vars = (variable_c,)
pc_cpt = {
(0,) : 0.5,
(1,) : 0.5
}
pot_c = (pc_vars, pc_cpt)
pr_vars = (variable_c, variable_r)
pr_cpt = {
... | 0.231354 | 0.397997 |
import logging
import warnings
INFO = 25
DETAILED_INFO = 20
try:
import mpi4py
MPISIZE = mpi4py.MPI.COMM_WORLD.Get_size()
MPIRANK = mpi4py.MPI.COMM_WORLD.Get_rank()
USING_MPI = MPISIZE > 1
except (ImportError, AttributeError):
USING_MPI = False
def configure_logging(verbosity="standard", module=... | bingo/util/log.py | import logging
import warnings
INFO = 25
DETAILED_INFO = 20
try:
import mpi4py
MPISIZE = mpi4py.MPI.COMM_WORLD.Get_size()
MPIRANK = mpi4py.MPI.COMM_WORLD.Get_rank()
USING_MPI = MPISIZE > 1
except (ImportError, AttributeError):
USING_MPI = False
def configure_logging(verbosity="standard", module=... | 0.627951 | 0.127462 |
from py_tests_common import *
def TypeofOperatorDeclaration_Test0():
c_program_text= """
type T= typeof(0);
"""
tests_lib.build_program( c_program_text )
def TypeofOperatorDeclaration_Test1():
c_program_text= """
type T= typeof( 55 * 88 );
"""
tests_lib.build_program( c_program_text )
def TypeofOperatorD... | source/tests/py_tests/typeof_test.py | from py_tests_common import *
def TypeofOperatorDeclaration_Test0():
c_program_text= """
type T= typeof(0);
"""
tests_lib.build_program( c_program_text )
def TypeofOperatorDeclaration_Test1():
c_program_text= """
type T= typeof( 55 * 88 );
"""
tests_lib.build_program( c_program_text )
def TypeofOperatorD... | 0.47244 | 0.206594 |
import nose.tools
import dcase_util
from dcase_util.containers import ListDictContainer
from nose.tools import *
import tempfile
import os
def test_container():
data = ListDictContainer([
{
'key1': 100,
'key2': 400,
},
{
'key1': 200,
'key2':... | tests/containers/test_ListDictContainer.py |
import nose.tools
import dcase_util
from dcase_util.containers import ListDictContainer
from nose.tools import *
import tempfile
import os
def test_container():
data = ListDictContainer([
{
'key1': 100,
'key2': 400,
},
{
'key1': 200,
'key2':... | 0.327023 | 0.33158 |
import pandas as pd
import quandl, math, datetime
import numpy as np
from sklearn import preprocessing, cross_validation, svm
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
from matplotlib import style
style.use('ggplot') # specifying the type of plotting chart to use
df... | app.py | import pandas as pd
import quandl, math, datetime
import numpy as np
from sklearn import preprocessing, cross_validation, svm
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
from matplotlib import style
style.use('ggplot') # specifying the type of plotting chart to use
df... | 0.636805 | 0.471102 |
import torch
import torch.nn as nn
class MultiEmbeddings(nn.Module):
def __init__(self, *variable_params):
# example: *[(name, num_embeddings, embedding_dim), ... ]
super().__init__()
self.params = variable_params
self.embeddings = nn.ModuleDict({
name: nn.Embedding(s,... | deepseries/model/seq2seq/utils.py | import torch
import torch.nn as nn
class MultiEmbeddings(nn.Module):
def __init__(self, *variable_params):
# example: *[(name, num_embeddings, embedding_dim), ... ]
super().__init__()
self.params = variable_params
self.embeddings = nn.ModuleDict({
name: nn.Embedding(s,... | 0.922474 | 0.325279 |
import sys
from os.path import exists as path_exists
from pyscaffold.api import create_project
from pyscaffold.cli import run
from pyscaffold.extensions.github_actions import GithubActions
def test_create_project_with_github_actions(tmpfolder):
# Given options with the GithubActions extension,
opts = dict(pr... | tests/extensions/test_github_actions.py | import sys
from os.path import exists as path_exists
from pyscaffold.api import create_project
from pyscaffold.cli import run
from pyscaffold.extensions.github_actions import GithubActions
def test_create_project_with_github_actions(tmpfolder):
# Given options with the GithubActions extension,
opts = dict(pr... | 0.236693 | 0.285447 |
from exo3 import lireCSV # fonction de lecture et de construction
# de la liste de dictionnaires
# fonctions d'affichage
from exo4 import printTableformatee, printTableformateeDeco
########################################################################
def printTitre( texte ) :
l = len(texte)
pri... | programmeNSI/cours/exo/exo5.py | from exo3 import lireCSV # fonction de lecture et de construction
# de la liste de dictionnaires
# fonctions d'affichage
from exo4 import printTableformatee, printTableformateeDeco
########################################################################
def printTitre( texte ) :
l = len(texte)
pri... | 0.073715 | 0.327991 |
from enum import Enum
class NamedEntityScoreEnum(Enum):
"""Enum for the score of a named entity"""
# The score is based on the number of models that detect the entity.
# The used models are AWS Comprehend, NLTK and Spacy
# The score is high if all models detected the entity
HIGH = "HIGH"
# The ... | entities/named_entity.py | from enum import Enum
class NamedEntityScoreEnum(Enum):
"""Enum for the score of a named entity"""
# The score is based on the number of models that detect the entity.
# The used models are AWS Comprehend, NLTK and Spacy
# The score is high if all models detected the entity
HIGH = "HIGH"
# The ... | 0.723798 | 0.45744 |
import csv
def calc_edit_dist(word1, word2):
'''
First, create a 2D array to enable dynamic programming.
Then, use dynamic programming to alculate
edit distance between two words.
'''
#this method needs fixing
comparison_matrix = create_comparision_matrix(word1, word2)
num_rows = len(comparison_matrix... | auto_correct.py | import csv
def calc_edit_dist(word1, word2):
'''
First, create a 2D array to enable dynamic programming.
Then, use dynamic programming to alculate
edit distance between two words.
'''
#this method needs fixing
comparison_matrix = create_comparision_matrix(word1, word2)
num_rows = len(comparison_matrix... | 0.229018 | 0.587825 |
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
"""
Verify that the Chmod() Action works.
"""
import os
import os.path
import stat
import TestSCons
test = TestSCons.TestSCons()
# Note: Windows basically has two modes that it can os.chmod() files to
# 0444 and 0666, and directories to 0555 and 0777,... | test/Chmod.py |
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
"""
Verify that the Chmod() Action works.
"""
import os
import os.path
import stat
import TestSCons
test = TestSCons.TestSCons()
# Note: Windows basically has two modes that it can os.chmod() files to
# 0444 and 0666, and directories to 0555 and 0777,... | 0.334372 | 0.200558 |
from math import *
from MITgcmutils import rdmds
from netCDF4 import Dataset
import numpy as np
import os
import pandas as pd
import pylab as pl
import scipy.io
import scipy as spy
import sys
lib_path = os.path.abspath('../../Building_canyon/BuildCanyon/PythonModulesMITgcm') # Add absolute path to my python ... | PythonScripts/CS_Sections_Areas.py | from math import *
from MITgcmutils import rdmds
from netCDF4 import Dataset
import numpy as np
import os
import pandas as pd
import pylab as pl
import scipy.io
import scipy as spy
import sys
lib_path = os.path.abspath('../../Building_canyon/BuildCanyon/PythonModulesMITgcm') # Add absolute path to my python ... | 0.18101 | 0.207235 |
import numpy as np
import scipy.sparse
import math
import multiprocessing as mp
import itertools
import sys
import os
import gc
from sklearn.neighbors import NearestNeighbors, kneighbors_graph, KDTree
from sklearn.metrics.pairwise import euclidean_distances
def chunks(lst, n):
for i in range(0, len(lst), n):
yie... | core.py | import numpy as np
import scipy.sparse
import math
import multiprocessing as mp
import itertools
import sys
import os
import gc
from sklearn.neighbors import NearestNeighbors, kneighbors_graph, KDTree
from sklearn.metrics.pairwise import euclidean_distances
def chunks(lst, n):
for i in range(0, len(lst), n):
yie... | 0.315103 | 0.350491 |
import pymysql
import os
import datetime
from prettytable import PrettyTable
con = pymysql.connect('localhost','root','','Bank5')
cur = con.cursor()
def signup() :
os.system('clear')
now = str(datetime.datetime.now())
name = input("\nEnter Your Name -: ");
address = input("\nEnter Your Address -: ")
date = input("... | bank5.py | import pymysql
import os
import datetime
from prettytable import PrettyTable
con = pymysql.connect('localhost','root','','Bank5')
cur = con.cursor()
def signup() :
os.system('clear')
now = str(datetime.datetime.now())
name = input("\nEnter Your Name -: ");
address = input("\nEnter Your Address -: ")
date = input("... | 0.038665 | 0.139778 |
from bs4 import BeautifulSoup
import requests
import pandas as pd
res=requests.get("http://books.toscrape.com/").text
soup=BeautifulSoup(res,'html.parser')
#Get the total page count
pagecount=soup.select_one('.current').text.split('of')[-1].strip()
title=[]
ratings=[]
cost=[]
for page in range(1,int(pagec... | Prueba_cadabook.py | from bs4 import BeautifulSoup
import requests
import pandas as pd
res=requests.get("http://books.toscrape.com/").text
soup=BeautifulSoup(res,'html.parser')
#Get the total page count
pagecount=soup.select_one('.current').text.split('of')[-1].strip()
title=[]
ratings=[]
cost=[]
for page in range(1,int(pagec... | 0.156008 | 0.086748 |
import os
import time
import logging
import numpy as np
import unittest
import matplotlib.pyplot as plt
from home_platform.rendering import Panda3dRenderer
from home_platform.suncg import SunCgSceneLoader, loadModel, SunCgModelLights
from panda3d.core import LMatrix4f, TransformState, LVecBase3
from home_platform.co... | tests/multimodalmaze/test_rendering.py |
import os
import time
import logging
import numpy as np
import unittest
import matplotlib.pyplot as plt
from home_platform.rendering import Panda3dRenderer
from home_platform.suncg import SunCgSceneLoader, loadModel, SunCgModelLights
from panda3d.core import LMatrix4f, TransformState, LVecBase3
from home_platform.co... | 0.430387 | 0.322739 |
import decimal
import pytest
import json
import requests
from datetime import datetime
from mock import Mock
import pyticketswitch
from pyticketswitch.client import Client, POST, GET
from pyticketswitch import exceptions
from pyticketswitch.trolley import Trolley
from pyticketswitch.reservation import Reservation
from ... | tests/test_client.py | import decimal
import pytest
import json
import requests
from datetime import datetime
from mock import Mock
import pyticketswitch
from pyticketswitch.client import Client, POST, GET
from pyticketswitch import exceptions
from pyticketswitch.trolley import Trolley
from pyticketswitch.reservation import Reservation
from ... | 0.561936 | 0.30702 |
import pytest
from app.api.services import (
save_token,
login_user,
logout_user,
get_users,
get_user,
save_new_user,
get_playlists,
get_playlist,
put_playlist,
save_new_playlist,
)
from app.api.models import BlacklistToken
from app.api.errors import BadRequest
class TestAuthS... | tests/test_services.py | import pytest
from app.api.services import (
save_token,
login_user,
logout_user,
get_users,
get_user,
save_new_user,
get_playlists,
get_playlist,
put_playlist,
save_new_playlist,
)
from app.api.models import BlacklistToken
from app.api.errors import BadRequest
class TestAuthS... | 0.469277 | 0.278714 |
import os
import bz2
import MySQLdb
import pandas as pd
import numpy as np
from collections import defaultdict
''' Connect to DB '''
db = MySQLdb.connect(host=os.environ.get("DATAVIVA_DB_HOST", "localhost"), user=os.environ[
"DATAVIVA_DB_USER"], passwd=os.environ["DATAVIVA_DB_PW"], db=os.environ["... | scripts/sc/_to_df.py | import os
import bz2
import MySQLdb
import pandas as pd
import numpy as np
from collections import defaultdict
''' Connect to DB '''
db = MySQLdb.connect(host=os.environ.get("DATAVIVA_DB_HOST", "localhost"), user=os.environ[
"DATAVIVA_DB_USER"], passwd=os.environ["DATAVIVA_DB_PW"], db=os.environ["... | 0.196363 | 0.201165 |
import cvmfs
import sys
class MerkleCatalogTreeIterator(cvmfs.CatalogTreeIterator):
def __init__(self, repository, root_catalog, visited_hashes = set()):
cvmfs.CatalogTreeIterator.__init__(self, repository, root_catalog)
self.visited_hashes = visited_hashes
def next(self):
catalog = c... | add-ons/tools/download_catalog_graph.py |
import cvmfs
import sys
class MerkleCatalogTreeIterator(cvmfs.CatalogTreeIterator):
def __init__(self, repository, root_catalog, visited_hashes = set()):
cvmfs.CatalogTreeIterator.__init__(self, repository, root_catalog)
self.visited_hashes = visited_hashes
def next(self):
catalog = c... | 0.277473 | 0.181844 |
from __future__ import annotations
import toolcli
from toolcli.command_utils import help_utils
def get_cd_help(parse_spec: toolcli.ParseSpec) -> str:
program_name = parse_spec.get('config', {}).get('base_command', 'PROGRAM')
return 'change working directory to ' + program_name + '-related location'
def get... | toolcli/command_utils/standard_subcommands/cd_command.py | from __future__ import annotations
import toolcli
from toolcli.command_utils import help_utils
def get_cd_help(parse_spec: toolcli.ParseSpec) -> str:
program_name = parse_spec.get('config', {}).get('base_command', 'PROGRAM')
return 'change working directory to ' + program_name + '-related location'
def get... | 0.414662 | 0.070816 |
import logging
from app import app
from app.models.sequence import Sequence
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.orm.exc import MultipleResultsFound
import pdb
from .logger import ProjectLogger
LEMMA = "lemma"
WORD = "word"
class SequenceProcessor(object):
"""Process given input into Sequ... | app/preprocessor/sequenceprocessor.py | import logging
from app import app
from app.models.sequence import Sequence
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.orm.exc import MultipleResultsFound
import pdb
from .logger import ProjectLogger
LEMMA = "lemma"
WORD = "word"
class SequenceProcessor(object):
"""Process given input into Sequ... | 0.617859 | 0.225513 |
from pathlib import Path
from timeit import default_timer as timer
import h5py
import numpy as np
import torch
from methods.utils.data_utilities import (_segment_index, load_dcase_format,
to_metrics2020_format)
from torch.utils.data import Dataset, Sampler
from tqdm import tqd... | seld/methods/ein_seld/data.py | from pathlib import Path
from timeit import default_timer as timer
import h5py
import numpy as np
import torch
from methods.utils.data_utilities import (_segment_index, load_dcase_format,
to_metrics2020_format)
from torch.utils.data import Dataset, Sampler
from tqdm import tqd... | 0.685844 | 0.244758 |
import os
import shutil
import socket
from omegaconf import OmegaConf
class WandbUrls: # pylint: disable=too-few-public-methods
def __init__(self, url):
url_hash = url.split("/")[-1]
project = url.split("/")[-3]
entity = url.split("/")[-4]
self.weight_url = url
self.log... | src/logger/jam_wandb.py | import os
import shutil
import socket
from omegaconf import OmegaConf
class WandbUrls: # pylint: disable=too-few-public-methods
def __init__(self, url):
url_hash = url.split("/")[-1]
project = url.split("/")[-3]
entity = url.split("/")[-4]
self.weight_url = url
self.log... | 0.350533 | 0.169097 |
import os
import time
from dbt.adapters.factory import get_adapter
from dbt.logger import GLOBAL_LOGGER as logger
from dbt.contracts.graph.parsed import ParsedNode
from dbt.contracts.graph.manifest import CompileResultNode
from dbt.contracts.results import ExecutionResult
import dbt.clients.jinja
import dbt.compilati... | dbt/runner.py | import os
import time
from dbt.adapters.factory import get_adapter
from dbt.logger import GLOBAL_LOGGER as logger
from dbt.contracts.graph.parsed import ParsedNode
from dbt.contracts.graph.manifest import CompileResultNode
from dbt.contracts.results import ExecutionResult
import dbt.clients.jinja
import dbt.compilati... | 0.411702 | 0.086825 |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Forum'
db.create_table('forums_forum', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key... | kitsune/forums/migrations/0001_initial.py | import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Forum'
db.create_table('forums_forum', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key... | 0.432063 | 0.098469 |
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request
from product_spiders.items import Product, ProductLoader
from decimal import Decimal
import logging
class CaldaiemuraliItSpider(BaseSpider):
name = "caldaiemurali.it"
allowed_domains = ["caldai... | portfolio/Python/scrapy/rosarioweb/caldaiemurali_it.py | from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request
from product_spiders.items import Product, ProductLoader
from decimal import Decimal
import logging
class CaldaiemuraliItSpider(BaseSpider):
name = "caldaiemurali.it"
allowed_domains = ["caldai... | 0.372391 | 0.079531 |
import math
from .searcher import Searcher
from pychemia import pcm_log
class ParticleSwarm(Searcher):
def __init__(self, population, params=None, generation_size=32, stabilization_limit=10):
"""
Implementation fo the Firefly algorithm for global minimization
This searcher uses a metric t... | pychemia/searcher/swarm2.py | import math
from .searcher import Searcher
from pychemia import pcm_log
class ParticleSwarm(Searcher):
def __init__(self, population, params=None, generation_size=32, stabilization_limit=10):
"""
Implementation fo the Firefly algorithm for global minimization
This searcher uses a metric t... | 0.737442 | 0.472075 |
import scipy.stats as scs
import numpy as np
from .quaternion import symplectic
def ge(n):
"""
:param n: size of random matrix
:return: random n by n matrix, drawn from the standard Gaussian ensemble
"""
return scs.norm().rvs(size=[int(n), int(n)])
def goe(n):
"""
:param n: size of rando... | rmt/ensembles.py | import scipy.stats as scs
import numpy as np
from .quaternion import symplectic
def ge(n):
"""
:param n: size of random matrix
:return: random n by n matrix, drawn from the standard Gaussian ensemble
"""
return scs.norm().rvs(size=[int(n), int(n)])
def goe(n):
"""
:param n: size of rando... | 0.765681 | 0.771198 |
from __future__ import absolute_import, division, print_function, with_statement, unicode_literals
from .middleware import *
from .uimodules import *
from .options import *
import traceback
import base64
import pprint
import linecache
class DebugBreakException(Exception):
"""Raise this to break into the debugge... | oz/error_pages/__init__.py |
from __future__ import absolute_import, division, print_function, with_statement, unicode_literals
from .middleware import *
from .uimodules import *
from .options import *
import traceback
import base64
import pprint
import linecache
class DebugBreakException(Exception):
"""Raise this to break into the debugge... | 0.656438 | 0.048722 |
'''Sorry for this name, but i didnt know how to call it so i went random word generator,
love appeared, one thing led to another and here we are now.'''
import discord
from discord.ext import commands
import random
import json
class love:
def __init__(self, client):
self.client = client
#... | love.py | '''Sorry for this name, but i didnt know how to call it so i went random word generator,
love appeared, one thing led to another and here we are now.'''
import discord
from discord.ext import commands
import random
import json
class love:
def __init__(self, client):
self.client = client
#... | 0.138171 | 0.137446 |
import sys
sys.path.append("../svg")
from geometry import GeometryLoss
import numpy as np
import pygame as pg
import torch
import pydiffvg
import tkinter as tk
from tkinter import filedialog
def box_kernel(val):
return np.heaviside(-val+1,0)
def cone_kernel(val):
return np.maximum(0,1-val)
de... | apps/svg_brush.py | import sys
sys.path.append("../svg")
from geometry import GeometryLoss
import numpy as np
import pygame as pg
import torch
import pydiffvg
import tkinter as tk
from tkinter import filedialog
def box_kernel(val):
return np.heaviside(-val+1,0)
def cone_kernel(val):
return np.maximum(0,1-val)
de... | 0.325521 | 0.311348 |
'''Advent of Code 2018 Day 6 solution'''
from typing import Tuple, List
import numpy
Coords = Tuple[int, ...]
def taxicabdistance(a: Coords, b: Coords) -> int:
'''Calculate Taxi Cab (Manhattan) distance between two pairs of coordinates'''
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def runsolution(inputs: List... | aoc2018/day06.py | '''Advent of Code 2018 Day 6 solution'''
from typing import Tuple, List
import numpy
Coords = Tuple[int, ...]
def taxicabdistance(a: Coords, b: Coords) -> int:
'''Calculate Taxi Cab (Manhattan) distance between two pairs of coordinates'''
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def runsolution(inputs: List... | 0.746509 | 0.656335 |
import numpy as np
from functools import partial
import multiprocessing as mp
from multiprocessing import Pool, Value, Array
class Object3D:
Object_Counter = 0
def __del__(self):
Object3D.Object_Counter -= 1
def __init__(self):
Object3D.Object_Counter +=1
def trilinear_int(sel... | Object3D_Class.py | import numpy as np
from functools import partial
import multiprocessing as mp
from multiprocessing import Pool, Value, Array
class Object3D:
Object_Counter = 0
def __del__(self):
Object3D.Object_Counter -= 1
def __init__(self):
Object3D.Object_Counter +=1
def trilinear_int(sel... | 0.311951 | 0.432723 |
from collections import defaultdict
import os
import re
import unicodedata
class WordList(object):
def __init__(self, lower=False, strip_nonalpha=False, echo=True, min=None, max=None, transforms=[]):
self._lower = lower
self._echo = echo
self._strip_nonalpha = strip_nonalpha
self.... | wordlist.py | from collections import defaultdict
import os
import re
import unicodedata
class WordList(object):
def __init__(self, lower=False, strip_nonalpha=False, echo=True, min=None, max=None, transforms=[]):
self._lower = lower
self._echo = echo
self._strip_nonalpha = strip_nonalpha
self.... | 0.749454 | 0.095097 |
from datetime import timedelta
import os,json,logging,subprocess
from airflow.models import DAG,Variable
from airflow.utils.dates import days_ago
from airflow.operators.bash_operator import BashOperator
from airflow.contrib.operators.ssh_operator import SSHOperator
from airflow.operators.python_operator import PythonOp... | dags/dag8_copy_ongoing_seqrun.py | from datetime import timedelta
import os,json,logging,subprocess
from airflow.models import DAG,Variable
from airflow.utils.dates import days_ago
from airflow.operators.bash_operator import BashOperator
from airflow.contrib.operators.ssh_operator import SSHOperator
from airflow.operators.python_operator import PythonOp... | 0.314366 | 0.106691 |
import os
import sys
import subprocess
import threading
from typing import List, Tuple
# Assumes meteor-1.5.jar is in the same directory as meteor.py. Change as needed.
METEOR_JAR = 'meteor-1.5.jar'
# print METEOR_JAR
class Meteor:
def __init__(self) -> None:
self.env = os.environ
self.env['LC_A... | metrics/meteor/meteor.py |
import os
import sys
import subprocess
import threading
from typing import List, Tuple
# Assumes meteor-1.5.jar is in the same directory as meteor.py. Change as needed.
METEOR_JAR = 'meteor-1.5.jar'
# print METEOR_JAR
class Meteor:
def __init__(self) -> None:
self.env = os.environ
self.env['LC_A... | 0.334916 | 0.301324 |
import ckit
from ckit.ckit_const import *
## @addtogroup widget
## @{
#--------------------------------------------------------------------
## タブバーウィジェット
#
class TabBarWidget(ckit.Widget):
MAX_ITEM_WIDTH = 30
def __init__( self, window, x, y, width, height, selchange_handler ):
... | lredit_tabbar.py | import ckit
from ckit.ckit_const import *
## @addtogroup widget
## @{
#--------------------------------------------------------------------
## タブバーウィジェット
#
class TabBarWidget(ckit.Widget):
MAX_ITEM_WIDTH = 30
def __init__( self, window, x, y, width, height, selchange_handler ):
... | 0.147524 | 0.103839 |
import threading
from xml.etree import ElementTree
try:
from .st_helper import running_in_st, is_st3
from . import colors
from .color_highlighter import ColorHighlighter
except ValueError:
from st_helper import running_in_st, is_st3
import colors
from color_highlighter import ColorHighlighter
... | color_scheme_color_highlighter.py |
import threading
from xml.etree import ElementTree
try:
from .st_helper import running_in_st, is_st3
from . import colors
from .color_highlighter import ColorHighlighter
except ValueError:
from st_helper import running_in_st, is_st3
import colors
from color_highlighter import ColorHighlighter
... | 0.822011 | 0.128307 |
import GestureAgentsTUIO.tuio as tuio
from GestureAgents.Events import Event
from GestureAgents.Agent import Agent
class TuioCursorEvents:
newAgent = Event()
class CursorAgent(Agent):
eventnames = ('newCursor', 'updateCursor', 'removeCursor')
class TuioAgentGenerator:
def __init__(self, screensize, i... | GestureAgentsTUIO/Tuio.py |
import GestureAgentsTUIO.tuio as tuio
from GestureAgents.Events import Event
from GestureAgents.Agent import Agent
class TuioCursorEvents:
newAgent = Event()
class CursorAgent(Agent):
eventnames = ('newCursor', 'updateCursor', 'removeCursor')
class TuioAgentGenerator:
def __init__(self, screensize, i... | 0.457379 | 0.189203 |
import torch
from torch.quantization.observer import MovingAverageMinMaxObserver
from torch.quantization.fake_quantize import FakeQuantize
from torch.quantization.quantization_mappings import *
from torch.quantization.quantize import swap_module
import src.utils as utils
import copy
import torch.nn.intrinsic as nni
f... | src/quant_utils.py | import torch
from torch.quantization.observer import MovingAverageMinMaxObserver
from torch.quantization.fake_quantize import FakeQuantize
from torch.quantization.quantization_mappings import *
from torch.quantization.quantize import swap_module
import src.utils as utils
import copy
import torch.nn.intrinsic as nni
f... | 0.702224 | 0.783575 |
def intriga(n):
# Inicializa um tabuleiro sem rainhas
tabuleiro = [None for _ in range(n)]
# Inicializa o numero minimo de rainhas com o máximo de rainhas possivel (numero de linhas)
minimum = len(tabuleiro)
minimum_pos = list()
# Testa a rainha causadora de intrigas em cada posição
# Test... | Simulado 03/RainhasAmigasComUmaIntriga/src/__main__.py | def intriga(n):
# Inicializa um tabuleiro sem rainhas
tabuleiro = [None for _ in range(n)]
# Inicializa o numero minimo de rainhas com o máximo de rainhas possivel (numero de linhas)
minimum = len(tabuleiro)
minimum_pos = list()
# Testa a rainha causadora de intrigas em cada posição
# Test... | 0.326701 | 0.606382 |
from typing import List, Union, Dict, Tuple, Set, Any, Literal
from functools import reduce
from json import dumps
from random import random
def to_terminal(
line_type: Union[Literal['warning', 'error', 'info', ''], None],
msg_type: Union[Literal['WARNING', 'ERROR', 'INFO', ''], str, None],
*m... | build/examples/random-solution/random-solution.py | from typing import List, Union, Dict, Tuple, Set, Any, Literal
from functools import reduce
from json import dumps
from random import random
def to_terminal(
line_type: Union[Literal['warning', 'error', 'info', ''], None],
msg_type: Union[Literal['WARNING', 'ERROR', 'INFO', ''], str, None],
*m... | 0.86053 | 0.362377 |
from riscv.EnvRISCV import EnvRISCV
from riscv.GenThreadRISCV import GenThreadRISCV
from base.Sequence import Sequence
class MainSequence(Sequence):
"""Exercise different combinations of values for the parameters for the genPA instruction.
Focus in this test is to try values of the Size, Align and CanAlias ... | tests/riscv/APIs/api_genPA_01_force.py | from riscv.EnvRISCV import EnvRISCV
from riscv.GenThreadRISCV import GenThreadRISCV
from base.Sequence import Sequence
class MainSequence(Sequence):
"""Exercise different combinations of values for the parameters for the genPA instruction.
Focus in this test is to try values of the Size, Align and CanAlias ... | 0.355327 | 0.509642 |
# Third Party
from django.urls import path
# Project
from orp_apps.orp_api import views
urlpatterns = [
path('', views.APIRoot.as_view(), name='api-root'),
path('taxonomies/', views.TaxonomyListView.as_view(), name='taxonomy-list'),
path('taxonomies/<int:id>/', views.TaxonomyDetailView.as_view(), name='t... | external-apis/src/orp_apps/orp_api/urls.py |
# Third Party
from django.urls import path
# Project
from orp_apps.orp_api import views
urlpatterns = [
path('', views.APIRoot.as_view(), name='api-root'),
path('taxonomies/', views.TaxonomyListView.as_view(), name='taxonomy-list'),
path('taxonomies/<int:id>/', views.TaxonomyDetailView.as_view(), name='t... | 0.420005 | 0.080973 |
from functools import singledispatch
from operator import attrgetter
from typing import Collection, Union
from antlr4 import FileStream, ParserRuleContext
from knitscript.astnodes import Block, Call, Document, \
ExpandingStitchRepeat, FixedBlockRepeat, FixedStitchRepeat, Get, \
NaturalLit, Node, PatternDef, P... | knitscript/_astgen.py | from functools import singledispatch
from operator import attrgetter
from typing import Collection, Union
from antlr4 import FileStream, ParserRuleContext
from knitscript.astnodes import Block, Call, Document, \
ExpandingStitchRepeat, FixedBlockRepeat, FixedStitchRepeat, Get, \
NaturalLit, Node, PatternDef, P... | 0.789477 | 0.180323 |
import tempfile
from pathlib import Path
from yt.data_objects.time_series import DatasetSeries
from yt.testing import assert_raises
from yt.utilities.exceptions import YTUnidentifiedDataType
def test_pattern_expansion():
file_list = [f"fake_data_file_{str(i).zfill(4)}" for i in range(10)]
with tempfile.Temp... | yt/data_objects/tests/test_time_series.py | import tempfile
from pathlib import Path
from yt.data_objects.time_series import DatasetSeries
from yt.testing import assert_raises
from yt.utilities.exceptions import YTUnidentifiedDataType
def test_pattern_expansion():
file_list = [f"fake_data_file_{str(i).zfill(4)}" for i in range(10)]
with tempfile.Temp... | 0.427516 | 0.455925 |
import numpy as np
import adafdr.method as md
import adafdr.data_loader as dl
def test_method_init():
""" test for md.method_init
"""
p, x, h, n_full, _ = dl.load_2d_bump_slope(n_sample=20000)
a, mu, sigma, w = md.method_init(p, x, 2, alpha=0.1, n_full=n_full, h=h,
... | test/test_method.py | import numpy as np
import adafdr.method as md
import adafdr.data_loader as dl
def test_method_init():
""" test for md.method_init
"""
p, x, h, n_full, _ = dl.load_2d_bump_slope(n_sample=20000)
a, mu, sigma, w = md.method_init(p, x, 2, alpha=0.1, n_full=n_full, h=h,
... | 0.431345 | 0.661281 |
import numpy as np
import subprocess
from insar.unwrapping import quality_maps
from itertools import product
import os
cwd = "/home/stepan/zpt/interferometry"
py_interp = "./env/bin/python"
folder_path = "./processing_results/150522_11-13-26/tests_26_08/hamming/"
file = "compl.npy"
compl = np.load(folder_path + file)
... | processing_scripts/params_test.py | import numpy as np
import subprocess
from insar.unwrapping import quality_maps
from itertools import product
import os
cwd = "/home/stepan/zpt/interferometry"
py_interp = "./env/bin/python"
folder_path = "./processing_results/150522_11-13-26/tests_26_08/hamming/"
file = "compl.npy"
compl = np.load(folder_path + file)
... | 0.132374 | 0.056652 |
from PyQt5.QtGui import QImage, QColor
from Common.color import Palette, Color
from threading import Thread
import numpy as np
class Image(QImage):
def __init__(self, image_path: str, width: int = 0, height: int = 0):
img = QImage(image_path)
if (width > 0) and (height > 0):
img = im... | src/Common/image.py | from PyQt5.QtGui import QImage, QColor
from Common.color import Palette, Color
from threading import Thread
import numpy as np
class Image(QImage):
def __init__(self, image_path: str, width: int = 0, height: int = 0):
img = QImage(image_path)
if (width > 0) and (height > 0):
img = im... | 0.544559 | 0.352648 |
import os
import pandas as pd
import numpy as np
from rpy2.robjects.packages import importr
import rpy2.robjects.packages as rpackages
from rpy2.robjects.vectors import StrVector
from rpy2.robjects import r
from rpy2.robjects import pandas2ri
pandas2ri.activate()
utils = rpackages.importr('utils')
utils.chooseCRANmi... | q2_winnowing/step4_5/decay_curve.py |
import os
import pandas as pd
import numpy as np
from rpy2.robjects.packages import importr
import rpy2.robjects.packages as rpackages
from rpy2.robjects.vectors import StrVector
from rpy2.robjects import r
from rpy2.robjects import pandas2ri
pandas2ri.activate()
utils = rpackages.importr('utils')
utils.chooseCRANmi... | 0.436142 | 0.512693 |
import pprint
import re # noqa: F401
import six
from lightly.openapi_generated.swagger_client.configuration import Configuration
class TagUpsizeRequest(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
... | lightly/openapi_generated/swagger_client/models/tag_upsize_request.py | import pprint
import re # noqa: F401
import six
from lightly.openapi_generated.swagger_client.configuration import Configuration
class TagUpsizeRequest(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
... | 0.642096 | 0.153708 |
import datetime
from google.appengine.ext import ndb
from components import auth
from components import utils
from testing_utils import testing
from test import test_util
from test.test_util import future
from go.chromium.org.luci.buildbucket.proto import common_pb2
import expiration
import model
class ExpireBuil... | appengine/cr-buildbucket/test/expiration_test.py |
import datetime
from google.appengine.ext import ndb
from components import auth
from components import utils
from testing_utils import testing
from test import test_util
from test.test_util import future
from go.chromium.org.luci.buildbucket.proto import common_pb2
import expiration
import model
class ExpireBuil... | 0.421909 | 0.277785 |
import random
from chaoscf.actions import terminate_app_instance, \
terminate_some_random_instance
from chaoscf.api import get_apps_for_org, get_app_instances
from chaoslib import Configuration, Secrets
from chaoslib.exceptions import FailedActivity
__all__ = ['get_app_states_by_org', 'terminate_random_app_instan... | kallisticore/modules/cloud_foundry/actions.py | import random
from chaoscf.actions import terminate_app_instance, \
terminate_some_random_instance
from chaoscf.api import get_apps_for_org, get_app_instances
from chaoslib import Configuration, Secrets
from chaoslib.exceptions import FailedActivity
__all__ = ['get_app_states_by_org', 'terminate_random_app_instan... | 0.592431 | 0.153391 |
from django.shortcuts import render, redirect
from django.http import HttpResponse
from scanner.background.DBmanager import DBmanager, check
from scanner.background import send_message
from .forms import IDAndItem
from django.contrib.auth import logout, authenticate, login
from django.contrib import messages
from djang... | gamesnstuff/scanner/views.py | from django.shortcuts import render, redirect
from django.http import HttpResponse
from scanner.background.DBmanager import DBmanager, check
from scanner.background import send_message
from .forms import IDAndItem
from django.contrib.auth import logout, authenticate, login
from django.contrib import messages
from djang... | 0.387459 | 0.092729 |
# # S_ProjectionVGSub [<img src="https://www.arpm.co/lab/icons/icon_permalink.png" width=30 height=30 style="display: inline;">](https://www.arpm.co/lab/redirect.php?code=S_ProjectionVGSub&codeLang=Python)
# For details, see [here](https://www.arpm.co/lab/redirect.php?permalink=eb-subordinated-brownian-motion).
# ## ... | scripts/sources/S_ProjectionVGSub.py |
# # S_ProjectionVGSub [<img src="https://www.arpm.co/lab/icons/icon_permalink.png" width=30 height=30 style="display: inline;">](https://www.arpm.co/lab/redirect.php?code=S_ProjectionVGSub&codeLang=Python)
# For details, see [here](https://www.arpm.co/lab/redirect.php?permalink=eb-subordinated-brownian-motion).
# ## ... | 0.523908 | 0.473231 |
""" """
# Standard library modules.
# Third party modules.
import pytest
from qtpy import QtCore, QtGui
# Local modules.
from pymontecarlo_gui.options.material import (
FormulaValidator,
MaterialPureWidget,
MaterialFormulaWidget,
MaterialAdvancedWidget,
MaterialListWidget,
)
from pymontecarlo_gui... | pymontecarlo_gui/options/test_material.py | """ """
# Standard library modules.
# Third party modules.
import pytest
from qtpy import QtCore, QtGui
# Local modules.
from pymontecarlo_gui.options.material import (
FormulaValidator,
MaterialPureWidget,
MaterialFormulaWidget,
MaterialAdvancedWidget,
MaterialListWidget,
)
from pymontecarlo_gui... | 0.743727 | 0.462959 |
import os
from ..schema.utils.engine import DataBase
__all__ = ['db', 'GenericService', 'PermissionsMixin']
db_path = os.getenv('DATABASE_URI')
db = DataBase(db_path)
def make_key(**opts):
key = '-'.join([
f'{k}={v}'
for k, v in dict(opts).items()
])
return key
# Caching is currently ... | src/db/services/generic.py | import os
from ..schema.utils.engine import DataBase
__all__ = ['db', 'GenericService', 'PermissionsMixin']
db_path = os.getenv('DATABASE_URI')
db = DataBase(db_path)
def make_key(**opts):
key = '-'.join([
f'{k}={v}'
for k, v in dict(opts).items()
])
return key
# Caching is currently ... | 0.502686 | 0.099821 |
import search
from math import(cos, pi)
sumner_map = search.UndirectedGraph(dict(
#Portland=dict(Mitchellville=7, Fairfield=17, Cottontown=18),
#Cottontown=dict(Portland=18),
#Fairfield=dict(Mitchellville=21, Portland=17),
#Mitchellville=dict(Portland=7, Fairfield=21),
#cost is in estimated minutes of ... | submissions/Johnson/puzzles.py | import search
from math import(cos, pi)
sumner_map = search.UndirectedGraph(dict(
#Portland=dict(Mitchellville=7, Fairfield=17, Cottontown=18),
#Cottontown=dict(Portland=18),
#Fairfield=dict(Mitchellville=21, Portland=17),
#Mitchellville=dict(Portland=7, Fairfield=21),
#cost is in estimated minutes of ... | 0.295636 | 0.156491 |
import datetime
import os
import sys
import yaml
import shutil
import argparse
import string
# This script will append the current number of commits given as an arg
# (presumably since some past base tag), and the git hash arg for a final
# version like: 0.1.189-3f73a592
VERSION_BASE = "0.1"
parser = argparse.Argume... | boilerplate/openshift/golang-osd-operator/csv-generate/common-generate-operator-bundle.py |
import datetime
import os
import sys
import yaml
import shutil
import argparse
import string
# This script will append the current number of commits given as an arg
# (presumably since some past base tag), and the git hash arg for a final
# version like: 0.1.189-3f73a592
VERSION_BASE = "0.1"
parser = argparse.Argume... | 0.350421 | 0.084153 |
import torch
from .base_model import BaseModel
from . import networks
import pdb
class Pix2PixModel(BaseModel):
""" This class implements the pix2pix model, for learning a mapping from input images to output images given paired data.
The model training requires '--dataset_mode aligned' dataset.
By defaul... | models/pix2pix_model.py | import torch
from .base_model import BaseModel
from . import networks
import pdb
class Pix2PixModel(BaseModel):
""" This class implements the pix2pix model, for learning a mapping from input images to output images given paired data.
The model training requires '--dataset_mode aligned' dataset.
By defaul... | 0.905119 | 0.375392 |
from numpy import *
import numpy as np
import os
import torch
import torch.nn as nn
from sklearn.metrics import f1_score, precision_score, recall_score
from torch.optim import lr_scheduler
from tensorboardX import SummaryWriter
from tqdm import tqdm
import logging # 引入logging模块
logging.basicConfig(level = logging.INFO... | DPCN/train.py | from numpy import *
import numpy as np
import os
import torch
import torch.nn as nn
from sklearn.metrics import f1_score, precision_score, recall_score
from torch.optim import lr_scheduler
from tensorboardX import SummaryWriter
from tqdm import tqdm
import logging # 引入logging模块
logging.basicConfig(level = logging.INFO... | 0.728265 | 0.20144 |
import optparse
# --------------------------------------------------------------------------------------------------------------------
class CmdSHTConf(object):
"""
unix command line handler
"""
# -------------------------------------------------------------------------------------------------------... | src/scs_mfr/cmd/cmd_sht_conf.py | import optparse
# --------------------------------------------------------------------------------------------------------------------
class CmdSHTConf(object):
"""
unix command line handler
"""
# -------------------------------------------------------------------------------------------------------... | 0.419291 | 0.107157 |
import os
import pickle
import itertools
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from sklearn.metrics import confusion_matrix
from sklearn.utils.multiclass import unique_labels
def plot_confusion_matrix0(y_true, y_pred,
classes=None,
... | src/utils/plots.py | import os
import pickle
import itertools
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from sklearn.metrics import confusion_matrix
from sklearn.utils.multiclass import unique_labels
def plot_confusion_matrix0(y_true, y_pred,
classes=None,
... | 0.785473 | 0.414129 |
from flask import Blueprint, request, jsonify, current_app
from main import db
from main.models.stock import IndexComponentSH50, IndexComponentHS300, Overview
from crawler.eastmoney.stock.index_component import get_sh50_component, get_hs300_component
from crawler.eastmoney.stock.data import get_code_hxtc
from main.stoc... | backend/main/stock_index_component.py | from flask import Blueprint, request, jsonify, current_app
from main import db
from main.models.stock import IndexComponentSH50, IndexComponentHS300, Overview
from crawler.eastmoney.stock.index_component import get_sh50_component, get_hs300_component
from crawler.eastmoney.stock.data import get_code_hxtc
from main.stoc... | 0.375248 | 0.085824 |
import os
import sys
from argparse import ArgumentParser, Namespace
from collections import OrderedDict
from typing import Any, Callable, Optional
from watchopticalmc.internal.generatemc.generatemc import GenerateMCConfig, generatemc
from watchopticalmc.internal.generatemc.makeratdb import makeratdb
from watchopticalm... | lib/watchopticalmc/watchopticalmc/scripts/generatemc.py | import os
import sys
from argparse import ArgumentParser, Namespace
from collections import OrderedDict
from typing import Any, Callable, Optional
from watchopticalmc.internal.generatemc.generatemc import GenerateMCConfig, generatemc
from watchopticalmc.internal.generatemc.makeratdb import makeratdb
from watchopticalm... | 0.598664 | 0.09886 |
import numpy as np
from abmarl.sim.modules import GridResources
def test_builder():
sim = GridResources.build()
assert sim.region == 10
assert sim.max_value == 1.
assert sim.min_value == 0.1
assert sim.revive_rate == 0.04
assert sim.coverage == 0.75
def test_builder_custom():
sim = Grid... | tests/test_grid_resources.py | import numpy as np
from abmarl.sim.modules import GridResources
def test_builder():
sim = GridResources.build()
assert sim.region == 10
assert sim.max_value == 1.
assert sim.min_value == 0.1
assert sim.revive_rate == 0.04
assert sim.coverage == 0.75
def test_builder_custom():
sim = Grid... | 0.68742 | 0.781664 |
import numpy as np
import click
import os
from PIL import Image
from lmnet.nnlib import NNLib as NNLib
from lmnet.common import Tasks
from lmnet.utils.output import JsonOutput, ImageFromJson
from lmnet.utils.config import (
load_yaml,
build_pre_process,
build_post_process,
)
def _pre_process(raw_image, ... | output_template/python/run.py | import numpy as np
import click
import os
from PIL import Image
from lmnet.nnlib import NNLib as NNLib
from lmnet.common import Tasks
from lmnet.utils.output import JsonOutput, ImageFromJson
from lmnet.utils.config import (
load_yaml,
build_pre_process,
build_post_process,
)
def _pre_process(raw_image, ... | 0.378919 | 0.13452 |
import logging
import spotipy
from spotmover.providers.spotify.util import obtain_token_localhost
from spotmover.providers.base import Provider, ProviderAuthError
from spotmover.dump import Dump
from spotmover.cache import DiskCache
logger = logging.getLogger(__name__)
def confirm(msg):
answer = input(msg + " "... | spotmover/providers/spotify/spotify.py | import logging
import spotipy
from spotmover.providers.spotify.util import obtain_token_localhost
from spotmover.providers.base import Provider, ProviderAuthError
from spotmover.dump import Dump
from spotmover.cache import DiskCache
logger = logging.getLogger(__name__)
def confirm(msg):
answer = input(msg + " "... | 0.411939 | 0.076304 |
"""Version bumper on upload."""
import subprocess
from datetime import datetime
import configparser
import v0tools_doc
DTFMT = "%Y-%m-%d %H:%M UTC"
def commits(start, end):
cmd = f"git rev-list {start}...{end}".split()
return subprocess.check_output(cmd, encoding="utf-8").splitlines()
def commit_details(c... | src/v0tools_doc/changelog.py | """Version bumper on upload."""
import subprocess
from datetime import datetime
import configparser
import v0tools_doc
DTFMT = "%Y-%m-%d %H:%M UTC"
def commits(start, end):
cmd = f"git rev-list {start}...{end}".split()
return subprocess.check_output(cmd, encoding="utf-8").splitlines()
def commit_details(c... | 0.405802 | 0.14069 |
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
class MyMainGUI(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.qtxt1 = QTextEdit(self)
self.btn1 = QPushButton("Start", self)
self.btn2 = QPushButton("Stop", self)
self.btn3 = QPushButton("a... | test.py | from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
class MyMainGUI(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.qtxt1 = QTextEdit(self)
self.btn1 = QPushButton("Start", self)
self.btn2 = QPushButton("Stop", self)
self.btn3 = QPushButton("a... | 0.429669 | 0.069226 |
import numbers
import numpy
import autofile.info
from autofile.system._util import utc_time as _utc_time
def conformer_trunk(nsamp, tors_ranges):
""" conformer trunk information
:param nsamp: the number of samples
:type nsamp: int
:param tors_ranges: sampling ranges [(start, end)] for each torsional
... | autofile/system/info.py | import numbers
import numpy
import autofile.info
from autofile.system._util import utc_time as _utc_time
def conformer_trunk(nsamp, tors_ranges):
""" conformer trunk information
:param nsamp: the number of samples
:type nsamp: int
:param tors_ranges: sampling ranges [(start, end)] for each torsional
... | 0.741206 | 0.731059 |
params_num = 0
allWeights = []
for i in range(len(model.layers)):
if "conv" in model.layers[i].name:
weights = model.layers[i].get_weights()[0]
params = weights.shape[3]
allWeights.append((i,np.arange(params_num,params_num+params)))
params_num += params
#NS_mutation_weight... | cifar10/scripts/model_mutation.py |
params_num = 0
allWeights = []
for i in range(len(model.layers)):
if "conv" in model.layers[i].name:
weights = model.layers[i].get_weights()[0]
params = weights.shape[3]
allWeights.append((i,np.arange(params_num,params_num+params)))
params_num += params
#NS_mutation_weight... | 0.282691 | 0.339116 |
from __future__ import (print_function, unicode_literals, division,
absolute_import)
import io
import os
import re
import subprocess
from common import vprint, exe, ff, wf, check, get_latest_driver_version
ETC = "/etc/glance/glance-api.conf"
PACKAGE_INSTALL = "/usr/lib/python2.7/dist-packages... | src/plugins/check_glance.py | from __future__ import (print_function, unicode_literals, division,
absolute_import)
import io
import os
import re
import subprocess
from common import vprint, exe, ff, wf, check, get_latest_driver_version
ETC = "/etc/glance/glance-api.conf"
PACKAGE_INSTALL = "/usr/lib/python2.7/dist-packages... | 0.28897 | 0.047603 |
from pathlib import Path
from typing import Any
from django.core.exceptions import ValidationError
from django.db import models
from django.db.models.base import ModelBase
from django_analyses.models import help_text
from django_analyses.models.input.definitions import messages
from django_analyses.models.input.input ... | django_analyses/models/input/definitions/input_definition.py | from pathlib import Path
from typing import Any
from django.core.exceptions import ValidationError
from django.db import models
from django.db.models.base import ModelBase
from django_analyses.models import help_text
from django_analyses.models.input.definitions import messages
from django_analyses.models.input.input ... | 0.916395 | 0.303293 |
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin, ClusterMixin
from itertools import repeat
class HistogramTransform(BaseEstimator, TransformerMixin):
"""Apply an histogram transform to the data.
"""
def __init__(self, edges):
"""
Paramete... | bactoml/decision_tree_classifier.py | import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin, ClusterMixin
from itertools import repeat
class HistogramTransform(BaseEstimator, TransformerMixin):
"""Apply an histogram transform to the data.
"""
def __init__(self, edges):
"""
Paramete... | 0.910426 | 0.608216 |
import os
import time
from datetime import date
from ftplib import FTP
import pandas as pd
from sqlalchemy import create_engine
# 服务器地址
FTP_SERVER = '172.16.17.32'
USER = 'yxh'
PWD = '<PASSWORD>'
FTP_PATH = '/'
local_root = 'E:\\projects\\python\\beestock\\data\\result'
DATE = time.strftime('%Y%m%d', time.localtime(t... | easytrader/assistant/hope_file_downloader.py |
import os
import time
from datetime import date
from ftplib import FTP
import pandas as pd
from sqlalchemy import create_engine
# 服务器地址
FTP_SERVER = '172.16.17.32'
USER = 'yxh'
PWD = '<PASSWORD>'
FTP_PATH = '/'
local_root = 'E:\\projects\\python\\beestock\\data\\result'
DATE = time.strftime('%Y%m%d', time.localtime(t... | 0.217254 | 0.087916 |
class Node(object):
def __init__(self, val):
self.val = val
self.next = None
class MyLinkedList:
def __init__(self):
self.head = None
def get(self, index):
"""
Get the value of the index-th node in the linked list. If the index is invalid, return -... | MyLinkedList.py | class Node(object):
def __init__(self, val):
self.val = val
self.next = None
class MyLinkedList:
def __init__(self):
self.head = None
def get(self, index):
"""
Get the value of the index-th node in the linked list. If the index is invalid, return -... | 0.579638 | 0.214671 |
from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401
from oci.decorators import init_model_state_from_kwargs
@init_model_state_from_kwargs
class TranscriptionNormalization(object):
"""
Information to Normalize generated transcript.
"""
def __ini... | src/oci/ai_speech/models/transcription_normalization.py |
from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401
from oci.decorators import init_model_state_from_kwargs
@init_model_state_from_kwargs
class TranscriptionNormalization(object):
"""
Information to Normalize generated transcript.
"""
def __ini... | 0.790692 | 0.251717 |
import pytest
from collections import OrderedDict
import numpy as np
import pypospack.potential as potential
def test__import__pypospack_potential():
from pypospack.potential import MorsePotential
def test__import__pypospack_potentials_morse():
from pypospack.potentials.morse import MorsePotential
def test__... | tests/potential/BornMayerPotential/test_MorsePotential.py | import pytest
from collections import OrderedDict
import numpy as np
import pypospack.potential as potential
def test__import__pypospack_potential():
from pypospack.potential import MorsePotential
def test__import__pypospack_potentials_morse():
from pypospack.potentials.morse import MorsePotential
def test__... | 0.411229 | 0.583648 |
import numpy as np
from astropy.wcs import WCS
from ._det_spatial import get_shadowed_pix_mask_for_urddata, DL, F, multiply_photons
from .time import get_gti, GTI, tGTI, emptyGTI, deadtime_correction
from .atthist import hist_orientation_for_attdata
from .planwcs import make_wcs_for_attdata
from .caldb import get_energ... | arttools/plot.py | import numpy as np
from astropy.wcs import WCS
from ._det_spatial import get_shadowed_pix_mask_for_urddata, DL, F, multiply_photons
from .time import get_gti, GTI, tGTI, emptyGTI, deadtime_correction
from .atthist import hist_orientation_for_attdata
from .planwcs import make_wcs_for_attdata
from .caldb import get_energ... | 0.421076 | 0.239944 |
from ops import *
from utils import *
from glob import glob
import time
import shutil
from tensorflow.contrib.data import prefetch_to_device, shuffle_and_repeat, map_and_batch
import numpy as np
class UGATIT(object) :
def __init__(self, sess, args):
self.light = args.light
self.args_dict... | UGATIT.py | from ops import *
from utils import *
from glob import glob
import time
import shutil
from tensorflow.contrib.data import prefetch_to_device, shuffle_and_repeat, map_and_batch
import numpy as np
class UGATIT(object) :
def __init__(self, sess, args):
self.light = args.light
self.args_dict... | 0.394318 | 0.088899 |
# Imports
import numpy as np
import cv2
import pickle
face_cascade = cv2.CascadeClassifier(
'/home/alejandro/Escritorio/Prototype FaceReconigtion/Cascades/data/haarcascades/haarcascade_frontalface_alt2.xml')
eye_cascade = cv2.CascadeClassifier(
'/home/alejandro/Escritorio/Prototype FaceReconigtion/Cascades/da... | Application.py |
# Imports
import numpy as np
import cv2
import pickle
face_cascade = cv2.CascadeClassifier(
'/home/alejandro/Escritorio/Prototype FaceReconigtion/Cascades/data/haarcascades/haarcascade_frontalface_alt2.xml')
eye_cascade = cv2.CascadeClassifier(
'/home/alejandro/Escritorio/Prototype FaceReconigtion/Cascades/da... | 0.515132 | 0.262415 |
from typing import Optional, List, Set, Callable
from rdflib import URIRef, Graph, OWL, RDF, BNode
from rdflib.compare import graph_diff
from rdflib.term import Node
from fhirtordf.rdfsupport.namespaces import FHIR
from fhirtordf.rdfsupport.prettygraph import PrettyGraph
def subj_pred_idx_to_uri(s: URIRef, p: URIRe... | fhirtordf/rdfsupport/rdfcompare.py | from typing import Optional, List, Set, Callable
from rdflib import URIRef, Graph, OWL, RDF, BNode
from rdflib.compare import graph_diff
from rdflib.term import Node
from fhirtordf.rdfsupport.namespaces import FHIR
from fhirtordf.rdfsupport.prettygraph import PrettyGraph
def subj_pred_idx_to_uri(s: URIRef, p: URIRe... | 0.833697 | 0.349949 |
from typing import Any, Dict, List, NoReturn, Optional, Type, Union
from sqlalchemy.exc import NoResultFound
from sqlalchemy.orm import Session
from tgbot.db.models import (
BaseModel,
TelegramUser,
Habit,
Event
)
class BaseRepo:
"""
Database abstraction layer
"""
model: Type[BaseMo... | tgbot/services/repository.py | from typing import Any, Dict, List, NoReturn, Optional, Type, Union
from sqlalchemy.exc import NoResultFound
from sqlalchemy.orm import Session
from tgbot.db.models import (
BaseModel,
TelegramUser,
Habit,
Event
)
class BaseRepo:
"""
Database abstraction layer
"""
model: Type[BaseMo... | 0.893759 | 0.287187 |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoMinorLocator
from matplotlib.collections import LineCollection
def grid(ax):
segments,colors,linewidths = [], [], []
for x in ax.xaxis.get_minorticklocs():
segments.append([(x,ymin), (x,ymax)])
colors.append("... | reference-scales.py | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoMinorLocator
from matplotlib.collections import LineCollection
def grid(ax):
segments,colors,linewidths = [], [], []
for x in ax.xaxis.get_minorticklocs():
segments.append([(x,ymin), (x,ymax)])
colors.append("... | 0.435661 | 0.446434 |
import os
import csv
import click
import random
import uwnet_datasets
def create_list(foldername, fulldir=True, suffix=".jpg"):
"""
:param foldername: The full path of the folder.
:param fulldir: Whether to return the full path or not.
:param suffix: Filter by suffix.
:return: The list of filena... | create_uwnet_dataset.py | import os
import csv
import click
import random
import uwnet_datasets
def create_list(foldername, fulldir=True, suffix=".jpg"):
"""
:param foldername: The full path of the folder.
:param fulldir: Whether to return the full path or not.
:param suffix: Filter by suffix.
:return: The list of filena... | 0.386185 | 0.173498 |
import os
import discord
from discord.ext import commands
import requests
import random
import numpy as np
from pydub import AudioSegment as audi
from moviepy.editor import *
from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip as cutr
import youtube_dl
audi.converter = "C:\\ffmpeg\\bin\\ffmpeg.exe"
audi.f... | cogs/AV.py | import os
import discord
from discord.ext import commands
import requests
import random
import numpy as np
from pydub import AudioSegment as audi
from moviepy.editor import *
from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip as cutr
import youtube_dl
audi.converter = "C:\\ffmpeg\\bin\\ffmpeg.exe"
audi.f... | 0.069065 | 0.081264 |
import os
import sys
current_folder = os.path.dirname(os.path.realpath(__file__))
sys.path.append(current_folder)
config_folder = os.path.join(current_folder, "..", "..", "matrix", "python")
sys.path.append(config_folder)
from console_formatter import Console_Formatter
from tf_index_controler import INDEX_CONT... | include/tf_nn_motor/models/tf_dataset_label_encoder.py | import os
import sys
current_folder = os.path.dirname(os.path.realpath(__file__))
sys.path.append(current_folder)
config_folder = os.path.join(current_folder, "..", "..", "matrix", "python")
sys.path.append(config_folder)
from console_formatter import Console_Formatter
from tf_index_controler import INDEX_CONT... | 0.096354 | 0.062245 |
import shutil
from pathlib import Path
import itertools
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import collections
from scipy.optimize import minimize_scalar
cols1 = ['F1_' + str(i) for i in range(3, 20, 2)]
cols2 = ['F2_' + str(i) for i in range(3, 20, 2)]
kCols = cols1 + cols2
de... | analysis/plot_break.py | import shutil
from pathlib import Path
import itertools
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import collections
from scipy.optimize import minimize_scalar
cols1 = ['F1_' + str(i) for i in range(3, 20, 2)]
cols2 = ['F2_' + str(i) for i in range(3, 20, 2)]
kCols = cols1 + cols2
de... | 0.545044 | 0.401923 |
import requests # We use Python "requests" module to do HTTP GET query
import json # Import JSON encoder and decode module
from operator import itemgetter
from apicem_config import * # APIC-EM IP is assigned in apicem_config.py
requests.packages.urllib3.disable_warnings() # Remove this line if not using ... | lab5-04-get-network-device-id-location.py | import requests # We use Python "requests" module to do HTTP GET query
import json # Import JSON encoder and decode module
from operator import itemgetter
from apicem_config import * # APIC-EM IP is assigned in apicem_config.py
requests.packages.urllib3.disable_warnings() # Remove this line if not using ... | 0.330579 | 0.064801 |
import os
import sys
import warnings
warnings.simplefilter("ignore")
import csv
import math
import tkinter
import tkinter.filedialog
import tkinter.messagebox
import numpy
from scipy.misc import imresize
from keras.models import load_model
import keras.backend
from matplotlib import pyplot as plt
from l... | bcnnSingleObjectClassifier.py | import os
import sys
import warnings
warnings.simplefilter("ignore")
import csv
import math
import tkinter
import tkinter.filedialog
import tkinter.messagebox
import numpy
from scipy.misc import imresize
from keras.models import load_model
import keras.backend
from matplotlib import pyplot as plt
from l... | 0.197677 | 0.301928 |
from PyQt4 import QtGui, QtCore
class MyDoubleSpinBox(QtGui.QDoubleSpinBox):
"""Selects all text once it receives a focusInEvent.
Use this widget instead of the usual QDoubleSpinBox for quick editing.
"""
def __init__(self, parent):
super(MyDoubleSpinBox, self).__init__()
self.setDe... | rampage/widgets/CommonWidgets.py | from PyQt4 import QtGui, QtCore
class MyDoubleSpinBox(QtGui.QDoubleSpinBox):
"""Selects all text once it receives a focusInEvent.
Use this widget instead of the usual QDoubleSpinBox for quick editing.
"""
def __init__(self, parent):
super(MyDoubleSpinBox, self).__init__()
self.setDe... | 0.653901 | 0.232713 |