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 message import *
# Fisrt half of byte
class CAPTAINTypes(MsgTypes):
# COMMON_DATA = 0x00
# ACK = 0x01
# control messages
INFO_ANNOUN = 0x02
SCORE_ANNOUN = 0x03
CLUSTER_ANNOUN = 0x04
ROUTE_ANNOUN = 0x05
REQ_SCORE = 0x06
REP_SCORE = 0x07
UPDATE_I... | capmessage.py | from message import *
# Fisrt half of byte
class CAPTAINTypes(MsgTypes):
# COMMON_DATA = 0x00
# ACK = 0x01
# control messages
INFO_ANNOUN = 0x02
SCORE_ANNOUN = 0x03
CLUSTER_ANNOUN = 0x04
ROUTE_ANNOUN = 0x05
REQ_SCORE = 0x06
REP_SCORE = 0x07
UPDATE_I... | 0.358016 | 0.185707 |
import inspect
from types import MethodType
from .. import devices
from ..managers.scene_manager import async_trigger_scene_off, async_trigger_scene_on
from .tools_base import ToolsBase
def _convert_val(val):
if '"' not in val and "'" not in val:
try:
return int(val)
except ValueErro... | pyinsteon/tools/cmd.py |
import inspect
from types import MethodType
from .. import devices
from ..managers.scene_manager import async_trigger_scene_off, async_trigger_scene_on
from .tools_base import ToolsBase
def _convert_val(val):
if '"' not in val and "'" not in val:
try:
return int(val)
except ValueErro... | 0.54577 | 0.175114 |
import sys
import os
THIRD_PARTY_PATH = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../third_party'))
if THIRD_PARTY_PATH not in sys.path:
sys.path.append(THIRD_PARTY_PATH)
from deepdefense_pytorch.models.cifar10 import ConvNet
from ares.model import ClassifierWithLogits
from are... | example/cifar10/deepdefense.py | import sys
import os
THIRD_PARTY_PATH = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../third_party'))
if THIRD_PARTY_PATH not in sys.path:
sys.path.append(THIRD_PARTY_PATH)
from deepdefense_pytorch.models.cifar10 import ConvNet
from ares.model import ClassifierWithLogits
from are... | 0.523908 | 0.253474 |
from logging import error
import discord
from discord import channel
from discord import activity
from discord.ext import commands
import json
from discord.ext.commands.core import has_permissions
intents = discord.Intents.default()
intents.members - True
client = commands.Bot(command_prefix='!', intents... | basic moderation bot python.py | from logging import error
import discord
from discord import channel
from discord import activity
from discord.ext import commands
import json
from discord.ext.commands.core import has_permissions
intents = discord.Intents.default()
intents.members - True
client = commands.Bot(command_prefix='!', intents... | 0.362405 | 0.051702 |
import time
import json
from flask import session, request, g, flash
from app import app
import config
logfile = open(config.logfilename, 'a')
def log(dictionary):
logfile.write(json.dumps(dictionary) + '\n')
logfile.flush()
id_prefix = str(int(time.time()))
id_counter = 0
def get_new_id():
global id... | app/request_logger.py | import time
import json
from flask import session, request, g, flash
from app import app
import config
logfile = open(config.logfilename, 'a')
def log(dictionary):
logfile.write(json.dumps(dictionary) + '\n')
logfile.flush()
id_prefix = str(int(time.time()))
id_counter = 0
def get_new_id():
global id... | 0.107989 | 0.066236 |
from collections import namedtuple
from enum import Enum
from typing import Mapping, List, Optional
import os
from os import path
from os import walk
import re
import logging
_log = logging.getLogger("bs-processors")
start_markdown = re.compile(r"\s*(\"\"\"|''')\s*")
section_start = re.compile(r"\s*#\s*SECTION_START\... | doc_extractor/src/example_extractor.py | from collections import namedtuple
from enum import Enum
from typing import Mapping, List, Optional
import os
from os import path
from os import walk
import re
import logging
_log = logging.getLogger("bs-processors")
start_markdown = re.compile(r"\s*(\"\"\"|''')\s*")
section_start = re.compile(r"\s*#\s*SECTION_START\... | 0.507812 | 0.311244 |
import telepot
import telegram
import urllib.request
from InstagramAPI import InstagramAPI
from telepot.namedtuple import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardButton, InlineKeyboardMarkup
client = InstagramAPI("jakybay", "camillo197")
client.login()
def on_chat_message(msg):
content_ty... | bot.py | import telepot
import telegram
import urllib.request
from InstagramAPI import InstagramAPI
from telepot.namedtuple import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardButton, InlineKeyboardMarkup
client = InstagramAPI("jakybay", "camillo197")
client.login()
def on_chat_message(msg):
content_ty... | 0.040941 | 0.053477 |
import logging
import os
import sys
from pathlib import Path
from typing import List, Tuple, Optional, Union, Dict, Set
from tqdm import tqdm
from langmodels.evaluation.customization import TokenTypeSubset
from langmodels.evaluation.metrics import bin_entropy
from langmodels.evaluation.metrics import mrr, Metric
from... | langmodels/evaluation/evaluation.py | import logging
import os
import sys
from pathlib import Path
from typing import List, Tuple, Optional, Union, Dict, Set
from tqdm import tqdm
from langmodels.evaluation.customization import TokenTypeSubset
from langmodels.evaluation.metrics import bin_entropy
from langmodels.evaluation.metrics import mrr, Metric
from... | 0.709321 | 0.226495 |
import sys, paramiko, time, re, signal, os, getpass, argparse
from subprocess import Popen, PIPE
from ethip import ethip
def stop(signal, frame):
print
exit(1)
def host_exec(command, channel):
if channel.recv_ready():
channel.recv(2048)
channel.send('%s\n' % command)
result = ''
while ... | vmsh.py | import sys, paramiko, time, re, signal, os, getpass, argparse
from subprocess import Popen, PIPE
from ethip import ethip
def stop(signal, frame):
print
exit(1)
def host_exec(command, channel):
if channel.recv_ready():
channel.recv(2048)
channel.send('%s\n' % command)
result = ''
while ... | 0.154344 | 0.114889 |
import rospy
import geometry_msgs.msg
from geometry_msgs.msg import Twist, Pose, Point, PoseStamped, Quaternion, Vector3
from sensor_msgs.msg import JointState
from std_msgs.msg import Header
import tf2_ros
from visualization_msgs.msg import Marker, InteractiveMarkerControl, MarkerArray
class ArmMark():
""" Publi... | nodes/arm_mark.py | import rospy
import geometry_msgs.msg
from geometry_msgs.msg import Twist, Pose, Point, PoseStamped, Quaternion, Vector3
from sensor_msgs.msg import JointState
from std_msgs.msg import Header
import tf2_ros
from visualization_msgs.msg import Marker, InteractiveMarkerControl, MarkerArray
class ArmMark():
""" Publi... | 0.555073 | 0.166032 |
import re
import boto3
import logging
import json
from datetime import datetime
from forward_recieved_email.utils import tools
from forward_recieved_email.config import settings
logger = logging.getLogger(__name__)
def check_email_is_spam(
message_id: str, receipt: str, sender: str, domain: str
) -> None:
... | forward_recieved_email/utils/check_spam.py | import re
import boto3
import logging
import json
from datetime import datetime
from forward_recieved_email.utils import tools
from forward_recieved_email.config import settings
logger = logging.getLogger(__name__)
def check_email_is_spam(
message_id: str, receipt: str, sender: str, domain: str
) -> None:
... | 0.304248 | 0.13612 |
import json
class lan:
def get_lan(self, datacenter_id, lan_id, depth=1):
"""
Retrieves a single LAN by ID.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param lan_id: The unique ID of the LAN.
:type la... | ionosenterprise/requests/lan.py | import json
class lan:
def get_lan(self, datacenter_id, lan_id, depth=1):
"""
Retrieves a single LAN by ID.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param lan_id: The unique ID of the LAN.
:type la... | 0.658418 | 0.530115 |
from xldlib.utils import serialization
__all__ = [
'from_args',
'from_list',
'serializable',
'to_list',
'uniquer',
]
# UNIQUER
# -------
def uniquer(seq, idfun=None):
'''
Convert sequence to a unique list while keeping order.
Recipe modified from:
https://code.activestate.com/rec... | xldlib/general/sequence/functions.py | from xldlib.utils import serialization
__all__ = [
'from_args',
'from_list',
'serializable',
'to_list',
'uniquer',
]
# UNIQUER
# -------
def uniquer(seq, idfun=None):
'''
Convert sequence to a unique list while keeping order.
Recipe modified from:
https://code.activestate.com/rec... | 0.768907 | 0.290138 |
from babel.support import Format
from lxml import etree
from invoicegenerator.config import ConfigStore
from invoicegenerator.generator.rml.rmlgenerator import RMLGenerator
from invoicegenerator.lib.pythonic_testcase import *
from invoicegenerator.model.address import Address
from invoicegenerator.model.invoice impor... | invoicegenerator/generator/rml/tests/rmlgenerator_test.py |
from babel.support import Format
from lxml import etree
from invoicegenerator.config import ConfigStore
from invoicegenerator.generator.rml.rmlgenerator import RMLGenerator
from invoicegenerator.lib.pythonic_testcase import *
from invoicegenerator.model.address import Address
from invoicegenerator.model.invoice impor... | 0.602179 | 0.203569 |
from flask import render_template, redirect, url_for, flash
from flask_wtf import FlaskForm
from wtforms import IntegerField, SubmitField, StringField, TextAreaField
from .models.product import Product
from .models.cart import Cart
from .models.purchase import OrderDetail
from .models.feedbackToProduct import feedbackT... | app/products.py | from flask import render_template, redirect, url_for, flash
from flask_wtf import FlaskForm
from wtforms import IntegerField, SubmitField, StringField, TextAreaField
from .models.product import Product
from .models.cart import Cart
from .models.purchase import OrderDetail
from .models.feedbackToProduct import feedbackT... | 0.317003 | 0.106041 |
import unittest
from neet.boolean import (LogicNetwork, WTNetwork)
import numpy as np
class TestSensitivity(unittest.TestCase):
def test_sensitivity(self):
net = WTNetwork([[1, -1], [0, 1]], [0.5, 0])
self.assertEqual(1.0, net.sensitivity([0, 0]))
def test_average_sensitivity_lengths(self):
... | test/boolean/test_sensitivity.py | import unittest
from neet.boolean import (LogicNetwork, WTNetwork)
import numpy as np
class TestSensitivity(unittest.TestCase):
def test_sensitivity(self):
net = WTNetwork([[1, -1], [0, 1]], [0.5, 0])
self.assertEqual(1.0, net.sensitivity([0, 0]))
def test_average_sensitivity_lengths(self):
... | 0.660829 | 0.739187 |
"""SAM module models."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
from django.db.models impo... | src/ralph_assets/licences/models.py | """SAM module models."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
from django.db.models impo... | 0.874225 | 0.146148 |
from baselines.common.vec_env import VecFrameStack
from gym import register
import sys
from comp300.LearningModel.AgentClasses import *
from baselines.common.cmd_util import make_vec_env
from statistics import stdev
from comp300.LearningModel.cmd_utils import getAverageParser
def getReward(agent, env, render=False):
... | comp300/LearningModel/getAverageReward.py | from baselines.common.vec_env import VecFrameStack
from gym import register
import sys
from comp300.LearningModel.AgentClasses import *
from baselines.common.cmd_util import make_vec_env
from statistics import stdev
from comp300.LearningModel.cmd_utils import getAverageParser
def getReward(agent, env, render=False):
... | 0.810741 | 0.475057 |
from .base import BaseEmbed
from ..utils.utils import check_Xs
import numpy as np
from scipy import linalg, stats
from scipy.sparse.linalg import svds
from sklearn.preprocessing import normalize
from mvlearn.embed.utils import select_dimension
class GCCA(BaseEmbed):
"""
An implementation of Generalized Cano... | mvlearn/embed/gcca.py |
from .base import BaseEmbed
from ..utils.utils import check_Xs
import numpy as np
from scipy import linalg, stats
from scipy.sparse.linalg import svds
from sklearn.preprocessing import normalize
from mvlearn.embed.utils import select_dimension
class GCCA(BaseEmbed):
"""
An implementation of Generalized Cano... | 0.923597 | 0.535524 |
import unittest
from typing import List
from unittest.mock import Mock, PropertyMock, patch
from src.t1000.application.resource.events import EventsDetail
from src.t1000.domain.entity import Event
class EventsDetailTestCase(unittest.TestCase):
def setUp(self):
super().setUp()
self.events_detail =... | test/t1000/unit/application/resource/events/test_events_detail.py | import unittest
from typing import List
from unittest.mock import Mock, PropertyMock, patch
from src.t1000.application.resource.events import EventsDetail
from src.t1000.domain.entity import Event
class EventsDetailTestCase(unittest.TestCase):
def setUp(self):
super().setUp()
self.events_detail =... | 0.745491 | 0.376996 |
import base64
from django.conf import settings
from django.core.files.base import ContentFile
from django.db.models.fields import BigIntegerField
from django.db.models.fields import BinaryField
from django.db.models.fields import BooleanField
from django.db.models.fields import CharField
from django.db.models.fields im... | djenerator/fields_generator.py | import base64
from django.conf import settings
from django.core.files.base import ContentFile
from django.db.models.fields import BigIntegerField
from django.db.models.fields import BinaryField
from django.db.models.fields import BooleanField
from django.db.models.fields import CharField
from django.db.models.fields im... | 0.71123 | 0.141281 |
__all__ = ['create_dash_app']
#Cell
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from functools import lru_cache
from pathlib import Path
import pandas as pd
import numpy as np
import requests
from .core import *
from .recommender im... | word2vec_recommender/explorer.py |
__all__ = ['create_dash_app']
#Cell
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from functools import lru_cache
from pathlib import Path
import pandas as pd
import numpy as np
import requests
from .core import *
from .recommender im... | 0.488039 | 0.093761 |
from urllib.parse import urlparse
from django.contrib.contenttypes.models import ContentType
from django.urls import resolve
from rest_framework import serializers
from drf_nest.serializers import LimitDepthMixin
from drf_nest.serializer_fields import TypeField, GenericRelatedField
from cbe.party.models imp... | cbe/cbe/party/serializers.py | from urllib.parse import urlparse
from django.contrib.contenttypes.models import ContentType
from django.urls import resolve
from rest_framework import serializers
from drf_nest.serializers import LimitDepthMixin
from drf_nest.serializer_fields import TypeField, GenericRelatedField
from cbe.party.models imp... | 0.469034 | 0.07627 |
from flask_unchained import FlaskForm, unchained
from py_meta_utils import (
AbstractMetaOption, McsArgs, MetaOption, MetaOptionsFactory, _missing,
process_factory_meta_options)
from sqlalchemy_unchained.validation import ValidationError, ValidationErrors
from typing import *
from wtforms.ext.sqlalchemy.fields ... | flask_unchained/bundles/sqlalchemy/forms.py | from flask_unchained import FlaskForm, unchained
from py_meta_utils import (
AbstractMetaOption, McsArgs, MetaOption, MetaOptionsFactory, _missing,
process_factory_meta_options)
from sqlalchemy_unchained.validation import ValidationError, ValidationErrors
from typing import *
from wtforms.ext.sqlalchemy.fields ... | 0.874292 | 0.126785 |
from django.db.models import QuerySet
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.urls import path
from django.http import HttpRequest, HttpResponse
from django.core.signing import BadSignature, SignatureExpired
from django.contrib.auth import ge... | django_modelapiview/ModelAPIView.py | from django.db.models import QuerySet
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.urls import path
from django.http import HttpRequest, HttpResponse
from django.core.signing import BadSignature, SignatureExpired
from django.contrib.auth import ge... | 0.737442 | 0.077308 |
import os
import sys
import unittest
import json
from django.test.client import Client
client = {}
frontendData = {}
# Runs before each test
def globalSetup():
global client
# Set a new "client" every time
client = Client()
# Test NonExisting routes
class NonExistingTest( unittest.TestCase ):
# Ru... | test.py | import os
import sys
import unittest
import json
from django.test.client import Client
client = {}
frontendData = {}
# Runs before each test
def globalSetup():
global client
# Set a new "client" every time
client = Client()
# Test NonExisting routes
class NonExistingTest( unittest.TestCase ):
# Ru... | 0.370795 | 0.505554 |
import numpy as np
def donor_acceptor_direction_vector(molecule, feat_type, atom_indx, coords, conformer_idx):
"""
Compute the direction vector for an H bond donor or H bond acceptor feature
Parameters
----------
molecule : rdkit.Chem.rdchem.Mol
Molecule that conta... | openpharmacophore/utils/direction_vector.py | import numpy as np
def donor_acceptor_direction_vector(molecule, feat_type, atom_indx, coords, conformer_idx):
"""
Compute the direction vector for an H bond donor or H bond acceptor feature
Parameters
----------
molecule : rdkit.Chem.rdchem.Mol
Molecule that conta... | 0.908638 | 0.832713 |
from platypush.plugins import action
from platypush.plugins.google import GooglePlugin
class GoogleYoutubePlugin(GooglePlugin):
"""
YouTube plugin.
Requires:
* **google-api-python-client** (``pip install google-api-python-client``)
* **oauth2client** (``pip install oauth2client``)
"... | platypush/plugins/google/youtube/__init__.py | from platypush.plugins import action
from platypush.plugins.google import GooglePlugin
class GoogleYoutubePlugin(GooglePlugin):
"""
YouTube plugin.
Requires:
* **google-api-python-client** (``pip install google-api-python-client``)
* **oauth2client** (``pip install oauth2client``)
"... | 0.694717 | 0.324302 |
import openstack
from common.openstack_libs import glance_client as client
from common.openstack_libs import glance_exception as glanceException
from common import log_orig as contrail_logging
from tcutils.util import retry
class GlanceHelper(object):
'''
Wrapper around glance client library
Optiona... | fixtures/glance_test.py | import openstack
from common.openstack_libs import glance_client as client
from common.openstack_libs import glance_exception as glanceException
from common import log_orig as contrail_logging
from tcutils.util import retry
class GlanceHelper(object):
'''
Wrapper around glance client library
Optiona... | 0.531696 | 0.164382 |
from labs.common.SensorData import SensorData
from coapthon.resources.resource import Resource
import coapthon.defines as defines
'''
classdocs
'''
class TempResourceHandler(Resource):
'''
CoAP resource for storing the temperature data
'''
def __init__(self, config, name="TemperatureRe... | apps/labs/module07/TempResourceHandler.py | from labs.common.SensorData import SensorData
from coapthon.resources.resource import Resource
import coapthon.defines as defines
'''
classdocs
'''
class TempResourceHandler(Resource):
'''
CoAP resource for storing the temperature data
'''
def __init__(self, config, name="TemperatureRe... | 0.626353 | 0.132852 |
import os
from subprocess import check_output, Popen, PIPE
from .helpers import modeToName, registerHash
def renderHtml(pathHtml,pageWidth,pathPng):
# convert all PDF pages into numbered images and place them in reference or comparison folder
head, tail = os.path.split(pathHtml)
somestring = "python3 "+os... | src/dapscompare/renderers.py |
import os
from subprocess import check_output, Popen, PIPE
from .helpers import modeToName, registerHash
def renderHtml(pathHtml,pageWidth,pathPng):
# convert all PDF pages into numbered images and place them in reference or comparison folder
head, tail = os.path.split(pathHtml)
somestring = "python3 "+os... | 0.067716 | 0.086246 |
import datetime
import mock
from google.protobuf import timestamp_pb2
from libs import analysis_status
from libs import time_util
from model import suspected_cl_status
from model.flake.analysis import triggering_sources
from model.flake.analysis.flake_culprit import FlakeCulprit
from model.flake.analysis.data_point i... | appengine/findit/services/test/event_reporting_test.py | import datetime
import mock
from google.protobuf import timestamp_pb2
from libs import analysis_status
from libs import time_util
from model import suspected_cl_status
from model.flake.analysis import triggering_sources
from model.flake.analysis.flake_culprit import FlakeCulprit
from model.flake.analysis.data_point i... | 0.566019 | 0.362772 |
import logging
import gensim
import numpy as np
import pandas as pd
from keras.callbacks import Callback
from keras.layers import Dense, Input, GlobalMaxPooling1D, Conv1D, Embedding
from keras.models import Model
from keras.optimizers import RMSprop
from keras.preprocessing.sequence import pad_sequences
from keras.pre... | demo.py | import logging
import gensim
import numpy as np
import pandas as pd
from keras.callbacks import Callback
from keras.layers import Dense, Input, GlobalMaxPooling1D, Conv1D, Embedding
from keras.models import Model
from keras.optimizers import RMSprop
from keras.preprocessing.sequence import pad_sequences
from keras.pre... | 0.818265 | 0.454896 |
import matplotlib
import pdb
import ftplib
import datetime
from urlparse import urlparse
import logging
import os
import sys
import gzip
import pylab as plt
import pandas as pd
from scipy.interpolate import griddata
import numpy as np
sys.path.append(os.path.join(os.getcwd(), os.pardir))
import region_parameters
from s... | ftp_linker/get_daily_images.py | import matplotlib
import pdb
import ftplib
import datetime
from urlparse import urlparse
import logging
import os
import sys
import gzip
import pylab as plt
import pandas as pd
from scipy.interpolate import griddata
import numpy as np
sys.path.append(os.path.join(os.getcwd(), os.pardir))
import region_parameters
from s... | 0.260578 | 0.145419 |
a = [11, 3, 5, 7, 9]
# eine Liste ist eine geordnete Zusammenfassung von Elementen
# auch als Array bekannt
print(a)
print(a)
print(a)
# unterschiedliche Datentypen bzw. beliebige Objekte
b = [2, "Hallo", 12.5]
print(b)
# auch eine Liste/Array ist ein Objekt und kann daher gespeichert werden
c = [[2, 4], ['a', 'b']]... | Lektion_5/22_Listen.py | a = [11, 3, 5, 7, 9]
# eine Liste ist eine geordnete Zusammenfassung von Elementen
# auch als Array bekannt
print(a)
print(a)
print(a)
# unterschiedliche Datentypen bzw. beliebige Objekte
b = [2, "Hallo", 12.5]
print(b)
# auch eine Liste/Array ist ein Objekt und kann daher gespeichert werden
c = [[2, 4], ['a', 'b']]... | 0.179135 | 0.511351 |
import json
import re
import glob
import requests
import datetime
from django.contrib.staticfiles.storage import staticfiles_storage
from django.http.response import Http404, JsonResponse
from django.views.generic.base import TemplateView
from iUTAHData.settings.base import *
from django.shortcuts import render
from d... | src/mdfserver/views.py | import json
import re
import glob
import requests
import datetime
from django.contrib.staticfiles.storage import staticfiles_storage
from django.http.response import Http404, JsonResponse
from django.views.generic.base import TemplateView
from iUTAHData.settings.base import *
from django.shortcuts import render
from d... | 0.317215 | 0.120698 |
from runners import GaussianNetworkRunner, BinaryNetworkRunner
from experiments import BinaryExperiment, GaussianExperiment
from priv_bmi import BMIExperiment
from utils import get_binary_data, get_gaussian_data
from utils import save_results
from privpack import BinaryPrivacyPreservingAdversarialNetwork as BinaryGAN
... | privpack-app/__main__.py | from runners import GaussianNetworkRunner, BinaryNetworkRunner
from experiments import BinaryExperiment, GaussianExperiment
from priv_bmi import BMIExperiment
from utils import get_binary_data, get_gaussian_data
from utils import save_results
from privpack import BinaryPrivacyPreservingAdversarialNetwork as BinaryGAN
... | 0.863046 | 0.225246 |
import os
import sys
import time
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
from shutil import copyfile
import psutil
import gc
def import_from(module, name):
"""
from 'module' import 'name'
:param module: module name
:param name: name of function that shall b... | GCE/utils.py | import os
import sys
import time
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
from shutil import copyfile
import psutil
import gc
def import_from(module, name):
"""
from 'module' import 'name'
:param module: module name
:param name: name of function that shall b... | 0.39222 | 0.136464 |
import wx
class Form1( wx.Panel ):
def __init__( self, parent, id ):
wx.Panel.__init__( self, parent, id )
self.quote = wx.StaticText( self, -1, "Your quote is",
wx.Point( 20, 30 ) )
self.logger = wx.TextCtrl( self, 5, "", wx.Point(300, 20),
... | python/wx/learn5.py | import wx
class Form1( wx.Panel ):
def __init__( self, parent, id ):
wx.Panel.__init__( self, parent, id )
self.quote = wx.StaticText( self, -1, "Your quote is",
wx.Point( 20, 30 ) )
self.logger = wx.TextCtrl( self, 5, "", wx.Point(300, 20),
... | 0.269518 | 0.089654 |
from ..common_descs import *
from .objs.tag import *
from supyr_struct.defs.tag_def import TagDef
wezr_capture_the_flag_variant_game_mode = (
"multiple",
"single",
"neutral",
)
wezr_capture_the_flag_variant_home_flag_waypoint = (
"unknown_1",
"unknown_2",
"unknown_3",
"... | h3/defs/wezr.py |
from ..common_descs import *
from .objs.tag import *
from supyr_struct.defs.tag_def import TagDef
wezr_capture_the_flag_variant_game_mode = (
"multiple",
"single",
"neutral",
)
wezr_capture_the_flag_variant_home_flag_waypoint = (
"unknown_1",
"unknown_2",
"unknown_3",
"... | 0.33764 | 0.200284 |
import unittest
import inspect
from pathlib import Path
import json
import psycopg
from common import (
MINDSDB_DATABASE,
CONFIG_PATH,
check_prediction_values,
condition_dict_to_str,
run_environment
)
# +++ define test data
TEST_DATASET = 'used_car_price'
TO_PREDICT = {
'enginesize': str,
... | tests/integration_tests/flows/test_postgres.py | import unittest
import inspect
from pathlib import Path
import json
import psycopg
from common import (
MINDSDB_DATABASE,
CONFIG_PATH,
check_prediction_values,
condition_dict_to_str,
run_environment
)
# +++ define test data
TEST_DATASET = 'used_car_price'
TO_PREDICT = {
'enginesize': str,
... | 0.456168 | 0.414899 |
import os
import dash_core_components as dcc
import dash_html_components as html
from dash_docs.tutorial.components import Example, Syntax
from dash_docs import tools
from dash_docs import reusable_components
def get_example_name(path):
"""Returns the name of an example given its path."""
# name is the filen... | dash_docs/tutorial/faqs.py | import os
import dash_core_components as dcc
import dash_html_components as html
from dash_docs.tutorial.components import Example, Syntax
from dash_docs import tools
from dash_docs import reusable_components
def get_example_name(path):
"""Returns the name of an example given its path."""
# name is the filen... | 0.833833 | 0.543833 |
import errno
import os
import sys
import time
import math, csv
import torch.nn as nn
import torch.nn.init as init
from torch.autograd import Variable
__all__ = ['get_mean_and_std', 'init_params', 'mkdir_p', 'AverageMeter', 'CSVLogger']
def get_mean_and_std(dataset):
'''Compute the mean and std value of dataset.... | utils/misc.py | import errno
import os
import sys
import time
import math, csv
import torch.nn as nn
import torch.nn.init as init
from torch.autograd import Variable
__all__ = ['get_mean_and_std', 'init_params', 'mkdir_p', 'AverageMeter', 'CSVLogger']
def get_mean_and_std(dataset):
'''Compute the mean and std value of dataset.... | 0.624294 | 0.29209 |
import re
import os
import argparse
from glob import glob
from utils import sync
from bmt import Bmt
class Iozone(Bmt):
def __init__(self, size='64M', record='1M', threads=4, **kwargs):
super().__init__(**kwargs)
self.name = 'IOZONE'
self.bin = 'iozone'
se... | src/iozone.py |
import re
import os
import argparse
from glob import glob
from utils import sync
from bmt import Bmt
class Iozone(Bmt):
def __init__(self, size='64M', record='1M', threads=4, **kwargs):
super().__init__(**kwargs)
self.name = 'IOZONE'
self.bin = 'iozone'
se... | 0.391755 | 0.106691 |
__all__ = ['get_all_flags', 'get_cell_flags', 'NoExportPreprocessor', 'test_nb']
# Cell
from .imports import *
from .sync import *
from .export import *
from .export import _mk_flag_re
from .export2html import _re_notebook2script
from nbconvert.preprocessors import ExecutePreprocessor
# Cell
_re_all_flag = ReTstFla... | nbdev/test.py |
__all__ = ['get_all_flags', 'get_cell_flags', 'NoExportPreprocessor', 'test_nb']
# Cell
from .imports import *
from .sync import *
from .export import *
from .export import _mk_flag_re
from .export2html import _re_notebook2script
from nbconvert.preprocessors import ExecutePreprocessor
# Cell
_re_all_flag = ReTstFla... | 0.394667 | 0.141815 |
from colorConv import *
from colBase import ColBase as cB
from colorFuncs import Harmonies
import colRGB as cRGB
class ColHSL(cB, Harmonies):
""" HSL color class
Inherits from ColBase, Harmonies """
lfields = ['H', 'S', 'L']
def __init__(self, H=-1.0, S=0.0, L=0.0, *args, **kwargs): # default: Bla... | SMFSWcolor/colHSL.py | from colorConv import *
from colBase import ColBase as cB
from colorFuncs import Harmonies
import colRGB as cRGB
class ColHSL(cB, Harmonies):
""" HSL color class
Inherits from ColBase, Harmonies """
lfields = ['H', 'S', 'L']
def __init__(self, H=-1.0, S=0.0, L=0.0, *args, **kwargs): # default: Bla... | 0.846006 | 0.274357 |
import pandas
import numpy as np
from cornellGrading import cornellQualtrics
import os
def genReadingAssignments(infile, outfile):
# generate reading assignments
# infile must be xlsx with two sheets (Readers & Canddiates)
# grab all input data
if isinstance(infile, str):
tmp = pandas.ExcelFi... | admissions/reading.py | import pandas
import numpy as np
from cornellGrading import cornellQualtrics
import os
def genReadingAssignments(infile, outfile):
# generate reading assignments
# infile must be xlsx with two sheets (Readers & Canddiates)
# grab all input data
if isinstance(infile, str):
tmp = pandas.ExcelFi... | 0.297776 | 0.332189 |
from math import isnan
import pytest
from haddock.gear.prepare_run import (
get_expandable_parameters,
populate_mol_parameters,
populate_topology_molecule_params,
)
from haddock.gear.yaml2cfg import read_from_yaml_config
from haddock.modules.topology.topoaa import DEFAULT_CONFIG
DEFAULT_DICT = read_... | tests/test_gear_prepare_run.py | from math import isnan
import pytest
from haddock.gear.prepare_run import (
get_expandable_parameters,
populate_mol_parameters,
populate_topology_molecule_params,
)
from haddock.gear.yaml2cfg import read_from_yaml_config
from haddock.modules.topology.topoaa import DEFAULT_CONFIG
DEFAULT_DICT = read_... | 0.692434 | 0.410106 |
try:
from mock import Mock, patch
except ImportError:
from unittest.mock import Mock, patch
from openid.consumer import consumer
from django.test import TestCase
from django.core.urlresolvers import reverse
from allauth.utils import get_user_model
from . import views
from .utils import AXAttribute
class Op... | allauth/socialaccount/providers/openid/tests.py | try:
from mock import Mock, patch
except ImportError:
from unittest.mock import Mock, patch
from openid.consumer import consumer
from django.test import TestCase
from django.core.urlresolvers import reverse
from allauth.utils import get_user_model
from . import views
from .utils import AXAttribute
class Op... | 0.542621 | 0.147832 |
from itertools import product
import pytest
import torch
import torch_scatter
from .utils import dtypes, devices, tensor
tests = [{
'name': 'add',
'src': [[2, 0, 1, 4, 3], [0, 2, 1, 3, 4]],
'index': [[4, 5, 4, 2, 3], [0, 0, 2, 2, 1]],
'dim': -1,
'fill_value': 0,
'expected': [[0, 0, 4, 3, 3, 0... | test/test_forward.py | from itertools import product
import pytest
import torch
import torch_scatter
from .utils import dtypes, devices, tensor
tests = [{
'name': 'add',
'src': [[2, 0, 1, 4, 3], [0, 2, 1, 3, 4]],
'index': [[4, 5, 4, 2, 3], [0, 0, 2, 2, 1]],
'dim': -1,
'fill_value': 0,
'expected': [[0, 0, 4, 3, 3, 0... | 0.57081 | 0.763858 |
from disasm import Types
from utils.ail_utils import ELF_utils, unify_int_list, dec_hex, get_loc
class lib32_helper(object):
"""
Manage PC relative code for x86 32bit binaries
"""
def __init__(self, instrs, funcs):
"""
:param instrs: instruction list
:param funcs: function lis... | uroboros-diversification/src/analysis/share_lib_helper.py | from disasm import Types
from utils.ail_utils import ELF_utils, unify_int_list, dec_hex, get_loc
class lib32_helper(object):
"""
Manage PC relative code for x86 32bit binaries
"""
def __init__(self, instrs, funcs):
"""
:param instrs: instruction list
:param funcs: function lis... | 0.751192 | 0.373704 |
import sys
from os import path, chdir
from . import issues
from .qs import isExist, confirm
from .arg import Help, defaultspath, StatusBar, IGNORE as ignore
from .version import Version
from .diff import diffhash, logviewer
from .git.commit import Commit
from .git.status import Status
from .git.init import Init
from .... | src/proc.py | import sys
from os import path, chdir
from . import issues
from .qs import isExist, confirm
from .arg import Help, defaultspath, StatusBar, IGNORE as ignore
from .version import Version
from .diff import diffhash, logviewer
from .git.commit import Commit
from .git.status import Status
from .git.init import Init
from .... | 0.185172 | 0.076684 |
import collections
import datetime
import os
from db.db import DatabaseConnection
import utils
def _get_tables_and_columns_in_schema(db, schema):
"""Returns a dict describing all tables and columns in `schema`."""
# Obtain names of tables in `schema`:
q = """
SELECT table_name FROM information_sch... | data/status.py | import collections
import datetime
import os
from db.db import DatabaseConnection
import utils
def _get_tables_and_columns_in_schema(db, schema):
"""Returns a dict describing all tables and columns in `schema`."""
# Obtain names of tables in `schema`:
q = """
SELECT table_name FROM information_sch... | 0.68941 | 0.205595 |
from torch import Tensor
from typing import List, Optional, Tuple
from torch import Tensor
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.checkpoint import checkpoint
class Boom(nn.Module):
def __init__(self, input_dim, hidden_dim=int(2048*2), dropout=0, shortcut=False):
... | model.py | from torch import Tensor
from typing import List, Optional, Tuple
from torch import Tensor
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.checkpoint import checkpoint
class Boom(nn.Module):
def __init__(self, input_dim, hidden_dim=int(2048*2), dropout=0, shortcut=False):
... | 0.942507 | 0.53959 |
from os import linesep
from sys import getsizeof
from logging import getLogger
from ._check import check_var, raise_
from ..Functions.get_logger import get_logger
from ..Functions.save import save
from ..Functions.load import load_init_dict
from ..Functions.Load.import_class import import_class
from copy import... | pyleecan/Classes/LUTslip.py | from os import linesep
from sys import getsizeof
from logging import getLogger
from ._check import check_var, raise_
from ..Functions.get_logger import get_logger
from ..Functions.save import save
from ..Functions.load import load_init_dict
from ..Functions.Load.import_class import import_class
from copy import... | 0.480479 | 0.102709 |
import logging
import gin
import numpy as np
from ribs.emitters import EmitterBase
from src.objectives.gym_control.td3 import TD3
logger = logging.getLogger(__name__)
@gin.configurable
class PGAEmitter(EmitterBase):
"""Emitter based on the PG variation from PGA-ME."""
def __init__(
self,
a... | src/emitters/pga_emitter.py | import logging
import gin
import numpy as np
from ribs.emitters import EmitterBase
from src.objectives.gym_control.td3 import TD3
logger = logging.getLogger(__name__)
@gin.configurable
class PGAEmitter(EmitterBase):
"""Emitter based on the PG variation from PGA-ME."""
def __init__(
self,
a... | 0.885495 | 0.272073 |
import unittest
import StringIO
from openmdao.main.api import Assembly, set_as_top
from openmdao.test.execcomp import ExecComp
from openmdao.lib.casehandlers.api import JSONCaseRecorder, CaseDataset
from openmdao.lib.drivers.sensitivity import SensitivityDriver
class RecordingOptionsTestCase(unittest.TestCase):
... | openmdao.lib/src/openmdao/lib/casehandlers/test/test_recording_options.py | import unittest
import StringIO
from openmdao.main.api import Assembly, set_as_top
from openmdao.test.execcomp import ExecComp
from openmdao.lib.casehandlers.api import JSONCaseRecorder, CaseDataset
from openmdao.lib.drivers.sensitivity import SensitivityDriver
class RecordingOptionsTestCase(unittest.TestCase):
... | 0.469763 | 0.296756 |
import tensorflow as tf
import tensorflow_probability as tfp
import sonnet as snt
class NNNormalDistribution(tf.Module):
"""A Normal distribution with mean and var parametrised by NN"""
def __init__(self,
size,
hidden_layer_sizes,
sigma_min=0.0,
... | filterflow/models/__init__.py | import tensorflow as tf
import tensorflow_probability as tfp
import sonnet as snt
class NNNormalDistribution(tf.Module):
"""A Normal distribution with mean and var parametrised by NN"""
def __init__(self,
size,
hidden_layer_sizes,
sigma_min=0.0,
... | 0.930126 | 0.324342 |
from ctypes import *
# Type definitions
# _abn_unit must be the same type like abn_unit in abn/include/abn.h file one
_abn_unit = c_uint32
# main type of ABN library
class _abn_t(Structure):
_fields_ = [("chain", POINTER(_abn_unit)),
("volume", c_uint)]
# pointers
_abn_t_p = POINTER(_abn_t)
_abn_unit_p = POINTE... | wrappers/python/abn_wrapper.py | from ctypes import *
# Type definitions
# _abn_unit must be the same type like abn_unit in abn/include/abn.h file one
_abn_unit = c_uint32
# main type of ABN library
class _abn_t(Structure):
_fields_ = [("chain", POINTER(_abn_unit)),
("volume", c_uint)]
# pointers
_abn_t_p = POINTER(_abn_t)
_abn_unit_p = POINTE... | 0.398992 | 0.223208 |
import string
import gensim
import numpy as np
import pandas as pd
import tensorflow as tf
from bs4 import BeautifulSoup
from janome.tokenizer import Tokenizer
from sklearn.metrics import f1_score, precision_score, recall_score
from sklearn.model_selection import train_test_split
from tensorflow.keras.callbacks import ... | src/SupervisedLearning/RNN_LSTM_CNN.py | import string
import gensim
import numpy as np
import pandas as pd
import tensorflow as tf
from bs4 import BeautifulSoup
from janome.tokenizer import Tokenizer
from sklearn.metrics import f1_score, precision_score, recall_score
from sklearn.model_selection import train_test_split
from tensorflow.keras.callbacks import ... | 0.876872 | 0.291249 |
import math
import numpy as np
class FGMPlanner:
def __init__(self, conf, robot_scale=0.3302):
self.conf = conf
self.PI = 3.141592
self.rf_distance = 2.5
self.RACECAR_LENGTH = 0.325
self.SPEED_MAX = self.conf.max_speed
self.SPEED_MIN = self.conf.min_speed
... | examples/planner/fgm_gnu.py |
import math
import numpy as np
class FGMPlanner:
def __init__(self, conf, robot_scale=0.3302):
self.conf = conf
self.PI = 3.141592
self.rf_distance = 2.5
self.RACECAR_LENGTH = 0.325
self.SPEED_MAX = self.conf.max_speed
self.SPEED_MIN = self.conf.min_speed
... | 0.409811 | 0.349699 |
import numpy as np
from scipy.spatial.distance import cdist
from sklearn.gaussian_process.kernels import Matern, RBF
from src.numeric.kronecker_algebra import kron_invert_matrices, kron_mv_prod, kron_log_det
class BetaPriorWithIntercept:
"""
Normal-InvGamma prior for the regression coefficients. The intercep... | src/inference/priors.py | import numpy as np
from scipy.spatial.distance import cdist
from sklearn.gaussian_process.kernels import Matern, RBF
from src.numeric.kronecker_algebra import kron_invert_matrices, kron_mv_prod, kron_log_det
class BetaPriorWithIntercept:
"""
Normal-InvGamma prior for the regression coefficients. The intercep... | 0.908557 | 0.688351 |
import os
import json
import logging
import glob
import csv
from bs4 import BeautifulSoup
log = logging.getLogger(__name__)
logging.basicConfig(format='%(message)s', level=logging.INFO)
log.info(f"Transforming berlinstartupjobs offers....")
BASE = os.path.dirname(os.path.abspath(__name__))
folder = os.path.join(BAS... | utils/berlinstartupjobs_transformer.py |
import os
import json
import logging
import glob
import csv
from bs4 import BeautifulSoup
log = logging.getLogger(__name__)
logging.basicConfig(format='%(message)s', level=logging.INFO)
log.info(f"Transforming berlinstartupjobs offers....")
BASE = os.path.dirname(os.path.abspath(__name__))
folder = os.path.join(BAS... | 0.219421 | 0.057361 |
import zipfile
import py.path # type hints
import pytest
import xmldiff.main
from lxml import etree
from benker.converters.ooxml2formex import convert_ooxml2formex
from tests.resources import RESOURCES_DIR
def _check_expected(dst_xml, expected_name):
# - Compare with expected
xml_parser = etree.XMLParser(... | tests/converters/test_convert_ooxml2formex4.py | import zipfile
import py.path # type hints
import pytest
import xmldiff.main
from lxml import etree
from benker.converters.ooxml2formex import convert_ooxml2formex
from tests.resources import RESOURCES_DIR
def _check_expected(dst_xml, expected_name):
# - Compare with expected
xml_parser = etree.XMLParser(... | 0.429788 | 0.384883 |
import os
import time
import shutil
import pytest
from filenumutils.filenum_functions import get_last_folder_number, get_last_file_number, get_next_file, get_next_folder
test_folder_path = None
def setup_function():
global test_folder_path
time_hash = str(time.time())[-6:]
test_folder_path = f'_test_fol... | filenumutils/tests/filenum_functions_test.py | import os
import time
import shutil
import pytest
from filenumutils.filenum_functions import get_last_folder_number, get_last_file_number, get_next_file, get_next_folder
test_folder_path = None
def setup_function():
global test_folder_path
time_hash = str(time.time())[-6:]
test_folder_path = f'_test_fol... | 0.372163 | 0.471162 |
from collections import OrderedDict
import dateutil.parser
import dateutil.tz
_PR_TITLE_TRUNCATION_LENGTH = 50
_WORK_ITEM_TITLE_TRUNCATION_LENGTH = 70
def transform_pull_requests_table_output(result):
table_output = []
for item in result:
table_output.append(_transform_pull_request_row(item))
r... | src/command_modules/vsts-cli-code/vsts/cli/code/_format.py |
from collections import OrderedDict
import dateutil.parser
import dateutil.tz
_PR_TITLE_TRUNCATION_LENGTH = 50
_WORK_ITEM_TITLE_TRUNCATION_LENGTH = 70
def transform_pull_requests_table_output(result):
table_output = []
for item in result:
table_output.append(_transform_pull_request_row(item))
r... | 0.347205 | 0.20466 |
import logging
import re
from collections import namedtuple
from packageurl import PackageURL
logger = logging.getLogger(__name__)
# This code has been vendored from scancode.
# https://github.com/nexB/scancode-toolkit/blob/16ae20a343c5332114edac34c7b6fcf2fb6bca74/src/packagedcode/rpm.py#L91
class EVR(namedtuple("... | vulnerabilities/rpm_utils.py |
import logging
import re
from collections import namedtuple
from packageurl import PackageURL
logger = logging.getLogger(__name__)
# This code has been vendored from scancode.
# https://github.com/nexB/scancode-toolkit/blob/16ae20a343c5332114edac34c7b6fcf2fb6bca74/src/packagedcode/rpm.py#L91
class EVR(namedtuple("... | 0.732879 | 0.19886 |
from statsmodels.tsa.api import VAR
from statsmodels.tsa.stattools import adfuller
import joblib
class DataNotMatchError(Exception):
pass
class PROCESS(object):
def __init__(self, data):
self.diff = 0
self.data = data
def adfuller_test(self, series, thresh=0.05, verbose=False):
... | qp/qptrain.py |
from statsmodels.tsa.api import VAR
from statsmodels.tsa.stattools import adfuller
import joblib
class DataNotMatchError(Exception):
pass
class PROCESS(object):
def __init__(self, data):
self.diff = 0
self.data = data
def adfuller_test(self, series, thresh=0.05, verbose=False):
... | 0.704465 | 0.565059 |
from __future__ import annotations
import math
import numpy as np
from numba import njit
@njit(cache=True)
def _slice_idx_generator(oH: int, oW: int, sH: int, sW: int) -> np.ndarray:
indices = np.empty((oH * oW, 2), np.int16)
ax = np.arange(oH)
ax *= sH
ax = np.repeat(ax, oW)
indices[:, 0] = a... | dnn/layers/utils/conv_utils.py | from __future__ import annotations
import math
import numpy as np
from numba import njit
@njit(cache=True)
def _slice_idx_generator(oH: int, oW: int, sH: int, sW: int) -> np.ndarray:
indices = np.empty((oH * oW, 2), np.int16)
ax = np.arange(oH)
ax *= sH
ax = np.repeat(ax, oW)
indices[:, 0] = a... | 0.848314 | 0.498657 |
import sys
from argparse import ArgumentParser
import numpy as np
import pandas as pd
from tensorflow import keras
input_args = sys.argv
Nucleosome_data_sample = pd.read_csv(input_args[1], delimiter='\t', header=None)
Nucleosome_data_new_all = Nucleosome_data_sample
TSS_matrix_new_all = pd.read_csv(input_args[2], de... | utils/Deeplearning_Nucleosome_predict_train_RPE.py |
import sys
from argparse import ArgumentParser
import numpy as np
import pandas as pd
from tensorflow import keras
input_args = sys.argv
Nucleosome_data_sample = pd.read_csv(input_args[1], delimiter='\t', header=None)
Nucleosome_data_new_all = Nucleosome_data_sample
TSS_matrix_new_all = pd.read_csv(input_args[2], de... | 0.380183 | 0.345823 |
# standard library
import datetime
# third party
from django.test import TestCase
# local
from query.reservoirqueries.models import ReservoirQueryParameters
from tests.fixture_manager import get_fixtures
class ReservoirQueryParametersTestCase(TestCase):
"""
Base class for testing the ReservoirQueryParameter... | Incident-Response/Tools/cyphon/cyphon/query/reservoirqueries/tests/test_models.py | # standard library
import datetime
# third party
from django.test import TestCase
# local
from query.reservoirqueries.models import ReservoirQueryParameters
from tests.fixture_manager import get_fixtures
class ReservoirQueryParametersTestCase(TestCase):
"""
Base class for testing the ReservoirQueryParameter... | 0.563138 | 0.626538 |
import sys
import os
import math
import torch
import torch.nn as nn
import pandas as pd
from graphiler import EdgeBatchDummy, NodeBatchDummy, mpdfg_builder, update_all
from graphiler.utils import load_data, setup, check_equal, bench, hetero_dataset, DEFAULT_DIM, init_log, empty_cache
import dgl.function as fn
from d... | examples/HGT/HGT.py | import sys
import os
import math
import torch
import torch.nn as nn
import pandas as pd
from graphiler import EdgeBatchDummy, NodeBatchDummy, mpdfg_builder, update_all
from graphiler.utils import load_data, setup, check_equal, bench, hetero_dataset, DEFAULT_DIM, init_log, empty_cache
import dgl.function as fn
from d... | 0.712932 | 0.533641 |
from django.db import models
from django.contrib.auth.models import AbstractUser
from utils.models import CommonModel
class User(AbstractUser):
""" 用户模型 """
avatar = models.ImageField('用户头像', upload_to='avatar/%Y%m', null=True, blank=True)
nickname = models.CharField('昵称', max_length=32, unique=... | accounts/models.py | from django.db import models
from django.contrib.auth.models import AbstractUser
from utils.models import CommonModel
class User(AbstractUser):
""" 用户模型 """
avatar = models.ImageField('用户头像', upload_to='avatar/%Y%m', null=True, blank=True)
nickname = models.CharField('昵称', max_length=32, unique=... | 0.388966 | 0.074601 |
import asyncio
import logging
import os
import shutil
import torch
from pyppeteer import launch
from torchvision.models import resnet18
from mmdeploy.core import FUNCTION_REWRITER, RewriterContext, patch_model
@FUNCTION_REWRITER.register_rewriter(
func_name='torchvision.models.ResNet._forward_impl')
def forward... | demo/demo_rewrite.py | import asyncio
import logging
import os
import shutil
import torch
from pyppeteer import launch
from torchvision.models import resnet18
from mmdeploy.core import FUNCTION_REWRITER, RewriterContext, patch_model
@FUNCTION_REWRITER.register_rewriter(
func_name='torchvision.models.ResNet._forward_impl')
def forward... | 0.57523 | 0.227909 |
import argparse
import logging
import torchvision.utils
from tqdm import tqdm
from typing import Optional
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from torchvision.utils import make_grid
from utils.eval import AverageMeterSet
from utils.train import get_random_block_mask, get_random... | eval.py | import argparse
import logging
import torchvision.utils
from tqdm import tqdm
from typing import Optional
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from torchvision.utils import make_grid
from utils.eval import AverageMeterSet
from utils.train import get_random_block_mask, get_random... | 0.897094 | 0.295522 |
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
import math
import copy
import numpy as np
class MAMLLayer(paddle.nn.Layer):
def __init__(self, conv_stride, conv_padding, conv_kernal, bn_channel):
super(MAMLLayer, self).__init__()
# ------------------------第1个conv2d---------... | models/multitask/maml/net.py |
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
import math
import copy
import numpy as np
class MAMLLayer(paddle.nn.Layer):
def __init__(self, conv_stride, conv_padding, conv_kernal, bn_channel):
super(MAMLLayer, self).__init__()
# ------------------------第1个conv2d---------... | 0.686475 | 0.239883 |
import zipfile
import io
import tempfile
import traceback
from collections import namedtuple
import rx
import rx.operators as ops
import rxsci as rs
from cyclotron.debug import trace_observable
from makinage.util import import_function
from mlflow.pyfunc import load_model
from mlflow.pyfunc.backend import PyFuncBack... | makinage/serve/serve.py | import zipfile
import io
import tempfile
import traceback
from collections import namedtuple
import rx
import rx.operators as ops
import rxsci as rs
from cyclotron.debug import trace_observable
from makinage.util import import_function
from mlflow.pyfunc import load_model
from mlflow.pyfunc.backend import PyFuncBack... | 0.699254 | 0.308477 |
from django.contrib.contenttypes.models import ContentType
from mayan.apps.acls.classes import ModelPermission
from mayan.apps.documents.tests.base import GenericDocumentViewTestCase
from mayan.apps.messaging.events import event_message_created
from mayan.apps.messaging.models import Message
from mayan.apps.testing.te... | mayan/apps/events/tests/test_views.py | from django.contrib.contenttypes.models import ContentType
from mayan.apps.acls.classes import ModelPermission
from mayan.apps.documents.tests.base import GenericDocumentViewTestCase
from mayan.apps.messaging.events import event_message_created
from mayan.apps.messaging.models import Message
from mayan.apps.testing.te... | 0.587233 | 0.246012 |
import pickle
import sys
import pytest
from .generate_old_pickles import PICKLE_DIRECTORY
def load_obj(filename, check_deprecation_warning='auto'):
if check_deprecation_warning == 'auto':
# pickles files generated with cloudpickle_fast.py on old versions of
# coudpickle with Python < 3.8 use non... | offline_install/cloudpickle-1.5.0/tests/test_backward_compat.py | import pickle
import sys
import pytest
from .generate_old_pickles import PICKLE_DIRECTORY
def load_obj(filename, check_deprecation_warning='auto'):
if check_deprecation_warning == 'auto':
# pickles files generated with cloudpickle_fast.py on old versions of
# coudpickle with Python < 3.8 use non... | 0.382718 | 0.348507 |
import os
import unittest
import xml.etree.ElementTree as ET
from flightaware2columbus.gpx_writer import (write2xml, xml_description,
xml_root, xml_trackpoints)
class TestGPX_Writer(unittest.TestCase):
def setUp(self):
self.test_filename = 'test.gpx'
s... | flightaware2columbus/tests/test_gpx_writer.py | import os
import unittest
import xml.etree.ElementTree as ET
from flightaware2columbus.gpx_writer import (write2xml, xml_description,
xml_root, xml_trackpoints)
class TestGPX_Writer(unittest.TestCase):
def setUp(self):
self.test_filename = 'test.gpx'
s... | 0.360602 | 0.36815 |
import logging as log
from BaseCM import cm_hddcdd
from BaseCM.cm_output import validate
logging = log.getLogger("cm-hdd_cdd")
logging.setLevel(log.DEBUG)
def hdd_cdd_stats(
geo,
refyear: int = 2050,
rcp: str = "4.5",
t_base_h: float = 18.0,
t_base_c: float = 22.0,
):
"""The `hdd_cdd_stats` ... | cm/hdd_cdd/hddcdd.py | import logging as log
from BaseCM import cm_hddcdd
from BaseCM.cm_output import validate
logging = log.getLogger("cm-hdd_cdd")
logging.setLevel(log.DEBUG)
def hdd_cdd_stats(
geo,
refyear: int = 2050,
rcp: str = "4.5",
t_base_h: float = 18.0,
t_base_c: float = 22.0,
):
"""The `hdd_cdd_stats` ... | 0.662032 | 0.431824 |
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("main", "0003_auto_20211101_1734"),
]
operations = [
migrations.RemoveField(
model_name="statementofwork",
name="team_directorate",
... | main/migrations/0004_auto_20211102_0728.py |
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("main", "0003_auto_20211101_1734"),
]
operations = [
migrations.RemoveField(
model_name="statementofwork",
name="team_directorate",
... | 0.474388 | 0.157817 |
from astropy.io import fits
import OpenEXR
import os
import json
import Imath
import warnings
from .utils import __FITS_HEADERS_ID, __get_pixeltype_from_bitpix, __change_array_type, __get_channel_from_pixeltype
def convert_directory(path, compression=None, output_pixel_type=None, verbose=True):
"""
Converts di... | exrconverter/fits2exr.py | from astropy.io import fits
import OpenEXR
import os
import json
import Imath
import warnings
from .utils import __FITS_HEADERS_ID, __get_pixeltype_from_bitpix, __change_array_type, __get_channel_from_pixeltype
def convert_directory(path, compression=None, output_pixel_type=None, verbose=True):
"""
Converts di... | 0.748904 | 0.475544 |
microcode = '''
def macroop ROL_R_I
{
roli reg, reg, imm, flags=(OF,CF)
};
def macroop ROL_M_I
{
ldst t1, seg, sib, disp
roli t1, t1, imm, flags=(OF,CF)
st t1, seg, sib, disp
};
def macroop ROL_P_I
{
rdip t7
ldst t1, seg, riprel, disp
roli t1, t1, imm, flags=(OF,CF)
st t1, seg, riprel... | src/arch/x86/isa/insts/general_purpose/rotate_and_shift/rotate.py |
microcode = '''
def macroop ROL_R_I
{
roli reg, reg, imm, flags=(OF,CF)
};
def macroop ROL_M_I
{
ldst t1, seg, sib, disp
roli t1, t1, imm, flags=(OF,CF)
st t1, seg, sib, disp
};
def macroop ROL_P_I
{
rdip t7
ldst t1, seg, riprel, disp
roli t1, t1, imm, flags=(OF,CF)
st t1, seg, riprel... | 0.337094 | 0.284943 |
import pytest # noqa
import py_cui
def test_move_right(SCROLLTEXTBLOCK):
text_box = SCROLLTEXTBLOCK('Hello World')
text_box._move_right()
cursor_x, _ = text_box.get_abs_cursor_position()
text_x, _ = text_box.get_cursor_text_pos()
assert text_x == 1
assert cursor_x == 43
def test_move_left_s... | tests/test_ui_implementations/test_text_block_imp.py | import pytest # noqa
import py_cui
def test_move_right(SCROLLTEXTBLOCK):
text_box = SCROLLTEXTBLOCK('Hello World')
text_box._move_right()
cursor_x, _ = text_box.get_abs_cursor_position()
text_x, _ = text_box.get_cursor_text_pos()
assert text_x == 1
assert cursor_x == 43
def test_move_left_s... | 0.576184 | 0.326808 |
import json
import numpy as np
from abc import ABC, abstractmethod
from typing import List, Dict, Tuple
import triton_python_backend_utils as pb_utils
import triton_python_model.utils as utils
class PostDetectionModel(ABC):
def __init__(self, input_names: List[str], output_names: List[str]) -> None:
"""Co... | triton_python_model/task/detection.py | import json
import numpy as np
from abc import ABC, abstractmethod
from typing import List, Dict, Tuple
import triton_python_backend_utils as pb_utils
import triton_python_model.utils as utils
class PostDetectionModel(ABC):
def __init__(self, input_names: List[str], output_names: List[str]) -> None:
"""Co... | 0.870583 | 0.525734 |
from third_party.json_schema_compiler.memoize import memoize
class HostFileSystemIterator(object):
'''Provides methods for iterating through host file systems, in both
ascending (oldest to newest version) and descending order.
'''
def __init__(self, file_system_creator, host_file_system, branch_utility):
... | chrome/common/extensions/docs/server2/host_file_system_iterator.py |
from third_party.json_schema_compiler.memoize import memoize
class HostFileSystemIterator(object):
'''Provides methods for iterating through host file systems, in both
ascending (oldest to newest version) and descending order.
'''
def __init__(self, file_system_creator, host_file_system, branch_utility):
... | 0.451327 | 0.228114 |
import pandas as pd
import pytest
from sklearn.exceptions import NotFittedError
from feature_engine.selection import DropConstantFeatures
def test_drop_constant_features(df_constant_features):
transformer = DropConstantFeatures(tol=1, variables=None)
X = transformer.fit_transform(df_constant_features)
# ... | tests/test_selection/test_drop_constant_features.py | import pandas as pd
import pytest
from sklearn.exceptions import NotFittedError
from feature_engine.selection import DropConstantFeatures
def test_drop_constant_features(df_constant_features):
transformer = DropConstantFeatures(tol=1, variables=None)
X = transformer.fit_transform(df_constant_features)
# ... | 0.811265 | 0.681029 |
import time
import sys
sys.path.append("..")
import os
import pygame
import rospy
from umnitsa_msgs.msg import Joystick
from geometry_msgs.msg import Twist
import numpy as np
from subprocess import call
class JoystickPublisher():
def __init__(self):
# initialize axes from parameter file
self.LTOGRIGHT = rospy.get... | src/umnitsa_joystick/src/joystick.py | import time
import sys
sys.path.append("..")
import os
import pygame
import rospy
from umnitsa_msgs.msg import Joystick
from geometry_msgs.msg import Twist
import numpy as np
from subprocess import call
class JoystickPublisher():
def __init__(self):
# initialize axes from parameter file
self.LTOGRIGHT = rospy.get... | 0.108602 | 0.07836 |
import gym
import hydra
from omegaconf import DictConfig
from rlcycle.common.abstract.action_selector import ActionSelector
from rlcycle.common.abstract.learner import LearnerBase
from rlcycle.common.abstract.loss import Loss
from rlcycle.common.models.base import BaseModel
from rlcycle.common.utils.env_generator impo... | rlcycle/build.py | import gym
import hydra
from omegaconf import DictConfig
from rlcycle.common.abstract.action_selector import ActionSelector
from rlcycle.common.abstract.learner import LearnerBase
from rlcycle.common.abstract.loss import Loss
from rlcycle.common.models.base import BaseModel
from rlcycle.common.utils.env_generator impo... | 0.641984 | 0.153771 |
from mpmath import mp
from .helpers import _s3, _s21, _s111
from ..helpers import untangle
# TODO modernize
class ZhangCuiLiu(object):
"""
<NAME>, <NAME> and <NAME>,
A set of symmetric quadrature rules on triangles and tetrahedra,
Journal of Computational Mathematics
Vol. 27, No. 1 (January 2009)... | quadpy/triangle/zhang_cui_liu.py | from mpmath import mp
from .helpers import _s3, _s21, _s111
from ..helpers import untangle
# TODO modernize
class ZhangCuiLiu(object):
"""
<NAME>, <NAME> and <NAME>,
A set of symmetric quadrature rules on triangles and tetrahedra,
Journal of Computational Mathematics
Vol. 27, No. 1 (January 2009)... | 0.311951 | 0.372334 |
# File generated according to WMatSelect.ui
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_WMatSelect(object):
def setupUi(self, WMatSelect):
WMatSelect.setObjectName("WMatSelect")
WMatSelect.resize(283, 30)
sizePolicy = QtWidge... | pyleecan/GUI/Dialog/DMatLib/WMatSelect/Ui_WMatSelect.py |
# File generated according to WMatSelect.ui
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_WMatSelect(object):
def setupUi(self, WMatSelect):
WMatSelect.setObjectName("WMatSelect")
WMatSelect.resize(283, 30)
sizePolicy = QtWidge... | 0.357343 | 0.063106 |
__all__ = ['Inception', 'FIDMetric']
# Cell
from scipy import linalg
import torch
from torchvision.models.utils import load_state_dict_from_url
from fastprogress.fastprogress import master_bar, progress_bar
from fastai.data.external import untar_data
from fastai.data.transforms import get_image_files
from fastai.data... | fastpapers/heusel2017gans.py |
__all__ = ['Inception', 'FIDMetric']
# Cell
from scipy import linalg
import torch
from torchvision.models.utils import load_state_dict_from_url
from fastprogress.fastprogress import master_bar, progress_bar
from fastai.data.external import untar_data
from fastai.data.transforms import get_image_files
from fastai.data... | 0.773601 | 0.38659 |
from datetime import datetime
from unittest import TestCase
from eocdb.core.db.db_submission import DbSubmission
from eocdb.core.models import DatasetValidationResult, Issue, QC_STATUS_SUBMITTED, QC_STATUS_VALIDATED
from eocdb.core.models.submission_file import SubmissionFile
class DbSubmissionTest(TestCase):
d... | tests/core/db/test_db_submission.py | from datetime import datetime
from unittest import TestCase
from eocdb.core.db.db_submission import DbSubmission
from eocdb.core.models import DatasetValidationResult, Issue, QC_STATUS_SUBMITTED, QC_STATUS_VALIDATED
from eocdb.core.models.submission_file import SubmissionFile
class DbSubmissionTest(TestCase):
d... | 0.426441 | 0.171027 |
from enum import Enum
from collections import namedtuple
ROOT_URL: str = "https://slack.com/api/"
HOOK_URL: str = "https://hooks.slack.com"
method = namedtuple("method", ("url", "itermode", "iterkey", "as_json"))
class Methods(Enum):
"""
Enumeration of available slack methods.
Provides `iterkey` and `it... | slack/methods.py | from enum import Enum
from collections import namedtuple
ROOT_URL: str = "https://slack.com/api/"
HOOK_URL: str = "https://hooks.slack.com"
method = namedtuple("method", ("url", "itermode", "iterkey", "as_json"))
class Methods(Enum):
"""
Enumeration of available slack methods.
Provides `iterkey` and `it... | 0.664323 | 0.195057 |
from tqdm import tqdm
import fsspec
import os
from joblib import Parallel, delayed, cpu_count
from zipfile import ZipFile
from lost_ds.functional.mapping import remap_img_path
from lost_ds.util import get_fs
def copy_imgs(df, out_dir, col='img_path', force_overwrite=False,
filesystem=None):
'''Cop... | lost_ds/copy.py | from tqdm import tqdm
import fsspec
import os
from joblib import Parallel, delayed, cpu_count
from zipfile import ZipFile
from lost_ds.functional.mapping import remap_img_path
from lost_ds.util import get_fs
def copy_imgs(df, out_dir, col='img_path', force_overwrite=False,
filesystem=None):
'''Cop... | 0.409575 | 0.189465 |
__author__ = 'rramchandani'
from pyVmomi import vim
from pyVirtualize.utils.exceptions import TimeOutException, ProgramNotExecuted
from ._base import BaseOperation
class ProcessOperations(BaseOperation):
"""
ProcessOperations provides APIs to manipulate the guest operating system processes.
"""
def... | src/pyVirtualize/pyvSphere/vm/operation/process.py | __author__ = 'rramchandani'
from pyVmomi import vim
from pyVirtualize.utils.exceptions import TimeOutException, ProgramNotExecuted
from ._base import BaseOperation
class ProcessOperations(BaseOperation):
"""
ProcessOperations provides APIs to manipulate the guest operating system processes.
"""
def... | 0.645455 | 0.252339 |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
... | vendas/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 = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
... | 0.543348 | 0.162214 |
import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from IPython.display import display, Markdown, HTML
def ambiguous_examples_analysis(workspace_pd, lang_util, threshold=0.7):
"""
Analyze the test workspace and find out similar utterances that belongs to differ... | assistant_dialog_skill_analysis/data_analysis/similarity_analyzer.py | import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from IPython.display import display, Markdown, HTML
def ambiguous_examples_analysis(workspace_pd, lang_util, threshold=0.7):
"""
Analyze the test workspace and find out similar utterances that belongs to differ... | 0.623033 | 0.641829 |
"""Sequana class to plot a CanvasJS linegraph from an embedded csv file.
"""
from sequana import logger
from sequana.plots.canvasjs_base import CanvasJS
class CanvasJSLineGraph(CanvasJS):
""" Class to create a CanvasJS linegraphe for an HTML page. It creates a
hidden pre section with your CSV. It is necessary... | sequana/plots/canvasjs_linegraph.py | """Sequana class to plot a CanvasJS linegraph from an embedded csv file.
"""
from sequana import logger
from sequana.plots.canvasjs_base import CanvasJS
class CanvasJSLineGraph(CanvasJS):
""" Class to create a CanvasJS linegraphe for an HTML page. It creates a
hidden pre section with your CSV. It is necessary... | 0.812012 | 0.339171 |