code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
import sys
_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... | protobuf/SubscribeReq_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.177561 | 0.09782 |
import array
import time
try:
import pulseio
except ImportError as excpt:
print("adafruit_dht requires the pulseio library, but it failed to load."+
" Note that CircuitPython does not support pulseio on all boards.")
raise excpt
__version__ = "0.0.0-auto.0"
__repo__ = "https://github.com/adafrui... | adafruit_dht.py | import array
import time
try:
import pulseio
except ImportError as excpt:
print("adafruit_dht requires the pulseio library, but it failed to load."+
" Note that CircuitPython does not support pulseio on all boards.")
raise excpt
__version__ = "0.0.0-auto.0"
__repo__ = "https://github.com/adafrui... | 0.715225 | 0.439807 |
def test_regression_737():
import xml # [unused-import]
def test_regression_923():
import unittest.case # [unused-import]
import xml as sql # [unused-import]
def test_unused_with_prepended_underscore():
_foo = 42
_ = 24
__a = 24
dummy = 24
_a_ = 42 # [unused-variable]
__a__ = 24 ... | vimfiles/bundle/vim-python/submodules/pylint/tests/functional/u/unused/unused_variable.py |
def test_regression_737():
import xml # [unused-import]
def test_regression_923():
import unittest.case # [unused-import]
import xml as sql # [unused-import]
def test_unused_with_prepended_underscore():
_foo = 42
_ = 24
__a = 24
dummy = 24
_a_ = 42 # [unused-variable]
__a__ = 24 ... | 0.311322 | 0.250729 |
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing pe... | naslib/predictors/utils/models/nasbench2_ops.py |
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing pe... | 0.932607 | 0.320555 |
from .kernel.astro import conversion as _oec
import numpy as np
def spherical2cartesian(r,
lat,
lon,
speed,
fpa,
heading) -> np.ndarray:
"""
Function to convert spherical state to cartesian.... | tudatpy/elements.py | from .kernel.astro import conversion as _oec
import numpy as np
def spherical2cartesian(r,
lat,
lon,
speed,
fpa,
heading) -> np.ndarray:
"""
Function to convert spherical state to cartesian.... | 0.871242 | 0.742001 |
from django.conf import settings
from restclients.canvas import Canvas
from restclients.exceptions import DataFailureException
from restclients.models.canvas import Report, ReportType, Attachment
from urllib3 import PoolManager
from time import sleep
import re
class ReportFailureException(Exception):
"""
This... | restclients/canvas/reports.py | from django.conf import settings
from restclients.canvas import Canvas
from restclients.exceptions import DataFailureException
from restclients.models.canvas import Report, ReportType, Attachment
from urllib3 import PoolManager
from time import sleep
import re
class ReportFailureException(Exception):
"""
This... | 0.598312 | 0.14551 |
from os import listdir
from discord.ext import commands
from discord.ext.commands import CommandNotFound, MissingRequiredArgument, CommandInvokeError, MissingRole, \
NoPrivateMessage
import discord
from ruamel.yaml import YAML
import logging
import os
from dotenv import load_dotenv
from Systems.levelsy... | main.py | from os import listdir
from discord.ext import commands
from discord.ext.commands import CommandNotFound, MissingRequiredArgument, CommandInvokeError, MissingRole, \
NoPrivateMessage
import discord
from ruamel.yaml import YAML
import logging
import os
from dotenv import load_dotenv
from Systems.levelsy... | 0.248261 | 0.067762 |
import cython
if not cython.compiled:
from disk import *
from collections import namedtuple
# A class that packs multiple inodes together into a single block
class InodePackDisk(object):
# Field index for meta-data
SIZE = 0
MTIME = 1
MODE = 2
NLINK = 3
_UNUSED = 4
OFF = 5
def __... | yggdrasil/legacy_inodepack.py | import cython
if not cython.compiled:
from disk import *
from collections import namedtuple
# A class that packs multiple inodes together into a single block
class InodePackDisk(object):
# Field index for meta-data
SIZE = 0
MTIME = 1
MODE = 2
NLINK = 3
_UNUSED = 4
OFF = 5
def __... | 0.507568 | 0.21103 |
from __future__ import unicode_literals
success_send_action_response = {
'recipient_id': '111',
}
success_send_attachment_response = {
'recipient_id': '111',
'message_id': 'mid.1469190965111:a229991ed7b8f01222'
}
failed_send_response = {
'error': {
'message': 'Invalid OAuth access token.',
... | tests/data.py | from __future__ import unicode_literals
success_send_action_response = {
'recipient_id': '111',
}
success_send_attachment_response = {
'recipient_id': '111',
'message_id': 'mid.1469190965111:a229991ed7b8f01222'
}
failed_send_response = {
'error': {
'message': 'Invalid OAuth access token.',
... | 0.278846 | 0.278061 |
from datetime import datetime
from lxml import etree
from lxml.builder import ElementMaker
from opds import ContentType, Namespace, LinkRel
def make_entry(values):
"""Create atom:entry element from dict which follow structure:
{
'title': str, # REQUIRED
'_id': str, # RE... | scieloopds/renderers.py | from datetime import datetime
from lxml import etree
from lxml.builder import ElementMaker
from opds import ContentType, Namespace, LinkRel
def make_entry(values):
"""Create atom:entry element from dict which follow structure:
{
'title': str, # REQUIRED
'_id': str, # RE... | 0.759761 | 0.309363 |
import torch
import torchvision
import os
import re
import time
import zipfile
import shutil
import tqdm
import random
from torch.utils.data import sampler
from PIL import Image
from itertools import cycle, islice
# ========================================================
# Dataset-related functions and classes
# ===... | examples/gans/src/utils.py | import torch
import torchvision
import os
import re
import time
import zipfile
import shutil
import tqdm
import random
from torch.utils.data import sampler
from PIL import Image
from itertools import cycle, islice
# ========================================================
# Dataset-related functions and classes
# ===... | 0.667148 | 0.33659 |
import argparse
import os
import cv2
import numpy as np
import tensorflow as tf
from BoxInceptionResnet import BoxInceptionResnet
from Visualize import Visualize
from Utils import CheckpointLoader
from Utils import PreviewIO
parser = argparse.ArgumentParser(description="RFCN tester")
parser.add_argument('-gpu', type=... | test.py |
import argparse
import os
import cv2
import numpy as np
import tensorflow as tf
from BoxInceptionResnet import BoxInceptionResnet
from Visualize import Visualize
from Utils import CheckpointLoader
from Utils import PreviewIO
parser = argparse.ArgumentParser(description="RFCN tester")
parser.add_argument('-gpu', type=... | 0.37399 | 0.165357 |
import os
import smtplib
import alerts.destination_base as destination_base
def split_addresses(addresses_string):
if ',' in addresses_string:
return addresses_string.split(',')
if ';' in addresses_string:
return addresses_string.split(';')
return [addresses_string]
class EmailDestina... | alerts/destination_email.py | import os
import smtplib
import alerts.destination_base as destination_base
def split_addresses(addresses_string):
if ',' in addresses_string:
return addresses_string.split(',')
if ';' in addresses_string:
return addresses_string.split(';')
return [addresses_string]
class EmailDestina... | 0.432782 | 0.109706 |
# Standard library imports
from typing import List, Optional, Tuple, Union
import mxnet as mx
import numpy as np
from mxnet.gluon import nn
# First-party imports
from gluonts.core.component import validated
from gluonts.dataset.common import Dataset
from gluonts.model.common import Tensor
from gluonts.mx.context imp... | src/gluonts/mx/representation/discrete_pit.py |
# Standard library imports
from typing import List, Optional, Tuple, Union
import mxnet as mx
import numpy as np
from mxnet.gluon import nn
# First-party imports
from gluonts.core.component import validated
from gluonts.dataset.common import Dataset
from gluonts.model.common import Tensor
from gluonts.mx.context imp... | 0.959875 | 0.590838 |
from caldavclientlibrary.protocol.http.authentication.authenticator import Authenticator
from caldavclientlibrary.protocol.http.util import parsetoken
from caldavclientlibrary.protocol.http.definitions import headers
from StringIO import StringIO
import hashlib
import uuid
class Digest(Authenticator):
def __ini... | caldavclientlibrary/protocol/http/authentication/digest.py |
from caldavclientlibrary.protocol.http.authentication.authenticator import Authenticator
from caldavclientlibrary.protocol.http.util import parsetoken
from caldavclientlibrary.protocol.http.definitions import headers
from StringIO import StringIO
import hashlib
import uuid
class Digest(Authenticator):
def __ini... | 0.687 | 0.154153 |
import os
import numpy as np
import json
import pytest
from django.utils.datastructures import MultiValueDict
from pytest_mock import mocker
import torch
from capreolus.collection import Collection
from capreolus.demo_app.views import ConfigsView, NeuralQueryView, QueryDictParserMixin, CompareNeuralQueryView, BM25Vi... | capreolus/demo_app/tests/test_views.py | import os
import numpy as np
import json
import pytest
from django.utils.datastructures import MultiValueDict
from pytest_mock import mocker
import torch
from capreolus.collection import Collection
from capreolus.demo_app.views import ConfigsView, NeuralQueryView, QueryDictParserMixin, CompareNeuralQueryView, BM25Vi... | 0.657868 | 0.407451 |
import json
import csv
import time
from PageReader import PageReader
# Main class, loads config, runs the scrape, and handles scrape output
class SiteScraper:
# Config data loaded from JSON
config = None
# Raw page scraper results
results = {}
# Results after analysis (collation, key counting, etc.... | SiteScraper.py | import json
import csv
import time
from PageReader import PageReader
# Main class, loads config, runs the scrape, and handles scrape output
class SiteScraper:
# Config data loaded from JSON
config = None
# Raw page scraper results
results = {}
# Results after analysis (collation, key counting, etc.... | 0.474144 | 0.146973 |
import os,socket,pickle,time
from threading import Thread,Lock
from templates import DEFAULT_PAGE,TEMPLATE_MAPPING
from urllib import parse
def set_dir(path) -> str:
lst = os.listdir(path)
setting_dir = f'{path}/DB'
if not 'DB' in lst:
os.mkdir(setting_dir)
return setting_dir
PATH = os.path.d... | linux-server/http_manager.py | import os,socket,pickle,time
from threading import Thread,Lock
from templates import DEFAULT_PAGE,TEMPLATE_MAPPING
from urllib import parse
def set_dir(path) -> str:
lst = os.listdir(path)
setting_dir = f'{path}/DB'
if not 'DB' in lst:
os.mkdir(setting_dir)
return setting_dir
PATH = os.path.d... | 0.276105 | 0.114418 |
from recoDataStructure import *
class DataReceiver:
"""This class helps us to read data into the program.
During the training stage, it can read data from file
and during recognition stage, it can get real time tracking data and
pass it to the Feature Extraction module."""
def __init__(... | dataAcquisition.py | from recoDataStructure import *
class DataReceiver:
"""This class helps us to read data into the program.
During the training stage, it can read data from file
and during recognition stage, it can get real time tracking data and
pass it to the Feature Extraction module."""
def __init__(... | 0.550366 | 0.532121 |
import json
import requests
import time
from datetime import datetime
from kolekto.printer import printer
from kolekto.datasources import Datasource, DefaultDatasourceSchema
from kolekto.exceptions import KolektoRuntimeError
from confiture.schema.containers import Value
from confiture.schema.types import String, Inte... | kolekto/datasources/tmdb.py | import json
import requests
import time
from datetime import datetime
from kolekto.printer import printer
from kolekto.datasources import Datasource, DefaultDatasourceSchema
from kolekto.exceptions import KolektoRuntimeError
from confiture.schema.containers import Value
from confiture.schema.types import String, Inte... | 0.362292 | 0.066387 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from . import outputs
__all__ = [
'GetCertificateOrderResult',
'AwaitableGetCertificateOrderResult',
'get_certificate_order',
'get_certificate_order_output... | sdk/python/pulumi_azure/appservice/get_certificate_order.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from . import outputs
__all__ = [
'GetCertificateOrderResult',
'AwaitableGetCertificateOrderResult',
'get_certificate_order',
'get_certificate_order_output... | 0.803405 | 0.090776 |
import os
import sys
import logging
import argparse
import re
import glob
VARIABLE_DECL = r'^variable\s+\"([\w_]+)\"\s+{'
VARIABLE = r'var\.([\w_]+)'
found = 0
log = logging.getLogger(__name__)
log.setLevel(level=os.environ.get("LOGLEVEL", logging.INFO))
loghandler = logging.StreamHandler()
formatter = logging.Format... | terraform_unused_vars/__main__.py | import os
import sys
import logging
import argparse
import re
import glob
VARIABLE_DECL = r'^variable\s+\"([\w_]+)\"\s+{'
VARIABLE = r'var\.([\w_]+)'
found = 0
log = logging.getLogger(__name__)
log.setLevel(level=os.environ.get("LOGLEVEL", logging.INFO))
loghandler = logging.StreamHandler()
formatter = logging.Format... | 0.234494 | 0.060641 |
from django.utils import tree
import re
FILTER_CONTAINS = u'%(field)s:%(value)s'
FILTER_EXACT = u'%(field)s:"%(value)s"'
FILTER_COMPARE = {
'gt': u'%(field)s:{%(value)s TO *}',
'gte': u'%(field)s:[%(value)s TO *]',
'lt': u'%(field)s:{* TO %(value)s}',
'lte': u'%(field)s:[* TO %(value)s]',
}
FILTER_RANG... | djangosolr/documents/query.py | from django.utils import tree
import re
FILTER_CONTAINS = u'%(field)s:%(value)s'
FILTER_EXACT = u'%(field)s:"%(value)s"'
FILTER_COMPARE = {
'gt': u'%(field)s:{%(value)s TO *}',
'gte': u'%(field)s:[%(value)s TO *]',
'lt': u'%(field)s:{* TO %(value)s}',
'lte': u'%(field)s:[* TO %(value)s]',
}
FILTER_RANG... | 0.44071 | 0.144662 |
import ast
import astor
from data.logic import _grammar_transformer
from spec.mamba import *
def to_source(root):
return astor.to_source(root, ' ')
def goal(program):
cleaned = textwrap.dedent(program.strip('\n'))
return to_source(ast.parse(cleaned))
with description('_GrammarTransformer'):
with it('pr... | spec/data/logic/_grammar_transformer_spec.py | import ast
import astor
from data.logic import _grammar_transformer
from spec.mamba import *
def to_source(root):
return astor.to_source(root, ' ')
def goal(program):
cleaned = textwrap.dedent(program.strip('\n'))
return to_source(ast.parse(cleaned))
with description('_GrammarTransformer'):
with it('pr... | 0.77518 | 0.605041 |
from .visa_status import *
from tabulate import tabulate
import pandas as pd
import argparse
import sys
pd.set_option("display.max_rows", None)
__version__ = "0.2.0"
def tabprint(print_df):
print(tabulate(print_df, headers="keys", tablefmt="fancy_grid", showindex=True))
def main(argv=None):
argv = sys.ar... | visa_cli/__init__.py | from .visa_status import *
from tabulate import tabulate
import pandas as pd
import argparse
import sys
pd.set_option("display.max_rows", None)
__version__ = "0.2.0"
def tabprint(print_df):
print(tabulate(print_df, headers="keys", tablefmt="fancy_grid", showindex=True))
def main(argv=None):
argv = sys.ar... | 0.292393 | 0.124612 |
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTW... | dump1090.py |
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTW... | 0.329284 | 0.14851 |
import unittest
from flask import Flask, json, abort
import flask_restful as restful
from wsmeext.flask import signature
from wsme.api import Response
from wsme.types import Base, text
class Model(Base):
id = int
name = text
class Criterion(Base):
op = text
attr = text
value = text
test_app = ... | tests/test_flask.py | import unittest
from flask import Flask, json, abort
import flask_restful as restful
from wsmeext.flask import signature
from wsme.api import Response
from wsme.types import Base, text
class Model(Base):
id = int
name = text
class Criterion(Base):
op = text
attr = text
value = text
test_app = ... | 0.504394 | 0.237112 |
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def model_line_func(t, a, b):
return a * t + b
class Percolation:
def __init__(self, length):
self.length = length
self.grid = np.zeros((length + 2, length + 2), dtype=int)
self.p = 0
self... | HW3/q7.py | import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def model_line_func(t, a, b):
return a * t + b
class Percolation:
def __init__(self, length):
self.length = length
self.grid = np.zeros((length + 2, length + 2), dtype=int)
self.p = 0
self... | 0.522446 | 0.459258 |
from future.moves.urllib.parse import urlparse
from django.db import connection
from django.db.models import Sum
import requests
import logging
from django.apps import apps
from api.caching.utils import storage_usage_cache
from framework.postcommit_tasks.handlers import enqueue_postcommit_task
from api.caching impor... | api/caching/tasks.py | from future.moves.urllib.parse import urlparse
from django.db import connection
from django.db.models import Sum
import requests
import logging
from django.apps import apps
from api.caching.utils import storage_usage_cache
from framework.postcommit_tasks.handlers import enqueue_postcommit_task
from api.caching impor... | 0.239794 | 0.074399 |
#=============================================================================
from FrontEnd.IntermediateCode.fe_icode_token_node import * ## to get direct access to all ICTokenNode_XXX classes
from FrontEnd.IntermediateCode.fe_tokenized_icode import FETokenizedICode
#===========================================... | src/FrontEnd/Scanner/fe_scanner.py | #=============================================================================
from FrontEnd.IntermediateCode.fe_icode_token_node import * ## to get direct access to all ICTokenNode_XXX classes
from FrontEnd.IntermediateCode.fe_tokenized_icode import FETokenizedICode
#===========================================... | 0.475605 | 0.296743 |
import os
import time
import altair as alt
import keras
import numpy as np
import pandas as pd
import streamlit as st
from keras.utils import plot_model
from PIL import Image
from streamlit_drawable_canvas import st_canvas
import footer
model_list = os.listdir("mlmodels")
model_path = st.sidebar.selectbox(
"Sel... | app/streamlit_app.py | import os
import time
import altair as alt
import keras
import numpy as np
import pandas as pd
import streamlit as st
from keras.utils import plot_model
from PIL import Image
from streamlit_drawable_canvas import st_canvas
import footer
model_list = os.listdir("mlmodels")
model_path = st.sidebar.selectbox(
"Sel... | 0.462959 | 0.126299 |
import sys
from os import mkdir
from os.path import join, exists
import numpy as np
import pandas as pd
import plotly.graph_objects as go
# If plotly does not save the image, try:
# conda install psutil
# conda install -c plotly plotly-orca
# Saving the image may be more complex on Linux
def plot_decomposition(resul... | plot.py | import sys
from os import mkdir
from os.path import join, exists
import numpy as np
import pandas as pd
import plotly.graph_objects as go
# If plotly does not save the image, try:
# conda install psutil
# conda install -c plotly plotly-orca
# Saving the image may be more complex on Linux
def plot_decomposition(resul... | 0.38168 | 0.291334 |
# In[258]:
import numpy as np
import pylab as plt
from tqdm import tqdm
from matplotlib import cm
from matplotlib.ticker import LinearLocator
# In[259]:
# https://hal.archives-ouvertes.fr/hal-00921656v1/document
# https://hal.archives-ouvertes.fr/hal-00921656v2/document
# https://www.researchgate.net/publication... | NonlinearOptics/NLSE_Propagation.py |
# In[258]:
import numpy as np
import pylab as plt
from tqdm import tqdm
from matplotlib import cm
from matplotlib.ticker import LinearLocator
# In[259]:
# https://hal.archives-ouvertes.fr/hal-00921656v1/document
# https://hal.archives-ouvertes.fr/hal-00921656v2/document
# https://www.researchgate.net/publication... | 0.698535 | 0.638497 |
from __future__ import division
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
import tensorflow as tf
import numpy as np
import cv2
from utils.model import deform_viz_model
from utils.mnist_gen import get_gen
from utils.viz_tools import plot_offset, get_scaled_imgs,... | plot_deform_conv.py | from __future__ import division
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
import tensorflow as tf
import numpy as np
import cv2
from utils.model import deform_viz_model
from utils.mnist_gen import get_gen
from utils.viz_tools import plot_offset, get_scaled_imgs,... | 0.649245 | 0.151906 |
import datetime
import logging
import sys
from django.utils import timezone
from modularodm import Q
from website.models import NodeLog
from website.app import init_app
from bson import ObjectId
from nose.tools import * # noqa
from tests.base import OsfTestCase
from tests.factories import NodeLogFactory
logger ... | scripts/ensure_log_dates.py | import datetime
import logging
import sys
from django.utils import timezone
from modularodm import Q
from website.models import NodeLog
from website.app import init_app
from bson import ObjectId
from nose.tools import * # noqa
from tests.base import OsfTestCase
from tests.factories import NodeLogFactory
logger ... | 0.245537 | 0.080574 |
import math
import logging
import numpy as np
from openpathsampling.netcdfplus import StorableNamedObject
logger = logging.getLogger(__name__)
init_log = logging.getLogger('openpathsampling.initialization')
class ShootingPointSelector(StorableNamedObject):
def f(self, snapshot, trajectory):
"""
... | openpathsampling/shooting.py | import math
import logging
import numpy as np
from openpathsampling.netcdfplus import StorableNamedObject
logger = logging.getLogger(__name__)
init_log = logging.getLogger('openpathsampling.initialization')
class ShootingPointSelector(StorableNamedObject):
def f(self, snapshot, trajectory):
"""
... | 0.89974 | 0.552359 |
from argparse import ArgumentParser
from pydoc import locate
import numpy as np
import torch
import torch.utils.data
from torch.utils.data import DataLoader
from pyronan.utils.misc import parse_slice
parser_dataset = ArgumentParser(add_help=False)
parser_dataset.add_argument("--item_list", nargs="+", default=[])
par... | pyronan/dataset.py | from argparse import ArgumentParser
from pydoc import locate
import numpy as np
import torch
import torch.utils.data
from torch.utils.data import DataLoader
from pyronan.utils.misc import parse_slice
parser_dataset = ArgumentParser(add_help=False)
parser_dataset.add_argument("--item_list", nargs="+", default=[])
par... | 0.768733 | 0.179872 |
import numpy as np
import matplotlib.pyplot as plt
from qusoliton.sdenls import SDENLS1D as NLS
# %% number of shots
nshots = 10
# %% parameters for evolution (as a dictionary)
input = dict()
input['zmax'] = 0.01
input['xmin'] = -10.0
input['xmax'] = 10.0
input['nx'] = 256
input['nplot'] = 200
input['nz'] =... | qusoliton/tests/test_Milstein_6_1D.py | import numpy as np
import matplotlib.pyplot as plt
from qusoliton.sdenls import SDENLS1D as NLS
# %% number of shots
nshots = 10
# %% parameters for evolution (as a dictionary)
input = dict()
input['zmax'] = 0.01
input['xmin'] = -10.0
input['xmax'] = 10.0
input['nx'] = 256
input['nplot'] = 200
input['nz'] =... | 0.288669 | 0.383266 |
from viggy_circuits import *
from math import sin
import matplotlib.pyplot as plt
def main():
circuit = Circuit()
wires = [InductorWire(inductance=0.2,
battery=2.0,
capacitance=1.0,
resistance=lambda t: 1.5 + sin(t)),
... | samples/lcr.py | from viggy_circuits import *
from math import sin
import matplotlib.pyplot as plt
def main():
circuit = Circuit()
wires = [InductorWire(inductance=0.2,
battery=2.0,
capacitance=1.0,
resistance=lambda t: 1.5 + sin(t)),
... | 0.726523 | 0.503235 |
import copy
import time
import mock
from . import common
from datadog_checks.openstack_controller import OpenStackControllerCheck
def test_parse_uptime_string(aggregator):
instance = common.MOCK_CONFIG["instances"][0]
instance['tags'] = ['optional:tag1']
init_config = common.MOCK_CONFIG['init_config']
... | openstack_controller/tests/test_openstack.py | import copy
import time
import mock
from . import common
from datadog_checks.openstack_controller import OpenStackControllerCheck
def test_parse_uptime_string(aggregator):
instance = common.MOCK_CONFIG["instances"][0]
instance['tags'] = ['optional:tag1']
init_config = common.MOCK_CONFIG['init_config']
... | 0.587707 | 0.300681 |
import numpy as np
from cliport.tasks.task import Task
from cliport.utils import utils
import pybullet as p
import random
class TowersOfHanoiSeqUnseenColors(Task):
"""Towers of Hanoi Sequence base class and task."""
def __init__(self):
super().__init__()
self.max_steps = 14
self.lang... | cliport/tasks/towers_of_hanoi_seq.py |
import numpy as np
from cliport.tasks.task import Task
from cliport.utils import utils
import pybullet as p
import random
class TowersOfHanoiSeqUnseenColors(Task):
"""Towers of Hanoi Sequence base class and task."""
def __init__(self):
super().__init__()
self.max_steps = 14
self.lang... | 0.706393 | 0.273041 |
import pytest
pytestmark = pytest.mark.django_db
import re
import sure
import pyquery
from lxml.html import FormElement
from django.test import Client
from django.urls import reverse as url
from django.http import QueryDict
from urllib.parse import urlencode, urlparse
def go_to(url, expected_status=200, follow_redire... | nuremberg/core/tests/acceptance_helpers.py | import pytest
pytestmark = pytest.mark.django_db
import re
import sure
import pyquery
from lxml.html import FormElement
from django.test import Client
from django.urls import reverse as url
from django.http import QueryDict
from urllib.parse import urlencode, urlparse
def go_to(url, expected_status=200, follow_redire... | 0.541894 | 0.416856 |
from __future__ import absolute_import, division, print_function, unicode_literals
from . import tools_tags as tools
from azure.mgmt.monitor.models import EventData
from .azure_common import BaseTest
from c7n_azure.actions.tagging import AutoTagBase, AutoTagDate
from mock import patch, Mock
from c7n.exceptions import... | tools/c7n_azure/tests_azure/test_actions_autotag-date.py | from __future__ import absolute_import, division, print_function, unicode_literals
from . import tools_tags as tools
from azure.mgmt.monitor.models import EventData
from .azure_common import BaseTest
from c7n_azure.actions.tagging import AutoTagBase, AutoTagDate
from mock import patch, Mock
from c7n.exceptions import... | 0.770206 | 0.245741 |
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Branch',
fields=[
('name', models.CharField(max_length=5, primary_key=True, ... | getrank/rankestimate/migrations/0001_initial.py |
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Branch',
fields=[
('name', models.CharField(max_length=5, primary_key=True, ... | 0.647575 | 0.150122 |
import re
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from django.contrib.auth.middleware import AuthenticationMiddleware
from django.contrib.messages.middleware import MessageMiddleware
from django.contrib.sessions.middleware import SessionMiddleware
from django.middleware.cs... | camper/middleware.py | import re
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from django.contrib.auth.middleware import AuthenticationMiddleware
from django.contrib.messages.middleware import MessageMiddleware
from django.contrib.sessions.middleware import SessionMiddleware
from django.middleware.cs... | 0.520009 | 0.06492 |
import pandas as pd
import matplotlib.pyplot as plt
from os import path
from src.utils.logger import Logger
from src.utils.path import PATH_DOCS, PATH_DATA_OUTPUT
import src.utils.input_output as io
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
import tensorflow
fro... | src/models/train_model - lstm(do not run).py | import pandas as pd
import matplotlib.pyplot as plt
from os import path
from src.utils.logger import Logger
from src.utils.path import PATH_DOCS, PATH_DATA_OUTPUT
import src.utils.input_output as io
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
import tensorflow
fro... | 0.645567 | 0.543287 |
import time
import os
from glob import glob
from pathlib import Path
directory = "/srcdir/"
RUNS = 1
### using oswalk Command. This is very slow
def run_os_walk():
a = time.time_ns()
for i in range(RUNS):
fu = [x[0] for x in os.walk(directory)]
print(f"os.walk\t\t\ttook {(time.time_ns() - a) / 1... | python/OS Scanning/scandir.py | import time
import os
from glob import glob
from pathlib import Path
directory = "/srcdir/"
RUNS = 1
### using oswalk Command. This is very slow
def run_os_walk():
a = time.time_ns()
for i in range(RUNS):
fu = [x[0] for x in os.walk(directory)]
print(f"os.walk\t\t\ttook {(time.time_ns() - a) / 1... | 0.188399 | 0.096153 |
from __future__ import annotations
import argparse
import pdb
import traceback
from typing import List, Tuple
VERBOSE: bool = False
def checksum(data: str) -> str:
def _check(d: str) -> str:
res: str = ""
for p in [(d[i:i + 2]) for i in range(0, len(d), 2)]:
if p in ["00", "11"]:
... | 2016/16-dragon_checksum/solve.py |
from __future__ import annotations
import argparse
import pdb
import traceback
from typing import List, Tuple
VERBOSE: bool = False
def checksum(data: str) -> str:
def _check(d: str) -> str:
res: str = ""
for p in [(d[i:i + 2]) for i in range(0, len(d), 2)]:
if p in ["00", "11"]:
... | 0.573559 | 0.264486 |
from __future__ import annotations
import sys
from os.path import dirname
sys.path.insert(0, dirname(dirname(__file__)))
from typing import *
from parfact import any, capproxy, capture, char, chars, digit, digits, letter, letters, nl, optional, sequence, string, ws, charset, Parser
from parfact.automaton import ParseE... | test/test_pattern.py | from __future__ import annotations
import sys
from os.path import dirname
sys.path.insert(0, dirname(dirname(__file__)))
from typing import *
from parfact import any, capproxy, capture, char, chars, digit, digits, letter, letters, nl, optional, sequence, string, ws, charset, Parser
from parfact.automaton import ParseE... | 0.621656 | 0.427038 |
import os, json
from functools import reduce
def cut_points(data, top):
points = []
for i in range(top):
for line in data:
if line[i] != ' ':
break
else:
points.append(i)
single_points = [-1, points[0]]
for p in points[1:]:
if p == singl... | data_parser.py | import os, json
from functools import reduce
def cut_points(data, top):
points = []
for i in range(top):
for line in data:
if line[i] != ' ':
break
else:
points.append(i)
single_points = [-1, points[0]]
for p in points[1:]:
if p == singl... | 0.31542 | 0.324463 |
import textwrap
import os
from cloudmesh.common.parameter import Parameter
from cloudmesh.common.console import Console
from cloudmesh.common.Host import Host
from cloudmesh.common.Printer import Printer
from cloudmesh.pi.cluster.k3.K3SDashboard import K3SDashboard
from cloudmesh.common.StopWatch import StopWatch
cl... | cloudmesh/pi/cluster/k3/k3.py | import textwrap
import os
from cloudmesh.common.parameter import Parameter
from cloudmesh.common.console import Console
from cloudmesh.common.Host import Host
from cloudmesh.common.Printer import Printer
from cloudmesh.pi.cluster.k3.K3SDashboard import K3SDashboard
from cloudmesh.common.StopWatch import StopWatch
cl... | 0.301362 | 0.089973 |
import re
def add_intl(template_string):
"""Wraps the language specific text in an html mako template in the
proper get text formatting.
template_string -- The string to convert.
returns The converted string
"""
analyze = [template_string]
# An array of patterns that should be ignored
... | src/cs2mako/addintl.py |
import re
def add_intl(template_string):
"""Wraps the language specific text in an html mako template in the
proper get text formatting.
template_string -- The string to convert.
returns The converted string
"""
analyze = [template_string]
# An array of patterns that should be ignored
... | 0.445047 | 0.409988 |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('product', '0010_auto_20200512_2106'),
('address', '0001_initial'),
migrations.swappable_dependency(sett... | order/migrations/0001_initial.py |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('product', '0010_auto_20200512_2106'),
('address', '0001_initial'),
migrations.swappable_dependency(sett... | 0.597256 | 0.13966 |
import os
import json
from rocksmith import PSARC, SNG
def path2dict(path):
n = len(path) + 1
d = {}
for dirpath, _, filenames in os.walk(path):
for filename in filenames:
fullpath = os.path.join(dirpath, filename)
with open(fullpath, 'rb') as fh:
d[fullpat... | rocksmith/utils.py | import os
import json
from rocksmith import PSARC, SNG
def path2dict(path):
n = len(path) + 1
d = {}
for dirpath, _, filenames in os.walk(path):
for filename in filenames:
fullpath = os.path.join(dirpath, filename)
with open(fullpath, 'rb') as fh:
d[fullpat... | 0.218003 | 0.117673 |
import unittest
from strtest import str_test
TEST_CODE1 = '''
from strtest import str_test
class TestCase(str_test.TestCaseWrapper):
TIMEOUT = 1
@str_test.error_message('Não funcionou para caso com zero.')
def test_numbers_3_0(self):
self.assertEqual(self.function(3,0), 3)
def test_numbers_... | tests/test_str_test.py |
import unittest
from strtest import str_test
TEST_CODE1 = '''
from strtest import str_test
class TestCase(str_test.TestCaseWrapper):
TIMEOUT = 1
@str_test.error_message('Não funcionou para caso com zero.')
def test_numbers_3_0(self):
self.assertEqual(self.function(3,0), 3)
def test_numbers_... | 0.375821 | 0.482551 |
from __future__ import absolute_import, division, print_function, \
unicode_literals
import os
import sys
import time
import socket
import six.moves.urllib as urllib
import hashlib
import logging
from zeroconf import ServiceInfo, Zeroconf
from six.moves.BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
fro... | zget/put.py | from __future__ import absolute_import, division, print_function, \
unicode_literals
import os
import sys
import time
import socket
import six.moves.urllib as urllib
import hashlib
import logging
from zeroconf import ServiceInfo, Zeroconf
from six.moves.BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
fro... | 0.565299 | 0.092115 |
import os
import argparse
import numpy as np
from tqdm import tqdm
def main():
parser = argparse.ArgumentParser(description='.')
parser.add_argument('--source-path', type=str, required=True,
help='Path to the source file txt')
parser.add_argument('--target-path', type=str, required=True,
he... | resample_raw_dataset.py | import os
import argparse
import numpy as np
from tqdm import tqdm
def main():
parser = argparse.ArgumentParser(description='.')
parser.add_argument('--source-path', type=str, required=True,
help='Path to the source file txt')
parser.add_argument('--target-path', type=str, required=True,
he... | 0.297572 | 0.09451 |
import bz2
import pickle
import _pickle as cPickle
from Cleaning.ms_cleaning import cleaning
def remove_stopwords(data, stop_words):
output_array=[]
for sentence in data:
temp_list=[]
for word in sentence.split():
if word.lower() not in stop_words:
temp_li... | Emotion/emotion.py | import bz2
import pickle
import _pickle as cPickle
from Cleaning.ms_cleaning import cleaning
def remove_stopwords(data, stop_words):
output_array=[]
for sentence in data:
temp_list=[]
for word in sentence.split():
if word.lower() not in stop_words:
temp_li... | 0.042523 | 0.104021 |
from datetime import datetime
DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
class ApiRequestException(Exception):
def __init__(self, response):
msg = "(%s) %s [%s]" % (response.status_code, response.reason, response.url)
super(ApiRequestException, self).__init__(msg)
self.response = response
... | cryptowatch/Msg.py | from datetime import datetime
DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
class ApiRequestException(Exception):
def __init__(self, response):
msg = "(%s) %s [%s]" % (response.status_code, response.reason, response.url)
super(ApiRequestException, self).__init__(msg)
self.response = response
... | 0.701713 | 0.083292 |
from typing import Dict, Union, Optional, Tuple, Any
import numpy as np
import pandas as pd
from ensmallen import Graph
import tensorflow as tf
from tensorflow.keras import Model
from embiggen.sequences.tensorflow_sequences import Node2VecSequence
from embiggen.embedders.tensorflow_embedders.abstract_random_walked_bas... | embiggen/embedders/tensorflow_embedders/node2vec.py | from typing import Dict, Union, Optional, Tuple, Any
import numpy as np
import pandas as pd
from ensmallen import Graph
import tensorflow as tf
from tensorflow.keras import Model
from embiggen.sequences.tensorflow_sequences import Node2VecSequence
from embiggen.embedders.tensorflow_embedders.abstract_random_walked_bas... | 0.97614 | 0.51129 |
import os
import pytest
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('php7-debian9')
@pytest.mark.parametrize('pkg', ['php7.0-fpm',
'php7.0-common',
... | molecule/default/tests/test_php7_debian9.py | import os
import pytest
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('php7-debian9')
@pytest.mark.parametrize('pkg', ['php7.0-fpm',
'php7.0-common',
... | 0.231875 | 0.093885 |
# Import Python libs
from __future__ import absolute_import
# Import Salt Libs
import salt.states.pkgrepo as pkgrepo
# Import Salt Testing Libs
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.mock import MagicMock, patch
from tests.support.unit import TestCase
class PkgrepoTestCase(TestCas... | tests/unit/states/test_pkgrepo.py | # Import Python libs
from __future__ import absolute_import
# Import Salt Libs
import salt.states.pkgrepo as pkgrepo
# Import Salt Testing Libs
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.mock import MagicMock, patch
from tests.support.unit import TestCase
class PkgrepoTestCase(TestCas... | 0.669637 | 0.257572 |
from django.urls import path
from parsifal.apps.reviews.planning import views
app_name = "planning"
urlpatterns = [
path("save_source/", views.save_source, name="save_source"),
path("remove_source/", views.remove_source_from_review, name="remove_source_from_review"),
path("suggested_sources/", views.sugg... | parsifal/apps/reviews/planning/urls.py | from django.urls import path
from parsifal.apps.reviews.planning import views
app_name = "planning"
urlpatterns = [
path("save_source/", views.save_source, name="save_source"),
path("remove_source/", views.remove_source_from_review, name="remove_source_from_review"),
path("suggested_sources/", views.sugg... | 0.300951 | 0.117471 |
from django.conf.urls import include, url
from django_sorcery import routers
from .testapp import views
router = routers.SimpleRouter()
router.register("owners", views.OwnerViewSet)
urlpatterns = [
# list views
# r"^(?P<id>[0-9]+)/$"
url(r"^list/owners/$", views.OwnerListView.as_view(), name="owners_lis... | tests/urls.py | from django.conf.urls import include, url
from django_sorcery import routers
from .testapp import views
router = routers.SimpleRouter()
router.register("owners", views.OwnerViewSet)
urlpatterns = [
# list views
# r"^(?P<id>[0-9]+)/$"
url(r"^list/owners/$", views.OwnerListView.as_view(), name="owners_lis... | 0.195633 | 0.12326 |
import requests
from random import sample
import logging
import logging.handlers
import xml.etree.cElementTree as ET
from os import path
import plistlib
APPNAME = "groups"
LOGLEVEL = logging.DEBUG
LOGFILE = "/usr/local/var/log/%s.log" % APPNAME
SIZE = 10 # number of computers to add to group
class Groups:
"""
... | groups.py | import requests
from random import sample
import logging
import logging.handlers
import xml.etree.cElementTree as ET
from os import path
import plistlib
APPNAME = "groups"
LOGLEVEL = logging.DEBUG
LOGFILE = "/usr/local/var/log/%s.log" % APPNAME
SIZE = 10 # number of computers to add to group
class Groups:
"""
... | 0.351311 | 0.077868 |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Category',
fields=[
('id', models.AutoField(auto_created=T... | Reconnaissance/Campus/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='Category',
fields=[
('id', models.AutoField(auto_created=T... | 0.548553 | 0.160365 |
from fastai.callback import Callback
from fastai.basic_train import Learner
from fastai.torch_core import torch, dataclass
import numpy as np
import pdb
def choose_corruption(inp, alpha):
nrows, ncols = inp.shape
lambd = []
for i in range(nrows):
col_idx = np.random.choice(ncols, (1,int(ncols*alp... | code/fastai_ext/fastai_ext/augmentations.py | from fastai.callback import Callback
from fastai.basic_train import Learner
from fastai.torch_core import torch, dataclass
import numpy as np
import pdb
def choose_corruption(inp, alpha):
nrows, ncols = inp.shape
lambd = []
for i in range(nrows):
col_idx = np.random.choice(ncols, (1,int(ncols*alp... | 0.685002 | 0.292791 |
import sys
import traceback
import discord
from discord.ext import commands
class ErrorHandler(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_command_error(self, ctx, error):
if isinstance(ctx.channel, discord.DMChannel):
return
... | cogs/errorhandler.py | import sys
import traceback
import discord
from discord.ext import commands
class ErrorHandler(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_command_error(self, ctx, error):
if isinstance(ctx.channel, discord.DMChannel):
return
... | 0.298594 | 0.134804 |
from ixnetwork_restpy.base import Base
from ixnetwork_restpy.files import Files
class OfChannelPortsLearnedInformation(Base):
"""Signifies the information learned from OF channel ports.
The OfChannelPortsLearnedInformation class encapsulates a list of ofChannelPortsLearnedInformation resources that are ... | ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/ofchannelportslearnedinformation_5e4e377ec6d51a64c183b7b37f203ba3.py | from ixnetwork_restpy.base import Base
from ixnetwork_restpy.files import Files
class OfChannelPortsLearnedInformation(Base):
"""Signifies the information learned from OF channel ports.
The OfChannelPortsLearnedInformation class encapsulates a list of ofChannelPortsLearnedInformation resources that are ... | 0.899844 | 0.253416 |
import xgboost as xgb
import tempfile
import os
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from matplotlib import pyplot as plt
import argparse
class Plotting(xgb.callback.TrainingCallback):
'''Plot evaluation result during training. On... | demo/guide-python/callbacks.py | import xgboost as xgb
import tempfile
import os
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from matplotlib import pyplot as plt
import argparse
class Plotting(xgb.callback.TrainingCallback):
'''Plot evaluation result during training. On... | 0.728748 | 0.463748 |
import os
import re
from io import StringIO
import dulwich
from dulwich import porcelain
from bottypes.invalid_command import InvalidCommand
from util.loghandler import log
class GitHandler():
"""Handles commit for multiple files."""
def __init__(self, repo_path):
try:
self.repo_path = ... | util/githandler.py | import os
import re
from io import StringIO
import dulwich
from dulwich import porcelain
from bottypes.invalid_command import InvalidCommand
from util.loghandler import log
class GitHandler():
"""Handles commit for multiple files."""
def __init__(self, repo_path):
try:
self.repo_path = ... | 0.519521 | 0.102709 |
from typing import Optional
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from telegram_bot.database import models
WELCOME_TEXT = """\
基于「和风」的天气预报机器人;根据定位查询精准实时天气,并每天自动播报。
如有任何问题,请联系 @daya233
"""
ENABLE_SUB, DISABLE_SUB = "enable_sub", "disable_sub"
GET_WEATHER, UPDATE_LOCATION = "weathe... | telegram_bot/telegram/keyboard/keyboard_markup_factory.py | from typing import Optional
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from telegram_bot.database import models
WELCOME_TEXT = """\
基于「和风」的天气预报机器人;根据定位查询精准实时天气,并每天自动播报。
如有任何问题,请联系 @daya233
"""
ENABLE_SUB, DISABLE_SUB = "enable_sub", "disable_sub"
GET_WEATHER, UPDATE_LOCATION = "weathe... | 0.623262 | 0.141756 |
import pytest
from datetime import timedelta
from django.conf import settings
from django.utils import timezone
from tests.common_tools import template_used
from tests.factories import ConferenceFactory, SponsorFactory, NewsFactory
from tests.common_tools import get_default_conference
def test_get_homepage(db, clie... | tests/test_homepage.py | import pytest
from datetime import timedelta
from django.conf import settings
from django.utils import timezone
from tests.common_tools import template_used
from tests.factories import ConferenceFactory, SponsorFactory, NewsFactory
from tests.common_tools import get_default_conference
def test_get_homepage(db, clie... | 0.491944 | 0.31434 |
import os, sys
def include_headers():
inc = [
"#include <linux/module.h> /* Needed by all modules */",
"#include <linux/kernel.h> /* Needed for KERN_ALERT */",
"",
"#include <linux/aio_abi.h> //aio_context_t",
"#include <trace/syscall.h> //struct perf_event_attr, struct pollfd",
"#inc... | misc/hacking/st_size.py | import os, sys
def include_headers():
inc = [
"#include <linux/module.h> /* Needed by all modules */",
"#include <linux/kernel.h> /* Needed for KERN_ALERT */",
"",
"#include <linux/aio_abi.h> //aio_context_t",
"#include <trace/syscall.h> //struct perf_event_attr, struct pollfd",
"#inc... | 0.180974 | 0.123868 |
import sys
import time
import datetime
import json
import os.path
jsonpath = os.path.join(os.path.dirname(__file__), 'storage/')
def fetch_JSON_data(filepath):
with open(filepath) as userData:
data = json.load(userData)
return data
def write_to_file(filepath,data):
with open(filepath,'w') as outf... | right_now.py | import sys
import time
import datetime
import json
import os.path
jsonpath = os.path.join(os.path.dirname(__file__), 'storage/')
def fetch_JSON_data(filepath):
with open(filepath) as userData:
data = json.load(userData)
return data
def write_to_file(filepath,data):
with open(filepath,'w') as outf... | 0.083237 | 0.130562 |
import random
from discord import Embed
import nextcord
from nextcord.ext import commands
import d20
from utils.embedder import embed_success, embed_error
class MyStringifier(d20.SimpleStringifier):
def _str_die(self, node):
the_rolls = []
for val in node.values:
inside = self._stringi... | cogs/roll/cog.py | import random
from discord import Embed
import nextcord
from nextcord.ext import commands
import d20
from utils.embedder import embed_success, embed_error
class MyStringifier(d20.SimpleStringifier):
def _str_die(self, node):
the_rolls = []
for val in node.values:
inside = self._stringi... | 0.491456 | 0.441553 |
import logging as logmodule
import time
from django.core.management.base import BaseCommand
from django.db.models import Q
from le_utils.constants import content_kinds
from le_utils.constants import exercises
from contentcuration.models import ContentNode
from contentcuration.models import License
logmodule.basicCon... | contentcuration/contentcuration/management/commands/fix_exercise_complete.py | import logging as logmodule
import time
from django.core.management.base import BaseCommand
from django.db.models import Q
from le_utils.constants import content_kinds
from le_utils.constants import exercises
from contentcuration.models import ContentNode
from contentcuration.models import License
logmodule.basicCon... | 0.301671 | 0.224916 |
import pytest
import tvm
from tvm import tir
from tvm.script import tir as T
from tvm.tir.schedule.testing import verify_trace_roundtrip
# fmt: off
# pylint: disable=no-member,invalid-name,unused-variable,unexpected-keyword-arg
@T.prim_func
def element_wise(A: T.Buffer[(128, 128), "float32"], C: T.Buffer[(128, 128), ... | tests/python/unittest/test_tir_schedule_set_scope.py | import pytest
import tvm
from tvm import tir
from tvm.script import tir as T
from tvm.tir.schedule.testing import verify_trace_roundtrip
# fmt: off
# pylint: disable=no-member,invalid-name,unused-variable,unexpected-keyword-arg
@T.prim_func
def element_wise(A: T.Buffer[(128, 128), "float32"], C: T.Buffer[(128, 128), ... | 0.416085 | 0.279263 |
__docformat__ = 'epytext'
# Native imports
import cPickle, csv, zipfile, tarfile, os
from ConfigParser import SafeConfigParser, NoSectionError
# Third party imports
import numpy as np
import requests
# Program imports
from mldata import BASE_DIR, USER_CFG
from mldata.status_bar i... | src/mldata/util.py | __docformat__ = 'epytext'
# Native imports
import cPickle, csv, zipfile, tarfile, os
from ConfigParser import SafeConfigParser, NoSectionError
# Third party imports
import numpy as np
import requests
# Program imports
from mldata import BASE_DIR, USER_CFG
from mldata.status_bar i... | 0.469034 | 0.151592 |
from tests import venv_path, clone_path, TestBase, tmplocation
import os
import clonevirtualenv
import sys
"""
Fixup scripts meerly just walks bin dir and calls to
fixup_link, fixup_activate, fixup_script_
"""
class TestFixupScripts(TestBase):
def test_fixup_activate(self):
file_ = os.path.join(venv_path... | tests/test_fixup_scripts.py | from tests import venv_path, clone_path, TestBase, tmplocation
import os
import clonevirtualenv
import sys
"""
Fixup scripts meerly just walks bin dir and calls to
fixup_link, fixup_activate, fixup_script_
"""
class TestFixupScripts(TestBase):
def test_fixup_activate(self):
file_ = os.path.join(venv_path... | 0.317744 | 0.297227 |
import logging
import pytest
from tests.common.helpers.assertions import pytest_assert
from tests.common.config_reload import config_reload
from tests.generic_config_updater.gu_utils import apply_patch, expect_op_success, expect_res_success, expect_op_failure
from tests.generic_config_updater.gu_utils import generate_... | tests/generic_config_updater/test_cacl.py | import logging
import pytest
from tests.common.helpers.assertions import pytest_assert
from tests.common.config_reload import config_reload
from tests.generic_config_updater.gu_utils import apply_patch, expect_op_success, expect_res_success, expect_op_failure
from tests.generic_config_updater.gu_utils import generate_... | 0.377885 | 0.534187 |
from datetime import datetime
from django.contrib.gis.geos import Point
from django.test import TestCase
import pytz
from robber import expect
from pinboard.serializers.mobile.relevant.document_serializer import DocumentSerializer
from data.factories import (
OfficerFactory,
AllegationFactory,
Allegation... | cpdb/pinboard/tests/serializers/mobile/relevant/test_document_serializer.py | from datetime import datetime
from django.contrib.gis.geos import Point
from django.test import TestCase
import pytz
from robber import expect
from pinboard.serializers.mobile.relevant.document_serializer import DocumentSerializer
from data.factories import (
OfficerFactory,
AllegationFactory,
Allegation... | 0.556882 | 0.260066 |
from moorpy.Catenary import catenary
import moorpy as mp
import numpy as np
import os
import sys
basepath = "C:/code/openfast/reg_tests"
sys.path.insert(0, os.path.sep.join([basepath, "lib"]))
import argparse
import shutil
import glob
import subprocess
import rtestlib as rtl
import pass_fail
import openfastDrivers
im... | reg_tests/MoordynChecks/MoordynQSchecks.py | from moorpy.Catenary import catenary
import moorpy as mp
import numpy as np
import os
import sys
basepath = "C:/code/openfast/reg_tests"
sys.path.insert(0, os.path.sep.join([basepath, "lib"]))
import argparse
import shutil
import glob
import subprocess
import rtestlib as rtl
import pass_fail
import openfastDrivers
im... | 0.441191 | 0.276452 |
import errno
import socket
import time
from microio import *
__all__ = ('Stream', 'connect', 'listen', 'serve', 'spawn')
class Stream:
def __init__(self, sock, read_size=65536):
sock.setblocking(False)
self.sock = sock
self.buffer = b''
self.read_size = read_size
def close... | examples/utils.py | import errno
import socket
import time
from microio import *
__all__ = ('Stream', 'connect', 'listen', 'serve', 'spawn')
class Stream:
def __init__(self, sock, read_size=65536):
sock.setblocking(False)
self.sock = sock
self.buffer = b''
self.read_size = read_size
def close... | 0.266644 | 0.058696 |
from datetime import datetime
from enum import Enum
import pytest
from monty.json import MSONable
from pydantic import BaseModel, Field
from maggma.api.utils import api_sanitize, serialization_helper
from typing import Union
from bson import ObjectId
class SomeEnum(Enum):
A = 1
B = 2
C = 3
class Pet(... | tests/api/test_utils.py | from datetime import datetime
from enum import Enum
import pytest
from monty.json import MSONable
from pydantic import BaseModel, Field
from maggma.api.utils import api_sanitize, serialization_helper
from typing import Union
from bson import ObjectId
class SomeEnum(Enum):
A = 1
B = 2
C = 3
class Pet(... | 0.837686 | 0.247078 |
from sfml.graphics import *
from sfml.system import Vector2
import weakref
# 2D hash intended for GUI and overlay mouse lick handling
# works with static Rectangles. References objects weakly.
class Fixed2DHash:
def __init__(self, global_size, cell_count, origin = Vector2(0.0, 0.0)):
self._size = global_... | engine/SpacialHash.py |
from sfml.graphics import *
from sfml.system import Vector2
import weakref
# 2D hash intended for GUI and overlay mouse lick handling
# works with static Rectangles. References objects weakly.
class Fixed2DHash:
def __init__(self, global_size, cell_count, origin = Vector2(0.0, 0.0)):
self._size = global_... | 0.543106 | 0.411495 |
# ===================================================================================
# This script/class script performs the scaling of the CTA calibration data base
# IRF following the given settings. It is intended for the studies of the systematics
# effects in CTA data analysis.
# Author: <NAME> (2018)
# ========... | Scale_IRFs.py |
# ===================================================================================
# This script/class script performs the scaling of the CTA calibration data base
# IRF following the given settings. It is intended for the studies of the systematics
# effects in CTA data analysis.
# Author: <NAME> (2018)
# ========... | 0.650245 | 0.280087 |
from dash.development.base_component import Component, _explicitize_args
class Nav(Component):
"""A Nav component.
Keyword arguments:
- children (a list of or a singular dash component, string or number; optional): The children of this component
- id (string; optional): The ID of this component, used to identi... | lib/python3.7/site-packages/dash_bootstrap_components/_components/Nav.py |
from dash.development.base_component import Component, _explicitize_args
class Nav(Component):
"""A Nav component.
Keyword arguments:
- children (a list of or a singular dash component, string or number; optional): The children of this component
- id (string; optional): The ID of this component, used to identi... | 0.875561 | 0.401219 |
from graph_tool import GraphView
import numpy as np
def number_of_classes( D, edge_labels=np.empty(0), stats=dict(), print_stats=False ):
"""counts the number of different classes"""
if edge_labels is None or edge_labels.size == 0:
edge_labels = np.array( [ D.ep.c0[p] for p in D.get_edges() ] )
#... | graph/measures/fernandez_et_al/typed_subjects_objects.py | from graph_tool import GraphView
import numpy as np
def number_of_classes( D, edge_labels=np.empty(0), stats=dict(), print_stats=False ):
"""counts the number of different classes"""
if edge_labels is None or edge_labels.size == 0:
edge_labels = np.array( [ D.ep.c0[p] for p in D.get_edges() ] )
#... | 0.643553 | 0.673178 |
from collections import ChainMap, defaultdict
from enum import Enum
import torch
from nndct_shared.base.key_names import FrameworkType
from nndct_shared.nndct_graph import (Graph, Tensor,
reorder_multi_subgraph_nodes)
from nndct_shared.utils import NndctDebugLogger, NndctOption... | tools/RNN/rnn_quantizer/pytorch_binding/pytorch_nndct/parse/parser.py |
from collections import ChainMap, defaultdict
from enum import Enum
import torch
from nndct_shared.base.key_names import FrameworkType
from nndct_shared.nndct_graph import (Graph, Tensor,
reorder_multi_subgraph_nodes)
from nndct_shared.utils import NndctDebugLogger, NndctOption... | 0.636692 | 0.284551 |
from jax.config import config
config.update("jax_enable_x64", True)
from jax.config import config
config.update("jax_debug_nans", True)
from random import randint
from jax import random
import flax.linen as nn
from typing import Sequence, Callable
import foo_vb_lib
import datasets as ds
import run
import ml_colle... | jsl/experimental/foo_vb/main.py | from jax.config import config
config.update("jax_enable_x64", True)
from jax.config import config
config.update("jax_debug_nans", True)
from random import randint
from jax import random
import flax.linen as nn
from typing import Sequence, Callable
import foo_vb_lib
import datasets as ds
import run
import ml_colle... | 0.824533 | 0.134662 |
from utils.base_test_class import BaseTestClass, execute_tests
import numpy as np
# Local
import gp_core
import kernel
def gen_gp_test_data():
""" This function generates a bunch of test data. """
# pylint: disable=too-many-locals
# Dataset 1
f1 = lambda x: (x**2).sum(axis=1)
N1 = 5
X1_tr = np.array(rang... | gp/unittest_gp_core.py |
from utils.base_test_class import BaseTestClass, execute_tests
import numpy as np
# Local
import gp_core
import kernel
def gen_gp_test_data():
""" This function generates a bunch of test data. """
# pylint: disable=too-many-locals
# Dataset 1
f1 = lambda x: (x**2).sum(axis=1)
N1 = 5
X1_tr = np.array(rang... | 0.569853 | 0.651687 |
from veros.core import friction
from veros.pyom_compat import get_random_state
from test_base import compare_state
TEST_SETTINGS = dict(
nx=70,
ny=60,
nz=50,
dt_tracer=3600,
dt_mom=3600,
enable_cyclic_x=True,
enable_conserve_energy=True,
enable_bottom_friction_var=True,
enable_hor... | test/pyom_consistency/friction_test.py | from veros.core import friction
from veros.pyom_compat import get_random_state
from test_base import compare_state
TEST_SETTINGS = dict(
nx=70,
ny=60,
nz=50,
dt_tracer=3600,
dt_mom=3600,
enable_cyclic_x=True,
enable_conserve_energy=True,
enable_bottom_friction_var=True,
enable_hor... | 0.59843 | 0.374333 |
import sqlite3
import argparse
from urllib.request import Request, urlopen
import csv
import re
import xml.etree.ElementTree as ET
from typing import List, Dict
import collections
import json
# BLASTの結果のtextファイル名をパラメータから取得
# $ python m2o.py <file path> のようにBLASTのformat 6 outputファイルを引数にしてスクリプトを呼ぶ
parser = argparse.Arg... | m2o.py |
import sqlite3
import argparse
from urllib.request import Request, urlopen
import csv
import re
import xml.etree.ElementTree as ET
from typing import List, Dict
import collections
import json
# BLASTの結果のtextファイル名をパラメータから取得
# $ python m2o.py <file path> のようにBLASTのformat 6 outputファイルを引数にしてスクリプトを呼ぶ
parser = argparse.Arg... | 0.458106 | 0.336113 |
from os.path import isfile
from csv import reader
from numpy import zeros, amax, tile
ZS_COL = 0 # Slot id
COIL_COL = 1 # Ntcoil (+/-)
RAD_COL = 2 # Rad layer id
TAN_COL = 3 # Tan layer id
def import_from_csv(self, file_path=None):
"""Import the winding matrix from a csv file.
One matrix for each phase
... | pyleecan/Methods/Machine/WindingUD/import_from_csv.py | from os.path import isfile
from csv import reader
from numpy import zeros, amax, tile
ZS_COL = 0 # Slot id
COIL_COL = 1 # Ntcoil (+/-)
RAD_COL = 2 # Rad layer id
TAN_COL = 3 # Tan layer id
def import_from_csv(self, file_path=None):
"""Import the winding matrix from a csv file.
One matrix for each phase
... | 0.57081 | 0.302488 |
import pytest
from flyteidl.core import catalog_pb2, errors_pb2
from flytekit.core.context_manager import FlyteContextManager
from flytekit.core.task import task
from flytekit.core.type_engine import TypeEngine
from flytekit.core.workflow import workflow
from flytekit.models.types import LiteralType, SimpleType
def ... | tests/flytekit/unit/core/test_protobuf.py | import pytest
from flyteidl.core import catalog_pb2, errors_pb2
from flytekit.core.context_manager import FlyteContextManager
from flytekit.core.task import task
from flytekit.core.type_engine import TypeEngine
from flytekit.core.workflow import workflow
from flytekit.models.types import LiteralType, SimpleType
def ... | 0.532668 | 0.424412 |
import os
import pandas as pd
from tqdm import tqdm
IS_LB = False
if __name__ == "__main__":
city_df = pd.read_json("system_result/City.json", lines=True)
if IS_LB:
path = "./yans2021hackathon_tknzd_tohoku_bert/City/tokenized/leaderboard"
files = os.listdir(path)
files = [f[:-4] for ... | src/final_submission.py | import os
import pandas as pd
from tqdm import tqdm
IS_LB = False
if __name__ == "__main__":
city_df = pd.read_json("system_result/City.json", lines=True)
if IS_LB:
path = "./yans2021hackathon_tknzd_tohoku_bert/City/tokenized/leaderboard"
files = os.listdir(path)
files = [f[:-4] for ... | 0.164181 | 0.123895 |
import lxml.html
from .bills import NHBillScraper
from .legislators import NHLegislatorScraper
metadata = {
'abbreviation': 'nh',
'name': 'New Hampshire',
'capitol_timezone': 'America/New_York',
'legislature_name': 'New Hampshire General Court',
'legislature_url': 'http://www.gencourt.state.nh.us/'... | openstates/openstates-master/openstates/nh/__init__.py | import lxml.html
from .bills import NHBillScraper
from .legislators import NHLegislatorScraper
metadata = {
'abbreviation': 'nh',
'name': 'New Hampshire',
'capitol_timezone': 'America/New_York',
'legislature_name': 'New Hampshire General Court',
'legislature_url': 'http://www.gencourt.state.nh.us/'... | 0.303938 | 0.193033 |
import os
always_on = [
'minimal',
]
always_off = [
'leapfetch',
]
other = [
'debug',
'chrpath',
'ipv6',
'manbuild',
'nostrip',
'slow',
'profiling',
'libQgpsmm',
]
knobs = [
'aivdm',
'ashtech',
'bluez',
'clientdebug',
'control_socket',
'controlsend',
... | devtools/identify_failing_build_options.py |
import os
always_on = [
'minimal',
]
always_off = [
'leapfetch',
]
other = [
'debug',
'chrpath',
'ipv6',
'manbuild',
'nostrip',
'slow',
'profiling',
'libQgpsmm',
]
knobs = [
'aivdm',
'ashtech',
'bluez',
'clientdebug',
'control_socket',
'controlsend',
... | 0.155335 | 0.098382 |
import os
from configparser import ConfigParser
from PyQt5.QtCore import QCoreApplication, QEvent, QObject, Qt, pyqtSlot
from PyQt5.QtGui import QKeyEvent
from app.webcam_application_ import WebcamApplication
from brightness.calcuator import BrightnessMode
from intergrated_gui.panel_widget import AngleTolerance, Pane... | intergrated_gui/panel_controller.py | import os
from configparser import ConfigParser
from PyQt5.QtCore import QCoreApplication, QEvent, QObject, Qt, pyqtSlot
from PyQt5.QtGui import QKeyEvent
from app.webcam_application_ import WebcamApplication
from brightness.calcuator import BrightnessMode
from intergrated_gui.panel_widget import AngleTolerance, Pane... | 0.642208 | 0.150372 |