code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
from flask import (
Blueprint,
abort,
current_app,
jsonify,
redirect,
render_template,
request,
session,
url_for,
)
from flask_user import roles_required
from ..database import db
from ..date_tools import localize_datetime
from ..extensions import oauth, recaptcha
from ..models.app_... | portal/eproms/views.py | from flask import (
Blueprint,
abort,
current_app,
jsonify,
redirect,
render_template,
request,
session,
url_for,
)
from flask_user import roles_required
from ..database import db
from ..date_tools import localize_datetime
from ..extensions import oauth, recaptcha
from ..models.app_... | 0.488771 | 0.108992 |
from django.contrib.auth.forms import UserCreationForm
from django.test import TestCase
from django.contrib.auth.models import User
# Create your tests here.
from django.urls import reverse,resolve
from ..views import signup
from ..forms import SignUpForm
class SignUpTests(TestCase):
def setUp(self):
url ... | accounts/tests/test_view_signup.py | from django.contrib.auth.forms import UserCreationForm
from django.test import TestCase
from django.contrib.auth.models import User
# Create your tests here.
from django.urls import reverse,resolve
from ..views import signup
from ..forms import SignUpForm
class SignUpTests(TestCase):
def setUp(self):
url ... | 0.443118 | 0.306161 |
import tensorflow as tf
import tensorflow_text as tf_text
import numpy as np
from tensorflow.keras.layers.experimental import preprocessing
def load_data(path):
# path = Path lib object (not string)
text = path.read_text(encoding='utf-8')
lines = text.splitlines()
pairs = [line.split('\t') for line ... | src/disfluency_generator/data_preparation.py | import tensorflow as tf
import tensorflow_text as tf_text
import numpy as np
from tensorflow.keras.layers.experimental import preprocessing
def load_data(path):
# path = Path lib object (not string)
text = path.read_text(encoding='utf-8')
lines = text.splitlines()
pairs = [line.split('\t') for line ... | 0.661595 | 0.465327 |
from ...imcmo import ManagedObject
from ...imccoremeta import MoPropertyMeta, MoMeta
from ...imcmeta import VersionMeta
class BiosVfCbsDfCmnDramNpsConsts:
VP_CBS_DF_CMN_DRAM_NPS_AUTO = "Auto"
VP_CBS_DF_CMN_DRAM_NPS_NPS0 = "NPS0"
VP_CBS_DF_CMN_DRAM_NPS_NPS1 = "NPS1"
VP_CBS_DF_CMN_DRAM_NPS_NPS2 = "NPS2... | imcsdk/mometa/bios/BiosVfCbsDfCmnDramNps.py |
from ...imcmo import ManagedObject
from ...imccoremeta import MoPropertyMeta, MoMeta
from ...imcmeta import VersionMeta
class BiosVfCbsDfCmnDramNpsConsts:
VP_CBS_DF_CMN_DRAM_NPS_AUTO = "Auto"
VP_CBS_DF_CMN_DRAM_NPS_NPS0 = "NPS0"
VP_CBS_DF_CMN_DRAM_NPS_NPS1 = "NPS1"
VP_CBS_DF_CMN_DRAM_NPS_NPS2 = "NPS2... | 0.414425 | 0.223525 |
import sys
sys.path.append('/home/cai/Documents/PyDMD/')
import numpy as np
import matplotlib.pyplot as plt
from read_dcm import DcmRead
import dicom
import SimpleITK as sitk
import os
image_dir = None #the results dir
"""
Input: iamge_sequence: the dce-mri data. the size is mn*t. m and n are related to the row and col... | PyDMD/DCE_tools/ti_curve.py | import sys
sys.path.append('/home/cai/Documents/PyDMD/')
import numpy as np
import matplotlib.pyplot as plt
from read_dcm import DcmRead
import dicom
import SimpleITK as sitk
import os
image_dir = None #the results dir
"""
Input: iamge_sequence: the dce-mri data. the size is mn*t. m and n are related to the row and col... | 0.203233 | 0.566198 |
import sys
from zlib import crc32
import numpy as np
import pytest
from distributed.protocol import (
serialize,
deserialize,
decompress,
dumps,
loads,
to_serialize,
msgpack,
)
from distributed.protocol.utils import BIG_BYTES_SHARD_SIZE
from distributed.protocol.numpy import itemsize
from ... | distributed/protocol/tests/test_numpy.py | import sys
from zlib import crc32
import numpy as np
import pytest
from distributed.protocol import (
serialize,
deserialize,
decompress,
dumps,
loads,
to_serialize,
msgpack,
)
from distributed.protocol.utils import BIG_BYTES_SHARD_SIZE
from distributed.protocol.numpy import itemsize
from ... | 0.423816 | 0.49231 |
import collections
import numpy as np
import os
import torch
import inference_util
import sis_util
from sufficient_input_subsets import sis
# Function to sort filenames by image index in path.
SR_SORT = lambda s: int(os.path.basename(s).split('_')[-1].split('.')[0])
LoadSISResults = collections.namedtuple(
'L... | sis_analysis_util.py |
import collections
import numpy as np
import os
import torch
import inference_util
import sis_util
from sufficient_input_subsets import sis
# Function to sort filenames by image index in path.
SR_SORT = lambda s: int(os.path.basename(s).split('_')[-1].split('.')[0])
LoadSISResults = collections.namedtuple(
'L... | 0.538741 | 0.34183 |
from tkinter import ttk
import tkinter
import webbrowser
import requests
from io import BytesIO
from PIL import Image, ImageTk
from core.compat import IS_WINDOWS
from .threadpool import thread_pool as _thread_pool
from urllib import parse
__author__ = 'zz'
class VarGetSetMixin:
def get(self):
return sel... | gui/widgets.py | from tkinter import ttk
import tkinter
import webbrowser
import requests
from io import BytesIO
from PIL import Image, ImageTk
from core.compat import IS_WINDOWS
from .threadpool import thread_pool as _thread_pool
from urllib import parse
__author__ = 'zz'
class VarGetSetMixin:
def get(self):
return sel... | 0.439026 | 0.067056 |
import pickle
from typing import List
from morphzero.ai.algorithms.hash_policy import HashPolicy, HashPolicyConfig
from morphzero.ai.base import EvaluationResult, TrainingData
from morphzero.common import board_to_string
from morphzero.games.connectfour.game import ConnectFourRules, ConnectFourState
from morphzero.gam... | morphzero/debug_main.py | import pickle
from typing import List
from morphzero.ai.algorithms.hash_policy import HashPolicy, HashPolicyConfig
from morphzero.ai.base import EvaluationResult, TrainingData
from morphzero.common import board_to_string
from morphzero.games.connectfour.game import ConnectFourRules, ConnectFourState
from morphzero.gam... | 0.579043 | 0.323113 |
import tensorflow as tf
from keras.callbacks import TensorBoard
import time
import os
import io
class TensorBoardColab:
def __init__(self, port=6006, graph_path='./Graph', startup_waiting_time=8):
self.port = port
self.graph_path = graph_path
self.writer = None
self.deep_writers = {}
get_ipython().system_ra... | quickcnn/setup_tbc.py | import tensorflow as tf
from keras.callbacks import TensorBoard
import time
import os
import io
class TensorBoardColab:
def __init__(self, port=6006, graph_path='./Graph', startup_waiting_time=8):
self.port = port
self.graph_path = graph_path
self.writer = None
self.deep_writers = {}
get_ipython().system_ra... | 0.335024 | 0.117218 |
import sys
from core.utils import get_media_from_email, month_range
from django.conf import settings
from django.contrib.auth.decorators import login_required, user_passes_test
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, redirect
from django.shortcuts im... | giza/views.py |
import sys
from core.utils import get_media_from_email, month_range
from django.conf import settings
from django.contrib.auth.decorators import login_required, user_passes_test
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, redirect
from django.shortcuts im... | 0.351534 | 0.153232 |
import matplotlib.pyplot as plt
import cPickle
import matplotlib as mpl
from numpy import *
colorbar = ['blue', 'green', 'red', 'yellow']
def plot(data, datay):
for ele, y in zip(data, datay):
plt.text(ele[0], ele[1], str(y), color = colorbar[y])
plt.xlim([-2, 2]);plt.ylim([-2, 2])
def plot_all(self... | ML/co-evaluate/createData.py | import matplotlib.pyplot as plt
import cPickle
import matplotlib as mpl
from numpy import *
colorbar = ['blue', 'green', 'red', 'yellow']
def plot(data, datay):
for ele, y in zip(data, datay):
plt.text(ele[0], ele[1], str(y), color = colorbar[y])
plt.xlim([-2, 2]);plt.ylim([-2, 2])
def plot_all(self... | 0.198763 | 0.563198 |
import json
import logging
from pathlib import Path, WindowsPath
from typing import Optional, Union
from .globals import get_settings_dir, SETTINGS_FILE_NAME, OPEN_VR_DLL, get_data_dir, APPS_STORE_FILE_NAME, get_version, KNOWN_APPS
from .utils import JsonRepr
class AppSettings(JsonRepr):
skip_keys = ['open_vr_fs... | app/app_settings.py | import json
import logging
from pathlib import Path, WindowsPath
from typing import Optional, Union
from .globals import get_settings_dir, SETTINGS_FILE_NAME, OPEN_VR_DLL, get_data_dir, APPS_STORE_FILE_NAME, get_version, KNOWN_APPS
from .utils import JsonRepr
class AppSettings(JsonRepr):
skip_keys = ['open_vr_fs... | 0.617974 | 0.085366 |
from dataclasses import dataclass, field
from typing import Dict, Optional, Tuple, Union
from .chaum_pedersen import ChaumPedersenProof
from .election_object_base import ElectionObjectBase
from .elgamal import ElGamalCiphertext
from .group import ElementModP, ElementModQ
from .logs import log_warning
from .types im... | src/electionguard/decryption_share.py | from dataclasses import dataclass, field
from typing import Dict, Optional, Tuple, Union
from .chaum_pedersen import ChaumPedersenProof
from .election_object_base import ElectionObjectBase
from .elgamal import ElGamalCiphertext
from .group import ElementModP, ElementModQ
from .logs import log_warning
from .types im... | 0.877391 | 0.277051 |
import contextlib
import os
import numpy as np
import torch.distributed
import torch.utils.data
from pytools.pyutils.io.serialize import dumps_pickle, loads_pickle
from pytools.pyutils.misc.decorator import check_fn, check_failed_message
__all__ = [
"activate",
"register_extra_group",
"unregister_extra_g... | third_party/pytools/pytools/pytorch/distributed.py | import contextlib
import os
import numpy as np
import torch.distributed
import torch.utils.data
from pytools.pyutils.io.serialize import dumps_pickle, loads_pickle
from pytools.pyutils.misc.decorator import check_fn, check_failed_message
__all__ = [
"activate",
"register_extra_group",
"unregister_extra_g... | 0.625209 | 0.165425 |
from __future__ import generator_stop
import os
import shutil
import tempfile
from utils import check_on_input
from modernize.__main__ import main as modernize_main
SINGLE_PRINT_CONTENT = """
print 'world'
"""
TWO_PRINTS_CONTENT = """
print 'Hello'
print 'world'
"""
COMPLICATED_CONTENT = """
print 'Hello'
print ... | tests/test_future_behaviour.py |
from __future__ import generator_stop
import os
import shutil
import tempfile
from utils import check_on_input
from modernize.__main__ import main as modernize_main
SINGLE_PRINT_CONTENT = """
print 'world'
"""
TWO_PRINTS_CONTENT = """
print 'Hello'
print 'world'
"""
COMPLICATED_CONTENT = """
print 'Hello'
print ... | 0.437103 | 0.106784 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Parameter
from torch.autograd import Variable
class DilatedLSTMCell(nn.Module):
def __init__(self, input_size, hidden_size, clock=10, bias=True):
super(DilatedLSTMCell, self).__init__()
self.input_size = inpu... | ai_challenge/models/dilated_rnn.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Parameter
from torch.autograd import Variable
class DilatedLSTMCell(nn.Module):
def __init__(self, input_size, hidden_size, clock=10, bias=True):
super(DilatedLSTMCell, self).__init__()
self.input_size = inpu... | 0.87157 | 0.499634 |
from __future__ import absolute_import
from scrapy.http.request import Request as ScrapyRequest
from scrapy.http.response import Response as ScrapyResponse
from frontera.core.models import Request as FrontierRequest
from frontera.core.models import Response as FrontierResponse
from frontera.utils.converters import Bas... | frontera/contrib/scrapy/converters.py | from __future__ import absolute_import
from scrapy.http.request import Request as ScrapyRequest
from scrapy.http.response import Response as ScrapyResponse
from frontera.core.models import Request as FrontierRequest
from frontera.core.models import Response as FrontierResponse
from frontera.utils.converters import Bas... | 0.606032 | 0.057467 |
import requests
import os.path
import json
import pprint
import sys
import getopt
class FHIRSearchClient:
''' Class to call FHIR server directly as a GA4GHSearch-like client
This does not use the fhirpy library '''
def __init__(self, hostURL, cookies, debug=False ):
self.hostURL = hostURL
self.debug = debug
s... | scripts/fhirpy/ncpi_fhir_requests_example.py | import requests
import os.path
import json
import pprint
import sys
import getopt
class FHIRSearchClient:
''' Class to call FHIR server directly as a GA4GHSearch-like client
This does not use the fhirpy library '''
def __init__(self, hostURL, cookies, debug=False ):
self.hostURL = hostURL
self.debug = debug
s... | 0.047702 | 0.075278 |
import frappe
from datetime import date
import calendar
from frappe import _
from frappe.utils.data import flt
def execute(filters=None):
columns, data = [], []
columns = get_columns()
tdata = get_emp_list(filters)
row = []
for item in tdata:
item_break = item[5]
sub_item = item_break[1:-1]
split_sub_ite... | tiger_app/tiger_app/report/salary_details_report/salary_details_report.py |
import frappe
from datetime import date
import calendar
from frappe import _
from frappe.utils.data import flt
def execute(filters=None):
columns, data = [], []
columns = get_columns()
tdata = get_emp_list(filters)
row = []
for item in tdata:
item_break = item[5]
sub_item = item_break[1:-1]
split_sub_ite... | 0.157655 | 0.200108 |
from enum import Enum
import uuid
from typing import Any, Optional, List
from ._helpers import construct_iso8601, process_row
from ._generated.models import (
BatchQueryRequest as InternalLogQueryRequest,
BatchQueryResponse,
)
class LogsTable(object):
"""Contains the columns and rows for one table in a ... | sdk/monitor/azure-monitor-query/azure/monitor/query/_models.py |
from enum import Enum
import uuid
from typing import Any, Optional, List
from ._helpers import construct_iso8601, process_row
from ._generated.models import (
BatchQueryRequest as InternalLogQueryRequest,
BatchQueryResponse,
)
class LogsTable(object):
"""Contains the columns and rows for one table in a ... | 0.919579 | 0.302018 |
import sys, os, argparse, shutil, math, re
def run():
# argparse Stuff
parser = argparse.ArgumentParser(description='Given an input bed file, this program will output a number of bed files, each will have same number of total base pairs. This routine is used to parallelize SomaticSeq tasks. One limitation, ... | somaticseq/utilities/split_Bed_into_equal_regions.py |
import sys, os, argparse, shutil, math, re
def run():
# argparse Stuff
parser = argparse.ArgumentParser(description='Given an input bed file, this program will output a number of bed files, each will have same number of total base pairs. This routine is used to parallelize SomaticSeq tasks. One limitation, ... | 0.399577 | 0.218711 |
# ==============================================================================
# IMPORTS
# ==============================================================================
from setuptools import setup, find_packages
import codecs
import os
import re
# ==================================================================... | setup.py | # ==============================================================================
# IMPORTS
# ==============================================================================
from setuptools import setup, find_packages
import codecs
import os
import re
# ==================================================================... | 0.530966 | 0.224991 |
from django.urls import path, re_path
from django.views.generic import TemplateView
from django.views.decorators.cache import cache_page
from .views import *
# Seconds * Minutes
#cache_time = 60 * 2
cache_time = 0
slash = '/?'
rest_urls = {
'cohort': 'rest/cohort/',
'trait': 'rest/trait/',
... | rest_api/urls.py | from django.urls import path, re_path
from django.views.generic import TemplateView
from django.views.decorators.cache import cache_page
from .views import *
# Seconds * Minutes
#cache_time = 60 * 2
cache_time = 0
slash = '/?'
rest_urls = {
'cohort': 'rest/cohort/',
'trait': 'rest/trait/',
... | 0.380068 | 0.069038 |
__author__ = '<EMAIL> (<NAME>)'
import os
import re
import sets
import sys
# We assume that this file is in the scripts/ directory in the Google
# Mock root directory.
DEFAULT_GMOCK_ROOT_DIR = os.path.join(os.path.dirname(__file__), '..')
# We need to call into gtest/scripts/fuse_gtest_files.py.
sys.path.append(os.p... | scripts/fuse_gmock_files.py | __author__ = '<EMAIL> (<NAME>)'
import os
import re
import sets
import sys
# We assume that this file is in the scripts/ directory in the Google
# Mock root directory.
DEFAULT_GMOCK_ROOT_DIR = os.path.join(os.path.dirname(__file__), '..')
# We need to call into gtest/scripts/fuse_gtest_files.py.
sys.path.append(os.p... | 0.45181 | 0.215743 |
import sys
import logging
import random
from pathlib import Path
import pandas as pd
from sklearn.model_selection import train_test_split
from tqdm import tqdm
def get_dataset(set_name, binary=False, **kwargs):
if set_name not in ['taxonomist', 'hpas', 'test', 'natops']:
raise ValueError("Wrong set_name"... | data_loading.py | import sys
import logging
import random
from pathlib import Path
import pandas as pd
from sklearn.model_selection import train_test_split
from tqdm import tqdm
def get_dataset(set_name, binary=False, **kwargs):
if set_name not in ['taxonomist', 'hpas', 'test', 'natops']:
raise ValueError("Wrong set_name"... | 0.33546 | 0.307631 |
import jwt
# The Users model
from models import User
# Importing the session
from db import session
# Datetime functionality
import datetime
# Reading the configuration file
import yaml
conf = yaml.safe_load(open("config.yml"))
# JWT constants
_SECRET = conf["jwt"]["secret"]
_ALGORITHM = conf["jwt"]["algorithm... | api-book/chapter-6-production-tools/jwt_token_example/jwt_tokens.py | import jwt
# The Users model
from models import User
# Importing the session
from db import session
# Datetime functionality
import datetime
# Reading the configuration file
import yaml
conf = yaml.safe_load(open("config.yml"))
# JWT constants
_SECRET = conf["jwt"]["secret"]
_ALGORITHM = conf["jwt"]["algorithm... | 0.722037 | 0.182153 |
import torch
import torch.nn as nn
from torch import sigmoid
from torch.nn.init import xavier_uniform_, zeros_, kaiming_uniform_
import torchvision as tv
def conv(in_planes, out_planes, kernel_size=3):
return nn.Sequential(
nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, padding=(kernel_size-1)/... | SfmLearner-Pytorch/models/PoseSep.py | import torch
import torch.nn as nn
from torch import sigmoid
from torch.nn.init import xavier_uniform_, zeros_, kaiming_uniform_
import torchvision as tv
def conv(in_planes, out_planes, kernel_size=3):
return nn.Sequential(
nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, padding=(kernel_size-1)/... | 0.932294 | 0.715325 |
import argparse
import subprocess as sp
import re
import os
import json
from parse_uniprot_entry_file import *
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--database_file', type=str, required=True, help="Path to the uniprot database file.")
parser.add_argument('-d',... | database/scripts/download_uniprot_as_files.py | import argparse
import subprocess as sp
import re
import os
import json
from parse_uniprot_entry_file import *
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--database_file', type=str, required=True, help="Path to the uniprot database file.")
parser.add_argument('-d',... | 0.371251 | 0.099865 |
import tensorflow as tf
from detext.layers.embedding_layer import create_embedding_layer
from detext.utils.layer_utils import get_sorted_dict
from detext.utils.parsing_utils import InputFtrType, InternalFtrType
class LstmLayer(tf.keras.layers.Layer):
def __init__(self, bidirectional, rnn_dropout, num_layers, for... | src/detext/layers/lstm_layer.py | import tensorflow as tf
from detext.layers.embedding_layer import create_embedding_layer
from detext.utils.layer_utils import get_sorted_dict
from detext.utils.parsing_utils import InputFtrType, InternalFtrType
class LstmLayer(tf.keras.layers.Layer):
def __init__(self, bidirectional, rnn_dropout, num_layers, for... | 0.872673 | 0.447279 |
import ctypes
import datetime
from time import sleep
import cv2
import numpy as np
import sounddevice as sd
from scipy.io import wavfile, loadmat
import csv
""" ~~~~~~~~~~~~~ TUNABLE PARAMETERS ~~~~~~~~~~~~~ """
# Name of the matlab file containing the test sequence
MAT_FILE_NAME = "NBACK_2_VersionA.mat"
# Th... | run_nback.py | import ctypes
import datetime
from time import sleep
import cv2
import numpy as np
import sounddevice as sd
from scipy.io import wavfile, loadmat
import csv
""" ~~~~~~~~~~~~~ TUNABLE PARAMETERS ~~~~~~~~~~~~~ """
# Name of the matlab file containing the test sequence
MAT_FILE_NAME = "NBACK_2_VersionA.mat"
# Th... | 0.592667 | 0.316726 |
from datamart.metadata.metadata_base import MetadataBase
from datamart.metadata.variable_metadata import VariableMetadata
from datamart.utils import Utils
class GlobalMetadata(MetadataBase):
def __init__(self, description: dict, datamart_id: int):
"""Init method of GlobalMetadata.
Args:
... | datamart/metadata/global_metadata.py | from datamart.metadata.metadata_base import MetadataBase
from datamart.metadata.variable_metadata import VariableMetadata
from datamart.utils import Utils
class GlobalMetadata(MetadataBase):
def __init__(self, description: dict, datamart_id: int):
"""Init method of GlobalMetadata.
Args:
... | 0.781205 | 0.138841 |
import numpy as np
from camos.tasks.analysis import Analysis
from camos.utils.generategui import (
NumericInput,
DatasetList,
CustomComboInput,
ImageInput,
)
from camos.plotter.image import Image
class Correlation(Analysis):
analysis_name = "Cluster Data"
required = ["dataset"]
def __ini... | camos/plugins/clustering/clustering.py | import numpy as np
from camos.tasks.analysis import Analysis
from camos.utils.generategui import (
NumericInput,
DatasetList,
CustomComboInput,
ImageInput,
)
from camos.plotter.image import Image
class Correlation(Analysis):
analysis_name = "Cluster Data"
required = ["dataset"]
def __ini... | 0.753739 | 0.435902 |
import os
import sys
def convert(filename, stream=sys.stdout):
fontname = os.path.splitext(os.path.basename(filename))[0]
fontname = fontname.replace('-', '_')
glyphs = []
comments = []
h = 16
w = 8
with open(filename) as handle:
for line in handle:
line = line.rstri... | site_scons/mkfont.py |
import os
import sys
def convert(filename, stream=sys.stdout):
fontname = os.path.splitext(os.path.basename(filename))[0]
fontname = fontname.replace('-', '_')
glyphs = []
comments = []
h = 16
w = 8
with open(filename) as handle:
for line in handle:
line = line.rstri... | 0.255715 | 0.076064 |
"""Generated protocol buffer code."""
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
# @@protoc_insertion_point(imports)
_sym_db = _symbol_databas... | forch/proto/grpc/device_report_pb2.py | """Generated protocol buffer code."""
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
# @@protoc_insertion_point(imports)
_sym_db = _symbol_databas... | 0.265404 | 0.089256 |
from django.utils import timezone
from pytz import UTC
from .availability_calendar_api import format_event_availability_calendar, activate_users_saved_timezone
from ..models import Event
from datetime import datetime, timedelta
def format_group_availability_calendar(event_id):
"""
Takes in event_id, accesses ... | LinkUp/core/apis/event_calendar_api.py | from django.utils import timezone
from pytz import UTC
from .availability_calendar_api import format_event_availability_calendar, activate_users_saved_timezone
from ..models import Event
from datetime import datetime, timedelta
def format_group_availability_calendar(event_id):
"""
Takes in event_id, accesses ... | 0.800731 | 0.368207 |
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from mephisto.data_model.assignment import (
Assignment,
InitializationData,
AssignmentState,
)
from mephisto.data_model.unit impo... | mephisto/operations/task_launcher.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from mephisto.data_model.assignment import (
Assignment,
InitializationData,
AssignmentState,
)
from mephisto.data_model.unit impo... | 0.684686 | 0.205755 |
from __future__ import absolute_import, division, print_function
from cctbx import crystal
from cctbx import sgtbx
from cctbx import xray
from cctbx.array_family import flex
from cctbx import miller
from mmtbx import max_lik
from mmtbx.max_lik import maxlik
from libtbx.test_utils import approx_equal
from libtbx.utils i... | mmtbx/max_lik/tst_maxlik.py | from __future__ import absolute_import, division, print_function
from cctbx import crystal
from cctbx import sgtbx
from cctbx import xray
from cctbx.array_family import flex
from cctbx import miller
from mmtbx import max_lik
from mmtbx.max_lik import maxlik
from libtbx.test_utils import approx_equal
from libtbx.utils i... | 0.544559 | 0.425247 |
import arcpy
import sys
import pyodbc
import datetime
# field names
X_fld = 'X'
Y_fld = 'Y'
PRECINCT_ID_fld = 'PRECINCT_ID'
COUNTY_ID_fld = 'COUNTY_ID'
RESIDENCE_ID_fld = 'RESIDENCE_ID'
VistaID_fld = 'VistaID'
try:
db = sys.argv[1]
db_username = sys.argv[2]
db_password = sys.argv[3]
db_server = sys.ar... | scripts/DJScript.py | import arcpy
import sys
import pyodbc
import datetime
# field names
X_fld = 'X'
Y_fld = 'Y'
PRECINCT_ID_fld = 'PRECINCT_ID'
COUNTY_ID_fld = 'COUNTY_ID'
RESIDENCE_ID_fld = 'RESIDENCE_ID'
VistaID_fld = 'VistaID'
try:
db = sys.argv[1]
db_username = sys.argv[2]
db_password = sys.argv[3]
db_server = sys.ar... | 0.091489 | 0.090053 |
import llnl.util.tty as tty
class Libsigsegv(AutotoolsPackage, GNUMirrorPackage):
"""GNU libsigsegv is a library for handling page faults in user mode."""
homepage = "https://www.gnu.org/software/libsigsegv/"
gnu_mirror_path = "libsigsegv/libsigsegv-2.12.tar.gz"
version('2.12', sha256='3ae1af359eeb... | var/spack/repos/builtin/packages/libsigsegv/package.py |
import llnl.util.tty as tty
class Libsigsegv(AutotoolsPackage, GNUMirrorPackage):
"""GNU libsigsegv is a library for handling page faults in user mode."""
homepage = "https://www.gnu.org/software/libsigsegv/"
gnu_mirror_path = "libsigsegv/libsigsegv-2.12.tar.gz"
version('2.12', sha256='3ae1af359eeb... | 0.63624 | 0.316171 |
lines = int(input())
table = []
for i in range(lines):
table.append(list(map(int, input().split(" "))))
def rotate(deg, table):
cout = []
if deg == 180:
for i in range(lines):
cout.append(table[i][::-1])
cout = cout[::-1]
elif deg == 90:
for i in range(lines):
... | archive/2018/Problem J4: Sunflowers.py | lines = int(input())
table = []
for i in range(lines):
table.append(list(map(int, input().split(" "))))
def rotate(deg, table):
cout = []
if deg == 180:
for i in range(lines):
cout.append(table[i][::-1])
cout = cout[::-1]
elif deg == 90:
for i in range(lines):
... | 0.179926 | 0.229104 |
import math
import sys
import numpy as np
import typeguard
from loguru import logger
def set_result_logger_level():
if "RESULT" not in logger._core.levels:
logger.level("RESULT", no=60, color="<cyan>")
def millify(num, precision=0):
"""Humanize number (e.g., 30000 --> 30k).
Taken from https://g... | utils.py | import math
import sys
import numpy as np
import typeguard
from loguru import logger
def set_result_logger_level():
if "RESULT" not in logger._core.levels:
logger.level("RESULT", no=60, color="<cyan>")
def millify(num, precision=0):
"""Humanize number (e.g., 30000 --> 30k).
Taken from https://g... | 0.661923 | 0.52342 |
import copy
import numpy as np
import numpy.linalg as la
import scipy
import time
from src.opt_trace import Trace, StochasticTrace
from src.utils import set_seed
SEED = 42
MAX_SEED = 10000000
class Optimizer:
"""
Base class for optimization algorithms. Provides methods to run them,
save the trace and p... | code/src/optimizer.py | import copy
import numpy as np
import numpy.linalg as la
import scipy
import time
from src.opt_trace import Trace, StochasticTrace
from src.utils import set_seed
SEED = 42
MAX_SEED = 10000000
class Optimizer:
"""
Base class for optimization algorithms. Provides methods to run them,
save the trace and p... | 0.746693 | 0.220133 |
import asyncio
import logging
from typing import Optional
from asyncio import StreamReader, StreamWriter
from .packet import Packet
from .exceptions import \
AuthenticationException, NulLResponseException, MaxRetriesExceedException
_DEFAULT_RCON_PORT = 25575
# Sent to server
_CMD_LOGIN = 3
_CMD_RUN = ... | asyncrcon/rcon.py | import asyncio
import logging
from typing import Optional
from asyncio import StreamReader, StreamWriter
from .packet import Packet
from .exceptions import \
AuthenticationException, NulLResponseException, MaxRetriesExceedException
_DEFAULT_RCON_PORT = 25575
# Sent to server
_CMD_LOGIN = 3
_CMD_RUN = ... | 0.683314 | 0.083068 |
import enum
import functools
import json
import os
import time
from typing import Any, Callable, Dict, List, Optional, Tuple
import dataclasses
import numpy as onp
from aqt.utils import tfevent_utils
EventSeries = tfevent_utils.EventSeries
# Type Aliases
# Nested dict mapping from component (first key), attribute ... | aqt/utils/report_utils.py | import enum
import functools
import json
import os
import time
from typing import Any, Callable, Dict, List, Optional, Tuple
import dataclasses
import numpy as onp
from aqt.utils import tfevent_utils
EventSeries = tfevent_utils.EventSeries
# Type Aliases
# Nested dict mapping from component (first key), attribute ... | 0.911451 | 0.406067 |
import traceback
from nova.openstack.common.report.models import with_default_views as mwdv
from nova.openstack.common.report.views.text import threading as text_views
class StackTraceModel(mwdv.ModelWithDefaultViews):
"""A Stack Trace Model
This model holds data from a python stack trace,
commonly extr... | nova/openstack/common/report/models/threading.py | import traceback
from nova.openstack.common.report.models import with_default_views as mwdv
from nova.openstack.common.report.views.text import threading as text_views
class StackTraceModel(mwdv.ModelWithDefaultViews):
"""A Stack Trace Model
This model holds data from a python stack trace,
commonly extr... | 0.488283 | 0.249893 |
from __future__ import print_function, division
# This is the original Python 2.7 build file, used in building GlowScript
# according to the scheme described in docs/MakingNewVersion.txt.
# A more sophisticated build program is build_cli.py contributed by <NAME>.
"""This python program converts various parts of glowsc... | glowscript-fix_helix_canvas_error/build_original.py | from __future__ import print_function, division
# This is the original Python 2.7 build file, used in building GlowScript
# according to the scheme described in docs/MakingNewVersion.txt.
# A more sophisticated build program is build_cli.py contributed by <NAME>.
"""This python program converts various parts of glowsc... | 0.331444 | 0.184657 |
import genprog.core as gp
import genprog.evolution as gpevo
from typing import Dict, List, Any, Set, Optional, Union, Tuple
import numpy as np
import vision_genprog.utilities
import cv2
import logging
possible_types = ['grayscale_image', 'color_image', 'binary_image',
'float', 'int', 'bool', 'vector2... | src/vision_genprog/tasks/image_processing.py | import genprog.core as gp
import genprog.evolution as gpevo
from typing import Dict, List, Any, Set, Optional, Union, Tuple
import numpy as np
import vision_genprog.utilities
import cv2
import logging
possible_types = ['grayscale_image', 'color_image', 'binary_image',
'float', 'int', 'bool', 'vector2... | 0.677687 | 0.448547 |
import ssl
import logging
import datetime
import pytz
from multidict import CIMultiDictProxy
from typing import List, Optional
from cryptoxlib.CryptoXLibClient import CryptoXLibClient, RestCallType
from cryptoxlib.clients.bitpanda import enums
from cryptoxlib.clients.bitpanda.exceptions import BitpandaRestException, B... | cryptoxlib/clients/bitpanda/BitpandaClient.py | import ssl
import logging
import datetime
import pytz
from multidict import CIMultiDictProxy
from typing import List, Optional
from cryptoxlib.CryptoXLibClient import CryptoXLibClient, RestCallType
from cryptoxlib.clients.bitpanda import enums
from cryptoxlib.clients.bitpanda.exceptions import BitpandaRestException, B... | 0.751648 | 0.162148 |
from typing import List, Optional
from qiskit.circuit import QuantumRegister, QuantumCircuit
from qiskit.circuit.library.standard_gates import MCXGate
class OR(QuantumCircuit):
r"""A circuit implementing the logical OR operation on a number of qubits.
For the OR operation the state :math:`|1\rangle` is inte... | qiskit/circuit/library/boolean_logic/quantum_or.py | from typing import List, Optional
from qiskit.circuit import QuantumRegister, QuantumCircuit
from qiskit.circuit.library.standard_gates import MCXGate
class OR(QuantumCircuit):
r"""A circuit implementing the logical OR operation on a number of qubits.
For the OR operation the state :math:`|1\rangle` is inte... | 0.966252 | 0.843959 |
import os
import subprocess
import time
import transmissionrpc
def get_rpc_client():
port = 9292
password = r"{<PASSWORD>"
username = ""
address = '0.0.0.0'
tc = transmissionrpc.Client(address=address,
port=port,
user=username,
... | sandbox/pdp2/TransmissionRpcTest.py | import os
import subprocess
import time
import transmissionrpc
def get_rpc_client():
port = 9292
password = r"{<PASSWORD>"
username = ""
address = '0.0.0.0'
tc = transmissionrpc.Client(address=address,
port=port,
user=username,
... | 0.137388 | 0.090937 |
from genesis_upgrade_tests.test_base import GenesisHeightBasedSimpleTestsCase
from test_framework.height_based_test_framework import SimpleTestDefinition
from test_framework.script import CScript, OP_CAT, OP_DUP
from test_framework.cdefs import MAX_SCRIPT_ELEMENT_SIZE_BEFORE_GENESIS, MAX_STACK_ELEMENTS_BEFORE_GENESIS,... | test/functional/genesis_upgrade_tests/max_stack_size.py |
from genesis_upgrade_tests.test_base import GenesisHeightBasedSimpleTestsCase
from test_framework.height_based_test_framework import SimpleTestDefinition
from test_framework.script import CScript, OP_CAT, OP_DUP
from test_framework.cdefs import MAX_SCRIPT_ELEMENT_SIZE_BEFORE_GENESIS, MAX_STACK_ELEMENTS_BEFORE_GENESIS,... | 0.446253 | 0.300771 |
import io
import os
from typing import NoReturn
import pytest
from engine.boards import Board, GenericBoard
from engine.constants import BOARDS
from tests import TEST_DIR, use_test_dir
from tests.engine import MOCK_CONFIG
class TestGenericBoard(object):
def setup_class(self) -> NoReturn:
self.conf_path... | tests/engine/test_boards.py |
import io
import os
from typing import NoReturn
import pytest
from engine.boards import Board, GenericBoard
from engine.constants import BOARDS
from tests import TEST_DIR, use_test_dir
from tests.engine import MOCK_CONFIG
class TestGenericBoard(object):
def setup_class(self) -> NoReturn:
self.conf_path... | 0.410756 | 0.448668 |
import logging
import os
import iris
from iris.analysis import MEAN
from iris.analysis.stats import pearsonr
from diagnostic import plot_diagnostic
from esmvaltool.diag_scripts.shared import group_metadata, run_diagnostic
logger = logging.getLogger(os.path.basename(__file__))
def get_provenance_record(attributes, ... | esmvaltool/diag_scripts/examples/correlate.py | import logging
import os
import iris
from iris.analysis import MEAN
from iris.analysis.stats import pearsonr
from diagnostic import plot_diagnostic
from esmvaltool.diag_scripts.shared import group_metadata, run_diagnostic
logger = logging.getLogger(os.path.basename(__file__))
def get_provenance_record(attributes, ... | 0.760651 | 0.288356 |
import mock
from neutron_lib import constants
from oslo_config import cfg
from neutron.agent.linux import dhcp
from neutron.agent.linux import ip_lib
from neutron.common import utils as common_utils
from neutron.conf.agent import common as config
from neutron.conf.agent import dhcp as dhcp_conf
from neutron.conf impo... | neutron/tests/functional/agent/linux/test_dhcp.py |
import mock
from neutron_lib import constants
from oslo_config import cfg
from neutron.agent.linux import dhcp
from neutron.agent.linux import ip_lib
from neutron.common import utils as common_utils
from neutron.conf.agent import common as config
from neutron.conf.agent import dhcp as dhcp_conf
from neutron.conf impo... | 0.496582 | 0.09611 |
# Add parent directory to path so that algobpy can be imported
import sys
sys.path.insert(0,'..')
from algobpy.parse import parseArgs
from pyteal import *
# source: https://github.com/algorand/smart-contracts/blob/master/devrel/poi/clawback-escrow.teal
def clawback_escrow(ASSET_ID, APP_ID):
# check properties of t... | examples/permissioned-token-freezing/assets/clawback-escrow.py |
# Add parent directory to path so that algobpy can be imported
import sys
sys.path.insert(0,'..')
from algobpy.parse import parseArgs
from pyteal import *
# source: https://github.com/algorand/smart-contracts/blob/master/devrel/poi/clawback-escrow.teal
def clawback_escrow(ASSET_ID, APP_ID):
# check properties of t... | 0.556882 | 0.373019 |
import json
import os
from abc import ABC, abstractmethod
from unittest.mock import ANY, patch
import pytest
from async_generator import async_generator, asynccontextmanager, yield_
from geopy import exc
from geopy.adapters import BaseAsyncAdapter
from geopy.location import Location
_env = {}
try:
with open(".te... | test/geocoders/util.py | import json
import os
from abc import ABC, abstractmethod
from unittest.mock import ANY, patch
import pytest
from async_generator import async_generator, asynccontextmanager, yield_
from geopy import exc
from geopy.adapters import BaseAsyncAdapter
from geopy.location import Location
_env = {}
try:
with open(".te... | 0.680454 | 0.416619 |
from django.test import TestCase
from rest_framework.authtoken.models import Token
from rest_framework import status
from rest_framework.test import APITestCase
from cride.circles.models import Circle, Invitation, Membership
from cride.users.models import Users, Profiles
class InvitationsManagerTestCase(TestCase):... | cride/tests/test_invitations.py |
from django.test import TestCase
from rest_framework.authtoken.models import Token
from rest_framework import status
from rest_framework.test import APITestCase
from cride.circles.models import Circle, Invitation, Membership
from cride.users.models import Users, Profiles
class InvitationsManagerTestCase(TestCase):... | 0.636918 | 0.354601 |
# Standard library imports
import sys
from urllib.parse import quote
# Third party imports
from qtpy.QtCore import Qt, QUrl, QUrlQuery, Signal
from qtpy.QtGui import QDesktopServices
from qtpy.QtWidgets import (QApplication, QCheckBox, QDialog, QFormLayout,
QHBoxLayout, QLabel, QLineEdit, Q... | spyder/widgets/reporterror.py | {dependencies} | 0.426322 | 0.103115 |
from django import template
from project import additional_scripts as scripts
from services import models
import os
from project.settings.base import PROJECT_ROOT
import re
import random
register = template.Library()
@register.filter(name='translite')
def translite(value, lang):
return scripts.Translite(value).tra... | project/mytemplatetags/templatetags/customtags.py | from django import template
from project import additional_scripts as scripts
from services import models
import os
from project.settings.base import PROJECT_ROOT
import re
import random
register = template.Library()
@register.filter(name='translite')
def translite(value, lang):
return scripts.Translite(value).tra... | 0.25128 | 0.110231 |
"""The psort CLI tool."""
import argparse
import collections
import os
# The following import makes sure the filters are registered.
from plaso import filters # pylint: disable=unused-import
# The following import makes sure the output modules are registered.
from plaso import output # pylint: disable=unused-impo... | plaso/cli/psort_tool.py | """The psort CLI tool."""
import argparse
import collections
import os
# The following import makes sure the filters are registered.
from plaso import filters # pylint: disable=unused-import
# The following import makes sure the output modules are registered.
from plaso import output # pylint: disable=unused-impo... | 0.74382 | 0.179567 |
import copy
import logging
import socket
from keystoneauth1 import adapter
from keystoneauth1 import exceptions as ksa_exc
import OpenSSL
from oslo_utils import importutils
from oslo_utils import netutils
import requests
import six
try:
import json
except ImportError:
import simplejson as json
from oslo_uti... | glanceclient/common/http.py |
import copy
import logging
import socket
from keystoneauth1 import adapter
from keystoneauth1 import exceptions as ksa_exc
import OpenSSL
from oslo_utils import importutils
from oslo_utils import netutils
import requests
import six
try:
import json
except ImportError:
import simplejson as json
from oslo_uti... | 0.566738 | 0.074164 |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
"""
FILE... | sdk/search/azure-search-documents/samples/sample_synonym_map_operations.py |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
"""
FILE... | 0.733356 | 0.318008 |
import math
from functools import reduce
from itertools import product
from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np
import torch
from torch import Tensor
Array = np.ndarray
Ints = Union[int, List[int], Tuple[int, ...]]
from pytorch_toolbelt.utils import pytorch_toolbelt_deprecated
_... | pytorch_toolbelt/inference/tiles.py | import math
from functools import reduce
from itertools import product
from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np
import torch
from torch import Tensor
Array = np.ndarray
Ints = Union[int, List[int], Tuple[int, ...]]
from pytorch_toolbelt.utils import pytorch_toolbelt_deprecated
_... | 0.930789 | 0.693428 |
from torchvision import datasets, transforms
from PIL import Image
import numpy as np
from torch.utils.data import Dataset, DataLoader
from torch.utils.data.sampler import SubsetRandomSampler
from torch.utils.data.dataloader import default_collate
import torchvision
import matplotlib.pyplot as plt
from torchvision imp... | dataloader2.py | from torchvision import datasets, transforms
from PIL import Image
import numpy as np
from torch.utils.data import Dataset, DataLoader
from torch.utils.data.sampler import SubsetRandomSampler
from torch.utils.data.dataloader import default_collate
import torchvision
import matplotlib.pyplot as plt
from torchvision imp... | 0.760917 | 0.585931 |
import sys
import math
# CONSTANTS
g = 3.711 # Gravity
max_angle = math.degrees(math.acos(g / 4)) - 1 # Maximum angle for constant vertical velocity at thrust 4
# PARAMETERS
min_h_speed = 10 # Minimum acceptable horizontal speed
min_v_distance = 750
# FIRST INPUTS
# The number of points used to draw the surface ... | Puzzles/Medium/003-Mars-Lander-Ep2.py | import sys
import math
# CONSTANTS
g = 3.711 # Gravity
max_angle = math.degrees(math.acos(g / 4)) - 1 # Maximum angle for constant vertical velocity at thrust 4
# PARAMETERS
min_h_speed = 10 # Minimum acceptable horizontal speed
min_v_distance = 750
# FIRST INPUTS
# The number of points used to draw the surface ... | 0.415017 | 0.61286 |
from pathlib import Path
from flake8_bandit import BanditTester
import pytest
def _get_errors(filename):
filename = Path(__file__).absolute().parent / filename
bt = BanditTester(tree=None, filename=str(filename), lines=None)
return list(bt.run())
@pytest.mark.parametrize(
"filename,line,message",
... | tests/test_bandit.py | from pathlib import Path
from flake8_bandit import BanditTester
import pytest
def _get_errors(filename):
filename = Path(__file__).absolute().parent / filename
bt = BanditTester(tree=None, filename=str(filename), lines=None)
return list(bt.run())
@pytest.mark.parametrize(
"filename,line,message",
... | 0.772874 | 0.61202 |
# pylint: disable=protected-access
import logging
import os
import pathlib
import subprocess
from contextlib import contextmanager
from shutil import rmtree
from typing import Any, Iterator, List, Type, Union
import pytest
from _pytest.monkeypatch import MonkeyPatch
from flaky import flaky
from packaging.version impor... | test/test_runtime.py | # pylint: disable=protected-access
import logging
import os
import pathlib
import subprocess
from contextlib import contextmanager
from shutil import rmtree
from typing import Any, Iterator, List, Type, Union
import pytest
from _pytest.monkeypatch import MonkeyPatch
from flaky import flaky
from packaging.version impor... | 0.783492 | 0.272787 |
import os
import shutil
import errno
from ..errors import error_response
from .fileio import joinpath
from flask import current_app
__all__ = ['get_lob_file', 'put_lob_file']
def get_lob_file(fsrc, fdest):
pass
def put_lob_file(fsrc, fdest):
'''Store the file to lobceder destination specified'''
if fde... | transmogrifier/api/utils/lobcder.py | import os
import shutil
import errno
from ..errors import error_response
from .fileio import joinpath
from flask import current_app
__all__ = ['get_lob_file', 'put_lob_file']
def get_lob_file(fsrc, fdest):
pass
def put_lob_file(fsrc, fdest):
'''Store the file to lobceder destination specified'''
if fde... | 0.121178 | 0.077483 |
import logging
import os
import subprocess
from common import app
from common import service
from common import utils
from common import docker_lib
from common import constants
from common import fm_logger
from manager.service_handler.mysql import aws_handler as awsh
fmlogging = fm_logger.Logging()
class AWSBuilder... | manager/builder/aws_builder.py | import logging
import os
import subprocess
from common import app
from common import service
from common import utils
from common import docker_lib
from common import constants
from common import fm_logger
from manager.service_handler.mysql import aws_handler as awsh
fmlogging = fm_logger.Logging()
class AWSBuilder... | 0.21684 | 0.046012 |
import fileinput
import sys
import subprocess
import os
class OtaAfrProject:
"""OtaAfrProject represents the Amazon FreeRTOS code base for OTA.
This class is used to update the Amazon FreeRTOS project for OTA.
Attributes:
_buildConfig(dict): Build configuration from 'build_config' field in board.js... | tools/ota_e2e_tests/aws_ota_test/aws_ota_project.py | import fileinput
import sys
import subprocess
import os
class OtaAfrProject:
"""OtaAfrProject represents the Amazon FreeRTOS code base for OTA.
This class is used to update the Amazon FreeRTOS project for OTA.
Attributes:
_buildConfig(dict): Build configuration from 'build_config' field in board.js... | 0.295738 | 0.075687 |
import json
import os
import sys
import pandas.io.sql as psql
import requests
crypto_tools_dir = os.getcwd().split('/scripts/')[0] + '/scripts/'
sys.path.append(crypto_tools_dir)
from crypto_tools import *
class PopulateCryptoCoinone(object):
"""
"""
def __init__(self):
"""
"""
... | scripts/populate_database/populate_coinone.py | import json
import os
import sys
import pandas.io.sql as psql
import requests
crypto_tools_dir = os.getcwd().split('/scripts/')[0] + '/scripts/'
sys.path.append(crypto_tools_dir)
from crypto_tools import *
class PopulateCryptoCoinone(object):
"""
"""
def __init__(self):
"""
"""
... | 0.130729 | 0.079997 |
import os
import yaml
from launch import LaunchDescription
from launch.actions import ExecuteProcess
from launch_ros.actions import Node
from ament_index_python.packages import get_package_share_directory
import xacro
def load_file(package_name, file_path):
package_path = get_package_share_directory(package_name)... | moveit_ros/moveit_servo/launch/pose_tracking_example.launch.py | import os
import yaml
from launch import LaunchDescription
from launch.actions import ExecuteProcess
from launch_ros.actions import Node
from ament_index_python.packages import get_package_share_directory
import xacro
def load_file(package_name, file_path):
package_path = get_package_share_directory(package_name)... | 0.580114 | 0.230216 |
import torch
import torch.nn as nn
import copy
import time
import shutil
import operator
import numpy as np
import random
import math
from PIL import Image, ImageOps
from torchvision import transforms
class AverageMeter():
"""Computes and stores the average and current value"""
def __init__(self):
sel... | code/utils.py | import torch
import torch.nn as nn
import copy
import time
import shutil
import operator
import numpy as np
import random
import math
from PIL import Image, ImageOps
from torchvision import transforms
class AverageMeter():
"""Computes and stores the average and current value"""
def __init__(self):
sel... | 0.743913 | 0.375477 |
import json
import falcon
from mock import PropertyMock, MagicMock, patch
from ddt import ddt, data, unpack
from tests import RestTestBase
from monitorrent.rest.settings_proxy import SettingsProxyEnabled, SettingsProxy
from monitorrent.settings_manager import SettingsManager
@ddt
class SettingsProxyEnabledTest(RestTe... | tests/rest/test_api_settings_proxy.py | import json
import falcon
from mock import PropertyMock, MagicMock, patch
from ddt import ddt, data, unpack
from tests import RestTestBase
from monitorrent.rest.settings_proxy import SettingsProxyEnabled, SettingsProxy
from monitorrent.settings_manager import SettingsManager
@ddt
class SettingsProxyEnabledTest(RestTe... | 0.5564 | 0.160036 |
import numpy as np
import tensorflow as tf
import gpflow as gpf
from kernel import LfmKernel
# TODO add docs
class LfmModel(gpf.models.GPR):
def __init__(
self,
data,
kernel,
num_output,
num_latent,
mean_function=None,
noise_variance=1.0,
):
""... | model.py | import numpy as np
import tensorflow as tf
import gpflow as gpf
from kernel import LfmKernel
# TODO add docs
class LfmModel(gpf.models.GPR):
def __init__(
self,
data,
kernel,
num_output,
num_latent,
mean_function=None,
noise_variance=1.0,
):
""... | 0.456168 | 0.50592 |
import numpy as np
from copy import copy
import warnings
from ..data import Dataset
import scipy.stats as stats
class VarianceThreshold:
def __init__(self, threshold=0):
"""
the variance threshold is a simple baseline approach to feature selection
it removes all features which variance doe... | src/si/data/feature_selection.py | import numpy as np
from copy import copy
import warnings
from ..data import Dataset
import scipy.stats as stats
class VarianceThreshold:
def __init__(self, threshold=0):
"""
the variance threshold is a simple baseline approach to feature selection
it removes all features which variance doe... | 0.53607 | 0.597373 |
from flask import Flask, render_template, jsonify, request
from bokeh.plotting import figure
import requests
from bokeh.embed import components
from bokeh.models import AjaxDataSource, CustomJS
from sys import stderr
from bokeh.models.widgets import DataTable, TableColumn
from datetime import datetime
from bokeh.models... | dashboard/app.py | from flask import Flask, render_template, jsonify, request
from bokeh.plotting import figure
import requests
from bokeh.embed import components
from bokeh.models import AjaxDataSource, CustomJS
from sys import stderr
from bokeh.models.widgets import DataTable, TableColumn
from datetime import datetime
from bokeh.models... | 0.314051 | 0.210746 |
from oslo_log import log as logging
from oslo_utils import importutils
from ironic.common import boot_devices
from ironic.common import exception
from ironic.drivers import base
from ironic.drivers.modules.cimc import common
imcsdk = importutils.try_import('ImcSdk')
LOG = logging.getLogger(__name__)
CIMC_TO_IRONIC... | ironic/drivers/modules/cimc/management.py |
from oslo_log import log as logging
from oslo_utils import importutils
from ironic.common import boot_devices
from ironic.common import exception
from ironic.drivers import base
from ironic.drivers.modules.cimc import common
imcsdk = importutils.try_import('ImcSdk')
LOG = logging.getLogger(__name__)
CIMC_TO_IRONIC... | 0.662141 | 0.11088 |
import superimport
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import minimize, line_search
def aoki_vectorized(x):
"""
F(x,y) = 0.5 (x^2 - y)^2 + 0.5 (x-1)^2
"""
f = 0.5 * np.square(np.square(x[:][0]) - x[:][1]) + 0.5 * np.square(x[:][0] - 1)
return f
def aoki(x):... | scripts/steepestDescentDemo.py | import superimport
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import minimize, line_search
def aoki_vectorized(x):
"""
F(x,y) = 0.5 (x^2 - y)^2 + 0.5 (x-1)^2
"""
f = 0.5 * np.square(np.square(x[:][0]) - x[:][1]) + 0.5 * np.square(x[:][0] - 1)
return f
def aoki(x):... | 0.556159 | 0.613237 |
import os
from pathlib import Path
from pants.base.build_environment import get_buildroot
from pants.option.scope import GLOBAL_SCOPE_CONFIG_SECTION
from pants.testutil.pants_run_integration_test import PantsRunIntegrationTest
class RunnerIntegrationTest(PantsRunIntegrationTest):
"""Test logic performed in PantsR... | tests/python/pants_test/bin/test_runner_integration.py |
import os
from pathlib import Path
from pants.base.build_environment import get_buildroot
from pants.option.scope import GLOBAL_SCOPE_CONFIG_SECTION
from pants.testutil.pants_run_integration_test import PantsRunIntegrationTest
class RunnerIntegrationTest(PantsRunIntegrationTest):
"""Test logic performed in PantsR... | 0.510741 | 0.276447 |
import timm
from torch import nn
from config import CFG
from loss_module import ArcMarginProduct, CurricularFace
class ShopeeModel(nn.Module):
def __init__(
self,
n_classes = CFG.CLASSES,
model_name = CFG.MODEL_NAME,
fc_dim = CFG.FC_DIM,
margin = CFG.MARGIN,
scale =... | input/shopee-competition-utils/shopee_image_model.py | import timm
from torch import nn
from config import CFG
from loss_module import ArcMarginProduct, CurricularFace
class ShopeeModel(nn.Module):
def __init__(
self,
n_classes = CFG.CLASSES,
model_name = CFG.MODEL_NAME,
fc_dim = CFG.FC_DIM,
margin = CFG.MARGIN,
scale =... | 0.909544 | 0.168446 |
from typing import List, Optional
from sharpy.interfaces import IZoneManager
from sharpy.managers.extensions import BuildDetector, ChatManager
from sharpy.plans.acts import *
from sharpy.plans.acts.terran import *
from sharpy.plans.require import *
from sharpy.plans.require.supply import SupplyType
from sharpy.plans.t... | dummies/terran/bio.py | from typing import List, Optional
from sharpy.interfaces import IZoneManager
from sharpy.managers.extensions import BuildDetector, ChatManager
from sharpy.plans.acts import *
from sharpy.plans.acts.terran import *
from sharpy.plans.require import *
from sharpy.plans.require.supply import SupplyType
from sharpy.plans.t... | 0.750736 | 0.417093 |
import cv2
import time
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GRAY = (127, 127, 127)
class ImageFilter:
"""
Responsible for applying filtering algorithms on the images.
"""
def __init__(self):
"""
A simple constructor that initializes variables used to crudely
time algori... | elegance/filter.py | import cv2
import time
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GRAY = (127, 127, 127)
class ImageFilter:
"""
Responsible for applying filtering algorithms on the images.
"""
def __init__(self):
"""
A simple constructor that initializes variables used to crudely
time algori... | 0.770249 | 0.560373 |
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class Quotation(Document):
pass
def auto_create_supplier_quotation(doc,method):
supplier=frappe.db.get_value('Supplier',{'is_internal_supplier':1,'represents_company':doc.company},'supplier_name')
company=frappe... | seabridge_app/seabridge_app/doctype/quotation/quotation.py |
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class Quotation(Document):
pass
def auto_create_supplier_quotation(doc,method):
supplier=frappe.db.get_value('Supplier',{'is_internal_supplier':1,'represents_company':doc.company},'supplier_name')
company=frappe... | 0.300027 | 0.148201 |
import aiohttp
import argparse
import asyncio
import functools
import json
import hmac
import logging
import pytz
import raftos
import time
from configparser import ConfigParser, NoSectionError, NoOptionError
from datetime import datetime, timedelta
from logging.handlers import SysLogHandler
from crontab import CronT... | beatle.py | import aiohttp
import argparse
import asyncio
import functools
import json
import hmac
import logging
import pytz
import raftos
import time
from configparser import ConfigParser, NoSectionError, NoOptionError
from datetime import datetime, timedelta
from logging.handlers import SysLogHandler
from crontab import CronT... | 0.420124 | 0.063453 |
import pyfos.pyfos_auth as pyfos_auth
import getpass
import getopt
import sys
import atexit
session = None
def exit_handler():
global session
if session is not None:
pyfos_auth.logout(session)
def exit_register(local_session):
global session
session = local_session
atexit.register(exit... | pyfos/utils/brcd_util.py | import pyfos.pyfos_auth as pyfos_auth
import getpass
import getopt
import sys
import atexit
session = None
def exit_handler():
global session
if session is not None:
pyfos_auth.logout(session)
def exit_register(local_session):
global session
session = local_session
atexit.register(exit... | 0.082805 | 0.064565 |
import gdb
import config
import midas_utils
from execution_context import ExecutionContext
def response(success,
message,
result,
type=None,
variableReference=0,
namedVariables=None,
indexedVariables=None,
memoryReference=None)... | modules/python/watch_variable.py | import gdb
import config
import midas_utils
from execution_context import ExecutionContext
def response(success,
message,
result,
type=None,
variableReference=0,
namedVariables=None,
indexedVariables=None,
memoryReference=None)... | 0.558568 | 0.101723 |
from world import world, setup_module, teardown_module
import create_source_steps as source_create
import create_dataset_steps as dataset_create
import create_ensemble_steps as ensemble_create
import create_prediction_steps as prediction_create
class TestEnsemblePrediction(object):
def setup(self):
"""
... | bigml/tests/test_09_ensemble_prediction.py | from world import world, setup_module, teardown_module
import create_source_steps as source_create
import create_dataset_steps as dataset_create
import create_ensemble_steps as ensemble_create
import create_prediction_steps as prediction_create
class TestEnsemblePrediction(object):
def setup(self):
"""
... | 0.49048 | 0.555194 |
import sys
import os.path
import pickle
from datetime import datetime
from adytum.util.sourceforge.base import login
# do a date check
filename, sfID, minDays, pickleFile = sys.argv[1:]
now = datetime.now()
minDays = int(minDays)
if os.path.exists(pickleFile):
fh = open(pickleFile)
lastSync = pickle.load(fh)
... | admin/syncSFRepo.py | import sys
import os.path
import pickle
from datetime import datetime
from adytum.util.sourceforge.base import login
# do a date check
filename, sfID, minDays, pickleFile = sys.argv[1:]
now = datetime.now()
minDays = int(minDays)
if os.path.exists(pickleFile):
fh = open(pickleFile)
lastSync = pickle.load(fh)
... | 0.093017 | 0.05375 |
import json
from monasca_notification import notification
def test_json():
"""Test the to_json method to verify it behaves as expected.
"""
ts = 1429029121239
alarm = {'alarmId': 'alarmId',
'alarmName': 'alarmName',
'timestamp': ts,
'stateChangeReason': 'stateCha... | tests/test_notification.py | import json
from monasca_notification import notification
def test_json():
"""Test the to_json method to verify it behaves as expected.
"""
ts = 1429029121239
alarm = {'alarmId': 'alarmId',
'alarmName': 'alarmName',
'timestamp': ts,
'stateChangeReason': 'stateCha... | 0.440469 | 0.161089 |
import os
from os import SEEK_CUR
from struct import unpack
import time
import numpy as np
from scipy import linalg
from ..pick import pick_types
from ...coreg import (read_elp, fit_matched_points, _decimate_points,
get_ras_to_neuromag_trans)
from ...utils import verbose, logger
from ...transfo... | mne/io/kit/kit.py |
import os
from os import SEEK_CUR
from struct import unpack
import time
import numpy as np
from scipy import linalg
from ..pick import pick_types
from ...coreg import (read_elp, fit_matched_points, _decimate_points,
get_ras_to_neuromag_trans)
from ...utils import verbose, logger
from ...transfo... | 0.681091 | 0.261698 |
# Import Statements
import subprocess # Subprocess example: subprocess.run(["ls", "-l"])
import pandas as pd
import datetime
import logging
# Function to convert microSWIFT file name to datetime
def get_microSWIFT_file_time(fname):
import datetime
# Convert Month string to month num
month_str = fname[-21:... | tools/getmicroSWIFTData.py | # Import Statements
import subprocess # Subprocess example: subprocess.run(["ls", "-l"])
import pandas as pd
import datetime
import logging
# Function to convert microSWIFT file name to datetime
def get_microSWIFT_file_time(fname):
import datetime
# Convert Month string to month num
month_str = fname[-21:... | 0.302082 | 0.243958 |
from codegen.utils import (
remove_c_comments,
blacken,
Patcher,
to_snake_case,
to_camel_case,
)
from pytest import raises
def dedent(code):
return code.replace("\n ", "\n")
def test_to_snake_case():
assert to_snake_case("foo_bar_spam") == "foo_bar_spam"
assert to_snake_case("_fo... | codegen/tests/test_codegen_utils.py | from codegen.utils import (
remove_c_comments,
blacken,
Patcher,
to_snake_case,
to_camel_case,
)
from pytest import raises
def dedent(code):
return code.replace("\n ", "\n")
def test_to_snake_case():
assert to_snake_case("foo_bar_spam") == "foo_bar_spam"
assert to_snake_case("_fo... | 0.621541 | 0.573977 |
import os
import pandas as pd
from statapy.utils import column_corrector
class DataSet(object):
"""
Class to hold a pandas dataset under the data field.
"""
def __init__(self, name, filename="", url="", data=None):
"""
:param name: Name of the DataSet object
:param filename: ... | statapy/data/dataset.py | import os
import pandas as pd
from statapy.utils import column_corrector
class DataSet(object):
"""
Class to hold a pandas dataset under the data field.
"""
def __init__(self, name, filename="", url="", data=None):
"""
:param name: Name of the DataSet object
:param filename: ... | 0.567937 | 0.388328 |
from .base import Folder
from .collections import FolderCollection
from ..items import CalendarItem, Contact, Message, Task, DistributionList, MeetingRequest, MeetingResponse, \
MeetingCancellation, ITEM_CLASSES, ASSOCIATED
from ..version import EXCHANGE_2010_SP1, EXCHANGE_2013, EXCHANGE_2013_SP1
class Calendar(F... | exchangelib/folders/known_folders.py | from .base import Folder
from .collections import FolderCollection
from ..items import CalendarItem, Contact, Message, Task, DistributionList, MeetingRequest, MeetingResponse, \
MeetingCancellation, ITEM_CLASSES, ASSOCIATED
from ..version import EXCHANGE_2010_SP1, EXCHANGE_2013, EXCHANGE_2013_SP1
class Calendar(F... | 0.566978 | 0.128662 |
from typing import Optional
from pydantic import BaseModel, Field
from enum import Enum
class MobileHandsetPriceModelInput(BaseModel):
"""Schema for input of the model's predict method."""
battery_power: Optional[int] = Field(None, title="battery_power", ge=500, le=2000,
... | mobile_handset_price_model/prediction/schemas.py | from typing import Optional
from pydantic import BaseModel, Field
from enum import Enum
class MobileHandsetPriceModelInput(BaseModel):
"""Schema for input of the model's predict method."""
battery_power: Optional[int] = Field(None, title="battery_power", ge=500, le=2000,
... | 0.946516 | 0.409162 |
import sys
import liqui_client
if len(sys.argv) < 2:
print("Usage: print-account-info.py <key file>")
print(" key file - Path to a file containing key/secret/nonce data")
sys.exit(1)
key_file = sys.argv[1]
with liqui_client.KeyHandler(key_file) as handler:
if not handler.keys:
print("No key... | samples/print-account-info.py | import sys
import liqui_client
if len(sys.argv) < 2:
print("Usage: print-account-info.py <key file>")
print(" key file - Path to a file containing key/secret/nonce data")
sys.exit(1)
key_file = sys.argv[1]
with liqui_client.KeyHandler(key_file) as handler:
if not handler.keys:
print("No key... | 0.085094 | 0.144089 |
import android
import sys
from behave import step
reload(sys)
sys.setdefaultencoding('utf-8')
# launch android app by its package name and activity name
@step(u'I launch "{app_name}" with "{apk_pkg_name}" and "{apk_activity_name}" on android')
def launch_app_by_names(context, app_name, apk_pkg_name, apk_activity_nam... | tools/atip/atip/android/steps.py |
import android
import sys
from behave import step
reload(sys)
sys.setdefaultencoding('utf-8')
# launch android app by its package name and activity name
@step(u'I launch "{app_name}" with "{apk_pkg_name}" and "{apk_activity_name}" on android')
def launch_app_by_names(context, app_name, apk_pkg_name, apk_activity_nam... | 0.444324 | 0.156169 |
import sys
from timeit import Timer
from random import shuffle
from bintrees import RBTree
from bintrees import FastRBTree, has_fast_tree_support
COUNT = 100
setup_RBTree = """
from __main__ import rb_build_delete, rb_build, rb_search
"""
setup_FastRBTree = """
from __main__ import crb_build_delete, crb_build, crb_... | thirdparty/bintrees-2.0.7/profiling/profile_rbtree.py |
import sys
from timeit import Timer
from random import shuffle
from bintrees import RBTree
from bintrees import FastRBTree, has_fast_tree_support
COUNT = 100
setup_RBTree = """
from __main__ import rb_build_delete, rb_build, rb_search
"""
setup_FastRBTree = """
from __main__ import crb_build_delete, crb_build, crb_... | 0.247896 | 0.149035 |