id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
9871086 | from util import *
send_gdb('break string_store')
expect_gdb('Breakpoint 1')
# string_store 1-byte forwards
send_gdb('c')
expect_gdb('Breakpoint 1')
send_gdb('finish')
send_gdb('watch -l p[1000000]')
expect_gdb('watchpoint')
send_gdb('reverse-continue')
expect_gdb('Old value = 97')
expect_gdb('New value = 0')
send_gd... |
9871203 | import pandas as pd
if __name__=='__main__':
for i in range(90001,90011):
prophet_file_path='../data/prophet/prophet_feature_'+str(i)+'.csv'
prophet_data=pd.read_csv(prophet_file_path,index_col=0)
prophet_data.index=pd.to_datetime(prophet_data.index)
train_file_path = '../data/tra... |
9871220 | import argparse
import configparser
import datetime
import os
import subprocess
import sys
import lbann
import lbann.contrib.args
import lbann.contrib.launcher
import numpy as np
from data import make_data_reader
from model import make_model
root_dir = os.path.dirname(os.path.realpath(__file__))
# -----------------... |
9871229 | from yowsup.layers.interface import YowInterfaceLayer, ProtocolEntityCallback
class SendLayer(YowInterfaceLayer):
send(origin, target, body):
outgoingMessageProtocolEntity = TextMessageProtocolEntity( body, target)
self.toLower(outgoingMessageProtocolEntity)
# receiving data
@ProtocolEnti... |
9871256 | from yowsup.common import YowConstants
from yowsup.layers.protocol_iq.protocolentities import IqProtocolEntity
from yowsup.structs import ProtocolTreeNode
class GetKeysIqProtocolEntity(IqProtocolEntity):
def __init__(self, jids):
super(GetKeysIqProtocolEntity, self).__init__("encrypt", _type = "get", to = Y... |
9871298 | import psycopg2
import toml
import numpy as np
import matplotlib.pyplot as plt
from lib import node_time, node_classification, node_latency
# Note, sudo is required to run this script.
config = toml.load("./db.toml")['psql']
conn = psycopg2.connect(
host=config['host'],
port=config['port'],
database=config... |
9871464 | from unittest.mock import Mock
import copy
from datetime import datetime
from twisted.internet import defer
from tests.protocols.smpp.test_smpp_server import SMPPClientTestCases
from smpp.twisted.protocol import SMPPSessionStates
from smpp.pdu.constants import priority_flag_value_map
from smpp.pdu.pdu_types import Regi... |
9871486 | import sys
import numpy as np
from yggdrasil.interface.YggInterface import (
YggRpcClient, YggOutput)
def main(iterations):
r"""Function to execute client communication with server that computes
numbers in the Fibonacci sequence.
Args:
iterations (int): The number of Fibonacci numbers to log.... |
9871498 | from __future__ import print_function
import numpy as np
import gc
import ctypes
libmain = ctypes.cdll.LoadLibrary("./libmain.so")
class DLDevice(ctypes.Structure):
_fields_ = [("device_type", ctypes.c_int),
("device_id", ctypes.c_int)]
class DLDataType(ctypes.Structure):
_fields_ = [("type_code",... |
9871525 | from ..dandiset import Dandiset
def test_get_dandiset_record():
out = Dandiset.get_dandiset_record({"identifier": "000000"})
# Should have only header with "DO NOT EDIT"
assert out.startswith("# DO NOT EDIT")
assert "000000" in out
|
9871549 | import sys
import uio
import usocket
import udnspkt
s = usocket.socket(usocket.AF_INET, usocket.SOCK_DGRAM)
dns_addr = usocket.getaddrinfo("192.168.127.12", 5353)[0][-1]
def resolve(domain, is_ipv6):
buf = uio.BytesIO(48)
udnspkt.make_req(buf, domain, is_ipv6, unicast=True)
v = buf.getvalue()
print... |
9871555 | import os
from django.test import TestCase
from django.contrib.staticfiles import finders
from longclaw import settings
from longclaw.core.templatetags import longclawcore_tags
class TagTests(TestCase):
def _test_static_file(self, pth):
result = finders.find(pth)
print(result)
self.assert... |
9871558 | import torch
from tqdm import tqdm
from nets.pspnet_training import CE_Loss, Dice_loss, Focal_Loss
from utils.utils import get_lr
from utils.utils_metrics import f_score
def fit_one_epoch(model_train, model, loss_history, optimizer, epoch, epoch_step, epoch_step_val, gen, gen_val, Epoch, cuda, dice_loss, focal_l... |
9871573 | import unittest
import rdflib
import sbol2
class TestCollection(unittest.TestCase):
def __init__(self, *args):
super().__init__(*args)
self.homespace = 'http://example.org'
def make_identity(self, homespace, name, version, tipe='Collection'):
uri = '{}/{}/{}/{}'
return uri.... |
9871611 | import os
from datetime import datetime, timedelta
from typing import List, Set, Union
from bs4 import BeautifulSoup
from selenium import webdriver
from time import sleep
from selenium.webdriver.firefox.webdriver import WebDriver as Firefox
from selenium.webdriver.chrome.webdriver import WebDriver as Chrome
os.environ... |
9871644 | import sys
class SearchFriendsChecker(object):
@staticmethod
def Check(searchinput):
if searchinput is None:
print("usage: kahla searchfriends [--searchinput <username>]")
print("simplified usage: kahla searchfriends [-si <username>]")
sys.exit(1)
|
9871645 | import os
import os.path as osp
import random
import numpy as np
import torch
from skimage import io
# This code is strongly borrowed from
# Label
# Each satellite image is paired with a mask image for land cover annotation. The mask is a RGB image with 7 classes of labels, using color-coding (R, G, B) as follows.
#... |
9871674 | import os
from pathlib import Path
from sphinx_testing import with_app
@with_app(buildername="html", srcdir="doc_test/doc_role_need_max_title_length_unlimited")
def test_max_title_length_unlimited(app, status, warning):
os.environ["MAX_TITLE_LENGTH"] = "-1"
app.build()
html = Path(app.outdir, "index.htm... |
9871690 | import mock
from cliquet.scripts import cliquet as cliquet_script
from .support import unittest
class InitSchemaTest(unittest.TestCase):
def setUp(self):
self.registry = mock.MagicMock()
def run_command(self, command):
with mock.patch('cliquet.scripts.cliquet.bootstrap') as mocked:
... |
9871727 | from mas_tools.models.autoencoders import deep_conv2d_vae
from mas_tools.ml import save_model_arch
if __name__ == "__main__":
path = 'E:/Projects/market-analysis-system/mas_vae/'
enc, dec, ae, _ = deep_conv2d_vae((80, 80, 3), latent_dim=60, filters_count=(3, 15), dropout=0.3)
save_model_arch(enc, path+'a... |
9871741 | import argparse
import pytorch_lightning as pl
from cassle.args.dataset import augmentations_args, dataset_args
from cassle.args.utils import additional_setup_linear, additional_setup_pretrain
from cassle.args.continual import continual_args
from cassle.methods import METHODS
from cassle.utils.checkpointer import Chec... |
9871777 | import collections
import copy
import unittest
from betamax.configure import Configuration
from betamax.cassette import Cassette
from betamax.recorder import Betamax
class TestConfiguration(unittest.TestCase):
def setUp(self):
self.cassette_options = copy.deepcopy(
Cassette.default_cassette_o... |
9871789 | import os
import json
def execute_commands_file(file_name, redis_client):
cwd = os.getcwd()
file_name = os.path.join(cwd, "./tests/files", file_name)
for line in open(file_name, "r").readlines():
if line.strip().startswith("#"):
continue
args = json.loads(line)
redis_... |
9871798 | from colorsys import hls_to_rgb, rgb_to_hls, hsv_to_rgb
def RGBA(R: int, G: int, B: int, A=1):
'''
Returns RGB(A) Color as formatted rgba string
Parameters
----------
R, G, B : 0 > 255
A : 0 > 1
Returns
-------
String
e.g Color.RGBA(245, 123, 123, 0.2)
>>> 'rgba(... |
9871799 | import unittest
from dojo import main, opposite_directions
class DojoTest(unittest.TestCase):
def test_opposite_directions(self):
self.assertFalse(opposite_directions("NORTH","NORTH"))
def test_opposite_directions4(self):
cases = ["NORTH", "WEST", "EAST", "SOUTH"]
for i, case in enume... |
9871822 | import pytest
@pytest.fixture
def software_0():
return{
"name": "star",
"title": "STAR",
"description": "STAR (Spliced Transcript Alignment to a Reference)."
}
@pytest.fixture
def software_1(software_0):
item = software_0.copy()
item.update({
'schema_version': '1',
... |
9871905 | from django.urls import include, path, re_path
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
path('dynamicdns/', include('dynamicdns.urls')),
path('admin/', admin.site.urls),
]
|
9871929 | import uuid
from datetime import datetime
from typing import Optional
from pydantic import UUID4
from sqlmodel import Field, SQLModel
class DocumentInput(SQLModel):
id: UUID4 = Field(default_factory=uuid.uuid4, primary_key=True)
content: str
class Document(DocumentInput, table=True):
created_at: dateti... |
9871933 | from __future__ import print_function
from builtins import object
class Pen(object):
def __init__(self):
self._color = 0 # "private" variable
@property
def color(self):
print("I AM GETTING THIS")
return self
@color.setter
def color(self, color):
print("I AM SETTING ... |
9871950 | from collections import defaultdict
import itertools
import logging
import math
import os
import pickle
import random
import sys
from tqdm import tqdm
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as functional
import torch.optim as optim
from torch.utils.data import ConcatDataset, D... |
9871964 | import logging, logging.handlers
def setup(name=__name__):
"""
Setup a logger with a rotating file handler
"""
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
# Make sure log files are 5mb or smaller and only keep 5 of them
handler = logging.handlers.Rot... |
9871990 | import numpy as np
import PIL
import cv2
import matplotlib.pyplot as plt
def torch_to_cv(img):
if isinstance(img, np.ndarray):
return np.moveaxis(img, 0, -1)
img = np.array(img.detach().cpu())
if len(img.shape) >= 3:
assert img.shape[0] <= 3 # first dim is color channel
return np... |
9871994 | import timeit
import cv2
import numpy as np
import tensorflow as tf
TIMES = 1000
def main():
interpreter = tf.lite.Interpreter(model_path="../tflite/model.lite")
interpreter.allocate_tensors()
input_index = interpreter.get_input_details()[0]["index"]
output_index = interpreter.get_output_details()[... |
9871999 | import time
import numpy as np
from PIL import Image
from LBP import LBP
from mpi4py import MPI
class Multiprocessing_LBP_MPI(LBP):
def __init__(self, input, num_processes, output):
LBP.__init__(self, input, num_processes, output)
self.communicator = MPI.COMM_WORLD
self.process_id = self.co... |
9872003 | import _pickle as cPickle
import logging
from pathlib import Path
from typing import List, Dict, Optional, Union, Callable, Iterable, Collection, Any
from collections import ChainMap
from itertools import repeat
from multiprocessing import Pool
from joblib import Parallel, delayed
from .document import Document
from ... |
9872036 | import json
import e2e.Libs.Ristretto.Ristretto as Ristretto
from e2e.Libs.BLS import PrivateKey
from e2e.Classes.Transactions.Claim import Claim
from e2e.Classes.Transactions.Transactions import Transactions
from e2e.Classes.Consensus.VerificationPacket import VerificationPacket
from e2e.Classes.Merit.Merit import... |
9872050 | import functools
from pgshovel.utilities import load
class Component(object):
@classmethod
def configure(cls, configuration):
raise NotImplementedError
def configure(configuration):
return functools.partial(
load(configuration['path']).configure,
configuration.get('configuration... |
9872087 | class InvalidAliasException(Exception):
"""
Raised when an input alias does not meet validity requirements.
"""
pass
class ReservedAliasException(Exception):
"""
Currently, raised only when the input alias is "linkr," a reserved keyword used for
application-level routing.
"""
pass
... |
9872140 | import math
from collections import defaultdict
def path_modifier(path):
length = 0.0 if math.isnan(path.length) else path.length
return {"id": path.pk, "length": length}
def get_key_optimizer():
next_id = iter(range(1, 1000000)).__next__
mapping = defaultdict(next_id)
return lambda x: mapping[x... |
9872143 | import sys
import argparse
import opentuner
from opentuner import ConfigurationManipulator
from opentuner import EnumParameter
from opentuner import FloatParameter
from opentuner import IntegerParameter
from opentuner import MeasurementInterface
from opentuner import Result
import socket
import pickle
import os
from se... |
9872145 | from flask_restful import Resource
from endpoints.DeepLearning.validators import model_validate_post_validator, get_code_post_validator
from endpoints.DeepLearning.services import model_validate_service, get_code_service, run_code_service, \
get_available_model_list
class ValidateModel(Resource):
def post(se... |
9872163 | import numpy as np
import tensorflow as tf
from stable_baselines.common.policies import ActorCriticPolicy, FeedForwardPolicy
from stable_baselines.a2c.utils import conv, linear, conv_to_fc
class CustomPolicy(FeedForwardPolicy):
"""
FeedForwardPolicy but with a custom cnn feature extractor.
"""
def __i... |
9872171 | import sys
sys.path.insert(0, "../")
from python_omegle.chatevent import ChatEvent
def make_events_json(*events):
EVENT_ENUM_TO_STRINGS = {
ChatEvent.CHAT_READY: "connected",
ChatEvent.CHAT_WAITING: "waiting",
ChatEvent.CHAT_ENDED: "strangerDisconnected",
ChatEvent.GOT_MESSAGE: "g... |
9872182 | import numpy as np
import cv2
def get_fundamental_mat_normalized(p1,p2):
F_, inliers = cv2.findFundamentalMat(p1.astype('float32'), p2.astype('float32'), method=cv2.LMEDS)
return F_,inliers
def get_perspective_transform_normalized(p1,p2):
"""Get least squares estimate of homography.
"""
H = find_h... |
9872249 | import tkinter as tk
# --- classes ---
# you can put this in separated file (it will need `import tkinter`)
import tkinter
class MsgBox(tkinter.Toplevel):
def __init__(self, title="MsgBox", message="Hello World"):
tkinter.Toplevel.__init__(self)
self.title(title)
self.label = ... |
9872252 | import re
import requests
import pandas as pd
import numpy as np
def hot_github(keyword):
url = 'https://github.com/trending/{0}'.format(keyword)
main_url = 'https://github.com{0}'
html = requests.get(url).content.decode('utf-8')
reg_hot_url = re.compile('<h3 class="repo-list-name">\s*<a href="(.*?)">... |
9872267 | import os.path
from . import consts
from .utils import request, s3_zipped_download, s3_zipped_upload, safe_call
tillerino_api = "https://api.tillerino.org"
def download_beatmap(ctx):
"""Download a .osu file."""
if not ctx.beatmap:
return None
osu_path = "/tmp/%s.osu" % ctx.beatmap.file_md5
... |
9872270 | import csv
from datamart_materialize.utils import SimpleConverter
class UnsupportedConversion(ValueError):
"""This conversion cannot work."""
def skip_rows(source_filename, dest_fileobj, nb_rows):
with open(source_filename, 'r') as src_fp:
src = iter(csv.reader(src_fp))
dst = csv.writer(des... |
9872290 | from django import forms
from django.core.exceptions import ValidationError
from django.utils import timezone
from apps.dashboard.widgets import DatetimePickerInput, multiple_widget_generator
from ..models import CommitteeApplicationPeriod
class CommitteeApplicationPeriodForm(forms.ModelForm):
def clean(self):
... |
9872296 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
from torch.autograd import Variable
class ActorCritic(nn.Module):
def __init__(self):
super(ActorCritic, self).__init__()
self.fc = nn.Sequential(
nn.Linear(135*2... |
9872317 | from __future__ import absolute_import, division, print_function, unicode_literals
from echomesh.output.TestCase import TestCase
class BidirectionalTest(TestCase):
def test_start_forward(self):
self.assertOutput(
{'type': 'bidi', 'width': 4},
['a', 'b', 'c', 'd', 'e', 'f', 'g'],
... |
9872324 | from django.contrib import admin
from twobuntu.accounts.models import Profile
admin.site.register(Profile)
|
9872385 | from dbnd._core.task import Config
class DbndAirflowOperatorConfig(Config):
_conf__task_family = "airflow_operator"
|
9872400 | from .context import assert_equal
import pytest
import hashlib
from sympy import UnevaluatedExpr, Symbol, Mul, Pow, Max, Min, gcd, lcm, floor, ceiling
x = Symbol('x', real=True, positive=True)
y = Symbol('y', real=True, positive=True)
def test_variable_letter():
assert_equal("\\variable{x}", Symbol('x' + hashlib... |
9872436 | from data_importers.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = "HRW"
addresses_name = "2021-03-25T11:47:14.508721/Democracy_Club__06May2021 - 2.tsv"
stations_name = "2021-03-25T11:47:14.508721/Democracy_Club__06May2021 - 2.... |
9872458 | example_headers = ["Inorg_arb_examplepy_plugin_0_fun_count_drp_0.02",
"_N?_examplepy_plugin_0_False_molarity_drp_0.02",
"Ox_N?_examplepy_plugin_0_True_molarity_drp_0.02",
"Org_arb_examplepy_plugin_0_fun_count_drp_0.02",
"_N?_examplepy_plugin_0_True_molarity_drp_0.02",
"_arb_examplepy_plugin_0_dull_molarity_drp_0.02",
"... |
9872464 | from coronacheck_tools.clitools.iotool import parse_input, write_output, deep_get # noqa: F401
from coronacheck_tools.clitools.convert import convert # noqa: F401
from coronacheck_tools.clitools.definitions import FORMAT_MAPPINGS, VALID_FORMATS # noqa: F401
|
9872537 | import dispatch.plugins.kandbox_planner.util.kandbox_date_util as date_util
class RewardFunction:
"""
Has the following members
"""
rule_code = "generic_rule"
rule_name = "Generic Rule (and it should not be used)"
message_template = "Generic Rule"
reward_range = [-1, 1]
result = {
... |
9872553 | import getopt
import sys
from samsungtv import SamsungTvApp
def usage_option(name, description):
return "\t--%s \t %s" % (name, description)
def usage():
print ""
print "Usage: " + sys.argv[0] + " [OPTIONS]"
print usage_option("scan", "SSPD Scan")
print usage_option("rescan", "SSPD Scan (re... |
9872564 | import random
from http import HTTPStatus
import requests
from rotkehlchen.tests.utils.api import (
api_url_for,
assert_error_response,
assert_ok_async_response,
assert_proper_response_with_result,
wait_for_async_task,
)
EXPECTED_8CB0_TXS = [{
'tx_hash': '0x79d9e5a55a92429ef1f6d2fad1161273065... |
9872569 | import numpy as np
from numpy.testing import assert_array_equal
from pystruct.inference import get_installed, inference_dispatch
def test_chain():
# test LP, AD3, AD3-BB and JT on a chain.
# they should all be exact
rnd = np.random.RandomState(0)
algorithms = get_installed([('ad3', {'branch_and_bound... |
9872570 | import unittest
from asterisk.ami import LoginAction, LogoffAction, SimpleAction
class AMIActionTest(unittest.TestCase):
def compare_actions(self, a1, a2):
a1 = str(a1).split('\r\n')
a2 = str(a2).split('\r\n')
self.assertEqual(a1[0], a2[0])
self.assertSetEqual(set(a1[1:]), set(a2[... |
9872620 | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import pickle
import numpy as np
class PSNR(nn.Module):
"""The PSNR score.
Args:
size_average (bool): Whether to average the PSNR score all over the samples in the batch (default: True).
max_value (int): The maximum... |
9872622 | def studyball():
i01.disableRobotRandom(30)
##keepball():
sleep(3)
i01.setHandSpeed("left", 0.65, 0.65, 0.65, 0.65, 0.65, 1.0)
i01.setHandSpeed("right", 0.65, 0.65, 0.65, 0.65, 0.65, 1.0)
i01.setArmSpeed("right", 0.75, 0.85, 0.95, 0.85)
i01.setArmSpeed("left", 0.75, 0.85, 0.95, 0.85)
i01.setHeadSpeed(0.... |
9872640 | c.ServerApp.port = 8888 # noqa
c.ServerApp.token = "" # noqa
c.ServerApp.password = "" # noqa
c.ServerApp.disable_check_xsrf = True # noqa
c.ServerApp.open_browser = False # noqa
c.LabApp.open_browser = False # noqa
c.LabApp.expose_app_in_browser = True # noqa
|
9872641 | import unittest
from tests.lib.client import get_client
from tests.lib.card_products import CardProducts
from tests.lib.card_transition_response import verify_card_transition_response
from tests.lib.utilities import Utilities
class TestCardsTransitionsCreate(unittest.TestCase):
"""Tests for the cards.transitions... |
9872653 | import responses
from unittest.mock import patch
from app.tests.conftests import TestBase
from app.models.account import Account
from app.models.account import EmailAddress
from app.controllers.tenant import create_tenant_and_account
from app.controllers.account import create_account
class MembersTestCase(TestBase):... |
9872681 | import KratosMultiphysics
import KratosMultiphysics.ConstitutiveModelsApplication as KratosMaterials
import importlib
def Factory(custom_settings, Model):
if(type(custom_settings) != KratosMultiphysics.Parameters):
raise Exception("expected input shall be a Parameters object, encapsulating a json string")
... |
9872705 | import streamlit as st
import pytesseract
import numpy as np
try:
import easyocr
reader = easyocr.Reader(['en'])
except:
pass
def try_all_OCR(crop_image):
st.write(" **OEM**: Engine mode \
\n**PSM**: Page Segmentation Mode \
\n Click [here](https://nanonets.com/blog/ocr-with-t... |
9872719 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from distributed import reduce_tensor
from CookieTTS.utils.audio.stft import STFT
from CookieTTS.utils.audio.audio_processing import window_sumsquare, dynamic_range_compression, dynamic_range_decompression
class MultiRes... |
9872723 | import pytest
from ass_tag_parser import (
AssDrawCmdMove,
AssDrawPoint,
AssItem,
AssTag,
AssTagAlignment,
AssTagAlpha,
AssTagAnimation,
AssTagBaselineOffset,
AssTagBlurEdges,
AssTagBlurEdgesGauss,
AssTagBold,
AssTagBorder,
AssTagClipRectangle,
AssTagClipVector,
... |
9872728 | from scapy.all import *
import atexit
from threading import Thread
import time
class ARPSpoofer:
def __init__(self, victim_ip, gateway_ip):
self.victim_ip = victim_ip
self.gateway_ip = gateway_ip
self.enable_ip_forward()
self.original_victim_mac = AskARP(victim_ip)
self.o... |
9872744 | from PyQt5.QtGui import QImage, QPixmap, QPainter
from PyQt5 import QtCore
import qrcode
# Image class for QR code
class Image(qrcode.image.base.BaseImage):
# constructor
def __init__(self, border, width, box_size):
# assigning border
self.border = border
# assigning width
s... |
9872789 | import graphene
class DaySchedule(graphene.Enum):
WFH = "WFH"
INOFFICE = "INOFFICE"
OFF = "OFF"
NONE = ""
@property
def description(self):
if self == DaySchedule.WFH:
return "Work From Home"
if self == DaySchedule.INOFFICE:
return "In Office"
if... |
9872816 | from tensorflow import keras
from tensorflow.keras import Input, Sequential, Model
from tensorflow.keras.layers import Dense, Activation, Conv1D, LeakyReLU, Flatten,\
Add, BatchNormalization, MaxPooling1D
from tensorflow.keras.initializers import glorot_uniform
from tensorflow.keras.... |
9872849 | import sys
from types import CodeType, FunctionType
from unittest import TestCase
def freeVar(val):
def nested():
return val
return nested.__closure__[0]
def find_nested_func(parent, child_name, **kwargs):
"""Returns a function nested inside another function.
:param parent: The parent funct... |
9872918 | from time import time
from gc import collect
from termcolor import colored
from ipaddress import ip_address
from collections import OrderedDict
from utilities.MiscHelpers import generateURLs
from utilities.ScanHelpers import massConnectScan
from utilities.DatabaseHelpers import Resolution, OpenPort, URL
def init(db, ... |
9872987 | from __future__ import absolute_import
from tests.integration.flask_app.app import sleep_task
from time import sleep
import pytest
from celery_once import AlreadyQueued
import pytest
@pytest.mark.framework
def test_flask():
sleep_task.delay(1)
sleep(0.5)
with pytest.raises(AlreadyQueued):
sleep_t... |
9872997 | from django.db import models
from picklefield import PickledObjectField
from shops.models import Shop
from sell.models import Sell, Cart
class PayPalShopSettings(models.Model):
shop = models.ForeignKey(Shop)
payer_id = models.CharField(max_length=92)
email = models.EmailField()
first_name = models.Ch... |
9873031 | from django.conf import settings as django_settings
from nautobot.core.settings_funcs import sso_auth_enabled
from nautobot.extras.registry import registry
def get_saml_idp():
"""
Context function to provide a query string for the first IDP configured for SAML.
If the configured SAML IDP is `google`, th... |
9873032 | import platform
import sys
import distro
def get_distro():
"""
In some distros, e.g. SUSE 15, platform.linux_distribution is present,
but returns an empty value
so we also try distro.linux_distribution in those cases
"""
osinfo = []
if hasattr(platform, 'linux_distribution'):
osin... |
9873034 | import sys
import kindred
from kindred.datageneration import generateData,generateTestData
def _bionlpst_bb3():
trainCorpus = kindred.bionlpst.load('2016-BB3-event-train')
devCorpus = kindred.bionlpst.load('2016-BB3-event-dev')
predictionCorpus = devCorpus.clone()
predictionCorpus.removeRelations()
classifier... |
9873042 | from .tasks import execute_pipeline, finalize
from .runner import run_pipelines, ExecutionResult, ProgressReport
|
9873066 | import os
import shutil
import subprocess
import sys
from contextlib import contextmanager
from os.path import isfile
from hatch.clean import remove_compiled_scripts
from hatch.config import get_proper_python, get_venv_dir
from hatch.exceptions import InvalidVirtualEnv
from hatch.utils import (
NEED_SUBPROCESS_SHE... |
9873071 | from threading import Thread, Timer, Event
from package_control import events
from queue import Queue
import webbrowser
import time as timeModule
import os
import json
import sublime_plugin
import sublime
from datetime import *
from .SoftwareHttp import *
from .SoftwareUtil import *
from .SoftwareRepo import *
from .So... |
9873096 | import json
from fastapi import APIRouter, Depends, HTTPException
from starlette.responses import Response
from ...algorithm import DbDtAlgorithm
from ...residual import (
calculate,
Reading,
)
from .DataApiQuery import DataApiQuery
from .data import format_timeseries, get_data_factory, get_data_query, get_ti... |
9873099 | from typing import Any, List
import enum
from absl import flags
from injector import Binder, Injector, Module
FLAGS = flags.FLAGS
class Environment(enum.Enum):
DEVELOPMENT = 'DEVELOPMENT'
PRODUCTION = 'PRODUCTION'
flags.DEFINE_enum_class('environment', Environment.PRODUCTION, Environment,
... |
9873149 | from .BooleanSchemaOption import BooleanSchemaOption
from .SchemaOptionDefs import SchemaOptionDefs
class RaggedBottomSchemaOption(BooleanSchemaOption):
def __init__(self):
super(RaggedBottomSchemaOption, self).__init__()
self.add(True, SchemaOptionDefs(setup=["cmd-raggedbottom.def"]))
s... |
9873161 | import sys, os
from flask import Flask, render_template
from flask_flatpages import FlatPages
from flask_frozen import Freezer
import config
# Some configuration, ensures
# 1. Pages are loaded on request.
# 2. File name extension for pages is Markdown.
app = Flask(__name__)
app.config.from_object(__name__)
app.config... |
9873163 | from app import db
from app.models.base_model import BaseEntity
from app.models.user import User
class Nominee(db.Model, BaseEntity):
__tablename__ = 'dvhj_nominee'
prints = ('id', 'name', 'valid')
name = db.Column(db.String(256))
valid = db.Column(db.Boolean)
def __init__(self, name=None):
... |
9873188 | import pytest
from datadog_checks.calico import CalicoCheck
from datadog_checks.dev.utils import get_metadata_metrics
from . import common
from .utils import get_fixture_path
@pytest.mark.unit
def test_check(aggregator, dd_run_check, mock_http_response):
mock_http_response(file_path=get_fixture_path('calico.tx... |
9873215 | import re
import os
import pkg_resources
def load_commands():
commands = []
for entry_point in pkg_resources.iter_entry_points(group='dokku_client.commands'):
command_class = entry_point.load()
command = command_class(name=entry_point.name)
commands.append(command)
commands = sorted... |
9873219 | import json
import logging
import requests
from core.analytics import OneShotAnalytics
from core.config.config import yeti_config
from core.errors import GenericYetiError, ObservableValidationError
from core.observables import AutonomousSystem, Hostname, Ip, Text, Url
class UrlScanIoApi(object):
"""
https:/... |
9873223 | import numpy as np
from tqdm.auto import tqdm
from ..base import ModificationAttack
class DICE(ModificationAttack):
"""
DICE (delete internally, connect externally)
"""
def __init__(self,
n_edge_mod,
ratio_delete=0.6,
allow_isolate=True,
... |
9873238 | import ctf
import os
import argparse
import time
import solve_args as sargs
import numpy as np
def run_bench(num_iter, s, k):
wrld = ctf.comm()
M = ctf.random.random((s,s))
X = ctf.random.random((k,s))
[U,S,VT] = ctf.svd(M)
S = np.arange(0,s)+1
M = ctf.dot(U*S,U.T())
te = ctf.timer_epoch("B... |
9873265 | import pandas as pd
import numpy as np
import os
# Copy CSV File here
def auto(filename):
data = pd.read_csv(filename)
# PriceDate Column - Does not contain Saturday and Sunday stock entries
data = data.fillna(method = "ffill")
# Copy CSV file here
data.to_csv(path_or_buf = filename, index = False) |
9873277 | from simulation.speedLimits import *
from simulation.trafficGenerators import *
maxFps= 40
size = width, heigth = 1280, 720
# in miliseconds
updateFrame = 500
seed = None
lanes = 3
length = 168*2
maxSpeed = 5
maxLength = 1000
speedLimits = [
SpeedLimit(range=((70, 0), (130, lanes-1)), limit=3, ticks=0),
... |
9873280 | from .anonymous_user import AnonymousUser
from .user import User
from .role import Role
from .user_role import UserRole
|
9873316 | from testers.cpiscine.CommonTester import CommonTester
from utils.ExecutionContext import TestRunInfo
class C05Tester(CommonTester):
name = "c05"
def __init__(self, info: TestRunInfo):
super().__init__(info)
def ex00(self):
self.exercise_files = ["ft_iterative_factorial.c"]
self.test_files = ["main.c"]
... |
9873359 | import requests
# Vuln Base Info
def info():
return {
"author": "cckuailong",
"name": '''Netsweeper 4.0.8 - Directory Traversal''',
"description": '''A directory traversal vulnerability in webadmin/reporter/view_server_log.php in Netsweeper before 3.1.10, 4.0.x before 4.0.9, and 4.1.x befo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.