id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
11400268 | import chardet
import copy
import io
import json
import ldap_peoples.ldif as ldif
import logging
from django.apps import apps
from django.conf import settings
from django.db import connections
from django.utils import timezone
from collections import OrderedDict
from ldap import modlist
from . ldap_utils import (form... |
11400282 | import pytest
@pytest.fixture
def klass():
from agile_analytics import CSVWriter
return CSVWriter
@pytest.fixture
def report(date):
from collections import namedtuple
Report = namedtuple("Report", ["summary", "table"])
table = [
["Week", "Completed"],
[date(2016, 5, 15), 4],
... |
11400335 | from tool.runners.python import SubmissionPy
import numpy as np
class DegemerSubmission(SubmissionPy):
def run(self, s):
# :param s: input in string format
# :return: solution flag
# Your code goes here
s = s.splitlines()
# 0 nothing, 1 horizontal, 2 vertical, 3 /, 4 \, 5 ... |
11400371 | import os, subprocess, time
def convert_state(x, y, width):
x += 1
y += 1
return (y-1)*width+x
def convert_action(action):
if(action == 0):
return "up"
elif(action == 1):
return "down"
elif(action == 2):
return "left"
elif(action == 3):
return "right"
el... |
11400399 | from terra_sdk.client.lcd import LCDClient
terra = LCDClient(chain_id="pisco-1", url="https://pisco-lcd.terra.dev")
res = terra.gov.deposits(proposal_id=5333)
print(res)
res = terra.gov.votes(proposal_id=5333)
print(res)
|
11400428 | import os
import textwrap
import sys
import pytest
from conda_devenv.gen_scripts import render_activate_script, render_deactivate_script
@pytest.fixture
def single_values():
return {"VALUE": "value"}
@pytest.fixture
def multiple_values():
paths = ["path_a", "path_b"]
return {"PATH": paths, "LD_LIBRAR... |
11400466 | from office365.runtime.paths.static_service_operation import StaticServiceOperationPath
from office365.runtime.queries.client_query import ClientQuery
from office365.runtime.paths.service_operation import ServiceOperationPath
class ServiceOperationQuery(ClientQuery):
def __init__(self, binding_type,
... |
11400480 | import argparse
import json
import pathlib
import contextlib
def make_remote(path: pathlib.Path):
with contextlib.suppress(FileNotFoundError):
(path / 'credentials.txt').unlink()
result = []
for meta_path in path.glob('course/*/meta.json'):
meta = json.loads(meta_path.read_bytes())
... |
11400488 | import sys
import collections
from lxml import etree
import pyquery
import sqlite3
def tags(s):
"""Split '<foo><bar><baz>' into ['foo', 'bar', 'baz']."""
return ' '.join(s[1:-1].split('><'))
XmlFields = [
('Id', int),
('PostTypeId', int),
('AcceptedAnswerId', int),
('CreationDate', str),
... |
11400489 | from sklearn.metrics import precision_recall_fscore_support
def f1_weighted(y_true, y_pred):
'''
This method is used to supress UndefinedMetricWarning
in f1_score of scikit-learn.
"filterwarnings" doesn't work in CV with multiprocess.
'''
_, _, f, _ = precision_recall_fscore_support(y_true, y_... |
11400521 | from typing import Dict
from ._crud_base import CrudBase
class Insert(CrudBase):
def insert(self, *items: Dict):
if len(items) == 0:
raise UserWarning('inserts cannot be empty')
columns = list(items[0].keys())
if len(columns) == 0:
raise UserWarning('insert cannot... |
11400557 | expected_output = {
"interfaces": {
"Control0/0": {
"ipv4": {"127.0.1.1": {"ip": "127.0.1.1"}},
"check": "YES",
"method": "CONFIG",
"link_status": "up",
"line_protocol": "up",
},
"GigabitEthernet0/0": {
"ipv4": {"192.168... |
11400561 | import math
from io import StringIO
from typing import List
from urllib.parse import unquote
import uuid
from daft import Node, PGM
from flask import Flask, request, Response, send_from_directory
app = Flask(__name__)
@app.route('/static/<path:path>')
def static_file(path):
return send_from_directory('static',... |
11400606 | from datetime import date, datetime
from decimal import Decimal
from types import MappingProxyType
from foil.compose import create_quantiles
from psycopg2.extras import NumericRange
TYPE_MAP = MappingProxyType({
'bool': bool,
'boolean': bool,
'smallint': int,
'integer': int,
'bigint': int,
'r... |
11400610 | from inferelator.preprocessing.priors import ManagePriors
from inferelator.preprocessing.simulate_data import make_data_noisy
|
11400647 | import pymysql
# 连接数据库
conn = pymysql.connect(host='127.0.0.1',port = 3306,user = 'root',
passwd = '<PASSWORD>',db = 'news_5_23')
c = conn.cursor()
# 查询多条数据fetchAll
c.execute("select content from event_news_ref into outfile '/var/lib/mysql-files/event_news_ref.txt'; ")
r = c.fetchone()
print(r)... |
11400662 | import cherrypy
import json
from bson import json_util
from girder import events
from girder.api import access, rest
from girder.api.v1.folder import Folder as FolderResource
from girder.constants import AccessType, TokenScope, SortDir
from girder.exceptions import ValidationException, RestException
from girder.models.... |
11400685 | import Orange
data = Orange.data.Table("lenses")
print("Attributes:", ", ".join(x.name for x in data.domain.attributes))
print("Class:", data.domain.class_var.name)
print("Data instances", len(data))
target = "soft"
print("Data instances with %s prescriptions:" % target)
atts = data.domain.attributes
for d in data:
... |
11400744 | from app.models.apply import ExtensionApply11Model, ExtensionApply12Model
from tests.v2.views import TCBase
class ExtensionApplyCancelTCBase(TCBase):
def __init__(self, hour, *args, **kwargs):
super(ExtensionApplyCancelTCBase, self).__init__(*args, **kwargs)
self.method = self.client.delete
... |
11400746 | from keras.utils import np_utils
from keras.datasets import mnist
import numpy as np
def load_mnist(digits = None, conv = False):
# Get MNIST test data
#X_train, Y_train, X_test, Y_test = data_mnist()
(X_train, y_train), (X_test, y_test) = mnist.load_data()
X_train = X_train.reshape(60000, 784)
X_t... |
11400757 | import copy
from cereal import car
from selfdrive.car.subaru.values import CAR
VisualAlert = car.CarControl.HUDControl.VisualAlert
def subaru_checksum(packer, values, addr):
dat = packer.make_can_msg(addr, 0, values)[2]
return (sum(dat[1:]) + (addr >> 8) + addr) & 0xff
def create_steering_control(packer, car_fin... |
11400777 | import os
import sys
DIR = os.path.abspath(os.path.dirname(__file__))
sys.path.append(os.path.join(DIR, "third_party", "pybind11"))
from glob import glob
from setuptools import setup
import pybind11
from pybind11.setup_helpers import Pybind11Extension, build_ext # noqa: E402
del sys.path[-1]
pkg_name = 'pybind11_pac... |
11400788 | import FWCore.ParameterSet.Config as cms
from CommonTools.ParticleFlow.pfParticleSelection_cff import *
from RecoEgamma.EgammaElectronProducers.electronEDIsolationDeposits_cff import *
from RecoEgamma.EgammaElectronProducers.electronEDIsolationValues_cff import *
edBasedElectronIsoTask = cms.Task(
pfParticleSel... |
11400816 | import requests
import random
from time import time
user_agent = [
'Mozilla/5.0 (X11; Linux i686; rv:64.0) Gecko/20100101 Firefox/64.0',
'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9a1) Gecko/20060814 Firefox/51.0',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Firefox... |
11400876 | from pyramid.events import subscriber, NewResponse
from dbas.database import DBDiscussionSession
from dbas.database.discussion_model import User
from dbas.events import ParticipatedInDiscussion, UserArgumentAgreement, UserStatementAttitude
from dbas.handler.voting import add_click_for_argument, add_click_for_statement... |
11400894 | import yaml
from pathlib import Path
import rdflib
from ontquery.terms import OntCuries
from pyontutils.utils import log
from pyontutils.config import auth
from pyontutils.closed_namespaces import * # EVIL but simplifies downstream imports
def interlex_namespace(user):
return 'http://uri.interlex.org/' + user
... |
11400921 | import torch
import wandb
from tqdm import tqdm
from trainers import register_trainer
from .base_trainer import BaseTrainer
@register_trainer("flag")
class FlagTrainer(BaseTrainer):
@staticmethod
def add_args(parser):
# fmt: off
parser.add_argument('--step-size', type=float, default=8e-3)
... |
11400949 | import os
import cv2 as cv
import numpy as np
import torch
from torchvision import transforms
from tqdm import tqdm
from config import device
from data_gen import data_transforms
from utils import ensure_folder
IMG_FOLDER = 'data/alphamatting/input_lowres'
TRIMAP_FOLDERS = ['data/alphamatting/trimap_lowres/Trimap1',... |
11400970 | import numpy as np
import scipy.ndimage
import skimage.transform
import cv2
import torch
import matplotlib
matplotlib.use('Agg')
from matplotlib import pylab as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D
from mvn.utils.img import image_batch_to_numpy, to_numpy, denormalize_image, resize_image
from mvn.util... |
11400973 | import numpy as np
from PyAstronomy import pyaC as PC
from PyAstronomy.pyaC import pyaErrors as PE
def airmassPP(zangle):
"""
Calculate airmass for plane parallel atmosphere.
Parameters
----------
zangle : float or array
The zenith angle in degrees.
Returns
-------
Airmass : ... |
11400998 | from CitySearch import *
from LocalitySearch import *
from flask import Flask, jsonify, request, send_file
controller = Flask(__name__)
@controller.route('/nlp-engine/fuzzy/city', methods=['POST'])
def getCities():
request_data = request.get_json()
inp = request_data['input_city']
lang = request_data['in... |
11401011 | from logger import logger
logging = logger.getChild('sessions.stopwatch.buffers.countdowns')
import misc
import time
from core.sessions.buffers.buffer_defaults import buffer_defaults
from main import Time
class Countdowns(Time):
def __init__(self, *args, **kwargs):
super(Countdowns, self).__init__(*a... |
11401037 | import traceback
class RQMonitorException(Exception):
"""
used to catch any possible exception that might occur in used libraries
or while performing some action and display gracefully inside rqmonitor
"""
def __init__(
self, message="RQ Monitor Global Exception", status_code=500, payload... |
11401087 | import logging
from bubuku.aws import AWSResources
from bubuku.aws.cluster_config import ClusterConfig
_LOG = logging.getLogger('bubuku.aws.node')
KAFKA_LOGS_EBS = 'kafka-logs-ebs'
class Ec2Node(object):
def __init__(self, aws: AWSResources, cluster_config: ClusterConfig, ip: str):
self.aws = aws
... |
11401119 | import torch # must be imported before anything from torchshapelets
from .discrepancies import CppDiscrepancy, L2Discrepancy, LogsignatureDiscrepancy
from .regularisation import similarity_regularisation
from .shapelet_transform import GeneralisedShapeletTransform
__version__ = '0.1.0'
del torch
|
11401128 | from __future__ import annotations
import asyncio
import typing
from ctc import rpc
from ctc import evm
from ctc import spec
async def async_get_tokens(
g_uni_pool: spec.Address,
) -> tuple[spec.Address, spec.Address]:
return await asyncio.gather(
rpc.async_eth_call(to_address=g_uni_pool, function_n... |
11401178 | class CFMLPlugin:
def get_completion_docs(self, cfml_view):
return None
def get_completions(self, cfml_view):
return None
def get_goto_cfml_file(self, cfml_view):
return None
def get_inline_documentation(self, cfml_view, doc_type):
return None
def get_method_previ... |
11401188 | import re
def clumpFractions(s):
"""
Replaces the whitespace between the integer and fractional part of a quantity
with a dollar sign, so it's interpreted as a single token. The rest of the
string is left alone.
clumpFractions("aaa 1 2/3 bbb")
# => "aaa 1$2/3 bbb"
"""
return ... |
11401200 | from datetime import datetime
from decimal import Decimal
from unittest.mock import Mock, patch
import pytz
from prices import Money
from ....giftcard.events import gift_cards_used_in_order_event
from ....giftcard.models import GiftCard
from ..utils import (
chunk_products,
generate_invoice_number,
genera... |
11401227 | import kerberos
import os
import requests
import sys
import pytest
username = os.environ.get('KERBEROS_USERNAME', 'administrator')
password = os.environ.get('KERBEROS_PASSWORD', '<PASSWORD>')
realm = os.environ.get('KERBEROS_REALM', 'example.com')
hostname = os.environ.get('KERBEROS_HOSTNAME', 'hostname.example.com')
... |
11401249 | import os
import h5py
import numpy as np
from sleap.info.write_tracking_h5 import (
get_tracks_as_np_strings,
get_occupancy_and_points_matrices,
remove_empty_tracks_from_matrices,
write_occupancy_file,
)
def test_output_matrices(centered_pair_predictions):
names = get_tracks_as_np_strings(cente... |
11401261 | import os
import cv2
import numpy as np
VALUE_RANGE_0_1 = '0,1'
VALUE_RANGE_1 = '-1,1'
VALUE_RANGE_0_255 = '0,255'
def read(filepath, color_flags=cv2.IMREAD_COLOR):
"""Opens an image file from disk.
Parameters
----------
filepath: str
The path to the image file to open.
color_flags: int,... |
11401262 | from django.views.generic import TemplateView
from django.shortcuts import render
class index(TemplateView):
template_name = 'index/home.html' |
11401269 | import asyncio
import pickle
import pytest
from pytest_toolbox.comparison import CloseToNow
from arq import Worker, func
from arq.connections import ArqRedis, RedisSettings, create_pool
from arq.constants import default_queue_name, in_progress_key_prefix, job_key_prefix, result_key_prefix
from arq.jobs import Deseria... |
11401328 | import unittest
import attr
from itemadapter import ItemAdapter
from itemloaders.processors import Compose, Identity, MapCompose, TakeFirst
from scrapy.http import HtmlResponse, Response
from scrapy.item import Item, Field
from scrapy.loader import ItemLoader
from scrapy.selector import Selector
try:
from datac... |
11401333 | from metadrive.envs.metadrive_env import MetaDriveEnv
if __name__ == "__main__":
config = {
"environment_num": 10,
"traffic_density": .0,
# "use_render":True,
"map": "SSSSS",
# "manual_control":True,
"controller": "joystick",
"random_agent_model": False,
... |
11401334 | import asyncio
import websockets
import json
import requests
import dateutil.parser as dp
import hmac
import base64
import zlib
import datetime
def bugerror(errInf,ctype=''):
_http = requests.session()
gUrl = 'https://link.yjyzj.cn/api'
pdata = {'viewid': 'home', 'part': 'collect',
'ctype': c... |
11401350 | import os
import platform
import shutil
import subprocess
import sys
def get_platform_compilers():
if platform.system() == 'Windows':
return [ 'vs2015', 'vs2017', 'vs2019', 'vs2019-clang' ]
elif platform.system() == 'Linux':
compilers = []
if shutil.which('g++-5'):
compilers.append('gcc5')
if shutil.which... |
11401365 | import numpy as np, sys, os, random, pdb, json, uuid, time, argparse
from pprint import pprint
import logging, logging.config
from collections import defaultdict as ddict
from ordered_set import OrderedSet
# PyTorch related imports
import torch
from torch.nn import functional as F
from torch.nn.init import xavier_norm... |
11401375 | from pytest import fixture
from can import Message
from uds.transmission_attributes import TransmissionDirection, AddressingType
from uds.can import CanAddressingFormat
from uds.segmentation import CanSegmenter
# Common
@fixture(params=[(0x00, 0xFF, 0xAA, 0x55), [0x00], (0xFF, ), [0x12, 0xFF, 0xE0, 0x1D, 0xC2, 0x... |
11401380 | from flask import Flask
from sqlbag.flask import FS, proxies, session_setup
s = proxies.s
def get_app():
a = Flask(__name__)
a.s = FS("postgresql:///example", echo=True)
session_setup(a)
return a
app = get_app()
@app.route("/")
def hello():
# returns 'Hello World!' as a response
return s... |
11401399 | import pandas as pd
from sklearn.datasets import load_iris
from gama.genetic_programming.compilers.scikitlearn import (
evaluate_individual,
compile_individual,
evaluate_pipeline,
)
from gama.utilities.metrics import Metric, scoring_to_metric
def test_evaluate_individual(SS_BNB):
import datetime
... |
11401404 | import abc
import time
import asyncio
import logging
import warnings
from typing import Optional, Set, Callable, Awaitable
from ..utils import DeadlineWrapper
from ..metadata import Deadline
log = logging.getLogger(__name__)
DEFAULT_CHECK_TTL = 30
DEFAULT_CHECK_TIMEOUT = 10
_Status = Optional[bool]
class CheckB... |
11401414 | import torch
import numpy as np
from allennlp.nn import util
from relex.modules.offset_embedders import OffsetEmbedder
def position_encoding_init(n_position: int, embedding_dim: int):
position_enc = np.array([[pos / np.power(10000, 2 * (j // 2) / embedding_dim)
for j in range(embeddi... |
11401416 | from chainerui.models.log import Log
def get_test_json():
return [
{
"loss": 100,
"epoch": 1,
},
{
"loss": 90,
"epoch": 2,
}
]
def test_log_serialize_numbers():
json_data = get_test_json()
logs = [Log(data) for data in j... |
11401429 | import json
import os
from . import utils
from .browsers.chrome_native import is_native
def dump_kwargs(**kwargs):
utils.alert(
title='%s Kwargs' % kwargs.get('entity_type', 'Unknown'),
message='<pre>%s</pre>' % json.dumps(kwargs, sort_keys=True, indent=4)
)
def dump_environ(**kwargs):
... |
11401474 | from django.conf.urls import url, include
from . import views
test_patterns = [
url(r'^$', views.index, name='django_daraja_index'),
url(r'^oauth/success', views.oauth_success, name='test_oauth_success'),
url(r'^stk-push/success', views.stk_push_success, name='test_stk_push_success'),
url(r'^business-payment/succe... |
11401498 | from typing import List
from dirty_models import ArrayField, BooleanField, ModelField, StringField, StringIdField
from . import BaseCollectionManager, BaseModelManager
from ..models import BaseModel, DateTimeField
from ..results import Result
class Participant(BaseModel):
is_admin = BooleanField(default=False)
... |
11401505 | def find_subsets(nums):
subsets = []
# TODO: Write your code here
subsets.append([])
for i in range(len(nums)):
storeLen = len(subsets)
for j in range(0,storeLen):
currSet = list(subsets[j])
currSet.append(nums[i])
subsets.append(currSet)
return subsets
|
11401510 | from utils import CSVScraper, CanadianPerson as Person
from pupa.scrape import Organization, Post
from collections import defaultdict
import re
class CanadaMunicipalitiesPersonScraper(CSVScraper):
csv_url = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vRrGXQy8qk16OhuTjlccoGB4jL5e8X1CEqRbg896ufLdh67DQk9nuGm-o... |
11401544 | from __future__ import absolute_import
import os.path
import math
from PIL import Image, ImageStat
import numpy as np
from shapely.geometry import Polygon, asPolygon
from shapely.ops import unary_union
from tesserocr import (
RIL, PSM, PT, OEM,
Orientation,
WritingDirection,
TextlineOrder,
tesserac... |
11401578 | import torch
import numpy as np
from sklearn.cluster import SpectralClustering
from cogdl.utils import spmm
from .. import BaseModel, register_model
@register_model("agc")
class AGC(BaseModel):
r"""The AGC model from the `"Attributed Graph Clustering via Adaptive Graph Convolution"
<https://arxiv.org/abs/190... |
11401585 | import ast
import inspect
import os
# From https://gist.github.com/Xion/617c1496ff45f3673a5692c3b0e3f75a
def get_short_lambda_body_text(lambda_func):
"""Return the source of a (short) lambda function.
If it's impossible to obtain, returns None.
"""
try:
source_lines, _ = inspect.getsourcelines... |
11401615 | from __future__ import absolute_import, unicode_literals
import os
import sys
from opencc.clib import opencc_clib
__all__ = ['OpenCC', 'CONFIGS', '__version__']
__version__ = opencc_clib.__version__
_thisdir = os.path.dirname(os.path.abspath(__file__))
_opencc_share_dir = os.path.join(_thisdir, 'clib', 'share', 'op... |
11401642 | import os
import os.path as osp
import tempfile
import numpy as np
import pytest
import torch
from mmhuman3d.models import HybrIK_trainer, HybrIKHead
from mmhuman3d.models.builder import build_body_model
from mmhuman3d.models.utils.inverse_kinematics import (
batch_get_3children_orient_svd,
batch_get_pelvis_o... |
11401653 | import pytz
import logging
import requests
from dateutil.parser import parse
from datetime import datetime, timedelta
from django.utils import timezone
from website.app import init_app
from scripts.analytics.base import SummaryAnalytics
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
LO... |
11401659 | from django.apps import AppConfig
class ExampleAppConfig(AppConfig):
name = "example"
verbose_name = "Sample Cats app "
|
11401719 | def openhand():
i01.setHandSpeed("right", 1.0, 1.0, 1.0, 1.0, 1.0, 1.0)
i01.rightHand.attach()
i01.moveHand("right",0,0,0,0,0)
i01.mouth.speak("Hands open, come closer, come closer")
sleep(0.5)
i01.rightHand.detach() |
11401725 | import filetype
filetype_matchers = [i for i in dir(filetype) if i.endswith('_matchers')]
def get_filetype_data_group(filetype_obj):
for fm in filetype_matchers:
if filetype_obj in getattr(filetype, fm):
return fm.split('_')[0]
return ''
def run(filepath):
filetype_obj = filetype.gu... |
11401738 | import os
from tests.integration.conftest import get_twindb_config_dir, docker_execute, assert_and_pause
from twindb_backup import LOG
def test_restore(
master1, storage_server, config_content_ssh, docker_client, rsa_private_key
):
twindb_config_dir = get_twindb_config_dir(docker_client, master1["Id"])
... |
11401769 | from sublime_plugin import WindowCommand
from ..platformio.clean import Clean
class DeviotCleanSketchCommand(WindowCommand):
def run(self):
Clean()
|
11401773 | from ..compiler_interface import CompilerInterface
from ..config import CompilationConfig, CompilationResult
from .compile_util import readonly_handler
from .compile_const import WORK_DIR
from .compile_cpp import compile_cpp
from .compile_git import compile_git
import os
import shutil
class Compiler(CompilerInterface... |
11401796 | import numpy as np
import logging
import sys
sys.path.append('..')
from fuzzycmeans import FCM
from fuzzycmeans.visualization import draw_model_2d
def example():
X = np.array([[1, 1], [1, 2], [2, 2], [9, 10], [10, 10], [10, 9], [9, 9], [20,20]])
fcm = FCM(n_clusters=3)
fcm.set_logger(tostdout=True, lev... |
11401832 | import argparse
import numpy as np
from mindaffectBCI import utopiaclient
from time import time, sleep
LOGINTERVAL_S = 3
t0=None
nextLogTime=None
def printLog(nSamp, nBlock):
''' textual logging of the data arrivals etc.'''
global t0, nextLogTime
t = time()
if t0 is None:
t0 = t
if nextLog... |
11401836 | def x(a=1):
return a
for j in range(3):
for i in range(j):
print(i)
i = i ** 2
i += 2
class A():
pass
a = x(a=2)
a = b = c = 1
a = list(range(5))
A.a = c
a[b] = b
e = b, c = c, 1
a, (b, c) = b, e
a += (lambda b: b)(a)
b = a
a = 2
c = {
"a": a,
"b": b
}
d = [a, b, c]
d[1]... |
11401915 | from .consumer import Consumer
from .exceptions import KafkianException
from .producer import Producer
__all__ = ["Consumer", "Producer", "KafkianException"]
|
11401965 | from PyAstronomy.pyaC import pyaErrors as PE
import numpy as np
def magToFluxDensity_bessel98(band, mag, mode="nu"):
"""
Convert magnitude into flux density according to Bessel et al. 1998
The conversion implemented here is based on the data given in Table A2 of
Bessel et al. 1998, A&A 333, 231-25... |
11402037 | from __future__ import absolute_import
import time
import logging
import numpy as np
from scipy.signal import lfilter
from relaax.server.parameter_server import parameter_server_base
from relaax.server.common import session
from . import trpo_config
from . import trpo_model
from .lib import network
logger = logging... |
11402076 | from datetime import date, timedelta
import numpy as np
##############
def dates_till_target(days=365, target=date.today()):
factors = np.arange(days-1,-1,step=-1).reshape(days,1)
return target - factors * timedelta(days=1)
def all_dates(first_date, last_date):
days_including_last = (last_date ... |
11402116 | N = int(input())
data = list(input().split())
result = ""
for i in data :
result += i[-1]
if result[-1] == '0' :
print("Yes")
else :
print("No")
|
11402128 | def maximum_value(maximum_weight, items):
totals = [[0 for _ in range(len(items) + 1)]
for _ in range(maximum_weight + 1)]
for weight in range(1, maximum_weight + 1):
for index, item in enumerate(items, 1):
if item['weight'] <= weight:
value = item['value'] + \... |
11402138 | import asyncio
import ipaddress
import collections
import logging
import math
import numpy
import scipy.constants
import time
from sanic import response
from hexi.plugin.MCAPlugin import MCAPlugin
from hexi.service import event
from plugins.mca_classical_washout import dfilter
_logger = logging.getLogger(__name__)
V... |
11402169 | import requests
import re
import time
def decodeQR(extension):
r = requests.get('https://zxing.org/w/decode?u=http%3A%2F%2Ftunnel.web.easyctf.com%2Fimages%2F'+extension+'.png')
regex = re.compile("Raw text</td><td><pre>([a-zA-z0-9\{_\}]+)", re.IGNORECASE)
return regex.findall(r.text)
#There are several br... |
11402196 | from __future__ import division
from __future__ import print_function
from builtins import range
import numpy as np
import numpy.random as npr
from matplotlib import pyplot as plt
plt.ion()
from pybasicbayes import models, distributions
###############
# load data #
###############
data = np.loadtxt('data.txt')
... |
11402201 | a = 3
result = 0
while a < 1000:
if(a % 3 == 0 or a % 5 == 0):
result += a
elif(a % 15 == 0):
result -= a
a += 1
print(result)
|
11402213 | from migen.fhdl.structure import *
from migen.fhdl.module import *
from migen.fhdl.bitcontainer import bits_for
from migen.fhdl.tools import *
from migen.fhdl.verilog import _printexpr as verilog_printexpr
from migen.fhdl.specials import *
def memory_emit_verilog(memory, ns, add_data_file):
r = ""
def gn(e):
... |
11402286 | def hello_function():
'''This is where the function documentation goes'''
print('Hello from function')
def function_with_return():
'''This function returns a number'''
return 42
def function_args(arg1):
'''Prints the argument it recieves'''
print(arg1)
def function_default_args(arg1=42):
... |
11402434 | from django.urls import path
from .views import QuoteAPIView
from .views import QuoteCategoryAPIView
urlpatterns = [
path('', QuoteCategoryAPIView.as_view()),
path('quotes/', QuoteAPIView.as_view()),
] |
11402496 | import math
from dataclasses import dataclass
from typing import Callable, List, Optional
from hooqu.analyzers.analyzer import (AggDefinition, DoubledValuedState,
StandardScanShareableAnalyzer)
from hooqu.analyzers.preconditions import has_column, is_numeric
from hooqu.dataframe i... |
11402510 | from ..common import files
from ..common.info import UNKNOWN
from ..parser import (
find as p_find,
)
from ..symbols import (
info as s_info,
find as s_find,
)
from .info import Variable
# XXX need tests:
# * vars_from_source
def _remove_cached(cache, var):
if not cache:
... |
11402526 | from flask import Blueprint
single_resource = Blueprint('single_resource', __name__)
from . import views # noqa
|
11402538 | import os
import torch
import argparse
import numpy as np
import matplotlib
from data import get_data
from pca_linear_map import PCALinMapping
from matplotlib import pyplot as plt
import time
from imageio import imwrite
from utils import mosaic
import yaml
import pickle as pkl
def save_results(a_to_b, X_A_test, X_B_t... |
11402559 | from FreeTAKServer.model.FTSModel.fts_protocol_object import FTSProtocolObject
from FreeTAKServer.model.FTSModelVariables.SubmitterVariables import SubmitterVariables as vars
class Submitter(FTSProtocolObject):
def __init__(self):
self.INTAG = None
@staticmethod
def ExcheckUpdate(INTAG=vars.Exchec... |
11402582 | import gym
def get_env(task : str) -> gym.Env:
if task in ['HalfCheetah-v3', 'Hopper-v3', 'Walker2d-v3', 'ib', 'finance', 'citylearn']:
import neorl
env = neorl.make(task)
else:
env = gym.make(task)
return env |
11402610 | import unittest
import numpy as np
import pandas as pd
from matminer.featurizers.structure.rdf import (
RadialDistributionFunction,
PartialRadialDistributionFunction,
ElectronicRadialDistributionFunction,
get_rdf_bin_labels,
)
from matminer.featurizers.structure.tests.base import StructureFeaturesTest... |
11402618 | import numpy as np
from pandas import Categorical, Series
import pandas._testing as tm
class TestUnique:
def test_unique_data_ownership(self):
# it works! GH#1807
Series(Series(["a", "c", "b"]).unique()).sort_values()
def test_unique(self):
# GH#714 also, dtype=float
ser = Se... |
11402629 | import sys
import torch
import numpy as np
import torch.nn as nn
from functools import partial
sys.path.append('../../')
from utils import transfer_train,transfer_eval,networks,dataloader,util
args,name = util.train_parser()
pm = util.Path_Manager_NA('../../dataset/na_fewshot',args=args)
config = util.Config(args=ar... |
11402641 | import windse
from dolfin import *
### Alias Parameters ###
params = windse.windse_parameters
### Set General Parameters ###
params["general"]["name"] = "Circle_Domain_Test"
### Set Box Parameters ###
radius = 1200
params["domain"]["type"] = "circle"
params["domain"]["mesh_type"] = "mshr"
params["domain"]["radi... |
11402678 | from enum import Enum
from ..Typing import *
_Action = Callable[[T, TE, TR], None]
__all__ = ['Delegate']
class Delegate:
"""
`delegate` represents a series of actions sharing the same context.
>>> from Redy.Async.Delegate import Delegate
>>> action = lambda task, product, globals: print(task.__name... |
11402696 | from .processor import *
class C3(DataProcessor):
"""
@article{sun2020investigating,
title={Investigating prior knowledge for challenging chinese machine reading comprehension},
author={<NAME> and <NAME> and <NAME> and <NAME>},
journal={Transactions of the Association for Computational Lingui... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.