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 sys
import unittest
import tempfile
import shutil
from pkg_resources import resource_filename #@UnresolvedImport
from pyPaSWAS.Core.Exceptions import InvalidOptionException
from pyPaSWAS import pypaswasall
class Test(unittest.TestCase):
''' Runs the application as the end-user would, testing for correct e... | implementations/warris2018/pyPaSWAS/Core/test/test_pypaswasall.py | import sys
import unittest
import tempfile
import shutil
from pkg_resources import resource_filename #@UnresolvedImport
from pyPaSWAS.Core.Exceptions import InvalidOptionException
from pyPaSWAS import pypaswasall
class Test(unittest.TestCase):
''' Runs the application as the end-user would, testing for correct e... | 0.36659 | 0.305892 |
# Libraries and Global Variables
# Standard
import sys
import os
if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import unittest
# Third-party
import mock
# Local
sys.path.append(os.getcwd())
import rabbitmq_class
import version
__version__ = version.__version__
class SetupExchange(objec... | test/unit/rabbitmq_class/rabbitmqpub_setupexchange.py | # Libraries and Global Variables
# Standard
import sys
import os
if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import unittest
# Third-party
import mock
# Local
sys.path.append(os.getcwd())
import rabbitmq_class
import version
__version__ = version.__version__
class SetupExchange(objec... | 0.423696 | 0.308451 |
import copy
import unittest
import os
import subprocess
import sys
import tempfile
from screwdrivercd.screwdriver.metadata import Metadata
class ScrewdriverTestCase(unittest.TestCase):
"""
Test case class for testing screwdriver wrappers that perform common operations like saving/restoring the environment
... | tests/__init__.py | import copy
import unittest
import os
import subprocess
import sys
import tempfile
from screwdrivercd.screwdriver.metadata import Metadata
class ScrewdriverTestCase(unittest.TestCase):
"""
Test case class for testing screwdriver wrappers that perform common operations like saving/restoring the environment
... | 0.279435 | 0.118003 |
import pandas as pd
import numpy as np
import warnings
import sklearn.metrics as mt
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import LabelEncoder
from sklearn.neighbors import KNeighborsClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_tes... | titanic.py | import pandas as pd
import numpy as np
import warnings
import sklearn.metrics as mt
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import LabelEncoder
from sklearn.neighbors import KNeighborsClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_tes... | 0.735642 | 0.687663 |
import sys
from PyQt5.QtCore import Qt
from qtpy.QtGui import QDoubleValidator
from qtpy.QtWidgets import (
QCheckBox,
QFormLayout,
QLineEdit,
QVBoxLayout,
QComboBox,
QSlider,
QDialogButtonBox,
QDialog
)
MIN_FS = 100
MAX_FS = 1000
STEP_SIZE = 100
MIN_ALLOWABLE_FS = 0.0001
DECIMAL_PLACES... | mnelab/dialogs/npydialog.py | import sys
from PyQt5.QtCore import Qt
from qtpy.QtGui import QDoubleValidator
from qtpy.QtWidgets import (
QCheckBox,
QFormLayout,
QLineEdit,
QVBoxLayout,
QComboBox,
QSlider,
QDialogButtonBox,
QDialog
)
MIN_FS = 100
MAX_FS = 1000
STEP_SIZE = 100
MIN_ALLOWABLE_FS = 0.0001
DECIMAL_PLACES... | 0.533154 | 0.129403 |
from webthing import Property, Thing, Value
from internet_monitor_webthing.connectivity_monitor import ConnectionInfo, ConnectionLog, ConnectionTester
import tornado.ioloop
class InternetConnectivityMonitorWebthing(Thing):
# regarding capabilities refer https://iot.mozilla.org/schemas
# there is also another... | internet_monitor_webthing/connectivity_monitor_webthing.py | from webthing import Property, Thing, Value
from internet_monitor_webthing.connectivity_monitor import ConnectionInfo, ConnectionLog, ConnectionTester
import tornado.ioloop
class InternetConnectivityMonitorWebthing(Thing):
# regarding capabilities refer https://iot.mozilla.org/schemas
# there is also another... | 0.667364 | 0.199952 |
from __future__ import print_function
from keras.models import Model, model_from_json
from keras.layers import Dense, Activation, Dropout, Input, Embedding
from keras.layers import CuDNNLSTM as LSTM
from keras.optimizers import RMSprop, Adam
from keras.utils.data_utils import get_file
from keras.callbacks import Mod... | generate.py |
from __future__ import print_function
from keras.models import Model, model_from_json
from keras.layers import Dense, Activation, Dropout, Input, Embedding
from keras.layers import CuDNNLSTM as LSTM
from keras.optimizers import RMSprop, Adam
from keras.utils.data_utils import get_file
from keras.callbacks import Mod... | 0.629547 | 0.214794 |
import requests
import os
import re
import pandas as pd
from bs4 import BeautifulSoup
import json
from globals import teams_list
roster_url = 'https://www.espn.com/college-football/team/roster/_/id/'
schedule_url = 'https://www.espn.com/college-football/team/schedule/_/id/'
def scrape_roster(team_id):
roster_re... | fetch_stats.py | import requests
import os
import re
import pandas as pd
from bs4 import BeautifulSoup
import json
from globals import teams_list
roster_url = 'https://www.espn.com/college-football/team/roster/_/id/'
schedule_url = 'https://www.espn.com/college-football/team/schedule/_/id/'
def scrape_roster(team_id):
roster_re... | 0.184547 | 0.174551 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from utils.feature_engineer import count_categorical
from utils.feature_engineer import agg_numeric
from utils.feature_engineer import missing_values_table
from utils.feature_engineer import light_gbm
import w... | scripts/feature_engineer.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from utils.feature_engineer import count_categorical
from utils.feature_engineer import agg_numeric
from utils.feature_engineer import missing_values_table
from utils.feature_engineer import light_gbm
import w... | 0.542863 | 0.421314 |
import pprint
import re # noqa: F401
import six
class ResourceServerIdentityHeadersJwt(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribut... | python/packages/ibm_application_gateway/config/resource_server_identity_headers_jwt.py | import pprint
import re # noqa: F401
import six
class ResourceServerIdentityHeadersJwt(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribut... | 0.778397 | 0.201656 |
import unittest
import os
class TestCodegen(unittest.TestCase):
"""
Test class around generating code from peripheral schemas.
"""
maxDiff = None
def gen_peripheral_template(self, template):
"""
Generates all I2C peripheral files for a given template.
"""
os.system... | test/test_codegen.py |
import unittest
import os
class TestCodegen(unittest.TestCase):
"""
Test class around generating code from peripheral schemas.
"""
maxDiff = None
def gen_peripheral_template(self, template):
"""
Generates all I2C peripheral files for a given template.
"""
os.system... | 0.507324 | 0.495484 |
__author__ = 'iambocai'
import sys, urllib2, base64, json, time,socket
step = 60
ip = socket.gethostname()
ts = int(time.time())
keys = ('messages_ready', 'messages_unacknowledged')
rates = ('ack', 'deliver', 'deliver_get', 'publish')
request = urllib2.Request("http://%s:15672/api/queues" %ip)
# see #issue4
base64... | falcon-monit-scripts/rabbitmq/rabbitmq-monitor.py |
__author__ = 'iambocai'
import sys, urllib2, base64, json, time,socket
step = 60
ip = socket.gethostname()
ts = int(time.time())
keys = ('messages_ready', 'messages_unacknowledged')
rates = ('ack', 'deliver', 'deliver_get', 'publish')
request = urllib2.Request("http://%s:15672/api/queues" %ip)
# see #issue4
base64... | 0.095766 | 0.100702 |
# Editor
import wx
import os
import tempfile
def mktemp():
fd, name = tempfile.mkstemp()
os.close(fd)
return name
class Editor(wx.Frame):
def __init__(self, parent, id, title, size=(600, 500)):
wx.Frame.__init__(self, parent, id, title, size=size)
# variables
self.modify = F... | caid-gui/Editor.py |
# Editor
import wx
import os
import tempfile
def mktemp():
fd, name = tempfile.mkstemp()
os.close(fd)
return name
class Editor(wx.Frame):
def __init__(self, parent, id, title, size=(600, 500)):
wx.Frame.__init__(self, parent, id, title, size=size)
# variables
self.modify = F... | 0.309337 | 0.080574 |
import psycopg2, psycopg2.extras, tokens
from datetime import datetime
from flask import g, Blueprint, request, make_response, jsonify
from flask_login import login_required, current_user
from config import app, Config
auths = Blueprint('auths', __name__)
def generate(user_id):
token = tokens.generate(user_id, g.... | auths.py | import psycopg2, psycopg2.extras, tokens
from datetime import datetime
from flask import g, Blueprint, request, make_response, jsonify
from flask_login import login_required, current_user
from config import app, Config
auths = Blueprint('auths', __name__)
def generate(user_id):
token = tokens.generate(user_id, g.... | 0.353651 | 0.071819 |
from django.shortcuts import render, redirect
from django.template import loader
from django.http import HttpResponseRedirect
from django.views import generic
from .models import Code, User
from django.urls import reverse_lazy
from django.views.generic.edit import CreateView, DeleteView
from django.contrib.auth ... | CodeMate/views.py | from django.shortcuts import render, redirect
from django.template import loader
from django.http import HttpResponseRedirect
from django.views import generic
from .models import Code, User
from django.urls import reverse_lazy
from django.views.generic.edit import CreateView, DeleteView
from django.contrib.auth ... | 0.264643 | 0.048994 |
from tensorflow.keras import backend as K
from tensorflow.keras.layers import Layer
import tensorflow as tf
import os, cv2
import numpy as np
import pandas as pd
import random, tqdm
import seaborn as sns
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings("ignore")
from tensorflow import keras
im... | src/segnetlayerkeras.py | from tensorflow.keras import backend as K
from tensorflow.keras.layers import Layer
import tensorflow as tf
import os, cv2
import numpy as np
import pandas as pd
import random, tqdm
import seaborn as sns
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings("ignore")
from tensorflow import keras
im... | 0.866472 | 0.470737 |
from itertools import combinations, product
from math import comb
from typing import List, Optional
from pymatgen.analysis.interface_reactions import InterfacialReactivity
from pymatgen.core.composition import Element
from pymatgen.entries.computed_entries import ComputedEntry
from tqdm.auto import tqdm
from rxn_netw... | src/rxn_network/enumerators/minimize.py | from itertools import combinations, product
from math import comb
from typing import List, Optional
from pymatgen.analysis.interface_reactions import InterfacialReactivity
from pymatgen.core.composition import Element
from pymatgen.entries.computed_entries import ComputedEntry
from tqdm.auto import tqdm
from rxn_netw... | 0.934522 | 0.374276 |
class Player():
"""docstring for Player"""
def __init__(self):
super(Player, self).__init__()
self.inventory = []
class Scene():
"""docstring for Scene"""
def __init__(self, intro, keywords, player=None, condition=None, success=None, fail=None):
super(Scene, self).__init__()
... | game.py | class Player():
"""docstring for Player"""
def __init__(self):
super(Player, self).__init__()
self.inventory = []
class Scene():
"""docstring for Scene"""
def __init__(self, intro, keywords, player=None, condition=None, success=None, fail=None):
super(Scene, self).__init__()
... | 0.480479 | 0.226527 |
import copy
import unittest
import verify_config
class VerifyConfigTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.schema = {"properties": {"ingress": {"type": "object"},
"egress": {"type": "object"},
"routingTable": {"... | Emulator/verify_config_tests.py |
import copy
import unittest
import verify_config
class VerifyConfigTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.schema = {"properties": {"ingress": {"type": "object"},
"egress": {"type": "object"},
"routingTable": {"... | 0.562657 | 0.332527 |
import os
import re
import sys
import bz2
import bct
import math
import random
import pickle
import numpy as np
import scipy as sp
import pandas as pd
import dionysus as d
import networkx as nx
import cpnet as cpa
import gensim.utils as gu
import gensim.models as gm
import gensim.matutils as gmat
import gensim.parsing.... | module/wiki.py | import os
import re
import sys
import bz2
import bct
import math
import random
import pickle
import numpy as np
import scipy as sp
import pandas as pd
import dionysus as d
import networkx as nx
import cpnet as cpa
import gensim.utils as gu
import gensim.models as gm
import gensim.matutils as gmat
import gensim.parsing.... | 0.58676 | 0.130895 |
from civicboom.tests import *
from civicboom.lib.database.get_cached import get_member
from civicboom.model.payment import *
from civicboom.model.meta import Session
from sqlalchemy import or_, and_, not_, null
import copy, datetime, urlparse
class TestPaymentController(TestController):
"""
Tests f... | src/civicboom/tests/functional/test_payment.py | from civicboom.tests import *
from civicboom.lib.database.get_cached import get_member
from civicboom.model.payment import *
from civicboom.model.meta import Session
from sqlalchemy import or_, and_, not_, null
import copy, datetime, urlparse
class TestPaymentController(TestController):
"""
Tests f... | 0.512449 | 0.315736 |
import numpy as np
from sklearn.model_selection import train_test_split
import pandas as pd
from sklearn.preprocessing import StandardScaler
class DualPerceptron:
def __init__(self, kernel, path):
self.kernel = kernel
self.x, self.y = DualPerceptron.get_data(path)
@staticmethod
def get_d... | Dual-Perceptron/dual_perceptron.py | import numpy as np
from sklearn.model_selection import train_test_split
import pandas as pd
from sklearn.preprocessing import StandardScaler
class DualPerceptron:
def __init__(self, kernel, path):
self.kernel = kernel
self.x, self.y = DualPerceptron.get_data(path)
@staticmethod
def get_d... | 0.656988 | 0.453988 |
from aiogram import Bot, types
from aiogram.contrib.middlewares.logging import LoggingMiddleware
from aiogram.dispatcher import Dispatcher
from aiogram.utils.executor import start_webhook
from sqlalchemy import select
from sqlalchemy.orm import Session
from api_parsing.utils import (calculate_time, get_json_from_api,
... | telegram_bot/bot_main.py | from aiogram import Bot, types
from aiogram.contrib.middlewares.logging import LoggingMiddleware
from aiogram.dispatcher import Dispatcher
from aiogram.utils.executor import start_webhook
from sqlalchemy import select
from sqlalchemy.orm import Session
from api_parsing.utils import (calculate_time, get_json_from_api,
... | 0.314787 | 0.096365 |
from DB_Connection import db
import smtplib
import pyttsx3
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from beautifultable import BeautifulTable
from Narrator import Narrator
from Login import User_Name, PIN_Confirmlg
import datetime as T
y = T.datetime.now()
x = y.... | Functionality.py | from DB_Connection import db
import smtplib
import pyttsx3
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from beautifultable import BeautifulTable
from Narrator import Narrator
from Login import User_Name, PIN_Confirmlg
import datetime as T
y = T.datetime.now()
x = y.... | 0.283484 | 0.08472 |
import pickle
from tqdm import tqdm
import pandas as pd
# Read in the datasets
# Player statistics data
path = open(r'C:\Users\charl\Desktop\FantasyFootball\Players\player_stats.pk', 'rb')
player_stats = pickle.load(path)
# results data for name mapping
path = open(r'C:\Users\charl\Desktop\FantasyFootball\Res... | tests/Clean_PlayerStats.py | import pickle
from tqdm import tqdm
import pandas as pd
# Read in the datasets
# Player statistics data
path = open(r'C:\Users\charl\Desktop\FantasyFootball\Players\player_stats.pk', 'rb')
player_stats = pickle.load(path)
# results data for name mapping
path = open(r'C:\Users\charl\Desktop\FantasyFootball\Res... | 0.165054 | 0.193414 |
__author__ = "<NAME> (<EMAIL>)"
import copy
import json
import numpy as np
import scipy.sparse as spsp
from thread2vec.common import get_package_path
def get_data(dataset, scale):
if dataset == "youtube":
item_to_userset_filepath = get_package_path() + "/data_folder/anonymized_data/youtube/item_to_user... | thread2vec/representation/utility.py | __author__ = "<NAME> (<EMAIL>)"
import copy
import json
import numpy as np
import scipy.sparse as spsp
from thread2vec.common import get_package_path
def get_data(dataset, scale):
if dataset == "youtube":
item_to_userset_filepath = get_package_path() + "/data_folder/anonymized_data/youtube/item_to_user... | 0.261897 | 0.182753 |
import sys
import os
import datetime
import argparse
import chardet
import re
import noval.syntax.syntax as syntax
from noval.util import logger
import noval.util.utils as utils
import noval.syntax.lang as lang
import easyplugindev as epd
from easyplugindev import _
def getResourcePath():
from pkg_resources impo... | plugins/CodeCounter/CodeCounter/CodeCounter.py | import sys
import os
import datetime
import argparse
import chardet
import re
import noval.syntax.syntax as syntax
from noval.util import logger
import noval.util.utils as utils
import noval.syntax.lang as lang
import easyplugindev as epd
from easyplugindev import _
def getResourcePath():
from pkg_resources impo... | 0.069498 | 0.096535 |
from elit.utils.io_util import load_json
from elit.common.dataset import TransformDataset
class BinaryClassDataset(TransformDataset):
def load_file(self, filepath: str):
for sample in load_json(filepath):
yield sample
def create_features(sample: dict, tokenizer, max_line_length=128,
... | eclare/baseline/binary/binary_dataset.py | from elit.utils.io_util import load_json
from elit.common.dataset import TransformDataset
class BinaryClassDataset(TransformDataset):
def load_file(self, filepath: str):
for sample in load_json(filepath):
yield sample
def create_features(sample: dict, tokenizer, max_line_length=128,
... | 0.578924 | 0.36441 |
from vendas_project.vendas.models import SaleDetail
from django.db.models import Sum, F, FloatField
''' ------------ '''
q = SaleDetail.objects.filter(sale=1).values('price_sale', 'quantity')
q.aggregate(Sum(F('price_sale') * F('quantity')), output_field=FloatField())
# falhou
''' ------------ '''
# Django 1.8.3
# http... | shell/snippets.py | from vendas_project.vendas.models import SaleDetail
from django.db.models import Sum, F, FloatField
''' ------------ '''
q = SaleDetail.objects.filter(sale=1).values('price_sale', 'quantity')
q.aggregate(Sum(F('price_sale') * F('quantity')), output_field=FloatField())
# falhou
''' ------------ '''
# Django 1.8.3
# http... | 0.350977 | 0.183905 |
import numpy as np
import pytest
import popart
import torch
from op_tester import op_tester
def test_tile(op_tester):
d1 = np.random.rand(2, 4, 3).astype(np.float32)
d2 = np.array([2, 4, 6]).astype(np.int64)
def init_builder(builder):
i1 = builder.addInputTensor(d1)
c = builder.aiOnnx.con... | tests/integration/operators_test/tile_test.py | import numpy as np
import pytest
import popart
import torch
from op_tester import op_tester
def test_tile(op_tester):
d1 = np.random.rand(2, 4, 3).astype(np.float32)
d2 = np.array([2, 4, 6]).astype(np.int64)
def init_builder(builder):
i1 = builder.addInputTensor(d1)
c = builder.aiOnnx.con... | 0.66072 | 0.602325 |
import functools
from typing import Optional
import pytest
from orchestrator.utils.functional import (
as_t,
expand_ranges,
first_available_or_next,
ireplace,
join_cs,
orig,
to_ranges,
)
def test_join_cs():
assert join_cs("") == ""
assert join_cs([]) == ""
assert join_cs(()) ... | test/unit_tests/utils/test_functional.py | import functools
from typing import Optional
import pytest
from orchestrator.utils.functional import (
as_t,
expand_ranges,
first_available_or_next,
ireplace,
join_cs,
orig,
to_ranges,
)
def test_join_cs():
assert join_cs("") == ""
assert join_cs([]) == ""
assert join_cs(()) ... | 0.87787 | 0.797123 |
import json
from copy import deepcopy
import kafka
from mindsdb.integrations.base import StreamIntegration
import mindsdb.interfaces.storage.db as db
from mindsdb_streams import KafkaStream, StreamController, StreamLearningController
class KafkaConnectionChecker:
def __init__(self, **params):
self.conne... | mindsdb/integrations/kafka/kafkadb.py | import json
from copy import deepcopy
import kafka
from mindsdb.integrations.base import StreamIntegration
import mindsdb.interfaces.storage.db as db
from mindsdb_streams import KafkaStream, StreamController, StreamLearningController
class KafkaConnectionChecker:
def __init__(self, **params):
self.conne... | 0.406273 | 0.055849 |
import numpy as np
class Tiling(object):
"""2D rectangular tiling.
Arguments:
limits {list} -- Min and max value tuple for each dimension.
ntiles {iterable} -- Number of tiles for each dimension.
offsets {iterable or None} -- Offset for each tile as multiple of tile width. No offse... | tilings.py | import numpy as np
class Tiling(object):
"""2D rectangular tiling.
Arguments:
limits {list} -- Min and max value tuple for each dimension.
ntiles {iterable} -- Number of tiles for each dimension.
offsets {iterable or None} -- Offset for each tile as multiple of tile width. No offse... | 0.782122 | 0.664731 |
import sys
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from awsglue.context import GlueContext
from awsglue.job import Job
from awsglue.dynamicframe import DynamicFrame
from pyspark.context import SparkContext
from pyspark.sql.functions import unix_timestamp
## @params: [JOB_NAME,S3_C... | exercise1/etl/glue_etl.py | import sys
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from awsglue.context import GlueContext
from awsglue.job import Job
from awsglue.dynamicframe import DynamicFrame
from pyspark.context import SparkContext
from pyspark.sql.functions import unix_timestamp
## @params: [JOB_NAME,S3_C... | 0.500977 | 0.298798 |
import requests
import time
from collections import OrderedDict
import smtplib
from email.mime.text import MIMEText
import os
_ip_checker_list = OrderedDict()
_notifications = set()
def registered_ip_checker(fn):
_ip_checker_list[fn] = None
return fn
def registered_notification(fn):
_notifications.add(f... | src/public_ip_monitor.py | import requests
import time
from collections import OrderedDict
import smtplib
from email.mime.text import MIMEText
import os
_ip_checker_list = OrderedDict()
_notifications = set()
def registered_ip_checker(fn):
_ip_checker_list[fn] = None
return fn
def registered_notification(fn):
_notifications.add(f... | 0.208743 | 0.054174 |
import urllib.parse
import urllib.request
import urllib.error
import json
'''
Below is a sample of currency code's you can use for this program.
United Arab Emirates = AED
United States = USD
Taiwan = TWD
Kenya = KES
Bitcoin = BTC
Ethereum = ETH
Litecoin = LTC
'''
# Enter your own API Key from http://www.alphavantag... | trial.py | import urllib.parse
import urllib.request
import urllib.error
import json
'''
Below is a sample of currency code's you can use for this program.
United Arab Emirates = AED
United States = USD
Taiwan = TWD
Kenya = KES
Bitcoin = BTC
Ethereum = ETH
Litecoin = LTC
'''
# Enter your own API Key from http://www.alphavantag... | 0.474875 | 0.183319 |
import logging
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
logger = logging.getLogger(__name__)
__all__ = ['null_checker', 'non_null_data_args',
'values_in_time', 'plot_what_if']
def values_in_time(obj, t, tau=None):
"""Obtain value(s) of object at time t, or right befor... | cvxportfolio/utils.py | import logging
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
logger = logging.getLogger(__name__)
__all__ = ['null_checker', 'non_null_data_args',
'values_in_time', 'plot_what_if']
def values_in_time(obj, t, tau=None):
"""Obtain value(s) of object at time t, or right befor... | 0.525125 | 0.515498 |
import os
import torch
import click
from torch import nn, optim
from torchvision import transforms
from torch.utils.data import random_split, DataLoader
from ignite.engine import Engine, Events, create_supervised_trainer, create_supervised_evaluator
from ignite.metrics import Accuracy, Precision, Recall, RunningAvera... | cutout/main.py | import os
import torch
import click
from torch import nn, optim
from torchvision import transforms
from torch.utils.data import random_split, DataLoader
from ignite.engine import Engine, Events, create_supervised_trainer, create_supervised_evaluator
from ignite.metrics import Accuracy, Precision, Recall, RunningAvera... | 0.678007 | 0.178669 |
import pandas as pd
from urllib.request import urlopen
import urllib.request
import json
import re
import numpy as np
def catch_nutriment_value(nutri_dict, id_):
''' Catch the value of a nutriment defined by its id_ '''
'''
Input :
nutri_dict(dictionary): contains all nutrients infor... | API_US_agri.py | import pandas as pd
from urllib.request import urlopen
import urllib.request
import json
import re
import numpy as np
def catch_nutriment_value(nutri_dict, id_):
''' Catch the value of a nutriment defined by its id_ '''
'''
Input :
nutri_dict(dictionary): contains all nutrients infor... | 0.431105 | 0.336876 |
from typing import Any, Dict, List, Optional
from ....models.models import Speaker
from ....permissions.permission_helper import has_perm
from ....permissions.permissions import Permissions
from ....shared.exceptions import ActionException, MissingPermission
from ....shared.filters import And, FilterOperator, Or
from ... | openslides_backend/action/actions/speaker/create.py | from typing import Any, Dict, List, Optional
from ....models.models import Speaker
from ....permissions.permission_helper import has_perm
from ....permissions.permissions import Permissions
from ....shared.exceptions import ActionException, MissingPermission
from ....shared.filters import And, FilterOperator, Or
from ... | 0.768907 | 0.16502 |
import random
import unittest
from QNetwork.qkd.diqkd import DIQKDNode, DIQKDSenderNode, DIQKDReceiverNode
from QNetwork.q_network_channels import QState
class QChannelDummy:
pass
class QChannelSpy:
def __init__(self):
self.received_bases = []
def send_epr(self, bases):
self.received_b... | QNetwork/tests/test_diqkd.py | import random
import unittest
from QNetwork.qkd.diqkd import DIQKDNode, DIQKDSenderNode, DIQKDReceiverNode
from QNetwork.q_network_channels import QState
class QChannelDummy:
pass
class QChannelSpy:
def __init__(self):
self.received_bases = []
def send_epr(self, bases):
self.received_b... | 0.713432 | 0.599339 |
import unittest
import numpy as np
from numpy.testing import assert_array_equal
from distarray.externals.six.moves import range
from distarray.testing import import_or_skip, DefaultContextTestCase
from distarray.globalapi.distarray import DistArray
from distarray.globalapi.maps import Distribution
def cleanup_file... | distarray/globalapi/tests/test_distributed_io.py | import unittest
import numpy as np
from numpy.testing import assert_array_equal
from distarray.externals.six.moves import range
from distarray.testing import import_or_skip, DefaultContextTestCase
from distarray.globalapi.distarray import DistArray
from distarray.globalapi.maps import Distribution
def cleanup_file... | 0.480966 | 0.456652 |
import logging
import time
import numpy as np
from . import utils
from . import optimize
from . import diagnosis
from .samplers import latin_sample_n
log = logging.getLogger(__name__)
class ExcursionProblem(object):
def __init__(self, functions, thresholds = [0.0], ndim = 1, bounding_box = None, plot_npoints = No... | excursion/__init__.py | import logging
import time
import numpy as np
from . import utils
from . import optimize
from . import diagnosis
from .samplers import latin_sample_n
log = logging.getLogger(__name__)
class ExcursionProblem(object):
def __init__(self, functions, thresholds = [0.0], ndim = 1, bounding_box = None, plot_npoints = No... | 0.592902 | 0.341418 |
from math import sqrt
class Vector(object):
def __init__(self, coordinates):
try:
if not coordinates:
raise ValueError
self.coordinates = tuple(coordinates)
self.dimension = len(coordinates)
except ValueError:
raise ValueError('The co... | algebra.py | from math import sqrt
class Vector(object):
def __init__(self, coordinates):
try:
if not coordinates:
raise ValueError
self.coordinates = tuple(coordinates)
self.dimension = len(coordinates)
except ValueError:
raise ValueError('The co... | 0.731059 | 0.594316 |
from __future__ import division
import os
import sys
import tempfile
from scipy import stats
from math import isnan, isinf
from numpy import isclose
from subprocess import check_call, call
root = os.path.abspath( sys.argv[ 0 ] )
for i in range( 3 ):
root = os.path.dirname( root )
sys.path.append( os.path.join( ro... | benchmarks/ferret/test.py | from __future__ import division
import os
import sys
import tempfile
from scipy import stats
from math import isnan, isinf
from numpy import isclose
from subprocess import check_call, call
root = os.path.abspath( sys.argv[ 0 ] )
for i in range( 3 ):
root = os.path.dirname( root )
sys.path.append( os.path.join( ro... | 0.225161 | 0.182644 |
import os
# This is needed to make daily_workflow work
os.environ["TZ"] = "UTC"
import gzip
import functools
import json
import random
import shutil
import string
import subprocess
import sys
import tempfile
import time
import unittest
from base64 import b64encode
import psycopg2
from centrifugation import httpt_b... | af/shovel/test_centrifugation.py |
import os
# This is needed to make daily_workflow work
os.environ["TZ"] = "UTC"
import gzip
import functools
import json
import random
import shutil
import string
import subprocess
import sys
import tempfile
import time
import unittest
from base64 import b64encode
import psycopg2
from centrifugation import httpt_b... | 0.307046 | 0.141815 |
import re
from ast import AST, parse
from dataclasses import dataclass
from typing import Dict, Iterator, Optional, Tuple
from breakfast.position import Position
WORD = re.compile(r"\w+|\W+")
@dataclass(order=True)
class Source:
lines: Tuple[str, ...]
module_name: str = "module"
file_name: Optional[s... | breakfast/source.py | import re
from ast import AST, parse
from dataclasses import dataclass
from typing import Dict, Iterator, Optional, Tuple
from breakfast.position import Position
WORD = re.compile(r"\w+|\W+")
@dataclass(order=True)
class Source:
lines: Tuple[str, ...]
module_name: str = "module"
file_name: Optional[s... | 0.85959 | 0.258127 |
import numpy as np
from numpy import random as rnd
import random
from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd
import progressbar
from PopulationClasses import Population
# defining constant integers to make labeling easy
SUS = 0 # susceptible
INF = 1 # infected
REC = 2 # recovered
DE... | runSimulation.py | import numpy as np
from numpy import random as rnd
import random
from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd
import progressbar
from PopulationClasses import Population
# defining constant integers to make labeling easy
SUS = 0 # susceptible
INF = 1 # infected
REC = 2 # recovered
DE... | 0.303113 | 0.593491 |
import os
import collections
import itertools
from . import helpers
__all__ = ('Display',)
class Graphic:
_Visual = collections.namedtuple('Visual', 'dirty ready clean')
__slots__ = ('_io', '_cursor', '_visuals', '_origin', '_width')
def __init__(self, io, cursor):
self._io = io
sel... | macOS/Xcode/Maestral/Maestral/app_packages/survey/display.py | import os
import collections
import itertools
from . import helpers
__all__ = ('Display',)
class Graphic:
_Visual = collections.namedtuple('Visual', 'dirty ready clean')
__slots__ = ('_io', '_cursor', '_visuals', '_origin', '_width')
def __init__(self, io, cursor):
self._io = io
sel... | 0.603231 | 0.355132 |
import pytest
import responses
import mock
from celery.exceptions import Retry
from django.core.cache import cache
from django.test import SimpleTestCase
from django.test import TestCase, override_settings
from pyfakefs.fake_filesystem_unittest import TestCase as FakeFsTestCase
from mii_rss.factories import FeedEntri... | tests/test_mii_rss.py | import pytest
import responses
import mock
from celery.exceptions import Retry
from django.core.cache import cache
from django.test import SimpleTestCase
from django.test import TestCase, override_settings
from pyfakefs.fake_filesystem_unittest import TestCase as FakeFsTestCase
from mii_rss.factories import FeedEntri... | 0.534127 | 0.284651 |
import argparse
from graph4nlp.pytorch.modules.config import get_basic_args
from graph4nlp.pytorch.modules.utils.config_utils import get_yaml_config, update_values
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"--dataset_yaml",
type=str,
default="examples/pyt... | examples/pytorch/semantic_parsing/graph2seq/args.py | import argparse
from graph4nlp.pytorch.modules.config import get_basic_args
from graph4nlp.pytorch.modules.utils.config_utils import get_yaml_config, update_values
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"--dataset_yaml",
type=str,
default="examples/pyt... | 0.538498 | 0.187356 |
from hashlib import sha256
from types import GeneratorType
import xmlsec
from django.http import HttpRequest
from lxml import etree # nosec
from lxml.etree import Element, SubElement # nosec
from structlog.stdlib import get_logger
from authentik.core.exceptions import PropertyMappingExpressionException
from authent... | authentik/providers/saml/processors/assertion.py | from hashlib import sha256
from types import GeneratorType
import xmlsec
from django.http import HttpRequest
from lxml import etree # nosec
from lxml.etree import Element, SubElement # nosec
from structlog.stdlib import get_logger
from authentik.core.exceptions import PropertyMappingExpressionException
from authent... | 0.620852 | 0.18139 |
import errno
import os
import sys
import _psutil_osx
import _psutil_posix
from psutil import _psposix
from psutil.error import AccessDenied, NoSuchProcess, TimeoutExpired
from psutil._compat import namedtuple
from psutil._common import *
__extra__all__ = []
# --- constants
NUM_CPUS = _psutil_osx.get_num_cpus()
BOOT... | Script/psutil-0.5.0/psutil/_psosx.py | import errno
import os
import sys
import _psutil_osx
import _psutil_posix
from psutil import _psposix
from psutil.error import AccessDenied, NoSuchProcess, TimeoutExpired
from psutil._compat import namedtuple
from psutil._common import *
__extra__all__ = []
# --- constants
NUM_CPUS = _psutil_osx.get_num_cpus()
BOOT... | 0.480966 | 0.080792 |
import logging
from pathlib import Path
import numpy as np
from PIL import Image
from proteus.models.base import BaseModel
from proteus.models.base.modelconfigs import (
BaseModelConfig,
BatchingModelConfig,
QuantizationModelConfig,
TritonOptimizationModelConfig,
)
from resizeimage import resizeimage
... | packages/proteus.models.superres/proteus/models/superres/client.py | import logging
from pathlib import Path
import numpy as np
from PIL import Image
from proteus.models.base import BaseModel
from proteus.models.base.modelconfigs import (
BaseModelConfig,
BatchingModelConfig,
QuantizationModelConfig,
TritonOptimizationModelConfig,
)
from resizeimage import resizeimage
... | 0.804367 | 0.152253 |
import os
import json
import time
from textwrap import dedent
from .. import run_nbgrader
from .base import BaseTestApp
from .conftest import notwindows
@notwindows
class TestNbGraderList(BaseTestApp):
def _release(self, assignment, exchange, cache, course_dir, course="abc101"):
self._copy_file(os.path... | nbgrader/tests/apps/test_nbgrader_list.py | import os
import json
import time
from textwrap import dedent
from .. import run_nbgrader
from .base import BaseTestApp
from .conftest import notwindows
@notwindows
class TestNbGraderList(BaseTestApp):
def _release(self, assignment, exchange, cache, course_dir, course="abc101"):
self._copy_file(os.path... | 0.469277 | 0.310133 |
import pandas as pd
import os
from pydub import AudioSegment
#TODO: Make this applicable by terminal
filenames = os.listdir(data_dir)
audio_filenames = []
for filename in filenames:
if ".csv" not in (filename.lower()):
audio_filenames.append(filename)
annotation_dict = {}
for audio_filename in audio_fi... | classifier/scripts/split_files.py | import pandas as pd
import os
from pydub import AudioSegment
#TODO: Make this applicable by terminal
filenames = os.listdir(data_dir)
audio_filenames = []
for filename in filenames:
if ".csv" not in (filename.lower()):
audio_filenames.append(filename)
annotation_dict = {}
for audio_filename in audio_fi... | 0.056633 | 0.088465 |
from huaweicloud_sis.client.asr_client import AsrCustomizationClient
from huaweicloud_sis.bean.asr_request import AsrCustomShortRequest
from huaweicloud_sis.utils import io_utils
import json
from huaweicloud_sis.client.tts_client import TtsCustomizationClient
from huaweicloud_sis.bean.tts_request import TtsCusto... | speech_interaction_demo.py |
from huaweicloud_sis.client.asr_client import AsrCustomizationClient
from huaweicloud_sis.bean.asr_request import AsrCustomShortRequest
from huaweicloud_sis.utils import io_utils
import json
from huaweicloud_sis.client.tts_client import TtsCustomizationClient
from huaweicloud_sis.bean.tts_request import TtsCusto... | 0.146301 | 0.108472 |
# .................................................................................................................
level_dict["cheese"] = {
"scheme": "yellow_scheme",
"size": (11,12,7),
"intro": "cheese",
"... | py/levels/cheese.py |
# .................................................................................................................
level_dict["cheese"] = {
"scheme": "yellow_scheme",
"size": (11,12,7),
"intro": "cheese",
"... | 0.162314 | 0.256937 |
import abc
from common.models.model import Model
from common.models.utils import make_rnn_cell
import tensorflow as tf
import numpy as np
"""
Abstract base class for generative sequence models
"""
class SequenceGenerativeModel(Model):
__metaclass__ = abc.ABCMeta
def __init__(self, hparams, sequence_encoder):
sup... | musicgen/common/models/sequenceGenerativeModel.py | import abc
from common.models.model import Model
from common.models.utils import make_rnn_cell
import tensorflow as tf
import numpy as np
"""
Abstract base class for generative sequence models
"""
class SequenceGenerativeModel(Model):
__metaclass__ = abc.ABCMeta
def __init__(self, hparams, sequence_encoder):
sup... | 0.838084 | 0.473292 |
from collections import Counter
from dataclasses import dataclass
from typing import Tuple, Union
class BitExpr:
def __lt__(self, other):
return repr(self) < repr(other)
@dataclass(frozen=True)
class Bit(BitExpr):
value: Union[bool, str] = 0 # Value should be 0, 1, or a unique name.
def __str_... | bit_algebra.py | from collections import Counter
from dataclasses import dataclass
from typing import Tuple, Union
class BitExpr:
def __lt__(self, other):
return repr(self) < repr(other)
@dataclass(frozen=True)
class Bit(BitExpr):
value: Union[bool, str] = 0 # Value should be 0, 1, or a unique name.
def __str_... | 0.92487 | 0.355132 |
from __future__ import print_function
import sys
import time
from test_example_node import ExampleNodeTester
from ariac_example import ariac_example
import rospy
import rostest
class GripperTester(ExampleNodeTester):
def test(self):
self.comp_class = ariac_example.MyCompetitionClass()
ariac_ex... | test_ariac/test_gripper.py |
from __future__ import print_function
import sys
import time
from test_example_node import ExampleNodeTester
from ariac_example import ariac_example
import rospy
import rostest
class GripperTester(ExampleNodeTester):
def test(self):
self.comp_class = ariac_example.MyCompetitionClass()
ariac_ex... | 0.552298 | 0.441854 |
# 美拍视频下载
import sys
import os
import re
import urlparse
import urllib
import urllib2
import shutil
from BeautifulSoup import BeautifulSoup
path_ts = 'E:\\Share\\ts'
url_prefix = 'http://media-pili.1iptv.com'
url_web = 'http://www.meipai.com/media/575186182'
def find_text(reg, text):
result = re.findall(reg, tex... | meipai.py |
# 美拍视频下载
import sys
import os
import re
import urlparse
import urllib
import urllib2
import shutil
from BeautifulSoup import BeautifulSoup
path_ts = 'E:\\Share\\ts'
url_prefix = 'http://media-pili.1iptv.com'
url_web = 'http://www.meipai.com/media/575186182'
def find_text(reg, text):
result = re.findall(reg, tex... | 0.081926 | 0.056888 |
from django.shortcuts import render
from django.core.paginator import Paginator
from backend.serializers import KindAnimeSerializer, KindSerializer, AnimeSerializer, EpisodeSerializer, UserSerializer, PersonalKindSerializer
from backend.forms import AuthForm, UserCreateForm, MainForm
from django.views.generic import Cr... | skibidi/website/views.py | from django.shortcuts import render
from django.core.paginator import Paginator
from backend.serializers import KindAnimeSerializer, KindSerializer, AnimeSerializer, EpisodeSerializer, UserSerializer, PersonalKindSerializer
from backend.forms import AuthForm, UserCreateForm, MainForm
from django.views.generic import Cr... | 0.333178 | 0.10904 |
from setuptools import distutils
from inspect import getmembers, isfunction
import functools
import glob
import os
import pkgutil
import sys
import types
__all__ = [
'get_python_library',
'get_python_methods',
'wraps',
]
if sys.version_info[0:2] >= (3, 4): # Python v3.4+?
wraps = functools.wraps # ... | gemini/utils/import_util.py | from setuptools import distutils
from inspect import getmembers, isfunction
import functools
import glob
import os
import pkgutil
import sys
import types
__all__ = [
'get_python_library',
'get_python_methods',
'wraps',
]
if sys.version_info[0:2] >= (3, 4): # Python v3.4+?
wraps = functools.wraps # ... | 0.301979 | 0.092688 |
import asyncio
from glob import glob
from typing import Optional
import aiohttp
import pincer
from pincer import Client
from pincer.objects import Embed
from mcoding_bot.config import Config
from mcoding_bot.database import Database
from mcoding_bot.cache import Cache
class Bot(Client):
def __init__(self, confi... | mcoding_bot/bot.py | import asyncio
from glob import glob
from typing import Optional
import aiohttp
import pincer
from pincer import Client
from pincer.objects import Embed
from mcoding_bot.config import Config
from mcoding_bot.database import Database
from mcoding_bot.cache import Cache
class Bot(Client):
def __init__(self, confi... | 0.73029 | 0.112893 |
__author__ = '<NAME>'
__email__ = '<EMAIL>'
import os
import shutil
import json
from uuid import UUID
import mock
from requests.exceptions import ConnectTimeout, ConnectionError as ConnectError
import pytest as pt
from source.app import FinnOwnership, Scraper
from source.util import TrackingError
class TestFinnOw... | tests/app/scrapers/test_finn_ownership.py | __author__ = '<NAME>'
__email__ = '<EMAIL>'
import os
import shutil
import json
from uuid import UUID
import mock
from requests.exceptions import ConnectTimeout, ConnectionError as ConnectError
import pytest as pt
from source.app import FinnOwnership, Scraper
from source.util import TrackingError
class TestFinnOw... | 0.604749 | 0.258853 |
import logging
import os
import shutil
from typing import BinaryIO, Iterator, Optional, List
import requests
from . import crypto, api, utils
from .params import KeeperParams
from .proto import record_pb2
from .vault import KeeperRecord, PasswordRecord, TypedRecord, FileRecord, AttachmentFile
def prepare_attachmen... | keepercommander/attachment.py |
import logging
import os
import shutil
from typing import BinaryIO, Iterator, Optional, List
import requests
from . import crypto, api, utils
from .params import KeeperParams
from .proto import record_pb2
from .vault import KeeperRecord, PasswordRecord, TypedRecord, FileRecord, AttachmentFile
def prepare_attachmen... | 0.561575 | 0.13589 |
from django.shortcuts import render, HttpResponse
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from rest_framework.response import Response
from rest_framework import status
from django.contrib.auth.models import Us... | users/views.py | from django.shortcuts import render, HttpResponse
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from rest_framework.response import Response
from rest_framework import status
from django.contrib.auth.models import Us... | 0.454956 | 0.070977 |
from PyQt5.QtWidgets import QSystemTrayIcon, QAction, QMenu
from PyQt5.QtGui import QIcon
from timer import PomoTimer
from pypresence import Presence
class System_tray():
def __init__(self, tray, app, times, subject, pref_win):
self.times = times
self.main_time = times[0]
self.ap... | tray.py | from PyQt5.QtWidgets import QSystemTrayIcon, QAction, QMenu
from PyQt5.QtGui import QIcon
from timer import PomoTimer
from pypresence import Presence
class System_tray():
def __init__(self, tray, app, times, subject, pref_win):
self.times = times
self.main_time = times[0]
self.ap... | 0.350533 | 0.069668 |
import os
import sys
sys.path.append('../../arl-python')
import numpy as np
import time
import argparse
from arl.image.cleaners import *
from utils import *
def msmfsclean_simplify(dirty, psf, window, gain, thresh, niter, scales, fracthresh, findpeak='CASA'):
assert 0.0 < gain < 2.0
assert niter > 0
as... | c-kernel/test/test_cleaners.py | import os
import sys
sys.path.append('../../arl-python')
import numpy as np
import time
import argparse
from arl.image.cleaners import *
from utils import *
def msmfsclean_simplify(dirty, psf, window, gain, thresh, niter, scales, fracthresh, findpeak='CASA'):
assert 0.0 < gain < 2.0
assert niter > 0
as... | 0.502441 | 0.536313 |
import dataclasses
import enum
import sphinx.application
import sphinx.environment
from typing import *
T = TypeVar('T')
class Converter:
"""
Converters are used to parse and validate directive and global options.
They are used as a more powerful substitute for helper functions declared
in `rst.di... | sphinx_a4doc/contrib/configurator.py | import dataclasses
import enum
import sphinx.application
import sphinx.environment
from typing import *
T = TypeVar('T')
class Converter:
"""
Converters are used to parse and validate directive and global options.
They are used as a more powerful substitute for helper functions declared
in `rst.di... | 0.861494 | 0.412708 |
import asyncio
import unittest.mock
import asynctest
import logging
import os
from functools import wraps
import shortuuid
from yarl import URL
from aio_pika import Connection, connect, Channel, Queue, Exchange
log = logging.getLogger(__name__)
for logger_name in ('pika.channel', 'pika.callback', 'pika.connectio... | tests/__init__.py | import asyncio
import unittest.mock
import asynctest
import logging
import os
from functools import wraps
import shortuuid
from yarl import URL
from aio_pika import Connection, connect, Channel, Queue, Exchange
log = logging.getLogger(__name__)
for logger_name in ('pika.channel', 'pika.callback', 'pika.connectio... | 0.486575 | 0.129706 |
import numpy as np
import cv2
import os
window_title = "The Input Image"
input_image = "input.jpg"
output_image = os.path.basename(__file__)[:-len(".py")] + ".jpg"
HORIZONTAL = 0
VERTICAL = 1
def read_image(file_name=input_image):
img = cv2.imread(file_name)
return img
def display_image(img, window_title=w... | LatestLibrary.py | import numpy as np
import cv2
import os
window_title = "The Input Image"
input_image = "input.jpg"
output_image = os.path.basename(__file__)[:-len(".py")] + ".jpg"
HORIZONTAL = 0
VERTICAL = 1
def read_image(file_name=input_image):
img = cv2.imread(file_name)
return img
def display_image(img, window_title=w... | 0.480722 | 0.235043 |
import sys
import os
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.version_info < (2, 4):
sys.exit("requires python 2.4 and up")
here = os.path.dirname(__file__)
exec(open(os.path.join(here, 'rpyc', 'version.py')).read())
setup(name = "rpyc",
version =... | tests/rpyc-3.2.3/setup.py | import sys
import os
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.version_info < (2, 4):
sys.exit("requires python 2.4 and up")
here = os.path.dirname(__file__)
exec(open(os.path.join(here, 'rpyc', 'version.py')).read())
setup(name = "rpyc",
version =... | 0.284278 | 0.213562 |
from random import randrange
from math import ceil
# Solde du jouueur
solde = 1000
print("\nVotre solde est de:", solde, "$.")
# Jouer tant que le solde du compte nous le permet
game_over = False
while game_over == False:
# Pour le numéro choisi
validation = False
while validation == False:
valid... | tp-tous-au-zcasino/ZCasino.py |
from random import randrange
from math import ceil
# Solde du jouueur
solde = 1000
print("\nVotre solde est de:", solde, "$.")
# Jouer tant que le solde du compte nous le permet
game_over = False
while game_over == False:
# Pour le numéro choisi
validation = False
while validation == False:
valid... | 0.210929 | 0.50293 |
import pytest
import fiona
import fiona.drvsupport
import fiona.meta
from fiona.drvsupport import supported_drivers
from fiona.errors import FionaValueError
from .conftest import requires_gdal2, requires_gdal23, requires_gdal31
from six import string_types
@requires_gdal31
@pytest.mark.parametrize("driver", supported... | tests/test_meta.py | import pytest
import fiona
import fiona.drvsupport
import fiona.meta
from fiona.drvsupport import supported_drivers
from fiona.errors import FionaValueError
from .conftest import requires_gdal2, requires_gdal23, requires_gdal31
from six import string_types
@requires_gdal31
@pytest.mark.parametrize("driver", supported... | 0.415373 | 0.236054 |
import numpy as np
import os
from yt.data_objects.level_sets.api import \
add_validator
from yt.funcs import mylog
from yt.utilities.lib.misc_utilities import \
gravitational_binding_energy
from yt.utilities.physical_constants import \
gravitational_constant_cgs as G
def _future_bound(
clump,
... | yt_p2p/clumps/validators.py | import numpy as np
import os
from yt.data_objects.level_sets.api import \
add_validator
from yt.funcs import mylog
from yt.utilities.lib.misc_utilities import \
gravitational_binding_energy
from yt.utilities.physical_constants import \
gravitational_constant_cgs as G
def _future_bound(
clump,
... | 0.696681 | 0.404978 |
import argparse
from itertools import combinations
import numpy as np
import re
import sys
def read_w2v(w2v_path, word2index, n_dims=300, unk_token="unk"):
"""takes tokens from files and returns word vectors
:param w2v_path: path to pretrained embedding file
:param word2index: Counter of tokens from proc... | python_src/keywords_incorp.py |
import argparse
from itertools import combinations
import numpy as np
import re
import sys
def read_w2v(w2v_path, word2index, n_dims=300, unk_token="unk"):
"""takes tokens from files and returns word vectors
:param w2v_path: path to pretrained embedding file
:param word2index: Counter of tokens from proc... | 0.5564 | 0.515681 |
import pytest
from mongoengine import ValidationError
from kairon.api.models import HttpActionConfigRequest, HttpActionParameters
from kairon.shared.data.data_objects import Slots, SlotMapping
class TestBotModels:
def test_http_action_params_valid(self):
assert HttpActionParameters(key="param1", value="... | tests/unit_test/models/model_test.py | import pytest
from mongoengine import ValidationError
from kairon.api.models import HttpActionConfigRequest, HttpActionParameters
from kairon.shared.data.data_objects import Slots, SlotMapping
class TestBotModels:
def test_http_action_params_valid(self):
assert HttpActionParameters(key="param1", value="... | 0.63307 | 0.453383 |
from ..CommonInterface import CommonInterfaceNsd
import json
import requests
class Nsd(CommonInterfaceNsd):
"""
NSD Management Interfaces
"""
def __init__(self, host, port=4002):
self._host = host
self._port = port
self._base_path = 'http://{0}:{1}'
self._u... | wrappers/SONATAClient/nsd.py | from ..CommonInterface import CommonInterfaceNsd
import json
import requests
class Nsd(CommonInterfaceNsd):
"""
NSD Management Interfaces
"""
def __init__(self, host, port=4002):
self._host = host
self._port = port
self._base_path = 'http://{0}:{1}'
self._u... | 0.583797 | 0.088899 |
from pathlib import Path
from unittest.mock import patch
import pytest
from remove_empty_comment.__main__ import main, transform
def test_integration():
with patch("sys.argv", ["remove-empty-comment"]):
with pytest.raises(SystemExit) as e:
main()
assert e.value.code == 0
with pat... | tests/test_integration.py | from pathlib import Path
from unittest.mock import patch
import pytest
from remove_empty_comment.__main__ import main, transform
def test_integration():
with patch("sys.argv", ["remove-empty-comment"]):
with pytest.raises(SystemExit) as e:
main()
assert e.value.code == 0
with pat... | 0.501709 | 0.387256 |
import threading
import requests
import argparse
import random
import json
import time
import sys
import re
import os
status = {
'sent': 0,
'errors': 0,
}
class youtube:
vid = None
session = None
def __init__(self, vid):
self.vid = vid
self.session = requests.session()
def getPlayerConfig(self):
r = sel... | visualize.py | import threading
import requests
import argparse
import random
import json
import time
import sys
import re
import os
status = {
'sent': 0,
'errors': 0,
}
class youtube:
vid = None
session = None
def __init__(self, vid):
self.vid = vid
self.session = requests.session()
def getPlayerConfig(self):
r = sel... | 0.07153 | 0.080213 |
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import copy
import numpy as np
from torchvision import datasets, transforms
import torch
import random
import csv
from utils.sampling import mnist_iid, mnist_noniid, cifar_iid
from utils.options import args_parser
from models.Update import LocalU... | federated-learning-master/tristan_experiment_MNIST_constant.py |
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import copy
import numpy as np
from torchvision import datasets, transforms
import torch
import random
import csv
from utils.sampling import mnist_iid, mnist_noniid, cifar_iid
from utils.options import args_parser
from models.Update import LocalU... | 0.488283 | 0.470858 |
import os.path
from data.base_dataset import BaseDataset, get_params
from data.image_folder import make_dataset
import torchvision.transforms as transforms
import glob
from PIL import Image
class TextureDataset(BaseDataset):
"""A dataset class for paired image dataset.
It assumes that the directory '/path/... | data/texture_dataset.py | import os.path
from data.base_dataset import BaseDataset, get_params
from data.image_folder import make_dataset
import torchvision.transforms as transforms
import glob
from PIL import Image
class TextureDataset(BaseDataset):
"""A dataset class for paired image dataset.
It assumes that the directory '/path/... | 0.864081 | 0.570152 |
import math
import random
import utils
import operator
required_percepts = ['get_state']
required_actions = ['set_state','set_coloredtrace', 'advance','turnabit','turn_toward']
def average_direction(long_range, actions):
direction = 0
for bird, distance in long_range:
direction += bird.states['dire... | modules/agents/brains/flocking_bird.py |
import math
import random
import utils
import operator
required_percepts = ['get_state']
required_actions = ['set_state','set_coloredtrace', 'advance','turnabit','turn_toward']
def average_direction(long_range, actions):
direction = 0
for bird, distance in long_range:
direction += bird.states['dire... | 0.382257 | 0.431884 |
from __future__ import print_function
import os
import argparse
import socket
import time
import tensorboard_logger as tb_logger
import torch
import torch.optim as optim
import torch.nn as nn
import torch.backends.cudnn as cudnn
import numpy as np
from models import model_dict
from dataset.cifar100 import get_cifar... | train_teacher.py | from __future__ import print_function
import os
import argparse
import socket
import time
import tensorboard_logger as tb_logger
import torch
import torch.optim as optim
import torch.nn as nn
import torch.backends.cudnn as cudnn
import numpy as np
from models import model_dict
from dataset.cifar100 import get_cifar... | 0.753467 | 0.124479 |
from argopandas.downloader import download_async
import os
import urllib.request
import tempfile
from typing import BinaryIO
class PathsDoNotExistError(Exception):
"""
The exception thrown when one or more requested path
does not exist locally and could not be downloaded.
"""
def __init__(self, b... | argopandas/mirror.py | from argopandas.downloader import download_async
import os
import urllib.request
import tempfile
from typing import BinaryIO
class PathsDoNotExistError(Exception):
"""
The exception thrown when one or more requested path
does not exist locally and could not be downloaded.
"""
def __init__(self, b... | 0.802168 | 0.256579 |
import shap
from stratx.ice import friedman_partial_dependence
from stratx import plot_stratpd
from articles.pd.support import synthetic_interaction_data
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from sklearn.ensemble import RandomForestRegressor
np.r... | articles/imp/genfigs/compare_friedman_shap_stratimpact.py | import shap
from stratx.ice import friedman_partial_dependence
from stratx import plot_stratpd
from articles.pd.support import synthetic_interaction_data
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from sklearn.ensemble import RandomForestRegressor
np.r... | 0.357231 | 0.577138 |
import os
import re
from ..google_api import (
GDrive,
GSheets,
GCellType,
)
from .spreadsheet import Spreadsheet
_google_file_id_regex = re.compile(r'^1[a-zA-Z0-9_-]{43}$')
class GSheetsReader(Spreadsheet):
def __init__(self, file, **kwargs):
"""Read a Google Sheets spreadsheet.
... | msl/io/readers/gsheets.py | import os
import re
from ..google_api import (
GDrive,
GSheets,
GCellType,
)
from .spreadsheet import Spreadsheet
_google_file_id_regex = re.compile(r'^1[a-zA-Z0-9_-]{43}$')
class GSheetsReader(Spreadsheet):
def __init__(self, file, **kwargs):
"""Read a Google Sheets spreadsheet.
... | 0.800458 | 0.385722 |
import pyCardDeck
from typing import List
class Gamer:
def __init__(self, name: str):
self.hand = []
self.name = name
def __str__(self):
return self.name
class GamePlace:
def __init__(self, gamers: List[Gamer]):
self.deck = pyCardDeck.Deck(
cards=generate_de... | task1.py | import pyCardDeck
from typing import List
class Gamer:
def __init__(self, name: str):
self.hand = []
self.name = name
def __str__(self):
return self.name
class GamePlace:
def __init__(self, gamers: List[Gamer]):
self.deck = pyCardDeck.Deck(
cards=generate_de... | 0.487307 | 0.251203 |
import sys
import pandas as pd
data = pd.read_csv("schedule_u.csv")
classes = []
with open("whitelist.txt", "r") as infile:
for line in infile:
classes.append(line.strip())
new_csv_16 = pd.DataFrame(columns=["Student ID", "Trimester"] + classes)
new_csv_17 = pd.DataFrame(columns=["Student ID", "Trimester"... | schedule_parser.py | import sys
import pandas as pd
data = pd.read_csv("schedule_u.csv")
classes = []
with open("whitelist.txt", "r") as infile:
for line in infile:
classes.append(line.strip())
new_csv_16 = pd.DataFrame(columns=["Student ID", "Trimester"] + classes)
new_csv_17 = pd.DataFrame(columns=["Student ID", "Trimester"... | 0.071827 | 0.184657 |
from threading import Thread
from nanomsg import Socket, SUB, PUSH, SUB_SUBSCRIBE, SOL_SOCKET, RCVTIMEO
from datetime import datetime
import os
from .datastruct import Event
class ClientMq(object):
def __init__(self, config, ui_event_engine, outgoing_queue):
self._ui_event_engine = ui_event_engine
... | source/common/client_mq.py | from threading import Thread
from nanomsg import Socket, SUB, PUSH, SUB_SUBSCRIBE, SOL_SOCKET, RCVTIMEO
from datetime import datetime
import os
from .datastruct import Event
class ClientMq(object):
def __init__(self, config, ui_event_engine, outgoing_queue):
self._ui_event_engine = ui_event_engine
... | 0.198958 | 0.041307 |
from . import computer
def part1():
"""
The software draws tiles to the screen with output instructions:
every three output instructions specify the x position (distance from the left), y position (distance from the top), and tile id.
0 is an empty tile. No game object appears in this tile.
1 is ... | 2019/days/day13.py | from . import computer
def part1():
"""
The software draws tiles to the screen with output instructions:
every three output instructions specify the x position (distance from the left), y position (distance from the top), and tile id.
0 is an empty tile. No game object appears in this tile.
1 is ... | 0.627723 | 0.752967 |
import subprocess
from typing import Dict, List, Optional, Union
class Stockfish:
""" Integrates the Stockfish chess engine with Python. """
def __init__(
self, path: str = None, depth: int = 2, param: Dict[str, Union[str, int]] = None
):
if param is None:
param = {}
... | stockfish.py |
import subprocess
from typing import Dict, List, Optional, Union
class Stockfish:
""" Integrates the Stockfish chess engine with Python. """
def __init__(
self, path: str = None, depth: int = 2, param: Dict[str, Union[str, int]] = None
):
if param is None:
param = {}
... | 0.884514 | 0.352843 |
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.p... | tests/fixtures/image_mood_classification_100_proto_pb2.py |
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.p... | 0.167866 | 0.131731 |
from pylab import *
from rnn import *
from brnn import *
from common import *
def example(hidden=10, examples=1000, epochs=100, eta=0.001, rnn=None, binary=False, progress=True, embedded=False):
import reber
data_source = reber.get_n_embedded_examples if embedded else reber.get_n_examples
DATA = map((lambd... | example.py | from pylab import *
from rnn import *
from brnn import *
from common import *
def example(hidden=10, examples=1000, epochs=100, eta=0.001, rnn=None, binary=False, progress=True, embedded=False):
import reber
data_source = reber.get_n_embedded_examples if embedded else reber.get_n_examples
DATA = map((lambd... | 0.516108 | 0.393589 |
import numpy as np
class LinearRegressionPy:
pass
class LinearRegressionNp:
def __init__(self, solver="normal_eq"):
self.solver = solver
self.theta = None
self.intercept_ = None
self.coef_ = None
def fit(self, X, y):
if self.solver == "normal_eq":
... | plb_ml_lib.py | import numpy as np
class LinearRegressionPy:
pass
class LinearRegressionNp:
def __init__(self, solver="normal_eq"):
self.solver = solver
self.theta = None
self.intercept_ = None
self.coef_ = None
def fit(self, X, y):
if self.solver == "normal_eq":
... | 0.749087 | 0.613468 |
import requests
from time import sleep
import time
import psutil
import os
NVF = 'test'
IP = '192.168.1.117'
DB = 'ns_1'
USER = 'test'
PASSWORD = '<PASSWORD>'
TIME = 1
interface = "lo"
cpu = 0.0
ul=0.00
dl=0.00
t0 = time.time()
upload=psutil.net_io_counters(pernic=True)[interface][0]
download=psutil.net_io_counters(... | examples/scripts/files/monitorVNF.py |
import requests
from time import sleep
import time
import psutil
import os
NVF = 'test'
IP = '192.168.1.117'
DB = 'ns_1'
USER = 'test'
PASSWORD = '<PASSWORD>'
TIME = 1
interface = "lo"
cpu = 0.0
ul=0.00
dl=0.00
t0 = time.time()
upload=psutil.net_io_counters(pernic=True)[interface][0]
download=psutil.net_io_counters(... | 0.121516 | 0.086246 |
begin_unit
comment|'# Copyright 2016 OpenStack Foundation'
nl|'\n'
comment|'# All Rights Reserved.'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may'
nl|'\n'
comment|'# not use this file except in compliance with the License. You may obtain'
nl|'\n'
co... | nova/conf/spice.py | begin_unit
comment|'# Copyright 2016 OpenStack Foundation'
nl|'\n'
comment|'# All Rights Reserved.'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may'
nl|'\n'
comment|'# not use this file except in compliance with the License. You may obtain'
nl|'\n'
co... | 0.578448 | 0.077134 |
from odps.compat import irange
from odps.tests.core import TestBase, tn
from odps.tunnel import CompressOption
TEST_PARTED_VOLUME_NAME = tn('pyodps_test_p_volume')
TEST_FS_VOLUME_NAME = tn('pyodps_test_fs_volume')
TEST_PARTITION_NAME = 'pyodps_test_partition'
TEST_FILE_NAME = 'test_output_file'
TEST_BLOCK_SIZE = 104... | odps/tunnel/tests/test_volumetunnel.py |
from odps.compat import irange
from odps.tests.core import TestBase, tn
from odps.tunnel import CompressOption
TEST_PARTED_VOLUME_NAME = tn('pyodps_test_p_volume')
TEST_FS_VOLUME_NAME = tn('pyodps_test_fs_volume')
TEST_PARTITION_NAME = 'pyodps_test_partition'
TEST_FILE_NAME = 'test_output_file'
TEST_BLOCK_SIZE = 104... | 0.502197 | 0.34679 |