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 |
|---|---|---|---|---|
import os
import click
import logging
from shclassify import Tree, log
usage_log_path = os.path.abspath(__file__) + '.log'
usage = logging.FileHandler(usage_log_path)
usage.setLevel(logging.INFO)
usage_fmt = logging.Formatter(
'%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'... | shclassify/scripts/cli.py | import os
import click
import logging
from shclassify import Tree, log
usage_log_path = os.path.abspath(__file__) + '.log'
usage = logging.FileHandler(usage_log_path)
usage.setLevel(logging.INFO)
usage_fmt = logging.Formatter(
'%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'... | 0.294621 | 0.058158 |
import numpy as np
from pysb.simulator.scipyode import ScipyOdeSimulator
from pysb.tools.sensitivity_analysis import \
InitialsSensitivity
from pysb.examples.tyson_oscillator import model
tspan = np.linspace(0, 200, 5001)
def obj_func_cell_cycle(trajectory):
"""
Calculate the frequency of the Y3
Pa... | pysb/examples/tools/run_sensitivity_analysis_tyson.py | import numpy as np
from pysb.simulator.scipyode import ScipyOdeSimulator
from pysb.tools.sensitivity_analysis import \
InitialsSensitivity
from pysb.examples.tyson_oscillator import model
tspan = np.linspace(0, 200, 5001)
def obj_func_cell_cycle(trajectory):
"""
Calculate the frequency of the Y3
Pa... | 0.859487 | 0.687155 |
import os
import sys
sys.path.append('../..')
from Lib.ConfigClass import Config, singular_colors
import json
scene_path = '/home/wangsd/Workspace/foliation-results/outputs/scenes/paper/teaser/'
output_path = '/pub/data/wangsd/images/teaser'
envmap_path = '/home/wangsd/Workspace/cg/data/envmap/gl-hdr-02.hdr'
checkerbo... | Blender/Scripts/wangsd/scripts/teaser.py | import os
import sys
sys.path.append('../..')
from Lib.ConfigClass import Config, singular_colors
import json
scene_path = '/home/wangsd/Workspace/foliation-results/outputs/scenes/paper/teaser/'
output_path = '/pub/data/wangsd/images/teaser'
envmap_path = '/home/wangsd/Workspace/cg/data/envmap/gl-hdr-02.hdr'
checkerbo... | 0.088618 | 0.045948 |
from os import mkdir, rmdir, getcwd
from os.path import join, exists
from shutil import rmtree
from python_utility.powerline.vagrant import VagrantSegment
from tests.constants import TEMPORARY_DIRECTORY
# TODO: The vagrant sub-process cannot access the temporary directory. What is
# a better practice? The insecure... | tests/powerline/test_vagrant.py | from os import mkdir, rmdir, getcwd
from os.path import join, exists
from shutil import rmtree
from python_utility.powerline.vagrant import VagrantSegment
from tests.constants import TEMPORARY_DIRECTORY
# TODO: The vagrant sub-process cannot access the temporary directory. What is
# a better practice? The insecure... | 0.226784 | 0.182589 |
import random
import time
from enum import Enum
import numpy as np
import pandas as pd
from scipy import sparse
from sklearn.decomposition import NMF
from sklearn.metrics import confusion_matrix
class CurrencyRating(Enum):
CHF = 5
GBP = 6
EUR = 7
USD = 8
NON_SWISS = 10
DEFAULT = 1
def sugge... | 03_clean_code/01_ranking_refactor/ranking/ranking_02_removed_basic_smells.py | import random
import time
from enum import Enum
import numpy as np
import pandas as pd
from scipy import sparse
from sklearn.decomposition import NMF
from sklearn.metrics import confusion_matrix
class CurrencyRating(Enum):
CHF = 5
GBP = 6
EUR = 7
USD = 8
NON_SWISS = 10
DEFAULT = 1
def sugge... | 0.589835 | 0.39161 |
from .serializers import ProfileSerializer,UserSerializer,ForgotPasswordSerializer,ResetPasswordSeriliazer
from rest_framework.views import APIView
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework import permissions,status
from .models i... | backend/keplerapi/authapi/views.py | from .serializers import ProfileSerializer,UserSerializer,ForgotPasswordSerializer,ResetPasswordSeriliazer
from rest_framework.views import APIView
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework import permissions,status
from .models i... | 0.464659 | 0.12692 |
if not request.is_local:
redirect(URL('default', 'index'))
def adminuser():
# http://stackoverflow.com/questions/10201300/how-can-i-create-new-auth-user-and-auth-group-on-web2py-running-on-google-app-en
if not db().select(db.auth_user.ALL).first():
db.auth_user.insert(
username=myconf... | controllers/initialize.py |
if not request.is_local:
redirect(URL('default', 'index'))
def adminuser():
# http://stackoverflow.com/questions/10201300/how-can-i-create-new-auth-user-and-auth-group-on-web2py-running-on-google-app-en
if not db().select(db.auth_user.ALL).first():
db.auth_user.insert(
username=myconf... | 0.40698 | 0.079282 |
def seating_systm_01(waiting_area):
while(True):
occupied = 0
changed = 0
for r, row in enumerate(waiting_area):
for c, seat in enumerate(row):
if seat[0] == '#':
y = r - 1
x = c - 1
for i in range(y, y +... | 11/seating_system.py | def seating_systm_01(waiting_area):
while(True):
occupied = 0
changed = 0
for r, row in enumerate(waiting_area):
for c, seat in enumerate(row):
if seat[0] == '#':
y = r - 1
x = c - 1
for i in range(y, y +... | 0.192539 | 0.505615 |
import os, sys, signal, subprocess
from sense_hat import SenseHat
from time import sleep
from libs.set_color import *
import variables.colors as c
import variables.joystick as j
sense = SenseHat()
sense.clear()
def joystickJoystick(direction):
if direction == "up":
if j.joystick_index == 0:
... | smart-lamp/modes/joystick.py | import os, sys, signal, subprocess
from sense_hat import SenseHat
from time import sleep
from libs.set_color import *
import variables.colors as c
import variables.joystick as j
sense = SenseHat()
sense.clear()
def joystickJoystick(direction):
if direction == "up":
if j.joystick_index == 0:
... | 0.055933 | 0.224906 |
from PyQt5 import QtCore, QtGui, QtWidgets
import time
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
class Ui_MainWindow(QMainWindow):
def setupUi(self, MainWindow):
# initialising timer to update value every second
timer = QTimer(self)
timer.timeout.connect(self.countdown)
... | 1-Beginner/countdown_timer/python/countdown-timer.py | from PyQt5 import QtCore, QtGui, QtWidgets
import time
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
class Ui_MainWindow(QMainWindow):
def setupUi(self, MainWindow):
# initialising timer to update value every second
timer = QTimer(self)
timer.timeout.connect(self.countdown)
... | 0.3512 | 0.054803 |
from collections import OrderedDict
import numpy as np
from dgp.annotations import (
BoundingBoxOntology, InstanceSegmentationOntology, Ontology, PanopticSegmentation2DAnnotation,
SemanticSegmentation2DAnnotation, SemanticSegmentationOntology
)
from dgp.proto.ontology_pb2 import Ontology as OntologyPB2
from d... | dgp/annotations/transform_utils.py | from collections import OrderedDict
import numpy as np
from dgp.annotations import (
BoundingBoxOntology, InstanceSegmentationOntology, Ontology, PanopticSegmentation2DAnnotation,
SemanticSegmentation2DAnnotation, SemanticSegmentationOntology
)
from dgp.proto.ontology_pb2 import Ontology as OntologyPB2
from d... | 0.903816 | 0.548734 |
import pandas as pd
import numpy as np
import more_itertools
import datetime
import logging
logger = logging.getLogger(__name__)
def parse(raw_response):
logger.info("Parsing raw json response.")
report = raw_response["report"]
raw_data = report["data"]
dimensions, metrics = _parse_header(report)
... | adobe_analytics/reports/parse.py | import pandas as pd
import numpy as np
import more_itertools
import datetime
import logging
logger = logging.getLogger(__name__)
def parse(raw_response):
logger.info("Parsing raw json response.")
report = raw_response["report"]
raw_data = report["data"]
dimensions, metrics = _parse_header(report)
... | 0.692642 | 0.320582 |
import hashlib
import json
import logging
import uuid
from collections import OrderedDict
from os.path import join
from pathlib import Path
from . import _oyaml as oyaml
logger = logging.getLogger(__name__)
def construct_filename(
name,
pretagname=None,
tagname=None,
t1=None,
t2=None,
subfol... | src/fmu/dataio/_utils.py | import hashlib
import json
import logging
import uuid
from collections import OrderedDict
from os.path import join
from pathlib import Path
from . import _oyaml as oyaml
logger = logging.getLogger(__name__)
def construct_filename(
name,
pretagname=None,
tagname=None,
t1=None,
t2=None,
subfol... | 0.563498 | 0.232986 |
import os
import unittest
from schablonesk.ast_printer import AstPrinter
from schablonesk.scanner import Scanner
from schablonesk.parser import Parser
class ParserTest(unittest.TestCase):
def setUp(self):
self.scanner = Scanner()
def test_parse_for_stmt(self):
code = """
:> for item... | test/test_parser.py | import os
import unittest
from schablonesk.ast_printer import AstPrinter
from schablonesk.scanner import Scanner
from schablonesk.parser import Parser
class ParserTest(unittest.TestCase):
def setUp(self):
self.scanner = Scanner()
def test_parse_for_stmt(self):
code = """
:> for item... | 0.428831 | 0.503113 |
import pytest
from flask import json, url_for
from tests.conftest import create_authorization_header
from app.models import Venue
class WhenGettingVenues(object):
def it_returns_all_venues(self, client, sample_venue, db_session):
response = client.get(
url_for('venues.get_venues'),
... | tests/app/routes/venues/test_rest.py | import pytest
from flask import json, url_for
from tests.conftest import create_authorization_header
from app.models import Venue
class WhenGettingVenues(object):
def it_returns_all_venues(self, client, sample_venue, db_session):
response = client.get(
url_for('venues.get_venues'),
... | 0.542136 | 0.352982 |
import numpy as np
from keras import backend as K
from keras import activations
from keras import initializers
from keras import regularizers
from keras import constraints
from keras.engine import Layer
from keras.engine import InputSpec
from keras.layers.recurrent import Recurrent, _time_distributed_dense
f... | layers/mLSTM.py | import numpy as np
from keras import backend as K
from keras import activations
from keras import initializers
from keras import regularizers
from keras import constraints
from keras.engine import Layer
from keras.engine import InputSpec
from keras.layers.recurrent import Recurrent, _time_distributed_dense
f... | 0.928555 | 0.54577 |
from typing import Any, cast, List, Optional, Union
from gitlab import cli
from gitlab import exceptions as exc
from gitlab import types
from gitlab.base import RequiredOptional, RESTManager, RESTObject
from gitlab.mixins import (
CreateMixin,
CRUDMixin,
DeleteMixin,
ListMixin,
ObjectDeleteMixin,
... | venv/Lib/site-packages/gitlab/v4/objects/runners.py | from typing import Any, cast, List, Optional, Union
from gitlab import cli
from gitlab import exceptions as exc
from gitlab import types
from gitlab.base import RequiredOptional, RESTManager, RESTObject
from gitlab.mixins import (
CreateMixin,
CRUDMixin,
DeleteMixin,
ListMixin,
ObjectDeleteMixin,
... | 0.905803 | 0.105441 |
import sys, sqlite3
from collections import namedtuple
import MeCab
import random
import Vocabulary1
conn = sqlite3.connect("./wnjpn.db", check_same_thread = False)
Word = namedtuple('Word', 'wordid lang lemma pron pos')
def getWords(lemma):
cur = conn.execute("select * from word where lemma=?", (lemma,))
retur... | SentenceGenerator.py |
import sys, sqlite3
from collections import namedtuple
import MeCab
import random
import Vocabulary1
conn = sqlite3.connect("./wnjpn.db", check_same_thread = False)
Word = namedtuple('Word', 'wordid lang lemma pron pos')
def getWords(lemma):
cur = conn.execute("select * from word where lemma=?", (lemma,))
retur... | 0.141756 | 0.146026 |
from unittest.mock import MagicMock
import copy
from scan.fetchers.cli.cli_fetch_vservice_vnics import CliFetchVserviceVnics
from scan.test.fetch.cli_fetch.test_data.cli_fetch_vservice_vnics import *
from scan.test.fetch.test_fetch import TestFetch
class TestCliFetchVserviceVnics(TestFetch):
def setUp(self):
... | scan/test/fetch/cli_fetch/test_cli_fetch_vservice_vnics.py | from unittest.mock import MagicMock
import copy
from scan.fetchers.cli.cli_fetch_vservice_vnics import CliFetchVserviceVnics
from scan.test.fetch.cli_fetch.test_data.cli_fetch_vservice_vnics import *
from scan.test.fetch.test_fetch import TestFetch
class TestCliFetchVserviceVnics(TestFetch):
def setUp(self):
... | 0.76291 | 0.282116 |
import html_generators as h
def assert_equal(a, b):
assert a == b, f'This:\n{a}\nIs not equal to:\n{b}'
import django
from django.conf import settings
from django.http import StreamingHttpResponse
from django.template import Template, Context
from django.template.engine import Engine
from django.utils.html import ... | tests/test_django.py | import html_generators as h
def assert_equal(a, b):
assert a == b, f'This:\n{a}\nIs not equal to:\n{b}'
import django
from django.conf import settings
from django.http import StreamingHttpResponse
from django.template import Template, Context
from django.template.engine import Engine
from django.utils.html import ... | 0.290276 | 0.277865 |
import pandas as pd
import streamlit as st
import re
import pydeck as pdk
import numpy as np
import altair as alt
applicants = pd.read_csv('./applicants.csv')
grants = pd.read_csv('./grants.csv')
# lat_midpoint = grants['lat'].median()
# lon_midpoint = grants['lon'].median()
min_grant, max_grant, med_grant = int(gr... | tiger.py | import pandas as pd
import streamlit as st
import re
import pydeck as pdk
import numpy as np
import altair as alt
applicants = pd.read_csv('./applicants.csv')
grants = pd.read_csv('./grants.csv')
# lat_midpoint = grants['lat'].median()
# lon_midpoint = grants['lon'].median()
min_grant, max_grant, med_grant = int(gr... | 0.234319 | 0.187114 |
import copy
from Engine import BaseEngine
from GTP import Move
# want policy network to influence evaluation????
# could modify score by policy probability, possibly in a depth-dependent way
def get_board_after_move(board, move):
ret = copy.deepcopy(board)
ret.play_stone(move[0], move[1], board.color_to_play)... | support/go-NN-master/engine/TreeSearch.py | import copy
from Engine import BaseEngine
from GTP import Move
# want policy network to influence evaluation????
# could modify score by policy probability, possibly in a depth-dependent way
def get_board_after_move(board, move):
ret = copy.deepcopy(board)
ret.play_stone(move[0], move[1], board.color_to_play)... | 0.582254 | 0.487368 |
print "=================================="
# 5-1
age = 20
if age >= 18:
print 'your age is', age # Python代码的缩进规则
print 'adult'
# 退出缩进需要多敲一行回车
print 'END'
score = 75
if score >= 60:
print 'passed'
print "=================================="
# 5-2
if age... | imooc/1rumen/5.py | print "=================================="
# 5-1
age = 20
if age >= 18:
print 'your age is', age # Python代码的缩进规则
print 'adult'
# 退出缩进需要多敲一行回车
print 'END'
score = 75
if score >= 60:
print 'passed'
print "=================================="
# 5-2
if age... | 0.095513 | 0.316455 |
import pytest
import os
from src.syn_reports.commands.user_project_access_report import UserProjectAccessReport
@pytest.fixture(scope='session')
def syn_user(syn_client):
return syn_client.getUserProfile(os.environ.get('SYNAPSE_USERNAME'))
def assert_user_success_from_print(capsys, *users):
captured = capsy... | tests/syn_reports/commands/user_project_access_report/test_user_project_access_report.py | import pytest
import os
from src.syn_reports.commands.user_project_access_report import UserProjectAccessReport
@pytest.fixture(scope='session')
def syn_user(syn_client):
return syn_client.getUserProfile(os.environ.get('SYNAPSE_USERNAME'))
def assert_user_success_from_print(capsys, *users):
captured = capsy... | 0.314787 | 0.267686 |
class RubiksCube:
# init a Rubicks Cube as a list of 54 ints
def __init__(self):
cube = []
for i in range(1, 55):
cube.append(i)
self.cube = cube
# check if cube is finished
def isFinished(self):
for i in range(1, 55):
if self.cube[i] !=... | cube.py | class RubiksCube:
# init a Rubicks Cube as a list of 54 ints
def __init__(self):
cube = []
for i in range(1, 55):
cube.append(i)
self.cube = cube
# check if cube is finished
def isFinished(self):
for i in range(1, 55):
if self.cube[i] !=... | 0.220888 | 0.618809 |
from flask import Flask
import redis
import json
from ...service.entity.book import Book
from ...exception.exception import BookAlreadyExistsException
app = Flask(__name__)
BOOK_COUNTER = "book_counter"
BOOK_ID_PREFIX = "book_"
class BookRepository:
def __init__(self):
self.db = redis.Redis(host = "red... | Aplikacja_Webowa_Etap_3/sixth_app/src/service/repositories/book_repository.py | from flask import Flask
import redis
import json
from ...service.entity.book import Book
from ...exception.exception import BookAlreadyExistsException
app = Flask(__name__)
BOOK_COUNTER = "book_counter"
BOOK_ID_PREFIX = "book_"
class BookRepository:
def __init__(self):
self.db = redis.Redis(host = "red... | 0.4206 | 0.138229 |
import torch
import torch.nn as nn
# locals
from .utils import OneHotEncode
from .encoders import SENNEncoder, StyleEncoder, VAEEncoder
from .decoders import SENNDecoder
class SENNConceptizer(nn.Module):
"""Class to reproduce Senn conceptizer architecture
Args:
n_concepts: number of concepts
... | SENN/conceptizers.py | import torch
import torch.nn as nn
# locals
from .utils import OneHotEncode
from .encoders import SENNEncoder, StyleEncoder, VAEEncoder
from .decoders import SENNDecoder
class SENNConceptizer(nn.Module):
"""Class to reproduce Senn conceptizer architecture
Args:
n_concepts: number of concepts
... | 0.933484 | 0.427397 |
from django import forms
from allauth.account.forms import SignupForm
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.core.validators import MaxValueValidator, MinValueValidator
from .models import CustomUser
from .models import Booking
from .models import Contact
from .models import ... | my_spotless_app/forms.py | from django import forms
from allauth.account.forms import SignupForm
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.core.validators import MaxValueValidator, MinValueValidator
from .models import CustomUser
from .models import Booking
from .models import Contact
from .models import ... | 0.538498 | 0.081703 |
import torch.nn as nn
import torch
import torchvision.models as models
class TotalGenLoss(nn.Module):
def __init__(self, is_cuda):
super(TotalGenLoss, self).__init__()
self.vgg = VGGContent()
if is_cuda:
self.vgg = self.vgg.cuda()
def forward(self, org_image, gen_image):
... | models.py | import torch.nn as nn
import torch
import torchvision.models as models
class TotalGenLoss(nn.Module):
def __init__(self, is_cuda):
super(TotalGenLoss, self).__init__()
self.vgg = VGGContent()
if is_cuda:
self.vgg = self.vgg.cuda()
def forward(self, org_image, gen_image):
... | 0.938039 | 0.453262 |
import pprint
import re # noqa: F401
import six
class Intervention(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the ... | mm_power_sdk_python/models/intervention.py | import pprint
import re # noqa: F401
import six
class Intervention(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the ... | 0.754282 | 0.226698 |
def rainRightJust():
rainfile = open("rainfall.txt","r")
outfile = open("rainfallRightJust.txt","w")
for aLine in rainfile:
values = aLine.split()
cityNames=values[0]
numbers=values[1]
outfile.write("%+25s %+5s \n" % (cityNames,numbers))
rainfile.close()
outfile.clo... | COS120/LABS/LAB09/LAB09.py | def rainRightJust():
rainfile = open("rainfall.txt","r")
outfile = open("rainfallRightJust.txt","w")
for aLine in rainfile:
values = aLine.split()
cityNames=values[0]
numbers=values[1]
outfile.write("%+25s %+5s \n" % (cityNames,numbers))
rainfile.close()
outfile.clo... | 0.160266 | 0.194731 |
import mariadb
import hashlib
import os
# set by other programs
PASSWORD = ""
# sets up a connection to the db
def getconn():
connection = mariadb.connect(user="root", host="mariadb", password=PASSWORD, autocommit=True)
cur = connection.cursor()
cur.execute("USE TLIS;")
cur.close()
return connection
# executes... | app/manager.py |
import mariadb
import hashlib
import os
# set by other programs
PASSWORD = ""
# sets up a connection to the db
def getconn():
connection = mariadb.connect(user="root", host="mariadb", password=PASSWORD, autocommit=True)
cur = connection.cursor()
cur.execute("USE TLIS;")
cur.close()
return connection
# executes... | 0.193948 | 0.186188 |
TWEET_EXPANSION = "attachments.poll_ids,attachments.media_keys,author_id,geo.place_id,in_reply_to_user_id,referenced_tweets.id,entities.mentions.username,referenced_tweets.id.author_id"
SPACE_EXPANSION = "invited_user_ids,speaker_ids,creator_id,host_ids"
LIST_EXPANSION = "owner_id"
PINNED_TWEET_EXPANSION = "pinned_twee... | pytweet/constants.py | TWEET_EXPANSION = "attachments.poll_ids,attachments.media_keys,author_id,geo.place_id,in_reply_to_user_id,referenced_tweets.id,entities.mentions.username,referenced_tweets.id.author_id"
SPACE_EXPANSION = "invited_user_ids,speaker_ids,creator_id,host_ids"
LIST_EXPANSION = "owner_id"
PINNED_TWEET_EXPANSION = "pinned_twee... | 0.337859 | 0.23456 |
from flask import Flask
from sqlalchemy import Column, Integer, String, Float, DateTime, Boolean
from database import Base
import settings
import stripe
import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = settings.DB_URL
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = settings.TRACK_MODIFICATI... | models.py | from flask import Flask
from sqlalchemy import Column, Integer, String, Float, DateTime, Boolean
from database import Base
import settings
import stripe
import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = settings.DB_URL
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = settings.TRACK_MODIFICATI... | 0.632049 | 0.081813 |
## The script can be run with Python 3.6 or higher version.
## The script requires 'requests' library to make the API calls.
import time
import common
headers = {"Content-Type" : "application/vnd.netbackup+json;version=4.0"}
# Perform bulk restore
def perform_bulk_restore(baseurl, token, bulk_backup_job_id, worklo... | recipes/python/backup-restore/vm_restore.py |
## The script can be run with Python 3.6 or higher version.
## The script requires 'requests' library to make the API calls.
import time
import common
headers = {"Content-Type" : "application/vnd.netbackup+json;version=4.0"}
# Perform bulk restore
def perform_bulk_restore(baseurl, token, bulk_backup_job_id, worklo... | 0.510985 | 0.110735 |
import numpy as np
import os
import torch
import torchvision.models as models
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader
import sys
import math
import torch.nn.init as init
import logging
from torch.nn.par... | DVC/net.py | import numpy as np
import os
import torch
import torchvision.models as models
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader
import sys
import math
import torch.nn.init as init
import logging
from torch.nn.par... | 0.598547 | 0.355747 |
from boto import exception
from django.core.exceptions import ValidationError
from flask import request
from rest_framework import status as http_status
import addons.myminio.settings as settings
from addons.base import generic_views
from addons.myminio import SHORT_NAME, FULL_NAME
from addons.myminio import utils
fro... | StorageAddon/osf.io/addon/views.py | from boto import exception
from django.core.exceptions import ValidationError
from flask import request
from rest_framework import status as http_status
import addons.myminio.settings as settings
from addons.base import generic_views
from addons.myminio import SHORT_NAME, FULL_NAME
from addons.myminio import utils
fro... | 0.431345 | 0.049245 |
import pubmed_parser as pp
def test_parsing():
article_path = "PMC4266334.xml"
abs_phars = pp.parse_pubmed_paragraph(article_path, all_paragraph=True,
section='abs',
subscpt=["", ""],
... | tests/test_paragraph_parsing.py | import pubmed_parser as pp
def test_parsing():
article_path = "PMC4266334.xml"
abs_phars = pp.parse_pubmed_paragraph(article_path, all_paragraph=True,
section='abs',
subscpt=["", ""],
... | 0.619932 | 0.633779 |
#Biblioteca para crear la interfaz gráfica
import tkinter as tk
#Función para correr un comando
from subprocess import call
#Módulo para crear hilos
import threading
#Módulo para interactuar con el sistema operativo
import os
#Módulo para obtener el tipo de archivo
import mimetypes
#Módulo para acceder a las variables... | menu.py | #Biblioteca para crear la interfaz gráfica
import tkinter as tk
#Función para correr un comando
from subprocess import call
#Módulo para crear hilos
import threading
#Módulo para interactuar con el sistema operativo
import os
#Módulo para obtener el tipo de archivo
import mimetypes
#Módulo para acceder a las variables... | 0.087024 | 0.244431 |
__author__ = "<NAME> <<EMAIL>>"
import datetime
import os
import xml.etree.ElementTree as ElementTree
from dateutil import parser
from icalendar import Calendar, Event
import requests
class Convert():
def __init__(self, filename):
self.filename = filename
def get_subjects(self):
result = []
... | convert.py | __author__ = "<NAME> <<EMAIL>>"
import datetime
import os
import xml.etree.ElementTree as ElementTree
from dateutil import parser
from icalendar import Calendar, Event
import requests
class Convert():
def __init__(self, filename):
self.filename = filename
def get_subjects(self):
result = []
... | 0.258139 | 0.089177 |
from util.plans import Leg
class DNASeqLeg(Leg):
primary_handles = [
"Yeast Library",
"Plasmid Library",
"Zymoprepped sample",
"Exonucleased sample",
"Template",
"Fragment",
"Gel",
"qPCR sample in",
"qPCR s... | menagerie/util/dna_seq_legs.py | from util.plans import Leg
class DNASeqLeg(Leg):
primary_handles = [
"Yeast Library",
"Plasmid Library",
"Zymoprepped sample",
"Exonucleased sample",
"Template",
"Fragment",
"Gel",
"qPCR sample in",
"qPCR s... | 0.622689 | 0.374104 |
import pandas as pd
from ....Trade.Strategy.Cta.DyST_TraceFocus import *
from ....Trade.Strategy.DyStockCtaBase import *
from ....Trade.DyStockStrategyBase import *
class DyStockDataFocusAnalysisUtility(object):
"""
热点分析工具类
这个类有点特别,会借助DyST_FocusTrace类
"""
class DummyCtaEngine:
def... | Stock/Data/Utility/Other/DyStockDataFocusAnalysisUtility.py | import pandas as pd
from ....Trade.Strategy.Cta.DyST_TraceFocus import *
from ....Trade.Strategy.DyStockCtaBase import *
from ....Trade.DyStockStrategyBase import *
class DyStockDataFocusAnalysisUtility(object):
"""
热点分析工具类
这个类有点特别,会借助DyST_FocusTrace类
"""
class DummyCtaEngine:
def... | 0.354321 | 0.209268 |
# ----------------------------------------------------------------------
# Imports
# ----------------------------------------------------------------------
import SUAVE
from SUAVE.Core import Units , Data
from .Lithium_Ion import Lithium_Ion
from SUAVE.Methods.Power.Battery.Cell_Cycle_Models.LiNiMnCoO2_cell_cycle... | SUAVE/SUAVE-2.5.0/trunk/SUAVE/Components/Energy/Storages/Batteries/Constant_Mass/Lithium_Ion_LiNiMnCoO2_18650.py |
# ----------------------------------------------------------------------
# Imports
# ----------------------------------------------------------------------
import SUAVE
from SUAVE.Core import Units , Data
from .Lithium_Ion import Lithium_Ion
from SUAVE.Methods.Power.Battery.Cell_Cycle_Models.LiNiMnCoO2_cell_cycle... | 0.84228 | 0.303796 |
import aiohttp
import pytest
from kopf.clients.auth import APIContext, reauthenticated_request
from kopf.clients.errors import APIClientResponseError, check_response
@reauthenticated_request
async def get_it(url: str, *, context: APIContext) -> None:
response = await context.session.get(url)
await check_resp... | tests/k8s/test_errors.py | import aiohttp
import pytest
from kopf.clients.auth import APIContext, reauthenticated_request
from kopf.clients.errors import APIClientResponseError, check_response
@reauthenticated_request
async def get_it(url: str, *, context: APIContext) -> None:
response = await context.session.get(url)
await check_resp... | 0.4856 | 0.285612 |
import locale
_supported = ['aa_DJ', 'aa_DJ.UTF-8', 'aa_ER', 'aa_<EMAIL>', 'aa_ET',
'af_ZA', 'af_ZA.UTF-8', 'am_ET', 'an_ES', 'an_ES.UTF-8', 'ar_AE',
'ar_AE.UTF-8', 'ar_BH', 'ar_BH.UTF-8', 'ar_DZ', 'ar_DZ.UTF-8',
'ar_EG', 'ar_EG.UTF-8', 'ar_IN', 'ar_IQ', 'ar_IQ.UTF-8', 'ar_JO'... | mwlib/_locale.py | import locale
_supported = ['aa_DJ', 'aa_DJ.UTF-8', 'aa_ER', 'aa_<EMAIL>', 'aa_ET',
'af_ZA', 'af_ZA.UTF-8', 'am_ET', 'an_ES', 'an_ES.UTF-8', 'ar_AE',
'ar_AE.UTF-8', 'ar_BH', 'ar_BH.UTF-8', 'ar_DZ', 'ar_DZ.UTF-8',
'ar_EG', 'ar_EG.UTF-8', 'ar_IN', 'ar_IQ', 'ar_IQ.UTF-8', 'ar_JO'... | 0.269133 | 0.056314 |
import datetime
import json
import os
from typing import List
from tabulate import tabulate
from testcase import TestCase
from testcase_file import TestCaseFile
def test_case_to_json(o: TestCase):
return o.to_json()
class Report:
def __init__(self, test_case_files: List[TestCaseFile], log_dir: str):
... | report.py | import datetime
import json
import os
from typing import List
from tabulate import tabulate
from testcase import TestCase
from testcase_file import TestCaseFile
def test_case_to_json(o: TestCase):
return o.to_json()
class Report:
def __init__(self, test_case_files: List[TestCaseFile], log_dir: str):
... | 0.320396 | 0.306864 |
import numpy
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import LSTM
from keras.callbacks import ModelCheckpoint,EarlyStopping
from keras.utils import np_utils
# load ascii text and covert to lowercase
filename = "Shelock Holmes-Hounds of Baskev... | Book-Generation /Code.py | import numpy
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import LSTM
from keras.callbacks import ModelCheckpoint,EarlyStopping
from keras.utils import np_utils
# load ascii text and covert to lowercase
filename = "Shelock Holmes-Hounds of Baskev... | 0.793306 | 0.346818 |
import os
import time
import requests
import sys
import subprocess
try:
import ipapi
except ImportError:
os.system("pip install ipapi")
opt = "\nHack/> "
ip = "\nEnter host: "
def cls():
os.system("clear")
class color:
org = '\033[33m'
End = '\033[0m'
def main():
cls()
print("--------[ Hack... | hack.py | import os
import time
import requests
import sys
import subprocess
try:
import ipapi
except ImportError:
os.system("pip install ipapi")
opt = "\nHack/> "
ip = "\nEnter host: "
def cls():
os.system("clear")
class color:
org = '\033[33m'
End = '\033[0m'
def main():
cls()
print("--------[ Hack... | 0.06271 | 0.10004 |
""" utils """
import os
import sys
import time
import math
import json
import stat
from datetime import datetime
from collections import Counter
import numpy as np
import mindspore.common.dtype as mstype
from mindspore import load_checkpoint, load_param_into_net, save_checkpoint, Tensor, Parameter
from mindspore.common... | research/cv/yolox/src/util.py | """ utils """
import os
import sys
import time
import math
import json
import stat
from datetime import datetime
from collections import Counter
import numpy as np
import mindspore.common.dtype as mstype
from mindspore import load_checkpoint, load_param_into_net, save_checkpoint, Tensor, Parameter
from mindspore.common... | 0.553023 | 0.284191 |
import pytest
from models import Grid, Position
from core.exceptions import OutOfBoundsError, InvalidGridCoordinates
class TestGrid(object):
def test_grid_x_str_value_error(self):
with pytest.raises(ValueError):
Grid('foo', 2)
def test_grid_y_str_value_error(self):
with pytest.ra... | models/test_grid.py | import pytest
from models import Grid, Position
from core.exceptions import OutOfBoundsError, InvalidGridCoordinates
class TestGrid(object):
def test_grid_x_str_value_error(self):
with pytest.raises(ValueError):
Grid('foo', 2)
def test_grid_y_str_value_error(self):
with pytest.ra... | 0.824568 | 0.703753 |
import unittest
from checkov.terraform.checks.resource.gcp.GoogleBigQueryDatasetPublicACL import check
from checkov.common.models.enums import CheckResult
class TestBigQueryDatasetPublicACL(unittest.TestCase):
def test_failure_special_group(self):
resource_conf = {"dataset_id": ["example_dataset"],
... | tests/terraform/checks/resource/gcp/test_GoogleBigQueryDatasetPublicACL.py | import unittest
from checkov.terraform.checks.resource.gcp.GoogleBigQueryDatasetPublicACL import check
from checkov.common.models.enums import CheckResult
class TestBigQueryDatasetPublicACL(unittest.TestCase):
def test_failure_special_group(self):
resource_conf = {"dataset_id": ["example_dataset"],
... | 0.555676 | 0.478529 |
import os
import re
RULE_REGEX = re.compile(r'(.+): (\d+)-(\d+) or (\d+)-(\d+)')
DEPARTURE_REGEX = re.compile(r'^departure')
def is_valid(value, rule1, rule2):
return (rule1[0] <= value <= rule1[1]) or (rule2[0] <= value <= rule2[1])
def filter_tickets(tickets, rules):
error_rate = 0
valid_tickets = []... | 2020/day16.py | import os
import re
RULE_REGEX = re.compile(r'(.+): (\d+)-(\d+) or (\d+)-(\d+)')
DEPARTURE_REGEX = re.compile(r'^departure')
def is_valid(value, rule1, rule2):
return (rule1[0] <= value <= rule1[1]) or (rule2[0] <= value <= rule2[1])
def filter_tickets(tickets, rules):
error_rate = 0
valid_tickets = []... | 0.354321 | 0.441673 |
import nltk
from nltk import TweetTokenizer
import string
import re
import numpy as np
class TextProcessor:
"""TextProcessor
This class is to help automate text processing for the analysis
of unstructured text data to be used for text mining and NLP tasks.
The main NLP librar... | src/text_processing/text_processor.py | import nltk
from nltk import TweetTokenizer
import string
import re
import numpy as np
class TextProcessor:
"""TextProcessor
This class is to help automate text processing for the analysis
of unstructured text data to be used for text mining and NLP tasks.
The main NLP librar... | 0.600657 | 0.295516 |
import jwt
import os
from flask import request, jsonify
from functools import wraps
from config import ENABLE_OBT_OAUTH, AUTH_CLIENT_SECRET_KEY, \
AUTH_CLIENT_AUDIENCE
def get_token():
try:
bearer, authorization = request.headers['Authorization'].split()
if 'bearer' not in bearer.lower():
... | cube-builder-aws/cube_builder_aws/utils/auth.py | import jwt
import os
from flask import request, jsonify
from functools import wraps
from config import ENABLE_OBT_OAUTH, AUTH_CLIENT_SECRET_KEY, \
AUTH_CLIENT_AUDIENCE
def get_token():
try:
bearer, authorization = request.headers['Authorization'].split()
if 'bearer' not in bearer.lower():
... | 0.303113 | 0.042503 |
from typing import List, Tuple
from bson import ObjectId, errors
from fastapi import Depends, FastAPI, HTTPException, Query, status
from motor.motor_asyncio import AsyncIOMotorClient, AsyncIOMotorDatabase
from chapter6.mongodb.models import (
PostDB,
PostCreate,
PostPartialUpdate,
)
app = FastAPI()
motor... | chapter6/mongodb/app.py | from typing import List, Tuple
from bson import ObjectId, errors
from fastapi import Depends, FastAPI, HTTPException, Query, status
from motor.motor_asyncio import AsyncIOMotorClient, AsyncIOMotorDatabase
from chapter6.mongodb.models import (
PostDB,
PostCreate,
PostPartialUpdate,
)
app = FastAPI()
motor... | 0.740737 | 0.113776 |
from .keys_and_values import KeysAndValues, deduplicate
class Dictish:
def __init__(self, key_value_pairs=None):
"""
Creates a new Dictish.
>>> Dictish()
Dictish()
Given a sequence of key-value pairs, the input is deduplicated on the keys.
>>> Dictish([("a", 1), ... | src/dictish/dictish.py | from .keys_and_values import KeysAndValues, deduplicate
class Dictish:
def __init__(self, key_value_pairs=None):
"""
Creates a new Dictish.
>>> Dictish()
Dictish()
Given a sequence of key-value pairs, the input is deduplicated on the keys.
>>> Dictish([("a", 1), ... | 0.787237 | 0.539529 |
import numpy as np
from sklearn.neighbors import KernelDensity
from ..utils.smoothing import bspline
def density_estimation(sample, X, h, kernel="epanechnikov"):
"""Kernel Density Estimation over the sample in domain X.
Routine for `sklearn.neighbors.KernelDensity`.
Args:
sample (np.array): Sam... | spd_trading/utils/density.py | import numpy as np
from sklearn.neighbors import KernelDensity
from ..utils.smoothing import bspline
def density_estimation(sample, X, h, kernel="epanechnikov"):
"""Kernel Density Estimation over the sample in domain X.
Routine for `sklearn.neighbors.KernelDensity`.
Args:
sample (np.array): Sam... | 0.961144 | 0.91611 |
import glob
import os
import shutil
import tempfile
from resource_management.core import shell
from resource_management.core.logger import Logger
from resource_management.core.exceptions import Fail
from resource_management.core.resources.system import Execute
from resource_management.core.resources.system import Dire... | ambari-server/src/main/resources/stacks/ADH/1.4/services/OOZIE/package/scripts/oozie_server_upgrade.py | import glob
import os
import shutil
import tempfile
from resource_management.core import shell
from resource_management.core.logger import Logger
from resource_management.core.exceptions import Fail
from resource_management.core.resources.system import Execute
from resource_management.core.resources.system import Dire... | 0.345657 | 0.083404 |
from abc import ABC, abstractmethod
import copy
class Oracle(ABC):
""" An abstract interface of functions.
`Oracle` provides a unified interface for defining optimization
objectives, or building function approximators, etc.
The user would want to implement the following methods:
... | rl/core/oracles/oracle.py |
from abc import ABC, abstractmethod
import copy
class Oracle(ABC):
""" An abstract interface of functions.
`Oracle` provides a unified interface for defining optimization
objectives, or building function approximators, etc.
The user would want to implement the following methods:
... | 0.858244 | 0.680534 |
from discord.ext import commands
import discord
from typing import Union
import asyncio
def embed_to_string(embed: discord.Embed) -> str:
"""Convert a embed to a string"""
string = ""
if embed.author:
string = f'{embed.author.name}\n'
if embed.title:
string += f'{embed.title}\n'
i... | cogs/utils/context.py | from discord.ext import commands
import discord
from typing import Union
import asyncio
def embed_to_string(embed: discord.Embed) -> str:
"""Convert a embed to a string"""
string = ""
if embed.author:
string = f'{embed.author.name}\n'
if embed.title:
string += f'{embed.title}\n'
i... | 0.625552 | 0.128416 |
# 告诉解释器用 utf-8编码去读取源码,因为可能有中文
# -*- coding: utf-8 -*-
print("hello world again")
answer = 42
name = "DengXiaoBai"
print(answer)
# ----------------print---------------
print('string1','string2','string3')
print(111.222222)
print('print can print number without \'\',like this:',1111)
print('print can print any var',... | helloworld.py |
# 告诉解释器用 utf-8编码去读取源码,因为可能有中文
# -*- coding: utf-8 -*-
print("hello world again")
answer = 42
name = "DengXiaoBai"
print(answer)
# ----------------print---------------
print('string1','string2','string3')
print(111.222222)
print('print can print number without \'\',like this:',1111)
print('print can print any var',... | 0.120258 | 0.155335 |
import abc
import numpy as np
try:
from . import bases # Only works when imported as a package.
except (ValueError, SystemError):
import parsimony.algorithms.bases as bases # When run as a program.
from parsimony.utils import check_arrays
import parsimony.utils.consts as consts
import parsimony.functions.pe... | parsimony/algorithms/utils.py | import abc
import numpy as np
try:
from . import bases # Only works when imported as a package.
except (ValueError, SystemError):
import parsimony.algorithms.bases as bases # When run as a program.
from parsimony.utils import check_arrays
import parsimony.utils.consts as consts
import parsimony.functions.pe... | 0.522202 | 0.320542 |
import os
import time
import random
def cls():
# Limpar tela
os.system('cls' if os.name == 'nt' else 'clear')
def Intro():
# Introdução do jogo
print("=*" * 20)
print(f"{'Jogo da Adivinhação':^40}")
print("=*" * 20)
time.sleep(2)
cls()
print("=*" * 20)
print(f"{'Tente adivinha... | Projetos/jogo_adivinhacao.py | import os
import time
import random
def cls():
# Limpar tela
os.system('cls' if os.name == 'nt' else 'clear')
def Intro():
# Introdução do jogo
print("=*" * 20)
print(f"{'Jogo da Adivinhação':^40}")
print("=*" * 20)
time.sleep(2)
cls()
print("=*" * 20)
print(f"{'Tente adivinha... | 0.234319 | 0.212988 |
import json
import logging
from optparse import OptionParser
import copy
import sys
import spplib.sdk.client as client
logging.basicConfig()
logger = logging.getLogger('logger')
logger.setLevel(logging.INFO)
parser = OptionParser()
parser.add_option("--user", dest="username", help="SPP Username")
parser.add_option("-... | samples/registervsnap.py |
import json
import logging
from optparse import OptionParser
import copy
import sys
import spplib.sdk.client as client
logging.basicConfig()
logger = logging.getLogger('logger')
logger.setLevel(logging.INFO)
parser = OptionParser()
parser.add_option("--user", dest="username", help="SPP Username")
parser.add_option("-... | 0.158956 | 0.067332 |
import ast
import asyncio
import tokenize
import io
import sys
from contextlib import redirect_stdout
__author__ = "Zylanx"
class OutputExprRewriter(ast.NodeTransformer):
"""
OutputExprRewriter: This transformer runs through every top level statement and wraps them in
so they... | eval_ast_gen.py | import ast
import asyncio
import tokenize
import io
import sys
from contextlib import redirect_stdout
__author__ = "Zylanx"
class OutputExprRewriter(ast.NodeTransformer):
"""
OutputExprRewriter: This transformer runs through every top level statement and wraps them in
so they... | 0.296552 | 0.302797 |
from __future__ import print_function
from twitchstream.outputvideo import TwitchBufferedOutputStream
from twitchstream.chat import TwitchChatStream
import argparse
import time
import numpy as np
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
required = parser.add_argument_gro... | examples/color.py | from __future__ import print_function
from twitchstream.outputvideo import TwitchBufferedOutputStream
from twitchstream.chat import TwitchChatStream
import argparse
import time
import numpy as np
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
required = parser.add_argument_gro... | 0.449876 | 0.107813 |
import importlib
import math
from collections import defaultdict
from itertools import chain
from pathlib import Path
import numpy as np
import pandas as pd
import tensorflow as tf
from transformers import BertTokenizerFast
from common import ModelType
from data import ProtestaData
from models import SequenceClassifi... | inference.py | import importlib
import math
from collections import defaultdict
from itertools import chain
from pathlib import Path
import numpy as np
import pandas as pd
import tensorflow as tf
from transformers import BertTokenizerFast
from common import ModelType
from data import ProtestaData
from models import SequenceClassifi... | 0.464416 | 0.239188 |
__all__ = [
"BasicLinter",
]
from beet import Context
from tokenstream import set_location
from mecha import (
AstCommand,
AstSelector,
Diagnostic,
DiagnosticCollection,
Mecha,
Reducer,
rule,
)
def beet_default(ctx: Context):
mc = ctx.inject(Mecha)
mc.lint.extend(BasicLinter... | mecha/contrib/lint_basic.py | __all__ = [
"BasicLinter",
]
from beet import Context
from tokenstream import set_location
from mecha import (
AstCommand,
AstSelector,
Diagnostic,
DiagnosticCollection,
Mecha,
Reducer,
rule,
)
def beet_default(ctx: Context):
mc = ctx.inject(Mecha)
mc.lint.extend(BasicLinter... | 0.542863 | 0.160792 |
from torch.utils.data import Dataset
import pymongo
import json
from collections import OrderedDict
import logging
logger = logging.getLogger(__name__)
class MongoWrapper:
"""
Load single turn Q,A data
"""
def __init__(self, config_path, filter_func=None):
"""
1. Mong... | libs/mongo_wrapper.py | from torch.utils.data import Dataset
import pymongo
import json
from collections import OrderedDict
import logging
logger = logging.getLogger(__name__)
class MongoWrapper:
"""
Load single turn Q,A data
"""
def __init__(self, config_path, filter_func=None):
"""
1. Mong... | 0.546617 | 0.171408 |
from __future__ import print_function
import sys
import argparse
DEFAULT = 8
#Argv voodoo so Kivy does not take over the world of arguments
argv = sys.argv[1:]
sys.argv = sys.argv[0]
parser = argparse.ArgumentParser(description='Read a QRcode as binary data')
#Converting arguments
parser.add_argument('filename', he... | binterpret.py | from __future__ import print_function
import sys
import argparse
DEFAULT = 8
#Argv voodoo so Kivy does not take over the world of arguments
argv = sys.argv[1:]
sys.argv = sys.argv[0]
parser = argparse.ArgumentParser(description='Read a QRcode as binary data')
#Converting arguments
parser.add_argument('filename', he... | 0.366703 | 0.089216 |
import tensorflow as tf
import numpy as np
from .net import Net
class VAE(Net):
def __init__(self, dil=1, latent_dim=128):
self.weights = {}
self.trainable = {}
self.dil = dil
self.latent_dim = latent_dim
def conv(self, name, inp, ksz, stride=1, bias=True, relu='relu', dil=1... | prdepth/net/VAE.py | import tensorflow as tf
import numpy as np
from .net import Net
class VAE(Net):
def __init__(self, dil=1, latent_dim=128):
self.weights = {}
self.trainable = {}
self.dil = dil
self.latent_dim = latent_dim
def conv(self, name, inp, ksz, stride=1, bias=True, relu='relu', dil=1... | 0.868325 | 0.509459 |
import numpy as np
from sklearn.base import clone
from ._utils_boot import boot_manual, draw_weights
from ._utils import fit_predict, fit_predict_proba, tune_grid_search
def fit_iivm(y, x, d, z,
learner_g, learner_m, learner_r, all_smpls, dml_procedure, score,
n_rep=1, g0_params=None, g1_pa... | doubleml/tests/_utils_iivm_manual.py | import numpy as np
from sklearn.base import clone
from ._utils_boot import boot_manual, draw_weights
from ._utils import fit_predict, fit_predict_proba, tune_grid_search
def fit_iivm(y, x, d, z,
learner_g, learner_m, learner_r, all_smpls, dml_procedure, score,
n_rep=1, g0_params=None, g1_pa... | 0.422028 | 0.292725 |
from classtime.logging import logging
logging = logging.getLogger(__name__) # pylint: disable=C0103
import re
class Schedule(object):
"""Represents a 5-day week of 24-hour days
Each day is split into 48 thirty-minute blocks
"""
NUM_BLOCKS = 24*2
"""Number of blocks in one day"""
NUM_DAYS = 5... | classtime/brain/scheduling/schedule.py | from classtime.logging import logging
logging = logging.getLogger(__name__) # pylint: disable=C0103
import re
class Schedule(object):
"""Represents a 5-day week of 24-hour days
Each day is split into 48 thirty-minute blocks
"""
NUM_BLOCKS = 24*2
"""Number of blocks in one day"""
NUM_DAYS = 5... | 0.66061 | 0.261549 |
from torch import optim
from torch.nn import functional as F
import torch
from dataset.factory import DatasetModule
from domain.base import Module, Hyperparameters
from domain.metadata import Metadata
from model.factory import ModelModule
from logger import logger
from trainer.base import TrainerBase
from trainer.cnn_... | trainer/factory.py | from torch import optim
from torch.nn import functional as F
import torch
from dataset.factory import DatasetModule
from domain.base import Module, Hyperparameters
from domain.metadata import Metadata
from model.factory import ModelModule
from logger import logger
from trainer.base import TrainerBase
from trainer.cnn_... | 0.773388 | 0.288231 |
import matplotlib.pyplot as plt
# Importing the Keras libraries and packages
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
from keras.layers import Dropout
# Initialising the CNN
classifier = Se... | cnn.py | import matplotlib.pyplot as plt
# Importing the Keras libraries and packages
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
from keras.layers import Dropout
# Initialising the CNN
classifier = Se... | 0.915259 | 0.667825 |
from oslo_config import cfg
from oslo_config import types
from oslo_log import log as logging
from congress.cfg_validator import parsing
from congress.tests import base
LOG = logging.getLogger(__name__)
OPT_TEST = {
u'positional': False, u'kind': u'BoolOpt',
u'deprecated_reason': None,
u'help': u'Enable... | congress/tests/cfg_validator/test_parsing.py | from oslo_config import cfg
from oslo_config import types
from oslo_log import log as logging
from congress.cfg_validator import parsing
from congress.tests import base
LOG = logging.getLogger(__name__)
OPT_TEST = {
u'positional': False, u'kind': u'BoolOpt',
u'deprecated_reason': None,
u'help': u'Enable... | 0.557845 | 0.198006 |
import BaseHTTPServer, SimpleHTTPServer
import ssl
import os
import base64
import threading
import sys
import random
import gzip
import io
# Config
PORT = 8000
CERT_FILE = '../server.pem'
currCmd = ""
logFileName = '../logs/logs.txt'
log_file = ""
class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
# Cust... | HBS_Server/www/HBS_Server.py |
import BaseHTTPServer, SimpleHTTPServer
import ssl
import os
import base64
import threading
import sys
import random
import gzip
import io
# Config
PORT = 8000
CERT_FILE = '../server.pem'
currCmd = ""
logFileName = '../logs/logs.txt'
log_file = ""
class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
# Cust... | 0.131912 | 0.043855 |
import os
from spack import *
class Mvdtool(CMakePackage):
"""MVD3 neuroscience file format parser and tool"""
homepage = "https://github.com/BlueBrain/MVDTool"
url = "https://github.com/BlueBrain/MVDTool.git"
git = "https://github.com/BlueBrain/MVDTool.git"
version('develop', git=ur... | var/spack/repos/builtin/packages/mvdtool/package.py |
import os
from spack import *
class Mvdtool(CMakePackage):
"""MVD3 neuroscience file format parser and tool"""
homepage = "https://github.com/BlueBrain/MVDTool"
url = "https://github.com/BlueBrain/MVDTool.git"
git = "https://github.com/BlueBrain/MVDTool.git"
version('develop', git=ur... | 0.349977 | 0.115986 |
import argparse
import datetime
import pathlib
import sys
import torch, torch.utils.tensorboard
import tqdm
import yaml
import model
import dataset
def main(mel_dir, embed_dir, dest_dir, config_path, model_path, weight_path):
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
config = yaml... | vc3/training.py | import argparse
import datetime
import pathlib
import sys
import torch, torch.utils.tensorboard
import tqdm
import yaml
import model
import dataset
def main(mel_dir, embed_dir, dest_dir, config_path, model_path, weight_path):
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
config = yaml... | 0.469277 | 0.129595 |
import numpy as np
from sklearn.model_selection import StratifiedShuffleSplit
from xgboost import XGBClassifier
class ConvenientXGBClassifier(XGBClassifier):
"""
XGBClassifier which has a `validation_fraction` parameter for splitting off a validation set just like i
SGDClassifier. In this class it's a fit... | python/handwritten_baseline/pipeline/model/classifier_clustering/xgboost.py | import numpy as np
from sklearn.model_selection import StratifiedShuffleSplit
from xgboost import XGBClassifier
class ConvenientXGBClassifier(XGBClassifier):
"""
XGBClassifier which has a `validation_fraction` parameter for splitting off a validation set just like i
SGDClassifier. In this class it's a fit... | 0.935139 | 0.527317 |
from Individual import *
class Random_Problem:
def __init__(self):
pass
# Searches for solution to 8-puzzle through random technique
def random_solve(self, state):
print("\nSolving Randomly...")
if state.is_goal():
print("Root is solution! ", end='')
... | Random_Problem.py | from Individual import *
class Random_Problem:
def __init__(self):
pass
# Searches for solution to 8-puzzle through random technique
def random_solve(self, state):
print("\nSolving Randomly...")
if state.is_goal():
print("Root is solution! ", end='')
... | 0.50415 | 0.341706 |
import sys
import importlib
from pathlib import Path
from typing import Dict, List, Tuple
from types import ModuleType
from pii_manager import PiiEnum
from .exception import InvArgException
# Folder for language-independent tasks
TASK_ANY = "any"
# Name of the list that holds the pii tasks at each module
_LISTNAME ... | pii-manager/src/pii_manager/helper/taskdict.py | import sys
import importlib
from pathlib import Path
from typing import Dict, List, Tuple
from types import ModuleType
from pii_manager import PiiEnum
from .exception import InvArgException
# Folder for language-independent tasks
TASK_ANY = "any"
# Name of the list that holds the pii tasks at each module
_LISTNAME ... | 0.509764 | 0.167491 |
import os
import logging
# Imports: third party
import pandas as pd
def save_mrns_and_csns_csv(
staging_dir: str,
hd5_dir: str,
adt: str,
first_mrn_index: int,
last_mrn_index: int,
overwrite_hd5: bool,
):
"""
Get unique MRNs and CSNs from ADT and save to patients.csv.
:param stag... | tensorize/utils.py | import os
import logging
# Imports: third party
import pandas as pd
def save_mrns_and_csns_csv(
staging_dir: str,
hd5_dir: str,
adt: str,
first_mrn_index: int,
last_mrn_index: int,
overwrite_hd5: bool,
):
"""
Get unique MRNs and CSNs from ADT and save to patients.csv.
:param stag... | 0.41834 | 0.298696 |
import torch as to
from copy import deepcopy
from sbi.inference import SNPE_C
from sbi import utils
import pyrado
from pyrado.sampling.sbi_embeddings import (
LastStepEmbedding,
)
from pyrado.algorithms.meta.npdr import NPDR
from pyrado.sampling.sbi_rollout_sampler import RolloutSamplerForSBI
from pyrado.environme... | Pyrado/scripts/training/qq-su_npdr_sim2sim.py | import torch as to
from copy import deepcopy
from sbi.inference import SNPE_C
from sbi import utils
import pyrado
from pyrado.sampling.sbi_embeddings import (
LastStepEmbedding,
)
from pyrado.algorithms.meta.npdr import NPDR
from pyrado.sampling.sbi_rollout_sampler import RolloutSamplerForSBI
from pyrado.environme... | 0.703651 | 0.251033 |
import re
import random
import hashlib
import base64
from iota import AsciiTrytesCodec
from config import TRITLI_SALT, SHORT_URL_LENGTH, SHORT_URL_CHARACTER_SET
# careful here: changes made here, will not be backwards compatible
def get_random_id():
return ''.join(random.SystemRandom().choice(SHORT_URL_CHARACTER... | src/util/util.py | import re
import random
import hashlib
import base64
from iota import AsciiTrytesCodec
from config import TRITLI_SALT, SHORT_URL_LENGTH, SHORT_URL_CHARACTER_SET
# careful here: changes made here, will not be backwards compatible
def get_random_id():
return ''.join(random.SystemRandom().choice(SHORT_URL_CHARACTER... | 0.404625 | 0.14016 |
import multiprocessing
import boto3
from kinesis.producer import AsyncProducer
class GEAsyncProducer(AsyncProducer):
"""
Overriden AsyncProducer from kinesis-python package.
Provides the ability to change the client setup as well, specifically the
endpoint_url.
"""
# https://github.com/NerdWa... | kinesis_conducer/producers/producer.py | import multiprocessing
import boto3
from kinesis.producer import AsyncProducer
class GEAsyncProducer(AsyncProducer):
"""
Overriden AsyncProducer from kinesis-python package.
Provides the ability to change the client setup as well, specifically the
endpoint_url.
"""
# https://github.com/NerdWa... | 0.767908 | 0.189128 |
import logging
import numpy as np
import rasterio
from skimage import exposure
from tqdm import tqdm
from tqdm.contrib.logging import logging_redirect_tqdm
from satproc.utils import sliding_windows
__author__ = "<NAME>"
__copyright__ = "Dymaxion Labs"
__license__ = "Apache-2.0"
_logger = logging.getLogger(__name__)... | src/satproc/histogram.py | import logging
import numpy as np
import rasterio
from skimage import exposure
from tqdm import tqdm
from tqdm.contrib.logging import logging_redirect_tqdm
from satproc.utils import sliding_windows
__author__ = "<NAME>"
__copyright__ = "Dymaxion Labs"
__license__ = "Apache-2.0"
_logger = logging.getLogger(__name__)... | 0.709422 | 0.273957 |
from neomodel import db
from abc import ABC, abstractmethod, abstractproperty
from typing import List
__all__ = ['centrality_algs', 'AbstractGraphAlg']
class AbstractGraphAlg(ABC):
def __init__(self, processor, algorithm, min_val=0):
self.processor = processor
self.algorithm = algorithm
... | src/api/graph_algs/centrality.py | from neomodel import db
from abc import ABC, abstractmethod, abstractproperty
from typing import List
__all__ = ['centrality_algs', 'AbstractGraphAlg']
class AbstractGraphAlg(ABC):
def __init__(self, processor, algorithm, min_val=0):
self.processor = processor
self.algorithm = algorithm
... | 0.871775 | 0.283719 |
import torch
import torch.nn as nn
import torchvision
__all__ = ['AlexNet', 'alexnet']
model_urls = {
'alexnet': 'https://download.pytorch.org/models/alexnet-owt-4df8aa71.pth',
}
class AlexNet(nn.Module):
def __init__(self, taskcla):
super(AlexNet, self).__init__()
self.taskcla = taskcla
... | LargeScale/networks/alexnet_hat.py | import torch
import torch.nn as nn
import torchvision
__all__ = ['AlexNet', 'alexnet']
model_urls = {
'alexnet': 'https://download.pytorch.org/models/alexnet-owt-4df8aa71.pth',
}
class AlexNet(nn.Module):
def __init__(self, taskcla):
super(AlexNet, self).__init__()
self.taskcla = taskcla
... | 0.867162 | 0.38292 |
from flask import Flask, render_template, request, flash, jsonify
from flask_sqlalchemy import SQLAlchemy
import psycopg2 # pip install psycopg2
import psycopg2.extras
from geoalchemy2 import Geometry
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:thanhnho@localhost/phun... | app.py | from flask import Flask, render_template, request, flash, jsonify
from flask_sqlalchemy import SQLAlchemy
import psycopg2 # pip install psycopg2
import psycopg2.extras
from geoalchemy2 import Geometry
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:thanhnho@localhost/phun... | 0.243822 | 0.066116 |
import json
import urllib2
import time
import matplotlib.pyplot as plt
import sys
CONF = {
'sensor': "192.168.11.7:8080", # ESP8266 (IP fixed/static assigned on DHCP server/router)
# 'sensor': "192.168.11.13:80", # Arduino Yun (IP not fixed...)
'interval_update': 20.,
'interval_timeout': 3.,
'log_file... | Yun_SHT31_WiFi_REST/Yun_ESP8266_SHT31_WiFi_REST.py | import json
import urllib2
import time
import matplotlib.pyplot as plt
import sys
CONF = {
'sensor': "192.168.11.7:8080", # ESP8266 (IP fixed/static assigned on DHCP server/router)
# 'sensor': "192.168.11.13:80", # Arduino Yun (IP not fixed...)
'interval_update': 20.,
'interval_timeout': 3.,
'log_file... | 0.169646 | 0.156041 |
import torch
from torch import nn
class BCE_VIRAT(nn.Module):
def __init__(self, reduction="mean", hard_thres=-1):
"""
:param hard_thres:
-1:软标签损失,直接基于标注中的软标签计算BECLoss;
>0:硬标签损失,将标签大于hard_thres的置为1,否则为0;
"""
super(BCE_VIRAT, self).__init__()
... | slowfast/models/loss_virat.py | import torch
from torch import nn
class BCE_VIRAT(nn.Module):
def __init__(self, reduction="mean", hard_thres=-1):
"""
:param hard_thres:
-1:软标签损失,直接基于标注中的软标签计算BECLoss;
>0:硬标签损失,将标签大于hard_thres的置为1,否则为0;
"""
super(BCE_VIRAT, self).__init__()
... | 0.867892 | 0.343562 |
import unittest
from shardingpy.exception import SQLParsingException
from shardingpy.parsing.lexer.dialect.mysql import MySQLLexer
from shardingpy.parsing.lexer.lexer import Lexer
from shardingpy.parsing.lexer.token import *
class LexerTestCase(unittest.TestCase):
dictionary = Dictionary()
def test_next_tok... | tests/parsing/lexer/test_lexer.py | import unittest
from shardingpy.exception import SQLParsingException
from shardingpy.parsing.lexer.dialect.mysql import MySQLLexer
from shardingpy.parsing.lexer.lexer import Lexer
from shardingpy.parsing.lexer.token import *
class LexerTestCase(unittest.TestCase):
dictionary = Dictionary()
def test_next_tok... | 0.624179 | 0.486941 |
import json
data = '''
[
{
"name":"Alena",
"count":100
},
{
"name":"Levon",
"count":97
},
{
"name":"Shakira",
"count":96
},
{
"name":"Keerah",
"count":95
},
{
"name":"Anesu",
"count":92
},
{
"name":"Zishan",
... | Walkthru_13/testcode.py | import json
data = '''
[
{
"name":"Alena",
"count":100
},
{
"name":"Levon",
"count":97
},
{
"name":"Shakira",
"count":96
},
{
"name":"Keerah",
"count":95
},
{
"name":"Anesu",
"count":92
},
{
"name":"Zishan",
... | 0.159872 | 0.248854 |
from typing import Callable, Generic, TypeVar, Union, Any, Optional, cast, overload
T = TypeVar("T") # Success type
E = TypeVar("E") # Error type
F = TypeVar("F")
U = TypeVar("U")
class Result(Generic[T, E]):
"""
A simple `Result` type inspired by Rust.
Not all methods (https://doc.rust-lang.org/std/... | result/result.py | from typing import Callable, Generic, TypeVar, Union, Any, Optional, cast, overload
T = TypeVar("T") # Success type
E = TypeVar("E") # Error type
F = TypeVar("F")
U = TypeVar("U")
class Result(Generic[T, E]):
"""
A simple `Result` type inspired by Rust.
Not all methods (https://doc.rust-lang.org/std/... | 0.951278 | 0.484929 |
import optparse, os, shutil, subprocess, sys, tempfile
def stop_err(msg):
sys.stderr.write(msg)
sys.exit()
def cleanup_before_exit(tmp_dir):
if tmp_dir and os.path.exists(tmp_dir):
shutil.rmtree(tmp_dir)
def main():
#Parse command line
parser = optparse.OptionParser()
parser.add_opti... | tools/soap/soapdenovo_configuration.py | import optparse, os, shutil, subprocess, sys, tempfile
def stop_err(msg):
sys.stderr.write(msg)
sys.exit()
def cleanup_before_exit(tmp_dir):
if tmp_dir and os.path.exists(tmp_dir):
shutil.rmtree(tmp_dir)
def main():
#Parse command line
parser = optparse.OptionParser()
parser.add_opti... | 0.117092 | 0.156427 |
from collections import deque
from re import S
import yaml
import numpy as np
with open('config.yml', 'r') as ymlfile:
cfg = yaml.load(ymlfile, Loader=yaml.FullLoader)
seed = cfg['setup']['seed']
ymlfile.close()
np.random.seed(seed)
import tensorflow as tf
from tensorflow.keras.optimizers import Adam
tf... | agent.py | from collections import deque
from re import S
import yaml
import numpy as np
with open('config.yml', 'r') as ymlfile:
cfg = yaml.load(ymlfile, Loader=yaml.FullLoader)
seed = cfg['setup']['seed']
ymlfile.close()
np.random.seed(seed)
import tensorflow as tf
from tensorflow.keras.optimizers import Adam
tf... | 0.742141 | 0.290893 |
import numpy
import numpy.testing
import algopy
def utpm2dirs(u):
"""
Vbar = utpm2dirs(u)
where u is an UTPM instance with
u.data.shape = (D,P) + shp
and V.shape == shp + (P,D)
"""
axes = tuple( numpy.arange(2,u.data.ndim))+ (1,0)
Vbar = u.data.transpose(axes)
return Vbar
def ... | algopy/utils.py | import numpy
import numpy.testing
import algopy
def utpm2dirs(u):
"""
Vbar = utpm2dirs(u)
where u is an UTPM instance with
u.data.shape = (D,P) + shp
and V.shape == shp + (P,D)
"""
axes = tuple( numpy.arange(2,u.data.ndim))+ (1,0)
Vbar = u.data.transpose(axes)
return Vbar
def ... | 0.571049 | 0.649829 |
from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse, Http404
from .forms import VacancyAddForm, ApplicantProfileEdit, EmployerProfileEdit, sortChoice
from .models import ApplicantProfile, EmployerProfile, Vacancy
from django.contrib.auth.forms import UserCreationFor... | swf/workfair/views.py | from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse, Http404
from .forms import VacancyAddForm, ApplicantProfileEdit, EmployerProfileEdit, sortChoice
from .models import ApplicantProfile, EmployerProfile, Vacancy
from django.contrib.auth.forms import UserCreationFor... | 0.27406 | 0.062046 |
from __future__ import annotations
import logging
import shutil
import tarfile
import tempfile
import uuid
from contextlib import contextmanager
from datetime import datetime
from pathlib import Path
from typing import Text, ContextManager, Tuple, Union
import rasa.utils.common
import rasa.shared.utils.io
from rasa.e... | rasa/engine/storage/local_model_storage.py | from __future__ import annotations
import logging
import shutil
import tarfile
import tempfile
import uuid
from contextlib import contextmanager
from datetime import datetime
from pathlib import Path
from typing import Text, ContextManager, Tuple, Union
import rasa.utils.common
import rasa.shared.utils.io
from rasa.e... | 0.883958 | 0.195498 |