code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
import numpy as np
import argparse
import os
import cv2
import random
import time
import threading
global lock
class rgb_crop_batcher:
def __init__(self,list_path,batch_size,crop_size):
self.imgs = []
self.pois = []
self.batch_size = batch_size
self.crop_size = crop_size
#s... | tensorflow/src/rgb_crop_batcher.py | import numpy as np
import argparse
import os
import cv2
import random
import time
import threading
global lock
class rgb_crop_batcher:
def __init__(self,list_path,batch_size,crop_size):
self.imgs = []
self.pois = []
self.batch_size = batch_size
self.crop_size = crop_size
#s... | 0.320821 | 0.1585 |
import numpy as np
# For testing whether a number is close to zero
_FLOAT_EPS = np.finfo(np.float64).eps
_EPS4 = _FLOAT_EPS * 4.0
def mulQuat(qa, qb):
res = np.zeros(4)
res[0] = qa[0] * qb[0] - qa[1] * qb[1] - qa[2] * qb[2] - qa[3] * qb[3]
res[1] = qa[0] * qb[1] + qa[1] * qb[0] + qa[2] * qb[3] - qa[3] *... | d4rl/kitchen/adept_envs/utils/quatmath.py |
import numpy as np
# For testing whether a number is close to zero
_FLOAT_EPS = np.finfo(np.float64).eps
_EPS4 = _FLOAT_EPS * 4.0
def mulQuat(qa, qb):
res = np.zeros(4)
res[0] = qa[0] * qb[0] - qa[1] * qb[1] - qa[2] * qb[2] - qa[3] * qb[3]
res[1] = qa[0] * qb[1] + qa[1] * qb[0] + qa[2] * qb[3] - qa[3] *... | 0.725162 | 0.891999 |
import typing
from abc import abstractmethod
from ..uno.x_interface import XInterface as XInterface_8f010a43
if typing.TYPE_CHECKING:
from .calendar import Calendar as Calendar_7f2d0962
from .calendar_item import CalendarItem as CalendarItem_a86c0af1
from ..lang.locale import Locale as Locale_70d308fa
clas... | ooobuild/lo/i18n/x_calendar.py | import typing
from abc import abstractmethod
from ..uno.x_interface import XInterface as XInterface_8f010a43
if typing.TYPE_CHECKING:
from .calendar import Calendar as Calendar_7f2d0962
from .calendar_item import CalendarItem as CalendarItem_a86c0af1
from ..lang.locale import Locale as Locale_70d308fa
clas... | 0.796094 | 0.396886 |
import math
import os
import sys
import matplotlib.pyplot as plt
from numpy.typing import NDArray
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from typing import List, Tuple
import numpy as np
from cbf import Pnorm2dCBF
from cbf_qp_solver import CBFNomQPSolver
from matplotlib imp... | example/field_cbf_qp_optimizer.py |
import math
import os
import sys
import matplotlib.pyplot as plt
from numpy.typing import NDArray
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from typing import List, Tuple
import numpy as np
from cbf import Pnorm2dCBF
from cbf_qp_solver import CBFNomQPSolver
from matplotlib imp... | 0.599368 | 0.395193 |
import pathlib
import ssl
import urllib.request
import json
import logging
import glob
from typing import List
from ..system.logger import log
from ..system.workers import SysCommand
from ..models import PackageSearch, PackageSearchResult
from ..exceptions import PackageError, SysCallError
from ..environment.storage im... | myrepo/tooling/packages.py | import pathlib
import ssl
import urllib.request
import json
import logging
import glob
from typing import List
from ..system.logger import log
from ..system.workers import SysCommand
from ..models import PackageSearch, PackageSearchResult
from ..exceptions import PackageError, SysCallError
from ..environment.storage im... | 0.295433 | 0.150403 |
# This code is a part of jamdict library: https://github.com/neocl/jamdict
# :copyright: (c) 2016 <NAME> <<EMAIL>>
# :license: MIT, see LICENSE for more details.
import os
import unittest
import logging
from jamdict import KanjiDic2SQLite
from jamdict import KanjiDic2XML
# ------------------------------------------... | test/test_kanjidic2_sqlite.py | # This code is a part of jamdict library: https://github.com/neocl/jamdict
# :copyright: (c) 2016 <NAME> <<EMAIL>>
# :license: MIT, see LICENSE for more details.
import os
import unittest
import logging
from jamdict import KanjiDic2SQLite
from jamdict import KanjiDic2XML
# ------------------------------------------... | 0.463444 | 0.298542 |
from cyberbrain import InitialValue, Symbol, Binding
def test_inplace_operations(tracer, mocked_responses):
a1 = a2 = a3 = a4 = a5 = a6 = a7 = a8 = a9 = a10 = a11 = a12 = 2
b = 2
tracer.start()
a1 **= b # INPLACE_POWER
a2 *= b # INPLACE_MULTIPLY
a3 //= b # INPLACE_FLOOR_DIVIDE
a4 /= b... | test/test_inplace.py | from cyberbrain import InitialValue, Symbol, Binding
def test_inplace_operations(tracer, mocked_responses):
a1 = a2 = a3 = a4 = a5 = a6 = a7 = a8 = a9 = a10 = a11 = a12 = 2
b = 2
tracer.start()
a1 **= b # INPLACE_POWER
a2 *= b # INPLACE_MULTIPLY
a3 //= b # INPLACE_FLOOR_DIVIDE
a4 /= b... | 0.557845 | 0.276007 |
import itertools
from .material import Material, MAT_WATER
# Counter for objects, every new object will have n+1 surface number
cell_counter = itertools.count(100)
created_cells = [] # All objects after initialisation go here
class Cell: # superclass with common properties/methods for all surfaces
def __init__(... | fitsgeo/cell.py | import itertools
from .material import Material, MAT_WATER
# Counter for objects, every new object will have n+1 surface number
cell_counter = itertools.count(100)
created_cells = [] # All objects after initialisation go here
class Cell: # superclass with common properties/methods for all surfaces
def __init__(... | 0.702326 | 0.545165 |
from spade.message import Message
from spade.behaviour import State
from agents import FactoryAgent
from .metadata import *
from copy import deepcopy
import random
from messages import *
from behaviours import WorkingState
MAX_TIMES = 4
def parseSets(string): # the format of the string [[[],[], ..], 'break', [[],[],... | src/states/StateComputeConcession.py | from spade.message import Message
from spade.behaviour import State
from agents import FactoryAgent
from .metadata import *
from copy import deepcopy
import random
from messages import *
from behaviours import WorkingState
MAX_TIMES = 4
def parseSets(string): # the format of the string [[[],[], ..], 'break', [[],[],... | 0.348423 | 0.193509 |
def quick_sort(_list,m=0,n=None):
''' “挖坑填数+分治法”
时间复杂度:
最坏情况: 每次基准都是最小值n*(n-1)=O(n^2) 冒泡排序
最优情况&平均情况:每次刚好一分为二,nlog(n)
T(n)=2T(n/2)+n -> T(n/2)=2T(n/4)+n/2 -> T(1)=1
n + 2(n/2) + 2^2(n/4) + ... + 2^x(1) = nlog(n)
2^x=n x=log(n)
空间负责度:O(1)
:param _list:... | pynovice/algorithm/algorithm_base/sort.py | def quick_sort(_list,m=0,n=None):
''' “挖坑填数+分治法”
时间复杂度:
最坏情况: 每次基准都是最小值n*(n-1)=O(n^2) 冒泡排序
最优情况&平均情况:每次刚好一分为二,nlog(n)
T(n)=2T(n/2)+n -> T(n/2)=2T(n/4)+n/2 -> T(1)=1
n + 2(n/2) + 2^2(n/4) + ... + 2^x(1) = nlog(n)
2^x=n x=log(n)
空间负责度:O(1)
:param _list:... | 0.158728 | 0.267175 |
from ctutlz import rfc6962
def test_parse_log_entry_type_0():
tdf = b'\x00\x00'
parse, offset = rfc6962._parse_log_entry_type(tdf)
assert offset == 2
assert parse == {
'tdf': b'\x00\x00',
'val': 0,
}
def test_parse_log_entry_type_1():
tdf = b'\x00\x01'
parse, offset = ... | tests/test_rfc6962.py | from ctutlz import rfc6962
def test_parse_log_entry_type_0():
tdf = b'\x00\x00'
parse, offset = rfc6962._parse_log_entry_type(tdf)
assert offset == 2
assert parse == {
'tdf': b'\x00\x00',
'val': 0,
}
def test_parse_log_entry_type_1():
tdf = b'\x00\x01'
parse, offset = ... | 0.719778 | 0.638272 |
from logging import getLogger, ERROR
getLogger("scapy.runtime").setLevel(ERROR)
import argparse
import sys
from PyQt5 import QtCore
from wifipumpkin3 import PumpkinShell
from wifipumpkin3.core.utility.printer import (
banner,
setcolor,
display_messages,
set_nocolors,
)
from wifipumpkin3.core.utility.co... | wifipumpkin3/__main__.py | from logging import getLogger, ERROR
getLogger("scapy.runtime").setLevel(ERROR)
import argparse
import sys
from PyQt5 import QtCore
from wifipumpkin3 import PumpkinShell
from wifipumpkin3.core.utility.printer import (
banner,
setcolor,
display_messages,
set_nocolors,
)
from wifipumpkin3.core.utility.co... | 0.269326 | 0.083628 |
# Copyright (c) 2019, <NAME>
# All rights reserved.
import argparse
import os
import re
import shutil
import tempfile
import git
# Returns False if there was an error.
def checkPackageName(queriedPackageName, performFix=False):
if not queriedPackageName:
print("You must specify a package name for this script ... | scripts/check-package-naming.py |
# Copyright (c) 2019, <NAME>
# All rights reserved.
import argparse
import os
import re
import shutil
import tempfile
import git
# Returns False if there was an error.
def checkPackageName(queriedPackageName, performFix=False):
if not queriedPackageName:
print("You must specify a package name for this script ... | 0.280715 | 0.058615 |
from types import NoneType
from celery.utils.log import get_task_logger
from django.utils.six import iteritems, string_types, integer_types, binary_type
from que.internal import InternalTask as _InternalTask
from vms.models import Dc, DefaultDc
logger = get_task_logger(__name__)
PRIMITIVES = (float, bool, NoneType,... | api/task/internal.py | from types import NoneType
from celery.utils.log import get_task_logger
from django.utils.six import iteritems, string_types, integer_types, binary_type
from que.internal import InternalTask as _InternalTask
from vms.models import Dc, DefaultDc
logger = get_task_logger(__name__)
PRIMITIVES = (float, bool, NoneType,... | 0.539711 | 0.078572 |
import functools
import itertools
import logging
import math
import random
from io import BytesIO
from pathlib import Path
from typing import List, Optional
import discord
from PIL import Image
from d4dj_utils.master.card_master import CardMaster
from d4dj_utils.master.gacha_master import GachaMaster
from discord.ext ... | miyu_bot/commands/cogs/gacha.py | import functools
import itertools
import logging
import math
import random
from io import BytesIO
from pathlib import Path
from typing import List, Optional
import discord
from PIL import Image
from d4dj_utils.master.card_master import CardMaster
from d4dj_utils.master.gacha_master import GachaMaster
from discord.ext ... | 0.672762 | 0.11808 |
import sys
from io import open
import os.path
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def parse_requirements(filename):
with open(filename, encoding="utf-8") as f:
for line in f:
yield line.strip()
def read(filename):
with open(fi... | setup.py |
import sys
from io import open
import os.path
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def parse_requirements(filename):
with open(filename, encoding="utf-8") as f:
for line in f:
yield line.strip()
def read(filename):
with open(fi... | 0.288268 | 0.092074 |
from enum import Enum, EnumMeta
from six import with_metaclass
class _CaseInsensitiveEnumMeta(EnumMeta):
def __getitem__(self, name):
return super().__getitem__(name.upper())
def __getattr__(cls, name):
"""Return the enum member matching `name`
We use __getattr__ instead of descriptor... | sdk/orbital/azure-mgmt-orbital/azure/mgmt/orbital/models/_azure_orbital_enums.py |
from enum import Enum, EnumMeta
from six import with_metaclass
class _CaseInsensitiveEnumMeta(EnumMeta):
def __getitem__(self, name):
return super().__getitem__(name.upper())
def __getattr__(cls, name):
"""Return the enum member matching `name`
We use __getattr__ instead of descriptor... | 0.748628 | 0.109992 |
from __future__ import annotations
import asyncio
import bisect
import collections
import contextlib
import dataclasses
import hashlib
import itertools
import logging
import os
import threading
import time
from argparse import ArgumentParser
from concurrent.futures.thread import ThreadPoolExecutor
from contextlib impo... | btrfslime/dedupe/__main__.py | from __future__ import annotations
import asyncio
import bisect
import collections
import contextlib
import dataclasses
import hashlib
import itertools
import logging
import os
import threading
import time
from argparse import ArgumentParser
from concurrent.futures.thread import ThreadPoolExecutor
from contextlib impo... | 0.76291 | 0.172207 |
# Simple template for doing unit tests
"""Unit test for munich_films.py"""
import os, time
import unittest
import requests
from bs4 import BeautifulSoup
import munich_films # module to be tested
# prepare input and reference data
testTextVersion = "artechok_originalton.html"
REFERENCE_OUTPUT = "reference_output.... | unittest_munichfilms.py |
# Simple template for doing unit tests
"""Unit test for munich_films.py"""
import os, time
import unittest
import requests
from bs4 import BeautifulSoup
import munich_films # module to be tested
# prepare input and reference data
testTextVersion = "artechok_originalton.html"
REFERENCE_OUTPUT = "reference_output.... | 0.251924 | 0.356447 |
from __future__ import division
import numpy as np
import scipy.sparse
from numpy.linalg import inv
from math import exp
from Parameters_LV import *
'''
This code returns the solution of the reaction-diffusion equation laplace u=D*u_t+r(u1,u2) with r( being the reaction function of the Lotka-Volerra equation)
, where ... | multiscaleRD/FD_LV.py | from __future__ import division
import numpy as np
import scipy.sparse
from numpy.linalg import inv
from math import exp
from Parameters_LV import *
'''
This code returns the solution of the reaction-diffusion equation laplace u=D*u_t+r(u1,u2) with r( being the reaction function of the Lotka-Volerra equation)
, where ... | 0.40698 | 0.564999 |
import os
import shutil
import unittest
from mock import patch
import activity.activity_GenerateSWHMetadata as activity_module
from activity.activity_GenerateSWHMetadata import (
activity_GenerateSWHMetadata as activity_object,
)
from provider.article import article
import tests.activity.settings_mock as settings_m... | tests/activity/test_activity_generate_swh_metadata.py | import os
import shutil
import unittest
from mock import patch
import activity.activity_GenerateSWHMetadata as activity_module
from activity.activity_GenerateSWHMetadata import (
activity_GenerateSWHMetadata as activity_object,
)
from provider.article import article
import tests.activity.settings_mock as settings_m... | 0.453988 | 0.128771 |
from __future__ import annotations
import re
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Type, Union
import lavapy
if TYPE_CHECKING:
from .pool import Node
__all__ = ("decodeQuery",
"Playable",
"PartialResource",
"Track",
"MultiTrack"... | lavapy/tracks.py | from __future__ import annotations
import re
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Type, Union
import lavapy
if TYPE_CHECKING:
from .pool import Node
__all__ = ("decodeQuery",
"Playable",
"PartialResource",
"Track",
"MultiTrack"... | 0.944112 | 0.335841 |
import time
from datetime import date as datetime
from urllib.parse import urljoin
from Scraper.CommonNewsHandler import CommonNewsHandler
from Requests.Requester import Requester
import re
from bs4 import BeautifulSoup
from Translation.GoogleTranslator import GoogleTranslator
class NewsScraper(CommonNewsHandler):
... | Country/Spanish/News/Efe/NewsScraper.py | import time
from datetime import date as datetime
from urllib.parse import urljoin
from Scraper.CommonNewsHandler import CommonNewsHandler
from Requests.Requester import Requester
import re
from bs4 import BeautifulSoup
from Translation.GoogleTranslator import GoogleTranslator
class NewsScraper(CommonNewsHandler):
... | 0.363534 | 0.054324 |
import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State, ALL
from dash.exceptions import PreventUpdate
import plotly.express as px
from server.model import Model
from settings.config import TITLE, ASSE... | application/dash.py | import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State, ALL
from dash.exceptions import PreventUpdate
import plotly.express as px
from server.model import Model
from settings.config import TITLE, ASSE... | 0.799716 | 0.350727 |
import json
import time
import click
from flask import abort
from flask.cli import with_appcontext
from roomsurvey.db import get_db
from roomsurvey.log import log
from roomsurvey.syndicate import get_syndicate_for_user
from roomsurvey.mail import survey_reminder_mail
def get_survey_data(crsid):
db = get_db()
... | roomsurvey/survey.py | import json
import time
import click
from flask import abort
from flask.cli import with_appcontext
from roomsurvey.db import get_db
from roomsurvey.log import log
from roomsurvey.syndicate import get_syndicate_for_user
from roomsurvey.mail import survey_reminder_mail
def get_survey_data(crsid):
db = get_db()
... | 0.194827 | 0.060529 |
import rospy
from geometry_msgs.msg import Twist
from math import atan2, degrees
from nav_msgs.msg import Odometry
from sensor_msgs.msg import LaserScan
from sys import argv
from time import time
RATE = 20
QUEUE_SIZE = 10
# Speed constants
kx, ky, kt = 1, 1, 2
# Messages
laserMsg = None
odomMsg = None
GOAL = None... | tp1/src/bug2.py |
import rospy
from geometry_msgs.msg import Twist
from math import atan2, degrees
from nav_msgs.msg import Odometry
from sensor_msgs.msg import LaserScan
from sys import argv
from time import time
RATE = 20
QUEUE_SIZE = 10
# Speed constants
kx, ky, kt = 1, 1, 2
# Messages
laserMsg = None
odomMsg = None
GOAL = None... | 0.587588 | 0.425844 |
from __future__ import unicode_literals
from snapshottest import Snapshot
snapshots = Snapshot()
snapshots[
"test_save_document_answer[integer-question__configuration0-None-question__format_validators0-1-None-SaveDocumentIntegerAnswer-True-option-slug-True] 1"
] = {
"saveDocumentIntegerAnswer": {
"an... | caluma/form/tests/snapshots/snap_test_document.py | from __future__ import unicode_literals
from snapshottest import Snapshot
snapshots = Snapshot()
snapshots[
"test_save_document_answer[integer-question__configuration0-None-question__format_validators0-1-None-SaveDocumentIntegerAnswer-True-option-slug-True] 1"
] = {
"saveDocumentIntegerAnswer": {
"an... | 0.522202 | 0.29305 |
import torch
from torch import nn
import torch.nn.functional as F
'''
Code adapted from https://github.com/uber-research/coordconv
accompanying the paper "An Intriguing Failing of Convolutional Neural Networks and the CoordConv Solution" (NeurIPS 2018)
'''
class AddCoords360(nn.Module):
def __i... | evaluate/previous_works/svsyn/models/modules.py | import torch
from torch import nn
import torch.nn.functional as F
'''
Code adapted from https://github.com/uber-research/coordconv
accompanying the paper "An Intriguing Failing of Convolutional Neural Networks and the CoordConv Solution" (NeurIPS 2018)
'''
class AddCoords360(nn.Module):
def __i... | 0.864053 | 0.546194 |
__author__ = 'LangJin'
import os, hashlib,urllib,time
from config import keys,redis_config
from .dbtools import RedisDb
def create_token():
'''
生成登陆后的token,格式如下:\n
"<KEY>"
'''
return hashlib.sha1(os.urandom(64)).hexdigest()
def encryption(username,password,role):
'''
说明:密码的加密算法,role是角色\n... | FlaskServer/app/utils/common.py | __author__ = 'LangJin'
import os, hashlib,urllib,time
from config import keys,redis_config
from .dbtools import RedisDb
def create_token():
'''
生成登陆后的token,格式如下:\n
"<KEY>"
'''
return hashlib.sha1(os.urandom(64)).hexdigest()
def encryption(username,password,role):
'''
说明:密码的加密算法,role是角色\n... | 0.283484 | 0.132824 |
from typing import Literal
import unittest
import Fumagalli_Motta_Tarantino_2020.tests.MockModels as MockModels
import Fumagalli_Motta_Tarantino_2020 as FMT20
class TestVisualize(unittest.TestCase):
show_plots: bool = False
show_always: bool = True
def setUpMock(self, **kwargs) -> None:
self.moc... | Fumagalli_Motta_Tarantino_2020/tests/Test_Visualize.py | from typing import Literal
import unittest
import Fumagalli_Motta_Tarantino_2020.tests.MockModels as MockModels
import Fumagalli_Motta_Tarantino_2020 as FMT20
class TestVisualize(unittest.TestCase):
show_plots: bool = False
show_always: bool = True
def setUpMock(self, **kwargs) -> None:
self.moc... | 0.865025 | 0.504089 |
import os
import pyspark.sql.functions as F
import pyspark.sql.types as T
from pyspark.sql import SparkSession
import argparse
from common import create_spark_session, title_string_udf, castInt_udf
# get arguments passed in spark-submit command
parser = argparse.ArgumentParser()
parser.add_argument("--bucketName",
... | scripts/spark/i94_data_dictionary.py | import os
import pyspark.sql.functions as F
import pyspark.sql.types as T
from pyspark.sql import SparkSession
import argparse
from common import create_spark_session, title_string_udf, castInt_udf
# get arguments passed in spark-submit command
parser = argparse.ArgumentParser()
parser.add_argument("--bucketName",
... | 0.45641 | 0.413773 |
import atexit
import functools
import argparse
import docker
from tensorforce.execution import Runner
from tensorforce.contrib.openai_gym import OpenAIGym
import gym
from .. import configs, utility, agents
client = docker.from_env()
def clean_up_agents(agents):
"""Stops all agents"""
return [agent.shutdow... | pommerman/cli/train_with_tensorforce.py | import atexit
import functools
import argparse
import docker
from tensorforce.execution import Runner
from tensorforce.contrib.openai_gym import OpenAIGym
import gym
from .. import configs, utility, agents
client = docker.from_env()
def clean_up_agents(agents):
"""Stops all agents"""
return [agent.shutdow... | 0.483648 | 0.303654 |
from odoo import models, fields, api, _
class report_project_task(models.AbstractModel):
_name = "account.report.project.task"
_inherit = 'account.report'
_description = 'Timesheet Report'
filter_date = {'date_from' : '', 'date_to' : '', 'filter' : 'this_month'}
filter_projects = True
fil... | models/report_project_task.py | from odoo import models, fields, api, _
class report_project_task(models.AbstractModel):
_name = "account.report.project.task"
_inherit = 'account.report'
_description = 'Timesheet Report'
filter_date = {'date_from' : '', 'date_to' : '', 'filter' : 'this_month'}
filter_projects = True
fil... | 0.158369 | 0.063861 |
__author__ = "<NAME>"
import torch
from ptp.configuration.configuration_error import ConfigurationError
from ptp.components.models.model import Model
from ptp.data_types.data_definition import DataDefinition
class Attn_Decoder_RNN(Model):
"""
Single layer GRU decoder with attention:
<NAME>., <NAME>., ... | ptp/components/models/attn_decoder_rnn.py |
__author__ = "<NAME>"
import torch
from ptp.configuration.configuration_error import ConfigurationError
from ptp.components.models.model import Model
from ptp.data_types.data_definition import DataDefinition
class Attn_Decoder_RNN(Model):
"""
Single layer GRU decoder with attention:
<NAME>., <NAME>., ... | 0.854521 | 0.470189 |
from __future__ import print_function
import argparse
import random
import sys
def read_file(name):
links = {}
for line in open(name):
filename, info = line.strip().split(':')
filename = filename.split("/")[-1]
targets = [int(n) for n in info.split() if n != '-']
src = max(tar... | disentanglement/tools/evaluation/significance.py |
from __future__ import print_function
import argparse
import random
import sys
def read_file(name):
links = {}
for line in open(name):
filename, info = line.strip().split(':')
filename = filename.split("/")[-1]
targets = [int(n) for n in info.split() if n != '-']
src = max(tar... | 0.364778 | 0.260948 |
import dbus
import dbus.exceptions
from bluezero import constants
from bluezero import dbus_tools
import bluezero.adapter
from bluezero import tools
logger = tools.create_module_logger(__name__)
class Device:
"""Remote Bluetooth Device Class.
This class instantiates an object that interacts with a remote
... | bluezero/device.py | import dbus
import dbus.exceptions
from bluezero import constants
from bluezero import dbus_tools
import bluezero.adapter
from bluezero import tools
logger = tools.create_module_logger(__name__)
class Device:
"""Remote Bluetooth Device Class.
This class instantiates an object that interacts with a remote
... | 0.875534 | 0.221098 |
# coding: utf-8
import logging
import unittest
from fedlearner_webconsole.utils import metrics
from fedlearner_webconsole.utils.metrics import _DefaultMetricsHandler, MetricsHandler
class _FakeMetricsHandler(MetricsHandler):
def emit_counter(self, name, value: int, tags: dict = None):
logging.info(f'[T... | web_console_v2/api/test/fedlearner_webconsole/utils/metrics_test.py |
# coding: utf-8
import logging
import unittest
from fedlearner_webconsole.utils import metrics
from fedlearner_webconsole.utils.metrics import _DefaultMetricsHandler, MetricsHandler
class _FakeMetricsHandler(MetricsHandler):
def emit_counter(self, name, value: int, tags: dict = None):
logging.info(f'[T... | 0.395835 | 0.356783 |
# 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 at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | lib/pymedphys/_streamlit/index.py |
# 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 at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | 0.850189 | 0.243255 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from . import outputs
from ._inputs import *
__all__ = ['MetricArgs', 'Metric']
@pulumi.input_type
class MetricArgs:
def __init__(__self__, *,
filter... | sdk/python/pulumi_gcp/logging/metric.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from . import outputs
from ._inputs import *
__all__ = ['MetricArgs', 'Metric']
@pulumi.input_type
class MetricArgs:
def __init__(__self__, *,
filter... | 0.922744 | 0.228996 |
import unittest
import numpy as np
from ceda_icompress.InfoMeasures.bitcount import bitcount, bitpaircount
from test_types import get_test_types
DIM_LEN = 128
class bitcountTest(unittest.TestCase):
"""Test the bitcount function with known answers."""
def test_ones_float32(self):
# generate a load of ... | ceda_icompress/UnitTests/test_bitcount.py | import unittest
import numpy as np
from ceda_icompress.InfoMeasures.bitcount import bitcount, bitpaircount
from test_types import get_test_types
DIM_LEN = 128
class bitcountTest(unittest.TestCase):
"""Test the bitcount function with known answers."""
def test_ones_float32(self):
# generate a load of ... | 0.738009 | 0.654136 |
from django.db import models
from django.db.models import Q
from core.mixins import ObjectUrlMixin, CoreDisplayMixin
from mozdns.domain.models import Domain
from core.utils import networks_to_Q
from core.keyvalue.models import KeyValue
class Vlan(models.Model, ObjectUrlMixin, CoreDisplayMixin):
id = models.Auto... | core/vlan/models.py | from django.db import models
from django.db.models import Q
from core.mixins import ObjectUrlMixin, CoreDisplayMixin
from mozdns.domain.models import Domain
from core.utils import networks_to_Q
from core.keyvalue.models import KeyValue
class Vlan(models.Model, ObjectUrlMixin, CoreDisplayMixin):
id = models.Auto... | 0.715821 | 0.16388 |
import io
import os
import re
import time
from datetime import date, datetime
from typing import Any, Dict, List, Optional, Union
def pretty_size(size: Union[int, float]) -> str:
"""
Converts a size in bytes to its string representation (e.g. 1024 -> 1KiB)
:param size: Size in bytes
"""
size = flo... | splitgraph/core/output.py | import io
import os
import re
import time
from datetime import date, datetime
from typing import Any, Dict, List, Optional, Union
def pretty_size(size: Union[int, float]) -> str:
"""
Converts a size in bytes to its string representation (e.g. 1024 -> 1KiB)
:param size: Size in bytes
"""
size = flo... | 0.748076 | 0.493653 |
import os
import subprocess
import json
import math
import uuid
import pandas as pd
from jinja2 import Environment, PackageLoader, select_autoescape
import pprint
from installed_clients.KBaseReportClient import KBaseReport
from .ui_utils import format_results
env = Environment(
loader=PackageLoader('kb_cmash','ut... | lib/kb_cmash/utils/CMashUtils.py | import os
import subprocess
import json
import math
import uuid
import pandas as pd
from jinja2 import Environment, PackageLoader, select_autoescape
import pprint
from installed_clients.KBaseReportClient import KBaseReport
from .ui_utils import format_results
env = Environment(
loader=PackageLoader('kb_cmash','ut... | 0.24015 | 0.069542 |
import builtins
import collections
import inspect
import re
import sys
import types
from dataclasses import dataclass, replace
from typing import *
from crosshair.util import debug, memo
def strip_comment_line(line: str) -> str:
line = line.strip()
if line.startswith("'''") or line.startswith('"""'):
... | crosshair/condition_parser.py | import builtins
import collections
import inspect
import re
import sys
import types
from dataclasses import dataclass, replace
from typing import *
from crosshair.util import debug, memo
def strip_comment_line(line: str) -> str:
line = line.strip()
if line.startswith("'''") or line.startswith('"""'):
... | 0.467332 | 0.214075 |
from onegov.feriennet import _
from onegov.form import Form
from onegov.form.fields import MultiCheckboxField
from onegov.user import User, UserCollection
from sqlalchemy import func
from wtforms.fields import BooleanField, RadioField, SelectField, StringField
from wtforms.fields.html5 import DecimalField
from wtforms.... | src/onegov/feriennet/forms/billing.py | from onegov.feriennet import _
from onegov.form import Form
from onegov.form.fields import MultiCheckboxField
from onegov.user import User, UserCollection
from sqlalchemy import func
from wtforms.fields import BooleanField, RadioField, SelectField, StringField
from wtforms.fields.html5 import DecimalField
from wtforms.... | 0.68056 | 0.166472 |
__all__ = []
import time
import logging
from WMCore.Database.DBFormatter import DBFormatter
class New(DBFormatter):
sql = """INSERT INTO wmbs_job (jobgroup, name, state, state_time,
couch_record, cache_dir, location, outcome,
fwjr_path) VALU... | src/python/WMCore/WMBS/MySQL/Jobs/New.py | __all__ = []
import time
import logging
from WMCore.Database.DBFormatter import DBFormatter
class New(DBFormatter):
sql = """INSERT INTO wmbs_job (jobgroup, name, state, state_time,
couch_record, cache_dir, location, outcome,
fwjr_path) VALU... | 0.223631 | 0.10961 |
from tir import Webapp
import unittest
class PCOA160(unittest.TestCase):
@classmethod
def setUpClass(inst):
inst.oHelper = Webapp()
inst.oHelper.Setup("SIGAPCO", "06/04/2020", "T1", "D MG 01 ")
inst.oHelper.Program("PCOA160")
def test_PCOA160_001(self):
#protege o... | Protheus_WebApp/Modules/SIGAPCO/PCOA160TESTCASE.py | from tir import Webapp
import unittest
class PCOA160(unittest.TestCase):
@classmethod
def setUpClass(inst):
inst.oHelper = Webapp()
inst.oHelper.Setup("SIGAPCO", "06/04/2020", "T1", "D MG 01 ")
inst.oHelper.Program("PCOA160")
def test_PCOA160_001(self):
#protege o... | 0.417271 | 0.17259 |
import sys
IS_PYTHON3 = sys.version_info[0] >= 3
if IS_PYTHON3:
exec("from ._input import input as _input")
exec("from ._parser import parser as _parser")
exec("from ._lexer import lexer as _lexer")
else:
exec("from _input import input as _input")
exec("from _parser import parser as _parser")
... | pyne/pyne/fortranformat/FortranRecordReader.py | import sys
IS_PYTHON3 = sys.version_info[0] >= 3
if IS_PYTHON3:
exec("from ._input import input as _input")
exec("from ._parser import parser as _parser")
exec("from ._lexer import lexer as _lexer")
else:
exec("from _input import input as _input")
exec("from _parser import parser as _parser")
... | 0.324021 | 0.141964 |
import json
from functools import wraps
from django.http import JsonResponse, Http404
from django.views.decorators.csrf import csrf_exempt
from ..cms.models import Region, Language
from ..cms.constants import feedback_ratings
def feedback_handler(func):
"""
Decorator definition for feedback API functions a... | integreat_cms/api/decorators.py | import json
from functools import wraps
from django.http import JsonResponse, Http404
from django.views.decorators.csrf import csrf_exempt
from ..cms.models import Region, Language
from ..cms.constants import feedback_ratings
def feedback_handler(func):
"""
Decorator definition for feedback API functions a... | 0.706292 | 0.261145 |
from minesweeper.auth.User import User
from tkinter import messagebox
import pickle
import os
class Auth:
def __init__(self):
self.__path = 'minesweeper/data/users.pickle'
self.current_user = None
self.users = []
try:
with open(self.__path, 'rb') as f:
... | minesweeper/auth/Auth.py | from minesweeper.auth.User import User
from tkinter import messagebox
import pickle
import os
class Auth:
def __init__(self):
self.__path = 'minesweeper/data/users.pickle'
self.current_user = None
self.users = []
try:
with open(self.__path, 'rb') as f:
... | 0.190762 | 0.062445 |
import logging
import os
import torch
from caffe2.proto import caffe2_pb2
from torch import nn
from detectron2.config import CfgNode as CN
from .caffe2_export import export_caffe2_detection_model, run_and_save_graph
from .caffe2_inference import ProtobufDetectionModel
from .caffe2_modeling import META_ARCH_CAFFE2_EXP... | detectron2/export/api.py | import logging
import os
import torch
from caffe2.proto import caffe2_pb2
from torch import nn
from detectron2.config import CfgNode as CN
from .caffe2_export import export_caffe2_detection_model, run_and_save_graph
from .caffe2_inference import ProtobufDetectionModel
from .caffe2_modeling import META_ARCH_CAFFE2_EXP... | 0.892832 | 0.26046 |
def dramkit_funcsytle(a, b='b', *args, **kwargs):
'''
本程序中的function代码风格示例
函数名由 ``小写单词`` 和 ``_`` 拼接而成,这里写函数详细描述,描述可能比较
长长长长长长长长长长长长,需要换行
参见 :class:`dramkit.pystyles.dramkit_style.DramkitClassStyle`
.. todo::
待完成描述
- todo1
- todo2
Parameters
----------
a : ... | dramkit/pystyles/dramkit_style.py | def dramkit_funcsytle(a, b='b', *args, **kwargs):
'''
本程序中的function代码风格示例
函数名由 ``小写单词`` 和 ``_`` 拼接而成,这里写函数详细描述,描述可能比较
长长长长长长长长长长长长,需要换行
参见 :class:`dramkit.pystyles.dramkit_style.DramkitClassStyle`
.. todo::
待完成描述
- todo1
- todo2
Parameters
----------
a : ... | 0.646237 | 0.490419 |
import pprint
import re # noqa: F401
import six
class UpdateUserRequest(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
an... | env/lib/python3.7/site-packages/docusign_admin/models/update_user_request.py | import pprint
import re # noqa: F401
import six
class UpdateUserRequest(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
an... | 0.525369 | 0.074736 |
import mock
import random
import string
import unittest
from cloudify.context import BootstrapContext
from cloudify.state import current_ctx
from cloudify.mocks import MockCloudifyContext
import openstack_plugin_common
import openstack_plugin_common.tests.test as common_test
import neutron_plugin
import neutron_pl... | neutron_plugin/tests/test.py |
import mock
import random
import string
import unittest
from cloudify.context import BootstrapContext
from cloudify.state import current_ctx
from cloudify.mocks import MockCloudifyContext
import openstack_plugin_common
import openstack_plugin_common.tests.test as common_test
import neutron_plugin
import neutron_pl... | 0.570571 | 0.118538 |
import six
import json
import logging
from six.moves.urllib import parse
from webob import exc
from robotice.utils import serializers
from robotice.utils import tasks
from robotice.api import wsgi
from robotice.api.v1.base import BaseController
from robotice.common.i18n import _
from celery import states
from celery... | robotice/api/v1/tasks.py | import six
import json
import logging
from six.moves.urllib import parse
from webob import exc
from robotice.utils import serializers
from robotice.utils import tasks
from robotice.api import wsgi
from robotice.api.v1.base import BaseController
from robotice.common.i18n import _
from celery import states
from celery... | 0.694717 | 0.091951 |
__all__ = ['TEST_PATH', 'TEST_JPG', 'TEST_PNG', 'TEST_JSON', 'TEST_CSV', 'progress_bar', 'resize_file', 'in_ipython',
'in_colab', 'in_notebook', 'gpu_memory', 'IN_IPYTHON', 'IN_COLAB', 'IN_NOTEBOOK', 'np_open_image',
'cv_open_image', 'old_colormap_segmentation_labels', 'generate_colormap_rgb', 'g... | cellsegment/core.py |
__all__ = ['TEST_PATH', 'TEST_JPG', 'TEST_PNG', 'TEST_JSON', 'TEST_CSV', 'progress_bar', 'resize_file', 'in_ipython',
'in_colab', 'in_notebook', 'gpu_memory', 'IN_IPYTHON', 'IN_COLAB', 'IN_NOTEBOOK', 'np_open_image',
'cv_open_image', 'old_colormap_segmentation_labels', 'generate_colormap_rgb', 'g... | 0.442155 | 0.388212 |
from datetime import datetime
from datetime import timezone
import logging
import time
import requests
import json
__author__ = "<NAME>"
__copyright__ = "Copyright 2018, <NAME>"
__license__ = "MIT"
__email__ = "<EMAIL>"
class OpenWeatherApi:
def __init__(self, api_key):
self.api_key = api_key
def get... | gw2pvo/ow_api.py | from datetime import datetime
from datetime import timezone
import logging
import time
import requests
import json
__author__ = "<NAME>"
__copyright__ = "Copyright 2018, <NAME>"
__license__ = "MIT"
__email__ = "<EMAIL>"
class OpenWeatherApi:
def __init__(self, api_key):
self.api_key = api_key
def get... | 0.465145 | 0.0729 |
from budgetportal.models import (
CategoryGuide,
Department,
FinancialYear,
Government,
Notice,
Sphere,
)
from django.test import Client, TestCase
from mock import MagicMock, patch
class BasicPagesTestCase(TestCase):
fixtures = ["video-language", "faq", "homepage", "menu", "test-guides-pag... | budgetportal/tests/test_pages.py | from budgetportal.models import (
CategoryGuide,
Department,
FinancialYear,
Government,
Notice,
Sphere,
)
from django.test import Client, TestCase
from mock import MagicMock, patch
class BasicPagesTestCase(TestCase):
fixtures = ["video-language", "faq", "homepage", "menu", "test-guides-pag... | 0.609292 | 0.329446 |
from preprocessing.dataset import SVHNDataset, SVHNPlotter
import os
import pandas as pd
import numpy as np
import PIL.Image
from util.fn import split_path
def dataset_to_image_dir(config):
file_name = config["general"].get("dataset_all")
if not os.path.exists(file_name):
os.makedirs("dataset_split", ... | util/dataset.py | from preprocessing.dataset import SVHNDataset, SVHNPlotter
import os
import pandas as pd
import numpy as np
import PIL.Image
from util.fn import split_path
def dataset_to_image_dir(config):
file_name = config["general"].get("dataset_all")
if not os.path.exists(file_name):
os.makedirs("dataset_split", ... | 0.432063 | 0.218419 |
from flask import url_for
from bs4 import BeautifulSoup
from tests.conftest import mock_sessions
class WhenGettingUsers:
def it_shows_all_fields_for_new_user_not_checked(self, client, mocker):
session_dict = {
'user': {
'access_area': 'admin'
},
'user_... | tests/app/main/views/admin/test_users.py | from flask import url_for
from bs4 import BeautifulSoup
from tests.conftest import mock_sessions
class WhenGettingUsers:
def it_shows_all_fields_for_new_user_not_checked(self, client, mocker):
session_dict = {
'user': {
'access_area': 'admin'
},
'user_... | 0.477554 | 0.201028 |
import os
import random
import sys
import pygame
from pygame.locals import *
class Shape(object):
def __init__(self, color):
self.color = color
def draw(self, surface):
raise NotImplementedError('Not implemented')
@staticmethod
def get_rand_color(min_value=0, max_value=255):
... | python/pygame/basic/draw-shapes.py | import os
import random
import sys
import pygame
from pygame.locals import *
class Shape(object):
def __init__(self, color):
self.color = color
def draw(self, surface):
raise NotImplementedError('Not implemented')
@staticmethod
def get_rand_color(min_value=0, max_value=255):
... | 0.479504 | 0.197967 |
import os
import platform
import time
from random import randint
from threading import Thread, current_thread
from time import sleep
import click
from pynput.keyboard import Controller as KeyboardController
from pynput.keyboard import Key
from pynput.mouse import Controller as MouseController
mouse = MouseController(... | jiggler.py | import os
import platform
import time
from random import randint
from threading import Thread, current_thread
from time import sleep
import click
from pynput.keyboard import Controller as KeyboardController
from pynput.keyboard import Key
from pynput.mouse import Controller as MouseController
mouse = MouseController(... | 0.417746 | 0.197039 |
import logging
from typing import List, Dict, Sequence, Iterable
LOGGER = logging.getLogger(__name__)
def get_glue_args(arguments: Sequence, options: List[str] = None) -> Dict:
"""
Parse Arguments supplied to the Job.
Parameters
----------
arguments
Sequence of options and values to be p... | glue/shared/glue_shared_lib/src/glue_shared/glue_interface.py | import logging
from typing import List, Dict, Sequence, Iterable
LOGGER = logging.getLogger(__name__)
def get_glue_args(arguments: Sequence, options: List[str] = None) -> Dict:
"""
Parse Arguments supplied to the Job.
Parameters
----------
arguments
Sequence of options and values to be p... | 0.837221 | 0.336904 |
import shutil
from PIL import Image
from ep.evalplatform.create_report import create_report, create_sensible_report
from ep.evalplatform.plotting import Plotter
from ep.evalplatform.utils import *
images_sufixes = [SEGPLOT_SUFFIX, TRACKPLOT_SUFFIX]
SUMMARY_GNUPLOT_FILE = "plot_summary.plt"
terminal_type = "png"
de... | ep/evalplatform/gather_results.py | import shutil
from PIL import Image
from ep.evalplatform.create_report import create_report, create_sensible_report
from ep.evalplatform.plotting import Plotter
from ep.evalplatform.utils import *
images_sufixes = [SEGPLOT_SUFFIX, TRACKPLOT_SUFFIX]
SUMMARY_GNUPLOT_FILE = "plot_summary.plt"
terminal_type = "png"
de... | 0.374333 | 0.342462 |
import torch
import torch.nn as nn
import torch.nn.functional as F
class ConvBnReLU(nn.Module):
"""Implements 2d Convolution + batch normalization + ReLU"""
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size: int = 3,
stride: int = 1,
pad: int... | models/module.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class ConvBnReLU(nn.Module):
"""Implements 2d Convolution + batch normalization + ReLU"""
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size: int = 3,
stride: int = 1,
pad: int... | 0.970099 | 0.736709 |
from avocado.formatters import registry as formatters
from varify.formatters import HTMLFormatter
class HGNCGene(HTMLFormatter):
href = 'http://www.genenames.org/data/hgnc_data.php?hgnc_id={}'
def to_html(self, values, **context):
if values['hgnc_id']:
href = self.href.format(values['hgnc... | varify/genes/formatters.py | from avocado.formatters import registry as formatters
from varify.formatters import HTMLFormatter
class HGNCGene(HTMLFormatter):
href = 'http://www.genenames.org/data/hgnc_data.php?hgnc_id={}'
def to_html(self, values, **context):
if values['hgnc_id']:
href = self.href.format(values['hgnc... | 0.420719 | 0.248426 |
import typing
from ask_sdk_model.services import ServiceClientFactory, ApiConfiguration
from ask_sdk_model import ResponseEnvelope
from .dispatch import RequestDispatcher
from .serialize import DefaultSerializer
from .handler_input import HandlerInput
from .exceptions import AskSdkException
from .attributes_manager i... | ask-sdk-core/ask_sdk_core/skill.py | import typing
from ask_sdk_model.services import ServiceClientFactory, ApiConfiguration
from ask_sdk_model import ResponseEnvelope
from .dispatch import RequestDispatcher
from .serialize import DefaultSerializer
from .handler_input import HandlerInput
from .exceptions import AskSdkException
from .attributes_manager i... | 0.823115 | 0.059729 |
import os, sys
script_dir = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, script_dir + os.sep + "lib")
import json, boto3
import logging
log = logging.getLogger()
log.setLevel(logging.INFO)
session = boto3.Session()
asg_client = session.client('autoscaling')
NODE_DRAINER_HOOK_NAME = "aws-node-dra... | aws-drainer/lambda/asg-hook-sync/main.py | import os, sys
script_dir = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, script_dir + os.sep + "lib")
import json, boto3
import logging
log = logging.getLogger()
log.setLevel(logging.INFO)
session = boto3.Session()
asg_client = session.client('autoscaling')
NODE_DRAINER_HOOK_NAME = "aws-node-dra... | 0.194712 | 0.054149 |
import cv2 as cv
import numpy as np
import time
import argparse
def get_args(data_end_row):
# ターミナルから実行する際に、再生の仕方を設定できます
# --start <int> 再生を始める行を指定できます
# --end <int> 再生を終える行を指定できます
# --pause_time <bool> 1行ごと(1回分の16フレーム分シーケンス)にポーズする時間を入れるか(一瞬止めるか)
parser = argparse.ArgumentParser()
par... | history_log_show.py | import cv2 as cv
import numpy as np
import time
import argparse
def get_args(data_end_row):
# ターミナルから実行する際に、再生の仕方を設定できます
# --start <int> 再生を始める行を指定できます
# --end <int> 再生を終える行を指定できます
# --pause_time <bool> 1行ごと(1回分の16フレーム分シーケンス)にポーズする時間を入れるか(一瞬止めるか)
parser = argparse.ArgumentParser()
par... | 0.14442 | 0.301772 |
import unittest
from pathlib import Path
from unittest.mock import MagicMock, patch
from taskcat import Config
from taskcat.exceptions import TaskCatException
from taskcat.testing import CFNTest
def get_config():
project_root_path = Path(__file__).parent / "../data/hook_plugin"
input_file_path = project_root... | tests/testing_module/test_hooks.py | import unittest
from pathlib import Path
from unittest.mock import MagicMock, patch
from taskcat import Config
from taskcat.exceptions import TaskCatException
from taskcat.testing import CFNTest
def get_config():
project_root_path = Path(__file__).parent / "../data/hook_plugin"
input_file_path = project_root... | 0.567817 | 0.398406 |
import cli
import config
import dbexecutor
import usermanager
class SurgeryOf1CStorage:
"""Класс реализует основные функции по работе с внутренним форматом хранения файлов конфигурации 1С"""
def __init__(self):
self.PARAMS = None
def init_config(self, config_file):
self.PARAMS = config.in... | surgery_of_1c_storage/__main__.py | import cli
import config
import dbexecutor
import usermanager
class SurgeryOf1CStorage:
"""Класс реализует основные функции по работе с внутренним форматом хранения файлов конфигурации 1С"""
def __init__(self):
self.PARAMS = None
def init_config(self, config_file):
self.PARAMS = config.in... | 0.134151 | 0.244419 |
import json
import os
import sys
from copy import deepcopy
import reversion
from django.conf import settings
from django.contrib import admin
from django.contrib.admin.sites import AdminSite
from django.contrib.admin.widgets import (FilteredSelectMultiple,
RelatedFieldWidgetWr... | cms/apps/pages/tests/test_admin.py | import json
import os
import sys
from copy import deepcopy
import reversion
from django.conf import settings
from django.contrib import admin
from django.contrib.admin.sites import AdminSite
from django.contrib.admin.widgets import (FilteredSelectMultiple,
RelatedFieldWidgetWr... | 0.381565 | 0.171581 |
import numpy as np
import random
import os
import renderer.optix_renderer.build.lib.rnd as rnd
RND_CONTEXT = 0
# This class accesses the C++ functions for the Optix renderer
class OptixRenderer():
def __init__(self, size, device):
global RND_CONTEXT
self.size = size
self.device = device
... | code/renderer/optix_renderer/render.py | import numpy as np
import random
import os
import renderer.optix_renderer.build.lib.rnd as rnd
RND_CONTEXT = 0
# This class accesses the C++ functions for the Optix renderer
class OptixRenderer():
def __init__(self, size, device):
global RND_CONTEXT
self.size = size
self.device = device
... | 0.467818 | 0.37777 |
import torch
from torch.nn import Parameter
from torch_geometric.nn import HeteroConv, SAGEConv
from torch_geometric.nn.inits import glorot
class HeteroGCLSTM(torch.nn.Module):
r"""An implementation similar to the Integrated Graph Convolutional Long Short Term
Memory Cell for heterogeneous Graphs.
... | torch_geometric_temporal/nn/hetero/heterogclstm.py | import torch
from torch.nn import Parameter
from torch_geometric.nn import HeteroConv, SAGEConv
from torch_geometric.nn.inits import glorot
class HeteroGCLSTM(torch.nn.Module):
r"""An implementation similar to the Integrated Graph Convolutional Long Short Term
Memory Cell for heterogeneous Graphs.
... | 0.939032 | 0.599954 |
import logging
import sys
import pytest
import mlflow
import mlflow.utils.logging_utils as logging_utils
from mlflow.utils.logging_utils import eprint
logger = logging.getLogger(mlflow.__name__)
LOGGING_FNS_TO_TEST = [logger.info, logger.warning, logger.critical, eprint]
@pytest.fixture(autouse=True)
def reset_std... | tests/utils/test_logging_utils.py | import logging
import sys
import pytest
import mlflow
import mlflow.utils.logging_utils as logging_utils
from mlflow.utils.logging_utils import eprint
logger = logging.getLogger(mlflow.__name__)
LOGGING_FNS_TO_TEST = [logger.info, logger.warning, logger.critical, eprint]
@pytest.fixture(autouse=True)
def reset_std... | 0.372505 | 0.260025 |
__author__ = "<NAME>"
# -*- coding: utf-8 -*-
"""
Utilities for downloading projects from Tidepool API
Reference: https://developer.tidepool.org/tidepool-api/index/
"""
import os
import datetime as dt
import sys
import requests
import logging
from data_science_tidepool_api_python.util import DATESTAMP_FORMAT
logge... | data_science_tidepool_api_python/makedata/tidepool_api.py | __author__ = "<NAME>"
# -*- coding: utf-8 -*-
"""
Utilities for downloading projects from Tidepool API
Reference: https://developer.tidepool.org/tidepool-api/index/
"""
import os
import datetime as dt
import sys
import requests
import logging
from data_science_tidepool_api_python.util import DATESTAMP_FORMAT
logge... | 0.404507 | 0.13788 |
from typing import Mapping, Optional, TypeVar, List
from collections.abc import Iterable
import discord
from discord.ext import commands
from fuzzywuzzy import fuzz
from src.main import PCParadiseBot
# pylint: disable=invalid-name
T = TypeVar("T")
# pylint: disable=invalid-name
def flatten(nested_iterable: Iterabl... | src/cogs/help.py | from typing import Mapping, Optional, TypeVar, List
from collections.abc import Iterable
import discord
from discord.ext import commands
from fuzzywuzzy import fuzz
from src.main import PCParadiseBot
# pylint: disable=invalid-name
T = TypeVar("T")
# pylint: disable=invalid-name
def flatten(nested_iterable: Iterabl... | 0.873309 | 0.24868 |
"""Unit tests for artifact conversion to and from Python Keras."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import glob
import json
import os
import shutil
import tempfile
import unittest
import keras
import tensorflow as tf
from tensorflowjs.conve... | python/tensorflowjs/converters/converter_test.py | """Unit tests for artifact conversion to and from Python Keras."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import glob
import json
import os
import shutil
import tempfile
import unittest
import keras
import tensorflow as tf
from tensorflowjs.conve... | 0.731442 | 0.421254 |
import pandas as pd
import numpy as np
from sklearn import model_selection
from sklearn import linear_model
from sklearn.metrics import mean_absolute_error
data = pd.read_csv("Players.csv")
# # data = data[data["Chance of playing next round"] != 0]
# data = data[data["Chance of playing next round"].notna()]
Midfielde... | Player_Data/Midfielder_Model.py | import pandas as pd
import numpy as np
from sklearn import model_selection
from sklearn import linear_model
from sklearn.metrics import mean_absolute_error
data = pd.read_csv("Players.csv")
# # data = data[data["Chance of playing next round"] != 0]
# data = data[data["Chance of playing next round"].notna()]
Midfielde... | 0.360939 | 0.466056 |
from lib import info
from lib.command import Command
from lib.logger import log_call, log
from lib.config import save_whitelist, save_jackpot, Config, _format_dict
from lib.formatter import Formatter
from lib.live_counter import LiveCounter
def _log_response(command, message, pipeline):
# type: (Command, str, str... | lib/bot.py | from lib import info
from lib.command import Command
from lib.logger import log_call, log
from lib.config import save_whitelist, save_jackpot, Config, _format_dict
from lib.formatter import Formatter
from lib.live_counter import LiveCounter
def _log_response(command, message, pipeline):
# type: (Command, str, str... | 0.332094 | 0.064653 |
import argparse
def parser_args():
parser = argparse.ArgumentParser()
parser.add_argument('--nEpochs', type=int, default=1000, help='number of training epochs')
parser.add_argument('--dataset', type=int, default=0, help='0 - ilids, 1 - prid')
parser.add_argument('--sampleSeqLength', type=int, default... | options.py | import argparse
def parser_args():
parser = argparse.ArgumentParser()
parser.add_argument('--nEpochs', type=int, default=1000, help='number of training epochs')
parser.add_argument('--dataset', type=int, default=0, help='0 - ilids, 1 - prid')
parser.add_argument('--sampleSeqLength', type=int, default... | 0.632616 | 0.056262 |
# Copyright (c) 2012 <NAME>
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# dis... | components/nghttp/nghttp2/doc/mkapiref.py |
# Copyright (c) 2012 <NAME>
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# dis... | 0.492676 | 0.071656 |
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import time
class RandomWalkWithAbsorbingBarrier:
def __init__(self, length):
self.length = length
self.x_initial = 0
self.life_time = 0
def render(self, x_0):
self.x_initial = x_0
... | HW4/q3.py | import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import time
class RandomWalkWithAbsorbingBarrier:
def __init__(self, length):
self.length = length
self.x_initial = 0
self.life_time = 0
def render(self, x_0):
self.x_initial = x_0
... | 0.575707 | 0.411939 |
import unittest
import shutil
import tempfile
import time
import subprocess
import os
import functools
import threading
import mock
import patchsyspath
import logging
import pika
from inaugurator.server import server
from inaugurator.server import rabbitmqwrapper
from inaugurator.server import config
from inaugurator i... | inaugurator/tests/integration_test.py | import unittest
import shutil
import tempfile
import time
import subprocess
import os
import functools
import threading
import mock
import patchsyspath
import logging
import pika
from inaugurator.server import server
from inaugurator.server import rabbitmqwrapper
from inaugurator.server import config
from inaugurator i... | 0.296043 | 0.115411 |
# standard library
import os
import unittest
from unittest.mock import MagicMock
# py3tester coverage target
__test_target__ = 'delphi.epidata.acquisition.covidcast.file_archiver'
class UnitTests(unittest.TestCase):
"""Basic unit tests."""
def test_archive_file_without_compression(self):
"""Archive a file ... | tests/acquisition/covidcast/test_file_archiver.py |
# standard library
import os
import unittest
from unittest.mock import MagicMock
# py3tester coverage target
__test_target__ = 'delphi.epidata.acquisition.covidcast.file_archiver'
class UnitTests(unittest.TestCase):
"""Basic unit tests."""
def test_archive_file_without_compression(self):
"""Archive a file ... | 0.793066 | 0.443299 |
from collections import defaultdict
from xml.etree import ElementTree
from django.conf import settings
from corehq.apps.fixtures.models import FixtureDataItem, FixtureDataType
from corehq.apps.users.models import CommCareUser
from dimagi.utils.modules import to_function
def hq_fixtures(user, version, last_sync=None):... | corehq/apps/fixtures/fixturegenerators.py | from collections import defaultdict
from xml.etree import ElementTree
from django.conf import settings
from corehq.apps.fixtures.models import FixtureDataItem, FixtureDataType
from corehq.apps.users.models import CommCareUser
from dimagi.utils.modules import to_function
def hq_fixtures(user, version, last_sync=None):... | 0.406509 | 0.144059 |
import argparse
from multiprocessing import cpu_count
from os.path import *
import pandas as pd
import os
from pkg_resources import resource_filename
from snakemake import snakemake
from isicle.utils import inchi2key, smi2key, write_string
from isicle import __version__
from isicle import export
from isicle import prep... | isicle/isicle.py | import argparse
from multiprocessing import cpu_count
from os.path import *
import pandas as pd
import os
from pkg_resources import resource_filename
from snakemake import snakemake
from isicle.utils import inchi2key, smi2key, write_string
from isicle import __version__
from isicle import export
from isicle import prep... | 0.23014 | 0.109301 |
import torch
from sklearn.kernel_approximation import Nystroem
from ... import params as P
from ... import utils
from ..model import Model
# Base class as wrapper for classifiers from scikit learn
class SkClassif(Model):
# Layer names
CLF = 'clf'
CLASS_SCORES = CLF # Symbolic name of the layer providing the class ... | neurolab/model/skclassif/skclassif.py | import torch
from sklearn.kernel_approximation import Nystroem
from ... import params as P
from ... import utils
from ..model import Model
# Base class as wrapper for classifiers from scikit learn
class SkClassif(Model):
# Layer names
CLF = 'clf'
CLASS_SCORES = CLF # Symbolic name of the layer providing the class ... | 0.596081 | 0.3111 |
from odoo import api, fields, models
class StockRulesReport(models.TransientModel):
_name = 'stock.rules.report'
_description = 'Stock Rules report'
product_id = fields.Many2one('product.product', string='Product', required=True)
product_tmpl_id = fields.Many2one('product.template', string='Product ... | odoo-13.0/addons/stock/wizard/stock_rules_report.py |
from odoo import api, fields, models
class StockRulesReport(models.TransientModel):
_name = 'stock.rules.report'
_description = 'Stock Rules report'
product_id = fields.Many2one('product.product', string='Product', required=True)
product_tmpl_id = fields.Many2one('product.template', string='Product ... | 0.517815 | 0.099952 |
import time
import platform
import cpuinfo
import examples
from rsa import RSA
class Benchmark:
def __init__(self, n: int, e: int, d: int, m: int, c: int, text: str) -> None:
self.n = n
self.e = e
self.d = d
self.m = m
self.c = c
self.text = text
self.rsa... | bench_rsa.py |
import time
import platform
import cpuinfo
import examples
from rsa import RSA
class Benchmark:
def __init__(self, n: int, e: int, d: int, m: int, c: int, text: str) -> None:
self.n = n
self.e = e
self.d = d
self.m = m
self.c = c
self.text = text
self.rsa... | 0.553988 | 0.176069 |
import sys
import unittest
sys.path.append('D:/Git/DEVS-Python')
from projects.simparc.P import P
from src.CONTENT import CONTENT
class testPModelTest(unittest.TestCase):
def setUp(self):
self.p = P()
def test_modeltest_p_inject(self):
"""!
@fn test_modeltest_p_inject
... | test/testPModelTest.py | import sys
import unittest
sys.path.append('D:/Git/DEVS-Python')
from projects.simparc.P import P
from src.CONTENT import CONTENT
class testPModelTest(unittest.TestCase):
def setUp(self):
self.p = P()
def test_modeltest_p_inject(self):
"""!
@fn test_modeltest_p_inject
... | 0.347648 | 0.354405 |
import argparse
import os
import shutil
import tempfile
from stackstrap.cli import StackStrapCLI
from stackstrap.commands import CommandError
from stackstrap.commands.create import name_type
from stackstrap.project import Project
from stackstrap.repository import Repository
from . import StackStrapTestCase
repo_url ... | tests/test_project.py | import argparse
import os
import shutil
import tempfile
from stackstrap.cli import StackStrapCLI
from stackstrap.commands import CommandError
from stackstrap.commands.create import name_type
from stackstrap.project import Project
from stackstrap.repository import Repository
from . import StackStrapTestCase
repo_url ... | 0.232223 | 0.199386 |
import argparse
import subprocess
import warnings
import datetime
import json
from seml.misc import get_slurm_jobs, s_if
from seml import database_utils as db_utils
from seml.queue_experiments import queue_experiments
from seml.start_experiments import start_experiments
def report_status(config_file):
detect_kil... | seml/main.py | import argparse
import subprocess
import warnings
import datetime
import json
from seml.misc import get_slurm_jobs, s_if
from seml import database_utils as db_utils
from seml.queue_experiments import queue_experiments
from seml.start_experiments import start_experiments
def report_status(config_file):
detect_kil... | 0.320183 | 0.140218 |
import os
import numpy as np
import compress_pickle
from transformer.utils import get_tqdm
from transformer.utils import get_logger
logger = get_logger('transformer')
def create_training_dataset(english_tokens,
german_tokens,
max_samples=None,
... | transformer/preprocess/training_dataset.py | import os
import numpy as np
import compress_pickle
from transformer.utils import get_tqdm
from transformer.utils import get_logger
logger = get_logger('transformer')
def create_training_dataset(english_tokens,
german_tokens,
max_samples=None,
... | 0.554712 | 0.375993 |
import uuid
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("connector_airflow", "0020_remove_all_dags"),
]
operations = [
migrations.RemoveField(
model_name="dag",
name="cluster",... | hexa/plugins/connector_airflow/migrations/0021_add_dag_template_and_more.py |
import uuid
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("connector_airflow", "0020_remove_all_dags"),
]
operations = [
migrations.RemoveField(
model_name="dag",
name="cluster",... | 0.494385 | 0.151435 |
import os
import re
import argparse
from pull_files import filter_files
HERE = os.getcwd()
ABSOLUTE_HERE = os.path.dirname(HERE)
BAD_PHRASE = "lorem ipsum"
def parse_args():
"""Construct the command line interface for the script"""
DESCRIPTION = "Script to check for occurences of 'Lorem Ipsum' in Markdown fi... | tests/lorem-ipsums.py | import os
import re
import argparse
from pull_files import filter_files
HERE = os.getcwd()
ABSOLUTE_HERE = os.path.dirname(HERE)
BAD_PHRASE = "lorem ipsum"
def parse_args():
"""Construct the command line interface for the script"""
DESCRIPTION = "Script to check for occurences of 'Lorem Ipsum' in Markdown fi... | 0.561936 | 0.165627 |
import base64
import json
from json import JSONDecodeError
from typing import (
Any,
Dict,
Optional,
)
from Crypto.Cipher import AES
from Crypto.Hash import SHA1
from Crypto.Protocol.KDF import PBKDF2
from Crypto.Random import random
from constants import (
ALGORITHMS,
ENCRYPTION_DEFAULT_OPTIONS,
... | src/algorithm/iron.py | import base64
import json
from json import JSONDecodeError
from typing import (
Any,
Dict,
Optional,
)
from Crypto.Cipher import AES
from Crypto.Hash import SHA1
from Crypto.Protocol.KDF import PBKDF2
from Crypto.Random import random
from constants import (
ALGORITHMS,
ENCRYPTION_DEFAULT_OPTIONS,
... | 0.882687 | 0.263576 |
import tensorflow as tf
from data_processing.autoaugment import distort_image_with_autoaugment, distort_image_with_randaugment
import pathlib
CROP_PADDING = 32
AUTOTUNE = tf.data.experimental.AUTOTUNE
def preprocess_image(image_bytes, image_size, is_training=False
, augment_name=None,
... | swintransformer/data_processing/data.py | import tensorflow as tf
from data_processing.autoaugment import distort_image_with_autoaugment, distort_image_with_randaugment
import pathlib
CROP_PADDING = 32
AUTOTUNE = tf.data.experimental.AUTOTUNE
def preprocess_image(image_bytes, image_size, is_training=False
, augment_name=None,
... | 0.945645 | 0.649745 |
from abc import ABC, abstractmethod
from datetime import datetime, timedelta
from typing import List
from twitchio.ext.commands import Context
import CynanBotCommon.utils as utils
import twitch.twitchUtils as twitchUtils
from cutenessUtils import CutenessUtils
from CynanBotCommon.analogue.analogueStoreReposi... | commands.py | from abc import ABC, abstractmethod
from datetime import datetime, timedelta
from typing import List
from twitchio.ext.commands import Context
import CynanBotCommon.utils as utils
import twitch.twitchUtils as twitchUtils
from cutenessUtils import CutenessUtils
from CynanBotCommon.analogue.analogueStoreReposi... | 0.610221 | 0.048519 |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import copy
from ansible.module_utils.six import iteritems
from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.cfg.base import (
ConfigBase,
)
from ansible_collections.ansible.netcommon.plugins.module_... | venv/lib/python3.6/site-packages/ansible_collections/cisco/ios/plugins/module_utils/network/ios/config/static_routes/static_routes.py | from __future__ import absolute_import, division, print_function
__metaclass__ = type
import copy
from ansible.module_utils.six import iteritems
from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.cfg.base import (
ConfigBase,
)
from ansible_collections.ansible.netcommon.plugins.module_... | 0.711431 | 0.167049 |