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 time
import json
from modules.DateGenerator import DateGenerator
from modules.Config import APILoader, Network
from modules.VaxFactory import VaxFactory
from modules.Device import UserAgents
from modules.Logger import Logger
class AppointmentBooking:
def __init__(self, data):
self.center_id = data["center_i... | modules/Appointment.py | import time
import json
from modules.DateGenerator import DateGenerator
from modules.Config import APILoader, Network
from modules.VaxFactory import VaxFactory
from modules.Device import UserAgents
from modules.Logger import Logger
class AppointmentBooking:
def __init__(self, data):
self.center_id = data["center_i... | 0.251188 | 0.199444 |
import os
from django.core.mail import send_mail
from django.template.loader import render_to_string
def feedback_mail(message, user):
plain = message + "\n\nPosted by %s, %s" % (user.fname, user.email)
subject = "FRCShirt Feedback"
print(os.getenv("ADMIN_EMAIL"))
send_mail(subject, plain, "FRCShirt<... | trade/email.py | import os
from django.core.mail import send_mail
from django.template.loader import render_to_string
def feedback_mail(message, user):
plain = message + "\n\nPosted by %s, %s" % (user.fname, user.email)
subject = "FRCShirt Feedback"
print(os.getenv("ADMIN_EMAIL"))
send_mail(subject, plain, "FRCShirt<... | 0.131703 | 0.125226 |
import collections
import warnings
import torch
from reid_evaluation.metric import evaluate, compute_distances
from utils import MetricTracker, SharedStorage
class ActiveMetric:
"""Metric class that actively interacts with MetricTracker and SharedStorage to track metrics,
during end-of-step and end-of-epoch... | model/metric.py | import collections
import warnings
import torch
from reid_evaluation.metric import evaluate, compute_distances
from utils import MetricTracker, SharedStorage
class ActiveMetric:
"""Metric class that actively interacts with MetricTracker and SharedStorage to track metrics,
during end-of-step and end-of-epoch... | 0.816333 | 0.58166 |
from mvsnet import preprocess as pp
import imageio
import argparse
import json
import utils
import os
"""
Converts DTU depth data from the format that is consumed by the original MVSNet
to the mvs-training format that is created by export_densify_frames
"""
def convert_dtu(dtu_dir, output_dir):
camera_base = os.... | datasets/convert/dtu_to_mvs_training.py | from mvsnet import preprocess as pp
import imageio
import argparse
import json
import utils
import os
"""
Converts DTU depth data from the format that is consumed by the original MVSNet
to the mvs-training format that is created by export_densify_frames
"""
def convert_dtu(dtu_dir, output_dir):
camera_base = os.... | 0.378 | 0.23865 |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
import matplotlib.patches as patches
from LucasKanadeBasis import *
from LucasKanade import *
from TemplateCorrection import *
import time
def copyRect(rect):
rect_new = []
for ele in rect:
rect_new += [ele]
return ... | src/testSylvSequence.py | import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
import matplotlib.patches as patches
from LucasKanadeBasis import *
from LucasKanade import *
from TemplateCorrection import *
import time
def copyRect(rect):
rect_new = []
for ele in rect:
rect_new += [ele]
return ... | 0.307462 | 0.514278 |
from monitor_server import SERVER
if SERVER.config['SQLALCHEMY_DATABASE_URI'].startswith('sqlite:'):
from sqlalchemy.dialects.sqlite.json import JSON
else:
from sqlalchemy.dialects.postgresql.json import JSON
class MetricModel(SERVER.DB.Model):
__tablename__ = 'TEST_METRICS'
test_id = SERVER.DB.Col... | monitor_server/data/model.py |
from monitor_server import SERVER
if SERVER.config['SQLALCHEMY_DATABASE_URI'].startswith('sqlite:'):
from sqlalchemy.dialects.sqlite.json import JSON
else:
from sqlalchemy.dialects.postgresql.json import JSON
class MetricModel(SERVER.DB.Model):
__tablename__ = 'TEST_METRICS'
test_id = SERVER.DB.Col... | 0.304972 | 0.057388 |
import tempfile
import os
from sqlite3 import OperationalError
import pytest
import hypothesis.strategies as hst
from hypothesis import given
import unicodedata
import qcodes as qc
import qcodes.dataset.sqlite_base as mut # mut: module under test
from qcodes.dataset.database import initialise_database
from qcodes.d... | qcodes/tests/dataset/test_sqlite_base.py |
import tempfile
import os
from sqlite3 import OperationalError
import pytest
import hypothesis.strategies as hst
from hypothesis import given
import unicodedata
import qcodes as qc
import qcodes.dataset.sqlite_base as mut # mut: module under test
from qcodes.dataset.database import initialise_database
from qcodes.d... | 0.384334 | 0.46794 |
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... | pgoapi/protos/pogoprotos/data/friends/friend_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.16248 | 0.112162 |
import os
import time
import yaml
from pathlib import Path
import numpy as np
import astropy.units as u
from astropy.coordinates import SkyCoord
from gammapy.modeling.models import (
SkyModel,
ExpCutoffPowerLawSpectralModel,
PointSpatialModel,
)
from gammapy.spectrum import FluxPointsEstimator
from gammapy.... | benchmarks/analysis_3d_joint.py | import os
import time
import yaml
from pathlib import Path
import numpy as np
import astropy.units as u
from astropy.coordinates import SkyCoord
from gammapy.modeling.models import (
SkyModel,
ExpCutoffPowerLawSpectralModel,
PointSpatialModel,
)
from gammapy.spectrum import FluxPointsEstimator
from gammapy.... | 0.662796 | 0.471467 |
from ast import Pass
import sqlite3
from pyrsistent import v
from utilities.exceptions import DBCursorError, DatabaseConnectionError, QueryError
class BaseService(object):
def __init__(self):
"""
:param cursor:
"""
super().__init__()
self.query = ""
def execute_quer... | services/base_service.py | from ast import Pass
import sqlite3
from pyrsistent import v
from utilities.exceptions import DBCursorError, DatabaseConnectionError, QueryError
class BaseService(object):
def __init__(self):
"""
:param cursor:
"""
super().__init__()
self.query = ""
def execute_quer... | 0.367384 | 0.159119 |
import matplotlib.pyplot as plt
import matplotlib.patches as patches
plt.figure(figsize=(10,10))
plt.axis('off')
cz = (0.3, 0.3, 0.3)
cy = (0.7, 0.4, 0.12)
ci = (0.1, 0.3, 0.5)
ct = (0.7, 0.2, 0.1)
def ln_func(text, x, y, color, mode=None):
if mode is None:
color_font = b_color = color
alpha_bg ... | paper/figure_predict.py | import matplotlib.pyplot as plt
import matplotlib.patches as patches
plt.figure(figsize=(10,10))
plt.axis('off')
cz = (0.3, 0.3, 0.3)
cy = (0.7, 0.4, 0.12)
ci = (0.1, 0.3, 0.5)
ct = (0.7, 0.2, 0.1)
def ln_func(text, x, y, color, mode=None):
if mode is None:
color_font = b_color = color
alpha_bg ... | 0.412412 | 0.474692 |
import argparse, os, readline, sys
require date, taskfile, help
__dir__ = os.path.join(*os.path.split(__file__)[:-1]) \
if os.path.basename(__file__)!=__file__ else "."
# Command Line Argument Validation
operations = "list add edit delete move do fail help report".split()
ap = argparse.ArgumentParser(description="... | src/cli.py | import argparse, os, readline, sys
require date, taskfile, help
__dir__ = os.path.join(*os.path.split(__file__)[:-1]) \
if os.path.basename(__file__)!=__file__ else "."
# Command Line Argument Validation
operations = "list add edit delete move do fail help report".split()
ap = argparse.ArgumentParser(description="... | 0.069954 | 0.087994 |
from collections import OrderedDict
import tensorflow as tf
from tensorflow.keras.layers import ReLU, LayerNormalization
from tensorflow.keras.layers import UpSampling2D
from .adain import AdaptiveInstanceNormalization
from .linear_blocks import linear_block
from .conv_blocks import res_block
from .conv_blocks impor... | models/decoder.py | from collections import OrderedDict
import tensorflow as tf
from tensorflow.keras.layers import ReLU, LayerNormalization
from tensorflow.keras.layers import UpSampling2D
from .adain import AdaptiveInstanceNormalization
from .linear_blocks import linear_block
from .conv_blocks import res_block
from .conv_blocks impor... | 0.804828 | 0.45944 |
import argparse
from jinja2 import Environment, PackageLoader
def main(properties):
env = Environment(loader=PackageLoader('templates'), trim_blocks=True, lstrip_blocks=True)
template = env.get_template('esp_template.jinja')
out_path = properties['out']
del properties['out']
with open(out_path,... | k8s/render.py |
import argparse
from jinja2 import Environment, PackageLoader
def main(properties):
env = Environment(loader=PackageLoader('templates'), trim_blocks=True, lstrip_blocks=True)
template = env.get_template('esp_template.jinja')
out_path = properties['out']
del properties['out']
with open(out_path,... | 0.699049 | 0.112747 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from . import outputs
from ._inputs import *
__all__ = ['ListenerArgs', 'Listener']
@pulumi.input_type
class ListenerArgs:
def __init__(__self__, *,
... | sdk/python/pulumi_alicloud/ga/listener.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from . import outputs
from ._inputs import *
__all__ = ['ListenerArgs', 'Listener']
@pulumi.input_type
class ListenerArgs:
def __init__(__self__, *,
... | 0.859162 | 0.119152 |
import re
import time
from ..base.account import BaseAccount
from ..helpers import parse_html_form, set_cookie
class TurbobitNet(BaseAccount):
__name__ = "TurbobitNet"
__type__ = "account"
__version__ = "0.12"
__status__ = "testing"
__pyload_version__ = "0.5"
__description__ = """TurbobitNe... | supports/pyload/src/pyload/plugins/accounts/TurbobitNet.py | import re
import time
from ..base.account import BaseAccount
from ..helpers import parse_html_form, set_cookie
class TurbobitNet(BaseAccount):
__name__ = "TurbobitNet"
__type__ = "account"
__version__ = "0.12"
__status__ = "testing"
__pyload_version__ = "0.5"
__description__ = """TurbobitNe... | 0.23855 | 0.123736 |
from cnn_simple import *
from utils import *
import os
import numpy as np
import argparse
import time
os.system('echo $CUDA_VISIBLE_DEVICES')
PATIENCE = 5 # The parameter is used for early stopping
def main():
parser = argparse.ArgumentParser(prog='train.py')
parser.add_argument('--epoch', type=int, default=1... | ML-Course-NTU-Lee/hw3/demo/train.py | from cnn_simple import *
from utils import *
import os
import numpy as np
import argparse
import time
os.system('echo $CUDA_VISIBLE_DEVICES')
PATIENCE = 5 # The parameter is used for early stopping
def main():
parser = argparse.ArgumentParser(prog='train.py')
parser.add_argument('--epoch', type=int, default=1... | 0.32178 | 0.222996 |
import json
import logging
import os
import shutil
import time
from copy import deepcopy
import certifi
import requests
import yaml
from assemblyline.common import log as al_log
from assemblyline.common.digests import get_sha256_for_file
from assemblyline.common.isotime import iso_to_epoch
al_log.init_logging('serv... | assemblyline_core/updater/url_update.py | import json
import logging
import os
import shutil
import time
from copy import deepcopy
import certifi
import requests
import yaml
from assemblyline.common import log as al_log
from assemblyline.common.digests import get_sha256_for_file
from assemblyline.common.isotime import iso_to_epoch
al_log.init_logging('serv... | 0.421433 | 0.075109 |
# In[1]:
# %pip install tensorflow==2.4.1
# %pip install transformers
# %pip install pyarrow
# %pip install tensorflow-addons
# In[1]:
import tensorflow as tf
import pandas as pd
import pickle
import os
import tensorflow_addons as tfa
from transformers import RobertaTokenizer, RobertaTokenizerFast, TFRobertaMode... | POC/mag_model_iteration_1.py |
# In[1]:
# %pip install tensorflow==2.4.1
# %pip install transformers
# %pip install pyarrow
# %pip install tensorflow-addons
# In[1]:
import tensorflow as tf
import pandas as pd
import pickle
import os
import tensorflow_addons as tfa
from transformers import RobertaTokenizer, RobertaTokenizerFast, TFRobertaMode... | 0.741955 | 0.31457 |
from collections import deque
from time import time
import numpy as np
class LoopTracker(object):
"""timekeeping, contains
1) with `enter`-> `exit`; 2) loop between current and next `exit`. """
def __init__(self, length):
self.with_time_list = deque(maxlen=length)
self.loop_time_list = d... | built-in/TensorFlow/Research/reinforcement-learning/ModelZoo_QMIX_TensorFlow/xt/util/profile_stats.py | from collections import deque
from time import time
import numpy as np
class LoopTracker(object):
"""timekeeping, contains
1) with `enter`-> `exit`; 2) loop between current and next `exit`. """
def __init__(self, length):
self.with_time_list = deque(maxlen=length)
self.loop_time_list = d... | 0.777046 | 0.32126 |
from . import db,login_manager
from werkzeug.security import generate_password_hash,check_password_hash
from flask_login import UserMixin
from datetime import datetime
#Added this code to solve the Exception: Missing user_loader or request_loader.
@login_manager.user_loader
def load_user(user_id):
return User.que... | app/models.py | from . import db,login_manager
from werkzeug.security import generate_password_hash,check_password_hash
from flask_login import UserMixin
from datetime import datetime
#Added this code to solve the Exception: Missing user_loader or request_loader.
@login_manager.user_loader
def load_user(user_id):
return User.que... | 0.372277 | 0.058051 |
from fractions import Fraction
from random import randint
NUMBER_OF_ITERATIONS = 10_000
FLOUR = True
SUGAR = False
def main(iterations: int = NUMBER_OF_ITERATIONS) -> None:
"""
print the percentage of the iterations where the selected person had the
required item
"""
times_person_A_has_extra_flou... | other/two_children_problem.py | from fractions import Fraction
from random import randint
NUMBER_OF_ITERATIONS = 10_000
FLOUR = True
SUGAR = False
def main(iterations: int = NUMBER_OF_ITERATIONS) -> None:
"""
print the percentage of the iterations where the selected person had the
required item
"""
times_person_A_has_extra_flou... | 0.523177 | 0.362236 |
import os
import time
from glob import glob
from multiprocessing import Pool, cpu_count
import numpy as np
import tensorflow as tf
from absl import app, logging
from absl.flags import argparse_flags
from tqdm import auto as tqdm
import lm.config
import lm.encoders
import lm.examples
args = None
def readlines_txt(sr... | src/lm/cli/encode.py | import os
import time
from glob import glob
from multiprocessing import Pool, cpu_count
import numpy as np
import tensorflow as tf
from absl import app, logging
from absl.flags import argparse_flags
from tqdm import auto as tqdm
import lm.config
import lm.encoders
import lm.examples
args = None
def readlines_txt(sr... | 0.522689 | 0.180215 |
import ddt
from deuceclient.tests import *
import httpretty
from deucevalere import vault_validate
from deucevalere.tests import *
from deucevalere.tests.client_base import TestValereClientBase
@ddt.ddt
@httpretty.activate
class TestConvenienceFunctionValidation(TestValereClientBase):
def setUp(self):
s... | deucevalere/tests/test_convenience_functions_validation.py | import ddt
from deuceclient.tests import *
import httpretty
from deucevalere import vault_validate
from deucevalere.tests import *
from deucevalere.tests.client_base import TestValereClientBase
@ddt.ddt
@httpretty.activate
class TestConvenienceFunctionValidation(TestValereClientBase):
def setUp(self):
s... | 0.511961 | 0.117876 |
"""Process road data from OSM extracts and create road network topology
"""
import os
from glob import glob
import fiona
import geopandas as gpd
import pandas as pd
from tqdm import tqdm
tqdm.pandas()
from utils import *
def get_road_condition_surface(x):
if not x.surface:
if x.highway in ('motorway','mo... | scripts/preprocess/road/process_road.py | """Process road data from OSM extracts and create road network topology
"""
import os
from glob import glob
import fiona
import geopandas as gpd
import pandas as pd
from tqdm import tqdm
tqdm.pandas()
from utils import *
def get_road_condition_surface(x):
if not x.surface:
if x.highway in ('motorway','mo... | 0.422266 | 0.382286 |
import config
import telebot
import sqlite3
bot = telebot.TeleBot(config.token)
user_markup = telebot.types.InlineKeyboardMarkup(row_width=2)
first_button = telebot.types.InlineKeyboardButton(text="Магазин", callback_data="shop")
second_button = telebot.types.InlineKeyboardButton(text="О нас", callback_data="ab... | main.py | import config
import telebot
import sqlite3
bot = telebot.TeleBot(config.token)
user_markup = telebot.types.InlineKeyboardMarkup(row_width=2)
first_button = telebot.types.InlineKeyboardButton(text="Магазин", callback_data="shop")
second_button = telebot.types.InlineKeyboardButton(text="О нас", callback_data="ab... | 0.063956 | 0.093719 |
import logging
from numbers import Real
import pandas as pd
from pandas.testing import assert_series_equal
import pytest
import toml
from incognita.data import ons_pd
from incognita.logger import logger
from incognita.utility import config
from incognita.utility import deciles
from incognita.utility import root
from ... | tests/test_utility.py | import logging
from numbers import Real
import pandas as pd
from pandas.testing import assert_series_equal
import pytest
import toml
from incognita.data import ons_pd
from incognita.logger import logger
from incognita.utility import config
from incognita.utility import deciles
from incognita.utility import root
from ... | 0.65368 | 0.445288 |
import os
import time
import torch
import random
import argparse
from tqdm import tqdm
from scorer import Scorer
from data_utils import load_data
from sagan_trainer import SAGAN_Trainer
from torchvision.utils import save_image
from torch.utils.tensorboard import SummaryWriter
class Instructor:
def __init__(self,... | main.py | import os
import time
import torch
import random
import argparse
from tqdm import tqdm
from scorer import Scorer
from data_utils import load_data
from sagan_trainer import SAGAN_Trainer
from torchvision.utils import save_image
from torch.utils.tensorboard import SummaryWriter
class Instructor:
def __init__(self,... | 0.586523 | 0.138928 |
from rest_framework import serializers
from .models import *
from rest_framework_simplejwt.tokens import RefreshToken
from django.contrib.auth import authenticate
from django.contrib.auth.models import update_last_login
class UserProfileSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model ... | railway_api/serializers.py | from rest_framework import serializers
from .models import *
from rest_framework_simplejwt.tokens import RefreshToken
from django.contrib.auth import authenticate
from django.contrib.auth.models import update_last_login
class UserProfileSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model ... | 0.529507 | 0.079603 |
' Argument parser '
import argparse
import pathlib
from . import(
constants,
custom_types
)
def valid_percent(value):
' Validate percentage values '
percent = float(value)
if 0 < percent <= 100:
return percent
raise argparse.ArgumentTypeError(f'{value} must be within 1 and 100')
def ... | teslacam/arg_parser.py | ' Argument parser '
import argparse
import pathlib
from . import(
constants,
custom_types
)
def valid_percent(value):
' Validate percentage values '
percent = float(value)
if 0 < percent <= 100:
return percent
raise argparse.ArgumentTypeError(f'{value} must be within 1 and 100')
def ... | 0.685423 | 0.285154 |
import torch
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
import scipy.misc
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch
import torch.optim as optim
import torchvision
import numpy as np
import torch.utils.data as data_utils
import t... | train_utils.py | import torch
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
import scipy.misc
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch
import torch.optim as optim
import torchvision
import numpy as np
import torch.utils.data as data_utils
import t... | 0.723016 | 0.550849 |
# Este script toma un archivo CSV y lo geolocaliza, es decir crea un nuevo archivo _geo.csv con columnas lat y long.
# Utiliza el API de Google Maps
# Instrucciones en como obtener la API Key para Google Maps: https://github.com/slawek87/geolocation-python
from geolocation.main import GoogleMaps
from geolocation.dist... | code/geolocalize.py |
# Este script toma un archivo CSV y lo geolocaliza, es decir crea un nuevo archivo _geo.csv con columnas lat y long.
# Utiliza el API de Google Maps
# Instrucciones en como obtener la API Key para Google Maps: https://github.com/slawek87/geolocation-python
from geolocation.main import GoogleMaps
from geolocation.dist... | 0.338296 | 0.477067 |
# FIXME IMPORT!
import random
import math
import copy
import time
import socket
import pickle
from RULEngine.Util.Pose import Pose
from RULEngine.Util.Position import Position
from RULEngine.Util.constant import POSITION_DEADZONE
from ai.Algorithm.IntelligentModule import Pathfinder
from ai.Debug.debug_interface impo... | ai/Algorithm/PathfinderRRT.py | # FIXME IMPORT!
import random
import math
import copy
import time
import socket
import pickle
from RULEngine.Util.Pose import Pose
from RULEngine.Util.Position import Position
from RULEngine.Util.constant import POSITION_DEADZONE
from ai.Algorithm.IntelligentModule import Pathfinder
from ai.Debug.debug_interface impo... | 0.158891 | 0.348008 |
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from api.utils import humanize_time
import datetime
import urllib
class ChatMessage(models.Model):
author = models.ForeignKey(User, related_name='author', null=False, blank=False)
message = models.CharFi... | api/models.py | from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from api.utils import humanize_time
import datetime
import urllib
class ChatMessage(models.Model):
author = models.ForeignKey(User, related_name='author', null=False, blank=False)
message = models.CharFi... | 0.5144 | 0.071559 |
import numpy as np
import math
from matplotlib import pyplot
import time
import sys
import numba
@numba.jit
def bilinear_interpolation(X, Y, f, x, y):
"""Returns the approximate value of f(x,y) using bilinear interpolation.
Arguments
---------
X, Y -- mesh grid.
f -- the function f that should be... | dyntrack/utils/FTLE.py | import numpy as np
import math
from matplotlib import pyplot
import time
import sys
import numba
@numba.jit
def bilinear_interpolation(X, Y, f, x, y):
"""Returns the approximate value of f(x,y) using bilinear interpolation.
Arguments
---------
X, Y -- mesh grid.
f -- the function f that should be... | 0.471467 | 0.663471 |
from fastapi import FastAPI, Depends, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy.orm import Session
from app.database import crud, models, schemas, SessionLocal, engine
from app.validate_wasm import validate_wasm
from typing import List
models.Base.metadata.create_all(bind=... | backend/app/main.py | from fastapi import FastAPI, Depends, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy.orm import Session
from app.database import crud, models, schemas, SessionLocal, engine
from app.validate_wasm import validate_wasm
from typing import List
models.Base.metadata.create_all(bind=... | 0.61231 | 0.065515 |
from pyrsistent import pmap, thaw
from .event import EventBase
from .util import is_pmap, ms_from_dt
class TimeRangeEvent(EventBase):
"""
The creation of an TimeRangeEvent is done by combining two parts -
the timerange and the data.
To construct you specify a TimeRange, along with the data.
The... | pypond/timerange_event.py | from pyrsistent import pmap, thaw
from .event import EventBase
from .util import is_pmap, ms_from_dt
class TimeRangeEvent(EventBase):
"""
The creation of an TimeRangeEvent is done by combining two parts -
the timerange and the data.
To construct you specify a TimeRange, along with the data.
The... | 0.91204 | 0.72594 |
import datetime
import scrapelib
import pytz
import cachetools
class GovInfo(scrapelib.Scraper):
BASE_URL = 'https://api.govinfo.gov'
def __init__(self, *args, api_key='DEMO_KEY', **kwargs):
super().__init__(*args, **kwargs)
self.headers['X-Api-Key'] = api_key
def collections(self):
... | govinfo/__init__.py | import datetime
import scrapelib
import pytz
import cachetools
class GovInfo(scrapelib.Scraper):
BASE_URL = 'https://api.govinfo.gov'
def __init__(self, *args, api_key='DEMO_KEY', **kwargs):
super().__init__(*args, **kwargs)
self.headers['X-Api-Key'] = api_key
def collections(self):
... | 0.371479 | 0.182389 |
# Python modules
from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtCore import pyqtSignal
import colorsys
# Wizard gui modules
from wizard.gui import gui_utils
class color_picker(QtWidgets.QWidget):
validate_signal = pyqtSignal(str)
color_signal = pyqtSignal(str)
def __init__(self, color='#798fe8... | wizard/gui/color_picker.py |
# Python modules
from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtCore import pyqtSignal
import colorsys
# Wizard gui modules
from wizard.gui import gui_utils
class color_picker(QtWidgets.QWidget):
validate_signal = pyqtSignal(str)
color_signal = pyqtSignal(str)
def __init__(self, color='#798fe8... | 0.669096 | 0.13788 |
import datetime
import jwt
from api.models import (AccountDetails, AgentCoins, AgentTransactionHistory,
ContactUs, User, UserCoins, UserTrasactionHistory, otp)
from CustomCode import (autentication, fixed_var, password_functions, sms,
string_generator, validator)
from dj... | api/views.py | import datetime
import jwt
from api.models import (AccountDetails, AgentCoins, AgentTransactionHistory,
ContactUs, User, UserCoins, UserTrasactionHistory, otp)
from CustomCode import (autentication, fixed_var, password_functions, sms,
string_generator, validator)
from dj... | 0.283583 | 0.118921 |
from data_science_layer.reporting.abstract_report import AbstractReport
from data_science_layer.pipeline.abstract_pipline import AbstractPipeline
import pkg_resources
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
class RegressorCurves(AbstractReport):
sub_folder = '... | data_science_layer/reporting/regressor_curves.py | from data_science_layer.reporting.abstract_report import AbstractReport
from data_science_layer.pipeline.abstract_pipline import AbstractPipeline
import pkg_resources
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
class RegressorCurves(AbstractReport):
sub_folder = '... | 0.42919 | 0.468243 |
import unittest
import enum
from test.asserting.policy import PolicyAssertion, get_fixture_path
from vint.linting.level import Level
from vint.linting.policy.prohibit_unused_variable import ProhibitUnusedVariable
class Fixtures(enum.Enum):
VALID_VIM_SCRIPT = get_fixture_path('prohibit_unused_variable_valid.vim')
... | test/integration/vint/linting/policy/test_prohibit_unused_variable.py | import unittest
import enum
from test.asserting.policy import PolicyAssertion, get_fixture_path
from vint.linting.level import Level
from vint.linting.policy.prohibit_unused_variable import ProhibitUnusedVariable
class Fixtures(enum.Enum):
VALID_VIM_SCRIPT = get_fixture_path('prohibit_unused_variable_valid.vim')
... | 0.364438 | 0.331174 |
import designes as dsgn
import characters as chr
import random as rdm
market_1 = False
market_2 = False
market_3 = False
lvl = 0
print(dsgn.main_screen())
cvp = int(input())
if cvp != 1:
print("ÇIKIŞ YAPILIYOR")
while 1:
print("""************************************************************... | Python-Game_Spark-man/main.py | import designes as dsgn
import characters as chr
import random as rdm
market_1 = False
market_2 = False
market_3 = False
lvl = 0
print(dsgn.main_screen())
cvp = int(input())
if cvp != 1:
print("ÇIKIŞ YAPILIYOR")
while 1:
print("""************************************************************... | 0.046206 | 0.121477 |
from django.core.management.base import BaseCommand, CommandError
import os
import re
import json
def fp_dict(path):
json_file=open(path)
json_str = json_file.read()
json_data = json.loads(json_str)
return json_data
def get_cont_type(self,jsonfile,n1,n2):
if(len(n1.split("x")) != 2):
self.... | dynadb/management/commands/addinfo_fplot.py | from django.core.management.base import BaseCommand, CommandError
import os
import re
import json
def fp_dict(path):
json_file=open(path)
json_str = json_file.read()
json_data = json.loads(json_str)
return json_data
def get_cont_type(self,jsonfile,n1,n2):
if(len(n1.split("x")) != 2):
self.... | 0.289071 | 0.057971 |
import os
import mock
import utils
from common import cli_helpers
# Need this for plugin imports
utils.add_sys_plugin_path("kubernetes")
from plugins.kubernetes.parts import ( # noqa E402
general,
network,
)
class TestKubernetesPluginPartGeneral(utils.BaseTestCase):
def setUp(self):
self.sna... | tests/unit/test_kubernetes.py | import os
import mock
import utils
from common import cli_helpers
# Need this for plugin imports
utils.add_sys_plugin_path("kubernetes")
from plugins.kubernetes.parts import ( # noqa E402
general,
network,
)
class TestKubernetesPluginPartGeneral(utils.BaseTestCase):
def setUp(self):
self.sna... | 0.42656 | 0.128416 |
import math
import glob
import threading
from PIL import Image
import tqdm
from TiledImage import others
def resizeImage(image: Image.Image, w, h, keepRatio=True):
if keepRatio:
ratio = image.width / image.height
if w > h:
return image.resize((int(ratio * h), h))
else:
... | TiledImage/__init__.py | import math
import glob
import threading
from PIL import Image
import tqdm
from TiledImage import others
def resizeImage(image: Image.Image, w, h, keepRatio=True):
if keepRatio:
ratio = image.width / image.height
if w > h:
return image.resize((int(ratio * h), h))
else:
... | 0.660282 | 0.39257 |
from django.urls import path
from django.contrib.auth import views as auth_views
from . import views
#crud urls
app_name='products'
urlpatterns=[
path('category/',views.get_all_categories,name='categories'),
path('category_view_ajax/',views.category_view_ajax,name="category_view_ajax"),
path('add_category/'... | products/urls.py | from django.urls import path
from django.contrib.auth import views as auth_views
from . import views
#crud urls
app_name='products'
urlpatterns=[
path('category/',views.get_all_categories,name='categories'),
path('category_view_ajax/',views.category_view_ajax,name="category_view_ajax"),
path('add_category/'... | 0.250821 | 0.044681 |
from __future__ import unicode_literals
import csv
import json
import os
from . import CONFIG, common, osm, plfunctions
from .cities import montreal as mrl
from .cities import quebec as qbc
from .cities import newyork as nyc
from .cities import seattle as sea
from .cities import boston as bos
from .database import Po... | prkng_process/pipeline.py | from __future__ import unicode_literals
import csv
import json
import os
from . import CONFIG, common, osm, plfunctions
from .cities import montreal as mrl
from .cities import quebec as qbc
from .cities import newyork as nyc
from .cities import seattle as sea
from .cities import boston as bos
from .database import Po... | 0.493409 | 0.113481 |
from flask import Flask, request, jsonify, render_template, abort, Response
from . import shallow_backend
from . import suggest
app = Flask(__name__)
app.debug = True
# todo: 1. suggestions do not work
# todo: 2. adding corrections is still not implemeneted
# todo: 3. joining tokens across the lines has to be imple... | app.py | from flask import Flask, request, jsonify, render_template, abort, Response
from . import shallow_backend
from . import suggest
app = Flask(__name__)
app.debug = True
# todo: 1. suggestions do not work
# todo: 2. adding corrections is still not implemeneted
# todo: 3. joining tokens across the lines has to be imple... | 0.297164 | 0.084568 |
import csv
import datetime
import os
import roslib
import rospy
import rostopic
_node_name = 'logger_node'
"""Name of this node in the ROS system."""
class DataIn(object):
"""Receiver and buffer of a topic."""
def __init__(self, topic, name=None):
"""Constructor.
topic -- topic including f... | src/logger_node.py | import csv
import datetime
import os
import roslib
import rospy
import rostopic
_node_name = 'logger_node'
"""Name of this node in the ROS system."""
class DataIn(object):
"""Receiver and buffer of a topic."""
def __init__(self, topic, name=None):
"""Constructor.
topic -- topic including f... | 0.596551 | 0.20201 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from myutils.nn import LSTM, Linear
class TextRCNN(nn.Module):
"""Text RCNN model."""
def __init__(self, config, pretrained_emb):
super(TextRCNN, self).__init__()
self.config = config["arch"]["args"]
# word embedding ... | src/model/text_rcnn.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from myutils.nn import LSTM, Linear
class TextRCNN(nn.Module):
"""Text RCNN model."""
def __init__(self, config, pretrained_emb):
super(TextRCNN, self).__init__()
self.config = config["arch"]["args"]
# word embedding ... | 0.944158 | 0.307397 |
from textx import metamodel_from_str, get_children_of_type
import numpy as np
import random
grammar = """
Model: commands*=GameCommand;
GameCommand: MoveCommand | ActionCommand;
MoveCommand: Left|Right|Up|Down;
ActionCommand: Reset | Exit;
Left: 'left' count=INT?;
Right: 'right' count=INT?;
Up: 'up' count=INT?;
Down:... | src/main/python/dsl.py |
from textx import metamodel_from_str, get_children_of_type
import numpy as np
import random
grammar = """
Model: commands*=GameCommand;
GameCommand: MoveCommand | ActionCommand;
MoveCommand: Left|Right|Up|Down;
ActionCommand: Reset | Exit;
Left: 'left' count=INT?;
Right: 'right' count=INT?;
Up: 'up' count=INT?;
Down:... | 0.52683 | 0.227148 |
from __future__ import annotations
from typing import Dict, Set, List, Tuple, Optional, Any
import enum
import gc
import math
import sys
import pytest
import msgspec
class FruitInt(enum.IntEnum):
APPLE = 1
BANANA = 2
class FruitStr(enum.Enum):
APPLE = "apple"
BANANA = "banana"
class Person(msgs... | tests/test_msgspec.py | from __future__ import annotations
from typing import Dict, Set, List, Tuple, Optional, Any
import enum
import gc
import math
import sys
import pytest
import msgspec
class FruitInt(enum.IntEnum):
APPLE = 1
BANANA = 2
class FruitStr(enum.Enum):
APPLE = "apple"
BANANA = "banana"
class Person(msgs... | 0.650689 | 0.596081 |
import os
os.chdir('../../..')
from pipelineFunctions import parseConfigFindList, parseConfigFindPath
root = os.getcwd()+'/'
print root
import sys
version,buildSample,buildRef,constructSample,CDSspecies,CDSOld,CDSgeneNaming, BB, nuc, weights_file, references_dir, query_dir, output_dir, bin = tuple(sys.argv[1:])
"""wit... | scaffolding_tool_bin/writeShFiles.py | import os
os.chdir('../../..')
from pipelineFunctions import parseConfigFindList, parseConfigFindPath
root = os.getcwd()+'/'
print root
import sys
version,buildSample,buildRef,constructSample,CDSspecies,CDSOld,CDSgeneNaming, BB, nuc, weights_file, references_dir, query_dir, output_dir, bin = tuple(sys.argv[1:])
"""wit... | 0.210523 | 0.090093 |
from collections import OrderedDict
import itertools
import sys
from tensorflow.keras.layers import Input
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import TerminateOnNaN
from flowket.callbacks.monte_carlo import TensorBoardWithGeneratorValid... | examples/j1j2_2d_monte_carlo_4.py | from collections import OrderedDict
import itertools
import sys
from tensorflow.keras.layers import Input
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import TerminateOnNaN
from flowket.callbacks.monte_carlo import TensorBoardWithGeneratorValid... | 0.586286 | 0.322753 |
from src.constants import *
from src.token import Token
from src.tokenizer import Tokenizer
from src.symbol_table import SymbolTable
from src.variable import Variable
from copy import copy
CLASSES = []
SUBROUTINES = []
class Parser(object):
def __init__(self, tokenizer):
""" Constructs parser object.... | src/parser.py | from src.constants import *
from src.token import Token
from src.tokenizer import Tokenizer
from src.symbol_table import SymbolTable
from src.variable import Variable
from copy import copy
CLASSES = []
SUBROUTINES = []
class Parser(object):
def __init__(self, tokenizer):
""" Constructs parser object.... | 0.496094 | 0.123762 |
from zorro.di import di, has_dependencies, dependency
from cairo import SolidPattern
import cairo
from .base import Widget
from tilenol.commands import CommandDispatcher
from tilenol.theme import Theme
from tilenol.ewmh import get_title
@has_dependencies
class Title(Widget):
dispatcher = dependency(CommandDispa... | tilenol/widgets/title.py | from zorro.di import di, has_dependencies, dependency
from cairo import SolidPattern
import cairo
from .base import Widget
from tilenol.commands import CommandDispatcher
from tilenol.theme import Theme
from tilenol.ewmh import get_title
@has_dependencies
class Title(Widget):
dispatcher = dependency(CommandDispa... | 0.505127 | 0.065995 |
import math
from pathlib import Path
from typing import Tuple
import moderngl
import moderngl_window as mglw
from moderngl_window import geometry
from moderngl_window.scene.camera import KeyboardCamera
import numpy as np
from pyrr import Matrix44
class Object:
def __init__(self) -> None:
self._scale =... | visualization/CubeViz/cube_viz.py | import math
from pathlib import Path
from typing import Tuple
import moderngl
import moderngl_window as mglw
from moderngl_window import geometry
from moderngl_window.scene.camera import KeyboardCamera
import numpy as np
from pyrr import Matrix44
class Object:
def __init__(self) -> None:
self._scale =... | 0.900732 | 0.401043 |
from os import urandom
from typing import Callable
from typing import Collection
from typing import Dict
from typing import List
from typing import Optional
from typing import Text
from delorean import Delorean
from django.contrib.auth import get_user_model
from django.test import Client
from rest_framework import sta... | src/project/utils/xtests.py | from os import urandom
from typing import Callable
from typing import Collection
from typing import Dict
from typing import List
from typing import Optional
from typing import Text
from delorean import Delorean
from django.contrib.auth import get_user_model
from django.test import Client
from rest_framework import sta... | 0.799521 | 0.288575 |
import sys
import re
import itertools
class Moon:
def __init__(self, position, velocity):
self._position = position
self._velocity = velocity
def get_position(self):
return self._position
def pull_towards(self, position):
self._velocity = tuple(map(lambda x: self._new_axis(x, position), range(... | python/2019_12_1.py | import sys
import re
import itertools
class Moon:
def __init__(self, position, velocity):
self._position = position
self._velocity = velocity
def get_position(self):
return self._position
def pull_towards(self, position):
self._velocity = tuple(map(lambda x: self._new_axis(x, position), range(... | 0.389779 | 0.295211 |
import argparse
import plotly.graph_objects as go
import pandas as pd
import os
# Import processed data
from vaccine_dataprep_Swedentots import (
first_two_timeseries,
third_timseries,
fourth_timseries,
Swedish_population,
)
aparser = argparse.ArgumentParser(description="Generate text insert json")
ap... | Vaccine_page/vaccine_timeseries_barchart.py | import argparse
import plotly.graph_objects as go
import pandas as pd
import os
# Import processed data
from vaccine_dataprep_Swedentots import (
first_two_timeseries,
third_timseries,
fourth_timseries,
Swedish_population,
)
aparser = argparse.ArgumentParser(description="Generate text insert json")
ap... | 0.617282 | 0.419172 |
import sys
from drone.actions.emr_launcher import launch_emr_task
from drone.actions.ssh_launcher import launch_ssh_task
from drone.job_runner.dependency_manager import dependencies_are_met
from drone.job_runner.job_progress_checker import check_running_job_progress
from drone.metadata.metadata import get_job_info, job... | drone/job_runner/job_runner.py | import sys
from drone.actions.emr_launcher import launch_emr_task
from drone.actions.ssh_launcher import launch_ssh_task
from drone.job_runner.dependency_manager import dependencies_are_met
from drone.job_runner.job_progress_checker import check_running_job_progress
from drone.metadata.metadata import get_job_info, job... | 0.101673 | 0.057599 |
import io
import unittest
from contextlib import redirect_stdout
from unittest.mock import patch
class TestQ(unittest.TestCase):
@patch('builtins.input', side_effect=[
'42 42',
'__________________________________________',
'__________________________________________',
'____________... | hackerearth/Algorithms/Where is Checkerboard/test.py | import io
import unittest
from contextlib import redirect_stdout
from unittest.mock import patch
class TestQ(unittest.TestCase):
@patch('builtins.input', side_effect=[
'42 42',
'__________________________________________',
'__________________________________________',
'____________... | 0.228845 | 0.078501 |
import pykazoo.restrequest
import pykazoo.phonenumbers
from unittest import TestCase
from unittest.mock import create_autospec
mock_rest_request = create_autospec(pykazoo.restrequest.RestRequest)
class TestPhoneNumbers(TestCase):
def setUp(self):
self.mock_rest_request = mock_rest_request
self.p... | tests/test_phonenumbers.py | import pykazoo.restrequest
import pykazoo.phonenumbers
from unittest import TestCase
from unittest.mock import create_autospec
mock_rest_request = create_autospec(pykazoo.restrequest.RestRequest)
class TestPhoneNumbers(TestCase):
def setUp(self):
self.mock_rest_request = mock_rest_request
self.p... | 0.57069 | 0.28049 |
from typing import TYPE_CHECKING, Optional
from nats.js import api
from nats.js.errors import KeyDeletedError
from dataclasses import dataclass
import base64
if TYPE_CHECKING:
from nats.js import JetStreamContext
KV_OP = "KV-Operation"
KV_DEL = "DEL"
KV_PURGE = "PURGE"
MSG_ROLLUP_SUBJECT = "sub"
class KeyValue... | nats/js/kv.py |
from typing import TYPE_CHECKING, Optional
from nats.js import api
from nats.js.errors import KeyDeletedError
from dataclasses import dataclass
import base64
if TYPE_CHECKING:
from nats.js import JetStreamContext
KV_OP = "KV-Operation"
KV_DEL = "DEL"
KV_PURGE = "PURGE"
MSG_ROLLUP_SUBJECT = "sub"
class KeyValue... | 0.905465 | 0.207255 |
import os
import argparse
import pandas as pd
import torch
import torch.nn as nn
import torch.optim as optim
from train_test_api.train_api import train
from train_test_api.test_api import eval_training
from conf import settings
from utils import get_network, get_training_dataloader, get_valid_dataloader, get_test_data... | train_on_cell_datasets.py | import os
import argparse
import pandas as pd
import torch
import torch.nn as nn
import torch.optim as optim
from train_test_api.train_api import train
from train_test_api.test_api import eval_training
from conf import settings
from utils import get_network, get_training_dataloader, get_valid_dataloader, get_test_data... | 0.388618 | 0.202384 |
import attr
from bokeh.models import VArea
from bokeh.models.sources import DataSource
from typing import List, Tuple, Type, cast
from jira_analysis.cycle_time.cycle_time import CycleTime
from jira_analysis.cycle_time.stats import (
rolling_average_cycle_time,
standard_deviations,
)
from jira_analysis.chart.b... | jira_analysis/cycle_time/chart/cycle_time/deviation.py | import attr
from bokeh.models import VArea
from bokeh.models.sources import DataSource
from typing import List, Tuple, Type, cast
from jira_analysis.cycle_time.cycle_time import CycleTime
from jira_analysis.cycle_time.stats import (
rolling_average_cycle_time,
standard_deviations,
)
from jira_analysis.chart.b... | 0.841142 | 0.394901 |
import pprint
import re
import os
pp = pprint.PrettyPrinter(indent=4)
#------------------------------------------------------------------
#Defining the function
#------------------------------------------------------------------
def best_pos( sequence, primer):
nr_comp = 0
primer.upper()
sequence.upper... | primer_seq_counts.py | import pprint
import re
import os
pp = pprint.PrettyPrinter(indent=4)
#------------------------------------------------------------------
#Defining the function
#------------------------------------------------------------------
def best_pos( sequence, primer):
nr_comp = 0
primer.upper()
sequence.upper... | 0.056809 | 0.257048 |
import socketio
import json
import aiohttp
from aiohttp import web
import traceback
from appdaemon.appdaemon import AppDaemon
# socketio handler
class DashStream(socketio.AsyncNamespace):
def __init__(self, ADStream, path, AD):
super().__init__(path)
self.AD = AD
self.ADStream = ADStr... | appdaemon/stream.py | import socketio
import json
import aiohttp
from aiohttp import web
import traceback
from appdaemon.appdaemon import AppDaemon
# socketio handler
class DashStream(socketio.AsyncNamespace):
def __init__(self, ADStream, path, AD):
super().__init__(path)
self.AD = AD
self.ADStream = ADStr... | 0.344003 | 0.069164 |
import pandas as pd
data = {
'apples': [3,2,5,7],
'oranges': [1,8,4,0]
}
# initializing dataframe
count = pd.DataFrame(data)
print (count)
'''
apples oranges
0 3 1
1 2 8
2 5 4
3 7 0
'''
# updating index
count = pd.DataFrame(data, index=['... | pandas/pandasBasics.py | import pandas as pd
data = {
'apples': [3,2,5,7],
'oranges': [1,8,4,0]
}
# initializing dataframe
count = pd.DataFrame(data)
print (count)
'''
apples oranges
0 3 1
1 2 8
2 5 4
3 7 0
'''
# updating index
count = pd.DataFrame(data, index=['... | 0.162413 | 0.249893 |
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
STOP_RENDERING = runtime.STOP_RENDERING
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 10
_modified_time = 1516665949.6025667
_enable_loop = True
_template_filename = 'C:/Users/mayaroney/PycharmProjects/fomo/homepage/templates/s... | homepage/templates/.cached_templates/sections.html.py | from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
STOP_RENDERING = runtime.STOP_RENDERING
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 10
_modified_time = 1516665949.6025667
_enable_loop = True
_template_filename = 'C:/Users/mayaroney/PycharmProjects/fomo/homepage/templates/s... | 0.344113 | 0.092401 |
import os
import torch
import math
from pytorch_lightning.root_module.memory import ModelSummary
from pytorch_lightning.root_module.grads import GradInformation
from pytorch_lightning.root_module.model_saving import ModelIO, load_hparams_from_tags_csv
from pytorch_lightning.root_module.hooks import ModelHooks
class ... | pytorch_lightning/root_module/root_module.py | import os
import torch
import math
from pytorch_lightning.root_module.memory import ModelSummary
from pytorch_lightning.root_module.grads import GradInformation
from pytorch_lightning.root_module.model_saving import ModelIO, load_hparams_from_tags_csv
from pytorch_lightning.root_module.hooks import ModelHooks
class ... | 0.869146 | 0.432483 |
from . import array_create
def atleast_1d(*arys):
"""
Convert inputs to arrays with at least one dimension.
Scalar inputs are converted to 1-dimensional arrays, whilst
higher-dimensional inputs are preserved.
Parameters
----------
arys1, arys2, ... : array_like
One or more input ... | bridge/npbackend/bohrium/concatenate.py | from . import array_create
def atleast_1d(*arys):
"""
Convert inputs to arrays with at least one dimension.
Scalar inputs are converted to 1-dimensional arrays, whilst
higher-dimensional inputs are preserved.
Parameters
----------
arys1, arys2, ... : array_like
One or more input ... | 0.930703 | 0.848784 |
from tkinter import *
from tkinter import ttk, Text
class Writing_Block_Remover:
def __init__(self) -> None:
self.root = Tk()
self.root.geometry("800x400")
self.root.title("Writing Block Remover")
self.frm = ttk.Frame(self.root, padding=10)
self.frm.grid()
self.style... | main.py | from tkinter import *
from tkinter import ttk, Text
class Writing_Block_Remover:
def __init__(self) -> None:
self.root = Tk()
self.root.geometry("800x400")
self.root.title("Writing Block Remover")
self.frm = ttk.Frame(self.root, padding=10)
self.frm.grid()
self.style... | 0.314156 | 0.118666 |
"""Module that contains widgets for managing AiiDAlab applications."""
from subprocess import CalledProcessError
import ipywidgets as ipw
import traitlets
from aiidalab.app import AppRemoteUpdateStatus as AppStatus
from aiidalab.app import AppVersion
from jinja2 import Template
from packaging.version import parse
fr... | home/app_manager.py | """Module that contains widgets for managing AiiDAlab applications."""
from subprocess import CalledProcessError
import ipywidgets as ipw
import traitlets
from aiidalab.app import AppRemoteUpdateStatus as AppStatus
from aiidalab.app import AppVersion
from jinja2 import Template
from packaging.version import parse
fr... | 0.691081 | 0.18508 |
import os
# The DAG object; we'll need this to instantiate a DAG
from airflow import DAG
# Operators and utils required from airflow
from airflow.operators.bash import BashOperator
from airflow.operators.dummy import DummyOperator
from airflow.operators.python import BranchPythonOperator
from airflow.models import Va... | dlme_airflow/task_groups/validate_dlme_metadata.py | import os
# The DAG object; we'll need this to instantiate a DAG
from airflow import DAG
# Operators and utils required from airflow
from airflow.operators.bash import BashOperator
from airflow.operators.dummy import DummyOperator
from airflow.operators.python import BranchPythonOperator
from airflow.models import Va... | 0.419172 | 0.2349 |
from http import HTTPStatus
from django.contrib.auth import get_user_model
from django.test import Client, TestCase
from django.urls import reverse
from posts.models import Group, Post
User = get_user_model()
class PostsURLTests(TestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
... | yatube/posts/tests/test_urls.py | from http import HTTPStatus
from django.contrib.auth import get_user_model
from django.test import Client, TestCase
from django.urls import reverse
from posts.models import Group, Post
User = get_user_model()
class PostsURLTests(TestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
... | 0.46393 | 0.124372 |
import itertools
import re
from collections import Counter
import numpy as np
import pandas as pd
import pymystem3
mystem = pymystem3.Mystem()
def clean_str(string):
"""
Tokenization/string cleaning for all datasets except for SST.
Original taken from https://github.com/yoonkim/CNN_sentence/blob... | data_helpers.py | import itertools
import re
from collections import Counter
import numpy as np
import pandas as pd
import pymystem3
mystem = pymystem3.Mystem()
def clean_str(string):
"""
Tokenization/string cleaning for all datasets except for SST.
Original taken from https://github.com/yoonkim/CNN_sentence/blob... | 0.779783 | 0.555435 |
from unittest import mock
import pytest
@pytest.fixture
def apps():
""" Mocks 'apps.get_model()' parameter in migration """
from .models import DummyModel
mocked_apps = mock.MagicMock()
mocked_apps.get_model = mock.MagicMock(return_value=DummyModel)
return mocked_apps
@pytest.fixture
def schema_... | tests/test_migrating.py | from unittest import mock
import pytest
@pytest.fixture
def apps():
""" Mocks 'apps.get_model()' parameter in migration """
from .models import DummyModel
mocked_apps = mock.MagicMock()
mocked_apps.get_model = mock.MagicMock(return_value=DummyModel)
return mocked_apps
@pytest.fixture
def schema_... | 0.559049 | 0.430267 |
from copy import deepcopy
import numpy as np
from random import Random
class Matrix:
# Initializes to zero matrix
def __init__(self, row, col):
self.row = row
self.col = col
self.matrix = [[0 for x in range(self.row)] for x in range(self.col) ]
# String representation o... | ANN Python/matrix.py | from copy import deepcopy
import numpy as np
from random import Random
class Matrix:
# Initializes to zero matrix
def __init__(self, row, col):
self.row = row
self.col = col
self.matrix = [[0 for x in range(self.row)] for x in range(self.col) ]
# String representation o... | 0.850903 | 0.594993 |
from enum import Enum
import datetime
import pprint
import xmltodict
from connectinfo import RawConnectInfo
class ManifestType(Enum):
CREATE_SLIVER = 0
RENEW_OR_LIST_SLIVER = 1
class Manifest(object):
'''Object to store parsed manifest'''
def __init__(self, manifest, do_parse=True):
self.d... | metareserve_geni/internal/gni/py2/manifest/manifest.py | from enum import Enum
import datetime
import pprint
import xmltodict
from connectinfo import RawConnectInfo
class ManifestType(Enum):
CREATE_SLIVER = 0
RENEW_OR_LIST_SLIVER = 1
class Manifest(object):
'''Object to store parsed manifest'''
def __init__(self, manifest, do_parse=True):
self.d... | 0.38341 | 0.100834 |
import csv
import re
# Regular expression to detect potential string values with missing quotes
sql_fun = ['true', 'false', 'avg', 'count', 'first', 'last', 'max', 'min',
'sum', 'ucase', 'lcase', 'mid', 'len', 'round', 'now', 'format']
string_exp = re.compile('^(?!["\']|{}).*[a-z]'.format('|'.join(sql_fun))... | csv2db.py | import csv
import re
# Regular expression to detect potential string values with missing quotes
sql_fun = ['true', 'false', 'avg', 'count', 'first', 'last', 'max', 'min',
'sum', 'ucase', 'lcase', 'mid', 'len', 'round', 'now', 'format']
string_exp = re.compile('^(?!["\']|{}).*[a-z]'.format('|'.join(sql_fun))... | 0.627038 | 0.539287 |
from django.db import models
class MinistryTime(models.Model):
Ministry = models.ForeignKey('Ministry', on_delete=models.CASCADE)
start_date = models.DateField(
auto_now=False, auto_now_add=False, default=None)
end_date = models.DateField(
auto_now=False, auto_now_add=False, default=None)
... | cms/models/MinistryTime.py | from django.db import models
class MinistryTime(models.Model):
Ministry = models.ForeignKey('Ministry', on_delete=models.CASCADE)
start_date = models.DateField(
auto_now=False, auto_now_add=False, default=None)
end_date = models.DateField(
auto_now=False, auto_now_add=False, default=None)
... | 0.361954 | 0.150965 |
from django.test import TestCase
from .models import *
# Create your tests here.
class ProfileTestClass(TestCase):
# Set up method
def setUp(self):
"""creation of profile for testing
"""
user = User.objects.create(
username = 'ayubu',
first_name = 'ayub',
... | insta/tests.py | from django.test import TestCase
from .models import *
# Create your tests here.
class ProfileTestClass(TestCase):
# Set up method
def setUp(self):
"""creation of profile for testing
"""
user = User.objects.create(
username = 'ayubu',
first_name = 'ayub',
... | 0.439747 | 0.197657 |
import pytest
from django.test.client import Client
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from core import authentication
from sso.user.tests.factories import UserFactory
@pytest.fixture
def user():
return User... | core/tests/test_authentication.py | import pytest
from django.test.client import Client
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from core import authentication
from sso.user.tests.factories import UserFactory
@pytest.fixture
def user():
return User... | 0.572245 | 0.292456 |
import os
from typing import List, Tuple
import cv2
import numpy as np
def get_data(muscima_pp_cropped_images_directory: str, visualise: bool = False) -> Tuple[List[dict], dict, dict]:
found_bg = False
all_imgs = {}
classes_count = {}
class_mapping = {}
annotation_file = os.path.join(muscima_pp_... | keras_frcnn/muscima_pp_cropped_image_parser.py | import os
from typing import List, Tuple
import cv2
import numpy as np
def get_data(muscima_pp_cropped_images_directory: str, visualise: bool = False) -> Tuple[List[dict], dict, dict]:
found_bg = False
all_imgs = {}
classes_count = {}
class_mapping = {}
annotation_file = os.path.join(muscima_pp_... | 0.483161 | 0.206494 |
class Operator:
"""
The preconditions represent the facts that have to be true
before the operator can be applied.
add_effects are the facts that the operator makes true.
delete_effects are the facts that the operator makes false.
"""
def __init__(self, name, preconditions, add_effects, del_... | planner/mmp_explanations/src/grounder/task.py | class Operator:
"""
The preconditions represent the facts that have to be true
before the operator can be applied.
add_effects are the facts that the operator makes true.
delete_effects are the facts that the operator makes false.
"""
def __init__(self, name, preconditions, add_effects, del_... | 0.830766 | 0.669252 |
__author__ = 'HPE'
import sushy
from sushy.resources import base
from sushy.resources.system import system
from sushy import utils as sushy_utils
from proliantutils import exception
from proliantutils import log
from proliantutils.redfish.resources.system import bios
from proliantutils.redfish.resources.system impor... | proliantutils/redfish/resources/system/system.py |
__author__ = 'HPE'
import sushy
from sushy.resources import base
from sushy.resources.system import system
from sushy import utils as sushy_utils
from proliantutils import exception
from proliantutils import log
from proliantutils.redfish.resources.system import bios
from proliantutils.redfish.resources.system impor... | 0.621311 | 0.107531 |
__author__ = '<NAME>'
from LearningAlgorithm import *
class Backpropagation(LearningAlgorithm):
def learn(self, learningRate, input, output, network):
"""
:param learningRate: double
:param input: list
:param output: list
:param network: [[Neuron]]
:return: [[Neuron... | OptimizationAlgorithms/Backpropagation.py | __author__ = '<NAME>'
from LearningAlgorithm import *
class Backpropagation(LearningAlgorithm):
def learn(self, learningRate, input, output, network):
"""
:param learningRate: double
:param input: list
:param output: list
:param network: [[Neuron]]
:return: [[Neuron... | 0.717408 | 0.653922 |
from variational_clustering.clustering import furthest_init
from variational_clustering.clustering import make_faces
from variational_clustering.clustering import k_means
from directional_clustering.clustering.kmeans import KMeans
from directional_clustering.fields import VectorField
__all__ = ["VariationalKMeans"]... | src/directional_clustering/clustering/kmeans/variational.py | from variational_clustering.clustering import furthest_init
from variational_clustering.clustering import make_faces
from variational_clustering.clustering import k_means
from directional_clustering.clustering.kmeans import KMeans
from directional_clustering.fields import VectorField
__all__ = ["VariationalKMeans"]... | 0.916465 | 0.633524 |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='CarePayment',
fields=[
('id', models.AutoField(auto_create... | mnolms/seisnet/migrations/0001_initial.py |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='CarePayment',
fields=[
('id', models.AutoField(auto_create... | 0.404037 | 0.16378 |
"""Tests for TPU Embeddings mid level API on TPU."""
from absl.testing import parameterized
from tensorflow.python.compat import v2_compat
from tensorflow.python.distribute import distribute_lib
from tensorflow.python.eager import def_function
from tensorflow.python.framework.tensor_shape import TensorShape
from tenso... | tensorflow/python/tpu/tests/tpu_embedding_v2_sequence_feature_test.py | """Tests for TPU Embeddings mid level API on TPU."""
from absl.testing import parameterized
from tensorflow.python.compat import v2_compat
from tensorflow.python.distribute import distribute_lib
from tensorflow.python.eager import def_function
from tensorflow.python.framework.tensor_shape import TensorShape
from tenso... | 0.874077 | 0.515559 |
import re # Regular expression operations
import wikipedia # Python library that makes it easy to access and parse data from Wikipedia
import wikipedia.exceptions # Exceptions of wikipedia library
import requests.exceptions # HTTP for Humans
from ava.utilities import nostderr # Submodule of Dragonfire to provide ... | ava/commands/find_in_wikipedia.py | import re # Regular expression operations
import wikipedia # Python library that makes it easy to access and parse data from Wikipedia
import wikipedia.exceptions # Exceptions of wikipedia library
import requests.exceptions # HTTP for Humans
from ava.utilities import nostderr # Submodule of Dragonfire to provide ... | 0.516595 | 0.292608 |
import logging
import confluent_kafka
from oslo_utils import encodeutils
log = logging.getLogger(__name__)
class KafkaProducer(object):
"""Wrapper around asynchronous Kafka Producer"""
def __init__(self, bootstrap_servers, **config):
"""
Create new Producer wrapper instance.
:para... | monasca_common/confluent_kafka/producer.py |
import logging
import confluent_kafka
from oslo_utils import encodeutils
log = logging.getLogger(__name__)
class KafkaProducer(object):
"""Wrapper around asynchronous Kafka Producer"""
def __init__(self, bootstrap_servers, **config):
"""
Create new Producer wrapper instance.
:para... | 0.756088 | 0.104249 |
import os
import pytest
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
from nagare.renderers import xml
from nagare.renderers import html_base as html
def test_parse1():
h = html.HeadRenderer()
root = h.fromfile(StringIO('<html><body/></html>'))
assert isinstan... | tests/test_parse.py |
import os
import pytest
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
from nagare.renderers import xml
from nagare.renderers import html_base as html
def test_parse1():
h = html.HeadRenderer()
root = h.fromfile(StringIO('<html><body/></html>'))
assert isinstan... | 0.591841 | 0.320369 |
import datetime
from sqlalchemy import create_engine
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import sessionmaker
from configs import DatabaseConfig
from database.models import Base, MoneyChanger, MoneyChangerBranch, PaymentRequest
from balebot.utils.logger import Logger
logger = Logger.get_log... | database/operations.py | import datetime
from sqlalchemy import create_engine
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import sessionmaker
from configs import DatabaseConfig
from database.models import Base, MoneyChanger, MoneyChangerBranch, PaymentRequest
from balebot.utils.logger import Logger
logger = Logger.get_log... | 0.416322 | 0.061848 |
class Ropa:
def __init__(self):
pass
def tender(self, clima): # Ejemplo
if clima == "lluvia":
return "no tiendo"
else:
return "tiendo"
def tender_con_negacion(self, clima): # Ejemplo
"""
Este ejemplo es equivalente (esto quiere decir que par... | if_statement/if_statement.py |
class Ropa:
def __init__(self):
pass
def tender(self, clima): # Ejemplo
if clima == "lluvia":
return "no tiendo"
else:
return "tiendo"
def tender_con_negacion(self, clima): # Ejemplo
"""
Este ejemplo es equivalente (esto quiere decir que par... | 0.574514 | 0.469216 |
import torch
import numpy as np
# 'department' will be classified as 'course' in GCN
label2id = {
'student': 0,
'faculty': 1,
'project': 2,
'course': 3,
'staff': 4,
'department': 3,
}
id2label = {
0: 'student',
1: 'faculty',
2: 'project',
3: 'course',
4: 'staff',
}
def... | utils/dataloader.py | import torch
import numpy as np
# 'department' will be classified as 'course' in GCN
label2id = {
'student': 0,
'faculty': 1,
'project': 2,
'course': 3,
'staff': 4,
'department': 3,
}
id2label = {
0: 'student',
1: 'faculty',
2: 'project',
3: 'course',
4: 'staff',
}
def... | 0.545044 | 0.468365 |
import math
import argparse
import keras as K
import numpy as np
from KnowledgeGraph import KnowledgeGraph
from common import *
class TransE:
@property
def embedding_entity(self):
return self.__embedding_entity
@property
def embedding_relation(self):
return self.__embedding_relation
... | src/TransE.py | import math
import argparse
import keras as K
import numpy as np
from KnowledgeGraph import KnowledgeGraph
from common import *
class TransE:
@property
def embedding_entity(self):
return self.__embedding_entity
@property
def embedding_relation(self):
return self.__embedding_relation
... | 0.830903 | 0.209227 |
import tflearn
test = 'test'
train = 'training'
def getXY():
X, Y = tflearn.data_utils.image_preloader(train, image_shape=(
80, 80), mode='folder', categorical_labels='True', normalize=True)
return X, Y
def main():
'''
Establishes architecture for CNN-fully-connected-RNN neural net.
'''... | architecture.py | import tflearn
test = 'test'
train = 'training'
def getXY():
X, Y = tflearn.data_utils.image_preloader(train, image_shape=(
80, 80), mode='folder', categorical_labels='True', normalize=True)
return X, Y
def main():
'''
Establishes architecture for CNN-fully-connected-RNN neural net.
'''... | 0.83762 | 0.67858 |