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 cooka.core.analyzer import PandasAnalyzer
from cooka.common.model import TrainJobConf, FrameworkType, ExperimentConf, TrainValidationHoldout
from cooka.common.model import TaskType, SampleConf
from hypernets.core.searcher import OptimizeDirection
class TestTrainJob:
def _make_train_job_conf(self, framework)... | cooka/test/run_test_train_job.py | from cooka.core.analyzer import PandasAnalyzer
from cooka.common.model import TrainJobConf, FrameworkType, ExperimentConf, TrainValidationHoldout
from cooka.common.model import TaskType, SampleConf
from hypernets.core.searcher import OptimizeDirection
class TestTrainJob:
def _make_train_job_conf(self, framework)... | 0.780913 | 0.354824 |
"""Public section, including homepage and signup."""
from flask import (
Blueprint,
current_app,
flash,
redirect,
render_template,
request,
url_for,
render_template_string
)
from flask_login import login_required, login_user, logout_user, current_user
from CarRentBlockChain.extensions i... | CarRentBlockChain/blueprints/public/public.py | """Public section, including homepage and signup."""
from flask import (
Blueprint,
current_app,
flash,
redirect,
render_template,
request,
url_for,
render_template_string
)
from flask_login import login_required, login_user, logout_user, current_user
from CarRentBlockChain.extensions i... | 0.411466 | 0.125333 |
from setup import *
import asm
p.iodev_set_usage(IODEV.FB, 0)
code_len = 12 * 16 * 8 + 4
data_len = 8 * 16 * 8
code_buffer = p.malloc(code_len)
data_buffer = p.malloc(data_len)
template = asm.ARMAsm("""
mov x2, x0
mrs x2, s3_0_c0_c0_0
str x2, [x1], #8
ret
""", code_buffer)
mov, mrs, st, ret = struc... | proxyclient/find_sprr_regs.py | from setup import *
import asm
p.iodev_set_usage(IODEV.FB, 0)
code_len = 12 * 16 * 8 + 4
data_len = 8 * 16 * 8
code_buffer = p.malloc(code_len)
data_buffer = p.malloc(data_len)
template = asm.ARMAsm("""
mov x2, x0
mrs x2, s3_0_c0_c0_0
str x2, [x1], #8
ret
""", code_buffer)
mov, mrs, st, ret = struc... | 0.161023 | 0.131173 |
import tensorflow as tf
import argparse
import numpy as np
input_size = (1, 1, 1, 1)
weight_size = (1, 1, 1, 1)
stride = 1 # default
padding = 0 # default
dilation = 1 # default
groups = 1 # default
input_filename = 'input.dat'
weight_filename = 'weight.dat'
output_filename = 'output.dat'
output_std_filename ... | src/Test/dat/conv_test/checker_tf.py | import tensorflow as tf
import argparse
import numpy as np
input_size = (1, 1, 1, 1)
weight_size = (1, 1, 1, 1)
stride = 1 # default
padding = 0 # default
dilation = 1 # default
groups = 1 # default
input_filename = 'input.dat'
weight_filename = 'weight.dat'
output_filename = 'output.dat'
output_std_filename ... | 0.41561 | 0.225875 |
from celery import task
from django.core.cache import cache
import urllib
import json
from models import Alliance, Corporation, NewsFeed
from API import cache_handler as handler
import eveapi
import feedparser
@task()
def update_alliance(allianceID):
"""
Updates an alliance and it's corporations from the API.
... | evewspace/core/tasks.py | from celery import task
from django.core.cache import cache
import urllib
import json
from models import Alliance, Corporation, NewsFeed
from API import cache_handler as handler
import eveapi
import feedparser
@task()
def update_alliance(allianceID):
"""
Updates an alliance and it's corporations from the API.
... | 0.285472 | 0.07221 |
import logging
from consulate.models import acl as model
from consulate.api import base
from consulate import exceptions
LOGGER = logging.getLogger(__name__)
class ACL(base.Endpoint):
"""The ACL endpoints are used to create, update, destroy, and query ACL
tokens.
"""
def bootstrap(self):
""... | consulate/api/acl.py | import logging
from consulate.models import acl as model
from consulate.api import base
from consulate import exceptions
LOGGER = logging.getLogger(__name__)
class ACL(base.Endpoint):
"""The ACL endpoints are used to create, update, destroy, and query ACL
tokens.
"""
def bootstrap(self):
""... | 0.817866 | 0.52275 |
from django import forms
from django.conf import settings
from django.contrib.auth import authenticate
from django.utils.translation import ugettext_lazy as _
from .models import LoginCode
from .utils import get_username_field
class AuthenticationForm(forms.Form):
"""
Base class for authenticating users. Ext... | nopassword/forms.py | from django import forms
from django.conf import settings
from django.contrib.auth import authenticate
from django.utils.translation import ugettext_lazy as _
from .models import LoginCode
from .utils import get_username_field
class AuthenticationForm(forms.Form):
"""
Base class for authenticating users. Ext... | 0.469763 | 0.060808 |
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import Qt, QSize, pyqtSignal, pyqtSlot
from PyQt5.QtCore import pyqtSignal
class SpeedButton(QPushButton):
indexclick = pyqtSignal(int)
def __init__(self, label, parent, index):
super(SpeedButton, self).__init__(label, parent)
s... | src/manualmovement.py | from PyQt5.QtWidgets import *
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import Qt, QSize, pyqtSignal, pyqtSlot
from PyQt5.QtCore import pyqtSignal
class SpeedButton(QPushButton):
indexclick = pyqtSignal(int)
def __init__(self, label, parent, index):
super(SpeedButton, self).__init__(label, parent)
s... | 0.165526 | 0.165357 |
import pygame
import sys
import time
import thread
import stream_server
import easygopigo3 as easy
class JoyStatus:
def __init__(self):
self.direction = (0, 0)
self.accelerate = False
self.bark = False
def control_gopigo(robot, joystatus):
moving = False
prev_speed = robot.get_spe... | joystick.py | import pygame
import sys
import time
import thread
import stream_server
import easygopigo3 as easy
class JoyStatus:
def __init__(self):
self.direction = (0, 0)
self.accelerate = False
self.bark = False
def control_gopigo(robot, joystatus):
moving = False
prev_speed = robot.get_spe... | 0.150153 | 0.13243 |
import numpy as np
from GMMModel import GMMModel
import os
import sys
class iVector(object):
"""
| iVector extractor
|
|
| config : a dictionary of config parameters
|
+--------------+------------------------------------------------------+
| tv_matrix | filename for tot... | pyslgr/iVector.py |
import numpy as np
from GMMModel import GMMModel
import os
import sys
class iVector(object):
"""
| iVector extractor
|
|
| config : a dictionary of config parameters
|
+--------------+------------------------------------------------------+
| tv_matrix | filename for tot... | 0.535584 | 0.388502 |
import logging
from exchangemanager import ExchangeManager
from bittrex import Bittrex
from result import Result
from order import Order
class BittrexManager(ExchangeManager):
def __init__(self, config = {} ):
ExchangeManager.__init__(self, "BTRX", config )
self.api = Bittrex()
self.balanc... | libs/exchanges/bittrexmanager.py | import logging
from exchangemanager import ExchangeManager
from bittrex import Bittrex
from result import Result
from order import Order
class BittrexManager(ExchangeManager):
def __init__(self, config = {} ):
ExchangeManager.__init__(self, "BTRX", config )
self.api = Bittrex()
self.balanc... | 0.227469 | 0.11204 |
import numpy as np
from pathlib import Path
class Experiment_Information:
def __init__(self, name, path, parameters, modulation):
'''
name: str
path: str
parameters: dict
'''
self.name = name
self.path = path
self.parameters = parameters
self.... | NorthNet/Classes/data_classes.py | import numpy as np
from pathlib import Path
class Experiment_Information:
def __init__(self, name, path, parameters, modulation):
'''
name: str
path: str
parameters: dict
'''
self.name = name
self.path = path
self.parameters = parameters
self.... | 0.594787 | 0.282345 |
from abc import ABC, abstractmethod
from torch.optim import SGD, Adam, AdamW
from torch.nn.utils import clip_grad_norm_
import numpy as np
from ..buffers import ReplayBuffer
from ..config.configuration import LocalConfig
from ..networks.actors import FCActorDiscrete, FCActorContinuous
from ..networks.critics import F... | bistrain/base/core.py | from abc import ABC, abstractmethod
from torch.optim import SGD, Adam, AdamW
from torch.nn.utils import clip_grad_norm_
import numpy as np
from ..buffers import ReplayBuffer
from ..config.configuration import LocalConfig
from ..networks.actors import FCActorDiscrete, FCActorContinuous
from ..networks.critics import F... | 0.716219 | 0.133528 |
from __future__ import annotations
from dataclasses import InitVar, dataclass, field
from typing import Optional, Union
from ...public import ecc
from .math import invert
# Notation follows https://tools.ietf.org/html/rfc6979
@dataclass
class Curve:
"""
$y^2 = x^3 + ax + b (mod p)
"""
curve_id: ec... | cryptokey/backend/textbook/ecc.py | from __future__ import annotations
from dataclasses import InitVar, dataclass, field
from typing import Optional, Union
from ...public import ecc
from .math import invert
# Notation follows https://tools.ietf.org/html/rfc6979
@dataclass
class Curve:
"""
$y^2 = x^3 + ax + b (mod p)
"""
curve_id: ec... | 0.912006 | 0.431464 |
from copy import deepcopy
from causallearn.graph.Edge import Edge
from causallearn.graph.Endpoint import Endpoint
def meek(cg, background_knowledge=None):
'''
Run Meek rules
Parameters
----------
cg : a CausalGraph object. Where cg.G.graph[j,i]=1 and cg.G.graph[i,j]=-1 indicates i --> j ,
... | causallearn/utils/PCUtils/Meek.py | from copy import deepcopy
from causallearn.graph.Edge import Edge
from causallearn.graph.Endpoint import Endpoint
def meek(cg, background_knowledge=None):
'''
Run Meek rules
Parameters
----------
cg : a CausalGraph object. Where cg.G.graph[j,i]=1 and cg.G.graph[i,j]=-1 indicates i --> j ,
... | 0.562777 | 0.280192 |
from pathlib import Path
from typing import Optional
from conan_app_launcher import ICON_SIZE
from PyQt5.QtCore import pyqtSignal, QSize, Qt
from PyQt5.QtWidgets import QPushButton, QGraphicsColorizeEffect, QGraphicsPixmapItem
from PyQt5.QtGui import QColor, QIcon, QPixmap
class ClickableIcon(QPushButton):
"""
... | src/conan_app_launcher/ui/widgets/clickable_icon.py |
from pathlib import Path
from typing import Optional
from conan_app_launcher import ICON_SIZE
from PyQt5.QtCore import pyqtSignal, QSize, Qt
from PyQt5.QtWidgets import QPushButton, QGraphicsColorizeEffect, QGraphicsPixmapItem
from PyQt5.QtGui import QColor, QIcon, QPixmap
class ClickableIcon(QPushButton):
"""
... | 0.828141 | 0.193204 |
import sys
try:
from PIL import Image
except:
if __name__ == "__main__":
puts("This program requires python3 PIL library, please pip3 install PIL")
sys.exit(0)
else:
pass
import os
import shutil
import pickle
import numpy as np
BASE_DIR = os.path.split(os.path.realpath(__file__))[0... | Convert.py |
import sys
try:
from PIL import Image
except:
if __name__ == "__main__":
puts("This program requires python3 PIL library, please pip3 install PIL")
sys.exit(0)
else:
pass
import os
import shutil
import pickle
import numpy as np
BASE_DIR = os.path.split(os.path.realpath(__file__))[0... | 0.160463 | 0.165155 |
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_databas... | src/vald/v1/vald/object_pb2.py | """Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_databas... | 0.280222 | 0.097993 |
from __future__ import division
import logging
import math
import numpy as np
class GaussianPlugInClassifier(object):
def __init__(self, X, Y, num_classes=2):
self.X = X
self.Y = Y
self.num_classes = num_classes
self.logger = logging.getLogger(__name__)
# Function that te... | ml_lib/gaussian_plugin_classifier.py | from __future__ import division
import logging
import math
import numpy as np
class GaussianPlugInClassifier(object):
def __init__(self, X, Y, num_classes=2):
self.X = X
self.Y = Y
self.num_classes = num_classes
self.logger = logging.getLogger(__name__)
# Function that te... | 0.382257 | 0.366335 |
import pandas as pd
from PySide6.QtGui import QIcon, Qt
from PySide6.QtCore import QThread
from PySide6.QtWidgets import QProgressBar, QDialog, QHeaderView, QTableWidgetItem
from gms_uploader.ui.uploader_dialog import Ui_Dialog as UI_Dialog_Uploader
from gms_uploader.modules.upload.support_classes import ParamikoFileUp... | gms_uploader/modules/upload/uploader.py | import pandas as pd
from PySide6.QtGui import QIcon, Qt
from PySide6.QtCore import QThread
from PySide6.QtWidgets import QProgressBar, QDialog, QHeaderView, QTableWidgetItem
from gms_uploader.ui.uploader_dialog import Ui_Dialog as UI_Dialog_Uploader
from gms_uploader.modules.upload.support_classes import ParamikoFileUp... | 0.370909 | 0.077378 |
import mock
import six
from senlin.api.middleware import fault
from senlin.api.openstack.v1 import actions
from senlin.common import exception as senlin_exc
from senlin.common import policy
from senlin.rpc import client as rpc_client
from senlin.tests.apiv1 import shared
from senlin.tests.common import base
@mock.p... | senlin/tests/apiv1/test_actions.py |
import mock
import six
from senlin.api.middleware import fault
from senlin.api.openstack.v1 import actions
from senlin.common import exception as senlin_exc
from senlin.common import policy
from senlin.rpc import client as rpc_client
from senlin.tests.apiv1 import shared
from senlin.tests.common import base
@mock.p... | 0.576184 | 0.197619 |
# Disclaimer!
# This code is not an optimal HTTP reverse shell!
# It is created to introduce as many aspects of 'covertutils' as possible.
# There are muuuuuch better ways to implement a reverse HTTP shell using this package,
# using many Python helpers like SimpleHTTPServer.
# In this file the HTTP requests/respo... | covertutils/examples/http_reverse_agent.py |
# Disclaimer!
# This code is not an optimal HTTP reverse shell!
# It is created to introduce as many aspects of 'covertutils' as possible.
# There are muuuuuch better ways to implement a reverse HTTP shell using this package,
# using many Python helpers like SimpleHTTPServer.
# In this file the HTTP requests/respo... | 0.33546 | 0.106365 |
from decimal import Decimal
from datetime import datetime
from mockdatagen.helpers import MockGen
from money.models import CurrencyData, Denomination, VAT, VATPeriod, AccountingGroup
@MockGen.register
class CurrencyDataGen:
model = CurrencyData
@staticmethod
def func():
CurrencyData.objects.get_... | backend/mockdatagen/mocks/money.py | from decimal import Decimal
from datetime import datetime
from mockdatagen.helpers import MockGen
from money.models import CurrencyData, Denomination, VAT, VATPeriod, AccountingGroup
@MockGen.register
class CurrencyDataGen:
model = CurrencyData
@staticmethod
def func():
CurrencyData.objects.get_... | 0.733261 | 0.219798 |
import logging
import io
import resource
import gc
import os
import random
import tempfile
import objgraph
from . import config
LOGGER = logging.getLogger(__name__)
debugs = []
def register_debug(cref):
'''
Register a function to be called for a memory summary
'''
debugs.append(cref)
def _in_mil... | cocrawler/memory.py | import logging
import io
import resource
import gc
import os
import random
import tempfile
import objgraph
from . import config
LOGGER = logging.getLogger(__name__)
debugs = []
def register_debug(cref):
'''
Register a function to be called for a memory summary
'''
debugs.append(cref)
def _in_mil... | 0.266357 | 0.081374 |
import logging
from google.protobuf.json_format import MessageToDict
from spaceone.core import pygrpc
from spaceone.core.connector import BaseConnector
from spaceone.core.utils import parse_endpoint
from spaceone.identity.error.error_authentication import *
_LOGGER = logging.getLogger(__name__)
class AuthPluginCon... | src/spaceone/identity/connector/auth_plugin_connector.py | import logging
from google.protobuf.json_format import MessageToDict
from spaceone.core import pygrpc
from spaceone.core.connector import BaseConnector
from spaceone.core.utils import parse_endpoint
from spaceone.identity.error.error_authentication import *
_LOGGER = logging.getLogger(__name__)
class AuthPluginCon... | 0.18717 | 0.057758 |
import os, shlex, glob
import random
from typing import List, Dict, Optional
from collections import namedtuple
from functools import partial
import tensorflow as tf
from bs4 import BeautifulSoup
from .tokenize_components import get_model_inputs
from ..params import config
from ..globals import stable_config
from .co... | src/cmv_modes/__init__.py | import os, shlex, glob
import random
from typing import List, Dict, Optional
from collections import namedtuple
from functools import partial
import tensorflow as tf
from bs4 import BeautifulSoup
from .tokenize_components import get_model_inputs
from ..params import config
from ..globals import stable_config
from .co... | 0.746786 | 0.253318 |
import discord
import logging
from . import values
from discord.ext import commands
from .cogs.commands import CommandsCog
from .utils import maybe_mention, ping_devs, EmojiURLs
logger = logging.getLogger(__name__)
class HelpCommand(commands.HelpCommand):
num_of_commands = len(CommandsCog().get_commands()) + 1
... | bdaybot/help.py | import discord
import logging
from . import values
from discord.ext import commands
from .cogs.commands import CommandsCog
from .utils import maybe_mention, ping_devs, EmojiURLs
logger = logging.getLogger(__name__)
class HelpCommand(commands.HelpCommand):
num_of_commands = len(CommandsCog().get_commands()) + 1
... | 0.301568 | 0.24854 |
import json
import numpy as np
import logging
logger = logging.getLogger(__name__)
class DirichletDist():
def __init__(self, config, **kwargs):
n_classes = config.n_classes
prior_alpha = np.zeros((n_classes, n_classes))
if config.worker.prior.type == 'predefined_homegeneous' or len(kwarg... | online_label/optimizer/utils.py | import json
import numpy as np
import logging
logger = logging.getLogger(__name__)
class DirichletDist():
def __init__(self, config, **kwargs):
n_classes = config.n_classes
prior_alpha = np.zeros((n_classes, n_classes))
if config.worker.prior.type == 'predefined_homegeneous' or len(kwarg... | 0.619701 | 0.197754 |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import make_moons, make_circles, make_classification, make_hastie_10_2
from sklearn.neural_network import MLPClassifier
from... | examples/sklearn.py |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import make_moons, make_circles, make_classification, make_hastie_10_2
from sklearn.neural_network import MLPClassifier
from... | 0.49585 | 0.391988 |
# Copyright notice:
# Copyright Members of the EMI Collaboration, 2013.
#
# See www.eu-emi.eu for details on the copyright holders
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License... | src/fts3rest/generate-api-doc.py |
# Copyright notice:
# Copyright Members of the EMI Collaboration, 2013.
#
# See www.eu-emi.eu for details on the copyright holders
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License... | 0.527317 | 0.14448 |
import sys
from celo_sdk.contracts.base_wrapper import BaseWrapper
from celo_sdk.registry import Registry
from web3 import Web3
class DowntimeSlasher(BaseWrapper):
"""
Contract handling slashing for Validator downtime using intervals
Attributes:
web3: Web3
Web3 object
regist... | celo_sdk/contracts/DowntimeSlasherWrapper.py | import sys
from celo_sdk.contracts.base_wrapper import BaseWrapper
from celo_sdk.registry import Registry
from web3 import Web3
class DowntimeSlasher(BaseWrapper):
"""
Contract handling slashing for Validator downtime using intervals
Attributes:
web3: Web3
Web3 object
regist... | 0.817283 | 0.34679 |
import re
import yaml
from quick_scheme import KeyBasedList
from quick_scheme import ListOfReferences, ListOfNodes
from quick_scheme import SchemeNode, Field
from quick_scheme import qs_yaml
DATA = '''
version: 1
updates:
# this is our update log to demonstrate lists
- '2019-08-14: initial version'
- '2019-... | examples/basic.py |
import re
import yaml
from quick_scheme import KeyBasedList
from quick_scheme import ListOfReferences, ListOfNodes
from quick_scheme import SchemeNode, Field
from quick_scheme import qs_yaml
DATA = '''
version: 1
updates:
# this is our update log to demonstrate lists
- '2019-08-14: initial version'
- '2019-... | 0.578091 | 0.311244 |
"""Test classes for translator_svc"""
import unittest
import uuid
import time
import futurist
from mock import patch
from mock import PropertyMock
from conductor.controller.translator_svc import TranslatorService
from conductor.common.models import plan
from conductor.common.music import api
from conductor.common.mus... | conductor/conductor/tests/unit/controller/test_translator_svc.py | """Test classes for translator_svc"""
import unittest
import uuid
import time
import futurist
from mock import patch
from mock import PropertyMock
from conductor.controller.translator_svc import TranslatorService
from conductor.common.models import plan
from conductor.common.music import api
from conductor.common.mus... | 0.316158 | 0.116387 |
from __future__ import absolute_import, division, print_function
import numpy as np
import nibabel as nib
import os
import sys
from numpy.testing import assert_array_almost_equal
from numpy.testing import assert_almost_equal
from nose.tools import assert_equals
sys.path.append(os.path.join(os.path.dirname(__file__), ... | code/utils/tests/test_mask_phase_2.py | from __future__ import absolute_import, division, print_function
import numpy as np
import nibabel as nib
import os
import sys
from numpy.testing import assert_array_almost_equal
from numpy.testing import assert_almost_equal
from nose.tools import assert_equals
sys.path.append(os.path.join(os.path.dirname(__file__), ... | 0.268366 | 0.376967 |
import numpy as np
def clipit(data, low, high, method, center):
"""Clips data in the current segment"""
# For the center point, take the median (if center_code==0), else the mean
if center == 'mad':
mid = np.nanmedian(data)
else:
mid = np.nanmean(data)
data = np.nan_to_num(data)
... | wotan/slide_clipper.py | import numpy as np
def clipit(data, low, high, method, center):
"""Clips data in the current segment"""
# For the center point, take the median (if center_code==0), else the mean
if center == 'mad':
mid = np.nanmedian(data)
else:
mid = np.nanmean(data)
data = np.nan_to_num(data)
... | 0.714528 | 0.664568 |
import sys
import os
from decimal import Decimal
import unittest
from datetime import datetime
import pytz
from dateutil.relativedelta import relativedelta
import magento
from mock import patch, MagicMock
import trytond.tests.test_tryton
from trytond.transaction import Transaction
from trytond.tests.test_tryton impor... | tests/test_sale.py | import sys
import os
from decimal import Decimal
import unittest
from datetime import datetime
import pytz
from dateutil.relativedelta import relativedelta
import magento
from mock import patch, MagicMock
import trytond.tests.test_tryton
from trytond.transaction import Transaction
from trytond.tests.test_tryton impor... | 0.374104 | 0.175768 |
import warnings, datetime, uuid, os, json, shutil, pickle
warnings.filterwarnings('ignore')
from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score, mean_squared_error
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import ExtraTreesRegressor
from skl... | training/train_btb.py | import warnings, datetime, uuid, os, json, shutil, pickle
warnings.filterwarnings('ignore')
from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score, mean_squared_error
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import ExtraTreesRegressor
from skl... | 0.456168 | 0.182498 |
import sys
import os
import subprocess
import config
import tempfile
import shutil
TAG = sys.argv[0]
# [fb] |j:s -> :j|s # bring semivowel j close to the left vowel rather than
# close to the consonant s
MAPPINGS = {'~|m:': '~:m|', '~|n:': '~:n|', ':d|Z': '|d:Z', 'd|Z:': 'd:Z|'}
# https://note.... | explogs/20_bracis_kaldi/g2p_map/news2m2m.py |
import sys
import os
import subprocess
import config
import tempfile
import shutil
TAG = sys.argv[0]
# [fb] |j:s -> :j|s # bring semivowel j close to the left vowel rather than
# close to the consonant s
MAPPINGS = {'~|m:': '~:m|', '~|n:': '~:n|', ':d|Z': '|d:Z', 'd|Z:': 'd:Z|'}
# https://note.... | 0.183813 | 0.15511 |
__author__ = "Sh-Zh-7"
__copyright__ = "Copyright (C) 2019 Sh-Zh-7"
__license__ = "MIT"
__email__ = "<EMAIL>"
import os
import json
import time
import getpass
import requests
import argparse
import warnings
from bs4 import BeautifulSoup as bs
# 禁止任何报错
warnings.filterwarnings("ignore")
# 禁止TF打印任何日志信息
os.environ['TF_CP... | spider.py | __author__ = "Sh-Zh-7"
__copyright__ = "Copyright (C) 2019 Sh-Zh-7"
__license__ = "MIT"
__email__ = "<EMAIL>"
import os
import json
import time
import getpass
import requests
import argparse
import warnings
from bs4 import BeautifulSoup as bs
# 禁止任何报错
warnings.filterwarnings("ignore")
# 禁止TF打印任何日志信息
os.environ['TF_CP... | 0.189221 | 0.106737 |
import sys
import os
sys.path.append('/home/koerstz/git/tQMC/QMC')
from qmconf import QMConf
def compare_lists(a, b):
for pair in zip(a,b):
if pair[0] != pair[1]:
return False
return True
def test_qmconf():
""" """
test_dir = os.path.dirname(os.path.realpath(__file__)) + '/data/f... | tests/test_qmconf.py | import sys
import os
sys.path.append('/home/koerstz/git/tQMC/QMC')
from qmconf import QMConf
def compare_lists(a, b):
for pair in zip(a,b):
if pair[0] != pair[1]:
return False
return True
def test_qmconf():
""" """
test_dir = os.path.dirname(os.path.realpath(__file__)) + '/data/f... | 0.273963 | 0.365428 |
import httplib, urllib, base64, zlib, re, optparse
class Market:
LOGIN_HOST = "www.google.com"
LOGIN_PAGE = "/accounts/ClientLogin"
LOGIN_SERVICE = "androidsecure"
LOGIN_TYPE = "HOSTED_OR_GOOGLE"
API_HOST = "android.clients.google.com"
API_PAGE = "/market/api/ApiRequest"
def __init_... | gplay-downloader.py | import httplib, urllib, base64, zlib, re, optparse
class Market:
LOGIN_HOST = "www.google.com"
LOGIN_PAGE = "/accounts/ClientLogin"
LOGIN_SERVICE = "androidsecure"
LOGIN_TYPE = "HOSTED_OR_GOOGLE"
API_HOST = "android.clients.google.com"
API_PAGE = "/market/api/ApiRequest"
def __init_... | 0.270866 | 0.119665 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from scipy.spatial.transform import Rotation as R
from scipy.spatial.transform import Slerp
from airobot.utils import common
class Position:
"""
Class for representing 3D positions... | airobot/utils/transform_util.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from scipy.spatial.transform import Rotation as R
from scipy.spatial.transform import Slerp
from airobot.utils import common
class Position:
"""
Class for representing 3D positions... | 0.96348 | 0.550607 |
import sys
import traceback
import dbutils
import gitutils
import mailutils
import reviewing.utils
import reviewing.filters
import reviewing.mail
import reviewing.comment
import reviewing.comment.propagate
from textutils import json_encode, json_decode
db = None
def init():
global db
db = dbutils.Database... | src/cli.py |
import sys
import traceback
import dbutils
import gitutils
import mailutils
import reviewing.utils
import reviewing.filters
import reviewing.mail
import reviewing.comment
import reviewing.comment.propagate
from textutils import json_encode, json_decode
db = None
def init():
global db
db = dbutils.Database... | 0.201971 | 0.095814 |
import math
import os
import re
from collections import OrderedDict
from datetime import datetime, timedelta
from passlib.hash import bcrypt_sha256
from pony.orm import commit # NOQA
from pony.orm import (
Database,
Optional,
Required,
Set,
avg,
count,
db_session,
get,
select,
... | trivia/models.py | import math
import os
import re
from collections import OrderedDict
from datetime import datetime, timedelta
from passlib.hash import bcrypt_sha256
from pony.orm import commit # NOQA
from pony.orm import (
Database,
Optional,
Required,
Set,
avg,
count,
db_session,
get,
select,
... | 0.40592 | 0.240084 |
del_items(0x80079AEC)
SetType(0x80079AEC, "int GetTpY__FUs(unsigned short tpage)")
del_items(0x80079B08)
SetType(0x80079B08, "int GetTpX__FUs(unsigned short tpage)")
del_items(0x80079B14)
SetType(0x80079B14, "void Remove96__Fv()")
del_items(0x80079B4C)
SetType(0x80079B4C, "void AppMain()")
del_items(0x80079BF4)
SetType... | psx/_dump_/10/_dump_ida_/set_funcs.py | del_items(0x80079AEC)
SetType(0x80079AEC, "int GetTpY__FUs(unsigned short tpage)")
del_items(0x80079B08)
SetType(0x80079B08, "int GetTpX__FUs(unsigned short tpage)")
del_items(0x80079B14)
SetType(0x80079B14, "void Remove96__Fv()")
del_items(0x80079B4C)
SetType(0x80079B4C, "void AppMain()")
del_items(0x80079BF4)
SetType... | 0.242744 | 0.105165 |
import csv
import time
import cv2
import numpy as np
import torch
from tqdm import tqdm
def load_classes(csv_reader):
"""
Load classes from csv.
:param csv_reader: csv
:return:
"""
result = {}
for line, row in enumerate(csv_reader):
line += 1
try:
class_name... | precompute_dataset.py | import csv
import time
import cv2
import numpy as np
import torch
from tqdm import tqdm
def load_classes(csv_reader):
"""
Load classes from csv.
:param csv_reader: csv
:return:
"""
result = {}
for line, row in enumerate(csv_reader):
line += 1
try:
class_name... | 0.770896 | 0.497253 |
import os
import pandas as pd
import backend
def main():
"""
Function main that execute the program
:return:
"""
loop = True
while loop:
backend.print_menu()
choice = backend.handle_choice_menu(4)
if choice == 1:
backend.try_download_file()
elif c... | code/main.py | import os
import pandas as pd
import backend
def main():
"""
Function main that execute the program
:return:
"""
loop = True
while loop:
backend.print_menu()
choice = backend.handle_choice_menu(4)
if choice == 1:
backend.try_download_file()
elif c... | 0.10945 | 0.105395 |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cpovc_registry', '0001_initial'),
('cpovc_main', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='coreservices... | cpovc_main/migrations/0002_auto_20180419_1202.py | from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cpovc_registry', '0001_initial'),
('cpovc_main', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='coreservices... | 0.632276 | 0.104889 |
from flask import Flask, request
import random,time,os
app = Flask(__name__)
lobby_list = {}
CURRENT_VERSION = '7-5-2021'
def gen_resp(msg,status):
resp = {
'status' : status,
'msg' : msg
}
return resp
class Player():
def __init__(self,new_name,new_id):
self.id = new_id
... | main_old.py | from flask import Flask, request
import random,time,os
app = Flask(__name__)
lobby_list = {}
CURRENT_VERSION = '7-5-2021'
def gen_resp(msg,status):
resp = {
'status' : status,
'msg' : msg
}
return resp
class Player():
def __init__(self,new_name,new_id):
self.id = new_id
... | 0.208824 | 0.073596 |
import dateutil.parser
from dateutil import tz
from datetime import timedelta
import time
import requests
from requests.auth import HTTPBasicAuth
from xui.solar_winds.solar_winds_scripts import TEST_SERVER_CONNECTION
from common.methods import generate_string_from_template
from utilities.models import ConnectionInfo
... | ui_extensions/solar_winds/solar_winds_helper.py | import dateutil.parser
from dateutil import tz
from datetime import timedelta
import time
import requests
from requests.auth import HTTPBasicAuth
from xui.solar_winds.solar_winds_scripts import TEST_SERVER_CONNECTION
from common.methods import generate_string_from_template
from utilities.models import ConnectionInfo
... | 0.493653 | 0.063048 |
import numpy as np
import os, datetime
import matplotlib
from scipy.misc import imsave
def makeFile(f):
if not os.path.exists(f):
os.makedirs(f)
def getDateTime(minutes=False):
t = datetime.datetime.now()
dt = ('%s_%s' % (t.month, t.day))
if minutes:
dt += '_%s-%s-%s' % (t.hour, t.minu... | eval/py_utils.py | import numpy as np
import os, datetime
import matplotlib
from scipy.misc import imsave
def makeFile(f):
if not os.path.exists(f):
os.makedirs(f)
def getDateTime(minutes=False):
t = datetime.datetime.now()
dt = ('%s_%s' % (t.month, t.day))
if minutes:
dt += '_%s-%s-%s' % (t.hour, t.minu... | 0.245627 | 0.201401 |
import os
import shutil
import subprocess
import matplotlib.pyplot as plt
from ustools.read_core_files import *
from ustools.ultrasound_utils import reduce_frame_rate
from ustools.transform_ultrasound import transform_ultrasound
def write_images_to_disk(ult_3d, directory, title=None, aspect='auto'):
"""
A f... | ustools/animate_utterance.py | import os
import shutil
import subprocess
import matplotlib.pyplot as plt
from ustools.read_core_files import *
from ustools.ultrasound_utils import reduce_frame_rate
from ustools.transform_ultrasound import transform_ultrasound
def write_images_to_disk(ult_3d, directory, title=None, aspect='auto'):
"""
A f... | 0.562657 | 0.481698 |
from devops.helpers.helpers import wait
from proboscis import test
from fuelweb_test.helpers.decorators import log_snapshot_on_error
from fuelweb_test.settings import DEPLOYMENT_MODE
from fuelweb_test.tests.base_test_case import SetupEnvironment
from fuelweb_test.tests.base_test_case import TestBasic
@test(groups=[... | fuelweb_test/tests/tests_strength/test_image_based.py |
from devops.helpers.helpers import wait
from proboscis import test
from fuelweb_test.helpers.decorators import log_snapshot_on_error
from fuelweb_test.settings import DEPLOYMENT_MODE
from fuelweb_test.tests.base_test_case import SetupEnvironment
from fuelweb_test.tests.base_test_case import TestBasic
@test(groups=[... | 0.369429 | 0.259046 |
import json
import logging
import typing as t
import black
from IPython.core import getipython
from IPython.core.interactiveshell import ExecutionInfo
from IPython.display import display, HTML, Javascript
from IPython.terminal.interactiveshell import TerminalInteractiveShell as Ipt
logging.basicConfig()
LOGGER = logg... | src/jupyter_black/jupyter_black.py | import json
import logging
import typing as t
import black
from IPython.core import getipython
from IPython.core.interactiveshell import ExecutionInfo
from IPython.display import display, HTML, Javascript
from IPython.terminal.interactiveshell import TerminalInteractiveShell as Ipt
logging.basicConfig()
LOGGER = logg... | 0.649245 | 0.204858 |
from unittest import TestCase
from typing import Generator
from fuzzy_search.fuzzy_phrase import text2skipgrams, Phrase
class Test(TestCase):
# text2skipgrams
def test_text2skipgrams_rejects_negative_ngram_size(self):
error = None
try:
next(text2skipgrams("test", ngram_size=-1, s... | test/test_fuzzy_phrase.py | from unittest import TestCase
from typing import Generator
from fuzzy_search.fuzzy_phrase import text2skipgrams, Phrase
class Test(TestCase):
# text2skipgrams
def test_text2skipgrams_rejects_negative_ngram_size(self):
error = None
try:
next(text2skipgrams("test", ngram_size=-1, s... | 0.653016 | 0.53783 |
import bisect
from collections import namedtuple
from numbers import Number, Real
from ..conf import conf
from ..helpers import intify
from ..display import superscript
_BaseDimension = namedtuple(
"_BaseDimension", "order name symbol display_unit".split())
# TODO: enforce Fraction, rather than float, on dimensi... | noether/unit/dimension.py |
import bisect
from collections import namedtuple
from numbers import Number, Real
from ..conf import conf
from ..helpers import intify
from ..display import superscript
_BaseDimension = namedtuple(
"_BaseDimension", "order name symbol display_unit".split())
# TODO: enforce Fraction, rather than float, on dimensi... | 0.477067 | 0.344388 |
from .baserawio import (BaseRawIO, _signal_channel_dtype, _signal_stream_dtype,
_spike_channel_dtype, _event_channel_dtype)
import numpy as np
try:
import h5py
HAVE_H5PY = True
except ImportError:
HAVE_H5PY = False
class BiocamRawIO(BaseRawIO):
"""
Class for reading data ... | neo/rawio/biocamrawio.py | from .baserawio import (BaseRawIO, _signal_channel_dtype, _signal_stream_dtype,
_spike_channel_dtype, _event_channel_dtype)
import numpy as np
try:
import h5py
HAVE_H5PY = True
except ImportError:
HAVE_H5PY = False
class BiocamRawIO(BaseRawIO):
"""
Class for reading data ... | 0.708717 | 0.364156 |
from typing import Mapping, Sequence, Union, Any, Dict
Func = Union[str, bool] # typing of func will change to Union[Callable, bool]
class Option:
def __init__(self, desc: str = '', func: Func = ''):
self.desc = desc
self.func = func
def __repr__(self):
return self.desc
class Scen... | trpg/data_classes.py | from typing import Mapping, Sequence, Union, Any, Dict
Func = Union[str, bool] # typing of func will change to Union[Callable, bool]
class Option:
def __init__(self, desc: str = '', func: Func = ''):
self.desc = desc
self.func = func
def __repr__(self):
return self.desc
class Scen... | 0.659734 | 0.180829 |
import re
import logging
from hurry.filesize import size as filesize
import html.parser
import threading
import requests
from modularirc import BaseModule
class WorkerThread(threading.Thread):
def __init__(self, module, source, target, url):
super().__init__()
self.module = module
self.so... | src/modularirc/modules/basemodules/url_scanner.py | import re
import logging
from hurry.filesize import size as filesize
import html.parser
import threading
import requests
from modularirc import BaseModule
class WorkerThread(threading.Thread):
def __init__(self, module, source, target, url):
super().__init__()
self.module = module
self.so... | 0.301568 | 0.142948 |
from CellParser.BrailleCellParser import BrailleCellParser
if __name__ == '__main__':
braille_tests = [
[[32, 14, 19, 1, 37, 29, 0, 30, 19, 17, 0, 32, 14, 19, 17, 17, 15]], # Shaun the Sheep
[[25, 21, 29, 4, 30]], # don't
[[30, 19, 17, 0, 27, 10, 23, 7, 4, 14, 0, 29, 17, 9, 5, 7, 1, ... | Braille-Algorithms/Tests/CellParserTest.py | from CellParser.BrailleCellParser import BrailleCellParser
if __name__ == '__main__':
braille_tests = [
[[32, 14, 19, 1, 37, 29, 0, 30, 19, 17, 0, 32, 14, 19, 17, 17, 15]], # Shaun the Sheep
[[25, 21, 29, 4, 30]], # don't
[[30, 19, 17, 0, 27, 10, 23, 7, 4, 14, 0, 29, 17, 9, 5, 7, 1, ... | 0.304662 | 0.243418 |
import os
import sys
sys.path.insert(0, os.path.abspath('%s/../../..' % os.path.dirname(__file__)))
from chromite.cbuildbot import commands
from chromite.cbuildbot import constants
from chromite.cbuildbot.cbuildbot_unittest import BuilderRunMock
from chromite.cbuildbot.stages import chrome_stages
from chromite.cbuildb... | cbuildbot/stages/chrome_stages_unittest.py | import os
import sys
sys.path.insert(0, os.path.abspath('%s/../../..' % os.path.dirname(__file__)))
from chromite.cbuildbot import commands
from chromite.cbuildbot import constants
from chromite.cbuildbot.cbuildbot_unittest import BuilderRunMock
from chromite.cbuildbot.stages import chrome_stages
from chromite.cbuildb... | 0.431584 | 0.121243 |
import os
import cv2
import glob
import numpy as np
from face import get_landmark, LandmarkIndex
from __init__ import tar_dir
def process_proxy(tar_id, rsize, line, ksize=15, sigma=1e2, k=1):
# process teeth proxies to get their landmarks and high-pass filters
F, S = {}, {}
for mode in ('upper'... | audio2video/teeth.py |
import os
import cv2
import glob
import numpy as np
from face import get_landmark, LandmarkIndex
from __init__ import tar_dir
def process_proxy(tar_id, rsize, line, ksize=15, sigma=1e2, k=1):
# process teeth proxies to get their landmarks and high-pass filters
F, S = {}, {}
for mode in ('upper'... | 0.344995 | 0.274339 |
"""Functions related to finding conda environments (both Python and R based)"""
from __future__ import absolute_import
from .activate_helper import source_env_vars_from_command
from .envs_common import (find_env_paths_in_basedirs, convert_to_env_data,
validate_IPykernel, validate_IRkernel)
fr... | environment_kernels/envs_conda.py | """Functions related to finding conda environments (both Python and R based)"""
from __future__ import absolute_import
from .activate_helper import source_env_vars_from_command
from .envs_common import (find_env_paths_in_basedirs, convert_to_env_data,
validate_IPykernel, validate_IRkernel)
fr... | 0.614394 | 0.322513 |
import torch
import cv2
import numpy as np
from .. import torch_utils
from .models.retinaface import RetinaFace
from ..box_utils import batched_decode
from .utils import decode_landm
from .config import cfg_re50
from .prior_box import PriorBox
from torch.hub import load_state_dict_from_url
class RetinaNetDetectorONNX... | face_detection/retinaface/onnx.py | import torch
import cv2
import numpy as np
from .. import torch_utils
from .models.retinaface import RetinaFace
from ..box_utils import batched_decode
from .utils import decode_landm
from .config import cfg_re50
from .prior_box import PriorBox
from torch.hub import load_state_dict_from_url
class RetinaNetDetectorONNX... | 0.884395 | 0.356055 |
from deepflash2.learner import EnsembleLearner, get_files, Path
from app import crud
import pathlib
import numpy as np
from app.api import classes, utils_transformations
import app.fileserver_requests as fsr
from app.api import utils_paths
import zarr
def predict_image_list(classifier_id, image_id_list, use_tta, chan... | mistos-backend/src/app/api/utils_deepflash.py | from deepflash2.learner import EnsembleLearner, get_files, Path
from app import crud
import pathlib
import numpy as np
from app.api import classes, utils_transformations
import app.fileserver_requests as fsr
from app.api import utils_paths
import zarr
def predict_image_list(classifier_id, image_id_list, use_tta, chan... | 0.489503 | 0.496521 |
#-------------------------------------------------------------------------------
#Header - Linkers, Libs, Constants
from string import strip
from numpy import mean
from argparse import ArgumentParser, RawDescriptionHelpFormatter
from itertools import islice
import csv
#-------------------------------------------------... | contig_coverage_from_perbase_gff.py | #-------------------------------------------------------------------------------
#Header - Linkers, Libs, Constants
from string import strip
from numpy import mean
from argparse import ArgumentParser, RawDescriptionHelpFormatter
from itertools import islice
import csv
#-------------------------------------------------... | 0.229708 | 0.088426 |
from collections import namedtuple
from enum import Enum, auto
from .card import Rank, Suit
MIN_PLAYERS = 2
MAX_PLAYERS = 5
MAX_SCORE = 25
MAX_HINTS = 8
LIVES = 3
RANKS = [
Rank.ONE, Rank.ONE, Rank.ONE,
Rank.TWO, Rank.TWO,
Rank.THREE, Rank.THREE,
Rank.FOUR, Rank.FOUR,
Rank.FIVE
]
class Choic... | framework/utils.py |
from collections import namedtuple
from enum import Enum, auto
from .card import Rank, Suit
MIN_PLAYERS = 2
MAX_PLAYERS = 5
MAX_SCORE = 25
MAX_HINTS = 8
LIVES = 3
RANKS = [
Rank.ONE, Rank.ONE, Rank.ONE,
Rank.TWO, Rank.TWO,
Rank.THREE, Rank.THREE,
Rank.FOUR, Rank.FOUR,
Rank.FIVE
]
class Choic... | 0.552057 | 0.148325 |
import os
import uuid
import time
import shutil
import subprocess
class Nemu():
def __init__(self):
self.uuid = uuid.uuid4().hex
self.test_dir = "/tmp/" + self.uuid
self.pidfile = self.test_dir + "/nemu.pid"
os.mkdir(self.test_dir)
with open(self.test_dir + "/nemu.cfg", 'w'... | test/utils.py | import os
import uuid
import time
import shutil
import subprocess
class Nemu():
def __init__(self):
self.uuid = uuid.uuid4().hex
self.test_dir = "/tmp/" + self.uuid
self.pidfile = self.test_dir + "/nemu.pid"
os.mkdir(self.test_dir)
with open(self.test_dir + "/nemu.cfg", 'w'... | 0.195748 | 0.139455 |
import flock, os, torch, uuid, time, glob
from atexit import register
class GpuShareUnit():
def __init__(self, which_gpu, lock_path=None, manual_gpu_ctl=True, gpu_party=''):
self.device = which_gpu
self.manual_gpu_ctl = True
self.lock_path=lock_path
self.gpu_party = gpu_party
... | UTILS/gpu_share_unfin.py | import flock, os, torch, uuid, time, glob
from atexit import register
class GpuShareUnit():
def __init__(self, which_gpu, lock_path=None, manual_gpu_ctl=True, gpu_party=''):
self.device = which_gpu
self.manual_gpu_ctl = True
self.lock_path=lock_path
self.gpu_party = gpu_party
... | 0.141845 | 0.043164 |
from __future__ import print_function, division
import numpy as np
from tensorflow import keras
class MDStackGenerator(keras.utils.Sequence):
"""
The `MDDataGenerator` load data from a `NpzFile` generated by the
preprocess function with `kdtree` mode. The file contain
the following keyword variables.... | gdynet/data.py | from __future__ import print_function, division
import numpy as np
from tensorflow import keras
class MDStackGenerator(keras.utils.Sequence):
"""
The `MDDataGenerator` load data from a `NpzFile` generated by the
preprocess function with `kdtree` mode. The file contain
the following keyword variables.... | 0.798108 | 0.565599 |
import time
# item = (ID, Weight, Value)
ITEMS = [("Green", 12, 4),
("Blue", 2, 2),
("Grey", 1, 2),
("Orange", 1, 1),
("Yellow", 4, 10)]
# Returns the value of an item
def value(item):
return item[2]
# Returns the weight of an item
def weight(item):
return item[1]
# Retur... | Knapsack Problem.py | import time
# item = (ID, Weight, Value)
ITEMS = [("Green", 12, 4),
("Blue", 2, 2),
("Grey", 1, 2),
("Orange", 1, 1),
("Yellow", 4, 10)]
# Returns the value of an item
def value(item):
return item[2]
# Returns the weight of an item
def weight(item):
return item[1]
# Retur... | 0.643329 | 0.473718 |
train_lr = [1,1,1,0,0,1,1,0,1,0,
0,1,1,0,1,0,1,1,0,1,
0,1,1,0,0,1,1,1,0,0,
0,0,1,1,0,1,1,1,1,0,
0,0,0,1,0,0,0,0,1,1,
1,1,1,1,0,1,1,1,1,1,
0,0,0,1,1,1,1,1,1,1,
0,0,1,1,0,0,1,0,1,1,
0,0,1,1,0,1,0,1,0,0,
1,... | work/my_func/data_info.py | train_lr = [1,1,1,0,0,1,1,0,1,0,
0,1,1,0,1,0,1,1,0,1,
0,1,1,0,0,1,1,1,0,0,
0,0,1,1,0,1,1,1,1,0,
0,0,0,1,0,0,0,0,1,1,
1,1,1,1,0,1,1,1,1,1,
0,0,0,1,1,1,1,1,1,1,
0,0,1,1,0,0,1,0,1,1,
0,0,1,1,0,1,0,1,0,0,
1,... | 0.227384 | 0.135118 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from ._enums import *
__all__ = [
'PlaybackConfigurationAdMarkerPassthroughArgs',
'PlaybackConfigurationAvailSuppressionArgs',
'PlaybackConfigurationBumperArgs... | sdk/python/pulumi_aws_native/mediatailor/_inputs.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from ._enums import *
__all__ = [
'PlaybackConfigurationAdMarkerPassthroughArgs',
'PlaybackConfigurationAvailSuppressionArgs',
'PlaybackConfigurationBumperArgs... | 0.854703 | 0.112893 |
import sys
import json
import requests
import os
from optparse import OptionParser
import logging
import networkx as nx
from collections import defaultdict
from nodemeisterlib import get_json, get_node_names, get_group_names, get_nm_group_classes
FORMAT = "[%(levelname)s %(filename)s:%(lineno)s - %(funcName)20s() ] ... | contrib/cli_scripts/find_class.py |
import sys
import json
import requests
import os
from optparse import OptionParser
import logging
import networkx as nx
from collections import defaultdict
from nodemeisterlib import get_json, get_node_names, get_group_names, get_nm_group_classes
FORMAT = "[%(levelname)s %(filename)s:%(lineno)s - %(funcName)20s() ] ... | 0.382833 | 0.118666 |
import random
import string
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ValidationError
from django.db import models
clean_field = lambda field: field.replace('.', '__').strip()
keygen = lambda: ''.join(random.choice(string.ascii_uppercase + string.digits) for x in ra... | ereports/models.py | import random
import string
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ValidationError
from django.db import models
clean_field = lambda field: field.replace('.', '__').strip()
keygen = lambda: ''.join(random.choice(string.ascii_uppercase + string.digits) for x in ra... | 0.502197 | 0.157655 |
__author__ = "<NAME>"
__copyright__ = "Copyright 2022, Maxon Computer GmbH"
__credits__ = ["<NAME>"]
__version__ = "0.1.0"
__license__ = "MIT0"
import os
import glob
import re
# Need to `cd` to RedshiftOSLShaders directory and then call this script via path.
PATH_SRC = os.getcwd()
ID_SHADER = "shader"
ID_IMAGE_SCREE... | gendocs.py | __author__ = "<NAME>"
__copyright__ = "Copyright 2022, Maxon Computer GmbH"
__credits__ = ["<NAME>"]
__version__ = "0.1.0"
__license__ = "MIT0"
import os
import glob
import re
# Need to `cd` to RedshiftOSLShaders directory and then call this script via path.
PATH_SRC = os.getcwd()
ID_SHADER = "shader"
ID_IMAGE_SCREE... | 0.482673 | 0.111531 |
import serial
from tkinter import *
start=False
player=0
def startButton(event, start):
if start==False:
start =True
strtText.set("PAUSE")
else:
start = False
strtText.set("START")
def playerButton(event, player):
if start:
player = player^1
plrText.set("PLAYER: "+str(player+1))
#construction for th... | app.py | import serial
from tkinter import *
start=False
player=0
def startButton(event, start):
if start==False:
start =True
strtText.set("PAUSE")
else:
start = False
strtText.set("START")
def playerButton(event, player):
if start:
player = player^1
plrText.set("PLAYER: "+str(player+1))
#construction for th... | 0.053837 | 0.220091 |
from django.test import TestCase
from django.urls import reverse
from taggit.models import Tag
from users.models import User, Profile
from blog.models import Article, UserUpload
class ArticleViewTest(TestCase):
@classmethod
def setUpTestData(cls):
# Set up non-modified objects used by all test method... | blog/tests/test_views.py | from django.test import TestCase
from django.urls import reverse
from taggit.models import Tag
from users.models import User, Profile
from blog.models import Article, UserUpload
class ArticleViewTest(TestCase):
@classmethod
def setUpTestData(cls):
# Set up non-modified objects used by all test method... | 0.466116 | 0.280863 |
import numpy as np
from numpy import pi
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as p3
from matplotlib import animation
import networkx as nx
from matplotlib.animation import FuncAnimation, PillowWriter
import utils
import config
numFrames = 8
def sameAxisAnimation(t_all, waypoints, pos_al... | Simulation/utils/animation.py | import numpy as np
from numpy import pi
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as p3
from matplotlib import animation
import networkx as nx
from matplotlib.animation import FuncAnimation, PillowWriter
import utils
import config
numFrames = 8
def sameAxisAnimation(t_all, waypoints, pos_al... | 0.492432 | 0.618924 |
import logging
import os
from dataclasses import dataclass
from importlib import import_module
from typing import Optional, List
from django.apps import apps
from django.db import connections
from django.db.migrations.recorder import MigrationRecorder
from django.template import engines
from django.utils import timezo... | data_migration/services/file_generator.py | import logging
import os
from dataclasses import dataclass
from importlib import import_module
from typing import Optional, List
from django.apps import apps
from django.db import connections
from django.db.migrations.recorder import MigrationRecorder
from django.template import engines
from django.utils import timezo... | 0.623606 | 0.096962 |
import numpy as np
import torch
from torch.autograd import Variable
from tqdm import tqdm
def hessian_spectral_norm_approx(model, loader, criterion, M=20, seed=777, logger=None):
model.train()
def get_Hv(v):
flat_grad_loss = None
flat_Hv = None
ind = 0
for batch_idx, (inputs, ... | src/util/hessian.py | import numpy as np
import torch
from torch.autograd import Variable
from tqdm import tqdm
def hessian_spectral_norm_approx(model, loader, criterion, M=20, seed=777, logger=None):
model.train()
def get_Hv(v):
flat_grad_loss = None
flat_Hv = None
ind = 0
for batch_idx, (inputs, ... | 0.663342 | 0.39946 |
from model.model import *
import argparse
import collections
from utils import *
from torch.utils.tensorboard import SummaryWriter
from parse_config import ConfigParser
import data_loader.data_loaders as module_data
import model.model as module_arch
import model.metric as module_metric
import model.loss as module_loss
... | main.py | from model.model import *
import argparse
import collections
from utils import *
from torch.utils.tensorboard import SummaryWriter
from parse_config import ConfigParser
import data_loader.data_loaders as module_data
import model.model as module_arch
import model.metric as module_metric
import model.loss as module_loss
... | 0.81335 | 0.12817 |
import os
from sigver.datasets.base import IterableDataset
from skimage.io import imread
from skimage import img_as_ubyte
MAX_X = 3000
MAX_Y = 3000
class PersianDataset(IterableDataset):
""" Helper class to load the brazilian PUC-PR dataset
"""
def __init__(self, path, file_extension='PNG'):
self.... | sigver/datasets/persian.py | import os
from sigver.datasets.base import IterableDataset
from skimage.io import imread
from skimage import img_as_ubyte
MAX_X = 3000
MAX_Y = 3000
class PersianDataset(IterableDataset):
""" Helper class to load the brazilian PUC-PR dataset
"""
def __init__(self, path, file_extension='PNG'):
self.... | 0.655557 | 0.215124 |
import filecmp
import os
import tempfile
import unittest
from .. import utils
PROFILE = 'localhost -u admin -p admin -t default_tenant'
FAILED = 1 # Bash return code. Easier to read.
SUCCEED = 0 # Bash return code. Easier to read.
REPO_ARCHIVE = 'https://github.com/cloudify-incubator/' \
'cloudify-ec... | ecosystem_tests/tests/test_ecosystem.py | import filecmp
import os
import tempfile
import unittest
from .. import utils
PROFILE = 'localhost -u admin -p admin -t default_tenant'
FAILED = 1 # Bash return code. Easier to read.
SUCCEED = 0 # Bash return code. Easier to read.
REPO_ARCHIVE = 'https://github.com/cloudify-incubator/' \
'cloudify-ec... | 0.388502 | 0.126893 |
from telegram.ext import Updater, CommandHandler
from telegram.ext.dispatcher import run_async
import sys
import requests
import bs4
import shutil
from io import BytesIO
from PIL import Image
from urllib.parse import unquote
import numpy as np
@run_async
def help(update, context):
chat_id = update.message.chat.i... | lurkmore-bot.py | from telegram.ext import Updater, CommandHandler
from telegram.ext.dispatcher import run_async
import sys
import requests
import bs4
import shutil
from io import BytesIO
from PIL import Image
from urllib.parse import unquote
import numpy as np
@run_async
def help(update, context):
chat_id = update.message.chat.i... | 0.216012 | 0.099602 |
__docformat__ = 'restructuredtext en'
__author__ = '<NAME> <<EMAIL>>'
import copy
import random
import sys
import zope.interface
from zope.interface.declarations import implementer
import requests
import ipaddress
class IIPSource(zope.interface.Interface):
"""
The IPSource is an object that provides the IP ... | src/echoip/sources.py | __docformat__ = 'restructuredtext en'
__author__ = '<NAME> <<EMAIL>>'
import copy
import random
import sys
import zope.interface
from zope.interface.declarations import implementer
import requests
import ipaddress
class IIPSource(zope.interface.Interface):
"""
The IPSource is an object that provides the IP ... | 0.630799 | 0.192501 |
import logging
import multiprocessing
import os
import typing
from datetime import datetime, timezone
import psycopg2
import psycopg2.errors as psycopg_errors
import psycopg2.extensions
import psycopg2.extras
import pytest
import pypgoutput
HOST = os.environ.get("PGHOST")
PORT = os.environ.get("PGPORT")
DATABASE_NAM... | tests/test_reader.py | import logging
import multiprocessing
import os
import typing
from datetime import datetime, timezone
import psycopg2
import psycopg2.errors as psycopg_errors
import psycopg2.extensions
import psycopg2.extras
import pytest
import pypgoutput
HOST = os.environ.get("PGHOST")
PORT = os.environ.get("PGPORT")
DATABASE_NAM... | 0.374905 | 0.180251 |
# Copyright (C) 2013 Sony Mobile Communications AB.
# All rights, including trade secret rights, reserved.
import os
import time
import glob
import json
import signal
from ave.network.exceptions import *
from ave.network.control import RemoteControl
from ave.network.connection import *
from ave.network.process ... | common/jobs/tests/hickup.py |
# Copyright (C) 2013 Sony Mobile Communications AB.
# All rights, including trade secret rights, reserved.
import os
import time
import glob
import json
import signal
from ave.network.exceptions import *
from ave.network.control import RemoteControl
from ave.network.connection import *
from ave.network.process ... | 0.312055 | 0.074804 |
import pytest
import mock
import numpy as np
import awkward as awk
from zinv.modules.readers import SelectionProducer
class DummyEvent(object):
def __init__(self):
self.config = mock.MagicMock()
self.dummy_selection = lambda ev: np.array([True, False, True])
self.iblock = 0
self.s... | tests/unit/modules/readers/test_SelectionProducer.py | import pytest
import mock
import numpy as np
import awkward as awk
from zinv.modules.readers import SelectionProducer
class DummyEvent(object):
def __init__(self):
self.config = mock.MagicMock()
self.dummy_selection = lambda ev: np.array([True, False, True])
self.iblock = 0
self.s... | 0.500732 | 0.35421 |
from .HttpClient import HttpClient
from .ApiResponse import ApiResponse
from .Constants import ReqMethod
import time
class AuthClient:
authUri = "/auth-api/v2/authenticate"
refreshUri = "/auth-api/v2/authenticate/refresh"
timeJitter = 5 # Seconds off server expiration time
def __init__(self, host, ... | smartlingApiSdk/AuthClient.py | from .HttpClient import HttpClient
from .ApiResponse import ApiResponse
from .Constants import ReqMethod
import time
class AuthClient:
authUri = "/auth-api/v2/authenticate"
refreshUri = "/auth-api/v2/authenticate/refresh"
timeJitter = 5 # Seconds off server expiration time
def __init__(self, host, ... | 0.307774 | 0.036016 |
from __future__ import division
from __future__ import unicode_literals
from builtins import str
import sqlalchemy
import sqlalchemy.ext.declarative
import sqlalchemy.orm
import datetime
import json
Base = sqlalchemy.ext.declarative.declarative_base()
def dump_item_to_list(item):
data = []
for column in item... | astatsscraper/persistence.py | from __future__ import division
from __future__ import unicode_literals
from builtins import str
import sqlalchemy
import sqlalchemy.ext.declarative
import sqlalchemy.orm
import datetime
import json
Base = sqlalchemy.ext.declarative.declarative_base()
def dump_item_to_list(item):
data = []
for column in item... | 0.499023 | 0.121921 |
import os
from collections import OrderedDict
from typing import Dict, List, Optional
import ConfigSpace.hyperparameters as CSH
from ConfigSpace.configuration_space import ConfigurationSpace
from autoPyTorch.datasets.base_dataset import BaseDatasetPropertiesType
from autoPyTorch.pipeline.components.base_choice import... | autoPyTorch/pipeline/components/preprocessing/tabular_preprocessing/feature_preprocessing/__init__.py | import os
from collections import OrderedDict
from typing import Dict, List, Optional
import ConfigSpace.hyperparameters as CSH
from ConfigSpace.configuration_space import ConfigurationSpace
from autoPyTorch.datasets.base_dataset import BaseDatasetPropertiesType
from autoPyTorch.pipeline.components.base_choice import... | 0.851937 | 0.3581 |
import sys
from threading import Thread
from gi.repository import GLib
import dbus
import dbus.mainloop.glib
class LrcReceiver:
def __init__(self, update_callback, logger):
self.update_callback = update_callback
self.logger = logger
self.bus = None
self.lyrics_text = None
... | clients/py3status/lrcshowrs.py |
import sys
from threading import Thread
from gi.repository import GLib
import dbus
import dbus.mainloop.glib
class LrcReceiver:
def __init__(self, update_callback, logger):
self.update_callback = update_callback
self.logger = logger
self.bus = None
self.lyrics_text = None
... | 0.417509 | 0.08196 |
import urllib
import time
import logging
#list of strings used when screen scraping the setup page
#chr 34 is a quotation mark
CTIP_STRING = """set("ctIP",""" + chr(34)
CTMASK_STRING = """set("ctMask",""" + chr(34)
CTGATEWAY_STRING = """set("ctGateway",""" + chr(34)
CTNETSPEED_STRING = """choose("ctNetSpeed","""
CT... | WebBrickGwConfig/WebBrickGwConfig/StartechWrapper.py |
import urllib
import time
import logging
#list of strings used when screen scraping the setup page
#chr 34 is a quotation mark
CTIP_STRING = """set("ctIP",""" + chr(34)
CTMASK_STRING = """set("ctMask",""" + chr(34)
CTGATEWAY_STRING = """set("ctGateway",""" + chr(34)
CTNETSPEED_STRING = """choose("ctNetSpeed","""
CT... | 0.15588 | 0.087564 |
from selenium import webdriver
from selenium.common.exceptions import MoveTargetOutOfBoundsException, NoSuchElementException, WebDriverException
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import... | src/recaptcha_solver.py | from selenium import webdriver
from selenium.common.exceptions import MoveTargetOutOfBoundsException, NoSuchElementException, WebDriverException
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import... | 0.279533 | 0.06078 |
import logging
import sys
from datetime import datetime
import pytz
from connect.client import ClientError, ConnectClient
from connect.reports.constants import REPORTS_ENV
from connect.reports.datamodels import Account, Report
from connect.reports.renderers import get_renderer
from executor.exception_handler import (... | executor/executor.py | import logging
import sys
from datetime import datetime
import pytz
from connect.client import ClientError, ConnectClient
from connect.reports.constants import REPORTS_ENV
from connect.reports.datamodels import Account, Report
from connect.reports.renderers import get_renderer
from executor.exception_handler import (... | 0.218669 | 0.112893 |
import os
import time
import pandas as pd
import numpy as np
import json
from pathlib import Path
from expworkup import googleio
## Set the workflow of the code used to generate the experimental data and to process the data
WorkupVersion=1.0
def Expdata(DatFile):
ExpEntry=DatFile
with open(ExpEntry, "r") as ... | expworkup/createjson.py | import os
import time
import pandas as pd
import numpy as np
import json
from pathlib import Path
from expworkup import googleio
## Set the workflow of the code used to generate the experimental data and to process the data
WorkupVersion=1.0
def Expdata(DatFile):
ExpEntry=DatFile
with open(ExpEntry, "r") as ... | 0.143278 | 0.238157 |
import json
from discord.ext import commands
from src.util import exceptions
with open('src/util/config.json', 'r') as f:
config = json.load(f)
def is_worker():
async def predicate(ctx):
workers = ctx.guild.get_role(config["neko_workers"])
ia = workers in ctx.message.author.roles
ic ... | src/util/checks.py | import json
from discord.ext import commands
from src.util import exceptions
with open('src/util/config.json', 'r') as f:
config = json.load(f)
def is_worker():
async def predicate(ctx):
workers = ctx.guild.get_role(config["neko_workers"])
ia = workers in ctx.message.author.roles
ic ... | 0.274254 | 0.055464 |
import albumentations as alb
import cv2
class HorizontalFlip(alb.BasicTransform):
r"""
Flip the image horizontally randomly (equally likely) and replace the
word "left" with "right" in the caption.
.. note::
This transform can also work on images only (without the captions).
Its beha... | virtex/data/transforms.py | import albumentations as alb
import cv2
class HorizontalFlip(alb.BasicTransform):
r"""
Flip the image horizontally randomly (equally likely) and replace the
word "left" with "right" in the caption.
.. note::
This transform can also work on images only (without the captions).
Its beha... | 0.890171 | 0.596139 |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import os
import codecs
import unicodedata
import pandas as pd
import csv
import xlrd
def strip_accents(text):
try:
text = unicode(text, 'utf-8')
except NameError: # unicode is a default on python 3
pas... | 0-GeraLista-Profs.py | from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import os
import codecs
import unicodedata
import pandas as pd
import csv
import xlrd
def strip_accents(text):
try:
text = unicode(text, 'utf-8')
except NameError: # unicode is a default on python 3
pas... | 0.081758 | 0.137128 |